std.crypto.tls.Client Hangs

Hi all,

I might be misunderstanding the reader/writer interfaces, but I’m not entirely sure what I’m doing wrong when trying to connect using tls.Client. Could someone take a look and point me in the right direction?

This is my code:

const std = @import("std");
const Io = std.Io;
const tls = std.crypto.tls;

const tls_client_17 = @import("tls_client_17");

pub fn main(init: std.process.Init) !void {
    const al: std.mem.Allocator = init.arena.allocator();
    var threaded = Io.Threaded.init(al, .{ .concurrent_limit = .limited(20) });
    const io = threaded.io();

    const host = try Io.net.HostName.init("example.com");
    var stream = try Io.net.HostName.connect(host, io, 443, .{ .mode = .stream, .protocol = .tcp });
    defer stream.close(io);

    var read_buf: [std.crypto.tls.max_ciphertext_record_len]u8 = @splat(0);
    var write_buf: [std.crypto.tls.max_ciphertext_record_len]u8 = @splat(0);
    var reader = stream.reader(io, &read_buf);
    var writer = stream.writer(io, &write_buf);

    const realtime_now = std.Io.Clock.real.now(io);
    var bundle: std.crypto.Certificate.Bundle = .empty;
    try bundle.rescan(al, io, realtime_now);
    defer bundle.deinit(al);

    var prng = std.Random.DefaultPrng.init(0);
    const rand = prng.random();
    var entropy_bytes = rand.array(u8, 240);

    var lock: std.Io.RwLock = .init;
    var client = try std.crypto.tls.Client.init(
        &reader.interface,
        &writer.interface,
        .{
            .host = .{
                .explicit = host.bytes,
            },
            .entropy = &entropy_bytes,
            .realtime_now = std.Io.Clock.real.now(io),
            .ca = .{ .bundle = .{ .bundle = &bundle, .gpa = al, .io = io, .lock = &lock } },
            .read_buffer = &read_buf,
            .write_buffer = &write_buf,
        },
    );

    std.debug.print("cipher: {any}\n", .{client.application_cipher}); // this proves that handshake is successful

    // send request
    try client.writer.print("GET / HTTP/1.1\r\nHost: {s}\r\nConnection: close\r\n\r\n", .{host.bytes});
    try client.writer.flush();
    std.debug.print("data sent\n", .{}); // this proves we got past the flush()

    // read response
    // const server_info = try client.reader.takeDelimiterInclusive('\n');
    const server_info = try client.reader.take(12); // initially I was using the above line, but that hung, so I tried to just take 12 bytes instead
    std.debug.print("Server info: {s}\n", .{server_info});
}

Thank you for your time.

You also need to flush the write buffer of the socket.

// send request
try client.writer.print("GET / HTTP/1.1\r\nHost: {s}\r\nConnection: close\r\n\r\n", .{host.bytes});
try client.writer.flush();
try writer.interface.flush(); // <<<

Also, I believe you need to have seperate buffers for the socket reader/writer and tcp reader/writers (though it seems to work when reusing it).

Two small other things I noticed with your code:

  • You don’t need to initialize the buffers to zero, you can just set them to undefined.
  • Instead of
    var stream = try Io.net.HostName.connect(host, io, 443, .{ .mode = .stream, .protocol = .tcp });
    
    you can do
    var stream = try host.connect(io, 443, .{ .mode = .stream, .protocol = .tcp });
    

@TerenceTux is right. You have to flush both the client writer and the tls ciphertext writer to get it to send all the way to the server.
client.writer.flush just flushes the writer to the ciphertext writer. The ciphertext will sit in that buffer until you flush it as well. This is expected behavior as you may want to write multiple things into the ciphertext and batch them. For your case though where you are sending a single request, you can flush both.

You should have separate buffers for the TLS ciphertext and the client read/write. Otherwise you may get weird behavior.

Instead of constructing your own IO, I would use the one from std.process.Init

