Something went wrong. Try again.
FTP for Zig 0.16: a client, a server, and the wire protocol as a layer you can use on its own, all built on std.Io.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What `TYPE`, `STRU` and `MODE` select, and the one of them that still does//! anything: the ASCII representation type, which is a line-ending conversion.//!//! RFC 959 §3 describes a machine room where hosts disagreed about what a byte//! was. Almost all of it is dead. `STRU` has three values and everything uses//! `F`; `MODE` has three and everything uses `S`; `TYPE` has four and two of//! them are for machines with no ASCII. What survives is the distinction//! between `TYPE I`, which moves bytes, and `TYPE A`, which moves text and//! converts its line endings to CRLF in flight — and that distinction is real,//! because it is how a file written on one operating system is read on//! another.
const std = @import("std");const Io = std.Io;const ascii = std.ascii;
/// The representation type a transfer is in, selected by `TYPE`.pub const Type = union(enum) { /// `TYPE A`. Text, with CRLF line endings on the wire whatever the two /// hosts use locally. See `encodeAscii` and `decodeAscii`. ascii: FormatControl, /// `TYPE E`. Text in EBCDIC. No modern server implements it, and neither /// does this library beyond naming it so that a `TYPE E` can be refused /// with the 504 it deserves rather than a 500. ebcdic: FormatControl, /// `TYPE I`. Bytes, unaltered. What every binary transfer uses, and what /// almost every client selects for everything. image, /// `TYPE L n`. Bytes of `n` bits, for hosts whose byte is not 8 bits /// wide. `TYPE L 8` is the same thing as `TYPE I` and is the only width /// this library accepts. local: u8,
/// What the second parameter of `TYPE A` and `TYPE E` selects: how the /// file's vertical formatting is carried. Only `non_print` is in use. pub const FormatControl = enum { /// `N`. No formatting characters beyond the line endings themselves. /// The default when the parameter is omitted, and what everything /// sends. non_print, /// `T`. TELNET format effectors. telnet, /// `C`. ASA carriage control, where the first character of each line /// is a printer command. carriage_control, };
/// Whether a transfer in this type needs its line endings converted. pub fn isText(t: Type) bool { return switch (t) { .ascii, .ebcdic => true, .image, .local => false, }; }
pub const ParseError = error{ /// The argument is not a type this library knows about at all. InvalidType, /// The type is one RFC 959 defines but this library will not do: /// EBCDIC, or a local byte width that is not 8. Worth telling apart /// from `InvalidType` because the reply differs — 504 rather than 501. UnsupportedType, };
/// Reads a `TYPE` argument: a letter, and for `A`, `E` and `L` a second /// parameter after a space. pub fn parse(arg: []const u8) ParseError!Type { const text = std.mem.trim(u8, arg, " "); if (text.len == 0) return error.InvalidType; const parameter = std.mem.trim(u8, text[1..], " "); switch (ascii.toUpper(text[0])) { 'A', 'E' => { const control: FormatControl = if (parameter.len == 0) .non_print else blk: { if (parameter.len != 1) return error.InvalidType; break :blk switch (ascii.toUpper(parameter[0])) { 'N' => .non_print, 'T' => .telnet, 'C' => .carriage_control, else => return error.InvalidType, }; }; if (control != .non_print) return error.UnsupportedType; if (ascii.toUpper(text[0]) == 'E') return error.UnsupportedType; return .{ .ascii = control }; }, 'I' => { if (parameter.len != 0) return error.InvalidType; return .image; }, 'L' => { const width = std.fmt.parseInt(u8, parameter, 10) catch return error.InvalidType; if (width != 8) return error.UnsupportedType; return .{ .local = width }; }, else => return error.InvalidType, } }
pub fn format(t: Type, w: *Io.Writer) Io.Writer.Error!void { switch (t) { .ascii => |c| try w.print("A{s}", .{controlSuffix(c)}), .ebcdic => |c| try w.print("E{s}", .{controlSuffix(c)}), .image => try w.writeAll("I"), .local => |n| try w.print("L {d}", .{n}), } }
fn controlSuffix(c: FormatControl) []const u8 { // `N` is the default, so it is left off: a few old servers answer 501 // to the parameter they themselves assume. return switch (c) { .non_print => "", .telnet => " T", .carriage_control => " C", }; }};
/// What `STRU` selects. `file` is the only one anything uses, and the only one/// this library will accept.pub const Structure = enum { /// `STRU F`. A file is a stream of bytes with no structure of its own. file, /// `STRU R`. A file is a sequence of records. record, /// `STRU P`. A file is a sequence of numbered pages, for TENEX. page,
pub fn parse(arg: []const u8) error{InvalidStructure}!Structure { const text = std.mem.trim(u8, arg, " "); if (text.len != 1) return error.InvalidStructure; return switch (ascii.toUpper(text[0])) { 'F' => .file, 'R' => .record, 'P' => .page, else => error.InvalidStructure, }; }
pub fn letter(s: Structure) u8 { return switch (s) { .file => 'F', .record => 'R', .page => 'P', }; }};
/// What `MODE` selects. `stream` is the only one anything uses, and the only/// one this library will accept.pub const Mode = enum { /// `MODE S`. The data connection carries the bytes and its close marks /// the end of the file. stream, /// `MODE B`. The data is framed in blocks with descriptors, which is how /// a transfer was meant to be restartable without closing the connection. block, /// `MODE C`. Blocks, run-length compressed. compressed,
pub fn parse(arg: []const u8) error{InvalidMode}!Mode { const text = std.mem.trim(u8, arg, " "); if (text.len != 1) return error.InvalidMode; return switch (ascii.toUpper(text[0])) { 'S' => .stream, 'B' => .block, 'C' => .compressed, else => error.InvalidMode, }; }
pub fn letter(m: Mode) u8 { return switch (m) { .stream => 'S', .block => 'B', .compressed => 'C', }; }};
pub const AsciiError = error{ ReadFailed, WriteFailed };
/// An `Io.Writer` that forwards to another, converting local line endings to/// the CRLF the wire uses.////// A LF that already has a CR in front of it is left alone, so a file that was/// written on a CRLF host and is being sent from a LF host arrives intact/// rather than with its line endings doubled. That check spans writes, which/// is the whole reason this is a struct with a field in it rather than a/// function.////// This is the conversion for a host whose local line ending is LF, which is/// every host this library is likely to run on. A host that ends its lines/// some other way needs a conversion of its own; there is nothing in `TYPE A`/// that says what the local form is.pub const AsciiEncoder = struct { interface: Io.Writer, out: *Io.Writer, /// Whether the last byte passed on was a CR. previous_was_cr: bool, /// How many bytes have been written to `out`. written: u64,
pub fn init(out: *Io.Writer, buffer: []u8) AsciiEncoder { return .{ .interface = .{ .vtable = &vtable, .buffer = buffer }, .out = out, .previous_was_cr = false, .written = 0, }; }
const vtable: Io.Writer.VTable = .{ .drain = drain };
fn drain(io_w: *Io.Writer, data: []const []const u8, splat: usize) Io.Writer.Error!usize { const e: *AsciiEncoder = @alignCast(@fieldParentPtr("interface", io_w)); try e.emit(io_w.buffered()); var consumed: usize = 0; for (data[0 .. data.len - 1]) |bytes| { try e.emit(bytes); consumed += bytes.len; } const pattern = data[data.len - 1]; for (0..splat) |_| { try e.emit(pattern); consumed += pattern.len; } return io_w.consume(io_w.end + consumed); }
fn emit(e: *AsciiEncoder, bytes: []const u8) Io.Writer.Error!void { var rest = bytes; while (std.mem.findScalar(u8, rest, '\n')) |i| { try e.out.writeAll(rest[0..i]); const preceded_by_cr = if (i == 0) e.previous_was_cr else rest[i - 1] == '\r'; const eol = if (preceded_by_cr) "\n" else "\r\n"; try e.out.writeAll(eol); e.written += i + eol.len; e.previous_was_cr = false; rest = rest[i + 1 ..]; } if (rest.len == 0) return; try e.out.writeAll(rest); e.written += rest.len; e.previous_was_cr = rest[rest.len - 1] == '\r'; }};
/// An `Io.Reader` that reads from another, converting the wire's CRLF line/// endings to a local LF.////// A CR that is not part of a CRLF is passed through. RFC 959 §3.1.1.1 says/// such a byte must be followed by NUL and that the NUL is then stripped, but/// no sender has done that in decades, and dropping a CR that a binary file/// happened to contain does more damage than keeping one.pub const AsciiDecoder = struct { interface: Io.Reader, in: *Io.Reader, /// A CR at the end of what has been read so far cannot be classified until /// the next byte arrives, so it is held rather than passed on. held_cr: bool,
pub fn init(in: *Io.Reader, buffer: []u8) AsciiDecoder { return .{ .interface = .{ .vtable = &vtable, .buffer = buffer, .seek = 0, .end = 0 }, .in = in, .held_cr = false, }; }
const vtable: Io.Reader.VTable = .{ .stream = stream };
fn stream(io_r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize { const d: *AsciiDecoder = @alignCast(@fieldParentPtr("interface", io_r)); const chunk = d.in.peekGreedy(1) catch |err| switch (err) { error.EndOfStream => { // A CR that turned out to be the last byte of the stream is a // CR, not half of a line ending. if (d.held_cr) { d.held_cr = false; w.writeByte('\r') catch return error.WriteFailed; return 1; } return error.EndOfStream; }, error.ReadFailed => return error.ReadFailed, }; // Bounding the input bounds the output, because this conversion only // ever removes bytes. const source = limit.slice(chunk); if (source.len == 0) return 0;
var written: usize = 0; if (d.held_cr) { d.held_cr = false; // If the next byte is a LF the held CR was the first half of a // CRLF and is dropped; the LF itself is written by the scan below. if (source[0] != '\n') { w.writeByte('\r') catch return error.WriteFailed; written += 1; } } var i: usize = 0; while (i < source.len) { const cr = std.mem.findScalarPos(u8, source, i, '\r') orelse { w.writeAll(source[i..]) catch return error.WriteFailed; written += source.len - i; break; }; w.writeAll(source[i..cr]) catch return error.WriteFailed; written += cr - i; if (cr + 1 == source.len) { d.held_cr = true; break; } if (source[cr + 1] != '\n') { w.writeByte('\r') catch return error.WriteFailed; written += 1; } i = cr + 1; } d.in.toss(source.len); return written; }};
/// Copies `r` to `w`, converting local line endings to the CRLF the wire uses./// Returns the number of bytes written. See `AsciiEncoder`.pub fn encodeAscii(r: *Io.Reader, w: *Io.Writer) AsciiError!u64 { var buffer: [4096]u8 = undefined; var encoder: AsciiEncoder = .init(w, &buffer); _ = r.streamRemaining(&encoder.interface) catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.WriteFailed => return error.WriteFailed, }; encoder.interface.flush() catch return error.WriteFailed; return encoder.written;}
/// Copies `r` to `w`, converting the wire's CRLF line endings to a local LF./// Returns the number of bytes written. See `AsciiDecoder`.pub fn decodeAscii(r: *Io.Reader, w: *Io.Writer) AsciiError!u64 { var buffer: [64]u8 = undefined; var decoder: AsciiDecoder = .init(r, &buffer); return decoder.interface.streamRemaining(w) catch |err| switch (err) { error.ReadFailed => return error.ReadFailed, error.WriteFailed => return error.WriteFailed, };}
// -- tests ----------------------------------------------------------------
const testing = std.testing;
test "TYPE arguments" { try testing.expectEqual(Type{ .ascii = .non_print }, try Type.parse("A")); try testing.expectEqual(Type{ .ascii = .non_print }, try Type.parse("a")); try testing.expectEqual(Type{ .ascii = .non_print }, try Type.parse("A N")); try testing.expectEqual(@as(Type, .image), try Type.parse("I")); try testing.expectEqual(Type{ .local = 8 }, try Type.parse("L 8"));
try testing.expectError(error.UnsupportedType, Type.parse("A T")); try testing.expectError(error.UnsupportedType, Type.parse("E")); try testing.expectError(error.UnsupportedType, Type.parse("L 7")); try testing.expectError(error.InvalidType, Type.parse("")); try testing.expectError(error.InvalidType, Type.parse("X")); try testing.expectError(error.InvalidType, Type.parse("I 8")); try testing.expectError(error.InvalidType, Type.parse("L x"));}
test "TYPE formatting" { var buffer: [16]u8 = undefined; try testing.expectEqualStrings("A", try std.fmt.bufPrint(&buffer, "{f}", .{Type{ .ascii = .non_print }})); try testing.expectEqualStrings("I", try std.fmt.bufPrint(&buffer, "{f}", .{@as(Type, .image)})); try testing.expectEqualStrings("L 8", try std.fmt.bufPrint(&buffer, "{f}", .{Type{ .local = 8 }}));}
test "STRU and MODE arguments" { try testing.expectEqual(Structure.file, try Structure.parse("F")); try testing.expectEqual(Structure.page, try Structure.parse("p")); try testing.expectError(error.InvalidStructure, Structure.parse("Q")); try testing.expectEqual(Mode.stream, try Mode.parse("S")); try testing.expectError(error.InvalidMode, Mode.parse(""));}
fn expectAscii(comptime convert: anytype, input: []const u8, expected: []const u8) !void { // A one-byte reader buffer, so that every boundary case a chunked // conversion can meet is met: a CR at the end of a chunk, a LF at the // start of one, a CRLF split down the middle. for ([_]usize{ 1, 2, 3, 7, 64 }) |buffer_len| { var read_buffer: [64]u8 = undefined; var source: Io.Reader = .fixed(input); var limited = source.limited(.unlimited, read_buffer[0..buffer_len]);
var out: [256]u8 = undefined; var w: Io.Writer = .fixed(&out); const written = try convert(&limited.interface, &w); try testing.expectEqualStrings(expected, w.buffered()); try testing.expectEqual(expected.len, written); }}
test "ASCII encoding adds the CR the wire wants" { try expectAscii(encodeAscii, "one\ntwo\n", "one\r\ntwo\r\n"); try expectAscii(encodeAscii, "", ""); try expectAscii(encodeAscii, "no newline", "no newline"); try expectAscii(encodeAscii, "\n", "\r\n"); try expectAscii(encodeAscii, "\n\n\n", "\r\n\r\n\r\n");}
test "ASCII encoding does not double a CRLF that was already there" { try expectAscii(encodeAscii, "one\r\ntwo\r\n", "one\r\ntwo\r\n"); try expectAscii(encodeAscii, "mixed\r\nendings\n", "mixed\r\nendings\r\n");}
test "ASCII decoding takes the CR back off" { try expectAscii(decodeAscii, "one\r\ntwo\r\n", "one\ntwo\n"); try expectAscii(decodeAscii, "", ""); try expectAscii(decodeAscii, "\r\n", "\n");}
test "ASCII decoding keeps a CR that is not part of a line ending" { try expectAscii(decodeAscii, "a\rb", "a\rb"); try expectAscii(decodeAscii, "trailing\r", "trailing\r"); try expectAscii(decodeAscii, "\r\r\n", "\r\n"); try expectAscii(decodeAscii, "\r\r\r", "\r\r\r");}
test "ASCII conversion round trips text" { const text = "first\nsecond\n\nfourth\nno trailing newline"; var encoded: [256]u8 = undefined; var ew: Io.Writer = .fixed(&encoded); var source: Io.Reader = .fixed(text); _ = try encodeAscii(&source, &ew); try expectAscii(decodeAscii, ew.buffered(), text);}
test "the encoder joins line endings split across two writes" { var out_buffer: [64]u8 = undefined; var out: Io.Writer = .fixed(&out_buffer); var scratch: [8]u8 = undefined; var encoder: AsciiEncoder = .init(&out, &scratch);
// The CR and the LF arrive in separate calls, so only state carried // between them stops this becoming "a\r\r\nb". try encoder.interface.writeAll("a\r"); try encoder.interface.writeAll("\nb\n"); try encoder.interface.flush(); try testing.expectEqualStrings("a\r\nb\r\n", out.buffered()); try testing.expectEqual(@as(u64, 6), encoder.written);}
test "the encoder handles a splat" { var out_buffer: [64]u8 = undefined; var out: Io.Writer = .fixed(&out_buffer); var scratch: [4]u8 = undefined; var encoder: AsciiEncoder = .init(&out, &scratch); try encoder.interface.splatBytesAll("x\n", 3); try encoder.interface.flush(); try testing.expectEqualStrings("x\r\nx\r\nx\r\n", out.buffered());}
test "the decoder joins a CRLF split across two reads" { // A one-byte source buffer, so the CR and the LF can never be seen // together and only the held-over state gets this right. var source: Io.Reader = .fixed("a\r\nb\r"); var source_buffer: [1]u8 = undefined; var limited = source.limited(.unlimited, &source_buffer); var scratch: [1]u8 = undefined; var decoder: AsciiDecoder = .init(&limited.interface, &scratch);
var out_buffer: [64]u8 = undefined; var out: Io.Writer = .fixed(&out_buffer); _ = try decoder.interface.streamRemaining(&out); try testing.expectEqualStrings("a\nb\r", out.buffered());}
test "the decoder respects a limit" { var source: Io.Reader = .fixed("abcdef"); var scratch: [8]u8 = undefined; var decoder: AsciiDecoder = .init(&source, &scratch); var out_buffer: [64]u8 = undefined; var out: Io.Writer = .fixed(&out_buffer); const n = try decoder.interface.stream(&out, .limited(3)); try testing.expect(n <= 3); try testing.expectEqualStrings("abc"[0..n], out.buffered());}