gload 0.5.1

A command line client for the Gemini protocol.
Documentation
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
//! This software is licensed as described in the file LICENSE, which
//! you should have received as part of this distribution.
//!
//! You may opt to use, copy, modify, merge, publish, distribute and/or sell
//! copies of the Software, and permit persons to whom the Software is
//! furnished to do so, under the terms of the LICENSE file.
//!
//! This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
//! KIND, either express or implied.
//!
//! SPDX-License-Identifier: BSD-3-Clause

use crate::{
	request::{Request, RequestConstructError},
	response::{Response, ResponseParseError, StatusCategory},
	tls::{self, Stream, TlsError},
};
use core::{cmp::Ordering, net::SocketAddr};
use rustls::pki_types::ServerName;
use std::net::ToSocketAddrs;
pub use tokio_util::sync::CancellationToken; // re-exported for callers
use url::Url;

macro_rules! debug {
	($($arg:tt)+) => {{
		#[cfg(feature = "logging")]
		::log::debug!(target: "gload::net", $($arg)+)
	}}
}

/// Defines behavior for the [`fetch`] function.
///
/// Because the addition of new future options is NOT considered a semver-major
/// breaking change, constructing this value directly may result in unexpected
/// compilation errors unless you use [`Default::default`] and the
/// "spread" syntax.
///
/// # Example
/// ```rust
/// # use gload::net::{FetchOptions, RedirectPolicy};
/// let options = FetchOptions {
///   redirect_policy: RedirectPolicy::follow(),
///   ..Default::default()
/// };
///
/// assert!(options.address_resolution_limit.is_none());
/// ```
#[derive(Debug, Clone)]
pub struct FetchOptions<H: ResponseHandler> {
	/// Which IP address families are allowed to be resolved from the request hostname.
	/// `None` indicates that both IPv4 and IPv6 addresses should be considered.
	pub address_resolution_limit: Option<IpResolutionLimit>,

	/// (TLS)  Do not throw an error if the server fails to send `close_notify`.
	///
	/// It is possible for an outside attacker to cause the TLS connection to break early, so it's
	/// important for clients to know how much message to expect from a server. Because the Gemini
	/// network protocol has no inherent way for clients to know how long a message will be before
	/// it is received, servers must send the TLS `close_notify` alert before closing the connection.
	///
	/// __WARNING__: this option loosens TLS security. By using this flag, you ask for exactly that.
	pub allow_truncation: bool,

	/// A token which can be used to signal a cancellation request to the network task.
	///
	/// Cancellation can be requested through the [`CancellationToken::cancel`] method.
	pub cancellation_token: CancellationToken,

	/// How redirects are to be handled.
	pub redirect_policy: RedirectPolicy,

	/// A value that implements [`ResponseHandler`] to handle requests to e.g. print results to stdout.
	pub response_handler: H,
}

impl Default for FetchOptions<DefaultHandler> {
	fn default() -> Self {
		Self {
			address_resolution_limit: None,
			allow_truncation: false,
			cancellation_token: CancellationToken::new(),
			redirect_policy: RedirectPolicy::no_follow(),
			response_handler: DefaultHandler,
		}
	}
}

/// Performs the given request synchronously, following redirects if the `callback` returns `true`.
///
/// **Note**: This is not to be used in an `async` context. This function creates a Tokio runtime
/// internally, which may cause problems if done inside of an existing Tokio runtime!
pub fn fetch_sync<H: ResponseHandler>(
	req: Request,
	options: FetchOptions<H>,
) -> Result<Response, SendError<H>> {
	let runtime = tokio::runtime::Builder::new_current_thread()
		.thread_name("gload-worker-thread")
		.enable_all()
		.build()
		.map_err(SendError::TokioRuntimeError)?;
	runtime.block_on(fetch(req, options))
}