pub fn main(init: std.process.Init) !void {
    const io = init.io;

Thank you both for your answers.

Southporter, I was planning on using a threadpool since I thought io_uring isn’t ready yet. I’m not that familiar with the io interfaces yet or how to use them. Do you have any resources you would recommend where I can learn some more about them?

Thanks again.

Hello, init.Io defaults to the threaded implementation.
If you think of actually doing something where green threads would be desireable, zio is much further along than the Evented in std.

Except some minor stuff its basically production ready.
Last stable relase is at 0.16 tho, 0.17 hopefully comming soon, there is one bugfix on master I am excited about.

So I’m familiar with the old:

var pool: std.Thread.Pool = undefined;
const cpu_count = try std.Thread.getCpuCount();
try pool.init(.{ .allocator = al, .n_jobs = cpu_count });
defer pool.deinit();

followed by:

var wg: std.Thread.WaitGroup = .{};
for (0..pool.threads.len) |_| {
    pool.spawnWg(&wg, getTask, .{ ... });
}

Do you know a good resource for sample code of how to use threadpools with “init.Io”?

As for zio, I gave it a try not too long ago, but the issue I was running into is that I had to mess with inserting delays when spawning tasks otherwise I was running into issues so I decided to use threading until io_uring is fully cooked and ready.

With the Threaded Io, thread pools will be handled for you. For something like this you woudl typically use a std.Io.Group

const io = init.io;
const group: std.Io.Group = .init;
// Necessary if you have error paths to account for when creating the tasks
errdefer group.cancel(io);

for (0..20) |_| {
    group.async(io, getTask, .{...});
    // Or if it requires concurency
    try group.concurent(io, getTask, .{...});
}
// Don't forget to wait!
try group.await(io);

This will handle the thread pool under the hood. It also works with any Io implementation. So you could swap out Evented later and it should still behave the same.

If you could remember a bit more about the issue, I’d really appreciate it. What was the behavior that prompted you adding delays when spawning tasks?

Hi lalinsky,
I was using the echo server example with a client on the same machine trying to echo back and forth:

zio echo server code:

const std = @import("std");
const zio = @import("zio");

pub const std_options_debug_io = zio.debug_io;

pub fn main(init: std.process.Init) !void {
    const rt = try zio.Runtime.init(init.gpa, .{});
    defer rt.deinit();

    const addr = try zio.net.IpAddress.parseIp4("127.0.0.1", 8080);

    const server = try addr.listen(.{ .reuse_address = true });
    defer server.close();

    std.log.info("TCP echo server listening on {f}", .{server.socket.address});
    std.log.info("Press Ctrl+C to stop the server", .{});

    var group: zio.Group = .init;
    defer group.cancel();

    while (true) {
        const stream = try server.accept(.{});
        errdefer stream.close();

        try group.spawn(handleClient, .{stream});
    }
}

fn handleClient(stream: zio.net.Stream) !void {
    defer stream.close();

    defer stream.shutdown(.both) catch |err| {
        std.log.err("Failed to shutdown client connection: {}", .{err});
    };

    var read_buffer: [1024]u8 = undefined;
    var reader = stream.reader(&read_buffer);

    var write_buffer: [1024]u8 = undefined;
    var writer = stream.writer(&write_buffer);

    while (true) {
        // Read a line from the client
        const line = reader.interface.takeDelimiterInclusive('\n') catch |err| switch (err) {
            error.EndOfStream => break,
            error.ReadFailed => |e| return reader.err orelse e,
            else => |e| return e,
        };
        std.log.info("{f}: {s}", .{ stream.socket.address, line });

        // Delay the response a little bit
        try zio.sleep(.fromMilliseconds(50));

        // Echo the line back
        try writer.interface.writeAll(line);
        try writer.interface.flush();
    }

    std.log.info("{f} disconnected", .{stream.socket.address});
}

zio client code:

const std = @import("std");
const zio = @import("zio");

pub const std_options_debug_io = zio.debug_io;

pub fn main(init: std.process.Init) !void {
    const rt = try zio.Runtime.init(init.gpa, .{});
    defer rt.deinit();

    const addr = try zio.net.IpAddress.parseIp4("127.0.0.1", 8080);

    var group: zio.Group = .init;
    defer group.cancel();

    for (0..5) |id| {
        std.log.info("id = {d:0>3}", .{id});
        try group.spawn(sendReq, .{ id, addr });
        try zio.sleep(.fromMilliseconds(500));
    }

    while (true) {}
}

fn sendReq(id: usize, addr: zio.net.IpAddress) !void {
    const client = try addr.connect(.{});
    defer client.close();

    var rbuf: [1024]u8 = undefined;
    var wbuf: [1024]u8 = undefined;
    var reader = client.reader(&rbuf);
    var writer = client.writer(&wbuf);

    try writer.interface.print("Req ID is {d:0>3}\n", .{id});
    try writer.interface.flush();
    const msg = try reader.interface.takeDelimiterExclusive('\n');

    std.log.info("{f}: {s}\n", .{ addr, msg });
}

The issue I was getting is that I had to have specific delays in place in order for me to get all of my echoes back. The above code is what I was what I figured out that worked by trial and error. 50 ms delay on the server, 500 ms delay on the client. When I change the client to no delay, I get no echoes back, and when I change it to a much shorter delay like 50 ms I only get some of my echoes back.

I’m not sure what the significance of the delays is or why they’re needed. I was just doing some testing.

Important question, were you on windows?

This is the problem, you should never run a busy wait like this with a cooperative runtime. This is what blocks the event loop. You should use group.wait() (if you are using native zio API like in the example) or group.await(io) (if you are using std.Io).

Debian Linux.

Ooooh I see. I don’t have time to try it right now but I’ll try it when I get back from work. Thanks a lot.

Thank you man. The “group.wait()” worked like a charm.

Man, you guys are on point. Thank you so much, all works. I’ll play around some more and come back with any other questions.

Cheers!