Skip to content

Support http over unix domain sockets - #392

Closed
ducaale wants to merge 26 commits into
masterfrom
http-over-unix-socket
Closed

ducaale wants to merge 26 commits into
masterfrom
http-over-unix-socket

Conversation

@ducaale

@ducaale ducaale commented Dec 29, 2024 •

Copy link
Copy Markdown
Owner

Adds a --unix-socket option similar to cURL for binding to a Unix domain socket. When used, all requests, including redirects, will go through the specified Unix socket.

Resources used:

Resolves #230

Comment thread src/unix_socket.rs Outdated

pub fn execute(&self, request: Request) -> Result<Response> {
self.rt.block_on(async {
// TODO: Support named pipes by replacing tokio::net::UnixStream::connect(..) with:

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Besides Docker for Window, I couldn't find any other examples of HTTP over named pipes, so I'm not sure if it's worth supporting at this time.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Daniel Stenberg (author of curl):

I'm not aware of any HTTP server supporting communication over a Windows named pipe, which I assume is a pretty good reason why nobody ever added this feature.

So no, there is no such option.

So I think it's OK not to support it.

I did find one more example: http://stunnix.com/a/http-over-named-pipes.shtml

Comment thread src/main.rs Outdated
Comment on lines +555 to +556
#[cfg(target_family = "unix")]
if let Some(unix_socket) = args.unix_socket {

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a fork of hyperlocal that adds support for windows but it might be better to wait until it is merged upstream

@ducaale
ducaale marked this pull request as ready for review December 29, 2024 22:18
@ducaale
ducaale marked this pull request as draft December 29, 2024 22:19
Comment thread src/unix_socket.rs Outdated
}
});

// TODO: don't ignore value from --timeout option

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regardless of how this is handled, I need to ensure the correct exit code is used for timeout errors

@ducaale ducaale Jan 7, 2025 •

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note to self: refer to impl<B> hyper::body::Body for TotalTimeoutBody<B> for how to implement timeout for body.

Also, we should consider moving to a combination of connect_timeout and read_timeout which is closer to how it is handled in python requests/HTTPie. See https://requests.readthedocs.io/en/stable/user/advanced/#timeouts

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, it seems read_timeout is not yet implemented for reqwest::blocking::Client

@blyxxyz blyxxyz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! I haven't looked at everything yet

Comment thread src/main.rs Resolved
Comment thread src/main.rs Resolved
Comment thread src/cli.rs Outdated

/// Connect using a Unix domain socket.
///
/// Example: --unix_socket=/var/run/temp.sock

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With this API you still have to make up a hostname for the URL, like curl, and unlike got and the HTTPie plugin.

AFAICT the typical use cases are for local services and not for proxies, meaning that the hostname is superfluous. But it also doesn't look like we're going to get a URL-based convention for this any time soon. And splitting it off into an option prevents redirect attacks. (Not sure how it should interact with sessions though... we need to look carefully at other areas of interference.)

A full command with the : shorthand might help users, e.g.

xh :/index.html --unix-socket=/var/run/temp.sock

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a good chance that unix domain sockets will be treated as a proxy in reqwest. This has the advantage that anything relying on hostname like cookies and Host header will keep working. Also, see denoland/deno#8821 (comment)

However, I still think we can support xh http://unix:/var/run/docker.sock:/containers/json by treating it as a syntactic sugar for xh :/containers/json --unix-socket=/var/run/docker.sock.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can always add syntactic sugar later. Right now there doesn't seem to be any consensus about the URL format.

If it ever gets to the point where browsers start supporting UDS URLs (as a non-experimental feature) then we should follow suit.

Comment thread src/unix_socket.rs Outdated
Comment on lines +65 to +70
let starting_time = Instant::now();
let mut response = self.execute(request)?;
response.extensions_mut().insert(ResponseMeta {
request_duration: starting_time.elapsed(),
content_download_duration: None,
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we skip any subsequent middleware this way? I don't understand this yet but it might be the wrong layer to do it.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is the last layer, but returning early and short-circuiting middlewares in this way might be confusing, not to mention the duplicated logic. Let me see if I can switch between UnixSocket and reqwest client inside ClientWithMiddleware.

@ducaale
ducaale marked this pull request as ready for review January 7, 2025 10:46
@ducaale
ducaale requested a review from blyxxyz January 11, 2025 18:11

@blyxxyz blyxxyz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good so far! (I haven't understood everything yet.)

Do you have tips for manually testing this?

Comment thread src/cli.rs
#[clap(
long,
value_name = "FILE",
conflicts_with_all=["proxy", "verify", "cert", "cert_key", "ssl", "resolve", "interface", "ipv4", "ipv6", "https", "http_version"]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Many of these might plausibly appear in an alias or config file, like --https, --ssl.

If someone passes --proxy they probably made a mistake but I think the list could be shorter. Maybe a guideline could be whether the option is compatible with a normal request to http://127.0.0.1?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Were you thinking of silently ignoring some of the flags or maybe printing a warning?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

--https for example doesn't force HTTPS, it just changes the default scheme of the URL. So maybe the user gets an error if they pass :/index.html because that gets converted to https://localhost/index.html and the socket doesn't support TLS, but if they use --https with an explicit http://localhost/index.html then that should be perfectly fine, just like in xh --https http://127.0.0.1 the --https flag is useless but harmless.

Comment thread src/unix_socket.rs
Comment on lines +41 to +45
tokio::task::spawn(async move {
if let Err(err) = conn.await {
log::error!("Connection failed: {:?}", err);
}
});

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it OK to merely log this? I assume it leads to a harder error somewhere down the line and it's just hard to get it out of the task?

Comment thread src/unix_socket.rs
Comment on lines +54 to +55
let mut sender = with_timeout(self.connect(), self.timeout).await??;
let response = with_timeout(sender.send_request(http_request), self.timeout).await??;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this mean we have a separate timeout for each stage?

Will there be a timeout for e.g. a large file upload?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, this is too aggressive. Your streaming example server times out and that kind of thing doesn't happen over TCP.

The docs say the timeout applies to individual connect/read/write operations. So I think that if you have a timeout of 1 second, as long as each individual read/write takes less than 1 second, it can go on indefinitely.

I don't know how easy it is to match that precisely but putting the timeout just on the connect step would already be decent.

Comment thread tests/server/mod.rs
Comment on lines +138 to +142
let file_name: String = rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(10)
.map(char::from)
.collect();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ducaale

ducaale commented Jan 21, 2025 •

Copy link
Copy Markdown
Owner Author

Do you have tips for manually testing this?

I have been using Docker API but you can also use Bun which natively supports unix domain sockets

// bun index.js

async function* hello(times) {
  for (let i = 0; i < times; i++) {
    yield `data: hello ${i}\n\n`;
    await Bun.sleep(1000);
  }
}

const server = Bun.serve({
  unix: "/tmp/my-socket.sock",
  fetch(req){
    return new Response(hello(10), {
      headers: {
        "Content-Type": "text/event-stream",
        Connection: "keep-alive",
      }
    });
  }
});

console.log(`Listening on unix:///tmp/my-socket.sock`);

I'm noticing some decoding errors so I will have to investigate that

$ cargo r -- -v : --unix-socket=/tmp/my-socket.sock

...lines omitted

data: hello 7

data: hello 8

xh: error: error decoding response body

Caused by:
    0: request or response body error
    1: error reading a body from connection
    2: unexpected EOF during chunk size line

Update: I'm getting a similar error in curl so it must be a server bug

$ curl -v http://localhost/stream --unix-socket /tmp/my-socket.sock

...lines omitted

data: hello 8

data: hello 9

* transfer closed with outstanding read data remaining
* Closing connection 0
curl: (18) transfer closed with outstanding read data remaining

@ducaale

ducaale commented Jan 25, 2025

Copy link
Copy Markdown
Owner Author

This one works for me without any "connection closed" errors

// package.json
// { "dependencies": { "express": "^4.21.2" } }

const { setTimeout } = require('node:timers/promises');
const fs = require('fs');

const express = require("express");

const app = express();

app.get("/stream", async (req, res) => {
  res.writeHead(200, {
    "Connection": "keep-alive",
    "Cache-Control": "no-cache",
    "Content-Type": "text/event-stream",
  });

  res.on('close', () => {
    res.end();
  });

  let counter = 0;
  while (counter < 10) {
    const chunk = JSON.stringify({chunk: counter++});
    res.write(`data: ${chunk}\n\n`);
    await setTimeout(1000);
  }

  res.end();
});

app.get("/hello", (req, res) => {
  res.send("hello world");
});

const socket_path = '/tmp/my-socket.sock';
fs.unlinkSync(socket_path);

app.listen(socket_path, () => console.log('server listening on', socket_path));

@ducaale

ducaale commented Mar 19, 2025 •

Copy link
Copy Markdown
Owner Author

Instead of emulating a reqwest client and re-implementing features like timeouts and cookies in hyper, I would like to experiment with spinning up a forward proxy. Fortunately, proxying with hyper seems much simpler than I expected:

Unix socket proxy (hyper)

// hyper = { version = "1", features = ["server", "http1", "client"] }
// hyper-util = { version = "0.1", features = ["tokio"] }
// tokio = { version = "1", features = ["full"] }

// xh :/stream -v --proxy http:http://127.0.0.1:3000

use hyper::{
    body::Incoming, client::conn::http1, server::conn::http1 as server_http1, service::service_fn,
    Request, Response,
};
use hyper_util::rt::TokioIo;
use std::net::SocketAddr;
use tokio::net::{TcpListener, UnixStream};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); // TODO: use port 0 like we do inside tests 
    let listener = TcpListener::bind(addr).await?;

    println!("Proxy running on http://{}", addr);
    
    // TODO: figure out how start and shutdown proxy server inside xh
    loop {
        let (stream, _) = listener.accept().await?;
        tokio::spawn(handle_connection(stream));
    }
}

async fn handle_connection(stream: tokio::net::TcpStream) {
    let io = TokioIo::new(stream);

    if let Err(err) = server_http1::Builder::new()
        .serve_connection(io, service_fn(forward_request))
        .await
    {
        eprintln!("Connection error: {}", err);
    }
}

async fn forward_request(req: Request<Incoming>) -> Result<Response<Incoming>, hyper::Error> {
    let uds_path = "/tmp/my-socket.sock";

    let stream = UnixStream::connect(uds_path).await.unwrap();

    let io = TokioIo::new(stream);
    let (mut sender, conn) = http1::Builder::new().handshake(io).await?;

    tokio::spawn(async move {
        if let Err(err) = conn.await {
            eprintln!("Connection error: {}", err);
        }
    });

    sender.send_request(req).await
}

Unix socket server (Node JS)

const { setTimeout } = require('node:timers/promises');
const fs = require('fs');

const express = require("express");

const app = express();

app.get("/stream", async (req, res) => {
  res.writeHead(200, {
    "Connection": "keep-alive",
    "Cache-Control": "no-cache",
    "Content-Type": "text/event-stream",
  });

  res.on('close', () => {
    res.end();
  });

  let counter = 0;
  while (counter < 10) {
    const chunk = JSON.stringify({chunk: counter++});
    res.write(`data: ${chunk}\n\n`);
    await setTimeout(1000);
  }

  res.end();
});

app.get("/hello", (req, res) => {
  res.send("hello world");
});

const socket_path = '/tmp/my-socket.sock';
if (fs.existsSync(socket_path)) {
  fs.unlinkSync(socket_path);
}

app.listen(socket_path, () => console.log('server listening on', socket_path));

I'll open a separate PR if I manage to get this working.

@ducaale

ducaale commented Mar 31, 2025

Copy link
Copy Markdown
Owner Author

Closing in favour of reqwest's upcoming native unix_socket() support 🥳

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support For Calling Unix Domain Sockets

2 participants