The chunked decoder slid every payload byte down over the chunk
headers before it, so the decoded body was one run for the sink: one
copy of the whole body inside the receive buffer, on top of the
receive itself.
A sink can now take the body as runs (net_http_connection_set_sink_spans).
For such a sink, a chunk of 16 KB or more stays where it was received
and is recorded as a run; shorter chunks are still slid down onto the
end of the run before them, so the runs stay few and long. At most
16 runs are held, in the handle, so nothing is allocated mid-transfer;
with all 16 in use, further chunks are slid as before until the hand-
off. The hand-off point is unchanged: when the free window behind
the held bytes would fall below 32 KB, and at the end of the body or
when it is cut short.
task_http's download sink takes runs and writes them with
filestream_writev: one writev() on the targets that have it, so the
chunks reach the file from where they were received. An identity
body goes as one run, as before. net_http_connection_set_sink and
its sinks are unchanged.
task_push_http_download_file_with_headers is task_push_http_download_file
with extra request headers, for a server that wants authorization;
task_push_http_download_file is now that with none. The Emscripten
backend has both.
A download to a file that ends in an HTTP error response used to hand
its callback no body, so a caller could not log the server's message.
It now hands it the start of the body, up to 4 KB, read back from the
file before the file is removed; only on that error path. A
successful download still hands its callback no body, and the callers
that stream already go by their streamed flag and the error before
they look at it.
The sink now gets a download in pieces of 32 KB or more (identity
bodies), so the file it writes asks for descriptor writes: no copy
through a stdio buffer on the desktops and Android. The restart
path's seek and truncate work on the descriptor too. Where
descriptor writes are not available the hint is ignored.
An upload read the whole file into one malloc before it started: up to
the 64 MiB multipart threshold for a single PUT, and the whole file,
however large, for a multipart upload, held until its last part was
acknowledged. Out of memory the upload failed, and on the consoles the
threshold is sized for, that is not far off.
The body is now pulled from the file by net_http as the socket takes
it, through net_http_connection_set_content_source, the way WebDAV
already uploads: one send buffer instead of the file. Each multipart
part is a byte range of the file, seeked to on its first run so it
reads its own bytes whatever was read before it, and a replay on a
fresh connection rewinds to the range's start. The payload hash for the
signature is taken by reading the range in 64 KiB runs into
sha256_stream_update. The fallback to a single PUT when the multipart
start fails in transport streams the whole file the same way.
task_push_http_transfer_with_source is task_push_http_transfer_with_
content with a source in place of the buffer. The upload's URL buffers
move off the stack (4.2 KiB to 112 bytes).
s3_backup_test's stub drains every streamed body as net_http would,
with a replay from the start, and checks it is all there and is what
was signed. New lanes: an 11 MiB multipart upload (three parts, each
its own range of the file), its single-PUT fallback, and an empty file.
The multipart threshold can be set by the test for that.
A finished task stays in the queue until its callback has run, and
the duplicate-download guard found it there: the same URL pushed from
the failed transfer's callback was refused as already in flight. The
achievement badge downloader retries that way after a network error,
so every retry was dropped, the badge's callback data leaked and the
badge queue stalled.
A finished transfer is no longer in flight, and the guard passes it
over now, in task_http.c and task_http_emscripten.c alike.
http_transport_failure_test gains a lane that fails a GET and pushes
the same URL from its callback: the retry must be taken and reach its
own callback. It fails on the old code.
net_http_update_budget() drains the socket while a caller-supplied
window allows, one read - with the TLS decryption behind it, and still
at most NET_HTTP_DRAIN_BUDGET (256 KiB) - per work item, instead of up
to a fixed 256 KiB per call; net_http_update() is that call without a
window and drains exactly as before. task_http.c passes the shared
per-frame I/O window, so a transfer moves as much a frame as its share
of the window allows on any link and any cipher speed: with the task
queue unthreaded, ten core updates totalling 180 MB download in 1.8 s
instead of 30.6 s; threaded transfers are unchanged.
http_transfer_stress_test gains a window lane: a window of one item per
update gets exactly one read per update, an unbounded one clamps every
read to 256 KiB and drains in fewer updates, and the body arrives intact
both ways. The http samples linking task_http.c now link
task_nbio_slice.c.
A download to a file - task_push_http_download_file(), which the core
updater and playlist thumbnails use - that lost its connection part way
through failed outright and deleted what it had. On a flaky link a
large core or asset bundle could fail at 90% every time.
It now picks up where it stopped, inside the same task:
- On the first response, a 200 that advertises "Accept-Ranges: bytes"
and a strong ETag (or else Last-Modified) makes the download
resumable. A weak ETag cannot validate a byte range.
- When the transfer then fails in transport mid-body - not an HTTP
error, not a full disk, not a cancel - the task opens a new request
for the same URL with "Range: bytes=N-" and that validator in
If-Range, N being what is already on disk, and keeps writing to the
same file.
- A 206 must continue exactly at N (Content-Range is checked); a 200
means the server sent the whole resource again - it ignored the range,
or If-Range found it changed - and the file starts over; anything
else fails the download and removes the file, as before.
- At most three resumes, each only after progress.
A completed resumed download reports status 200 to the callback, since
the whole file was delivered (the thumbnail callback checks for exactly
200), and progress covers the whole file rather than the last slice.
net_http gains net_http_header(), a lookup of a response header while
the transfer is still running, which is what the sink needs to decide.
Two task_http fixes on the way: a failed download to a file set its
error string twice and leaked the first, and a task cancelled before
its connection became a transfer leaked the connection.
New samples/tasks/http/http_resume_test drives the real task_http.c,
net_http.c and task queue against a scripted server: resumed once,
resumed twice, resource changed (the new body alone, not spliced),
wrong Content-Range, no validator (no resume tried), and a connection
that drops every time (fails after three resumes). Six of its checks
fail on the previous code, where every one of these downloads failed.
Every transfer allocated a string_list for its response headers: the
struct, a 32-slot array, and a strdup per header line, then freed all
of it when the task finished - on the task thread, or on the video
thread in an unthreaded build. A typical response has 10 to 20 lines;
a 64-line one cost 67 allocations before a byte of body arrived.
The headers now go into one block as they are parsed: each line
NUL-terminated, an empty line at the end, grown by doubling from 1 KiB
and bounded by the existing 64 KiB header cap. It is allocated with
the first header line (a failed connect allocates nothing) and handed
over whole. In the harness, 64 header lines cost one allocation more
than one line does. The Location offset replaces the pointer into the
list, since the block may move as it grows.
API:
net_http_headers_take() the block, ownership to the caller (free());
same NULL rules as net_http_headers_ex()
net_http_header_next() walk the lines
net_http_header_value() first field by name, case-insensitive
net_http_body_is_framed() takes the block
net_http_headers() / net_http_headers_ex() remain for code outside
RetroArch, building a string_list from the block on demand; nothing
in-tree calls them.
http_transfer_data_t.headers is the block. task_http hands it over
and frees it; task_core_updater frees it; the emscripten backend
compacts the browser's header text into the same layout in the buffer
it already had, so it also drops to one allocation. WebDAV, S3 and
Google Drive walk it with net_http_header_next(), and S3's ETag lookup
uses net_http_header_value(). The WebDAV, S3, transport-failure and
cheevos harnesses build or take blocks; the S3 harness links net_http.c
for the helpers.
A WebDAV upload read the complete file into a buffer, and
net_http_connection_set_content() then copied that buffer again, so
two copies of the file sat in memory for the whole transfer. Saves are
small, but a save state is not, and several uploads run at once.
net_http gains a request-body source: net_http_connection_set_content_source()
takes a Content-Length, a read callback and an optional rewind
callback. net_http_send_request() pulls the body from the source in
64 KiB runs and sends each as it arrives, so one run is all that is
ever held; a source that delivers fewer bytes than the advertised
length fails the request as a transport error would, since the header
has already promised them. When a request has to be replayed on a
fresh connection the source is rewound first; a source with no rewind,
or one whose rewind fails, is not replayed.
task_push_webdav_put_stream() wraps that for the task queue, and the
cloud-sync WebDAV driver uploads straight from the open RFILE through
filestream_read, rewinding with filestream_seek. The existing seek to
the start before the upload is kept, as the Digest-challenge retry
still reaches this path with the file at its end.
Checked with a 3 MB body PUT to a local server: the received body is
byte-identical (SHA-256) and the request completes with 201.
With destructive sync off, a WebDAV delete moves the server's file
into deleted/, but an upload overwrote it in place: the setting
protected against the server's copy being removed and not against it
being replaced, which is the more likely way to lose a save (an older
or broken save from another device overwriting a good one). The code
carried a TODO/FIXME for exactly this. The local side already keeps
cloud_backups/ before a fetch replaces a local file.
An upload now copies the server's file to deleted/<path>-<yymmdd-
hhmmss>, the name a delete uses, before the PUT. COPY rather than
MOVE, so the server keeps its file until the PUT replaces it, and an
upload that fails after the backup leaves the server as it was. A 404
means there is nothing to back up yet; any other failure stops the
upload rather than overwrite without a backup. The COPY and the PUT
each get their own Digest retry. The server manifest is rewritten
every sync and is not backed up; its name moves to
cloud_sync_driver.h as CLOUD_SYNC_SERVER_MANIFEST so the driver can
recognise it.
Adds task_push_webdav_copy() beside task_push_webdav_move() in both
HTTP backends, sharing the Destination-header code.
samples/network/webdav_backup includes webdav.c and plays the server
request by request: backup before PUT, into deleted/ named as a delete
names it, 404 not an error, a failed backup stopping the upload with
one failure report, destructive sync and the manifest not backed up,
and a Digest retry each for COPY and PUT. Against the old driver 5
checks fail. Runs in CI Linux samples/network under ASan+UBSan and
TSan; the other WebDAV harnesses gain the new stub.
A transfer driven from a task thread has nothing to pace it, so
task_http_iterate_transfer() slept a millisecond between passes whether
or not the peer had answered - paid in full even when the bytes were
already there, and a transfer of n passes cost n milliseconds of pure
delay. The FIXME on it asked for a wait with a timeout.
net_http_wait() is that wait. It knows which way the transfer is going,
so it waits for writability while connecting or sending and for
readability once the request is out, and it returns the moment the
transport is ready rather than at the end of a fixed interval. The
unthreaded queue is paced by the frame and waits for nothing, as before.
What makes it safe to wait at all is knowing when there is nothing to
wait for. A pass that stopped on its own drain budget left bytes
buffered and must not block, and the same is true inside the TLS layer,
where decrypted bytes can be held after the socket has gone quiet; only
the receive path's EAGAIN exit has handed over everything it holds, so
only that exit marks the transfer as blocked and every other outcome
returns from the wait immediately.
The stress harness covers a wait that returns on data rather than on the
timeout, a wait with no socket to wait on, and a peer that accepts and
then never answers, which is the case that has to come back on the
timeout rather than hang.
A transfer that never reaches a status now reports where it stopped.
net_http keeps the first failing stage ("dns_lookup_failed",
"ssl_connect_failed", ...) and, for the TLS stages, the library's own
error through the new ssl_socket_last_error(), which both backends
implement: the last mbedtls return code from config, setup, hostname
or handshake, and BearSSL's engine error. net_http_failure() hands
them to the task layer, whose error string becomes
"Download failed: ssl_connect_failed (-0x7200)." rather than
"Download failed.", and the webdav failure line appends it whenever
the status is -1.
This is what a log from a console can carry: the transport logger
only exists in DEBUG builds and writes to stderr, so a Vita that could
not complete a handshake had nothing to show but "HTTP -1". The
mbedtls code is printed in the form its error table uses, so -0x7200
reads as MBEDTLS_ERR_SSL_INVALID_RECORD without a debug build
(libretro/RetroArch#19475).
strlcpy() begins with strlen() of its source. It lives in another
translation unit, so with no LTO that scan happens at runtime even when
the source is a literal whose length the compiler already measured, and
the call itself cannot be folded away either.
strlcpy_lit() passes the length over as sizeof(). When the destination
size is also a constant -- sizeof(buf), the usual case -- nothing is
left but the stores memcpy() compiles to:
strlcpy "core_options" sizeof(buf) 7.01 ns
strlcpy_lit "core_options" sizeof(buf) 0.42 ns
strlcpy 41-char literal sizeof(buf) 7.74 ns
strlcpy_lit 41-char literal sizeof(buf) 0.71 ns
strlcpy "core_options" runtime len 7.11 ns
strlcpy_lit "core_options" runtime len 0.70 ns
The destination bound is kept. When the literal does not fit it defers
to strlcpy(), so the copy truncates as before rather than overrunning;
a form that took only the literal would have turned every one of these
sites into an overflow waiting for a small buffer. The literal is
concatenated with "" so a non-literal source is a compile error rather
than a sizeof() that silently measures a pointer.
818 sites across 104 files were converted by parsing arguments rather
than by pattern-matching text: only a three-argument call whose second
argument is a bare string literal is rewritten, so a macro that happens
to expand to a literal is left alone. Line endings are preserved, so
the CRLF files carry only their own changed lines.
test/compat/test_strl.c compares the two against each other over every
destination size from 0 past the literal's length, for literals that
are empty, single-character, path-shaped, adjacently concatenated and
escape-bearing, checking the return, the terminator and the whole
buffer so an overrun past the terminator is caught. ASan+UBSan+LSan and
TSan both 4/4. The full menu_displaylist_build_list walk over every
displaylist type is byte-identical to before the change
(md5 a2a081bcac09cdc8d72d67efd14ac40e).
net_http_new() allocates response.data up front as the receive buffer,
64KiB of plain malloc(). On a transport failure -- DNS, connect(), or
a socket error before the status line -- nothing is written into it
and response.len stays 0, but the pointer is non-NULL, and
net_http_data()'s accept_err skipped the status check and returned it.
So every failed download published uninitialised, unterminated heap as
http_transfer_data_t::data. On a body torn mid-transfer it was worse:
response.len is the Content-Length remainder there, not the bytes that
landed, so a consumer copying data->len read heap that never arrived
off the socket.
Every give-up path already resets response.status to -1, and
net_http_new() initialises it so; both accessors now key off that and
return NULL, leaving ownership with the handle so net_http_delete()
reclaims the buffer.
task_http.c gated task_set_error() on RETRO_TASK_FLG_MUTE, which only
ever suppressed the on-screen notification in
task_queue_push_progress(); task->error is a separate channel handed
to the callback unconditionally. Muted is the common case for internal
traffic, and task_core_updater.c's list callback computes
`data && (!err || !*err)`, so an unreachable host looked like a
successfully downloaded empty core list.
Adds samples/tasks/http/http_transport_failure_test.c and wires it
into the samples-tasks-http CI job: four failure lanes entering
net_http_update() at four different points, two contrast lanes (a 200
and a 404 must still deliver their bodies) and two task lanes, muted
and unmuted. getaddrinfo is wrapped at link time so the DNS lane
cannot quietly start testing a successful lookup. Twelve checks fail
on the pre-fix tree; both contrast lanes pass there.
Verified: new test 47/47 under ASan+UBSan with leaks on, and TSan;
existing http samples unchanged; C89 gate clean.
Fixes a SIGSEGV inside task_http_finder(), reported on Windows:
#0 strcmp ()
#1 task_http_finder ()
#2 retro_task_threaded_find ()
#3 task_push_http_transfer_generic_titled ()
#4 task_push_http_download_file ()
#5 download_pl_thumbnail ()
task_http_transfer_handler() freed its http_handle_t as soon as it set
RETRO_TASK_FLG_FINISHED. But a task stays *findable* long after its
handler is done: retro_task_threaded_find() scans the running,
finished and retiring lists, and task_http_finder() dereferences
task->state on every candidate it is handed. task->state therefore
dangled for the entire window between the last handler tick and full
retirement, and any push racing a finishing download read freed
memory.
This is not new. It survived because connection_url was an inline
char[NAME_MAX_LENGTH]: reading a freed-but-still-mapped array yields
stale bytes and strcmp() plods through them harmlessly. Making
connection_url a pointer -- so that long URLs stopped defeating the
duplicate-download guard -- turned the same read into "load the freed
chunk's tombstone and dereference it". The pointer change did not
introduce the defect, it removed the padding that was hiding it, and
the thumbnail downloader moving to task_push_http_download_file() put
far more pushes alongside far more retirements.
The handle is now released in task_http_transfer_cleanup(), which the
queue calls during retirement, with task->state cleared first. Same
change in the emscripten backend, which had the identical shape.
Also closes the narrow window underneath it in task_queue.c.
retro_task_internal_retire_body() ran the callback and cleanup with
neither lock held while the task was still in tasks_retiring, which
find() scans. cleanup() is where a task releases task->state, so that
raced any concurrent find(). Retirement is split: the callback still
runs while the task is findable, since it may push follow-up tasks and
so cannot hold finished_lock, but cleanup now runs only after the task
has been pruned from the retiring list and is unreachable.
Separately, 56d5967 left a C90 violation in task_core_updater.c --
output_dir, http_title and _tlen declared after the calloc/goto that
precedes them:
tasks/task_core_updater.c:822:13: error: ISO C90 forbids mixed
declarations and code [-Werror=declaration-after-statement]
Declarations moved to the top of the block. No behavioural change.
TESTS
samples/tasks/http/http_task_lifetime_test.c is the lane that was
missing, and its absence is why the crash shipped. The other HTTP
samples drive net_http.c directly, which covers the protocol engine
well and the task layer not at all -- and the task layer is where this
lived. It links the real task_http.c and the real task_queue.c,
threaded, against a loopback server, stubbing only msg_hash_to_str()
and task_window_progress_cb(); neither participates in lifetime.
Threads push GETs over a small set of URLs while the queue finishes
and retires earlier ones, so every push walks all three lists and
collides with retirement continuously.
Verified in both directions: with the teardown moved back into the
handler it reports heap-use-after-free with the same stack as the
crash above and exits 1; with the fix it is clean. ASan is what makes
it assertable at all -- a use-after-free on a recently freed chunk
otherwise reads plausible bytes and passes.
A new Makefile.dedup lets http_url_dedup_test run under the
sanitizers and at both NAME_MAX_LENGTH values.
CI
A samples-tasks-http job is added to Linux-samples-tasks.yml covering
all five HTTP samples, each under the sanitizers that can catch its
defect, plus a syntax-only C89 pass over the five translation units
this area touches. That last step exists because the mixed
declaration above reached master: the full C89 build in retroarch.yml
does catch it, but only after a configure and a complete build, and
the C99 habit of declaring at first use is silent under the default
build. The syntax pass fails in seconds instead.
_GNU_SOURCE is added on top of the Makefile's C89_BUILD flag set
because -ansi otherwise hides the POSIX prototypes (strdup and
friends) these files legitimately use, burying the dialect errors
being checked under unrelated int-conversion noise -- an artefact
worth naming, since a check calibrated wrongly is worse than none.
It runs as its own job so the existing samples-tasks budget is
untouched; the whole job takes well under a minute locally. Every
step body was executed verbatim before committing, and both the
lifetime step and the C89 step were confirmed to exit 1 on a
reintroduced regression.
VERIFICATION
Full sweep, 27 configurations: all five HTTP samples across baseline,
ASan, TSan, UBSan and ASan+UBSan, with detect_leaks=1 and
detect_stack_use_after_return=1 throughout, plus the dedup sample at
both NAME_MAX_LENGTH values. All pass; no sanitizer report of any
kind across the whole sweep log. Explicit LeakSan-only runs of the
three socket-driven suites are clean, which is meaningful because the
stress suite calls net_http_deinit() -- without it the DNS cache and
connection pool hang off file-scope globals and count as still
reachable.
net_http.c, task_queue.c, task_http.c, task_core_updater.c and
task_pl_thumbnail_download.c compile clean and pass the exact
C89_BUILD flag set; task_http_emscripten.c verified with emcc 6.0.5 at
-Wall.
Three loose ends from the HTTP task audit.
1. The duplicate-download guard silently stopped guarding.
Both backends stored the request URL in
char connection_url[NAME_MAX_LENGTH] via strlcpy, but
task_http_finder() compares that stored copy against the raw candidate
URL. Truncation on the stored side alone means that once a URL
reaches NAME_MAX_LENGTH -- 256, or 128 on the small-path platforms --
the two can never compare equal, so the check whose comment reads
"Concurrent download of the same file is not allowed" returned false
for every candidate.
The failure is one-directional and therefore silent: truncation cannot
conflate two distinct URLs, since the candidate is never truncated to
match, so nothing broke loudly and downloads just stopped being
deduplicated. Playlist thumbnail URLs exceed the buffer routinely,
concatenating a long CDN base path with a percent-encoded game title.
The cost is not just bandwidth: both tasks reach their completion
callback, and cb_http_task_download_pl_thumbnail() ends in
filestream_write_file() on an identical path. Two writers, one file.
connection_url is now a heap-owned copy of the full URL in both
backends. NULL means "no key" and matches nothing, so an allocation
failure admits a redundant download rather than dropping one -- the
safe direction, since a dropped push strands the caller's completion
callback forever. samples/tasks/http/http_url_dedup_test.c, which
landed red documenting this, now passes at both NAME_MAX_LENGTH
values; it keeps the old fixed-buffer shape as a second oracle so a
revert is caught.
Two small ones alongside it, both in task_http.c:
cb_http_conn_default() returned -1 on network_init() failure without
setting http->error, and the caller discards the return value -- so
the task advanced with a NULL handle, net_http_update(NULL, ...)
returned true immediately, and it finished with neither data nor an
error, which callers read as a clean success with task_data == NULL.
And HTTP_STATUS_TRANSFER_PARSE / _PARSE_FREE were never set by
anything, so the enumerators and the case handling one of them were
dead.
2. net_http_init() / net_http_deinit().
The locks guarding the DNS cache and connection pool were created
lazily on first use:
if (!dns_cache_lock) dns_cache_lock = slock_new();
which is an unsynchronised first-use initialisation of the very lock
meant to serialise that cache. Two threads arriving together each
create one, one store wins, and the loser goes on locking an object
nobody else holds. It does not reproduce once the locks exist, which
is why a TSan run over concurrent transfers came back clean -- the
window is only ever the first two requests of the process.
There was also no teardown at all: pooled sockets and their SSL
contexts, cached addrinfo, the strdup'd domains and both mutexes lived
until the process exited. LeakSan could not see any of it, since the
lists hang off file-scope globals and so count as still reachable.
net_http_init() is called from retroarch.c immediately before
task_queue_init(), which is what spawns the task thread;
net_http_deinit() after task_queue_deinit(), so no transfer can still
hold a pooled connection. deinit detaches both lists under their lock
and drains them with it released -- net_http_resolve() takes the same
lock at the end of its run, so joining a resolver thread while holding
it would deadlock.
3. Core downloads stream to disk.
cb_http_task_core_updater_download() buffered the whole core in RAM
and wrote it in one go, which is what task_push_http_download_file()
was added to avoid. Everything that gated the write --
path_mkdir() and the "decompression already in progress" check -- now
runs before the transfer starts rather than after it, which is the
reordering that made this worth doing separately. The
already-decompressing check matters more in the new position, not
less: it now prevents overwriting a file another task is reading,
where before it merely declined to.
The callback keeps the output_dir computation for the decompress call
and gates on data->status, since the partial file is removed unless
the transfer finished cleanly with a 2xx.
Sample suite extended to 92 checks, including a teardown case that
deinits, re-inits and transfers again -- calling deinit is what makes
any real leak in the cache and pool visible to LeakSan. Clean under
ASan, LSan, UBSan and TSan. net_http.c, task_http.c and
task_core_updater.c compile clean; task_http_emscripten.c verified
with emcc 6.0.5 at -Wall; retroarch.c hunks are the two
net_http_init/deinit calls and one include.
Responses were accumulated whole in RAM and only then written out, so
a core download held its entire payload -- up to the 256 MiB
NET_HTTP_MAX_CONTENT_LENGTH ceiling -- as anonymous memory for the
life of the transfer, and then copied all of it a second time through
filestream_write_file(). Worse, T_LEN sized the receive buffer to
Content-Length the moment the headers parsed, so a server's advertised
length alone drove the allocation before a single body byte arrived.
net_http_connection_set_sink() attaches a callback that receives each
run of decoded body bytes as it arrives. With a sink set the buffer
stays at the receive window, the Content-Length preallocation is
skipped, and net_http_data() returns NULL/0 since the handle retains
nothing; status and headers are unaffected. A sink returning false
aborts the transfer like any transport failure, which is how a full
disk surfaces instead of a silently truncated file.
Measured with the sample harness on a 4 MiB body: the buffered path
peaks at 4128812 bytes of receive window, the streamed path stays
under 1 MiB regardless of payload size.
Flushing is per body type, since pos/len mean different things in
each. T_LEN decrements len by what it hands off so the existing
"pos == len" completion test keeps working untouched, with the
advertised total moved to a new content_len field for progress
reporting. T_FULL flushes and resets both. T_CHUNK flushes at three
points -- mid-chunk carry-over, chunk straddling the receive window,
and end of parse pass -- sliding the unconsumed raw tail to the front
each time so the decoder's invariant (len is the decoded offset of the
current chunklen line) still holds at zero. Progress now reports
flushed + pos rather than pos alone.
None of the flush paths run without a sink, so the default behaviour
is byte-for-byte what it was.
task_push_http_download_file() is the task-layer entry point: it opens
the destination before the transfer starts, so a bad path fails the
push rather than surfacing megabytes later, and removes the partial
file unless the transfer finished cleanly with a 2xx -- a leftover
partial would otherwise be indistinguishable from a good core on the
next run. The completion callback gets status and headers with
data == NULL.
The emscripten backend implements the same entry point by writing
through in its settle callback. The browser buffers the whole
response either way, so it is not a memory win there; it exists so
both backends honour one contract.
Sample coverage extended to 91 checks: body reconstructed
byte-for-byte through the sink across all three framings, at chunk
sizes down to 1 and with the server dribbling bytes so every boundary
is torn; the handle retaining nothing; a sink write failure aborting
rather than truncating; and a peak-window ceiling. That ceiling is
paired with a contrast case asserting the *buffered* path exceeds it,
so the test cannot quietly pass by both paths happening to stay small
on a given host.
Clean under ASan, LSan, UBSan and TSan.
Not migrated here: cb_http_task_core_updater_download() still buffers.
It calls path_mkdir() and the "decompression already in progress"
check after the download completes, both of which have to move ahead
of the transfer before it can stream, and that reordering wants
testing against a real build rather than the loopback harness.
Build on the task_window_progress_cb helper introduced in d1228e6
and propagate the Win32 taskbar progress overlay (and any other
platform window progress hook) to more long-running user-visible
tasks.
Helper relocation:
- Move the implementation from task_http.c (HAVE_NETWORKING-gated)
to task_file_transfer.c (always built), so non-network tasks
can use it without pulling in HAVE_NETWORKING.
- Move the prototype in tasks_internal.h out of the HAVE_NETWORKING
block for the same reason.
- Drop the duplicated copy in task_database.c
(task_database_progress_cb) in favour of the shared helper, and
the now-unused video_display_server.h include alongside it.
New coverage:
- task_pl_thumbnail_download.c: the system-wide bulk thumbnail
download task. Long, user-initiated, already drives
task->progress monotonically across two outer phases.
- task_cloudsync.c: cloud sync, which can be very long and reports
progress as files are reconciled.
- task_core_backup.c: both the backup and restore outer tasks, so
user-initiated backup/restore of cores reflects on the taskbar.
The single-entry pl_thumbnail outer task and short-running tasks
(decompress, disc scan, playlist manager, menu explore) are left
unchanged for now -- they finish too quickly for the taskbar
indicator to be useful, and adding them is a trivial follow-up if
that turns out to be wrong.
The Win32 taskbar progress overlay (the green bar drawn on the
RetroArch taskbar icon during downloads) never appeared. Two
independent bugs were keeping it dark:
1) wndproc: the 'TaskbarButtonCreated' message check was nested
inside unrelated 'case' arms (WM_MOUSEMOVE..WM_NCLBUTTONDBLCLK,
WM_DROPFILES..WM_COMMAND, and the WM_PAINT branch of the GDI
wrappers). Since 'TaskbarButtonCreated' is a registered window
message with its own dynamically-allocated value, those arms
could never match it, so WIN32_CMN_FLAG_TASKBAR_CREATED was
never set and dispserv_win32's set_window_progress() always
early-outed without calling ITaskbarList3::SetProgressValue.
Move the comparison to the top of each dispatcher
(wnd_proc_common, wnd_proc_common_internal,
wnd_proc_winraw_common_internal, wnd_proc_common_dinput_internal)
so it sees every incoming message. Short-circuit on the flag
bit so the comparison only runs until the message arrives once.
The HAVE_TASKBAR gate is unchanged; pre-Win7 builds either don't
define it or fall back through the existing taskbar_list NULL
guard in dispserv_win32.
2) task_core_updater: even with the flag set, the five outer
aggregating tasks (get_list, single download,
update_installed_cores, play_feature_delivery_install,
play_feature_delivery_switch) never set a progress_cb. They
spawn inner http transfers with mute=true to suppress per-core
on-screen toasts, which also suppresses the inner tasks'
progress_cb invocation in task_queue_push_progress(). Net
result: video_display_server_set_window_progress() was never
being called during a Core Updater run.
Promote the existing http progress forwarder
(http_transfer_progress_cb in task_http.c) to a public helper
named task_window_progress_cb, declare it in tasks_internal.h,
and wire it as the progress_cb of all five outer tasks. The
aggregating tasks already drive task->progress in 0..100 across
their state machines, so no other plumbing is needed.
Single-zip update flows (Update Assets, Update Cheats, Update
Databases, etc.) were already working because their underlying
http transfer is unmuted and titled, and the existing progress_cb
fired for those.
Apply strlcpy_append (commit 78c52ab) to seven sites flagged
in the strlcpy-misuse audit, all sharing the same shape:
_len = strlcpy(dst, src1, sizeof(dst));
dst[_len] = c1;
dst[++_len] = c2;
...
strlcpy(dst + _len, src2, sizeof(dst) - _len);
None of these had a bound on _len. When src1 was longer
than sizeof(dst) - 1, strlcpy returned strlen(src1) >=
sizeof(dst) and:
- the dst[_len], dst[++_len], ... character writes ran
off the end of dst (stack buffer overflow);
- the trailing strlcpy got len - _len which underflowed
size_t, producing an unbounded copy.
Sites:
menu/drivers/materialui.c:8090 - "Draw message box".
dst is msg[NAME_MAX_LENGTH] which is 128 on Xbox1, 3DS,
PSP, PS2, GameCube, Wii, WiiU, PS3, Emscripten and 256
elsewhere. src1 is menu_st->input_dialog_kb_label[256]
(always 256 regardless of platform). On the small-
NAME_MAX_LENGTH platforms a long label drove _len up to
~255 and the chain wrote up to 127 bytes past the stack
frame. Reachable from any input dialog.
tasks/task_http.c:495 and tasks/task_http_emscripten.c:312 -
download status string. dst is tmp[NAME_MAX_LENGTH];
src1 is the localized "Downloading" string. Same
primitive on small-NAME_MAX_LENGTH platforms when a
translation pushed the prefix close to the cap.
menu/cbs/menu_cbs_sublabel.c:2164 - core backup CRC sublabel.
The chain wrote 8 character bytes ("00000000") plus a NUL
after the localized "Backup CRC: " prefix. dst is the
caller's s/len; if a translation pushed the prefix close
to len, the 9 byte writes ran past the caller's buffer.
steam/steam.c:449/471/493 - rich-presence content strings.
Three near-identical cases (CONTENT_SYSTEM, CONTENT_CORE,
CONTENT_SYSTEM_CORE). Each builds "LABEL (CONTENT)" or
"LABEL (N/A)" with hand-unrolled writes of " (", "N/A",
"/", "A", ")", "\0" at offsets _len + N. dst is
content[PATH_MAX_LENGTH] (512 on small platforms, 4096
elsewhere) and the per-character write offsets reached
_len + 12 on the SYSTEM_CORE variant; long labels OOB-
wrote up to 12 bytes past content.
Replace each chain with a sequence of strlcpy_append calls
on a single rolling cursor, with the helper handling the
bound check at every step. No functional change at the
buffer-fits-comfortably end; on small buffers the new code
truncates cleanly instead of stack-overflowing.
No new tests -- the strlcpy_append regression test from
commit 78c52ab covers the helper's contract; these are
just additional users.
task_push_http_transfer_file() was assigning t->title AFTER
task_push_http_transfer_generic() had already published the task to
the queue with task_queue_push(). Worker threads can pick up,
execute, and finalise (free) a published task at any time --
retro_task_regular_gather() / task_queue_remove_finished() does
free(task->title); free(task) once RETRO_TASK_FLG_FINISHED is set
(task_queue.c:213-222). If the network request resolves to an
instant failure (DNS failure, ENETUNREACH while offline, immediate
cancel) or the worker simply schedules through the task quickly
under load, the worker reaches free(t) before the file helper
writes t->title. The post-push write is then a heap-use-after-free.
Symptoms in the wild: glibc malloc_printerr / abort during
download-heavy startup paths (core updater, asset/thumbnail packs),
backtrace pointing into task_http_transfer_cleanup or task_queue
finalise, no obvious smoking gun in the source it points at.
Fix: split task_push_http_transfer_generic() into a titled variant
that sets t->title before task_queue_push(). The non-titled wrapper
preserves the existing behaviour for the seven other callers (POST,
WebDAV verbs, content-bearing requests) which do not assign title.
task_push_http_transfer_file() now builds the title string locally
first and passes it through, eliminating the post-publication write.
Verified with an ASan harness mirroring the wo
task_push_http_transfer_generic() decided whether a request is a "plain"
GET (and therefore subject to dedup via task_http_finder) by doing:
method = net_http_connection_method(conn);
if (memcmp(method, "GET", 3) == 0 && method[3] == '\0')
`method` is a pointer into a buffer that net_http_connection_new()
strdup'd from caller-supplied data; its allocation is exactly
strlen(method) + 1 bytes. Two cases overrun that buffer:
1) method == NULL. task_push_http_transfer_with_content() forwards the
caller-supplied `method` argument straight to net_http_connection_new()
without a NULL check; net_http_connection_new() itself permits a NULL
method (conn->method stays NULL). net_http_connection_method() then
returns NULL and the memcmp dereferences it.
2) method shorter than 3 chars (e.g. "" or a 1-char custom verb).
strdup allocates 1 or 2 bytes; memcmp reads 3 bytes regardless,
overrunning the heap allocation. AddressSanitizer reports:
==N==ERROR: AddressSanitizer: heap-buffer-overflow
READ of size 3 at <addr> thread T0
#0 ... memcmp
#1 task_push_http_transfer_generic tasks/task_http.c:274
<addr> is located 0 bytes after 2-byte region [...,...]
allocated by thread T0 here:
#0 ... strdup
#1 net_http_connection_new
The trailing `method[3] == '\0'` guard happens *after* memcmp's read,
so it cannot prevent the overflow.
Replace the unsafe pair with string_is_equal(), which is bounded by the
buffer's own NUL terminator and is already used elsewhere in this file
(see task_http_finder at line 242 and the existing #include of
<string/stdstring.h>). Add an explicit NULL guard for the method that
takes the existing error path; this also frees `conn` via the goto so
the existing ownership invariant on the error label is preserved.
Add a standalone regression test under samples/tasks/http/ and wire it
into Linux-samples-tasks CI. The test mirrors
samples/tasks/decompress/archive_name_safety_test.c: it keeps a
verbatim copy of the predicate (the dispatch decision is local to
task_push_http_transfer_generic and not in a public header) and
exercises it against the truth-table plus the bounds-safety regression
cases ("", "X", "GE", NULL). Inputs are strdup'd so each buffer's
allocation is exactly strlen+1, matching what net_http_connection_new()
does and making the pre-fix expression trip ASan in CI.
The Makefile honours SANITIZER= the same way samples/tasks/database/
does, and the new CI step builds with SANITIZER=address so a regression
to any unsafe expression is caught at the bounds level, not just the
truth-table level. Verified locally: with the post-fix predicate the
test passes clean under ASan; reverting the predicate to the pre-fix
memcmp causes ASan to abort with "heap-buffer-overflow ... READ of
size 3" on the empty-string case.
build-essential on ubuntu-latest already pulls libasan via gcc-13's
libgcc-13-dev, so no apt-get changes are needed in the workflow.
Found via a focused ASan harness around the task_http.c finish-path
ownership logic.
Swept through tasks/ looking for unchecked malloc/calloc/realloc
returns followed by dereferences that would NULL-segv on OOM.
Fixes span 12 files and 22 individual sites; split by file:
* task_save.c (5 fixes):
- task_save_handler_finished: task_data calloc was
unchecked before a memcpy(task_data, state, ...) that
NULL-derefs on OOM. Now NULL-checked; on failure the
task_set_data attachment is skipped and save_state_cb /
undo_save_state_cb consume NULL via their own NULL checks
(added below).
- save_state_cb (consumer for task_save_handler_finished):
previously assumed task_data non-NULL and called
strdup(state->path) unconditionally. Now early-returns on
NULL task_data.
- content_load_state_cb (consumer for task_load_handler_
finished): previously dereferenced load_data->size / ->data
at variable initialisation time. Now NULL-checks first,
hoisting the field reads past the guard.
- content_load_and_save_state_cb: previously dereferenced
load_data->path / ->undo_data / ->undo_size / ->flags.
Now delegates to content_load_state_cb on NULL (which
handles NULL safely) and skips the save push.
- task_load_handler_finished: on calloc failure the
old code early-returned without freeing the on-thread
'state' struct or setting a task error - a pre-existing
leak plus silent failure. Now frees state->data + state
and sets a task error so the user sees the failure.
* task_translation.c (1 fix):
- PNG decode path: raw_image_data malloc unchecked;
the indexed write in the conversion loop NULL-derefs.
NULL-check + 'goto finish' (which NULL-safely frees
raw_image_data_alpha and rpng).
* task_patch.c (2 fixes):
- apply_patch_xdelta: *targetdata malloc unchecked;
xd3_decode_memory writes into it. NULL-check + set
PATCH_TARGET_ALLOC_FAILED + goto cleanup_stream (matching
the explicit ENOSPC handling below).
- indexed patch scan: four mallocs for
name_ips_indexed / name_bps_indexed / name_ups_indexed /
name_xdelta_indexed were unchecked before four strlcpy
calls that NULL-deref. Joint NULL-check returns true
early (same observable result as no extra patches found).
* task_database.c (1 fix):
- database_info_list_iterate_found_match: db_crc +
entry_path_str mallocs unchecked before the '[0] = \\0;'
stores that NULL-deref. Joint NULL-check frees whichever
succeeded and returns SCAN_VERDICT_ERROR so the scanner
moves on to the next content entry cleanly.
* task_audio_mixer.c (2 fixes):
- task_push_audio_mixer_load: nbio->path strdup was
unchecked; downstream strdup(nbio->path) in the ogg
upload handler is UB on NULL (POSIX). NULL-check +
goto error.
- task_push_audio_mixer_load_and_play: identical twin
pattern, identical fix.
(Note: these are NOT the audio_mixer UAF that was separately
reverted upstream as 4be8b20. Those were in
audio/audio_driver.c; these are in the task enqueue path.)
* task_decompress.c (3 fixes):
- file_archived: callback_error malloc unchecked
before strlcpy. NULL-gate the error-string population
(skipping leaves task->error NULL, which task_set_error
and downstream consumers handle).
- file_decompressed: same twin pattern, same fix.
- task_decompress_handler_finished: data calloc
unchecked before data->source_file = ... write. On OOM
free source_file (which would otherwise leak via the
skipped task_set_data) and set a task error.
* task_database_cue.c (3 fixes):
- PS2 detect_ps2_game: disc_data malloc unchecked
before intfstream_read, which writes via fread (no NULL
guard on destination). NULL-check + return 0, matching
the PS1/PSP twin patterns above/below which already had
this check.
- track_extract first variant: data malloc unchecked before
intfstream_read. NULL-check + goto error.
- track_extract second variant: twin pattern, twin fix.
* task_http.c (1 fix):
- task_http_transfer_handler: http_transfer_data_t malloc
unchecked before data->data / ->len / ->headers /
->status writes. On OOM free the already-fetched 'tmp'
buffer (data was about to take ownership) and set a task
error. Moved 'bool mute;' declaration into the success
branch to avoid an unused-variable warning on the failure
branch.
* task_wifi.c (1 fix):
- task_push_wifi_connect: task->user_data malloc
unchecked before memcpy. On OOM free task->title and the
task itself, return false so the caller sees a clean
failure.
* task_content_disc.c (1 fix):
- dump-cue DUMP_STATE_WRITE_CUE: cue_data calloc
unchecked before filestream_read. NULL-gate the read;
cue_data is actually unused after the read (only passed
to free at the bottom of this block), so skipping the
read has no further consequence beyond the failed read
itself.
* task_autodetect_blissbox.c (2 fixes):
- lp_device_path LocalAlloc unchecked before
strlcpy NULL-derefs. NULL-check + 'continue' to advance
the inner SetupDiEnumDeviceInterfaces 'for (i = 0; ...;
i++)' loop to the next device interface.
- device_path malloc unchecked before the indexed
copy loop NULL-derefs. NULL-check + free the
LocalAlloc'd lp_device_path + continue.
Both 'continue' statements target the inner for-loop's i++
advance clause, which is the intended behaviour (skip this
interface, try the next). The outer 'while (!ret)' loop
increments 'index' at the bottom of its body, which is
unaffected by the inner continue.
* task_steam.c (1 fix):
- task_push_steam_core_dlc_install: both task_init
and steam_core_dlc_install_state_t calloc were unchecked
before the state->app_id / ->name / ->has_downloaded and
task->handler / ->state / ->title / ->progress / ->callback
writes that NULL-deref. Joint NULL-check frees whichever
succeeded and returns; caller is menu Steam-DLC action
with no task-return channel, so return-silently matches
the pre-patch failure mode (task would have crashed or
silently not installed) without the crash.
(This is separate from the two other steam/steam.c bugs
that are blocked on an external mist.h enum value.)
All fixes follow the same pattern: NULL-check immediately after
the alloc, clean up partial state on failure, and propagate the
error via either task_set_error, a bool/enum return, or the
next-task-iteration advance (continue). Free-on-NULL paths
exploit free(NULL) being a no-op to minimise conditional
branches.
Thread-safety: these are all on-thread modifications within the
task worker or task-dispatch thread context - task_queue.c
serialises completion callbacks on the main thread before the
task_data memory is read, so the NULL-toleration added in
completion callbacks is safe against the earlier-dispatched
worker writing NULL into task_data.
Scope: all fixes are local to individual task handlers/callbacks;
no API changes, no header changes, no cross-subsystem impact.
The task_queue.c callback dispatch contract is unchanged -
callbacks receive task_data which may be NULL if the handler
was unable to allocate it, and callbacks are now consistently
NULL-tolerant in the cases touched here.
Reachability: every fix is reachable under OOM. The
more likely user-facing cases are save_state_cb /
content_load_state_cb / content_load_and_save_state_cb
(triggered on every save-state / load-state action), and the
blissbox enumeration (triggered on every USB joypad hotplug if
blissbox support is built in).
* Massive reduction in heap space allocation, going from settings struct
264kb to 119Kb
* Use NAME_MAX_LENGTH for base paths/names, etc
* Use DIR_MAX_LENGTH for directory sizes
assignments for strings longer than 2 chars
- Use strlcpy concatenation instead of strlcat
- Make sure that what remains of iteration of the '_len' variable
for manual char assignment
is done in a safer way so mistakes are less possible
usage of strlcpy (when position/offset of previous strlcpy/snprintf call
is known. strlcat implementation in libretro-common makes implicit strlen
call, using strlcpy avoids this
* Reduce a bunch of local char variables by use of said clever usage,
should save up on local stack size usage
Avoids the internal strlen call inside strdup, and strdup is a deprecated
function starting from MSVC2005 anyways.
NOTE: Do NOT pass STRLEN_CONST as n parameter to strldup, it needs to
be at least +1 character higher than the strlen return value of the same
string