// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The accept loop: a listening socket, and a `Session` for each client that //! arrives. //! //! There is not much to it, which is the point — everything that makes a //! server an FTP server is in `Session`, and everything that makes it serve //! anything in particular is in `Filesystem` and `Auth`. A program that wants //! to accept connections some other way (from a systemd socket, from an //! `inetd`-style parent, over a TLS listener) can skip this entirely and drive //! `Session` itself. //! //! Sessions run concurrently, one task each, because a session spends nearly //! all of its time blocked on a socket. Where the `Io` implementation cannot //! provide concurrency the connection is served inline instead, which is //! correct but serves one client at a time. const std = @import("std"); const Io = std.Io; const net = Io.net; const Allocator = std.mem.Allocator; const protocol = @import("../protocol.zig"); const Reply = protocol.Reply; const Session = @import("Session.zig"); const TimeoutReader = @import("../TimeoutReader.zig"); const TimeoutWriter = @import("../TimeoutWriter.zig"); const Server = @This(); io: Io, gpa: Allocator, /// Copied rather than referenced, so that a caller does not have to keep its /// own `Session.Config` alive for the life of the server. The pointers inside /// it — the file system, the authenticator, the greeting — must of course /// still outlive it. config: Session.Config, options: Options, listener: net.Server, pub const Options = struct { /// The control connection's read buffer, per session. Bounds the length of /// a single command line, and so of the longest pathname a client can /// send. read_buffer_len: usize = 4096, write_buffer_len: usize = 4096, /// How many connections the kernel holds for us between accepts. kernel_backlog: u31 = net.default_kernel_backlog, /// Whether to set SO_REUSEADDR, so that a restarted server does not have /// to wait out the previous one's sockets in TIME_WAIT. reuse_address: bool = true, /// How long a client may say nothing on the control connection before it /// is told 421 and disconnected. Null waits forever, which a server on a /// public network does not want: a client that connects and goes quiet /// holds a task and a socket until it leaves. /// /// It bounds silence, not the session, and only while a command is being /// waited for — a long transfer is not idleness, and its data connection /// has `Session.Config.data_timeout` instead. It also bounds how long a /// client may leave a reply unread, after which it is disconnected without /// one. Needs an `Io` that can time a socket operation out; see /// `TimeoutReader` and `TimeoutWriter`. idle_timeout: ?Io.Duration = null, }; pub const ListenError = net.IpAddress.ListenError; /// Starts listening. The address's port may be zero, in which case the kernel /// picks one and `localAddress` reports which — which is how a test gets a /// server without choosing a port that something else may already have. pub fn listen( io: Io, gpa: Allocator, address: net.IpAddress, config: Session.Config, options: Options, ) ListenError!Server { std.debug.assert(options.read_buffer_len >= Reply.min_control_buffer_len); return .{ .io = io, .gpa = gpa, .config = config, .options = options, .listener = try net.IpAddress.listen(&address, io, .{ .kernel_backlog = options.kernel_backlog, .reuse_address = options.reuse_address, }), }; } pub fn deinit(server: *Server) void { server.listener.deinit(server.io); server.* = undefined; } /// Where the server is actually listening, with the port filled in. pub fn localAddress(server: *const Server) net.IpAddress { return server.listener.socket.address; } /// Stops `serve`, from another task. /// /// Shutting the listening socket down is what RFC-less operating systems have /// instead of a cancel: `accept` returns `error.SocketNotListening`, which /// `serve` treats as "we are done" rather than as a failure. Sessions already /// running are not disturbed; `serve` waits for them before it returns. pub fn shutdown(server: *Server) void { const as_stream: net.Stream = .{ .socket = server.listener.socket }; as_stream.shutdown(server.io, .both) catch {}; } pub const ServeError = error{ /// Accepting failed for a reason that is not going to go away: the process /// is out of file descriptors, or the network stack has gone. AcceptFailed, } || Io.Cancelable; /// Accepts connections until `shutdown` is called or the task is cancelled, /// serving each one concurrently. /// /// Waits for the sessions in flight before returning, so that a caller which /// frees the file system afterwards is not freeing it underneath one. pub fn serve(server: *Server) ServeError!void { var group: Io.Group = .init; // On the way out — including out of a cancellation — the sessions are // asked to stop and then waited for. defer group.cancel(server.io); while (true) { const stream = server.listener.accept(server.io) catch |err| switch (err) { // `shutdown` was called, or the socket was never listening. error.SocketNotListening => return, error.Canceled => return error.Canceled, // One client's connection died between the SYN and the accept, or // was refused by a firewall rule. Neither says anything about the // next one. error.ConnectionAborted, error.BlockedByFirewall, error.ProtocolFailure => continue, else => return error.AcceptFailed, }; group.concurrent(server.io, serveConnection, .{ server, stream }) catch |err| switch (err) { // No concurrency to be had from this `Io`, or no room left for // another task. Serving inline is still serving; it just means // the next client waits. error.ConcurrencyUnavailable => serveConnection(server, stream), }; } } /// Accepts exactly one connection and serves it in this task, returning when /// the session ends. /// /// What a test wants, and what a program driven by `inetd` wants. pub fn serveOne(server: *Server) ServeError!void { const stream = server.listener.accept(server.io) catch |err| switch (err) { error.SocketNotListening => return, error.Canceled => return error.Canceled, else => return error.AcceptFailed, }; serveConnection(server, stream); } /// Everything one session needs, in one allocation, because `Session` holds /// pointers into the reader and the writer and so none of it may move. const Connection = struct { stream: net.Stream, reader: TimeoutReader, writer: TimeoutWriter, session: Session, }; fn serveConnection(server: *Server, stream: net.Stream) void { const gpa = server.gpa; defer stream.close(server.io); const connection = gpa.create(Connection) catch return; defer gpa.destroy(connection); const read_buffer = gpa.alloc(u8, server.options.read_buffer_len) catch return; defer gpa.free(read_buffer); const write_buffer = gpa.alloc(u8, server.options.write_buffer_len) catch return; defer gpa.free(write_buffer); connection.* = .{ .stream = stream, .reader = .init(stream, server.io, read_buffer, TimeoutReader.idle(server.options.idle_timeout)), .writer = .init(stream, server.io, write_buffer, TimeoutWriter.idle(server.options.idle_timeout)), .session = undefined, }; connection.session = .init( server.io, gpa, &server.config, &connection.reader.interface, &connection.writer.interface, .{ // `accept` reports the peer; the address the client reached us on // is the one we are listening at. .peer = stream.socket.address, .local = server.listener.socket.address, }, ); defer connection.session.deinit(); // A session that fails has usually lost the connection it would have // reported the failure over, so there is nothing to do about it here. The // caller sees the connection go, which is all the protocol has to say. // // The exception is a client that went quiet: the connection is fine, and // RFC 959 has a reply for closing it, so the client is told why. connection.session.run() catch |err| switch (err) { error.ReadFailed => if (connection.reader.timedOut()) { const w = &connection.writer.interface; Reply.write(w, .service_unavailable, "Idle timeout, closing control connection") catch {}; w.flush() catch {}; }, else => {}, }; } test { _ = Session; }