/// Performs the given request, following redirects if the `callback` returns `true`.
///
/// You may cancel the request using a [`CancellationToken`].
///
/// # Example
/// ```no_run
/// use gload::{FetchOptions, Request, fetch, net::CancellationToken};
/// use url_static::url;
///
/// let token = CancellationToken::new();
///
/// let options = FetchOptions {
///   cancellation_token: token.clone(),
///   ..Default::default()
/// };
/// let req = Request::new(url!("gemini://git.average.name/AverageHelper/gload")).unwrap();
/// tokio::spawn(fetch(req, options));
///
/// // later...
/// token.cancel(); // the request will stop as soon as it is able
/// ```
pub async fn fetch<H: ResponseHandler>(
	req: Request,
	options: FetchOptions<H>,
) -> Result<Response, SendError<H>> {
	if options.cancellation_token.is_cancelled() {
		return Err(SendError::Cancelled);
	}

	// validity checks for req payload
	let resolution_limit = options.address_resolution_limit;
	let (authority, addrs, payload) = prepare_req(&req, resolution_limit)?;
	let mut res = send_req_to(
		&authority,
		&addrs,
		payload,
		options.allow_truncation,
		&options.cancellation_token,
	)
	.await?;

	options
		.response_handler
		.handle(&res)
		.map_err(SendError::Handler)?;
	debug!("* shutting down connection #0"); // TODO: would it be awful to try reusing the connection?

	let max_redirs = match options.redirect_policy.max_redirs() {
		None => return Ok(res),
		Some(max) => max,
	};

	for conn_idx in 1..=(max_redirs + 1) {
		// We don't bother caching redirects, so Permanent and Temporary are the same to us
		if res.status().category() != StatusCategory::Redirection {
			// not a redirect
			return Ok(res);
		} else if let Some(target) = res.meta() {
			if conn_idx > max_redirs {
				break;
			}
			// redirect to target
			let (authority, addrs, payload) = match Url::parse(target) {
				Err(_) => {
					// not a URL, must be a (relative or absolute) path
					handle_redir_to_path(&req, &authority, &addrs, target)?
				}
				Ok(absolute_uri) if absolute_uri.host() == Some(req.host()) => {
					// URL but same hostname, so either a different path or port
					let new_req = Request::new(absolute_uri)?;

					if new_req.port() == req.port() {
						// same port; we may re-use the previous IP // TODO: Also re-use connection?
						handle_redir_to_path(&req, &authority, &addrs, target)?
					} else {
						// different port; needs new IP resolution
						debug!(
							"* Redirects to port from {} to {}",
							req.port(),
							new_req.port()
						);
						debug!("* Issue another request to this URL: '{new_req}'",);
						prepare_req(&new_req, resolution_limit)?
					}
				}
				Ok(absolute_uri) => {
					// URL to a different host
					debug!("* Issue another request to this URL: '{absolute_uri}'");
					let new_req = Request::new(absolute_uri)?;
					prepare_req(&new_req, resolution_limit)?
				}
			};

			res = send_req_to(
				&authority,
				&addrs,
				payload,
				options.allow_truncation,
				&options.cancellation_token,
			)
			.await?;

			options
				.response_handler
				.handle(&res)
				.map_err(SendError::Handler)?;
			debug!("* shutting down connection #{conn_idx}");
		} else {
			// redirect has no target! send back to the caller for handling, similar to a bodyless sucess response
			return Ok(res);
		}
	}

	// We've exhausted our redirect loop
	Err(SendError::TooManyRedirects { max: max_redirs })
}

/// The maximum number of redirections that a Gemini client may follow.
pub const REDIR_LIMIT: u8 = 5; // Spec: "Client MUST limit the number of redirections they follow to 5 redirections."

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RedirectPolicy(u8);

impl RedirectPolicy {
	/// The client is to follow up to five (5) redirects.
	pub const fn follow() -> Self {
		Self(REDIR_LIMIT)
	}

	/// Redirections are not to be followed. The first response is returned as-is.
	pub const fn no_follow() -> Self {
		Self(u8::MAX) // well above allowed number of redirects
	}

	/// The client is to follow up to the given number of redirects.
	///
	/// # Panics
	/// Panics if `max` is greater than 5. This is to enforce the Gemini Protocol spec, which states
	/// that the client "MUST limit the number of redirections they follow to 5 redirections."
	// TODO: Should we just clamp instead?
	pub const fn follow_only(max: u8) -> Self {
		assert!(max <= REDIR_LIMIT, "cannot follow more than 5 redirections");
		Self(max)
	}

	/// Returns the number of allowed redirects, if a limit is given. `None` indicates that
	/// no redirects should be followed, and the response should be returned as-is. `Some(0)`
	/// indicates that an error should be returned if any redirects are encountered.
	const fn max_redirs(&self) -> Option<u8> {
		if self.0 <= REDIR_LIMIT {
			Some(self.0)
		} else {
			None // u8::MAX case
		}
	}
}

