Skip to content

Fix VLA stack overflow in TLS writev after write failure - #4307

Merged
murphyjacob4 merged 3 commits into
valkey-io:unstablefrom
murphyjacob4:tls-writev-fix
Aug 10, 2026
Merged

murphyjacob4 merged 3 commits into
valkey-io:unstablefrom
murphyjacob4:tls-writev-fix

Conversation

@murphyjacob4

@murphyjacob4 murphyjacob4 commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Problem

The bug was originally introduced by #1737

In tls.c, we normally avoid consolidating IO vectors into a buffer if they exceed a capped amount (NET_MAX_WRITES_PER_EVENT, which is 64KB). However, on OpenSSL write errors, we must never trigger a subsequent write that is smaller than the previous failed write. In this path, we must consolidate the IO vectors to ensure the write is at least as large as the last write we made on the socket:

    char buf[iov_bytes_len];
    size_t offset = 0;
    for (int i = 0; i < iovcnt && offset < iov_bytes_len; i++) {
        memcpy(buf + offset, iov[i].iov_base, iov[i].iov_len);

However, iov_bytes_len can easily exceed the stack boundaries if one of the IO vectors is large (e.g. a large key read), leading to a crash:

Thread 1 (Thread 0x7ffff7b65700 (LWP 191) "valkey-server"):
#0  0x00005555557a04bc in connTLSWritev (conn_=0x7ffff6e518c0, iov=<optimized out>, iovcnt=5) at src/tls.c:1713
#1  0x00005555556d2a21 in connWritev (conn=<optimized out>, iov=0x7fffffff9240, iovcnt=5) at src/connection.h:256
#2  writevToClient (c=<optimized out>) at src/networking.c:2814
#3  _writeToClient (c=<optimized out>) at src/networking.c:2868
#4  0x00005555556d326c in writeToClient (c=0x7ffff6e7a780) at src/networking.c:3117
#5  writeToClient (c=0x7ffff6e7a780) at src/networking.c:3108
#6  sendReplyToClient (conn=<optimized out>) at src/networking.c:3127
#7  0x00005555557a0ffd in callHandler (conn=0x7ffff6e518c0, handler=<optimized out>) at src/connhelpers.h:79
#8  tlsHandleEvent (conn=0x7ffff6e518c0, mask=<optimized out>) at src/tls.c:1507
#9  0x00005555555fbad5 in aeProcessEvents (flags=27, eventLoop=0x7ffff6e45f80) at src/ae.c:504
#10 aeMain (eventLoop=0x7ffff6e45f80) at src/ae.c:543
#11 0x00005555555eb83a in main (argc=2, argv=0x7fffffffd588) at src/server.c:7833

Fix

To fix this, we simply avoid allocating large buffers on the stack by using a fixed-size stack buffer char buf[NET_MAX_WRITES_PER_EVENT] (64KB) and performing partial copies:

  1. Calculate total length of all iov blocks to decide if we can use one-by-one writing.
  2. If total length is larger than NET_MAX_WRITES_PER_EVENT (64KB) and iov[0] is large enough to satisfy last_failed_write_data_len, write blocks sequentially one-by-one.
  3. Otherwise (combine path), copy data from iov into a fixed-size stack buffer of NET_MAX_WRITES_PER_EVENT (64KB), capping the copy at 64KB (partial copy if it exceeds).
  4. Verify that we copied at least last_failed_write_data_len to satisfy OpenSSL retry constraint.
  5. Write the combined buffer and return the number of bytes copied (Valkey connection layer will handle the remaining data as a partial write retry).

Important: this should keep the existing "write must be larger than last failed write" invariant, considering: 1) if the last write went to the consolidated buffer path, it would be at most NET_MAX_WRITES_PER_EVENT 2) if the last write did not go through the consolidated buffer path, it will be at the front of the iov, and therefore our iov[0] >= last_failed_write_data_len check will always pass (it is the same write).

Finally, since we added IO threaded TLS writes, the stack limit may be even smaller for the thread (depending on the system). We work around this in bio threads, and I am copying that workaround to IO threads to ensure the stack is not smaller than NET_MAX_WRITES_PER_EVENT.

Testing

A regression test was appended to the existing TLS test suite in tests/unit/tls.tcl. We need to add a new debug subcommand DEBUG FORCE-TLS-WRITE-ERROR <0 or 1> to deterministically trigger OpenSSL write failures. With this flow, we write a command with a small response and force it to trigger an IO error, then we write a command with a larger response and resolve the IO errors. The response to the large command will accumulate in the buffer, and we will attempt to write out the full output buffer for the client, which now includes a massive final IO vector. In the old code, this would trigger a stack overflow as we try to allocate O(megabytes) on the stack.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The server adds a debug command and state field for forced TLS write errors. TLS vector writes now use bounded buffering and validate retry lengths. A regression test exercises small and large pipelined TLS responses.

Changes

TLS write-error handling

Layer / File(s) Summary
TLS write-error debug control
src/server.h, src/server.c, src/debug.c
The server stores and initializes debug_force_tls_write_error. The DEBUG FORCE-TLS-WRITE-ERROR <0|1> command updates the flag and returns success.
Bounded TLS vector writes and regression coverage
src/tls.c, tests/unit/tls.tcl
TLS writes inject EAGAIN for debugging, bound vector data to NET_MAX_WRITES_PER_EVENT, validate retry lengths, and return EIO when required. The TLS test covers pipelined small and large responses.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant TLSClient
  participant DebugCommand
  participant connTLSWritev
  participant connTLSWrite
  TLSClient->>DebugCommand: Set FORCE-TLS-WRITE-ERROR
  DebugCommand->>connTLSWritev: Enable forced write error
  connTLSWritev->>connTLSWrite: Submit vector data
  connTLSWrite-->>connTLSWritev: Return EAGAIN and retry length
  connTLSWritev->>connTLSWrite: Retry bounded data
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main fix: preventing a VLA stack overflow in TLS writev after a write failure.
Description check ✅ Passed The description explains the TLS stack overflow, the fixed-buffer solution, retry behavior, and regression testing.

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.

@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: 3

🧹 Nitpick comments (1)
src/tls.c (1)

1716-1743: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Consider a GoogleTest for the buffer-coalescing and retry-length logic.

The buffer-fill loop and the to_write < conn->last_failed_write_data_len retry check are pure, TLS-independent logic. Extracting this into a small testable helper and adding a GoogleTest under src/unit/ would let boundary cases (to_write exactly at NET_MAX_WRITES_PER_EVENT, multi-iovec coalescing, retry-length exactly satisfied/unsatisfied) be verified without a live 10 MB TLS round trip.

As per path instructions: "Place data-structure and low-level logic tests in src/unit/ as C++ GoogleTest tests."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tls.c` around lines 1716 - 1743, Extract the buffer-coalescing and
retry-length validation from the connTLSWritev flow into a small TLS-independent
helper, preserving the NET_MAX_WRITES_PER_EVENT cap and
last_failed_write_data_len check. Add a C++ GoogleTest under src/unit/ covering
exact-capacity writes, multi-iovec concatenation, and retry lengths that are
exactly satisfied or unsatisfied.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/debug.c`:
- Around line 1097-1099: Add a usage and description entry for DEBUG
FORCE-TLS-WRITE-ERROR to the help[] array in the DEBUG HELP definitions,
matching the formatting and wording style of the existing DEBUG subcommand
entries and reflecting its required argument.

In `@src/tls.c`:
- Around line 1716-1743: Update createIOThread() so its pthread attributes
configure the stack size using the VALKEY_THREAD_STACK_SIZE guard, matching
bioInit() before creating I/O threads; preserve the existing thread creation
behavior while ensuring connTLSWritev() has sufficient stack space for its fixed
buffer.

In `@tests/unit/tls.tcl`:
- Around line 806-859: Add a bounded timeout to the raw socket read in the TLS
regression test, replacing the blocking read in the read_failed catch block with
nonblocking/fileevent handling and an after-based timeout. Ensure a stalled
connection sets the failure condition and allows the test to continue to the
existing crash/EOF validation instead of hanging indefinitely.

---

Nitpick comments:
In `@src/tls.c`:
- Around line 1716-1743: Extract the buffer-coalescing and retry-length
validation from the connTLSWritev flow into a small TLS-independent helper,
preserving the NET_MAX_WRITES_PER_EVENT cap and last_failed_write_data_len
check. Add a C++ GoogleTest under src/unit/ covering exact-capacity writes,
multi-iovec concatenation, and retry lengths that are exactly satisfied or
unsatisfied.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 660b8ccf-8ce5-4ae9-af20-7f1dcc12db98

📥 Commits

Reviewing files that changed from the base of the PR and between fb94efb and e11bf1b.

📒 Files selected for processing (5)
  • src/debug.c
  • src/server.c
  • src/server.h
  • src/tls.c
  • tests/unit/tls.tcl

Comment thread src/tls.c Resolved
Comment thread tests/unit/tls.tcl Resolved

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/debug.c`:
- Around line 1097-1099: Update the DEBUG FORCE-TLS-WRITE-ERROR branch in the
command handler to parse c->argv[2] with getLongFromObjectOrReply, reject values
other than 0 or 1 with an error reply, and only then assign
server.debug_force_tls_write_error and return success.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 95a972ec-1776-4919-b471-a0cefc9ca402

📥 Commits

Reviewing files that changed from the base of the PR and between e11bf1b and 371517f.

📒 Files selected for processing (5)
  • src/debug.c
  • src/server.c
  • src/server.h
  • src/tls.c
  • tests/unit/tls.tcl
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/server.c
  • src/server.h
  • tests/unit/tls.tcl
  • src/tls.c

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/debug.c`:
- Around line 1097-1099: Update the DEBUG HELP command listing to include
force-tls-write-error, documenting its argument syntax and purpose consistently
with the existing entries. Locate the help array or DEBUG HELP response
definition near the other debug command descriptions, and update related command
documentation if that listing is maintained separately.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b8072338-00b1-468f-a89c-653b212423ac

📥 Commits

Reviewing files that changed from the base of the PR and between 371517f and 2a77f81.

📒 Files selected for processing (5)
  • src/debug.c
  • src/server.c
  • src/server.h
  • src/tls.c
  • tests/unit/tls.tcl
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/server.h
  • src/server.c
  • src/tls.c
  • tests/unit/tls.tcl

Comment thread src/debug.c Resolved

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/debug.c`:
- Around line 1099-1101: Update the FORCE-TLS-WRITE-ERROR branch in the debug
command handler to parse the argument with the bounded 64-bit reply parser
instead of atoi, reject parse failures and values other than 0 or 1, and only
then assign server.debug_force_tls_write_error and return the success reply.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dc21ce05-7be7-4c36-bf4f-36a6bb30eeb2

📥 Commits

Reviewing files that changed from the base of the PR and between 2a77f81 and cc07c94.

📒 Files selected for processing (5)
  • src/debug.c
  • src/server.c
  • src/server.h
  • src/tls.c
  • tests/unit/tls.tcl
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/server.h
  • src/server.c
  • tests/unit/tls.tcl
  • src/tls.c

Comment thread src/debug.c Resolved

@valkey-review-bot valkey-review-bot 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.

The bounded-copy approach looks right: consolidated writes are now capped at 64 KB and the leftover is handled as a partial write by writevToClient, and the "retry must be at least as large as the last failed write" invariant still holds because any last_failed_write_data_len above 64 KB can only come from a single-iovec write in the one-by-one path, which is still iov[0] on the retry.

Two things to address: the new fallback guard's failure mode, and the fact that the regression test can go green without ever reaching the fixed path.

Comment thread src/tls.c Resolved
Comment thread tests/unit/tls.tcl Resolved
@murphyjacob4
murphyjacob4 force-pushed the tls-writev-fix branch 6 times, most recently from b4b40d3 to b789a2e Compare July 31, 2026 21:42
@murphyjacob4 murphyjacob4 moved this to To be backported in Valkey 7.2 Jul 31, 2026
@murphyjacob4 murphyjacob4 moved this to To be backported in Valkey 8.0 Jul 31, 2026
@murphyjacob4 murphyjacob4 moved this to To be backported in Valkey 8.1 Jul 31, 2026
@murphyjacob4 murphyjacob4 moved this to To be backported in Valkey 9.0 Jul 31, 2026
@murphyjacob4 murphyjacob4 moved this to To be backported in Valkey 9.1 Jul 31, 2026
@murphyjacob4 murphyjacob4 added the run-extra-tests Run extra tests on this PR (Runs all tests from daily except valgrind and RESP) label Jul 31, 2026
@murphyjacob4
murphyjacob4 requested a review from ranshid July 31, 2026 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-extra-tests Run extra tests on this PR (Runs all tests from daily except valgrind and RESP)

Projects

Status: Done
Status: Done
Status: Done
Status: Done
Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants