web: SSL but bad

This commit is contained in:
2026-03-08 23:37:22 +01:00
parent 1f07cc38ba
commit 6315589fa1
13 changed files with 1175 additions and 804 deletions

View File

@@ -4,6 +4,7 @@ const Server = @This();
const Connection = @import("Connection.zig");
const FileDescriptor = @import("FileDescriptor.zig").FileDescriptor;
const http = @import("http.zig");
const openssl = @import("openssl.zig");
const RequestRouter = @import("RequestRouter.zig");
const Worker = @import("Worker.zig");
@@ -12,6 +13,7 @@ const errno = linux.E.init;
fd: FileDescriptor,
address: std.net.Address,
ssl_ctx: ?*openssl.SslContext,
workers: []Worker,
threads: []std.Thread,
request_router: RequestRouter,
@@ -33,7 +35,10 @@ const huge_page_size = 2 * 1024 * 1024;
pub const Options = struct {
request_router: RequestRouter,
address: std.net.Address = .initIp4(.{ 127, 0, 0, 1 }, 80),
address: std.net.Address = .initIp4(.{ 127, 0, 0, 1 }, 8000),
/// If not `null`, the server will use TLS with the provided OpenSSL
/// context.
ssl_ctx: ?*openssl.SslContext = null,
max_connections: u32 = 128,
/// The number of worker threads. If set to `0`, the number of worker
/// threads will be equal to the number of logical CPU cores.
@@ -170,6 +175,7 @@ pub fn init(allocator: std.mem.Allocator, options: Options) !Server {
return .{
.fd = fd,
.address = listen_address,
.ssl_ctx = options.ssl_ctx,
.workers = workers,
.threads = threads,
.request_router = options.request_router,
@@ -222,6 +228,12 @@ pub fn listen(self: *Server, running: *const std.atomic.Value(bool)) !void {
continue;
};
const ssl: ?*openssl.Ssl = self.maybeInitSsl(fd) catch |e| {
std.log.err("Error while estabilishing SSL connection: {}", .{e});
fd.close();
continue;
};
{
self.mutex.lock();
defer self.mutex.unlock();
@@ -229,8 +241,7 @@ pub fn listen(self: *Server, running: *const std.atomic.Value(bool)) !void {
while (true) {
if (self.connection_pool.pop()) |node| {
const connection: *Connection = @fieldParentPtr("node", node);
connection.fd = fd;
connection.address = address;
connection.reinit(address, fd, ssl);
self.connection_queue.prepend(node);
break;
}
@@ -243,6 +254,17 @@ pub fn listen(self: *Server, running: *const std.atomic.Value(bool)) !void {
}
}
fn maybeInitSsl(self: *const Server, fd: FileDescriptor) !?*openssl.Ssl {
if (self.ssl_ctx) |ssl_ctx| {
const ssl = try openssl.Ssl.new(ssl_ctx);
try ssl.setFd(fd);
try ssl.accept();
return ssl;
} else {
return null;
}
}
fn err(rc: usize) !void {
const e = errno(rc);
return if (e != .SUCCESS) error.SystemError else {};