/// A trait for handling request responses.
pub trait ResponseHandler: core::fmt::Debug {
	type Error: core::error::Error;

	/// Called at the end of each request. Use this method to, for example, log the
	/// response body to standard output.
	///
	/// **Note**: This method should NOT be used to implement redirects. Instead, use the
	/// [`FetchOptions::redirect_policy`] to specify how redirects should be handled.
	fn handle(&self, res: &Response) -> Result<(), Self::Error>;
}

/// A response handler that does nothing.
#[derive(Debug)]
pub struct DefaultHandler;

impl ResponseHandler for DefaultHandler {
	type Error = core::convert::Infallible;

	fn handle(&self, _: &Response) -> Result<(), Self::Error> {
		Ok(())
	}
}

fn prepare_req<H: ResponseHandler>(
	req: &Request,
	resolution_limit: Option<IpResolutionLimit>,
) -> Result<(ServerName<'static>, Vec<SocketAddr>, Vec<u8>), SendError<H>> {
	let host = req.host();
	let port = req.port();
	let addrs = resolve(&host, port, resolution_limit)?;
	let authority = match ServerName::try_from(host.to_string()) {
		Err(_) => {
			return Err(SendError::CouldNotResolveHost(to_owned_host(&host)));
		}
		Ok(a) => a,
	};

	Ok((authority, addrs, req.as_bytes()))
}

/// Creates a new request based on an old request and a new target path.
fn handle_redir_to_path<H: ResponseHandler>(
	old_req: &Request,
	authority: &ServerName<'static>,
	addrs: &[SocketAddr],
	path: &str,
) -> Result<(ServerName<'static>, Vec<SocketAddr>, Vec<u8>), SendError<H>> {
	let req = old_req.with_new_path(path)?;
	debug!("* Issue another request to this URL: '{req}'");

	Ok((authority.clone(), addrs.to_owned(), req.as_bytes()))
}

/// Sends a request to the given host.
async fn send_req_to<H: ResponseHandler>(
	authority: &ServerName<'static>,
	addrs: &[SocketAddr],
	payload: Vec<u8>,
	allow_truncation: bool,
	token: &CancellationToken,
) -> Result<Response, SendError<H>> {
	// If all addrs fail, return the latest error.
	// If one succeeds, pass that stream and addr along.
	let (tcp_stream, addr) = {
		let mut last: Option<Result<(Stream, SocketAddr), TlsError>> = None;
		for addr in addrs {
			debug!("*   Trying {addr}...");
			let stream_res = tokio::select! {
				_ = token.cancelled() => { return Err(SendError::Cancelled) }
				r = tls::open_stream(addr, authority.clone()) => r
			};
			match stream_res {
				Err(err) => {
					last = Some(Err(err));
					continue;
				}
				Ok(s) => {
					last = Some(Ok((s, *addr)));
					break;
				}
			}
		}
		match last {
			None => unreachable!("addrs is nonempty"),
			Some(Err(err)) => return Err(err.into()),
			Some(Ok(s)) => s,
		}
	};

	let response_bytes = tokio::select! {
		_ = token.cancelled() => { return Err(SendError::Cancelled) }
		r = tls::send(&addr, authority, tcp_stream, payload, allow_truncation) => r
	}?;

	let res = Response::new(response_bytes)?;
	Ok(res)
}

/// Indicates something went wrong when trying to send a request or receive a response.
#[derive(Debug)]
#[non_exhaustive]
pub enum SendError<H: ResponseHandler> {
	/// The caller requested cancellation.
	Cancelled,

	/// No IP addresses could be resolved from the request host.
	CouldNotResolveHost(url::Host<String>),

	/// The response handler returned an error.
	Handler(H::Error),

	/// Could not create a request from a redirect target.
	RequestConstruct(RequestConstructError),

	/// Could not parse the server response.
	ResponseParse(ResponseParseError),

	/// Something went wrong while sending the request.
	Tls(TlsError),

	/// Could not spawn a worker thread.
	TokioRuntimeError(std::io::Error),

	/// If we continue, we'll exceeded a maximum number of redirects.
	TooManyRedirects { max: u8 },
}

