Repository navigation
Conversation
…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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
In background-loop (threaded) mode,
SetEncodings,SetPixelFormatand the ExtendedClipboard Request/Peek replies are handled on the client input thread withoutcl->sendMutex, while the client output thread may be in the middle ofrfbSendFramebufferUpdate(). This PR applies these messages undercl->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:-AutoSelect=0 -PreferredEncoding=Tight -QualityLevel=8 -FullColor=1the connection stays stable.TigerVNC calls
requestNewUpdate()fromCConnection::framebufferUpdateStart(). When an encoding setting has changed, it writesSetEncodingsas 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)
SetEncodingsthat contains the ExtendedClipboard pseudo-encoding callsrfbSendExtendedClipboardCapability(), which usesrfbWriteExact()withoutsendMutex.rfbWriteExact()holdsoutputMutexfor one write only.rfbSendUpdateBuf()chunks, so the 16-byteServerCutTextmessage can land between two chunks of the same update.preferredEncoding,enableLastRectEncoding, the Tight/TurboJPEG quality and compression levels and the cursor flags.rfbSendFramebufferUpdate()reads these fields once to count rectangles (includingrfbNumCodedRectsTight()), then again to encode them.nRectsmay no longer match the rectangles actually sent.cl->formatand callssetTranslateFunction(), which rebuilds the translation tables, while an encoder may be using them. The Raw encoder computes the bytes per line once per rectangle.sendMutexand readcl->extClipboardData, whichrfbSendServerCutTextUTF8()frees and replaces undersendMutex(Extended Clipboard replies can interleave with framebuffer updates #767).What is demonstrated and what is inferred:
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:extClipboardUserCap,extClipboardMaxUnsolicitedSizeandenableExtendedClipboardwithoutsendMutex, whilerfbSendServerCutTextUTF8()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.sendMutexheld, and these helpers callrfbCloseClient()on failure.rfbCloseClient()runs theclose()callbacks of protocol extensions, so a callback that sends to the client (rfbSendXvp(),rfbSendBell(), ...) deadlocks onsendMutex. 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
SetPixelFormatsince the first revision: the defaultrfbSetTranslateFunction()closes the client for unsupported formats, now withsendMutexheld. 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()callsrfbSendBell():98aaee08dd72cerfbSendServerCutTextUTF8()The last row is not caused by this PR:
rfbSendServerCutTextUTF8()already called these helpers undersendMutexon 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):
libvncserver: send ExtendedClipboard Request/Peek replies under sendMutexlibvncserver: apply SetEncodings under sendMutexlibvncserver: apply SetPixelFormat under sendMutexSecond revision, on top, unchanged history:
libvncserver: store ExtendedClipboard Caps under sendMutexlibvncserver: close client after releasing sendMutex on ExtendedClipboard errorslibvncserver: check SetPixelFormat before taking sendMutextest: add sendmutextestChanges
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 takingsendMutex, with the same checks.cl->formatand callingsetTranslateFunction()then happen undersendMutex. A customsetTranslateFunction()is called undersendMutextoo.nEncodings * 4, at most 256 KiB), so the mutex is never held across a socket read.sendMutex.rfbSendXvp()takessendMutexitself, so the Xvp init message is now sent after the mutex is released, instead of while the list is being parsed.sendMutex, asrfbSendServerCutTextUTF8()already does.sendMutex.rfbSendExtendedClipboardCapability(),rfbSendExtendedClipboardNotify(),rfbSendExtendedServerCutTextData()): they only report a failure. Their five callers releasesendMutex, then callrfbCloseClient().No change to
rfbSendFramebufferUpdate(), the encoders, the wire format, the public headers or the exported symbols.Locking
outputMutex(rfbWriteExact()),updateMutex(rfbRedrawAfterHideCursor()) and the extension list mutex are taken. This is the same order asclientOutput()andrfbNewFramebuffer(), which takesendMutexfirst.sendMutexagain.rfbSendXvp()would, and it has been moved out.rfbCloseClient()withsendMutexheld, except for errors inside a customsetTranslateFunction()and for write or allocation errors of the BGR233 colour map sent by the default one.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.rfbSendServerCutTextUTF8(), the client iterator holds a reference, so the client stays valid until it is closed.rfbTightExtensionClientClose()joins the download thread, which takessendMutexfor every block it sends. Closing a client withsendMutexheld during a download can therefore deadlock without any synthetic callback. I found this by reading the code and did not reproduce it.SetPixelFormat.Testing
Rect too bigafter a quality change. AutoSelect off → stable.Rect too bigin the test sessions run so far. Mouse and keyboard input still work.rfbserver.cdiagnostics with-Wall -Wextra: unchanged.-Wdeclaration-after-statement/-Wvladiagnostics (C90): unchanged.8dd72ce.sendmutextest.8dd72ceand no longer with this revision. The remaining reports are the same with and without this PR: the statistics counters instats.c,allFds/maxFdinrfbCloseClient()against the listener thread, the same fields inrfbNewTCPOrUDPClient()when a client is added from another thread (as the test does, likerfbReverseConnection()), andauth.c.test/sendmutextest.c: 13 scenarios.cl->writeToSocket. A test extension whoseclose()callsrfbSendBell()turns a close withsendMutexheld into a deadlock.alarm()watchdog. Clients are connected throughsocketpair(), so no TCP port is opened.Scope and limitations
sendMutexheld, not changed here: the output thread when a framebuffer update fails,rfbSendXvp(),rfbSendBell(),rfbSendServerCutText(), the allocation error and Latin-1 paths ofrfbSendServerCutTextUTF8(),rfbSendSetColourMapEntries(), the UltraVNC file transfer andrfbNewFramebuffer(). These need a broader change, for example around extension close callbacks, and are better handled separately.rfbSetClientColourMap()is called from the FramebufferUpdateRequest handler while holdingupdateMutexand can takesendMutex. This only applies to colour-mapped servers.sendMutexdesign.git merge-tree).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.