Skip to content

Lightpanda: the headless browser designed for AI and automation

Rename option from --socket to --unix-socket

Karl Seguin375af14aa654
diff --git a/README.md b/README.md
index 45f0eddac..a4c759dfc 100644
--- a/README.md
+++ b/README.md
@@ -120,27 +120,12 @@ available to adjust waiting time before dump.
```console
./lightpanda serve --obey-robots --log-format pretty --log-level info --host 127.0.0.1 --port 9222
```
-For an optional **local Unix-domain socket listener** instead of TCP (on
-Unix-like hosts), use an absolute socket path:
-
-```sh
-./lightpanda serve --socket /run/user/1000/lightpanda.sock
-curl --unix-socket /run/user/1000/lightpanda.sock http://localhost/json/version
-```
-
-`--socket` cannot be combined with `--host`, `--port`, or
-`--advertise-host`. The socket is created with owner-only (`0600`)
-permissions, is not replaced if already present, and is unlinked on normal
-server shutdown. Clients must support HTTP/WebSocket over Unix sockets and
-connect directly to the specified socket path; `/json/version` reports a
-null `webSocketDebuggerUrl` because no TCP endpoint exists. Ordinary
-Puppeteer/Playwright connections to `ws://127.0.0.1:9222` still use the
-existing TCP mode.
-
-Unix socket permissions are **not** isolation from other processes sharing
-the same Unix identity, including processes that can inspect or change the
-server's runtime. Use separate OS users or an execution sandbox when
-running untrusted agents.
+
+To listen on a Unix-domain socket (owner-only, mode 0600) instead of TCP:
+
+```console
+./lightpanda serve --unix-socket /run/user/1000/lightpanda.sock
+```
Once the CDP server started, you can run a Puppeteer script by configuring the
`browserWSEndpoint`.
diff --git a/src/Config.zig b/src/Config.zig
index d2cdbedf3..12bad7047 100644
--- a/src/Config.zig
+++ b/src/Config.zig
@@ -407,7 +407,7 @@ pub const Commands = cli.Builder(.{
.options = .{
.{ .name = "host", .type = ?[]const u8 },
.{ .name = "port", .type = ?u16 },
- .{ .name = "socket", .type = ?[:0]const u8, .path = true },
+ .{ .name = "unix_socket", .type = ?[:0]const u8, .path = true },
.{ .name = "advertise_host", .type = ?[]const u8 },
// Repeatable; one server can speak several on the same port.
.{ .name = "protocol", .type = Protocol, .multiple = true },
@@ -510,6 +510,7 @@ pub const Commands = cli.Builder(.{
const RunMode = Commands.Enum;
pub const Mode = Commands.Union;
pub const Agent = @FieldType(Mode, "agent");
+const Serve = @FieldType(Mode, "serve");
mode: Mode,
// The command as typed. Mirrors `mode`, except `run` normalizes to `.agent`
@@ -853,9 +854,14 @@ pub fn port(self: *const Config) u16 {
};
}
+// Optional in the option table so --unix-socket can reject an explicit one.
+pub fn serveHost(self: *const Config) []const u8 {
+ return self.mode.serve.host orelse "127.0.0.1";
+}
+
pub fn advertiseHost(self: *const Config) []const u8 {
return switch (self.mode) {
- .serve => |opts| opts.advertise_host orelse advertiseHostFallback(opts.host orelse "127.0.0.1"),
+ .serve => |opts| opts.advertise_host orelse advertiseHostFallback(self.serveHost()),
.mcp => "127.0.0.1",
else => unreachable,
};
@@ -880,13 +886,6 @@ pub fn remoteAllowOrigins(self: *const Config) []const []const u8 {
};
}
-// Wildcard bind addresses (0.0.0.0, ::) are not routable for clients
-// resolving /json/version. Fall back to a loopback address so the
-// advertised webSocketDebuggerUrl is at least connectable from the same
-// host (covers the official Docker image, which exposes 9222 via the
-// container's published port, and the WSL localhost bridge).
-// For remote hosts, users can still pin the URL with --advertise-host.
-// See issue #1922.
fn advertiseHostFallback(host: []const u8) []const u8 {
if (isHostWildcard(host)) {
return "127.0.0.1";
@@ -900,7 +899,7 @@ fn advertiseHostFallback(host: []const u8) []const u8 {
// resolvable, but the caller still benefits from emitting a guidance log.
pub fn bindIsWildcard(self: *const Config) bool {
return switch (self.mode) {
- .serve => |opts| opts.advertise_host == null and isHostWildcard(opts.host orelse "127.0.0.1"),
+ .serve => |opts| opts.advertise_host == null and isHostWildcard(self.serveHost()),
else => false,
};
}
@@ -1305,19 +1304,21 @@ pub fn parseArgs(allocator: Allocator, proc_args: std.process.Args) !Config {
command = .{ .agent = agent_opts };
}
- // A Unix listener must not quietly open a TCP endpoint as well.
if (command == .serve) {
- const opts = command.serve;
- if (opts.socket != null) {
+ if (command.serve.unix_socket) |path| {
+ const opts = command.serve;
if (opts.host != null or opts.port != null or opts.advertise_host != null) {
- log.fatal(.app, "socket conflicts with TCP", .{});
+ log.fatal(.app, "invalid argument", .{ .arg = "--unix-socket", .hint = "cannot be combined with --host, --port or --advertise-host" });
return error.InvalidArgument;
}
- for (opts.protocol.items) |protocol| {
- if (protocol != .cdp) {
- log.fatal(.app, "socket is CDP-only", .{});
- return error.InvalidArgument;
- }
+ // `:` would end the path in the advertised ws+unix:// URL.
+ if (std.fs.path.isAbsolute(path) == false or std.mem.findScalar(u8, path, ':') != null) {
+ log.fatal(.app, "invalid argument", .{ .arg = "--unix-socket", .value = path, .hint = "must be an absolute path without ':'" });
+ return error.InvalidArgument;
+ }
+ if (path.len >= @sizeOf(@FieldType(std.posix.sockaddr.un, "path"))) {
+ log.fatal(.app, "invalid argument", .{ .arg = "--unix-socket", .value = path, .hint = "path is too long" });
+ return error.InvalidArgument;
}
}
}
@@ -1868,23 +1869,28 @@ test "Config: parseArgs --load-resources defaults stylesheets on for mcp and age
}
}
-test "Config: unix socket serve flag refuses TCP flags" {
- log.expectLog(&.{.app});
- const vectors = [_][*:0]const u8{ "lightpanda", "serve", "--socket", "/tmp/lp-test.sock", "--port", "9322" };
- const proc_args: std.process.Args = .{ .vector = &vectors };
- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
- defer arena.deinit();
- try std.testing.expectError(error.InvalidArgument, parseArgs(arena.allocator(), proc_args));
+test "Config: --unix-socket rejects TCP flags and bad paths" {
+ log.expectLog(&.{ .app, .app, .app, .app, .app });
+ var long: [120:0]u8 = @splat('a');
+ long[0] = '/';
+ const cases = [_][]const [*:0]const u8{
+ &.{ "lightpanda", "serve", "--unix-socket", "/tmp/lp.sock", "--port", "9322" },
+ &.{ "lightpanda", "serve", "--unix-socket", "/tmp/lp.sock", "--host", "127.0.0.1" },
+ &.{ "lightpanda", "serve", "--unix-socket", "lp.sock" },
+ &.{ "lightpanda", "serve", "--unix-socket", "/tmp/lp:1.sock" },
+ &.{ "lightpanda", "serve", "--unix-socket", &long },
+ };
+ for (cases) |vector| {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ try std.testing.expectError(error.InvalidArgument, parseArgs(arena.allocator(), .{ .vector = vector }));
+ }
}
-test "Config: unix socket serve flag is parsed without opening TCP" {
- const vectors = [_][*:0]const u8{ "lightpanda", "serve", "--socket", "/tmp/lp-test.sock" };
- const proc_args: std.process.Args = .{ .vector = &vectors };
+test "Config: --unix-socket" {
+ const vector = [_][*:0]const u8{ "lightpanda", "serve", "--unix-socket", "/tmp/lp.sock", "--protocol", "webdriver" };
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
- const config = try parseArgs(arena.allocator(), proc_args);
- try std.testing.expect(config.mode == .serve);
- try std.testing.expectEqualStrings("/tmp/lp-test.sock", config.mode.serve.socket.?);
- try std.testing.expectEqual(@as(?u16, null), config.mode.serve.port);
- try std.testing.expectEqual(@as(?[]const u8, null), config.mode.serve.host);
+ const config = try parseArgs(arena.allocator(), .{ .vector = &vector });
+ try std.testing.expectEqualStrings("/tmp/lp.sock", config.mode.serve.unix_socket.?);
}
diff --git a/src/help.zon b/src/help.zon
index 3e2160c36..0dc43616a 100644
--- a/src/help.zon
+++ b/src/help.zon
@@ -68,17 +68,16 @@
\\ cdp Chrome DevTools Protocol (WebSocket on /).
\\ webdriver WebDriver BiDi (WebSocket on /session) plus the
\\ classic WebDriver session endpoints.
- \\ --socket <PATH>
- \\ Serve CDP over a local Unix-domain socket instead of TCP.
- \\ Must be absolute; cannot combine with --host, --port,
- \\ --advertise-host, or WebDriver BiDi. Owner-only mode 0600.
- \\ /json/version does not advertise a TCP WebSocket URL.
\\ --remote-allow-origins <ORIGIN>
\\ Origin (e.g. http://localhost:3000) allowed in the Origin header
\\ of CDP and BiDi WebSocket upgrades, or * to allow any. Can be
\\ passed multiple times. Upgrades without an Origin header are
\\ always accepted.
\\ Defaults to none, rejecting any upgrade that sends an Origin.
+ \\ --unix-socket <PATH>
+ \\ Listen on this Unix-domain socket (mode 0600) instead of TCP.
+ \\ Must be absolute. Cannot be combined with --host, --port or
+ \\ --advertise-host.
,
.fetch =
\\usage: {0s} fetch <url>... [OPTIONS] [COMMON_OPTIONS]
diff --git a/src/main.zig b/src/main.zig
index e15b32555..32a22945e 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -123,26 +123,29 @@ fn run(allocator: Allocator, main_arena: Allocator, proc_args: std.process.Args)
switch (args.mode) {
.serve => |opts| {
log.debug(.app, "startup", .{ .mode = "serve", .snapshot = app.snapshot.fromEmbedded() });
- const server = if (opts.socket) |path| blk: {
- if (opts.host != null or opts.port != null or opts.advertise_host != null) {
- log.fatal(.app, "socket conflicts with TCP", .{});
- return error.InvalidArgument;
- }
- break :blk lp.Server.initUnix(app, path) catch |err| {
- log.fatal(.app, "unix socket server error", .{ .err = err, .path = path });
- return err;
- };
- } else blk: {
- const host = opts.host orelse "127.0.0.1";
- const port = opts.port orelse 9222;
- const address = std.Io.net.IpAddress.parse(host, port) catch |err| {
- log.fatal(.app, "invalid server address", .{ .err = err, .host = host, .port = port });
+ const address: lp.Server.Address = if (opts.unix_socket) |path| .{ .unix = path } else .{
+ .ip = std.Io.net.IpAddress.parse(args.serveHost(), args.port()) catch |err| {
+ log.fatal(.app, "invalid server address", .{ .err = err, .host = args.serveHost(), .port = args.port() });
return args.printUsageAndExit(main_arena, .serve, false);
- };
- break :blk lp.Server.init(app, address) catch |err| {
- log.fatal(.app, "server run error", .{ .err = err, .host = host, .port = port });
- return err;
- };
+ },
+ };
+
+ var server = lp.Server.init(app, address) catch |err| {
+ if (err != error.AddressInUse) {
+ log.fatal(.app, "server run error", .{ .err = err });
+ } else switch (address) {
+ .ip => log.fatal(.app, "address already in use", .{
+ .host = args.serveHost(),
+ .port = args.port(),
+ .hint = "Another process is already listening on this address. " ++
+ "Stop the other process or use --port to choose a different port.",
+ }),
+ .unix => |path| log.fatal(.app, "address already in use", .{
+ .path = path,
+ .hint = "The path already exists. If no other process is listening on it, delete it.",
+ }),
+ }
+ return err;
};
defer server.deinit();
@@ -258,7 +261,7 @@ fn run(allocator: Allocator, main_arena: Allocator, proc_args: std.process.Args)
log.fatal(.mcp, "invalid cdp address", .{ .err = err, .port = port });
return;
};
- cdp_server = try lp.Server.init(app, address);
+ cdp_server = try lp.Server.init(app, .{ .ip = address });
try sighandler.on(lp.Server.shutdown, .{cdp_server.?});
}
defer if (cdp_server) |s| s.deinit();
diff --git a/src/server/Server.zig b/src/server/Server.zig
index 859391a2e..9fa302cec 100644
--- a/src/server/Server.zig
+++ b/src/server/Server.zig
@@ -124,26 +124,12 @@ bidi_session_url: []const u8,
json_version_response: []const u8,
-const ListenerTransport = union(enum) {
- tcp: sys_net.IpAddress,
- unix: [:0]const u8,
+pub const Address = union(enum) {
+ ip: sys_net.IpAddress,
+ unix: [:0]const u8, // Absolute path, validated by Config
};
-pub fn init(app: *App, address: sys_net.IpAddress) !*Server {
- return initWithTransport(app, .{ .tcp = address });
-}
-
-/// Bind the existing HTTP/WebSocket protocol on a local Unix socket.
-/// Does not remove a pre-existing pathname (which might belong to another service).
-pub fn initUnix(app: *App, path: [:0]const u8) !*Server {
- if (path.len == 0 or path.len >= @sizeOf(@FieldType(posix.sockaddr.un, "path"))) {
- return error.InvalidSocketPath;
- }
- if (path[0] != '/') return error.SocketPathMustBeAbsolute;
- return initWithTransport(app, .{ .unix = path });
-}
-
-fn initWithTransport(app: *App, transport: ListenerTransport) !*Server {
+pub fn init(app: *App, address: Address) !*Server {
const config = app.config;
const allocator = app.allocator;
@@ -153,73 +139,42 @@ fn initWithTransport(app: *App, transport: ListenerTransport) !*Server {
var scratch = try std.Io.Writer.Allocating.initCapacity(allocator, 8192);
errdefer scratch.deinit();
- var json_version_response: []const u8 = "";
- var bidi_session_url: []const u8 = "";
-
const max_connections = fdBudget(config);
- var unix_bound = false;
- errdefer if (unix_bound) switch (transport) {
- .unix => |path| {
- _ = std.c.unlink(path.ptr);
- },
- .tcp => {},
+ const listener = switch (address) {
+ .ip => |ip| try listenIp(ip, config.maxPendingConnections()),
+ .unix => |path| try listenUnix(path, config.maxPendingConnections()),
+ };
+ const unix_path: ?[:0]const u8 = switch (address) {
+ .ip => null,
+ .unix => |path| path,
};
+ errdefer closeListener(listener, unix_path);
- const listener = blk: {
- const flags = posix.SOCK.STREAM | posix.SOCK.CLOEXEC | posix.SOCK.NONBLOCK;
- const l = switch (transport) {
- .tcp => |address| try sys_net.socket(sys_net.family(&address), flags, posix.IPPROTO.TCP),
- .unix => try sys_net.socket(posix.AF.UNIX, flags, 0),
- };
- errdefer sys_net.close(l);
+ const ws_url = switch (address) {
+ .ip => try allocator.print("ws://{s}:{d}/", .{ config.advertiseHost(), (try sys_net.boundAddress(listener)).getPort() }),
+ .unix => |path| try allocator.print("ws+unix://{s}:/", .{path}),
+ };
+ defer allocator.free(ws_url);
- const bound_port: u16 = switch (transport) {
- .tcp => |address| tcp_bound: {
- try posix.setsockopt(l, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
- if (@hasDecl(posix.TCP, "NODELAY")) {
- try posix.setsockopt(l, posix.IPPROTO.TCP, posix.TCP.NODELAY, &std.mem.toBytes(@as(c_int, 1)));
- }
- const sa = sys_net.sockaddrFromAddress(&address);
- try sys_net.bind(l, sa.ptr(), sa.len);
- break :tcp_bound (try sys_net.boundAddress(l)).getPort();
- },
- .unix => |path| unix_socket: {
- var sa: posix.sockaddr.un = std.mem.zeroes(posix.sockaddr.un);
- sa.family = posix.AF.UNIX;
- @memcpy(sa.path[0..path.len], path);
- try sys_net.bind(l, @ptrCast(&sa), @intCast(@offsetOf(posix.sockaddr.un, "path") + path.len + 1));
- unix_bound = true;
- if (std.c.chmod(path.ptr, 0o600) != 0) return error.SocketPermissions;
- break :unix_socket 0;
- },
- };
+ const json_version_response = try http.buildJSONVersionResponse(app, ws_url);
+ errdefer allocator.free(json_version_response);
- json_version_response = try http.buildJSONVersionResponse(app, switch (transport) {
- .tcp => bound_port,
- .unix => null,
- });
- errdefer allocator.free(json_version_response);
- bidi_session_url = try allocator.print("ws://{s}:{d}/session/", .{ config.advertiseHost(), bound_port });
- errdefer allocator.free(bidi_session_url);
-
- try sys_net.listen(l, config.maxPendingConnections());
- switch (transport) {
- .tcp => log.note(.note, "server running", .{
- .address = try sys_net.boundAddress(l),
- .max_connections = max_connections,
- .max_browser_connections = config.maxConnections(),
- }),
- .unix => |path| log.note(.note, "server running on unix socket", .{
- .path = path,
- .max_connections = max_connections,
- .max_browser_connections = config.maxConnections(),
- }),
- }
+ const bidi_session_url = try allocator.print("{s}session/", .{ws_url});
+ errdefer allocator.free(bidi_session_url);
- break :blk l;
- };
- errdefer sys_net.close(listener);
+ switch (address) {
+ .ip => log.note(.note, "server running", .{
+ .address = try sys_net.boundAddress(listener),
+ .max_connections = max_connections,
+ .max_browser_connections = config.maxConnections(),
+ }),
+ .unix => |path| log.note(.note, "server running", .{
+ .path = path,
+ .max_connections = max_connections,
+ .max_browser_connections = config.maxConnections(),
+ }),
+ }
var http_connection_pool = try Connection.Pool.init(app);
errdefer http_connection_pool.deinit();
@@ -254,10 +209,7 @@ fn initWithTransport(app: *App, transport: ListenerTransport) !*Server {
.app = app,
.io_engine = io_engine,
.listener = listener,
- .unix_path = switch (transport) {
- .tcp => null,
- .unix => |path| path,
- },
+ .unix_path = unix_path,
.listener_paused = false,
.scratch = scratch,
.request_arena = std.heap.ArenaAllocator.init(allocator),
@@ -283,6 +235,53 @@ fn initWithTransport(app: *App, transport: ListenerTransport) !*Server {
return self;
}
+fn listenIp(address: sys_net.IpAddress, backlog: u31) !posix.socket_t {
+ const flags = posix.SOCK.STREAM | posix.SOCK.CLOEXEC | posix.SOCK.NONBLOCK;
+ const l = try sys_net.socket(sys_net.family(&address), flags, posix.IPPROTO.TCP);
+ errdefer sys_net.close(l);
+
+ try posix.setsockopt(l, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
+ if (@hasDecl(posix.TCP, "NODELAY")) {
+ try posix.setsockopt(l, posix.IPPROTO.TCP, posix.TCP.NODELAY, &std.mem.toBytes(@as(c_int, 1)));
+ }
+
+ const sa = sys_net.sockaddrFromAddress(&address);
+ try sys_net.bind(l, sa.ptr(), sa.len);
+ try sys_net.listen(l, backlog);
+ return l;
+}
+
+// An existing file at `path` fails the bind with AddressInUse: it may be
+// another server's socket, so it is never removed.
+fn listenUnix(path: [:0]const u8, backlog: u31) !posix.socket_t {
+ var sa = std.mem.zeroes(posix.sockaddr.un);
+ lp.assert(path.len < sa.path.len, "unix socket path too long", .{ .len = path.len });
+ sa.family = posix.AF.UNIX;
+ @memcpy(sa.path[0..path.len], path);
+
+ const flags = posix.SOCK.STREAM | posix.SOCK.CLOEXEC | posix.SOCK.NONBLOCK;
+ const l = try sys_net.socket(posix.AF.UNIX, flags, 0);
+ errdefer sys_net.close(l);
+
+ try sys_net.bind(l, @ptrCast(&sa), @intCast(@offsetOf(posix.sockaddr.un, "path") + path.len + 1));
+ errdefer std.Io.Dir.cwd().deleteFile(lp.io, path) catch {};
+
+ // Not atomic with the bind, but connecting needs write permission,
+ // which a umask rarely grants to anyone but the owner.
+ if (std.c.chmod(path.ptr, 0o600) != 0) {
+ return error.SocketPermissions;
+ }
+ try sys_net.listen(l, backlog);
+ return l;
+}
+
+fn closeListener(listener: posix.socket_t, unix_path: ?[:0]const u8) void {
+ sys_net.close(listener);
+ if (unix_path) |path| {
+ std.Io.Dir.cwd().deleteFile(lp.io, path) catch {};
+ }
+}
+
pub fn deinit(self: *Server) void {
const allocator = self.app.allocator;
@@ -301,10 +300,7 @@ pub fn deinit(self: *Server) void {
self.http_connection_pool.deinit();
allocator.free(self.json_version_response);
allocator.free(self.bidi_session_url);
- sys_net.close(self.listener);
- if (self.unix_path) |path| {
- _ = std.c.unlink(path.ptr);
- }
+ closeListener(self.listener, self.unix_path);
self.io_engine.deinit();
allocator.destroy(self);
}
@@ -403,12 +399,12 @@ fn accept(self: *Server, now: u64) !void {
}
};
errdefer sys_net.close(socket);
- if (self.unix_path == null) configureSocket(socket);
-
- const peer: sys_net.IpAddress = if (self.unix_path != null)
- .{ .ip4 = .loopback(0) }
- else
- sys_net.addressFromSockaddr(@ptrCast(&address));
+ // A Unix socket has neither TCP options nor a peer IP.
+ var peer: sys_net.IpAddress = .{ .ip4 = .unspecified(0) };
+ if (self.unix_path == null) {
+ configureSocket(socket);
+ peer = sys_net.addressFromSockaddr(@ptrCast(&address));
+ }
if (comptime lp.IS_DEBUG) {
log.debug(.serve, "client connected", .{ .address = peer });
}
@@ -1490,7 +1486,7 @@ const WorkerRequest = struct {
const testing = @import("../testing.zig");
test "server: buildJSONVersionResponse" {
- const res = try http.buildJSONVersionResponse(testing.test_app, testing.test_app.config.port());
+ const res = try http.buildJSONVersionResponse(testing.test_app, "ws://127.0.0.1:9222/");
defer testing.test_app.allocator.free(res);
// The response includes the build version, so check structure rather than exact bytes.
@@ -1505,6 +1501,10 @@ test "server: buildJSONVersionResponse" {
try testing.expect(std.mem.find(u8, res, "\"User-Agent\": \"Lightpanda/") != null);
try testing.expect(std.mem.find(u8, res, "\"Lightpanda-Version\": \"" ++ lp.build_config.version ++ "\"") != null);
try testing.expect(std.mem.find(u8, res, "\"webSocketDebuggerUrl\": \"ws://127.0.0.1:9222/\"") != null);
+
+ const unix = try http.buildJSONVersionResponse(testing.test_app, "ws+unix:///tmp/a\"b.sock:/");
+ defer testing.test_app.allocator.free(unix);
+ try testing.expect(std.mem.find(u8, unix, "\"webSocketDebuggerUrl\": \"ws+unix:///tmp/a\\\"b.sock:/\"}") != null);
}
test "Client: http header past the initial buffer" {
@@ -3460,7 +3460,7 @@ const LoopTest = struct {
address: sys_net.IpAddress,
fn init() !LoopTest {
- const server = try Server.init(testing.test_app, .{ .ip4 = .loopback(0) });
+ const server = try Server.init(testing.test_app, .{ .ip = .{ .ip4 = .loopback(0) } });
errdefer server.deinit();
server.protocols = .{ .cdp = true, .webdriver = true };
// run() does this; runOnce() on its own would never see an accept
@@ -3689,11 +3689,12 @@ test "server: unix listener accepts a client and removes owned socket on shutdow
const path = try std.fmt.allocPrintSentinel(testing.allocator, "{s}/cdp.sock", .{absolute_dir}, 0);
defer testing.allocator.free(path);
- const server = try Server.initUnix(testing.test_app, path);
+ const server = try Server.init(testing.test_app, .{ .unix = path });
var live = true;
defer if (live) server.deinit();
- try testing.expectEqual(@as(c_int, 0), std.c.access(path.ptr, 0));
- try testing.expectError(error.AddressInUse, Server.initUnix(testing.test_app, path));
+ try testing.expectEqual(0, std.c.access(path.ptr, 0));
+ try testing.expect(std.mem.indexOf(u8, server.json_version_response, "\"ws+unix://") != null);
+ try testing.expectError(error.AddressInUse, Server.init(testing.test_app, .{ .unix = path }));
try server.io_engine.monitorListener(server.listener);
const client = try sys_net.socket(posix.AF.UNIX, posix.SOCK.STREAM | posix.SOCK.CLOEXEC, 0);
@@ -3701,16 +3702,10 @@ test "server: unix listener accepts a client and removes owned socket on shutdow
var address: posix.sockaddr.un = std.mem.zeroes(posix.sockaddr.un);
address.family = posix.AF.UNIX;
@memcpy(address.path[0..path.len], path);
- try testing.expectEqual(@as(c_int, 0), std.c.connect(client, @ptrCast(&address), @intCast(@offsetOf(posix.sockaddr.un, "path") + path.len + 1)));
+ try testing.expectEqual(0, std.c.connect(client, @ptrCast(&address), @intCast(@offsetOf(posix.sockaddr.un, "path") + path.len + 1)));
try server.accept(lp.datetime.milliTimestamp(.boot));
try testing.expect(server.http_connections.first != null);
server.deinit();
live = false;
try testing.expect(std.c.access(path.ptr, 0) != 0);
}
-
-test "server: unix listener refuses non-absolute and overlong paths" {
- try testing.expectError(error.SocketPathMustBeAbsolute, Server.initUnix(testing.test_app, "cdp.sock"));
- const too_long = "/" ++ "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
- try testing.expectError(error.InvalidSocketPath, Server.initUnix(testing.test_app, too_long));
-}
diff --git a/src/server/http.zig b/src/server/http.zig
index d3f64f4e9..3f3dccfad 100644
--- a/src/server/http.zig
+++ b/src/server/http.zig
@@ -1030,23 +1030,7 @@ fn touch(server: *Server, conn: *Connection, now: u64) void {
server.http_connections.append(&conn.node);
}
-pub fn buildJSONVersionResponse(app: *const App, port: ?u16) ![]const u8 {
- // Unix sockets have no connectable TCP WebSocket URL. Do not invent
- // ws://localhost:0/ and accidentally advertise an unsecured endpoint.
- // Unix-socket-aware clients should connect directly to the socket path.
- if (port == null) {
- const body =
- "{\"Browser\": \"Lightpanda/1.0\", " ++
- "\"Protocol-Version\": \"1.3\", " ++
- "\"User-Agent\": \"Lightpanda/1.0\", " ++
- "\"Lightpanda-Version\": \"" ++ lp.build_config.version ++ "\", " ++
- "\"webSocketDebuggerUrl\": null}";
- return app.allocator.print(
- "HTTP/1.1 200 OK\r\nContent-Length: {d}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{s}",
- .{ body.len, body },
- );
- }
- const host = app.config.advertiseHost();
+pub fn buildJSONVersionResponse(app: *const App, ws_url: []const u8) ![]const u8 {
if (app.config.bindIsWildcard()) {
// Serve is bound to INADDR_ANY but no --advertise-host was given;
// advertiseHost() falls back to 127.0.0.1 so clients can still
@@ -1062,16 +1046,18 @@ pub fn buildJSONVersionResponse(app: *const App, port: ?u16) ![]const u8 {
"\"Protocol-Version\": \"1.3\", " ++
"\"User-Agent\": \"Lightpanda/1.0\", " ++
"\"Lightpanda-Version\": \"" ++ lp.build_config.version ++ "\", " ++
- "\"webSocketDebuggerUrl\": \"ws://{s}:{d}/\"" ++
+ "\"webSocketDebuggerUrl\": {f}" ++
"}}";
- const body_len = std.fmt.count(body_format, .{ host, port.? });
+ // A unix socket path is user input: escape it.
+ const url = std.json.fmt(ws_url, .{});
+ const body_len = std.fmt.count(body_format, .{url});
const response_format =
"HTTP/1.1 200 OK\r\n" ++
"Content-Length: {d}\r\n" ++
"Content-Type: application/json; charset=UTF-8\r\n\r\n" ++
body_format;
- return try app.allocator.print(response_format, .{ body_len, host, port.? });
+ return try app.allocator.print(response_format, .{ body_len, url });
}
// Where the upgraded socket goes: a new worker, or an existing session's.
@@ -1087,6 +1073,7 @@ fn upgrade(server: *Server, conn: *Connection, req: *Connection.Request, target:
const accept_key = webSocketAccept(req.head, &accept_buf, .{
.host = server.advertise_host,
.origins = server.remote_allow_origins,
+ .check_host = server.unix_path == null,
}) catch |err| {
const response: []const u8 = switch (err) {
error.ForbiddenOrigin => forbidden_origin_response,
@@ -1122,6 +1109,9 @@ fn upgrade(server: *Server, conn: *Connection, req: *Connection.Request, target:
// from the old Handshake path. `allow` holds the explicit --advertise-host and
// --remote-allow-origins, if any.
const Allow = struct {
+ // DNS rebinding needs a TCP connection: a browser can't reach a unix
+ // socket, and its clients send a bare `Host: localhost`.
+ check_host: bool = true,
host: ?[]const u8 = null,
origins: []const []const u8 = &.{},
};
@@ -1161,7 +1151,7 @@ fn webSocketAccept(head: []const u8, out: *[28]u8, allow: Allow) ![]const u8 {
log.warn(.serve, "rejected websocket origin", .{ .origin = h.value[0..@min(h.value.len, 64)], .note = "See `--remote-allow-origins <origins>` if this is a legitimate origin" });
return error.ForbiddenOrigin;
}
- } else if (std.ascii.eqlIgnoreCase(h.key, "host")) {
+ } else if (allow.check_host and std.ascii.eqlIgnoreCase(h.key, "host")) {
if (isAllowedHost(h.value, allow.host) == false) {
log.warn(.serve, "rejected websocket host", .{ .host = h.value[0..@min(h.value.len, 64)], .note = "See `--advertise-host <host>` if this is a legitimate host" });
return error.ForbiddenHost;
@@ -1244,6 +1234,8 @@ test "http: webSocketAccept honours the advertised host" {
var out: [28]u8 = undefined;
try testing.expectError(error.ForbiddenHost, webSocketAccept(head, &out, .{}));
try testing.expectString("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", try webSocketAccept(head, &out, .{ .host = "lightpanda" }));
+ // Over a unix socket any Host is fine.
+ try testing.expectString("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", try webSocketAccept(head, &out, .{ .check_host = false }));
}
test "http: isAllowedOrigin" {
diff --git a/src/testing.zig b/src/testing.zig
index 4b6b1bce3..aef335dae 100644
--- a/src/testing.zig
+++ b/src/testing.zig
@@ -654,7 +654,7 @@ test "tests:afterAll" {
fn serveCDP(wg: *lp.WaitGroup) !void {
const address = try std.Io.net.IpAddress.parse("127.0.0.1", 0);
- test_cdp_server = Server.init(test_app, address) catch |err| {
+ test_cdp_server = Server.init(test_app, .{ .ip = address }) catch |err| {
std.debug.print("CDP server error: {}", .{err});
return err;
};