Standard library · Network

ftp

An FTP and FTPS client: listing a directory, uploading and downloading files.

import ftp

This package connects to FTP servers, for uploading a site to shared hosting or pulling files off old equipment and suppliers' servers. Plain FTP sends the password and the data unencrypted; wherever the server supports it, use DialTLS, which encrypts both the commands and the data with AUTH TLS. When the server also speaks SSH, SFTP through ssh is the better choice: one encrypted connection, no separate data channel.

Transfers go in passive mode (EPSV, or PASV when the server lacks it), which works from behind a firewall; active mode (PORT) is not offered. The parsing functions, such as ParseListLine, are available for writing tools of your own too.

Things to know:

  • Call Binary before transfers, or a server in ASCII mode may change line endings inside images and archives.
  • Upload and Download hold the whole file in memory, and an interrupted transfer starts again from the beginning; there is no resume. Fine for site files and reports, not for multi-gigabyte backups.
  • Read, Write and Append carry a str, so they are for text: binary content stops at the first zero byte. Use Upload and Download for anything else.
  • Servers that require TLS session reuse on the data connection refuse every transfer; see the last section.

Publish a site to shared hosting

The usual job: connect with DialTLS, refuse to go on unless both the commands and the data are encrypted, log in, and upload a build directory with UploadDir. Switch to binary mode with Binary before any transfer, or some servers will change the line endings inside images and archives. Keeping the old index.html under another name with Rename gives you something to go back to.

ftp-publish-site.salam
import ftp

func main:
    mut c := ftp.DialTLS("ftp.example-host.com", 21)
    if not ftp.Ok(c):
        println "cannot connect:", ftp.LastReply(c)
        ret 1
    end
    if not ftp.Secure(c) or not ftp.SecureData(c):
        println "the server would not encrypt the session, stopping"
        ftp.Close(c)
        ret 1
    end
    if not ftp.Login(c, "site-user", "app-password"):
        println "login failed:", ftp.LastCode(c), ftp.LastReply(c)
        ftp.Close(c)
        ret 1
    end
    _ := ftp.Binary(c)
    _ := ftp.MkdirAll(c, "/public_html")
    if ftp.Exists(c, "/public_html/index.html"):
        _ := ftp.Rename(c, "/public_html/index.html", "/public_html/index.old.html")
    end
    if not ftp.UploadDir(c, "dist", "/public_html"):
        println "upload failed:", ftp.LastReply(c)
        ret 1
    end
    println "uploaded, index.html is", ftp.Size(c, "/public_html/index.html"), "bytes"
    ftp.Quit(c)
    ftp.Close(c)
    ret 0
end

This needs a real server, so it is only checked here. Every function that talks to the server leaves the reply in LastCode and LastReply, so after a false you can always print what the server said.

Fetch only the new files

List returns one FileInfo per entry with the name, the size and whether it is a directory or a link. Comparing that with what is already on disk turns a full download into a cheap sync, which suits a nightly job that collects reports from a supplier.

ftp-sync-down.salam
import ftp
import os

func main:
    mut c := ftp.DialTLS("files.example.com", 21)
    if not ftp.Ok(c) or not ftp.Login(c, "reports", "app-password"):
        println "cannot log in:", ftp.LastReply(c)
        ret 1
    end
    _ := ftp.Binary(c)
    _ := os.MkdirAll("reports")
    mut fetched := 0
    mut skipped := 0
    each f in ftp.List(c, "/daily"):
        if f.is_dir or f.is_link:
            continue
        end
        local := "reports/" + f.name
        if os.Exists(local):
            skipped++
            continue
        end
        if ftp.Download(c, "/daily/" + f.name, local):
            fetched++
        else:
            println "failed:", f.name, ftp.LastReply(c)
        end
    end
    println "fetched", fetched, "new files, skipped", skipped
    ftp.Quit(c)
    ftp.Close(c)
    ret 0
end

For a stricter check than "the file exists", compare f.size with the local size, or ModTime with the time you stored after the last run.

