Standard library · Network

ftpd

An FTP and FTPS server that shares a directory with a login, passive transfers and optional TLS.

import ftpd

This package is an FTP server written in Salam. Give it a root directory, a user and a password, call Listen and then Serve, and any FTP client can list, upload, download, rename and delete files below that directory. Paths are resolved inside the root, and a symbolic link inside it that points outside the root, or at nothing, is refused rather than followed. It is the other half of the ftp client package, and the two work together.

It speaks plain FTP and FTPS. Transfers use passive mode (PASV and EPSV) on a port range you choose, so open that range in the firewall. Login is either one configured user with a password, or anonymous access when allow_anonymous is on; with neither, nobody can log in. With a certificate and a key the server also takes explicit FTPS (AUTH TLS, then PROT P for the data connection) and, with implicit_tls, implicit FTPS where the connection is encrypted from the first byte.

What to know before you use it:

•

There is one user. user and password describe a single account; a list of accounts, per-user directories and permissions are not part of this package.

•

Clients are served one after another. Serve handles one connection to the end before it accepts the next, so it suits a small drop box or a build artefact server, not a busy public one.

•

Plain FTP sends the password in the clear. Turn on tls_enabled with cert_file and key_file, and set require_tls so that the server refuses USER and PASS until the connection is encrypted. A client has to start TLS before it sends the password; a client that sends it first has already leaked it, so require_tls protects only clients that behave.

•

Port 0 picks a free port, and Port tells you which. That is how the examples and the tests run without clashing with anything.

Serve a directory with a login

Make a configuration with NewConfig, set the root, the user, the password and the passive port range, create the server with New, and call Listen. Listen is false when the port is taken or you may not use it; check it before Serve, which runs until the server is stopped. Ports below 1024, including the usual 21, need extra rights on most systems, which is why the example uses 2121.

ftpd-serve-files.salam
import ftpd
import env

func main:
    mut cfg := ftpd.NewConfig()
    cfg.host = "127.0.0.1"
    cfg.port = 2121
    cfg.root = "/srv/ftp"
    cfg.user = "reports"
    cfg.password = env.Get("FTP_PASSWORD")
    if cfg.password.len() == 0:
        println "set FTP_PASSWORD first"
        ret 1
    end
    cfg.passive_start = 40000
    cfg.passive_end = 40100
    mut srv := ftpd.New(cfg)
    if not ftpd.Listen(srv):
        println "cannot listen on port", cfg.port
        ret 1
    end
    println "serving", cfg.root, "on port", ftpd.Port(srv)
    ftpd.Serve(srv)
    ftpd.Close(srv)
    ret 0
end

The example binds to the loopback address and reads the password from the FTP_PASSWORD variable, so it never listens for other machines with a password written in the page; plain FTP should not leave the machine, use FTPS for that. It runs until it is stopped, so it is only checked here. Point any client at it, for example the ftp package with Dial and Login using the same user and password.

Encrypt the connection with FTPS

A certificate and a private key in PEM files turn on TLS. A client then upgrades the connection with AUTH TLS and protects the file data with PROT P. require_tls goes one step further and refuses USER and PASS until that has happened, so the server will not even try a login on a plain connection, though a password a misbehaving client already sent is gone. With implicit_tls the server expects TLS from the very first byte, the older FTPS style that uses its own port.

ftpd-ftps.salam
import ftpd
import env

func main:
    mut cfg := ftpd.NewConfig()
    cfg.port = 2121
    cfg.root = "/srv/ftp"
    cfg.user = "reports"
    cfg.password = env.Get("FTP_PASSWORD")
    if cfg.password.len() == 0:
        println "set FTP_PASSWORD first"
        ret 1
    end
    cfg.tls_enabled = true
    cfg.cert_file = "/etc/ssl/certs/ftp.crt"
    cfg.key_file = "/etc/ssl/private/ftp.key"
    cfg.require_tls = true
    mut srv := ftpd.New(cfg)
    if not ftpd.Listen(srv):
        println "cannot listen on port", cfg.port
        ret 1
    end
    ftpd.Serve(srv)
    ret 0
end

If the certificate or the key cannot be read, TLS stays off even when tls_enabled is true, so test the setup with a real client once before you trust it.

Defaults and a free port

A fresh configuration listens on all interfaces on port 21, serves the current directory, and lets nobody in until you set a user or turn on anonymous access. Passive transfers use ports 40000 to 40100. The program below shows the defaults, then binds to port 0 on the loopback address to find out which port the system gave it. Nothing connects, so it runs without a network.

ftpd-listen.salam
import ftpd

func main:
    mut cfg := ftpd.NewConfig()
    println cfg.port, cfg.root, cfg.allow_anonymous
    println cfg.passive_start, cfg.passive_end, cfg.tls_enabled
    cfg.host = "127.0.0.1"
    cfg.port = 0
    cfg.allow_anonymous = true
    mut srv := ftpd.New(cfg)
    println ftpd.Listen(srv)
    println ftpd.Port(srv) > 0
    ftpd.Close(srv)
    println srv.running
end
Output
21 . false
40000 40100 false
true
true
false

After Listen the configuration inside the server holds the real port, which is what Port returns. Close stops the server and releases the port.

Which function for which job

JobUse
Start from the defaultsNewConfig, then set the fields of Config
Create the serverNew
Open the portListen, then Port to read it
Serve clients until stoppedServe
Serve exactly one clientServeOnce
Stop and free the portClose

Types

Config

#
struct Config

The configuration of an FTP server.

NameTypeDescription
hoststr = "0.0.0.0"The address to listen on; 0.0.0.0 means every interface.
portint = 21The port to listen on; 21 by default, and 0 lets the system choose one.
rootstr = "."The directory the clients see as /; nothing above it can be reached.
allow_anonymousbool = falseLets clients log in as the anonymous user without a password; off by default.
anonymous_userstr = "anonymous"The name that counts as anonymous; anonymous by default.
userstr = ""The name of the one account that may log in with a password.
passwordstr = ""The password of that account.
passive_startint = 40000The first port of the range used for passive data connections; 40000 by default.
passive_endint = 40100The last port of that range; 40100 by default.
tls_enabledbool = falseTurns on FTPS; it needs cert_file and key_file as well.
cert_filestr = ""The path of the certificate in PEM form.
key_filestr = ""The path of the private key in PEM form.
implicit_tlsbool = falseExpects TLS from the first byte of the connection, as implicit FTPS does.
require_tlsbool = falseRefuses login until the connection has been encrypted.
ftpd-Config.salam
import ftpd

func main:
    mut cfg := ftpd.NewConfig()
    println cfg.host, cfg.port, cfg.root
    println cfg.allow_anonymous, cfg.anonymous_user
    println cfg.user == "", cfg.password == ""
    println cfg.passive_start, cfg.passive_end
    println cfg.tls_enabled, cfg.implicit_tls, cfg.require_tls
    println cfg.cert_file == "", cfg.key_file == ""
    cfg.user = "reports"
    cfg.allow_anonymous = true
    println cfg.user, cfg.allow_anonymous
end
Output
0.0.0.0 21 .
false anonymous
true true
40000 40100
false false false
true true
reports true

Server

#
struct Server

A running FTP server.

NameTypeDescription
configConfigThe configuration the server was made with; after Listen its port is the real one.
listenertcp.ServerThe listening socket.
runningbool = falseTrue after Listen worked and until Close is called.
tls_cfgtls.ServerConfigThe TLS settings loaded from the certificate and key; empty when TLS is off.
ftpd-Server.salam
import ftpd

func main:
    mut cfg := ftpd.NewConfig()
    cfg.host = "127.0.0.1"
    cfg.port = 0
    cfg.root = "/tmp"
    mut srv := ftpd.New(cfg)
    println srv.running, srv.config.root
    println ftpd.Listen(srv), srv.running
    println ftpd.Port(srv) > 0, srv.config.port == ftpd.Port(srv)
    ftpd.Close(srv)
    println srv.running
end
Output
false /tmp
true true
true true
false

Functions

NewConfig

#
func NewConfig(): Config

A configuration with the defaults: port 21, the current directory as root, no login allowed yet.

The example for this item is shown with the ones above: ftpd-Config.salam

New

#
func New(cfg: Config): Server

Makes a server from a configuration and loads the certificate when TLS is on. It does not listen yet.

The example for this item is shown with the ones above: ftpd-Server.salam

Listen

#
func Listen(srv &: Server): bool

Opens the port; false when it could not be bound.

The example for this item is shown with the ones above: ftpd-Server.salam

Close

#
func Close(srv &: Server)

Stops the server and frees the port.

The example for this item is shown with the ones above: ftpd-Server.salam

Port

#
func Port(srv: Server): int

The port the server listens on; the real one after Listen when the configuration said 0.

The example for this item is shown with the ones above: ftpd-Server.salam

ServeOnce

#
func ServeOnce(srv &: Server): bool

Waits for one client, serves it until it quits, and returns true; false when the port is not open or the accept failed.

ftpd-Serve.salam
import ftpd

func main:
    mut cfg := ftpd.NewConfig()
    cfg.host = "127.0.0.1"
    cfg.port = 2121
    cfg.root = "/srv/ftp"
    cfg.allow_anonymous = true
    mut srv := ftpd.New(cfg)
    if not ftpd.Listen(srv):
        ret 1
    end
    handled := ftpd.ServeOnce(srv)
    println "one client served:", handled
    ftpd.Serve(srv)
    ftpd.Close(srv)
    ret 0
end

Serve

#
func Serve(srv &: Server)

Serves clients one after another until running becomes false or the listener fails.

The example for this item is shown with the ones above: ftpd-Serve.salam