impl<H: ResponseHandler> From<RequestConstructError> for SendError<H> {
	fn from(value: RequestConstructError) -> Self {
		Self::RequestConstruct(value)
	}
}

impl<H: ResponseHandler> From<ResponseParseError> for SendError<H> {
	fn from(value: ResponseParseError) -> Self {
		Self::ResponseParse(value)
	}
}

impl<H: ResponseHandler> From<TlsError> for SendError<H> {
	fn from(value: TlsError) -> Self {
		Self::Tls(value)
	}
}

impl<H: ResponseHandler> core::fmt::Display for SendError<H> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::Cancelled => write!(f, "request cancelled"),
			Self::CouldNotResolveHost(host) => {
				write!(f, "could not resolve IP address from host: {host}")
			}
			Self::Handler(err) => write!(f, "{err}"),
			Self::RequestConstruct(err) => write!(
				f,
				"could not create a request from a redirect target: {err}"
			),
			Self::ResponseParse(err) => write!(f, "could not parse the server's response: {err}"),
			Self::Tls(err) => write!(f, "something went wrong while sending the request: {err}"),
			Self::TokioRuntimeError(err) => write!(f, "could not sawn a worker thread: {err}"),
			Self::TooManyRedirects { max } => write!(
				f,
				"received a redirect response, but we've already reached the a maximum number of redirects ({max})"
			),
		}
	}
}

impl<H: ResponseHandler> core::error::Error for SendError<H> {}