Read a directory listing yourself

FTP has no fixed format for listings; most servers send the same columns as ls -l. ParseListLine reads such a line into a FileInfo, which is useful when you get listings from somewhere else, such as a log or a ListRaw call, and want to work with them without a connection.

ftp-listing-report.salam
import ftp
import str

func main:
    raw := "drwxr-xr-x    2 ftp ftp     4096 Jan 01  2026 old\n-rw-r--r--    1 ftp ftp   120034 Oct 02 08:10 sales-2026-10-01.csv\n-rw-r--r--    1 ftp ftp   118702 Oct 03 08:10 sales-2026-10-02.csv\n-rw-r--r--    1 ftp ftp  2251800 Oct 03 08:12 photos.zip\nlrwxrwxrwx    1 ftp ftp       20 Oct 03 08:12 latest.csv -> sales-2026-10-02.csv"

    mut total := 0 as i64
    mut files := 0
    mut biggest := ftp.FileInfo {}
    each line in str.Split(raw, "\n"):
        f := ftp.ParseListLine(line)
        if f.is_dir:
            println "dir ", f.name
            continue
        end
        if f.is_link:
            println "link", f.name
            continue
        end
        println "file", f.name, f.size, f.raw_date
        files++
        total += f.size
        if f.size > biggest.size:
            biggest = f
        end
    end
    println files, "files,", total, "bytes; biggest:", biggest.name
end
Outputdir old file sales-2026-10-01.csv 120034 Oct 02 08:10 file sales-2026-10-02.csv 118702 Oct 03 08:10 file photos.zip 2251800 Oct 03 08:12 link latest.csv 3 files, 2490536 bytes; biggest: photos.zip

Servers that require TLS session reuse

Some FTPS servers insist that the data connection resumes the TLS session of the command connection. vsftpd does this with its default require_ssl_reuse=YES, and so do FileZilla Server and the Rebex test server. This package does not resume sessions yet, so on those servers logging in works but every listing and transfer is refused with reply 425:

ftp-public-demo.salam
import ftp

func main:
    mut c := ftp.DialTLS("test.rebex.net", 21)
    if not ftp.Ok(c) or not ftp.Login(c, "demo", "password"):
        println "cannot log in:", ftp.LastCode(c), ftp.LastReply(c)
        ret 1
    end
    println "encrypted:", ftp.Secure(c), ftp.SecureData(c)
    println "system:", ftp.System(c)
    entries := ftp.List(c, "/")
    if entries.Len() == 0 and ftp.LastCode(c) >= 400:
        println "listing refused:", ftp.LastReply(c)
    end
    each f in entries:
        println f.name, f.is_dir
    end
    ftp.Quit(c)
    ftp.Close(c)
    ret 0
end

Run against test.rebex.net, it printed:

encrypted: true true
system: 215 UNIX Type: L8
listing refused: 425 Cannot secure data connection - TLS session resumption required.

If you run the server, set require_ssl_reuse=NO in vsftpd. If you do not, and the server offers SFTP, use ssh instead; fall back to plain Dial only on a network you trust, since it sends the password in the clear.

Which function for which job

JobUse
Connect securelyDialTLS, or DialTLSWith for a private CA; Dial then AuthTLS does the same in two steps
Check that encryption is onSecure for the commands, SecureData for the files
Small text filesRead, Write, Append
Files on diskUpload, Download, UploadDir, DownloadDir
Look before you actExists, IsDir, Size, ModTime, List
A command with no function of its ownCommand, which returns the reply code

Types

FileInfo

struct FileInfo
The information about one file from the server listing.
NameTypeDescription
namestr = ""The name.
sizei64 = 0The size.
is_dirbool = falseIt is a directory.
is_linkbool = falseIt is a link.
modestr = ""The permissions, such as rw-r--r--.
raw_datestr = ""The date exactly as the server wrote it.
ftp-Parse.salam
import ftp

