Repository navigation
fix errno values read as system error codes - #19749
kevinushey wants to merge 24 commits into
Conversation
systemError(boost::system::errc::X) bound to the int overload and built a system-category code, which holds Win32 codes on Windows, so the errno value was read as a Win32 error and given that error's message. Add errc_t overloads that build a generic-category code, and make Error's equality treat a generic code as an error condition, so checks written as systemError(errc::X) still match the errno or Win32 code the system reports. That equivalence makes the address_in_use retry in startHttpConnectionListenerWithTimeout() match for the first time, so free the listener that failed to bind before allocating its replacement. Addresses #19745.
An enum argument converted to int and became a system-category code. Enums that are boost error code enums now use their own category (asio, json-rpc, windows_error, ...), and any other enum fails to compile. This moves the one existing caller, SessionVCS's json::errc::ParamInvalid, into the json-rpc category, so the client gets it as an invalid-parameter RPC error. Addresses #19745.
systemError(EINVAL, ...) builds a system-category code, which Windows reads as a Win32 error. Pass the matching errc instead, and give C runtime errno values in the Win32-only files the generic category. A linter test fails on either pattern. Addresses #19745.
zlib return codes and kern_return_t values went to systemError(int), so their messages were strerror()'s (or Win32's) for an unrelated number. Report them with zlib's and mach's own messages instead. Addresses #19745.
R_ERRNO (the C runtime errno, also on Windows) and errc values paired with system_category() by hand made the same mistake; build those as generic codes and add both to the linter test. Reject every unscoped enum without a boost category in systemError(), and every enum in systemCallError(). Test zlib errors against a deterministic Z_DATA_ERROR. Addresses #19745.
The lint now finds systemCallError() with a non-literal name and covers every file with Win32 in its name; captureCommand() reads errno before logging. Addresses #19745.
ERROR_LOCATION may be evaluated first, and its allocations can change errno. Addresses #19745.
Value comparisons against an errc ignore the code's category, so on Windows a Win32 code matched whichever errc shared its number (and the accept backoff never saw WSAEMFILE). Compare as conditions instead, and add the pattern to the linter test. StreamWriter now hands its error handler the write's error code, so handleStreamError() no longer rebuilds one in the generic category. Addresses #18946. Addresses #19745.
gtritchie
left a comment
There was a problem hiding this comment.
A few things below, plus one outside the diff:
src/cpp/r/session/RConsoleHistory.cpp:191: the #19689 comment says a bare errc value would go to systemError(int), which on Windows reads 21 as a Win32 code ("The device is not ready"). With the new errc_t overloads that's no longer true, so the comment now contradicts the code. The std::make_error_code(std::errc::...) calls at :181 and :196 build the same generic-category error as systemError(boost::system::errc::...), differing only in the Windows message text (MSVC's std table vs the CRT's strerror()). test-history.R:98 matches with ignore.case = TRUE, so either spelling passes. At least the comment should be updated or removed.
| boost::system::system_category()), | ||
| error, | ||
| ERROR_LOCATION); | ||
| Error permissionError = systemError(boost::system::errc::permission_denied, error, ERROR_LOCATION); |
There was a problem hiding this comment.
This bug predates this PR, but it's next to a line the PR changes. The check above (:913) lets a lookup failure through only when it's permission_denied, which the comment says means "no user was found". Since 670762b (2020), User::Impl::populateUser reports a missing user as ENOENT instead. This PR turns that into errc::no_such_file_or_directory in User.cpp, and the new equivalence doesn't make it match permission_denied. So a user who isn't in passwd yet (the PAM case the comment describes) always ends up here and is refused. Either the check should test for not-found (isNotFoundError(error)), or the comment should change to say the request is rejected.
| // startHttpConnectionListenerWithTimeout() calls this again while the | ||
| // address is in use; replace the listener that failed to bind (it never | ||
| // started, so nothing else holds it) | ||
| delete s_pHttpConnectionListener; |
There was a problem hiding this comment.
Now that the address_in_use retry actually runs, each attempt (about 10, from waitWithTimeout(fn, 0, 100, 1)) goes back through initTcpHttpConnectionListener() and logs its startup warnings again. A standalone session gets an empty shared secret, and verify-signatures defaults to false, so a session waiting on its reused port logs "The tcp http listener initialized without signature validation: --verify-signatures option missing" about 10 times instead of once. Running as root also repeats the line-75 warning. Could the warnings be logged once, or the retry rebind the same listener instead of rebuilding it?
|
|
||
| contents <- paste(readLines(cppFile, warn = FALSE), collapse = "\n") | ||
| patterns <- c(errnoConstant, rErrno, errcAsSystem, errcByValue) | ||
| if (grepl("Win32", basename(cppFile), fixed = TRUE)) |
There was a problem hiding this comment.
The C runtime errno pattern only runs on files with Win32 in the name, so Windows-only #ifdef _WIN32 blocks in shared files (e.g. AdvisoryFileLock.cpp, FileSerializer.cpp) aren't checked. Also, errcByValue requires errc::, so error.getCode() == ENOENT in cross-platform code has the same category-blind problem but isn't flagged. I didn't find any current offenders, so this only matters for future code.
The std::make_error_code() spelling and its comment worked around systemError(errc) reading the value as a Win32 code, which no longer happens. Addresses #19745.
Builds a generic-category error from an int errno value, and rejects enums at compile time (an errc goes to systemError()). Replaces the hand-built std::error_code(..., std::generic_category()) at the C runtime errno sites. Addresses #19745.
The C runtime errno rule, and a new rule against comparing a code's value with an errno constant, now cover #ifdef _WIN32 regions of shared files as well as Win32 files. Addresses #19745.
Letting a user who isn't in passwd through skips the uid check, and any local user can create a socket in the world-writable streams directory, so an impostor's socket could receive the request. Reject every lookup failure, including the permission_denied one the old check let through, and fix the comments. Addresses #18946.
Recognize '#if _WIN32', conjunctions with _WIN32, and the #elif/#else branches that follow a _WIN32 test; accept chained receivers such as e.code().value(); don't flag EOF. Test genericError()'s description form against enums too. Addresses #19745.
RStudio E2E - all platforms1 test(s) failed
All platforms - commit |
|
Superseded by #19753, which fixes the same categories with a narrower change: |
Intent
On Windows, errors that RStudio builds from an errno value reported the message of an unrelated Win32 error with the same number. For example,
errc::io_error(5) reported "Access is denied", anderrc::is_a_directory(21) reported "The device is not ready" (theloadhistory()symptom fixed for that one call in #19689). About 364 calls are spelledsystemError(boost::system::errc::X, ...), and 77 more make the same mistake another way: an errno constant (49), a C runtimeerrno(6, countingR_ERRNO), anerrcpaired withsystem_category()by hand (9), or a code's raw value compared against anerrc(13).The error factories now require a category for integer inputs. The compiler catches the same mistake for errno constants, saved integers and Win32
DWORDvalues.It also resolves #18946. Callers can now ask whether a native error matches a portable condition, including when a session should retry binding a port.
Fixes #19745.
Fixes #18946.
Approach
Portable
errcvalues use the generic category. Boost’serrc::errc_trepresents portable errno conditions. It previously converted toint, sosystemError(errc::X, ...)interpreted it as a native code. Theerrc_toverloads preserve its generic category. When the TCP resolver reports success with no endpoints, the connector usesmake_error_code(errc::io_error)so Boost supplies the category.Portable conditions have an explicit predicate. Both equality overloads on
core::Errorcompare the numeric code and category name. Zero codes represent success. Useerror.matches(boost::system::errc::X)to ask whether a generic or native system error represents a portable condition. Boost supplies the platform mapping for native codes.On Windows,
ERROR_FILE_NOT_FOUNDandERROR_PATH_NOT_FOUNDare distinct errors. Both matcherrc::no_such_file_or_directory. The file helpers still accept only those two native codes and the generic missing-file code. Socket and file-lock callers use the condition they intend to handle.isDiskSpaceError()recognizes the portable no-space condition and POSIXEDQUOT. Atomic writes also recognize POSIX permission, read-only filesystem, busy mount point, and cross-device errors when deciding whether to try their fallback.The listener retries a busy port.
startHttpConnectionListenerWithTimeout()checkserror.matches(boost::system::errc::address_in_use)after a bind failure. Desktop and standalone sessions can retry when a previous session is releasing the port. Initialization disposes of the listener that failed to bind before creating its replacement. The POSIX TCP listener logs its configuration warnings once across retries.Error factories require a categorized code. The public
systemError()andsystemCallError()overloads reject bare integers.systemError()accepts a Boost error code or a registered Boost error-code enum in its own category, including Asio and JSON-RPC errors. Scoped standard error-code enums such asstd::io_errcwork throughstd::error_code. An unscoped enum registered only with the standard library needs an explicitstd::error_code(value).systemCallError()takes a categorized code and prefixes its message with the call name. The unknown-VCS case invcs_clonenow reportsjson::errc::ParamInvalidin the JSON-RPC category.Native calls and C runtime errors. Callers choose the category at the point where the origin of a number is known.
The 46 calls that passed an errno constant (
systemError(EINVAL, ...)) now pass the matching errc. Most are in POSIX-only files, where they were correct but are now spelled portably. The ones that compile on Windows were wrong:Win32System.cpp(getChildProcesses) andSessionContentUrls.cpp.The 3 POSIX-only test fixtures that need the native code (
FileSerializerTests) build it explicitly withsystem_category(), as the newErrorTestsdo.The Win32 CRT callers and R's
iconvstrImpl()save the runtime errno immediately after the failing call and usegenericError(saved, ...). This preserves the code across cleanup, logging, and construction of the error location.Some code built the same mistake by hand, as
error_code(errc::X, system_category()). Windows' output capture (ioError()) andTcpIpAsyncConnector's empty-endpoint error reportederrc::io_erroras "Access is denied"; both now use the generic category, as doFilePath::completeChildPath()'s two "not within the parent" errors and the POSIX-only server proxy'spermission_denied.AsyncServerTestsbuilt native POSIX codes that way; it now spells them as errno constants withsystem_category()(identical values).LAST_SYSTEM_ERROR()is Windows-only and capturesGetLastError()before constructing the source location. POSIX callers saveerrnoand pass it togenericError()or tosystemCallError()withgeneric_category()when a diagnostic includes the call name. Shared CRT callers, including the debug logger’sopen()call, use the sameerrnoconvention on Windows. APIs such aspthread_atfork()that return an error number use that return value.The R linter checks category-blind comparisons and
errcvalues paired withsystem_category().The local stream proxy rejects requests when the user lookup fails. It needs the resolved UID to verify socket ownership.
zlib and Mach return codes get their own categories.
ZlibUtil.cppandResponse.cpppassed zlib return codes (e.g.Z_DATA_ERROR, -3), andMacResources.cpppassedkern_return_tvalues, tosystemError(int). Their messages werestrerror()'s (or Win32's) for an unrelated number. A newzlib::zlibError()(inZlibUtil.hpp) and a file-localmachError()report them aszlib/macherrors withzError()/mach_error_string()messages.Visible changes besides the messages:
errcerrors and failures constructed withgenericError(savedErrno, ...), including POSIX system calls, now log and serialize with categorygeneric(thetypefield in JSON logs,categoryin RPC errors). The client checks onlyServerErrorCause.isWindowsSharingViolation()by category, and that check is for a Win32 code.strerror()text.Codes are compared as conditions, never by value against an errc (#18946).
getCode() == errc::Xandec.value() == errc::Xignore the category, so on Windows they matched whichever Win32 code shared the errc's number. They're nowerror.matches(errc::X)or boost'sec == errc::X:isResourceExhaustionError(): the accept backoff never ran on Windows, where asio reportsWSAEMFILE(10024), not 24. boost mapsWSAEMFILEandERROR_NOT_ENOUGH_MEMORY/ERROR_OUTOFMEMORYto the two errcs; the system-category guard stays.SessionChat.cpp's five "Permission denied" / "protocol not supported" checks: on WindowsERROR_ACCESS_DENIEDis 5, not 13, so file permission errors fell through to the generic message.SocketAcceptorService's destructor (WSAEBADF), and, for consistency, the POSIX-onlyLocalStreamAsyncServer/ClientandSocketOwnership.cppchecks (same result on POSIX).handleStreamError()keeps the write's error code (#18946).StreamWriterturned the asio write error into anError, andAsyncConnectionImpl::handleStreamError()rebuilt anerror_codefrom it in the generic category, because anErrorkeeps only its category's name.StreamWriternow hands its error handler theerror_codeitself, whichhandleStreamError()passes on unchanged; the session'sHttpConnectionImplgets a small adapter that logs it as before.The shared header exposes the same API to rstudio-pro. Downstream callers passing raw integers must identify their source when rebuilding. Portable condition checks use
matches(), and serializederrcerrors carry thegenericcategory.Automated Tests
src/cpp/shared_core/ErrorTests.cpp(new;rstudio-shared-core-tests, also run byrstudio-tests --scope core):ErrorTest.ErrcErrorsUseTheGenericCategory: all four errc overloads build a generic-category error with the errc's generic message, keeping the description and cause.ErrorTest.ErrcErrorsMatchTheSameErrcBuiltAnyWay:systemError(errc::X),Error(errc::X),systemError(std::make_error_code(std::errc::X)), and a genericerror_codeall compare equal.ErrorTest.DistinctCodesCanMatchTheSameConditionchecks exact equality against bothErrorand Boost error codes. On Windows it also checks that both native missing-file codes match the portable condition while remaining distinct.ErrorTest.GenericErrorsUseTheGenericCategorychecks the category, message and optional description for saved errno values.ErrorTest.ErrcErrorsDoNotMatchUnrelatedErrors: a different errc, another category with the same number, andSuccess()don't match. On Windows, system 21 (ERROR_NOT_READY) doesn't matcherrc::is_a_directory.ErrorTest.ErrorCodeEnumsUseTheirOwnCategory: an unscoped test error-code enum with its own category (unscoped likejson::errc, so it would also convert toint) keeps that category, message, description, and cause through all four overloads.Compile-time checks reject
intandunsigned longacross all foursystemErrorforms and both named-call forms.CategorizedCodesKeepTheirCategorycovers explicit codes, causes, descriptions and named-call messages.LastSystemErrorCapturesGetLastErrorchecks Win32 capture and the call site. Non-Windows builds check thatLAST_SYSTEM_ERRORis undefined.FileSerializerTest.IsDiskSpaceErrorClassifiesnow also asserts that an errcno_space_on_deviceerror is a disk-space error and an errcno_such_file_or_directoryerror is not.ZlibTest.DecompressErrorsAreZlibErrors(new): a stream whose header names compression method 0 fails with azlib-categoryZ_DATA_ERROR,zError()'s message, and the inflation description.LoggingTest.CanJsonLogErrorpinned the old behavior (typesystem, and the Win32 text on Windows); it now expectsgenericand the generic message.StreamWriter.ErrorHandlerGetsTheWritesErrorCode(new,core/http/StreamWriterTests.cpp): a stream whose writes fail with anasio.miscerror hands the error handler that exact code, category included.AsyncServerResourceExhaustion.ClassifiesResourceErrorsnow uses the codes asio reports (no_descriptors,no_memory, ...), which are native on each platform; on Windows it fails without the fix.test-linter.Rchecks production comparisons againstsystemError(errc::…)and raw code values. Fixtures cover both operand orders, multiline calls and Windows-only branches.host_statistics()/task_info()to fail, soMacResources.cpp'smachError()is covered only by the build.The Windows build runs the Windows-specific assertions in the shared-core tests. At commit
344f427171, the macOS runner passed all 2,014 C++ tests (890 core, 13 server-core, 26 shared-core, 951 rsession, 134 rserver). R testthat reported 4,850 passed, 14 skipped, zero failures and zero warnings.The listener retry has no automated test, since it needs a whole session. Checked by hand with a desktop-mode
rsessionon a port another process held:system error 48 (Address already in use).344f427171, holding the port produced 10 attempts over about a second and exit 1 withOperation timed outcaused byAddress already in use.The macOS follow-up at
aaee1a040dpassed 929 core, server-core, and shared-core C++ tests and 104 R linter expectations. A child-process callback check received Asio's original EOF category and message. Running the linter against the previous sources identified all four unsafe Win32 calls.At
437be46c0fthe full macOSrstudio-testsrun passed 2,016 C++ tests and 4,847 R expectations. The R suite reported 14 skips and zero failures or warnings.At
a053d7a326the macOS suite passed 2,015 C++ tests and 4,846 R expectations, with 14 R skips. The last-error runtime test now runs on Windows, and the macOS build checks that the macro is undefined.QA Notes
On Windows:
loadhistory(tempdir())should reportis a directory(as it does after report savehistory() / loadhistory() failures as errors on windows #19689).rsessionlogs for internal errors should read like errno messages (e.g. "Input/output error", "Invalid argument") rather than unrelated Win32 messages ("Access is denied", "The device does not recognize the command").On any platform, Desktop: start RStudio while another process listens on the port the session is given. The session now retries for about a second before failing, instead of failing at once. This is hard to arrange through the Desktop app, so the hand check above is the practical test.
Documentation
None needed.
Checklist
NEWS.md