mirror of
https://github.com/libretro/RetroArch.git
synced 2026-11-23 00:36:42 -10:00
codex/android-native-streaming
30
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
a3e9cc4a70 |
net_http: request identity content coding
net_http hands the body to callers as sent and decodes no content coding, so every request now says so with Accept-Encoding: identity; without the header a server is free to pick any coding. The resume harness checks both the first request and the resumed one carry it. |
||
|
|
fe1389662b |
http_transfer_stress_test: judge the drain per call, not as an average
The throughput guard asked for 256KiB per net_http_update() averaged over the body. That is exactly net_http.c's drain budget, so it only held when the test's server thread had a full budget waiting before every call; on a loaded two-CPU runner it sometimes had not, and the check failed about one run in four with the drain intact. What the guard is for is that a call reads until the socket is empty rather than taking one bite and returning. It checks that now, per call, from the test's recv() hook: every body update must end on EAGAIN, at the byte budget (within the minimum read window net_http.c will not spend on a short read), or at the iteration cap. The average is still printed. Passed eight runs in a row, and six with three busy loops on the two CPUs. With net_http.c cut to one recv() per call, every body update is reported. |
||
|
|
a3cf738010 |
task_http: a GET retried from its own callback is not its duplicate
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. |
||
|
|
21635dd171 |
samples: build with -g1 instead of -g
The sample and test builds used full debug info. -g1 keeps what sanitizer reports and backtraces need - function names, files and line numbers - and drops the variable and type information nobody reads in CI. Objects get about 30% smaller (rh265.o under ASan+UBSan: 5.1MB to 3.7MB), so the ccache caches hold more of each job's build and are quicker to restore and save. |
||
|
|
767c6f89c2 | net: Add Basic Auth support to HTTP requests (#19717) | ||
|
|
217c50838e |
net_http: refuse a redirect from https to http
net_http_redirect takes the new scheme from the Location URL, so an https request redirected to http:// carried on over plain HTTP with no sign to the caller. A redirect that leaves TLS now ends the transfer with an error; https to https, relative Locations and http to https are followed as before. The request's Authorization and Cookie headers stay with the host and port they were sent to: a redirect elsewhere goes out without them, and other headers follow as before. The same host moving from http onto https keeps them. This changes behaviour for any caller that relied on such a redirect: it now fails where it used to succeed unencrypted, and a cross-host redirect that needed the credentials now gets no further than the new host's answer to an unauthenticated request. samples/tasks/http/http_limits_test.c gains lanes for both: the downgrade and cross-origin cases fail without the change and pass with it, and the allowed cases pass either way. Closes #19696 |
||
|
|
de4cf0ef5f |
net_http: drain the socket within the caller's time window
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. |
||
|
|
c4ff3d3369 |
samples/tasks/http: link compat_strl.c into http_dns_lifetime_test
|
||
|
|
cec500d0cb |
task_http: resume an interrupted download to a file
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. |
||
|
|
beef1f13b9 |
net_http: share the header-text compactor; test the real one
The Emscripten backend gets response headers from the browser as one text blob and turns it into net_http's header block itself. Its test could not build task_http_emscripten.c (emcc only), so it carried a copy of the parser - and the copy had already drifted: it still split into a string_list, while the backend had moved to the block. The conversion is now net_http_headers_compact() in net_http.c: header text in, the block net_http_headers_take() returns out, in place, with CR and trailing spaces trimmed, blank lines dropped and the final line kept without its newline. The Emscripten backend calls it on the buffer the browser filled; http_emscripten_headers_test links net_http.c and calls it too, so the response side has no copy left to drift. The request side stays a copy, being static to the emcc-only file, as the test's header says. http_emscripten_headers_test: the same response cases (splitting, blank and final lines, lower-cased names, NULL and empty input) against the real function, under ASan and UBSan. |
||
|
|
2302213409 |
net_http: parse bracketed IPv6 literals in URLs and redirects
An IPv6 address in a URL is bracketed because it contains colons (RFC 3986 3.2.2): http://[::1]:8080/x. Both places that split host from port took the first colon: - net_http_connection_iterate()/_done() stopped the host at "[" and refused the rest as a bad port, so such a URL could not be requested at all; - net_http_redirect() split the joined URL the same way, so a redirect to a literal failed (or, with digits in the right place, went to a junk host and port). Both now treat a leading "[" as a literal running to its "]", with the port colon only after it; an unterminated, empty or trailing-garbage literal is refused. The domain keeps its brackets, which the Host header needs ("Host: [::1]:8080"), and the resolver strips them before getaddrinfo(), which wants the bare address. url_join needed nothing: it never looks inside the authority. Not covered: TLS to an IPv6 literal still passes the bracketed form as the server name, as it passes any other host. http_limits_test (net_http.c included whole, resolver stubbed): URL split with and without a port and with a zone id, the three malformed forms, the resolver's argument, and a redirect to http://[::1]:8443/v6. All fail on the previous code. |
||
|
|
b071b96a07 |
net_http: fall back to the next address family when socket() refuses one
getaddrinfo() with AF_UNSPEC lists IPv6 addresses next to IPv4 ones, often first. On a system without IPv6 - a kernel or console network stack built without it - socket() refuses AF_INET6, and that ended the attempt in two places: - net_http_new_socket() created the socket for the first address only, so an IPv6 address listed first failed the transfer outright with "socket_create_failed", IPv4 addresses untried; - the connect loop moved on with socket_next(), which returns -1 when socket() fails for the next address, and the loop read that as the end of the list, so an IPv6 address mid-list hid every address after it. Both now go through net_http_socket_for(), which creates the socket for the first address at or after the current one that the system accepts, and the connection remembers that address's family so connect starts there. An extra socket() call happens only on a refused family; the common case is unchanged. Full Happy Eyeballs (racing connects) is not attempted. http_limits_test, with socket() stubbed to refuse AF_INET6: an IPv6 address first connects over the IPv4 one after it, and with the first IPv4 address refusing the connection and an IPv6 one next, the IPv4 address after that is still tried. Both fail on the previous code. |
||
|
|
566f3ae9a0 |
net_http: cap idle pooled connections and close them after 30 s idle
Every keep-alive connection a finished transfer handed back stayed in the pool until the server closed it and select() noticed. Nothing bounded how many - each one a descriptor here and a slot on the server - and nothing aged them. A connection whose NAT mapping or server keep-alive timer expired silently is never reported readable, so it was reused: the request went into a dead socket and the transfer waited out its timeout. A finished transfer now hands its connection back through net_http_conn_pool_release(), which stamps it idle and, past 8 idle connections, closes the one idle longest. The pool sweep that already runs when a transfer looks for a connection closes any idle for more than 30 s before it even asks select(). Reconnecting costs a handshake; a dead socket cost the whole timeout. Neither touches the receive path: the release runs once per finished transfer and the reap once per pool lookup. With the pool owned by the driving thread, neither takes a lock. http_limits_test: 20 finished connections leave 8 idle (all 20 stayed before), the longest-idle go first, and a connection is reused at 15 s idle and closed at 30 s. |
||
|
|
02dd573a34 |
net_http: cap the DNS cache at 32 entries
Every distinct host:port added a cache entry, and a successful one had its timestamp bumped on every hit, so it lived for as long as it kept being used. A session that touches many hosts - thumbnail mirrors, cloud sync, netplay lobbies, core and asset downloads - grew a list that is walked on every connect, with no bound. Inserting a new host:port now evicts the least recently used entry once there are more than 32. A lookup still in flight is never the victim: its resolver owns the entry until it publishes. The cap costs one walk on insert only; a cache hit and the receive path are untouched. The expiry sweep also reads the clock once per walk rather than twice per entry. New samples/tasks/http/http_limits_test (net_http.c included whole, clock and resolver stubbed), threaded and unthreaded, under ASan+UBSan: 100 distinct hosts leave 101 entries before this change and 32 after, the newest kept and their addresses freed as they go. |
||
|
|
e2e07068eb |
net_http: drop the DNS cache and pool locks
net_http took a mutex around every DNS cache and connection pool access and parked DNS waits on a condition variable, on the premise that any thread might drive a transfer. None does: in RetroArch every net_http_new/update/wait/delete comes from task_http on the task queue's worker, or on the main thread with threaded tasks off, and switching between the two stops the queue first, so the handover is ordered by the join. The only real concurrency is the DNS resolver threads, each of which fills in one cache entry. So the cache and pool now belong to the driving thread, and nothing takes a lock: - A resolver reads its entry's domain and port in place (they are set before the thread starts and never change), writes addr, publishes valid with a release store and touches the entry no more. The owner reads valid with an acquire load, and reads addr, frees the entry or joins its thread only after that. The strdup the resolver took under the lock, a copy of something nobody could change, is gone. - The pool loses its lock outright; only the driving thread uses it. - connect no longer pins the cache entry with a user count: the pin covered another thread's expiry sweep running mid-connect, which cannot happen. - net_http_wait() parks on a retro_eventcount the resolver notifies after publishing, re-checking the lookup after registering so a publish in between is never missed, and bounded by the caller's timeout as before. net_http_init() creates it; there are no locks left to create. - net_http_deinit() can no longer deadlock: resolvers wait on nothing, so joining one only lasts as long as its getaddrinfo(). The sweep still never joins a resolver that has not published - that used to deadlock on the lock and would now stall the driving thread for the whole lookup - and find() no longer reads addr before valid is published, which TSan would report as a race now that no lock orders the two. The rule is documented next to net_http_init() in net_http.h. The stress test's concurrency case drove six transfers from six threads, which RetroArch never does; it now interleaves them on one thread as the task queue does, with the resolvers running alongside under TSan. The DNS lifetime test loses its nested-connect case (the cross-thread sweep it modelled) and the init-failure test its resolver strdup case (the strdup is gone). The tests that build net_http with HAVE_THREADS link retro_eventcount.c, as Makefile.common and griffin already do under HAVE_THREADS. The samples network job now fails if net_http.c calls an slock_ or scond_ function. Stress, transport-failure, task-lifetime, DNS-evict and the semantics harness pass under TSan and ASan+UBSan. |
||
|
|
dba5458fb5 |
net_http: keep response headers in one block instead of a string_list
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.
|
||
|
|
7e80941861 |
net_http: create locks only in net_http_init, strncmp the scheme
net_http_new_socket() still created the DNS cache and pool locks on first use, the unsynchronised initialisation net_http_init() exists to replace: two threads arriving together could each create one and then lock different objects. RetroArch calls net_http_init() before the task queue starts, as do the threaded test harnesses, so the lazy path only ever served programs that skipped it - and served them racily. It is gone; such a program now runs unlocked (slock_lock(NULL) is a no-op), which is documented in net_http.h and next to the sample, which now calls net_http_init()/net_http_deinit(). No lock is added: this removes three creations from the connect path. net_http_connection_new() compared the scheme with memcmp, reading 7 or 8 bytes of a URL that may be shorter. strncmp stops at the NUL. http_transfer_stress_test's silent-peer case called net_http_deinit() to drop pooled connections and carried on relying on the lazy creation; it now calls net_http_init() after it, as its re-init case already did. One new check (an exactly-sized "ht" URL), which ASan reports as a heap-buffer-overflow on the previous code. |
||
|
|
41caa78885 |
Handle HTTP cache allocation and resolver startup failures
Reject cache entries whose hostname allocation fails, check DNS entry and resolver-thread creation, and roll back failed startup without leaving a pending cache entry. Complete resolver hostname-copy failures as failed lookups. Close newly created sockets when connection-pool allocation fails. Add deterministic allocation and thread-start failure tests, cleanup checks and recovery coverage for threaded and non-threaded builds, and register both variants in CI. |
||
|
|
9ada776276 |
Retain cached DNS addresses during HTTP connection setup
Connection setup uses addrinfo after releasing the DNS cache lock. An expiration sweep can reclaim it while a slow connection attempt still uses it. Count active connect users under the cache lock, skip their entries during eviction, and release the reference on every exit path without holding the lock across socket or TLS operations. Add deterministic eviction tests for plain and TLS success/failure, early exits and overlapping users, and register both build variants in task CI. |
||
|
|
4ee4e9ebc4 |
net_http: wait on the socket instead of sleeping a millisecond a pass
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. |
||
|
|
367b717681 |
buildsystem: rstrtod in the nested sample and tool trees too
The previous sweep enumerated makefiles by pattern at the repository root and under libretro-common/samples, and missed every nested build tree: libretro-db and its two sample tests (the reported failures), the top-level samples/ tree for gfx, menu, playlist, and tasks including the four http stress makefile variants, and the standalone makefiles of the bundled ffmpeg, imageviewer, and net-retropad cores. This pass enumerated by find across the whole repository instead, and every source list linking config_file.c, file_stream.c, or rjson.c now carries string/rstrtod.c -- 24 more makefiles. All of them build with the sanitizer arguments the workflows pass, and the two tests the libretro-db job executes build and run clean. Two directories fail identically on the pristine upstream tree and are untouched here: libretro-db/lua's rmsgpack_test wants intfstream objects it does not link, and samples/gfx/font_lifecycle references video_driver_thread_wrapper_active, which no longer exists. |
||
|
|
f3d2eedbfc |
net_http: don't publish the receive buffer as a body on a failed transfer
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. |
||
|
|
f4db782502 |
net_http: bound the drain loop properly, and let close-delimited bodies through
Two follow-ups to |
||
|
|
7890b0aa87 |
task_http: keep task->state alive until the queue retires the task
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,
|
||
|
|
beede58749 |
net_http: don't join a live resolver under the DNS cache lock; stream thumbnail downloads to disk
Two follow-ups from the HTTP task audit.
1. net_http_dns_cache_remove_expired() could deadlock the task thread.
The function runs with the DNS cache lock held --
net_http_dns_cache_find() is only ever called under it, from
net_http_new_socket() and net_http_connect() -- and it joined the
resolver thread of any entry it decided to evict. net_http_resolve()
takes that same lock twice, once on entry to copy the domain and port
and again on completion to publish the result. A join against a
thread blocked acquiring the lock the joiner is holding never
returns.
The window is not theoretical, which is what makes this worth fixing
rather than noting. entry->addr stays NULL for the whole resolution,
so the fail-timeout arm of the expiry test
(!entry->addr && entry->timestamp + dns_cache_fail_timeout < now)
fires after dns_cache_fail_timeout, which is 30 seconds -- and
getaddrinfo_retro() against a blackholed resolver routinely blocks
longer than that. The entry therefore looks expired precisely while
its own resolver thread is still running. The outcome is a hung task
thread, and in unthreaded builds a hung frontend, from nothing worse
than a slow DNS server.
Entries whose resolver has not published yet are now skipped and left
for a later sweep. entry->valid is set by the resolver under the lock
immediately before it unlocks and returns, so once it is set nothing
that thread does can block on the sweep and the join is safe -- which
is the assumption net_http_dns_cache_find() already made for its own
join, and the reason net_http_deinit() drains the list with the lock
released.
samples/tasks/http/http_dns_evict_deadlock_test.c reproduces it
deterministically rather than waiting 30 seconds on an unreachable
nameserver. It wraps two symbols at link time: getaddrinfo, to park
the resolver mid-flight on a nominated hostname, and
cpu_features_get_time_usec, to age the cache entry past the fail
timeout instantly. --wrap rather than a strong definition because
both live in libretro-common objects linked into the test, so
overriding them the way http_transfer_stress_test.c overrides libc's
recv() would be a duplicate definition.
Since the failure mode is a hang rather than a wrong answer, the sweep
runs on its own thread behind a watchdog: on timeout the test reports
and exits non-zero rather than blocking CI forever. Confirmed to
deadlock with the guard removed and to pass with it restored.
2. Thumbnail downloads stream to disk.
cb_http_task_download_pl_thumbnail() buffered each image in full and
wrote it in one go. Individually these are small, so this is
consistency rather than a memory win -- but it is also the second of
the two callers that had this shape, and leaving one behind invites
the next one to be written the same way.
As with the core updater, path_mkdir() moves ahead of the transfer,
since the body now lands in transf->path as it arrives. The callback
keeps its data->status check; task_push_http_download_file() removes
the partial file unless the transfer finished cleanly, so a non-200
leaves nothing behind. Drops the now-unused file_stream.h include and
refreshes two comments still naming task_push_http_transfer_file().
Verified: stress suite 92/92 and the new deadlock test 2/2, both clean
under ASan, LSan, UBSan and TSan. (TSan caught a plain volatile flag
in the new test's own watchdog handshake, now mutex-guarded --
volatile orders nothing between threads.) net_http.c,
task_pl_thumbnail_download.c, task_http.c and task_core_updater.c
compile clean; task_http_emscripten.c verified with emcc 6.0.5 at
-Wall.
|
||
|
|
56d5967020 |
net_http: own the dedup key, add explicit init/deinit, stream core downloads to disk
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.
|
||
|
|
1787d2253a |
net_http: add a streaming body sink, and a task entry point that downloads straight to disk
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. |
||
|
|
51c3c8dca0 |
task_http_emscripten: move to emscripten_fetch, restoring headers, binary bodies and response status
The emscripten backend sat on emscripten_async_wget2_data(), and that API is the root cause of how far this file had drifted from tasks/task_http.c. It takes the request body as a single NUL-terminated `const char*` and offers nothing for request headers, a user agent, or reading response headers back, so everything the native path provides beyond "GET a URL into memory" was silently dropped or stubbed out. emscripten_fetch() covers all of it; switching over closes six defects at once. - Request headers were accepted and discarded on every entry point. task_push_http_transfer_with_headers() sent none, which meant no Authorization header, so cloud sync could not authenticate at all. All five webdav helpers logged "Response headers not supported, webdav won't work" and then did exactly that. RetroArch passes headers as a raw CRLF blob and fetch wants a NULL-terminated key/value array, so http_req_headers_parse() converts between them. - task_push_webdav_put() passed put_data as a NUL-terminated string and dropped the `len` argument entirely, truncating any binary payload at its first zero byte. Length now travels explicitly. - Response headers are recovered via emscripten_fetch_get_response_headers() and split into the same string_list of "Name: Value" lines net_http.c produces. - resp->status was hardcoded to 200, and the error callback recorded no status at all, so callers branching on data->status -- webdav's 401 digest challenge, the thumbnail downloader's 404 check -- saw a NULL task_data and could not distinguish "not found" from "the network died". Both paths now settle with the real status, and error bodies are kept since 4xx/5xx routinely carry one. - wget_onload_cb() returned early when its malloc failed, leaking the whole response buffer. The fetch is now closed unconditionally. - Cancelling a task never aborted the transfer. http_handle_free() closes the fetch, which emscripten guarantees suppresses any further callback. Two lifetime fixes carried over from task_http.c: task_push_http_transfer_file() assigned t->title after task_queue_push(), the exact use-after-free already fixed and commented in the native file -- harmless single-threaded, a genuine race under -pthread/PROXY_TO_PTHREAD. And emscripten_fetch does not copy requestData or requestHeaders, so http_handle now owns both for the fetch's lifetime rather than retaining a caller's buffer. Also drops the local http_transfer_progress_cb(), which called video_display_server_set_window_progress() unconditionally while its header was behind #ifdef RARCH_INTERNAL, in favour of the shared task_window_progress_cb() the native path uses; and sets RETRO_TASK_FLG_ALTERNATIVE_LOOK, which was missing here. network/cloud_sync/webdav.c matches the digest challenge case-insensitively now. Browsers lower-case response header names, so "WWW-Authenticate: Digest " never matched on this backend. Header names are case-insensitive per RFC 9110 5.1, so the consumer was what needed fixing; webdav_create_digest_auth() skips a fixed byte count past the prefix, so the offset is unaffected. Makefile.emscripten passes -sFETCH=1, which the fetch API requires. Adds samples/tasks/http/http_emscripten_headers_test.c covering both conversions against hand-built blobs of the kind task_push_webdav_move() and task_push_http_transfer_with_content() produce: bare LF, missing trailing CRLF, empty values, embedded colons, malformed lines, and growth past the initial array capacity. A header dropped here is an auth failure rather than a crash, so the degenerate cases are worth pinning. 33 checks, clean under ASan and UBSan. Verified with emcc 6.0.5: the file compiles clean at -Wall and -sFETCH=1 links. |
||
|
|
f9ecd73148 |
net_http: drain socket per update; fix close-delimited bodies, response leaks and cache races (#19323)
* net_http: drain the socket per update, fix close-delimited bodies, free unretrieved response state, and lock the DNS cache
Four defects found while auditing tasks/task_http.c, which is a thin
state machine over net_http_update() and owns no I/O of its own.
Measurements below are from samples/tasks/http/http_transfer_stress_test.c
(added separately), driving this file against a loopback server with
SO_RCVBUF pinned to 64KiB.
1. One recv() per update capped throughput.
socket_receive_all_nonblocking() is a single recv() despite the name,
and net_http_update() issued exactly one per call.
task_http_iterate_transfer() calls net_http_update() once per
task-queue tick, so transfer time was
(body_size / bytes_per_recv) * tick_period
with bytes_per_recv bounded by the kernel receive buffer. The tick
period is ~1ms threaded (the retro_sleep(1) in
task_http_iterate_transfer) and one frame -- 16.7ms at 60Hz --
unthreaded. Measured: 4MiB needed 45 body ticks with 46 recv() calls,
i.e. one recv per tick. At 60Hz that is 0.8s of pure scheduling
latency for a transfer worth ~0.02s of I/O; 16MiB measured 6.3s
against 0.09s for a plain drain loop.
net_http_update() now loops until the socket reports EAGAIN. Two
bounds keep a fast or hostile peer from holding the calling thread
(the video thread in unthreaded builds): NET_HTTP_DRAIN_BUDGET caps
bytes per call so a saturated link yields rather than stalling a
frame, and NET_HTTP_DRAIN_MAX_ITERS caps syscalls so a peer dribbling
single bytes cannot spin us. Exceeding either just returns false and
resumes next tick, as before. Same syscall count, 45 ticks -> 1.
2. The receive window collapsed before each buffer growth.
For the doubling-growth body types the window handed to recv() is
buflen - pos, which decays toward zero just before each realloc --
measured at 16 bytes with 3.6MB still outstanding. Grow early against
NET_HTTP_MIN_RECV_WINDOW instead of waiting for pos to reach buflen.
Minimum observed window is now ~48KiB.
3. Connection-close-delimited bodies were discarded entirely.
bodytype defaults to T_FULL and response->len is only ever assigned by
the Content-Length parse or the chunked decoder, so it stays 0 for
T_FULL. The shared tail of net_http_receive_body() then ran
if (response->pos > response->len) return false;
which the first body byte trips, failing the transfer with status -1
and dropping the payload. The only T_FULL path that worked was a
genuinely empty body. Give T_FULL its own branch that accumulates and
lets the newlen < 0 case at the top of the function terminate it.
Measured: 4MiB EOF-framed body went from 0 bytes returned to complete.
4. net_http_delete() freed no response state, despite "Cleans up all
memory".
Neither response.data nor response.headers was freed, and the doc
comment on net_http_data() claiming the buffer "is freed by
net_http_delete()" was false. Any path that did not retrieve both
accessors leaked -- notably task_http.c's cancel and OOM branches,
which free the body but never call net_http_headers_ex(), so every
cancelled download leaked its header list. ASan over the test suite
reported 21113 bytes in 73 allocations, all response header
string_lists.
Track ownership explicitly: the handle owns both until the caller
retrieves them, at which point only the flag flips (the pointers stay
put, so repeated accessor calls remain idempotent -- task_http.c calls
net_http_data() twice on the error path). net_http_delete() frees
whatever was never claimed. ASan now reports no leaks.
5. Two data races on the process-global caches.
net_http_connect() called net_http_dns_cache_find() with no lock. That
is not a read-only lookup: it calls net_http_dns_cache_remove_expired(),
which unlinks entries, freeaddrinfo()s their addrinfo and free()s the
entry, and it also joins resolver threads and bumps timestamps. One
download could therefore free a cache entry another was walking under
the lock -- a use-after-free of the entry and its addrinfo, not a
benign race. Take the lock, and NULL-check the result: the entry can
expire between net_http_new_socket() and here, so the dereference was
reachable rather than the "big bug" the old comment assumed.
Separately, net_http_update() wrote conn->in_use unlocked while
net_http_conn_pool_remove_expired() read it under the pool lock and
fed the fd to select(). Take the pool lock for that write.
TSan reported six races across four sites with six concurrent
transfers; it is now clean.
Not addressed here: the lazy `if (!dns_cache_lock) dns_cache_lock =
slock_new();` in net_http_new_socket() is itself unsynchronised, so a
first-use race can leave two threads holding different mutexes. It
does not reproduce once the locks exist, and fixing it properly wants
an explicit net_http_init()/net_http_deinit() pair called before any
task thread starts -- which is also where the DNS cache and connection
pool should be torn down, since neither has any teardown path today.
Verified with ASan, UBSan, LSan and TSan over the new suite; all clean,
57/57 checks passing.
* samples/tasks/http: add transfer stress and URL dedup regression tests
Two additions alongside the existing http_method_match_test.c.
http_transfer_stress_test.c drives the real net_http.c against a
loopback server and asserts on what task_http.c would observe. It
covers framing correctness (Content-Length, chunked across chunk sizes
1..65536, and connection-close-delimited), the same again with the
server dribbling a few bytes per write so every header line, chunk
header and chunk boundary is torn across receive calls, per-tick
transfer cost, receive-window floor, failure teardown (truncated
bodies, four malformed head shapes) and six concurrent transfers for
TSan to look at the process-global DNS cache and connection pool.
Two details make the tick-cost measurement mean something.
It interposes socket() to pin SO_RCVBUF, because per-update byte yield
otherwise tracks host /proc/sys/net tuning and autoscaling, and recv()
to count calls and record the requested window. The server side uses
read(), so only net_socket.c traffic is recorded. Both are plain
strong definitions resolved through RTLD_NEXT -- no LD_PRELOAD needed,
since net_http.c and net_socket.c link into the binary.
It also sleeps the task-queue tick period between updates. Without
that the client polls far faster than the peer can fill the socket,
every recv() takes a sliver, and the number reports the server's write
rate rather than the structural per-tick cap -- it swung between 263
and 93207 B/tick across runs. Sleeping the period lets the receive
buffer saturate between calls, which is the regime RetroArch actually
runs in and the only one where ticks-per-body is stable. Ticks-per-body
is cadence-independent once saturated, so measuring at the 1ms threaded
cadence keeps the test fast while the 60Hz figure is the same count
scaled by 16.7ms. Setup ticks (DNS/connect/send) are counted
separately so resolver latency does not pollute throughput.
http_url_dedup_test.c is pure logic with no dependencies, following the
verbatim-oracle convention of http_method_match_test.c and
archive_name_safety_test.c. task_http.c stores the request URL in
connection_url[NAME_MAX_LENGTH] via strlcpy but task_http_finder()
compares that truncated copy against the raw candidate, so once a URL
reaches NAME_MAX_LENGTH the two can never match and the "concurrent
download of the same file is not allowed" guard silently stops
guarding. Playlist thumbnail URLs trigger it routinely, and the
consequence is not just wasted bandwidth: both tasks reach their
completion callback, and cb_http_task_download_pl_thumbnail() ends in
filestream_write_file() on an identical path.
The failure is one-directional -- truncation cannot conflate two
distinct URLs, because the candidate is never truncated to match -- so
the test asserts both that a long URL fails to dedup itself today and
that distinct long URLs stay distinct, the latter guarding against a
future fix that hashes the key to a fixed width and introduces the
false positive this bug does not have. It pins the divergence at
exactly NAME_MAX_LENGTH and builds with -DNAME_MAX_LENGTH=128 for the
small-path platforms.
This test is red until connection_url is made to hold the full URL; it
documents the live defect.
Build:
make -f Makefile.stress check [SANITIZER=address|thread|undefined]
cc -Wall -std=gnu99 -g -O0 -o http_url_dedup_test http_url_dedup_test.c
---------
Co-authored-by: libretroadmin <>
|
||
|
|
ae3292fe03 |
task_http: fix heap-buffer-overflow in GET fast-path + regression test
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.
|