1use futures::channel::oneshot;
23use std::io::{self, Read, Write};
24use std::net::{Ipv4Addr, Ipv6Addr, TcpListener, TcpStream};
25use std::sync::mpsc;
26use std::time::{Duration, Instant};
27
28const ACCEPT_POLL: Duration = Duration::from_millis(100);
30const STREAM_TIMEOUT: Duration = Duration::from_secs(10);
32const EXCHANGE_WAIT: Duration = Duration::from_secs(120);
34const MAX_REQUEST_BYTES: usize = 16 * 1024;
35const ANY_PORT_ATTEMPTS: usize = 6;
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
41pub enum LoopbackHost {
42 Ipv4,
44 Localhost,
47}
48
49#[derive(Debug, thiserror::Error)]
51pub enum LoopbackError {
52 #[error(transparent)]
55 Bind(io::Error),
56 #[error(transparent)]
58 Io(io::Error),
59 #[error("timed out waiting for the sign-in in the browser")]
61 TimedOut,
62 #[error("{0}")]
64 Refused(String),
65 #[error("the sign-in listener stopped unexpectedly")]
67 Stopped,
68}
69
70#[derive(Clone, Debug)]
74pub struct Loopback {
75 provider: String,
76 app: String,
77 host: LoopbackHost,
78 ports: Vec<u16>,
79 path: String,
80}
81
82impl Loopback {
83 pub fn new(
88 provider: impl Into<String>,
89 host: LoopbackHost,
90 ports: impl IntoIterator<Item = u16>,
91 path: impl Into<String>,
92 ) -> Self {
93 Self {
94 provider: provider.into(),
95 app: "rig".into(),
96 host,
97 ports: ports.into_iter().collect(),
98 path: path.into(),
99 }
100 }
101
102 #[must_use]
104 pub fn with_app_name(mut self, app: impl Into<String>) -> Self {
105 self.app = app.into();
106 self
107 }
108
109 pub fn listen(&self, state: String, deadline: Instant) -> Result<Listener, LoopbackError> {
120 let (listeners, port) = self.bind()?;
121 for listener in &listeners {
122 listener.set_nonblocking(true).map_err(LoopbackError::Io)?;
123 }
124 let host = match self.host {
125 LoopbackHost::Ipv4 => "127.0.0.1",
126 LoopbackHost::Localhost => "localhost",
127 };
128 let redirect_uri = format!("http://{host}:{port}{}", self.path);
129 let (sender, callback) = oneshot::channel();
130 let serving = Serving {
131 pages: Pages {
132 provider: escape_html(&self.provider),
133 app: escape_html(&self.app),
134 },
135 path: self.path.clone(),
136 state,
137 deadline,
138 };
139 std::thread::Builder::new()
140 .name("sign-in-listener".into())
141 .spawn(move || serving.serve(&listeners, sender))
142 .map_err(LoopbackError::Io)?;
143 Ok(Listener {
144 redirect_uri,
145 callback,
146 })
147 }
148
149 fn bind(&self) -> Result<(Vec<TcpListener>, u16), LoopbackError> {
152 for &port in &self.ports {
153 let attempts = if port == 0 { ANY_PORT_ATTEMPTS } else { 1 };
154 for _ in 0..attempts {
155 if let Some(bound) = self.bind_port(port)? {
156 return Ok(bound);
157 }
158 }
159 }
160 let ports: Vec<String> = self.ports.iter().map(u16::to_string).collect();
161 Err(LoopbackError::Bind(io::Error::new(
162 io::ErrorKind::AddrInUse,
163 format!(
164 "the sign-in callback ports {} on the loopback address are in use",
165 ports.join(", ")
166 ),
167 )))
168 }
169
170 fn bind_port(&self, port: u16) -> Result<Option<(Vec<TcpListener>, u16)>, LoopbackError> {
172 let ipv4 = match TcpListener::bind((Ipv4Addr::LOCALHOST, port)) {
173 Ok(listener) => listener,
174 Err(error) if taken(&error) => return Ok(None),
175 Err(error) => return Err(LoopbackError::Bind(error)),
176 };
177 let port = ipv4.local_addr().map_err(LoopbackError::Bind)?.port();
178 if self.host == LoopbackHost::Ipv4 {
179 return Ok(Some((vec![ipv4], port)));
180 }
181 match TcpListener::bind((Ipv6Addr::LOCALHOST, port)) {
182 Ok(ipv6) => Ok(Some((vec![ipv4, ipv6], port))),
183 Err(error) if taken(&error) => Ok(None),
184 Err(_) => Ok(Some((vec![ipv4], port))),
186 }
187 }
188}
189
190fn taken(error: &io::Error) -> bool {
192 matches!(
193 error.kind(),
194 io::ErrorKind::AddrInUse | io::ErrorKind::PermissionDenied
195 )
196}
197
198pub struct Listener {
201 redirect_uri: String,
202 callback: oneshot::Receiver<Result<Received, LoopbackError>>,
203}
204
205impl Listener {
206 pub fn redirect_uri(&self) -> &str {
209 &self.redirect_uri
210 }
211
212 pub async fn code(self) -> Result<Received, LoopbackError> {
221 self.callback.await.map_err(|_| LoopbackError::Stopped)?
222 }
223}
224
225pub struct Received {
229 code: String,
230 outcome: mpsc::Sender<Result<(), String>>,
231}
232
233impl Received {
234 pub fn code(&self) -> &str {
236 &self.code
237 }
238
239 pub fn succeeded(self) {
241 self.outcome.send(Ok(())).ok();
242 }
243
244 pub fn failed(self, reason: &str) {
246 self.outcome.send(Err(reason.to_owned())).ok();
247 }
248}
249
250#[derive(Debug, PartialEq, Eq)]
252enum Callback {
253 Code(String),
255 Failed(String),
257 StateMismatch,
259 NoCode,
261 Other,
263}
264
265fn parse_callback(request_line: &str, path: &str, expected_state: &str) -> Callback {
269 let mut parts = request_line.split_whitespace();
270 let (Some("GET"), Some(target)) = (parts.next(), parts.next()) else {
271 return Callback::Other;
272 };
273 let (target_path, query) = target.split_once('?').unwrap_or((target, ""));
274 if target_path != path {
275 return Callback::Other;
276 }
277 let (mut code, mut state, mut error, mut description) = (Vec::new(), Vec::new(), None, None);
278 for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
279 match key.as_ref() {
280 "code" => code.push(value.into_owned()),
281 "state" => state.push(value.into_owned()),
282 "error" => error = Some(value.into_owned()),
283 "error_description" => description = Some(value.into_owned()),
284 _ => {}
285 }
286 }
287 if state.as_slice() != [expected_state] {
288 return Callback::StateMismatch;
289 }
290 if let Some(error) = error {
291 return Callback::Failed(match description.filter(|text| !text.trim().is_empty()) {
292 Some(description) => format!("the browser sign-in returned {error} ({description})"),
293 None => format!("the browser sign-in returned {error}"),
294 });
295 }
296 match code.as_slice() {
297 [code] if !code.is_empty() => Callback::Code(code.clone()),
298 _ => Callback::NoCode,
299 }
300}
301
302struct Serving {
304 pages: Pages,
305 path: String,
306 state: String,
307 deadline: Instant,
308}
309
310impl Serving {
311 fn serve(
312 &self,
313 listeners: &[TcpListener],
314 sender: oneshot::Sender<Result<Received, LoopbackError>>,
315 ) {
316 let pages = &self.pages;
317 let result = 'serve: loop {
318 if sender.is_canceled() {
319 return;
320 }
321 if Instant::now() >= self.deadline {
322 break Err(LoopbackError::TimedOut);
323 }
324 let mut accepted = None;
325 for listener in listeners {
326 match listener.accept() {
327 Ok((stream, _)) => {
328 accepted = Some(stream);
329 break;
330 }
331 Err(error)
332 if matches!(
333 error.kind(),
334 io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted
335 ) => {}
336 Err(error) => break 'serve Err(LoopbackError::Io(error)),
337 }
338 }
339 let Some(mut stream) = accepted else {
340 std::thread::sleep(ACCEPT_POLL);
341 continue;
342 };
343 let until = (Instant::now() + STREAM_TIMEOUT).min(self.deadline);
345 let Ok(line) = read_request_line(&mut stream, until, || sender.is_canceled()) else {
346 continue;
347 };
348 match parse_callback(&line, &self.path, &self.state) {
349 Callback::Other => respond(&mut stream, "404 Not Found", "Not found."),
350 Callback::StateMismatch => {
351 respond(&mut stream, "400 Bad Request", &pages.state_mismatch())
352 }
353 Callback::NoCode => respond(&mut stream, "400 Bad Request", &pages.no_code()),
354 Callback::Failed(message) => {
355 respond(&mut stream, "200 OK", &pages.failed(&message));
356 break Err(LoopbackError::Refused(message));
357 }
358 Callback::Code(code) => {
359 let (outcome, wait) = mpsc::channel();
360 if sender.send(Ok(Received { code, outcome })).is_err() {
361 respond(&mut stream, "200 OK", &pages.cancelled());
362 return;
363 }
364 let body = match wait.recv_timeout(EXCHANGE_WAIT) {
365 Ok(Ok(())) => pages.signed_in(),
366 Ok(Err(message)) => pages.failed(&message),
367 Err(_) => pages.cancelled(),
368 };
369 respond(&mut stream, "200 OK", &body);
370 return;
371 }
372 }
373 };
374 sender.send(result).ok();
375 }
376}
377
378fn read_request_line(
382 stream: &mut TcpStream,
383 until: Instant,
384 stopped: impl Fn() -> bool,
385) -> io::Result<String> {
386 stream.set_nonblocking(false)?;
388 stream.set_write_timeout(Some(STREAM_TIMEOUT))?;
389 let mut head = Vec::new();
390 let mut chunk = [0u8; 1024];
391 while !head.windows(4).any(|window| window == b"\r\n\r\n") {
392 if head.len() >= MAX_REQUEST_BYTES {
393 return Err(io::Error::new(
394 io::ErrorKind::InvalidData,
395 "request head too large",
396 ));
397 }
398 let left = until.saturating_duration_since(Instant::now());
399 if left.is_zero() || stopped() {
400 return Err(io::ErrorKind::TimedOut.into());
401 }
402 stream.set_read_timeout(Some(left.min(ACCEPT_POLL)))?;
404 match stream.read(&mut chunk) {
405 Ok(0) => break,
406 Ok(read) => head.extend(chunk.iter().take(read)),
407 Err(error)
408 if matches!(
409 error.kind(),
410 io::ErrorKind::WouldBlock
411 | io::ErrorKind::TimedOut
412 | io::ErrorKind::Interrupted
413 ) => {}
414 Err(error) => return Err(error),
415 }
416 }
417 let head = String::from_utf8_lossy(&head);
418 Ok(head.lines().next().unwrap_or_default().to_owned())
419}
420
421fn respond(stream: &mut TcpStream, status: &str, body: &str) {
422 let response = format!(
423 "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\n\
424 Content-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{body}",
425 body.len()
426 );
427 stream.write_all(response.as_bytes()).ok();
428 stream.flush().ok();
429}
430
431struct Pages {
433 provider: String,
434 app: String,
435}
436
437impl Pages {
438 fn signed_in(&self) -> String {
439 let Self { provider, app } = self;
440 page(
441 &format!("Signed in to {provider}"),
442 &format!("You can close this tab and return to {app}."),
443 )
444 }
445
446 fn failed(&self, message: &str) -> String {
447 let message = escape_html(message);
448 page(
449 "Sign-in failed",
450 &format!("Sign-in failed: {message}. Return to {}.", self.app),
451 )
452 }
453
454 fn state_mismatch(&self) -> String {
455 let app = &self.app;
456 page(
457 "Sign-in not recognised",
458 &format!(
459 "This sign-in link is not the one {app} is waiting for. Start it again from {app}."
460 ),
461 )
462 }
463
464 fn no_code(&self) -> String {
465 let app = &self.app;
466 page(
467 "No sign-in code",
468 &format!(
469 "This page brought back no sign-in code. {app} is still waiting: finish signing in from the provider's page."
470 ),
471 )
472 }
473
474 fn cancelled(&self) -> String {
475 let app = &self.app;
476 page(
477 "Sign-in cancelled",
478 &format!("{app} stopped waiting for this sign-in. Start it again from {app}."),
479 )
480 }
481}
482
483fn page(title: &str, message: &str) -> String {
485 format!(
486 "<!doctype html><html><head><meta charset=\"utf-8\"><title>{title}</title></head>\
487 <body style=\"font-family: system-ui, sans-serif; margin: 4rem auto; max-width: 32rem\">\
488 <h1>{title}</h1><p>{message}</p></body></html>"
489 )
490}
491
492fn escape_html(text: &str) -> String {
493 let mut escaped = String::with_capacity(text.len());
494 for character in text.chars() {
495 match character {
496 '&' => escaped.push_str("&"),
497 '<' => escaped.push_str("<"),
498 '>' => escaped.push_str(">"),
499 '"' => escaped.push_str("""),
500 '\'' => escaped.push_str("'"),
501 other => escaped.push(other),
502 }
503 }
504 escaped
505}
506
507#[cfg(test)]
508mod tests;