Skip to content

libvncserver: synchronize client encoding updates with framebuffer transmission - #768

Open
Roxas0Dev wants to merge 9 commits into
LibVNC:masterfrom
Roxas0Dev:sendmutex-client-messages
Open

Roxas0Dev wants to merge 9 commits into
LibVNC:masterfrom
Roxas0Dev:sendmutex-client-messages

Conversation

@Roxas0Dev

@Roxas0Dev Roxas0Dev commented Nov 4, 2026 •

Copy link
Copy Markdown

Summary

In background-loop (threaded) mode, SetEncodings, SetPixelFormat and the ExtendedClipboard Request/Peek replies are handled on the client input thread without cl->sendMutex, while the client output thread may be in the middle of rfbSendFramebufferUpdate(). This PR applies these messages under cl->sendMutex, so they can no longer write into an in-flight framebuffer update or change per-client encoding state halfway through one.

The second revision fixes two problems found by @mikaelpelle in the first one (see "Second revision" below) and adds a regression test.

Related: #767 (same client symptom through the Request → Provide path), bk138/droidVNC-NG#94.

Problem

Observed with droidVNC-NG, which runs LibVNCServer with rfbRunEventLoop(screen, -1, TRUE), and the TigerVNC viewer with AutoSelect enabled. After a few seconds of continuous full-screen updates, the viewer disconnects with:

CMsgReader: Rect too big: ...
CConn:      Rect too big
  • With -AutoSelect=0 -PreferredEncoding=Tight -QualityLevel=8 -FullColor=1 the connection stays stable.
  • With AutoSelect enabled, the server log shows a quality renegotiation (8 → 6) shortly before the disconnect.

TigerVNC calls requestNewUpdate() from CConnection::framebufferUpdateStart(). When an encoding setting has changed, it writes SetEncodings as soon as it starts receiving an update. AutoSelect picks quality 8 above roughly 16 Mbit/s and 6 below. A drop to 6 therefore happens when the link is saturated, which is also when the server is most likely still writing that update.