/// Resolves the given host and port to a list of IP addresses. An `OK` value
/// is guaranteed to be nonempty.
fn resolve<H: ResponseHandler>(
	host: &url::Host<&str>,
	port: u16,
	resolution_limit: Option<IpResolutionLimit>,
) -> Result<Vec<SocketAddr>, SendError<H>> {
	let mut addrs = match host {
		url::Host::Domain(domain) => [domain, ":", &port.to_string()]
			.concat()
			.to_socket_addrs() // does DNS resolution
			.unwrap_or_else(|_| Vec::new().into_iter())
			.collect(),
		url::Host::Ipv4(ip) => vec![SocketAddr::new((*ip).into(), port)],
		url::Host::Ipv6(ip) => vec![SocketAddr::new((*ip).into(), port)],
	};

	if let Some(limit) = resolution_limit {
		// Strip non-matching addresses from results
		match limit {
			IpResolutionLimit::Ipv4 => addrs.retain(|ip| ip.is_ipv4()),
			IpResolutionLimit::Ipv6 => addrs.retain(|ip| ip.is_ipv6()),
		}
	}

	if addrs.is_empty() {
		return Err(SendError::CouldNotResolveHost(to_owned_host(host)));
	}

	// Order IPv6 first
	addrs.sort_by(|a, b| {
		if a.is_ipv6() && b.is_ipv4() {
			Ordering::Less
		} else if a.is_ipv4() && b.is_ipv6() {
			Ordering::Greater
		} else {
			Ordering::Equal
		}
	});

	debug!("* Host {host}:{port} was resolved.");

	// Get first addr of each type:
	let mut res = Vec::with_capacity(2);

	if let Some(ipv6) = addrs.iter().find(|ip| ip.is_ipv6()) {
		debug!("* IPv6: {}", ipv6.ip());
		res.push(*ipv6);
	} else {
		debug!("* IPv6: (none)");
	}

	if let Some(ipv4) = addrs.iter().find(|ip| ip.is_ipv4()) {
		debug!("* IPv4: {}", ipv4.ip());
		res.push(*ipv4);
	} else {
		debug!("* IPv4: (none)");
	}

	Ok(res)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IpResolutionLimit {
	/// Only resolve IPv4 addresses.
	Ipv4,

	/// Only resolve IPv6 addresses.
	Ipv6,
}

fn to_owned_host(host: &url::Host<&str>) -> url::Host<String> {
	match host {
		url::Host::Domain(domain) => url::Host::Domain(domain.to_string()),
		url::Host::Ipv4(ip) => url::Host::Ipv4(*ip),
		url::Host::Ipv6(ip) => url::Host::Ipv6(*ip),
	}
}

// MARK: - Tests

#[cfg(test)]
mod tests {
	use super::*;
	use crate::test_server::{
		new_runtime, start_friendly_server, start_redir_server, start_unfriendly_server_slow,
	};
	use core::time::Duration;
	use url_static::url;

	#[test]
	fn test_redir_by_uri_target() {
		let cases = [
			url!("gemini://localhost"),
			url!("gemini://localhost/"),
			url!("gemini://localhost/foo"),
			url!("gemini://localhost/foo/bar"),
			url!("gemini://localhost/foo/bar"),
		];

		let localhost_v6 = "[::1]:1965".to_socket_addrs().unwrap().next().unwrap();
		let localhost_v4 = "127.0.0.1:1965".to_socket_addrs().unwrap().next().unwrap();

		for uri in cases {
			let expected = Request::new(uri.clone()).unwrap();
			let req = Request::new(uri).unwrap();
			let (authority, addrs, payload) = prepare_req::<DefaultHandler>(&req, None).unwrap();
			assert_eq!(payload, expected.as_bytes());
			assert_eq!(authority.to_str(), "localhost");
			assert!(
				addrs.contains(&localhost_v6) || addrs.contains(&localhost_v4),
				"{addrs:?}"
			);
		}
	}

	#[test]
	fn test_resolves_all_address_families() {
		let localhost_v4 = "127.0.0.1:1965".to_socket_addrs().unwrap().next().unwrap();
		let localhost_v6 = "[::1]:1965".to_socket_addrs().unwrap().next().unwrap();
		let uri = url!("gemini://localhost:1965");
		let host = uri.host().unwrap();
		let port = uri.port().unwrap();

		let res = resolve::<DefaultHandler>(&host, port, None).unwrap();
		assert_eq!(res.len(), 2);
		assert!(res.contains(&localhost_v4));
		assert!(res.contains(&localhost_v6));
	}

	#[test]
	fn test_resolves_only_ipv4() {
		let localhost_v4 = "127.0.0.1:1965".to_socket_addrs().unwrap().next().unwrap();
		let uri = url!("gemini://localhost:1965");
		let host = uri.host().unwrap();
		let port = uri.port().unwrap();

		let res = resolve::<DefaultHandler>(&host, port, Some(IpResolutionLimit::Ipv4)).unwrap();
		assert_eq!(res.len(), 1);
		assert!(res.contains(&localhost_v4));
	}

	#[test]
	fn test_resolves_only_ipv6() {
		let localhost_v6 = "[::1]:1965".to_socket_addrs().unwrap().next().unwrap();
		let uri = url!("gemini://localhost:1965");
		let host = uri.host().unwrap();
		let port = uri.port().unwrap();

		let res = resolve::<DefaultHandler>(&host, port, Some(IpResolutionLimit::Ipv6)).unwrap();
		assert_eq!(res.len(), 1);
		assert!(res.contains(&localhost_v6));
	}

	#[test]
	fn test_redir_by_path_target() {
		// targets that cannot be parsed as URIs get treated as paths

		#[rustfmt::skip]
		let cases = [
			("gemini://localhost/", "..", "gemini://localhost/"),
			("gemini://localhost/", "/..", "gemini://localhost/"),
			("gemini://localhost/", "../..", "gemini://localhost/"),
			("gemini://localhost/", "/../..", "gemini://localhost/"),
			("gemini://localhost/", "../../", "gemini://localhost/"),
			("gemini://localhost/", "/", "gemini://localhost/"),
			("gemini://localhost", "/", "gemini://localhost/"),
			("gemini://localhost", "", "gemini://localhost/"), // shouldn't happen because Meta would be None, but may as well check
			("gemini://localhost", ".", "gemini://localhost/"),
			("gemini://localhost", "..", "gemini://localhost/"),
			("gemini://localhost", "../..", "gemini://localhost/"),
			("gemini://localhost/target", "", "gemini://localhost/target"),
			("gemini://localhost/target/", "", "gemini://localhost/target/"),
			("gemini://localhost/target", "/..", "gemini://localhost/"),
			("gemini://localhost/target/", "/..", "gemini://localhost/"),
			("gemini://localhost/target", "/../..", "gemini://localhost/"),
			("gemini://localhost/target/target", "/..", "gemini://localhost/"),
			("gemini://localhost/target/target", "/../", "gemini://localhost/"),
			("gemini://localhost/target/target", "..", "gemini://localhost/target"),
			("gemini://localhost/target/target", "../", "gemini://localhost/target/"),
			("gemini://localhost/target/target", "/../..", "gemini://localhost/"),
			("gemini://localhost/target/target/", "/../..", "gemini://localhost/"),
			("gemini://localhost/target/target/", "", "gemini://localhost/target/target/"),
			("gemini://localhost/target/target/", ".", "gemini://localhost/target/target"),
			("gemini://localhost", "/target", "gemini://localhost/target"),
			("gemini://localhost/", "/target", "gemini://localhost/target"),
			("gemini://localhost/", "/target/", "gemini://localhost/target/"),
			("gemini://localhost/target", "/target", "gemini://localhost/target"),
			("gemini://localhost/target", "/target/", "gemini://localhost/target/"),
			("gemini://localhost/target/", "/target", "gemini://localhost/target"),
			("gemini://localhost/target/", "/target/", "gemini://localhost/target/"),
			("gemini://localhost/target", "target", "gemini://localhost/target/target"),
			("gemini://localhost/target/", "target", "gemini://localhost/target/target"),
			("gemini://localhost/target/", "target/", "gemini://localhost/target/target/"),
			("gemini://localhost/target/", "target/foo", "gemini://localhost/target/target/foo"),
			("gemini://localhost/target", "..", "gemini://localhost/"),
			("gemini://localhost/target", "#foo", "gemini://localhost/target"),
			("gemini://localhost/target", "foo#foo", "gemini://localhost/target/foo"),
			("gemini://localhost/target", "foo/#foo", "gemini://localhost/target/foo/"),
			("gemini://localhost", "foo and bar", "gemini://localhost/foo%20and%20bar"),
			("gemini://localhost/", "foo and bar", "gemini://localhost/foo%20and%20bar"),
			("gemini://localhost/", "foo and bar/", "gemini://localhost/foo%20and%20bar/"),
			("gemini://localhost/", "foo and bar/baz", "gemini://localhost/foo%20and%20bar/baz"),
			("gemini://localhost/", "/gemini://", "gemini://localhost/gemini:/"), // colon is valid, but the extra slash is removed
			("gemini://localhost/", "/gemini://example.com", "gemini://localhost/gemini:/example.com"),
			("gemini://localhost/", "/可愛い", "gemini://localhost/%E5%8F%AF%E6%84%9B%E3%81%84"),
			("gemini://localhost/", "/可愛い/", "gemini://localhost/%E5%8F%AF%E6%84%9B%E3%81%84/"),
		];

		let authority = ServerName::try_from("localhost").unwrap();
		let addrs = "[::]:0".to_socket_addrs().unwrap().collect::<Vec<_>>();
		for (start, path, expected) in cases {
			let expected = Request::from_uri_string(expected).unwrap();
			let exp_payload = expected.as_bytes();
			let old_req = Request::from_uri_string(start).unwrap();
			let new_req =
				handle_redir_to_path::<DefaultHandler>(&old_req, &authority, &addrs, path).unwrap();
			assert_eq!(
				new_req.2,
				exp_payload,
				"{} != {}",
				String::from_utf8_lossy(&new_req.2).trim(),
				String::from_utf8_lossy(&exp_payload).trim()
			);
		}
	}

	#[test]
	fn test_fails_to_redir_when_limit_is_zero() {
		let server = start_redir_server("/nowhere"); // target returns Not Found
		let port = server.addr().port();

		let req = Request::from_uri_string(format!("gemini://localhost:{port}")).unwrap();
		let options = FetchOptions {
			redirect_policy: RedirectPolicy::follow_only(0),
			..Default::default()
		};
		let err = fetch_sync(req, options).err().unwrap();
		assert!(
			matches!(err, SendError::TooManyRedirects { max: 0 }),
			"{err:?}"
		);
		assert_eq!(server.request_count(), 1); // first request was a redir, and we're supposed to follow zero of those so we fail early
	}

	#[test]
	fn test_fails_to_redir_when_limit_is_one() {
		let server = start_redir_server("/");
		let port = server.addr().port();

		let req = Request::from_uri_string(format!("gemini://localhost:{port}")).unwrap();
		let options = FetchOptions {
			redirect_policy: RedirectPolicy::follow_only(1),
			..Default::default()
		};
		let err = fetch_sync(req, options).err().unwrap();
		assert!(
			matches!(err, SendError::TooManyRedirects { max: 1 }),
			"{err:?}"
		);
		assert_eq!(server.request_count(), 2); // two requests; second ended up being a redir too, so we fail early
	}

	#[test]
	fn test_succeeds_when_redir_limit_is_one_and_only_one_redir() {
		let server = start_redir_server("/hello"); // target returns success
		let port = server.addr().port();

		let req = Request::from_uri_string(format!("gemini://localhost:{port}")).unwrap();
		let options = FetchOptions {
			redirect_policy: RedirectPolicy::follow_only(1),
			..Default::default()
		};
		let res = fetch_sync(req, options).unwrap();
		assert!(res.is_success());
		assert_eq!(server.request_count(), 2); // two requests; second was the target, so we're fine
	}

	#[test]
	fn test_fails_to_redir_when_limit_is_two() {
		let server = start_redir_server("/");
		let port = server.addr().port();

		let req = Request::from_uri_string(format!("gemini://localhost:{port}")).unwrap();
		let options = FetchOptions {
			redirect_policy: RedirectPolicy::follow_only(2),
			..Default::default()
		};
		let err = fetch_sync(req, options).err().unwrap();
		assert!(
			matches!(err, SendError::TooManyRedirects { max: 2 }),
			"{err:?}"
		);
		assert_eq!(server.request_count(), 3); // three requests; third ended up being a redir too, so we fail early
	}

	#[test]
	fn test_fails_to_redir_when_limit_is_default() {
		let server = start_redir_server("/");
		let port = server.addr().port();

		let req = Request::from_uri_string(format!("gemini://localhost:{port}")).unwrap();
		let options = FetchOptions {
			redirect_policy: RedirectPolicy::follow(),
			..Default::default()
		};
		let err = fetch_sync(req, options).err().unwrap();
		assert!(
			matches!(err, SendError::TooManyRedirects { max: 5 }),
			"{err:?}"
		);
		assert_eq!(server.request_count(), 6); // six requests; sixth ended up being a redir too, so we fail early
	}

	#[test]
	fn test_sync_api() {
		// Choose a port that isn't in use
		let port = std::net::TcpListener::bind("[::]:0")
			.unwrap()
			.local_addr()
			.unwrap()
			.port();

		// This request should fail in a predictable way
		let req = Request::from_uri_string(format!("gemini://localhost:{port}")).unwrap();
		let err = fetch_sync(req, Default::default()).err().unwrap();
		assert!(
			matches!(err, SendError::Tls(TlsError::Open(ref err)) if err.kind() == std::io::ErrorKind::ConnectionRefused),
			"{err:?}"
		);
	}

	#[test]
	fn test_cancelling_before_flight() {
		let key = rcgen::generate_simple_self_signed(["localhost".into()]).unwrap();
		let server = start_friendly_server(key);
		let port = server.addr().port();

		// This request should fail in a predictable way
		let req = Request::from_uri_string(format!("gemini://localhost:{port}")).unwrap();
		let token = CancellationToken::new();
		token.cancel();
		let options = FetchOptions {
			cancellation_token: token,
			..Default::default()
		};
		let err = fetch_sync(req, options).err().unwrap();
		assert!(matches!(err, SendError::Cancelled), "{err:?}");
		assert_eq!(server.request_count(), 0); // request never took flight
	}

	#[test]
	fn test_cancelling_during_flight() {
		let server = start_unfriendly_server_slow();
		let port = server.addr().port();

		let req = Request::from_uri_string(format!("gemini://localhost:{port}")).unwrap();
		let token = CancellationToken::new();
		let options = FetchOptions {
			cancellation_token: token.clone(),
			..Default::default()
		};

		let runtime = new_runtime("test-client-runtime-worker");
		let err = runtime
			.block_on(async move {
				let handle = tokio::spawn(fetch(req, options));
				tokio::time::sleep(Duration::from_millis(100)).await;
				token.cancel();
				handle.await.unwrap()
			})
			.err()
			.unwrap();
		assert!(matches!(err, SendError::Cancelled), "{err:?}");
		assert_eq!(server.request_count(), 1); // request took flight, but we don't care because we were cancelled
	}
}