# zig-tftp
A TFTP server and client library for Zig 0.17: RFC 1350, the option
extensions of RFCs 2347, 2348 and 2349, and netascii.
nixpkgs has no Zig 0.17 yet, so the devshell (`nix develop`) takes the 0.17.0
release from [zig-overlay](https://git.jcollie.dev/jeff/zig-overlay).
The API documentation is at , generated
from the doc comments in the source and published from `main`. To read it
locally, `zig build docs-serve` builds it and serves it on
(`-Ddocs-port=N` for another port). It has to be
served rather than opened as a file, since the viewer fetches its sources at
runtime.
## Where this lives
```console
git clone https://git.jcollie.dev/jeff/zig-tftp.git
```
It is mirrored on Tangled at .
It is also on the Radicle network, where the repository's identifier is
```
rad:z3pN8MGEbGShGc5JrxLFKirYDgUAG
```
and `rad clone rad:z3pN8MGEbGShGc5JrxLFKirYDgUAG` fetches it from any node
that seeds it, needing no account and no forge.
## Adding it to a project
```console
zig fetch --save=tftp git+https://git.jcollie.dev/jeff/zig-tftp.git
```
```zig
const tftp = b.dependency("tftp", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("tftp", tftp.module("tftp"));
```
## Using it
### A server
`tftp.Server` is generic over an application type that decides what each
request reads from or writes to, so the library never touches a file system
itself. The application is handed a `tftp.Request`, which holds the filename,
mode and options and the addresses at both ends, and answers a read with
something that has a `std.Io.Reader` and a write with something that has a
`std.Io.Writer`:
```zig
const App = struct {
pub const Read = struct {
interface: std.Io.Reader,
pub fn reader(self: *Read, _: std.Io, _: std.mem.Allocator) !*std.Io.Reader {
return &self.interface;
}
// Optional: reported to a client that asks with the `tsize` option.
pub fn size(self: *Read, _: std.Io) ?u64 {
return self.interface.buffer.len;
}
pub fn deinit(_: *Read, _: std.Io, _: std.mem.Allocator) void {}
};
pub fn readFrom(_: *const App, _: std.Io, _: std.mem.Allocator, request: tftp.Request) !Read {
// Who is asking, and on which address, for access control or a log.
std.log.info("{f} asked {f} for {s}", .{ request.remote, request.local, request.filename });
if (request.remote != .ip4) return error.PermissionDenied;
if (!std.mem.eql(u8, request.filename, "hello.txt")) return error.FileNotFound;
return .{ .interface = .fixed("Hello, world!\n") };
}
// With no `writeTo`, the server is read-only and refuses every write
// request with an access violation. `writeTo` and its `Write` type work
// the same way as reading; see `src/main.zig`.
};
var app: App = .{};
var server: tftp.Server(App) = .init(&app, try .parseLiteral("0.0.0.0:69"));
try server.run(io, gpa);
```
An error from the application ends the transfer, and the client is told why
with the closest TFTP error code: `error.FileNotFound` is "File not found",
`error.PermissionDenied` is "Access violation", `error.NoSpaceLeft` is "Disk
full", and so on. The API documentation for `Server` has the whole list, and
the optional `reserve` method a write may have to refuse a file by its size.
### A client
`tftp.Client` downloads with `get` and uploads with `put`, into any
`std.Io.Writer` and from any `std.Io.Reader`:
```zig
const client: tftp.Client = .init(try .parseLiteral("192.0.2.1:69"));
var file: std.Io.Writer.Allocating = .init(gpa);
defer file.deinit();
var diagnostics: tftp.Client.Diagnostics = .{};
const result = client.get(io, "pxelinux.0", &file.writer, .{
.blocksize = 1428,
.size = true,
.diagnostics = &diagnostics,
}) catch |err| {
// The server refused, or ended the transfer, and said why.
if (err == error.ErrorReceived)
std.log.err("{t}: {s}", .{ diagnostics.code, diagnostics.message() });
return err;
};
std.log.info("{d} bytes, block size {?d}", .{ result.bytes, result.options.blocksize });
```
Options are asked for, not assumed: `result.options` holds what the server
acknowledged, which may be a smaller block size than was asked for, or
nothing at all from a server that predates RFC 2347.
### Trying it
`zig-tftp`, the executable this builds, is both ends of the library from the
command line:
```console
zig-tftp [serve [ADDRESS]]
zig-tftp get SERVER REMOTE [LOCAL] [--mode octet|netascii] [--blksize N] [--timeout N] [--tsize]
zig-tftp put SERVER LOCAL [REMOTE] [--mode octet|netascii] [--blksize N] [--timeout N] [--tsize]
```
With no arguments, or `serve`, it runs a demonstration server on
`127.0.0.1` port 6969, which answers every read with the text of RFC 1350
and accepts writes into memory, refusing any file whose name begins with
`bad`. `get` and `put` talk to any TFTP server; SERVER's port defaults to 69,
LOCAL defaults to the last component of REMOTE, and `-` is standard output
or standard input.
```console
$ nix develop -c zig build run &
$ ./zig-out/bin/zig-tftp get 127.0.0.1:6969 rfc1350.txt --blksize 1428 --tsize
received rfc1350.txt: 24599 bytes, block size 1428, size 24599
$ ./zig-out/bin/zig-tftp get 127.0.0.1:6969 bad.txt
server: access_violation: Access violation
```
The tftp-hpa client and server are in the development shell as well, to
try either end against the reference implementation.
## Features
* Read and write requests in `octet`, `netascii` and `mail` modes (RFC 1350).
Netascii is translated to and from the host's line endings in both
directions, so the application only ever sees local text.
* Option negotiation (RFC 2347) with `blksize` (RFC 2348), `timeout` and
`tsize` (RFC 2349). A negotiated `timeout` is the retransmission interval;
otherwise the interval starts at 250 ms and doubles, and a transfer is
abandoned after six retransmissions without progress.
* Each transfer runs concurrently, on a port of its own. A packet from any
other port is answered with "Unknown transfer ID" and does not disturb the
transfer.
* A server listening on every address (`0.0.0.0` or `::`) knows which one
each request was sent to, from `IP_PKTINFO` and `IPV6_RECVPKTINFO`
(RFC 3542), on Linux and Apple's platforms. The application is told it in
`tftp.Request`, and the transfer answers from that address, so a client on
a host with several addresses hears back from the one it asked. Elsewhere
the request reports the address the server is bound to.
* Files of any length: block numbers wrap from 65535 to zero.
* Robust against loss and duplication. A duplicate ACK is ignored rather than
answered, which avoids the Sorcerer's Apprentice bug (RFC 1123, section
4.2.3.1); a repeated DATA block is acknowledged again but not written again;
and after the final ACK of a write the server waits to answer the last block
again, in case that ACK was lost.
* Every failure is reported to the client with an ERROR packet, including
malformed packets and netascii that breaks the rules of RFC 854.
* A client, `tftp.Client`, with the same option negotiation, netascii
translation and handling of loss and duplication, since both ends run the
same transfer loops. It checks an OACK against what it asked for and ends
the transfer with error 8, as RFC 2347 requires, if the server raised the
block size, changed the timeout, or acknowledged something not asked for.
* The netascii codecs and the packet encoder and decoder are public, as
`tftp.netascii` and `tftp.Packet`, for use on their own.
### Not yet
* The `windowsize` option (RFC 7440).
## Testing
```console
zig build test
```
runs the unit tests, the tests that drive the server and the client against
each other and against scripted peers over the loopback interface, a test of
the client against tftp-hpa's `in.tftpd` when it is on the `PATH` (it is in
the development shell), and the fuzz targets' seeds. The Forgejo workflow runs
those, checks formatting and REUSE compliance, and fuzzes every target for
fifteen seconds on each push.
### Fuzzing
`tests/fuzz.zig` holds five fuzz targets, each stated as a property rather
than an example:
* `packets`: any datagram either fails to decode or survives being encoded
and decoded again unchanged.
* `options`: decoded options are always within the ranges their RFCs allow,
and survive a round trip.
* `netascii`: the four netascii codecs agree with each other however their
input is chunked and however small their buffers are, and encoding and
decoding is lossless where the local line ending is LF.
* `session`: a whole transfer, driven over the loopback interface by a fuzzed
request and a fuzzed script of client packets. The server must not crash,
leak or hang, everything it sends must be a well formed packet, and in
octet mode it must send and write exactly the right bytes.
* `client`: the mirror of `session`, a `get` or `put` against a server made
of a fuzzed script, including option acknowledgments it did not ask for,
blocks out of sequence and packets from other ports. The client must not
crash, leak or hang, must send only well formed packets, and when it
reports success must be telling the truth about how much it moved.
Zig's own fuzzer runs them, guided by coverage. It takes over the terminal
with a web interface until it is interrupted, or stops after a given number of
runs and reports; `-Dfuzz-filter` narrows it to the targets whose name
contains a string:
```console
zig build fuzz --fuzz # until interrupted
zig build fuzz --fuzz=1M # a bounded run
zig build fuzz --fuzz -Dfuzz-filter=netascii
```
A bounded run reports once per test binary, under the name of its first
target, but every target in it was fuzzed. A finding prints `input saved to`
above the report.
`zig build fuzz-run` drives the same targets with a mutation loop of its own
(`tools/fuzz.zig`), with no coverage feedback, but with a leak check after
every input, a watchdog for hangs and a seed that repeats a run exactly. It
is what the workflow runs:
```console
zig build fuzz-run # a minute of each target
zig build fuzz-run -- --seconds 300 --target netascii
zig build fuzz-run -- --seed 12345 # the same run again
```
A failure, panic or hang is written to `fuzz-findings/`, with the command that
runs that input again. `-Dfuzz-optimize=debug` builds the loop with stack
traces that can be read.
## License
MIT. The project follows the [REUSE](https://reuse.software/) specification,
so every file says what its license is.
## References cited
The standards this library implements, the chain of documents that define
`netascii` mode, and the implementation it is checked against. All of them are
in the `zig-tftp` collection in Zotero, with the full text of every RFC and of
IEN 133 attached.
### The TFTP protocol
* K. R. Sollins, *The TFTP Protocol*, [IEN 133](https://www.rfc-editor.org/ien/ien133.txt),
January 1980. The original specification. Obsoleted by RFC 783.
* K. R. Sollins, *TFTP Protocol (revision 2)*, [RFC 783](https://www.rfc-editor.org/info/rfc783),
June 1981. Obsoleted by RFC 1350. Defines the `mail` transfer mode that
RFC 1350 later declares obsolete.
* K. R. Sollins, *The TFTP Protocol (Revision 2)*, [RFC 1350](https://www.rfc-editor.org/info/rfc1350),
July 1992. **STD 33**, the current specification, and the source of the
opcodes, the packet layouts, error codes 0 to 7, and the rule that a packet
from an unknown port is answered with error 5 and otherwise ignored.
* R. Braden, ed., *Requirements for Internet Hosts - Application and Support*,
[RFC 1123](https://www.rfc-editor.org/info/rfc1123), October 1989. **STD 3**.
Section 4.2 corrects TFTP; 4.2.3.1 is the Sorcerer's Apprentice bug, and why
a duplicate ACK must never be answered with a retransmission.
### TFTP option extensions
* G. Malkin and A. Harkin, *TFTP Option Extension*, [RFC 2347](https://www.rfc-editor.org/info/rfc2347),
May 1998. Defines the OACK packet and error code 8. Obsoletes RFC 1782.
* G. Malkin and A. Harkin, *TFTP Blocksize Option*, [RFC 2348](https://www.rfc-editor.org/info/rfc2348),
May 1998. The `blksize` option, valid from 8 to 65464. Obsoletes RFC 1783.
* G. Malkin and A. Harkin, *TFTP Timeout Interval and Transfer Size Options*,
[RFC 2349](https://www.rfc-editor.org/info/rfc2349), May 1998. The `timeout`
and `tsize` options. Obsoletes RFC 1784.
* G. Malkin and A. Harkin, *TFTP Option Extension*, [RFC 1782](https://www.rfc-editor.org/info/rfc1782),
March 1995. Obsoleted by RFC 2347.
* G. Malkin and A. Harkin, *TFTP Blocksize Option*, [RFC 1783](https://www.rfc-editor.org/info/rfc1783),
March 1995. Obsoleted by RFC 2348.
* G. Malkin and A. Harkin, *TFTP Timeout Interval and Transfer Size Options*,
[RFC 1784](https://www.rfc-editor.org/info/rfc1784), March 1995. Obsoleted by
RFC 2349.
* G. Malkin and A. Harkin, *TFTP Option Negotiation Analysis*, [RFC 1785](https://www.rfc-editor.org/info/rfc1785),
March 1995. Informational.
* P. Masotta, *TFTP Windowsize Option*, [RFC 7440](https://www.rfc-editor.org/info/rfc7440),
January 2015. Not implemented yet.
### Sockets
* W. Stevens, M. Thomas, E. Nordmark and T. Jinmei, *Advanced Sockets
Application Program Interface (API) for IPv6*, [RFC 3542](https://www.rfc-editor.org/info/rfc3542),
June 2003. Informational. Defines `IPV6_RECVPKTINFO` and the control message
that reports the address an IPv6 datagram was sent to, which
`src/lib/pktinfo.zig` reads; `IP_PKTINFO` is its IPv4 counterpart.
### netascii
RFC 1350 does not define `netascii` itself. It defers to ASCII "with the
modifications specified in the Telnet Protocol Specification", so the codecs
in `src/lib/netascii.zig` are governed by these documents rather than by the
TFTP RFCs.
* J. Postel and J. Reynolds, *Telnet Protocol Specification*, [RFC 854](https://www.rfc-editor.org/info/rfc854),
May 1983. **STD 8**, the current definition of the Network Virtual
Terminal, and the rule the codecs enforce: "The sequence 'CR LF' must be
treated as a single 'new line' character", "the sequence 'CR NUL' must be
used where a carriage return alone is actually desired", and "the CR
character must be avoided in other contexts". Obsoletes RFC 764.
* J. Postel, *Telnet Protocol specification*, [RFC 764](https://www.rfc-editor.org/info/rfc764),
June 1980. The revision RFC 783 cites. Obsoleted by RFC 854.
* United States of America Standards Institute, *USA Standard Code for
Information Interchange*, X3.4-1968. Reference [1] of RFC 1350, for the
underlying character set. TFTP's `netascii` is 8 bit all the same, not 7.
### Reference implementation
* H. P. Anvin, [tftp-hpa](https://git.kernel.org/pub/scm/network/tftp/tftp-hpa.git).
The de facto reference implementation, and the one in the development
shell. Its `netascii` conversions are `read_ahead()` (encode) and
`write_behind()` (decode) in `common/tftpsubs.c`.
tftp-hpa has no per platform conversions. It opens files with `O_TEXT`, lets
the C runtime translate line endings, and then always applies those two LF
based conversions. This library does both steps at once for each line
ending convention, and its tests check every convention against that
composition over an exhaustive corpus of short inputs.
The one deliberate difference is on input: an unescaped CR, which RFC 854
forbids, is rejected here. tftp-hpa passes it through, noting that "spec is
undefined if we get CR as last byte of file or a CR followed by anything
else. In this case we leave it alone."