func main:
    println ftp.ReplyCode("230 Login successful."), ftp.ReplyCode("broken")
    println ftp.IsFinalLine("211-Features:"), ftp.IsFinalLine("211 End")
    println ftp.ParsePasv("227 Entering Passive Mode (192,168,1,10,19,137)")
    println ftp.ParseEpsv("229 Entering Extended Passive Mode (|||50000|)")
    file := ftp.ParseListLine("-rw-r--r--    1 ftp      ftp          1024 Sep 30 12:00 notes.txt")
    println file.name, file.size, file.is_dir, file.is_link, file.mode, file.raw_date
    folder := ftp.ParseListLine("drwxr-xr-x    2 ftp      ftp          4096 Jan 01  2026 backup")
    println folder.name, folder.is_dir
    link := ftp.ParseListLine("lrwxrwxrwx    1 ftp      ftp             7 Mar 03 09:15 current -> backup")
    println link.name, link.is_link
end
Output230 0 false true 192.168.1.10:5001 50000 notes.txt 1024 false false rw-r--r-- Sep 30 12:00 backup true current true

Client

struct Client
One FTP connection.
NameTypeDescription
conntcp.ConnThe TCP connection of the commands.
okbool = falseThe connection is healthy.
hoststr = ""The host.
portint = 21The port.
rxbufstr = ""The data that was read.
last_replystr = ""The last reply of the server.
last_codeint = 0The code of the last reply.
securebool = falseThe command channel is encrypted.
tls_idxint = -1The index of the TLS connection.
prot_pbool = falseThe data channel is encrypted too.
tls_cfgtls.ConfigThe TLS configuration.
ftp-Client.salam
import ftp
import tls

func main:
    mut c := ftp.DialTLS("ftp.example.com", 21)
    if not ftp.Ok(c) or not ftp.Login(c, "ali", "s3cret"):
        println ftp.LastCode(c), ftp.LastReply(c)
        ret
    end
    println ftp.Secure(c), ftp.SecureData(c)
    println ftp.System(c)
    println ftp.Features(c)
    _ := ftp.Binary(c)
    println ftp.Pwd(c)
    _ := ftp.MkdirAll(c, "/site/assets")
    _ := ftp.Cwd(c, "/site")
    _ := ftp.Write(c, "index.html", "<h1>hello</h1>")
    _ := ftp.Append(c, "log.txt", "one more line\n")
    println ftp.Read(c, "index.html")
    println ftp.Upload(c, "logo.png", "assets/logo.png")
    println ftp.Download(c, "log.txt", "log-copy.txt")
    each entry in ftp.List(c, "."):
        println entry.name, entry.size, entry.is_dir
    end
    each name in ftp.NameList(c, "assets"):
        println name
    end
    println ftp.ListRaw(c, ".").Len() > 0
    println ftp.Size(c, "index.html"), ftp.ModTime(c, "index.html")
    println ftp.IsDir(c, "assets"), ftp.IsLink(c, "current"), ftp.Exists(c, "old.html")
    _ := ftp.Rename(c, "log.txt", "log-1.txt")
    _ := ftp.Move(c, "log-1.txt", "archive/log-1.txt")
    _ := ftp.Delete(c, "archive/log-1.txt")
    _ := ftp.CdUp(c)
    _ := ftp.Mkdir(c, "tmp")
    _ := ftp.Rmdir(c, "tmp")
    _ := ftp.RemoveAll(c, "/site/old")
    _ := ftp.UploadDir(c, "public", "/site")
    _ := ftp.DownloadDir(c, "/site", "backup")
    println ftp.Command(c, "SITE CHMOD 644 index.html")
    println ftp.Noop(c)
    _ := ftp.Ascii(c)
    ftp.Quit(c)
    ftp.Close(c)

    mut plain := ftp.Dial("ftp.example.com", 21)
    println ftp.AuthTLS(plain)
    mut cfg := tls.NewConfig("ftp.example.com")
    cfg.ca_file = "company-ca.pem"
    mut configured := ftp.DialTLSWith("ftp.example.com", 21, cfg)
    mut upgraded := ftp.Dial("ftp.example.com", 21)
    println ftp.AuthTLSWith(upgraded, cfg)
    ftp.Close(plain)
    ftp.Close(configured)
    ftp.Close(upgraded)
end

Functions

Dial

func Dial(host: str, port: int): Client
Connects to an FTP server; not logged in yet.

The example for this item is shown with the ones above: ftp-Client.salam

AuthTLSWith

func AuthTLSWith(c &: Client, cfg: tls.Config): bool
Secures the connection with AUTH TLS and the given configuration.

The example for this item is shown with the ones above: ftp-Client.salam

AuthTLS

func AuthTLS(c &: Client): bool
Secures the connection with AUTH TLS.

The example for this item is shown with the ones above: ftp-Client.salam

DialTLS

func DialTLS(host: str, port: int): Client
Connects and secures it at once with AUTH TLS; explicit FTPS.

The example for this item is shown with the ones above: ftp-Client.salam

DialTLSWith

func DialTLSWith(host: str, port: int, cfg: tls.Config): Client
The same, with a TLS configuration.

The example for this item is shown with the ones above: ftp-Client.salam

Secure

func Secure(c: Client): bool
The command channel is encrypted.

The example for this item is shown with the ones above: ftp-Client.salam

SecureData

func SecureData(c: Client): bool
The data channel is encrypted too.

The example for this item is shown with the ones above: ftp-Client.salam

Login

func Login(c &: Client, user: str, password: str): bool
Logs in.

The example for this item is shown with the ones above: ftp-Client.salam

Quit

func Quit(c &: Client)
Logs out with QUIT.

The example for this item is shown with the ones above: ftp-Client.salam

Close

func Close(c &: Client)
Closes the connection.

The example for this item is shown with the ones above: ftp-Client.salam

Ok

func Ok(c: Client): bool
The connection is healthy.

The example for this item is shown with the ones above: ftp-Client.salam

LastReply

func LastReply(c: Client): str
The text of the last reply.

The example for this item is shown with the ones above: ftp-Client.salam

LastCode

func LastCode(c: Client): int
The code of the last reply, such as 230.

The example for this item is shown with the ones above: ftp-Client.salam

Command

func Command(c &: Client, line: str): int
Sends a raw command and returns the reply code.

The example for this item is shown with the ones above: ftp-Client.salam

Noop

func Noop(c &: Client): bool
The NOOP command, for keeping the connection alive.

The example for this item is shown with the ones above: ftp-Client.salam

System

func System(c &: Client): str
The system type of the server.

The example for this item is shown with the ones above: ftp-Client.salam

Features

func Features(c &: Client): str
The features the server announces with FEAT.

The example for this item is shown with the ones above: ftp-Client.salam

Binary

func Binary(c &: Client): bool
Binary transfer mode; for everything but plain text.

The example for this item is shown with the ones above: ftp-Client.salam

Ascii

func Ascii(c &: Client): bool
Text transfer mode.

The example for this item is shown with the ones above: ftp-Client.salam

Pwd

func Pwd(c &: Client): str
The current directory.

The example for this item is shown with the ones above: ftp-Client.salam

Cwd

func Cwd(c &: Client, path: str): bool
Changes directory.

The example for this item is shown with the ones above: ftp-Client.salam

CdUp

func CdUp(c &: Client): bool
Goes to the directory above.

The example for this item is shown with the ones above: ftp-Client.salam

Mkdir

func Mkdir(c &: Client, path: str): bool
Makes a directory.

The example for this item is shown with the ones above: ftp-Client.salam

Rmdir

func Rmdir(c &: Client, path: str): bool
Deletes an empty directory.

The example for this item is shown with the ones above: ftp-Client.salam

MkdirAll

func MkdirAll(c &: Client, path: str): bool
Makes the directory and the ones above it.

The example for this item is shown with the ones above: ftp-Client.salam

ListRaw

func ListRaw(c &: Client, path: str): str
The directory listing exactly as the server sends it.

The example for this item is shown with the ones above: ftp-Client.salam

List

func List(c &: Client, path: str): Vector<FileInfo>
The directory listing, parsed.

The example for this item is shown with the ones above: ftp-Parse.salam

NameList

func NameList(c &: Client, path: str): Vector<str>
The names in the directory only.

The example for this item is shown with the ones above: ftp-Client.salam

Size

func Size(c &: Client, path: str): i64
The size of a file; -1 when it could not be had.

The example for this item is shown with the ones above: ftp-Client.salam

ModTime

func ModTime(c &: Client, path: str): str
The modification time in YYYYMMDDHHMMSS form.

The example for this item is shown with the ones above: ftp-Client.salam

IsDir

func IsDir(c &: Client, path: str): bool
It is a directory.

The example for this item is shown with the ones above: ftp-Client.salam

func IsLink(c &: Client, path: str): bool
It is a link.

The example for this item is shown with the ones above: ftp-Client.salam

Exists

func Exists(c &: Client, path: str): bool
The file or directory is there.

The example for this item is shown with the ones above: ftp-Client.salam

Read

func Read(c &: Client, remote: str): str
Reads a remote file as text; binary content stops at the first zero byte, so use Download for it.

The example for this item is shown with the ones above: ftp-Client.salam

Write

func Write(c &: Client, remote: str, data: str): bool
Writes text to a file on the server.

The example for this item is shown with the ones above: ftp-Client.salam

Append

func Append(c &: Client, remote: str, data: str): bool
Adds text to the end of a file.

The example for this item is shown with the ones above: ftp-Client.salam

Download

func Download(c &: Client, remote: str, local: str): bool
Downloads a remote file into a local file, byte for byte; the whole file is held in memory first.

The example for this item is shown with the ones above: ftp-Client.salam

Upload

func Upload(c &: Client, local: str, remote: str): bool
Sends a local file, byte for byte; it is read into memory in full before the transfer.

The example for this item is shown with the ones above: ftp-Client.salam

Delete

func Delete(c &: Client, path: str): bool
Deletes a file.

The example for this item is shown with the ones above: ftp-Client.salam

Rename

func Rename(c &: Client, from_path: str, to_path: str): bool
Renames it.

The example for this item is shown with the ones above: ftp-Client.salam

Move

func Move(c &: Client, from_path: str, to_path: str): bool
Moves it; the target directory is made when it is not there.

The example for this item is shown with the ones above: ftp-Client.salam

RemoveAll

func RemoveAll(c &: Client, path: str): bool
Deletes the directory and everything in it.

The example for this item is shown with the ones above: ftp-Client.salam

DownloadDir

func DownloadDir(c &: Client, remote: str, local: str): bool
Downloads a directory with everything in it.

The example for this item is shown with the ones above: ftp-Client.salam

UploadDir

func UploadDir(c &: Client, local: str, remote: str): bool
Sends a local directory with everything in it.

The example for this item is shown with the ones above: ftp-Client.salam

ReplyCode

func ReplyCode(line: str): int
The three digit code of a reply line; zero when there is none.

The example for this item is shown with the ones above: ftp-Parse.salam

IsFinalLine

func IsFinalLine(line: str): bool
It is the closing line of a multi line reply; the closing line has a space after the code, not a dash.

The example for this item is shown with the ones above: ftp-Parse.salam

ParsePasv

func ParsePasv(reply: str): str
Pulls the data address and port out of a PASV reply.

The example for this item is shown with the ones above: ftp-Parse.salam

ParseEpsv

func ParseEpsv(reply: str): int
Pulls the data port out of an EPSV reply.

The example for this item is shown with the ones above: ftp-Parse.salam

ParseListLine

func ParseListLine(line: str): FileInfo
Parses one Unix style listing line.

The example for this item is shown with the ones above: ftp-Parse.salam