Skip to content

Make it possible to use std.crypto.tls.Client - #1

Merged
lalinsky merged 6 commits into
mainfrom
stream-tls
Sep 26, 2025
Merged

lalinsky merged 6 commits into
mainfrom
stream-tls

Conversation

@lalinsky

@lalinsky lalinsky commented Sep 26, 2025 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Added a TLS demo demonstrating an HTTPS GET over TCP.
    • Introduced vectored I/O for TCP streams (efficient multi-buffer read/write and "read at least" support).
  • Chores

    • Simplified example configuration and added the TLS demo to the examples list.
  • Tests

    • Expanded tests for vectored I/O, including empty and zero-length buffer edge cases.

Implements vectored I/O operations for TcpStream:
- readv(): reads into first non-empty buffer only
- readvAll(): reads into all buffers completely
- writev(): writes from first non-empty buffer only
- writevAll(): writes from all buffers completely

The implementation emulates vectored I/O using existing read/write
methods since xev doesn't provide native iovec support.

Includes comprehensive test coverage for all operations and edge cases.
Enhances TcpStream with full StreamInterface compliance:
- Add error type aliases (ReadError, WriteError)
- Add readAtLeast() method for TLS client support
- Fix iovec field names (base/len vs iov_base/iov_len)
- Make writevAll() return void to match interface contract
- Update all vectored I/O tests with correct field names

Add TLS demo showcasing HTTPS client:
- examples/tls_demo.zig: Complete HTTPS client using std.crypto.tls
- examples/tcp_test.zig: Basic TCP connectivity test
- build.zig: Add run steps for new examples

The TLS demo demonstrates secure HTTPS communication over our
custom TCP implementation, successfully bridging zio.tls async
runtime with Zig's standard TLS library.
@coderabbitai

coderabbitai Bot commented Sep 26, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Removes per-example step/desc metadata from the build, adding a tls-demo entry and building executables directly from name/file. Adds examples/tls_demo.zig implementing a TLS-over-TCP HTTP GET demo. Extends src/tcp.zig with vectored I/O APIs (readv/writev variants) and readAtLeast plus tests.

Changes

Cohort / File(s) Summary
Build config simplification
build.zig
Removes step/desc fields from example definitions; examples are now { name, file }. Builds executables directly from example.file; special-cases libc linkage for stack-overflow-demo. Adds tls-demo entry.
New TLS example
examples/tls_demo.zig
Adds pub fn main() !void which creates an allocator and runtime, spawns a TLS task, resolves an IP for httpbin.org, connects TCP port 443, performs a TLS client handshake (no CA verification for demo), sends an HTTP GET, reads bytes, and logs lifecycle and results.
TCP vectored I/O APIs
src/tcp.zig
Adds public ReadError, WriteError, readv, readvAll, readAtLeast, writev, writevAll. Expands tests for vectored I/O, including empty iovecs and zero-length buffers.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Main as tls_demo.main
  participant RT as Runtime
  participant DNS as Resolver
  participant TCP as TcpStream
  participant TLS as TlsClient
  participant Server as httpbin.org:443

  User->>Main: start
  Main->>RT: init + spawn runTlsTask
  RT-->>Main: task handle
  Main->>RT: run()
  RT->>DNS: resolve("httpbin.org")
  DNS-->>RT: IP address
  RT->>TCP: connect(IP, 443)
  TCP-->>RT: connected
  RT->>TLS: handshake(host="httpbin.org", no_verification)
  TLS->>Server: TLS handshake
  Server-->>TLS: handshake complete
  RT->>TLS: write("GET /get HTTP/1.1\r\nHost: httpbin.org\r\n\r\n")
  TLS->>Server: send request
  Server-->>TLS: HTTPS response bytes
  TLS-->>RT: read response
  RT->>RT: log/print partial response
  RT-->>Main: task complete
  Main-->>User: exit
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I hopped through sockets, a rabbit in code,
TLS flowers blooming along the road.
I readv, writev, nibble bytes with delight,
Sent a tiny GET into the night.
Build burrow trimmed — examples take flight. 🥕🐇

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
Title Check ✅ Passed The title directly reflects the pull request’s main goal of enabling the std.crypto.tls.Client API, which underlies the new TLS example, TcpStream enhancements, and build script refactoring. It is concise, specific, and avoids unnecessary detail. A teammate scanning the history will immediately understand that TLS client usage was enabled.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch stream-tls

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (3)
src/tcp.zig (2)