Root cause (code inspection)

  1. ExtendedClipboard capabilities on SetEncodings. Every SetEncodings that contains the ExtendedClipboard pseudo-encoding calls rfbSendExtendedClipboardCapability(), which uses rfbWriteExact() without sendMutex.
    • rfbWriteExact() holds outputMutex for one write only.
    • A framebuffer update is written in several rfbSendUpdateBuf() chunks, so the 16-byte ServerCutText message can land between two chunks of the same update.
  2. SetEncodings state. The handler resets, then rebuilds, preferredEncoding, enableLastRectEncoding, the Tight/TurboJPEG quality and compression levels and the cursor flags.
    • rfbSendFramebufferUpdate() reads these fields once to count rectangles (including rfbNumCodedRectsTight()), then again to encode them.
    • If the fields change between the two reads, nRects may no longer match the rectangles actually sent.
  3. SetPixelFormat. The handler updates cl->format and calls setTranslateFunction(), which rebuilds the translation tables, while an encoder may be using them. The Raw encoder computes the bytes per line once per rectangle.
  4. ExtendedClipboard Request/Peek replies. They write without sendMutex and read cl->extClipboardData, which rfbSendServerCutTextUTF8() frees and replaces under sendMutex (Extended Clipboard replies can interleave with framebuffer updates #767).

What is demonstrated and what is inferred:

  • Demonstrated: the client failure and its dependence on AutoSelect.
  • Inferred: item 1 alone is enough to produce the error and fits the timing. Items 2–4 are races found by reading the code.
  • I did not capture the RFB byte stream in this setup, so I cannot say which of these occurred in a given failing session.
  • Extended Clipboard replies can interleave with framebuffer updates #767 independently reconstructs a failing stream in which a complete ExtendedClipboard message sits between framebuffer rectangles.

Second revision

@mikaelpelle tested the first revision (8dd72ce) with the deterministic ExtendedClipboard regression from #767: 20/20 ordering tests, the SetPixelFormat test and the 5 registered CTests passed, and the outgoing clipboard corruption is gone in their setup. They also reported two remaining problems, both confirmed here:

  1. Incoming ExtendedClipboard Caps. The handler updates extClipboardUserCap, extClipboardMaxUnsolicitedSize and enableExtendedClipboard without sendMutex, while rfbSendServerCutTextUTF8() reads them under it. This is inherited from master. ThreadSanitizer reports the race every time with the new test, and no longer with the fix.
  2. Deadlock on write errors. The first revision calls the ExtendedClipboard send helpers with sendMutex held, and these helpers call rfbCloseClient() on failure. rfbCloseClient() runs the close() callbacks of protocol extensions, so a callback that sends to the client (rfbSendXvp(), rfbSendBell(), ...) deadlocks on sendMutex. Their historical patch avoids this by letting the helper return the failure and closing the client after releasing the mutex, which is what this revision does.

The same deadlock applies to an invalid SetPixelFormat since the first revision: the default rfbSetTranslateFunction() closes the client for unsupported formats, now with sendMutex held. This one can be triggered by the client itself, without a write error.

Which deadlocks the first revision introduced, with the new test and an extension whose close() calls rfbSendBell():

Scenario master 98aaee0 first revision 8dd72ce this revision
write error on the SetEncodings capability message ok deadlock ok
write error on the Request reply ok deadlock ok
write error on the Peek reply ok deadlock ok
invalid SetPixelFormat (12 bpp, or 16 bpp with a colour map) ok deadlock ok
write error in rfbSendServerCutTextUTF8() deadlock deadlock ok

The last row is not caused by this PR: rfbSendServerCutTextUTF8() already called these helpers under sendMutex on master, and the second fix covers it as well.

Commits

First revision, one commit per message type, so each can be reverted or dropped on its own (for example if #767 lands first):

  1. libvncserver: send ExtendedClipboard Request/Peek replies under sendMutex
  2. libvncserver: apply SetEncodings under sendMutex
  3. libvncserver: apply SetPixelFormat under sendMutex

Second revision, on top, unchanged history:

  1. libvncserver: store ExtendedClipboard Caps under sendMutex
  2. libvncserver: close client after releasing sendMutex on ExtendedClipboard errors
  3. libvncserver: check SetPixelFormat before taking sendMutex
  4. test: add sendmutextest

Changes

  • SetPixelFormat: the message is still read first.
    • With the default rfbSetTranslateFunction(), the formats it rejects (bits per pixel other than 8, 16, 24 if enabled, or 32, and colour maps other than 8 bit) are rejected before taking sendMutex, with the same checks.
    • Updating cl->format and calling setTranslateFunction() then happen under sendMutex. A custom setTranslateFunction() is called under sendMutex too.
  • SetEncodings:
    • The whole encoding list is read first into a heap buffer (nEncodings * 4, at most 256 KiB), so the mutex is never held across a socket read.
    • The reset, the per-encoding handling and the ExtendedClipboard capability write then run under sendMutex.
  • Xvp: rfbSendXvp() takes sendMutex itself, so the Xvp init message is now sent after the mutex is released, instead of while the list is being parsed.
  • ExtendedClipboard Request/Peek replies: sent under sendMutex, as rfbSendServerCutTextUTF8() already does.
  • ExtendedClipboard Caps: the message is parsed and checked first. A corrupt message still closes the client, before taking the lock. The three fields are then stored under sendMutex.
  • ExtendedClipboard send helpers (rfbSendExtendedClipboardCapability(), rfbSendExtendedClipboardNotify(), rfbSendExtendedServerCutTextData()): they only report a failure. Their five callers release sendMutex, then call rfbCloseClient().

No change to rfbSendFramebufferUpdate(), the encoders, the wire format, the public headers or the exported symbols.

Locking

  • Lock order: inside the new critical sections, only outputMutex (rfbWriteExact()), updateMutex (rfbRedrawAfterHideCursor()) and the extension list mutex are taken. This is the same order as clientOutput() and rfbNewFramebuffer(), which take sendMutex first.
  • No re-entry: none of the callees takes sendMutex again. rfbSendXvp() would, and it has been moved out.
  • Closing the client: the paths changed here no longer call rfbCloseClient() with sendMutex held, except for errors inside a custom setTranslateFunction() and for write or allocation errors of the BGR233 colour map sent by the default one.
    • Between the release and rfbCloseClient(), the output thread may try to write to the failed connection and close the client itself. rfbCloseClient() already handles being called twice, and the test covers it.
    • In rfbSendServerCutTextUTF8(), the client iterator holds a reference, so the client stays valid until it is closed.
  • Correction to the first revision's description: it said that the TightVNC file-transfer close hook takes no lock. That is wrong: rfbTightExtensionClientClose() joins the download thread, which takes sendMutex for every block it sends. Closing a client with sendMutex held during a download can therefore deadlock without any synthetic callback. I found this by reading the code and did not reproduce it.
  • Behavioural change: the input thread now waits for an in-flight update before applying these messages. Input events queued behind them may be processed slightly later during a large update on a slow link.
    • New pixel formats and encodings take effect from the next update, which is what TigerVNC expects: it switches its own pixel format at the end of the update during which it sent SetPixelFormat.

Testing

  • droidVNC-NG: 2.22.2 on Bliss OS (Android 12L, x86_64) in VirtualBox, 1024×768, continuous full-screen updates, TigerVNC viewer on Windows. First revision:
    • Before: AutoSelect on → Rect too big after a quality change. AutoSelect off → stable.
    • After: AutoSelect on → no Rect too big in the test sessions run so far. Mouse and keyboard input still work.
    • The second revision has not been tested in this setup yet.
  • Android build (first revision): Android NDK 28.2 (clang) for arm64-v8a, armeabi-v7a, x86 and x86_64.
    • rfbserver.c diagnostics with -Wall -Wextra: unchanged.
    • -Wdeclaration-after-statement / -Wvla diagnostics (C90): unchanged.
  • Linux build (second revision): GCC 13 on Ubuntu 24.04 (WSL2), Debug and Release.
    • Compiler warnings: the same as on 8dd72ce.
    • CTest: 6/6, the 5 existing tests and the new sendmutex test.
    • The new test passes 10 times in a row, and 20 times as 4 parallel instances.
    • Each fix commit was built and tested on its own: the test fails until the commit that fixes the scenario.
  • ThreadSanitizer (GCC 13): the Caps race is reported on 8dd72ce and no longer with this revision. The remaining reports are the same with and without this PR: the statistics counters in stats.c, allFds/maxFd in rfbCloseClient() against the listener thread, the same fields in rfbNewTCPOrUDPClient() when a client is added from another thread (as the test does, like rfbReverseConnection()), and auth.c.
  • test/sendmutextest.c: 13 scenarios.
    • Write errors are injected through cl->writeToSocket. A test extension whose close() calls rfbSendBell() turns a close with sendMutex held into a deadlock.
    • Each scenario runs in a child process with an alarm() watchdog. Clients are connected through socketpair(), so no TCP port is opened.
    • Besides the deadlocks above, it checks the Caps size limits and the plain text fallback, a corrupt Caps message, Caps received while texts are sent, a client closed by two threads at once, the Caps and Xvp init order after SetEncodings, and valid pixel formats (8 bpp colour map, 16, 24 and 32 bpp).
    • It is built on Unix with pthreads and zlib only.
  • Not done: MSVC and the other CI configurations, Windows threads, TLS/WebSockets connections, and the regression suite from Extended Clipboard replies can interleave with framebuffer updates #767 on the second revision.
  • Passing tests and a clean ThreadSanitizer run do not prove that no other race or deadlock is left.

Scope and limitations

  • Only relevant for servers using the background event loop. Without threads there is no concurrent output thread.
  • Clients closed with sendMutex held, not changed here: the output thread when a framebuffer update fails, rfbSendXvp(), rfbSendBell(), rfbSendServerCutText(), the allocation error and Latin-1 paths of rfbSendServerCutTextUTF8(), rfbSendSetColourMapEntries(), the UltraVNC file transfer and rfbNewFramebuffer(). These need a broader change, for example around extension close callbacks, and are better handled separately.
  • Other paths not touched:
  • Overlap with other work:

Credits

Thanks to @mikaelpelle for testing the first revision against their regression suite, for reporting both problems fixed in the second revision, and for the error-handling approach of their historical patch.

…utex

The replies to an ExtendedClipboard Request or Peek were written from
the client input thread without holding cl->sendMutex. They could thus
end up between two chunks of a framebuffer update written by the output
thread, which makes clients like TigerVNC fail with "Rect too big". They
also read cl->extClipboardData, which rfbSendServerCutTextUTF8() replaces
under sendMutex.

Send them under sendMutex like rfbSendServerCutTextUTF8() does.

See LibVNC#767.
SetEncodings was processed on the client input thread without holding
cl->sendMutex, while the output thread may be sending a framebuffer
update:

- the ExtendedClipboard capabilities sent in reply could be written
  between two chunks of that update;
- the encoding settings it resets and sets again could change between
  rfbSendFramebufferUpdate() counting the rectangles and encoding them.

TigerVNC with AutoSelect sends SetEncodings when it starts receiving an
update after changing its quality level, and then disconnected with
"Rect too big".

Read the encoding list first, so that the mutex is never held while
blocking on the socket, then apply it under sendMutex. The Xvp init
message is now sent after releasing the mutex, as rfbSendXvp() takes it
itself.
SetPixelFormat changed cl->format and rebuilt the translation tables on
the client input thread while the output thread may be encoding a
framebuffer update with them.

Apply it under sendMutex, as rfbNewFramebuffer() already does when
calling setTranslateFunction().
A Caps message changed extClipboardUserCap, extClipboardMaxUnsolicitedSize
and enableExtendedClipboard without sendMutex, while
rfbSendServerCutTextUTF8() reads them under it.

Parse and check the message first, then store the result under
sendMutex. A corrupt message still closes the client, before taking the
lock.
…oard errors

rfbSendExtendedClipboardCapability(), rfbSendExtendedClipboardNotify()
and rfbSendExtendedServerCutTextData() are called with sendMutex held and
closed the client on failure. rfbCloseClient() runs the close() callbacks
of protocol extensions, and one that sends to the client, e.g. with
rfbSendXvp(), then deadlocks on sendMutex.

Let these helpers only report the failure, and have their callers close
the client once sendMutex is released.
Since SetPixelFormat is applied under sendMutex, a client sending a pixel
format the default rfbSetTranslateFunction() does not support was closed
with sendMutex held, which deadlocks with a protocol extension whose
close() callback sends to the client.

Reject these formats with the same checks before taking sendMutex. A
custom setTranslateFunction() is still called under sendMutex.
Covers client messages handled under sendMutex: ExtendedClipboard Caps,
write errors while ExtendedClipboard messages are sent, and SetPixelFormat.

Write errors are injected through cl->writeToSocket, and a protocol
extension whose close() callback calls rfbSendBell() turns a client
closed with sendMutex held into a deadlock. Each scenario runs in a child
process that alarm() terminates, so a deadlock fails the test instead of
hanging it. Clients are connected through socketpair(), no TCP port is
opened.
Comment thread test/sendmutextest.c Fixed
readServerMsg() multiplied the 16-bit width and height of each raw
rectangle as int, which overflows for large values before the result is
passed to skip() as size_t (reported by CodeQL). Compute the size as
size_t and reject rectangles larger than the framebuffer, which also
keeps the rawBytes total within int.
readServerMsg() negated the signed length of an extended ServerCutText,
which overflows for INT32_MIN (0x80000000). No sender with int sizes
produces it, so reject it before the negation.

Add a parser-limits scenario that feeds the parser a length of INT32_MIN,
a length shorter than the flags and a 65535x65535 rectangle, and checks
that each is rejected without reading past the message.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants