Skip to content

Commit 6ee5a2f

Browse files
committed
fix(curl): retain redirect headers when a later request fails
1 parent 33c94aa commit 6ee5a2f

2 files changed

Lines changed: 151 additions & 29 deletions

File tree

‎src/commands/curl.rs‎

Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ async fn cmd_curl(os: &dyn Kernel, args: &[String]) -> CommandResult {
379379
};
380380
wprintln!(w, "curl: (1) Protocol \"{}\" {}", scheme, why)?;
381381
}
382-
return Ok(1);
382+
break Err(1);
383383
}
384384

385385
// Inject credentials (only for original URL, not redirects)
@@ -441,31 +441,21 @@ async fn cmd_curl(os: &dyn Kernel, args: &[String]) -> CommandResult {
441441
{
442442
wprintln!(w, "curl: (28) Operation timed out")?;
443443
}
444-
if let Some(ref fmt) = write_out {
445-
let vars = WriteOut {
446-
status: 0,
447-
content_type: "",
448-
size_download: 0,
449-
url_effective: &current_url,
450-
};
451-
let mut w = io::stdout()?;
452-
wprint!(w, "{}", expand_write_out(fmt, &vars))?;
453-
}
454-
return Ok(28);
444+
break Err(28);
455445
}
456446
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
457447
if let Some(ref mut w) = err {
458448
wprintln!(w, "curl: {}", e)?;
459449
}
460-
return Ok(1);
450+
break Err(1);
461451
}
462452
Err(e) => {
463453
if (!silent || show_error)
464454
&& let Some(ref mut w) = err
465455
{
466456
wprintln!(w, "curl: (6) {}", e)?;
467457
}
468-
return Ok(6);
458+
break Err(6);
469459
}
470460
};
471461

@@ -503,7 +493,7 @@ async fn cmd_curl(os: &dyn Kernel, args: &[String]) -> CommandResult {
503493
redirects_left -= 1;
504494
continue;
505495
}
506-
break r;
496+
break Ok(r);
507497
} else {
508498
// Redirect hop — minimal headers, no credentials
509499
let http_req = crate::os::HttpRequest {
@@ -523,31 +513,21 @@ async fn cmd_curl(os: &dyn Kernel, args: &[String]) -> CommandResult {
523513
{
524514
wprintln!(w, "curl: (28) Operation timed out")?;
525515
}
526-
if let Some(ref fmt) = write_out {
527-
let vars = WriteOut {
528-
status: 0,
529-
content_type: "",
530-
size_download: 0,
531-
url_effective: &current_url,
532-
};
533-
let mut w = io::stdout()?;
534-
wprint!(w, "{}", expand_write_out(fmt, &vars))?;
535-
}
536-
return Ok(28);
516+
break Err(28);
537517
}
538518
Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
539519
if let Some(ref mut w) = err {
540520
wprintln!(w, "curl: {}", e)?;
541521
}
542-
return Ok(1);
522+
break Err(1);
543523
}
544524
Err(e) => {
545525
if (!silent || show_error)
546526
&& let Some(ref mut w) = err
547527
{
548528
wprintln!(w, "curl: (6) {}", e)?;
549529
}
550-
return Ok(6);
530+
break Err(6);
551531
}
552532
};
553533

@@ -585,7 +565,38 @@ async fn cmd_curl(os: &dyn Kernel, args: &[String]) -> CommandResult {
585565
redirects_left -= 1;
586566
continue;
587567
}
588-
break r;
568+
break Ok(r);
569+
}
570+
};
571+
let resp = match resp {
572+
Ok(resp) => resp,
573+
Err(code) => {
574+
// Headers already received survive a failed redirect hop.
575+
if !hop_headers.is_empty() || (code == 28 && write_out.is_some()) {
576+
let mut out = io::stdout()?;
577+
if !hop_headers.is_empty() {
578+
if let Some(ref path) = output {
579+
let fd = io::open(os, path, OpenFlags::write()).await?;
580+
io::take_writer(fd)?
581+
.write_all(hop_headers.as_bytes())
582+
.await?;
583+
} else {
584+
out.write_all(hop_headers.as_bytes()).await?;
585+
}
586+
}
587+
if code == 28
588+
&& let Some(ref fmt) = write_out
589+
{
590+
let vars = WriteOut {
591+
status: 0,
592+
content_type: "",
593+
size_download: 0,
594+
url_effective: &current_url,
595+
};
596+
wprint!(out, "{}", expand_write_out(fmt, &vars))?;
597+
}
598+
}
599+
return Ok(code);
589600
}
590601
};
591602

‎tests/curl_integration.rs‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ async fn start_server() -> String {
6262
.route("/echo", any(echo_handler))
6363
.route("/status/{code}", get(status_handler))
6464
.route("/redirect", get(|| async { Redirect::temporary("/hello") }))
65+
.route(
66+
"/redirect-slow",
67+
get(|| async { Redirect::temporary("/slow") }),
68+
)
6569
.route(
6670
"/redirect-rel",
6771
get(|| async { Redirect::temporary("hello") }),
@@ -337,6 +341,88 @@ fn curl_head_flag_follows_redirects_showing_every_hop() {
337341
}));
338342
}
339343

344+
#[test]
345+
fn curl_head_flag_keeps_headers_when_a_later_hop_fails() {
346+
let (rt, local) = rt();
347+
rt.block_on(local.run_until(async {
348+
let (mut shell, base) = shell_with_server().await;
349+
for (path, flags, status, location) in [
350+
("/redirect-ftp", "", 1, "ftp://example.com/file"),
351+
("/redirect", "--proto-redir '=https'", 1, "/hello"),
352+
("/redirect-slow", "-m 1 -w done", 28, "/slow"),
353+
] {
354+
for output in ["", "-o /tmp/headers"] {
355+
let out = shell
356+
.run(&format!("curl -sSIL {flags} {output} {base}{path}"))
357+
.await;
358+
assert_eq!(out.status, status, "{path}: {}", out.stderr);
359+
assert!(!out.stderr.is_empty(), "{path}");
360+
let headers = if output.is_empty() {
361+
out.stdout
362+
} else {
363+
assert_eq!(out.stdout, if status == 28 { "done" } else { "" });
364+
shell.run("cat /tmp/headers").await.stdout
365+
};
366+
assert!(headers.starts_with("HTTP/1.1 307 "), "{path}: {headers}");
367+
assert!(
368+
headers.contains(&format!("\r\nlocation: {location}\r\n")),
369+
"{path}: {headers}"
370+
);
371+
assert!(
372+
headers.ends_with(if status == 28 && output.is_empty() {
373+
"\r\n\r\ndone"
374+
} else {
375+
"\r\n\r\n"
376+
}),
377+
"{path}: {headers}"
378+
);
379+
}
380+
}
381+
}));
382+
}
383+
384+
#[test]
385+
fn curl_head_flag_keeps_headers_when_a_redirect_connection_fails() {
386+
let (rt, local) = rt();
387+
rt.block_on(local.run_until(async {
388+
let target_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
389+
let target = format!("http://{}", target_listener.local_addr().unwrap());
390+
let location = target.clone();
391+
let app = Router::new().route(
392+
"/away",
393+
get(move || async move { Redirect::temporary(&location) }),
394+
);
395+
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
396+
let base = format!("http://{}", listener.local_addr().unwrap());
397+
tokio::task::spawn_local(async move {
398+
axum::serve(listener, app).await.unwrap();
399+
});
400+
// Hold the target port, but close every connection without a response.
401+
tokio::task::spawn_local(async move {
402+
while let Ok((stream, _)) = target_listener.accept().await {
403+
drop(stream);
404+
}
405+
});
406+
let mut shell = Shell::builder()
407+
.allow_url(&base)
408+
.allow_url(&target)
409+
.build()
410+
.unwrap();
411+
for output in ["", "-o /tmp/headers"] {
412+
let out = shell.run(&format!("curl -sSIL {output} {base}/away")).await;
413+
assert_eq!(out.status, 6, "{}", out.stderr);
414+
let headers = if output.is_empty() {
415+
out.stdout
416+
} else {
417+
assert_eq!(out.stdout, "");
418+
shell.run("cat /tmp/headers").await.stdout
419+
};
420+
assert!(headers.starts_with("HTTP/1.1 307 "), "{headers}");
421+
assert!(headers.contains(&format!("location: {target}\r\n")));
422+
}
423+
}));
424+
}
425+
340426
#[test]
341427
fn curl_head_flag_with_output_writes_headers_to_the_file() {
342428
let (rt, local) = rt();
@@ -374,6 +460,17 @@ fn curl_head_flag_with_fail_shows_headers_then_exits_22() {
374460
out.stdout
375461
);
376462
assert!(out.stdout.ends_with("\r\n\r\n404"), "{}", out.stdout);
463+
464+
let out = shell
465+
.run(&format!(
466+
"curl -sIf -o /tmp/headers -w '%{{http_code}}' {base}/status/404"
467+
))
468+
.await;
469+
assert_eq!(out.status, 22);
470+
assert_eq!(out.stdout, "404");
471+
let headers = shell.run("cat /tmp/headers").await.stdout;
472+
assert!(headers.starts_with("HTTP/1.1 404 Not Found\r\n"));
473+
assert!(headers.ends_with("\r\n\r\n"));
377474
}));
378475
}
379476

@@ -723,6 +820,20 @@ fn curl_redirect_to_blocked_ip_denied() {
723820
"{}",
724821
out.stderr
725822
);
823+
824+
for output in ["", "-o /tmp/headers"] {
825+
let out = shell.run(&format!("curl -sSIL {output} {base}/away")).await;
826+
assert_eq!(out.status, 1);
827+
assert!(out.stderr.contains("access denied: 127.0.0.1"));
828+
let headers = if output.is_empty() {
829+
out.stdout
830+
} else {
831+
assert_eq!(out.stdout, "");
832+
shell.run("cat /tmp/headers").await.stdout
833+
};
834+
assert!(headers.starts_with("HTTP/1.1 307 "), "{headers}");
835+
assert!(headers.contains(&format!("location: {target}/hello\r\n")));
836+
}
726837
}));
727838
}
728839

0 commit comments

Comments
 (0)