119-120: Add specific error types for better API clarity.

The ReadError and WriteError aliases are too broad using anyerror. This makes error handling less predictable for users and hides the actual error set. Consider defining specific error unions based on the underlying operations.

Apply this diff to provide more specific error types:

-    pub const ReadError = anyerror;
-    pub const WriteError = anyerror;
+    pub const ReadError = xev.ReadError;
+    pub const WriteError = xev.WriteError;

216-225: Clarify readv behavior vs POSIX readv
Document that readv only reads the first non-empty buffer and direct users to readvAll for full POSIX-style vectored I/O.

examples/tcp_test.zig (1)

17-17: Replace hardcoded example.com IP with a DNS lookup

The IPv4 address 93.184.216.34 is outdated—example.com now returns multiple anycast A records (e.g. 23.215.0.136, 23.215.0.138, 23.192.228.80, …). Hardcoding risks breakage. Use a DNS-based lookup (e.g. via zio.Address.resolve or similar) to obtain the current A record at runtime.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a108a52 and 4c6af43.

📒 Files selected for processing (4)
  • build.zig (2 hunks)
  • examples/tcp_test.zig (1 hunks)
  • examples/tls_demo.zig (1 hunks)
  • src/tcp.zig (4 hunks)
🔇 Additional comments (8)
src/tcp.zig (3)

248-257: LGTM! Solid implementation with proper assertion.

The readAtLeast function correctly handles partial reads and includes an important assertion to validate the input parameters.


738-773: LGTM! Excellent edge case testing.

The edge case test properly validates behavior with empty iovecs and zero-length buffers. This is crucial for robust vectored I/O implementation.


491-549: Test has incorrect expectations for readv behavior.

The test expects readv to read exactly 5 bytes into the first buffer, but this assumes the server sends exactly "Hello, World!" and the client reads it in a specific way. Network I/O is inherently unpredictable.

Apply this diff to make the test more robust:

 const ClientTask = struct {
     fn run(rt: *Runtime) !void {
         rt.sleep(10);

-        const addr = try Address.parseIp4("127.0.0.1", 8080);
+        const addr = try Address.parseIp4("127.0.0.1", 8080); // Should match server port
         var stream = try TcpStream.connect(rt, addr);

         var buf1: [5]u8 = undefined;
         const buf2: [5]u8 = undefined;
         const buf3: [10]u8 = undefined;

         var iovecs = [_]std.posix.iovec{
             .{ .base = buf1.ptr, .len = buf1.len },
             .{ .base = @constCast(buf2.ptr), .len = buf2.len },
             .{ .base = @constCast(buf3.ptr), .len = buf3.len },
         };

         const bytes_read = try stream.readv(&iovecs);
-        try testing.expect(bytes_read == 5);
-        try testing.expectEqualStrings("Hello", &buf1);
+        try testing.expect(bytes_read > 0);
+        try testing.expect(bytes_read <= buf1.len);
+        // Only check the content that was actually read
+        const expected_prefix = "Hello"[0..@min(bytes_read, 5)];
+        try testing.expectEqualStrings(expected_prefix, buf1[0..bytes_read]);

         stream.close();
     }
 };

Likely an incorrect or invalid review comment.

build.zig (2)

33-34: LGTM! Clean integration of new examples.

The addition of TLS demo and TCP test examples follows the existing pattern and maintains consistency with other examples.


48-55: LGTM! Proper dependency management for run steps.

The run step implementation correctly ensures that executables are installed before running them, following Zig build system best practices.

examples/tcp_test.zig (1)

4-41: LGTM! Well-structured TCP example with proper resource cleanup.

The example demonstrates proper usage of the zio TCP API with appropriate error handling and resource management using defer statements.

examples/tls_demo.zig (2)

17-17: Same IP address concern as tcp_test.zig.

The hardcoded IP address 93.184.216.34 for example.com should be verified for current accuracy.


4-55: LGTM! Good TLS usage example with proper error handling.

The example demonstrates the intended usage pattern for TLS over TCP streams with proper resource management and informative logging.

Comment thread examples/tls_demo.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
Comment thread src/tcp.zig Resolved
- Remove check for 0-byte writes that would cause early return
- Make iovecs parameter const since we don't mutate it
- Now matches standard library behavior where write() returning 0
  is considered an unexpected condition rather than normal EOF
- Delete examples/tcp_test.zig file
- Remove run step configuration from build system
- Simplify examples array to only include name and file
- Examples are now built as executables without custom run commands
- Apply working TLS implementation from stash with httpbin.org
- Increase stack size to 4MB to prevent segfaults during TLS handshake
- Use writeAll() instead of write() for proper TLS Client API usage
- Add better error handling and detailed logging
- Convert to standalone function structure
- TLS demo now successfully completes HTTPS requests
@lalinsky lalinsky changed the title Make it possible to use std.tls Make it possible to use std.tls.client.Client Sep 26, 2025
@lalinsky lalinsky changed the title Make it possible to use std.tls.client.Client Make it possible to use std.crypto.tls.Client Sep 26, 2025
@lalinsky
lalinsky merged commit 65f8ad2 into main Sep 26, 2025
@lalinsky
lalinsky deleted the stream-tls branch September 26, 2025 22:20
This was referenced Sep 27, 2025
lalinsky added a commit that referenced this pull request Jan 6, 2026
* Add stack alloocator

* Optimize stack allocation size to reduce memory waste

Use power-of-2 rounded size for total allocation instead of adding
extra guard page, preventing wasted pages from rounding. Add size
validation to ensure minimum requirements for guard page and metadata.

* Integrate Stack allocator with Coroutine

- Import Stack from stack.zig
- Remove old stack types (RawStack, StackPtr)
- Add stack_alignment constant to each Context architecture
- Update Coroutine to store Stack pointer (non-optional)
- Fix setup() to use Stack metadata (base/limit) with correct terminology
- Fix Windows TIB initialization to use proper Stack fields
- Update initContext to take usize and add alignment assertion
- Update tests to use Stack.alloc() instead of allocator.alignedAlloc()

* Add valgrind stack registration support

Register coroutine stacks with valgrind to enable proper tracking during
context switches. Without registration, valgrind would flag stack pointer
changes as invalid memory access.

- Add valgrind_stack_id field to both StackPosix and StackWindows
- Call std.valgrind.stackRegister() in alloc() when built with Debug mode
- Call std.valgrind.stackDeregister() in free() to clean up
- Only active when builtin.valgrind_support is enabled

* Fix stack allocation for platforms with large page sizes

Ensure stack allocation rounds to at least 2 pages to support platforms
with large page sizes like Apple (16KB pages). The test was allocating
8KB which failed on macOS because we need at least:
- 1 page for guard
- Space for metadata and usable stack

Now allocate @max(maximum_size, page_size * 2) before rounding to
power-of-2, ensuring sufficient space on all platforms.

* Relax stack allocation test to handle platform variations

Change exact size check to >= check since allocation size varies by
platform page size (4KB on Linux, 16KB on macOS). Test now verifies:
- Allocation is at least the requested size
- Use actual allocation.len for limit calculations
- Still validates base/limit relationship and bounds

* Add test for fully committed stack allocation

Test the edge case where committed_size equals maximum_size (100%
committed). This is important to verify especially on Windows where
the allocation logic handles committed vs reserved regions differently.

* Implement stack extension with lazy commit

Add extend() method that grows stack by 1.5x factor in 64KB chunks:

POSIX changes:
- Change mmap to use PROT_NONE for lazy commit (reserve address space)
- mprotect initial committed region to READ|WRITE
- extend() uses mprotect to commit additional pages as needed
- Layout: [guard (PROT_NONE)][uncommitted (PROT_NONE)][committed][metadata]

Windows changes:
- extend() commits additional pages and moves guard page down
- Maintains PAGE_GUARD for automatic growth

Both platforms:
- Growth factor of 1.5x (3/2) current committed size
- Rounds to 64KB chunks
- Updates valgrind stack registration on growth
- Returns StackOverflow if no space remaining

Add test verifying extend() commits more memory and allows writes.

* Refactor how we handle context

* Add StackAllocator abstraction with vtable

Introduces StackAllocator struct with vtable for future stack pool
implementations. The default allocator uses existing stackAlloc/stackFree
functions via vtable indirection.

Also changes stackFree to accept StackInfo by value instead of pointer,
since it only reads the struct without modifying it.

* Switch Windows stack allocation to RtlCreateUserStack

Replace manual VirtualAlloc/VirtualFree approach with RtlCreateUserStack
and RtlFreeUserStack from ntdll.dll. This provides automatic stack growth
via PAGE_GUARD on real Windows.

Changes:
- Add INITIAL_TEB struct and ntdll extern declarations
- Rewrite stackAllocWindows to use RtlCreateUserStack
- Update stackFreeWindows to use RtlFreeUserStack
- Make stackExtendWindows unreachable (Windows handles growth automatically)
- Skip extend test on Windows platform
- Relax test assertions to handle Wine's eager commit behavior

Benefits:
- Native Windows stack management with automatic growth
- Simpler allocation/free implementation
- Compatible with both Wine and real Windows

* Fix NetBSD stack allocation using PROT_MPROTECT to declare future permissions

NetBSD security restriction prevents making memory protection more permissive
via mprotect() than the initial mmap() protection. Use PROT_MPROTECT macro to
declare upfront that we will need READ|WRITE permissions later for stack growth.

* Add FreeBSD PROT_MAX support alongside NetBSD PROT_MPROTECT

FreeBSD 13+ provides PROT_MAX to declare maximum permissions upfront,
similar to NetBSD's PROT_MPROTECT. This is needed when stricter security
policies are enabled. Unified both into PROT_MAX_FUTURE helper function.

* Cleanup

* Add validation to prevent committed size from exceeding maximum size

After aligning sizes to page boundaries, validate that the committed size
doesn't exceed the available space. This prevents passing invalid sizes to
RtlCreateUserStack on Windows or attempting to commit more memory than
allocated on POSIX systems. Also fixed POSIX allocation to account for guard
page in the total size calculation.

* Move fiber_data from StackInfo to Context

fiber_data is Windows-specific coroutine state (TEB offset 0x20) that belongs
in the Context structure rather than StackInfo. This change moves it to the
appropriate location for each supported architecture.

* Fix confusing saturating subtraction in stackExtendPosix

Replace the if-else that produces 0 on underflow with an explicit check that
returns error.StackOverflow when size_to_commit > info.limit. This prevents
computing an invalid address and makes the error condition clear.

* Add stack overflow checks in Coroutine.setup

Check that stack_top doesn't go below stack_limit when allocating
CoroutineData and Entrypoint structures on the coroutine stack. This
catches stack overflow during setup before invalid memory access occurs.

* Fiber data is only for windows
lalinsky added a commit that referenced this pull request Feb 19, 2026
Use 'adr r2, 0f + 1' instead of separate 'adr r2, 0f' + 'adds r2, #1'
to set the Thumb mode LSB in the return address.
lalinsky added a commit that referenced this pull request Feb 19, 2026
)

Use 'adr r2, 0f + 1' instead of separate 'adr r2, 0f' + 'adds r2, #1'
to set the Thumb mode LSB in the return address.
@coderabbitai coderabbitai Bot mentioned this pull request Apr 20, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant