diff --git a/CMakeLists.txt b/CMakeLists.txt index 36dae1d520..960b8d7b1b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -74,6 +74,9 @@ option(FIREBASE_USE_BORINGSSL "Build against BoringSSL instead of using your system's OpenSSL." OFF) option(FIREBASE_USE_LINUX_CXX11_ABI "Build Linux SDK using the C++11 ABI instead of the legacy ABI." OFF) +option(FIREBASE_ANDROID_HTTP_CURL + "Build the native HTTP transport (app/http) for Android. Downloads and builds libcurl and BoringSSL." + OFF) # This should only be enabled by the GitHub Action build script. option(FIREBASE_GITHUB_ACTION_BUILD @@ -426,8 +429,50 @@ if((FIREBASE_INCLUDE_DATABASE AND DESKTOP) AND NOT FIREBASE_INCLUDE_FIRESTORE) add_external_library(leveldb) endif() -# Some of the external libraries are not used for mobile. -if(DESKTOP) +# The Android native HTTP transport (app/http, built only with +# FIREBASE_ANDROID_HTTP_CURL) uses libcurl with a BoringSSL of its own, both +# linked statically. They are built with firebase_app, so there is nothing to +# do when reusing a prior Gradle build of it. +if(ANDROID AND FIREBASE_ANDROID_HTTP_CURL AND + NOT FIREBASE_CPP_USE_PRIOR_GRADLE_BUILD) + set(firebase_build_android_curl ON) + message(STATUS "Building BoringSSL for the Android HTTP transport...") + build_android_boringssl() + message(STATUS "Build of BoringSSL for the Android HTTP transport complete.") + + # Make libcurl's find_package(OpenSSL) resolve to that BoringSSL. + set(OPENSSL_INCLUDE_DIR ${BORINGSSL_ANDROID_SOURCE_DIR}/include + CACHE PATH "" FORCE) + set(OPENSSL_SSL_LIBRARY ${BORINGSSL_ANDROID_BINARY_DIR}/libssl.a + CACHE FILEPATH "" FORCE) + set(OPENSSL_CRYPTO_LIBRARY ${BORINGSSL_ANDROID_BINARY_DIR}/libcrypto.a + CACHE FILEPATH "" FORCE) + add_library(OpenSSL::Crypto STATIC IMPORTED GLOBAL) + set_target_properties(OpenSSL::Crypto PROPERTIES + IMPORTED_LOCATION "${OPENSSL_CRYPTO_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${OPENSSL_INCLUDE_DIR}" + ) + add_library(OpenSSL::SSL STATIC IMPORTED GLOBAL) + set_target_properties(OpenSSL::SSL PROPERTIES + IMPORTED_LOCATION "${OPENSSL_SSL_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${OPENSSL_INCLUDE_DIR}" + INTERFACE_LINK_LIBRARIES OpenSSL::Crypto + ) + + # libcurl detects SSL_set0_wbio() by linking a C program against libssl. + # BoringSSL's libssl is C++, so that check fails for want of a C++ runtime + # rather than of the function. libcurl would add one to the check, and to + # everything linking libcurl, if OPENSSL_USE_STATIC_LIBS were set, but which + # C++ runtime to link is the final Android library's choice (ANDROID_STL). + # BoringSSL has the function, so state the result instead. + set(HAVE_SSL_SET0_WBIO 1) +else() + set(firebase_build_android_curl OFF) +endif() + +# libcurl is used on desktop and by the Android HTTP transport, with the same +# configuration. The other external libraries here are not used for mobile. +if(DESKTOP OR firebase_build_android_curl) # Configure libcurl before adding its subdirectory. # Note: curl 8.23.0 requires CMake >= 3.18 (CMP0077=NEW), so plain set() of # normal variables overrides curl's option() defaults without polluting the @@ -532,12 +577,21 @@ if(DESKTOP) endif() endif() + if(ANDROID) + # Compile libcurl's public API with hidden visibility as well (its internal + # symbols already are), so the shared library the transport is linked into + # does not export it. + target_compile_definitions(libcurl_static PRIVATE CURL_STATICLIB) + endif() + # Clean up generic normal variables set specifically for curl so they do not # leak into subsequent add_subdirectory() calls (zlib, firestore, etc.). unset(BUILD_STATIC_LIBS) unset(BUILD_EXAMPLES) - add_external_library(zlib) + if(DESKTOP) + add_external_library(zlib) + endif() endif() if(DESKTOP AND NOT CMAKE_CROSSCOMPILING) diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 5cc8f879b7..6d92dc13b4 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -390,6 +390,13 @@ if (NOT ANDROID AND NOT IOS) add_subdirectory(rest) endif() +# Cross-platform native streaming HTTP transport (libcurl on desktop and +# Android, NSURLSession on iOS/tvOS). On Android it brings in libcurl and +# BoringSSL, so it is only built on request. +if(NOT ANDROID OR FIREBASE_ANDROID_HTTP_CURL) + add_subdirectory(http) +endif() + if(FIREBASE_CPP_BUILD_TESTS) # Add the tests subdirectory add_subdirectory(tests) diff --git a/app/http/CMakeLists.txt b/app/http/CMakeLists.txt new file mode 100644 index 0000000000..82a243ac5e --- /dev/null +++ b/app/http/CMakeLists.txt @@ -0,0 +1,123 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# CMake file for the cross-platform native streaming HTTP transport library +# (`firebase_http_transport`). + +cmake_minimum_required(VERSION 3.22) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED YES) + +set(http_transport_SRCS + http_bridge.h + http_transport.h + http_transport_common.cc + websocket.h + websocket_common.cc) + +if(ANDROID) + # firebase_rest_lib is not built for Android, so the two libcurl helpers the + # curl backend shares with it are compiled into this library directly. + list(APPEND http_transport_SRCS + http_transport_curl.cc + http_transport_curl_internal.h + http_transport_curl_android.cc + http_transport_curl_platform.h + websocket_curl.cc + ${FIREBASE_CPP_SDK_ROOT_DIR}/app/rest/curl/curl_handles.cc + ${FIREBASE_CPP_SDK_ROOT_DIR}/app/rest/curl/tls_policy.cc) +elseif(IOS) + list(APPEND http_transport_SRCS + http_transport_apple.mm + websocket_apple.mm) +else() + list(APPEND http_transport_SRCS + http_transport_curl.cc + http_transport_curl_internal.h + websocket_curl.cc) +endif() + +add_library(firebase_http_transport STATIC + ${http_transport_SRCS}) + +set_property(TARGET firebase_http_transport PROPERTY FOLDER "Firebase Cpp") + +# Match firebase_app's -fno-exceptions / /EHs-c- build settings. +if(MSVC) + target_compile_options(firebase_http_transport PRIVATE /EHs-c-) +else() + target_compile_options(firebase_http_transport PRIVATE -fno-exceptions) +endif() + +target_include_directories(firebase_http_transport + PUBLIC + ${FIREBASE_CPP_SDK_ROOT_DIR} +) + +target_link_libraries(firebase_http_transport + PUBLIC + firebase_app +) + +if(ANDROID) + # libcurl and the BoringSSL it was built against (see the top-level + # CMakeLists.txt) are linked statically into whatever links this library. + target_include_directories(firebase_http_transport + PRIVATE + ${CURL_SOURCE_DIR}/include + ) + target_compile_definitions(firebase_http_transport + PRIVATE + FIREBASE_HTTP_BUNDLED_BORINGSSL=1 + ) + target_link_libraries(firebase_http_transport + PRIVATE + libcurl + OpenSSL::SSL + OpenSSL::Crypto + ) +elseif(IOS) + set_source_files_properties(http_transport_apple.mm websocket_apple.mm + PROPERTIES COMPILE_OPTIONS "-fobjc-arc" + ) + target_link_libraries(firebase_http_transport + PRIVATE + "-framework Foundation" + ) +else() + target_include_directories(firebase_http_transport + PRIVATE + ${CURL_SOURCE_DIR}/include + ) + if(MSVC) + target_compile_definitions(firebase_http_transport + PRIVATE + WIN32_LEAN_AND_MEAN + NOMINMAX + CURL_STATICLIB=1 + ) + endif() + target_link_libraries(firebase_http_transport + PRIVATE + firebase_rest_lib + libcurl + ) +endif() + +if(NOT ANDROID AND NOT IOS) + cpp_pack_library(firebase_http_transport "deps/app") + if(FIREBASE_CPP_BUILD_TESTS) + add_subdirectory(tests) + endif() +endif() diff --git a/app/http/http_bridge.h b/app/http/http_bridge.h new file mode 100644 index 0000000000..808f1b00bf --- /dev/null +++ b/app/http/http_bridge.h @@ -0,0 +1,205 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Flat handle-based C++/SWIG bridge for the cross-platform streaming HTTP +// transport (`firebase_http_transport`). +// +// Deliberately keeps its header surface restricted to primitive types and +// `std::string` so language bindings (such as Unity C# SWIG) can include it +// directly without exposing C++17 STL containers or native-to-managed reverse +// function-pointer callbacks. + +#ifndef FIREBASE_APP_HTTP_HTTP_BRIDGE_H_ +#define FIREBASE_APP_HTTP_HTTP_BRIDGE_H_ + +#include + +#include + +namespace firebase { + +// Creates a new HTTP operation handle without starting it. +// `headers_packed` encodes headers as `Name\tValue\n` lines. +// `content_length` uses `-2` for no request content, `-1` for unknown-length +// chunked streaming content, or `>= 0` for a known fixed byte length. +int64_t HttpCreateRequestInternal(const char* method, const char* url, + const char* headers_packed, + const char* proxy_url, + int64_t content_length); + +// Starts the platform-native HTTP operation for `handle`. +void HttpStartRequestInternal(int64_t handle); + +// Non-blocking write of up to `length` request body bytes into the bounded +// upload pipe. Returns: +// `> 0` bytes accepted. +// `0` the pipe is full (arming a request-space event). +// `-1` the operation failed or was canceled, the handle is unknown, or the +// arguments are invalid. +// `-2` the transport stopped consuming the request body because the server +// responded early or the response already completed. This is not an +// error: stop writing and wait for the response headers. +int32_t HttpTryWriteRequestBodyInternal(int64_t handle, void* data, + int32_t length); + +// Marks the end of the request body stream for `handle`. Does nothing once +// the transport stopped consuming the request body. +void HttpFinishRequestBodyInternal(int64_t handle); + +// Polls response header readiness. Returns HTTP status code (`> 0`) once +// headers are committed, `0` if still pending (arming a headers-ready event), +// or `-1` on transport error or cancellation. +int32_t HttpPollResponseHeadersInternal(int64_t handle); + +// Returns the committed response reason phrase and headers packed as: +// `\n\t\n...` +std::string HttpGetResponseHeadersInternal(int64_t handle); + +// Non-blocking read of up to `max_length` response body bytes. Returns bytes +// copied (`> 0`), `0` on clean EOF, `-2` if no bytes are buffered yet (arming +// a body-available event), or `-1` on invalid arguments, transport error, or +// cancellation. +int32_t HttpTryReadResponseBodyInternal(int64_t handle, void* dest, + int32_t max_length); + +// Returns the terminal transport error message for `handle`, if any. +std::string HttpGetErrorInternal(int64_t handle); + +// Returns the structured error class for `handle`: +// 0 = None +// 1 = Canceled +// 2 = Connect (DNS, refused, reset, unreachable, TLS handshake or record +// failure, connection dropped mid-transfer) +// 3 = Certificate (peer certificate or host name verification failed) +// 4 = Timeout (connect or transfer timeout) +// 5 = Other (protocol error, unknown) +// 6 = InvalidRequest (rejected before any network I/O: bad header, method, +// URL scheme, content length, or proxy URL) +int32_t HttpGetErrorClassInternal(int64_t handle); + +// Cancels an in-flight HTTP operation immediately and wakes any armed waiters. +void HttpCancelRequestInternal(int64_t handle); + +// Cancels (if active) and removes `handle` from the operation registry. +void HttpDestroyRequestInternal(int64_t handle); + +// Cancels and removes all active HTTP operations from the registry and wakes +// the event pump (for example on Editor domain reload or shutdown). +void HttpCancelAllRequestsInternal(); + +// Waits up to `timeout_ms` (`< 0` for infinite, `0` for non-blocking poll) for +// the next completion event. Returns `(handle << 8) | event_kind`, or `0` on +// timeout / explicit wake. +int64_t HttpWaitNextEventInternal(int32_t timeout_ms); + +// Wakes a thread blocked in `HttpWaitNextEventInternal` (e.g. on shutdown or +// domain unload). +void HttpWakeEventPumpInternal(); + +// ---- WebSockets ----------------------------------------------------------- +// +// WebSocket handles come from the same id space as HTTP operation handles and +// their events arrive through `HttpWaitNextEventInternal`: +// 4 = WebSocketOpen (the socket opened or failed) +// 5 = WebSocketReceive (a message, a close, or a failure is available) +// 6 = WebSocketSendSpace (the send queue has room again) +// An event is posted only after the call that reported "pending", "nothing +// buffered", or "queue full" armed it, and at most once per arming. +// `HttpCancelAllRequestsInternal` also aborts every WebSocket. + +// Creates a WebSocket handle without connecting. `url` must use `ws://` or +// `wss://`. `headers_packed` uses the `Name\tValue\n` form of +// `HttpCreateRequestInternal`. `subprotocols` is a comma separated list, empty +// for none. A handle is always returned; invalid arguments give a handle that +// has already failed with error class InvalidRequest. +int64_t WebSocketCreateInternal(const char* url, const char* headers_packed, + const char* subprotocols, + const char* proxy_url); + +// Starts connecting `handle`. Later calls do nothing. +void WebSocketConnectInternal(int64_t handle); + +// Returns `1` once the socket has opened, `0` while connecting (arming a +// WebSocketOpen event), or `-1` if it failed, was canceled, or is closed. +int32_t WebSocketPollOpenInternal(int64_t handle); + +// Returns the subprotocol the server selected, or an empty string. +std::string WebSocketGetSubprotocolInternal(int64_t handle); + +// Adds one fragment of a message; the message is sent once a fragment with +// `end_of_message` arrives. `message_type` is `1` for text or `2` for binary +// and is taken from the first fragment. Returns: +// `1` accepted. +// `0` the send queue is full (arming a WebSocketSendSpace event). +// `-1` the socket is not open, a close was already requested, the arguments +// are invalid, or the message would exceed 16 MiB. In the last case +// the fragments collected so far are dropped and the socket stays +// usable. +int32_t WebSocketTrySendInternal(int64_t handle, int32_t message_type, + void* data, int32_t length, + bool end_of_message); + +// Copies up to `max_length` bytes of the oldest received message. Returns: +// `>= 0` `(bytes_copied << 8) | flags`; flag bit 0 = this was the end of +// the message, bit 1 = the message is binary (otherwise text). An +// empty message gives zero bytes with bit 0 set. +// `-2` nothing is buffered (arming a WebSocketReceive event). +// `-3` the socket closed cleanly; the close code and reason are +// available. Messages received before the close are returned first. +// Before `WebSocketCloseInternal` was called this is returned as +// soon as the peer's Close frame arrived; afterwards it is returned +// once the state is `4`. +// `-1` the socket failed or was canceled (received messages are +// dropped), or the arguments are invalid. +int64_t WebSocketTryReceiveInternal(int64_t handle, void* dest, + int32_t max_length); + +// Starts the closing handshake: the Close frame is sent after the messages +// already queued, and no further message is accepted. When the peer closed +// first this sends the reply; the transport does not reply on its own. `code` +// `0` sends a Close frame without a status code. `reason` is cut to 123 +// bytes. Calling it again does nothing. On a socket that is still connecting +// it cancels the socket. +void WebSocketCloseInternal(int64_t handle, int32_t code, const char* reason); + +// Returns `0` connecting, `1` open, `2` close requested locally, `3` close +// received from the peer, `4` closed (handshake finished and connection +// gone), or `5` failed or canceled (also for an unknown handle). +int32_t WebSocketGetStateInternal(int64_t handle); + +// Return the status code and reason of the peer's Close frame: `0` and empty +// until it arrives, `1005` if it carried no status code. +int32_t WebSocketGetCloseCodeInternal(int64_t handle); +std::string WebSocketGetCloseReasonInternal(int64_t handle); + +// Return the failure message and the error class (same values as +// `HttpGetErrorClassInternal`) for `handle`. +std::string WebSocketGetErrorInternal(int64_t handle); +int32_t WebSocketGetErrorClassInternal(int64_t handle); + +// Drops the connection at once without a closing handshake and wakes every +// armed waiter. +void WebSocketCancelInternal(int64_t handle); + +// Forgets `handle`. A socket that is not closed yet is canceled first, so its +// connection is dropped without a closing handshake; a Close frame requested +// with `WebSocketCloseInternal` but not yet sent may never be sent. Safe on a +// handle that is already closed, failed, or canceled. +void WebSocketDestroyInternal(int64_t handle); + +} // namespace firebase + +#endif // FIREBASE_APP_HTTP_HTTP_BRIDGE_H_ diff --git a/app/http/http_transport.h b/app/http/http_transport.h new file mode 100644 index 0000000000..1dd4bc46f4 --- /dev/null +++ b/app/http/http_transport.h @@ -0,0 +1,267 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Cross-platform streaming HTTP transport: +// - Desktop (Linux / macOS / Windows) and Android: libcurl multi-handle +// (sharing `firebase_rest_lib`'s TLS policy and ref-counted curl +// initialization). +// - Apple mobile (iOS / tvOS): NSURLSession with bound-stream uploads. +// +// Behavior shared by both backends: +// - Bounded buffering in both directions (`kMaxRequestBufferBytes` upload +// pipe, `kMaxResponseBufferBytes` download buffer), with response bytes +// delivered as they arrive (for example Server-Sent Events). +// - The request body upload and the response download are streamed at the +// same time. +// - Redirects are not followed. A 3xx response is delivered like any other +// response, with its status, its headers (including `Location`), and its +// body; the caller decides whether to send another request. +// - When a backend stops sending the request body because the server +// responded early, the response is still delivered and +// `HttpTryWriteRequestBodyInternal` returns `kHttpWriteClosed`. +// +// Differences between the backends: +// - Connect timeout: libcurl enforces a 60-second connect timeout. +// `NSURLSession` does not expose a connect-only timeout separate from the +// idle read timeout, so the Apple backend relies on the OS TCP connect +// timeout while keeping `timeoutIntervalForRequest` high so idle SSE +// streams are not terminated. +// - Response headers and reason phrases: libcurl returns the server-sent +// reason phrase and preserves duplicate response headers as separate +// entries. Apple's `NSHTTPURLResponse` does not expose raw HTTP/1.1 reason +// phrases or unmerged header lists, so the Apple backend reports an empty +// reason phrase and coalesces duplicate response headers per +// `NSHTTPURLResponse.allHeaderFields`. + +#ifndef FIREBASE_APP_HTTP_HTTP_TRANSPORT_H_ +#define FIREBASE_APP_HTTP_HTTP_TRANSPORT_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_bridge.h" + +namespace firebase { +namespace http { + +// Event kinds delivered through `HttpWaitNextEventInternal` in the low 8 bits +// of the packed `(handle << 8) | kind` return value. +enum HttpEventKind : int32_t { + kHttpEventNone = 0, + kHttpEventRequestSpaceAvailable = 1, + kHttpEventResponseHeadersReady = 2, + kHttpEventResponseBodyAvailable = 3, + // WebSocket events, see `websocket.h`. + kHttpEventWebSocketOpen = 4, + kHttpEventWebSocketReceive = 5, + kHttpEventWebSocketSendSpace = 6, +}; + +// Structured terminal failure categories returned by +// `HttpGetErrorClassInternal`. +enum HttpErrorClass : int32_t { + kHttpErrorNone = 0, + kHttpErrorCanceled = 1, + // DNS, refused, reset, unreachable, TLS handshake or record failure, or a + // connection dropped mid-transfer. + kHttpErrorConnect = 2, + // The peer certificate or host name verification failed. + kHttpErrorCertificate = 3, + kHttpErrorTimeout = 4, + kHttpErrorOther = 5, + // Rejected before any network I/O: bad header, method, URL scheme, content + // length, or proxy URL. + kHttpErrorInvalidRequest = 6, +}; + +// Bounded buffer limits per in-flight operation to preserve socket-level +// backpressure in both upload and download directions. +inline constexpr size_t kMaxRequestBufferBytes = 256 * 1024; +inline constexpr size_t kLowWaterRequestBytes = 128 * 1024; +inline constexpr size_t kMaxResponseBufferBytes = 2 * 1024 * 1024; +inline constexpr size_t kLowWaterResponseBytes = 1 * 1024 * 1024; + +// Special content_length sentinel indicating no request body is attached. +inline constexpr int64_t kNoRequestContent = -2; +// Special content_length sentinel indicating unknown-length chunked content. +inline constexpr int64_t kChunkedRequestContent = -1; + +// Return codes from `HttpTryReadResponseBodyInternal`. +inline constexpr int32_t kHttpReadWouldBlock = -2; +inline constexpr int32_t kHttpReadErrorOrCanceled = -1; + +// Return code from `HttpTryWriteRequestBodyInternal` when the transport +// stopped consuming the request body (early response, or the response already +// completed). Not an error. +inline constexpr int32_t kHttpWriteClosed = -2; + +struct ByteChunk { + std::vector data; + size_t offset = 0; + + size_t remaining() const { return data.size() - offset; } +}; + +// Request parameters for `CreateOperation`. +struct HttpRequestOptions { + std::string method = "GET"; + std::string url; + std::vector> headers; + std::string proxy_url; + int64_t content_length = kNoRequestContent; +}; + +// Shared state for a single HTTP request/response lifecycle, held via +// `std::shared_ptr` by both the handle table and the active platform backend so +// cancellation or handle destruction never races with native worker threads. +struct HttpOperation { + int64_t id = 0; + std::string method; + std::string url; + std::vector> request_headers; + std::string proxy_url; + int64_t content_length = kNoRequestContent; + + mutable std::mutex mutex; + std::condition_variable req_cv; + std::condition_variable resp_cv; + + // Request body streaming pipe (caller -> native backend). + std::deque req_chunks; + size_t req_buffered_bytes = 0; + bool req_eof = false; + bool req_write_closed = false; + bool req_space_armed = false; + + // Response header state (native backend -> caller). + bool headers_ready = false; + int32_t status_code = 0; + std::string reason_phrase; + std::vector> response_headers; + bool resp_headers_armed = false; + + // Response body streaming pipe (native backend -> caller). + std::deque resp_chunks; + size_t resp_buffered_bytes = 0; + bool resp_eof = false; + bool resp_read_armed = false; + + // Terminal failure / cancellation / single-start state. + std::atomic started{false}; + std::atomic canceled{false}; + bool failed = false; + HttpErrorClass error_class = kHttpErrorNone; + std::string error_message; + + // Platform backend hooks invoked outside `mutex` when state changes. + std::function on_request_data_changed; + std::function on_response_space_available; + std::function on_cancel; + + bool IsCanceled() const { return canceled.load(std::memory_order_acquire); } + + // Called by the platform backend once final response status & headers arrive. + void CommitResponseHeaders( + int32_t status, std::string_view reason, + std::vector> headers); + + // Called by the platform backend when it stops consuming request body bytes + // before the caller finished writing them (for example after an early error + // response). Wakes a caller waiting for pipe space; later writes return + // `kHttpWriteClosed` without failing the response. The backend must still + // call `CommitResponseHeaders`, `MarkResponseComplete`, or `MarkFailed` + // afterwards. + void MarkRequestWriteClosed(); + + // Called by the platform backend as response body bytes arrive. + // Returns true if buffered bytes are now >= `kMaxResponseBufferBytes`, + // telling the backend to pause socket reads until + // `on_response_space_available` fires. + bool PushResponseBytes(const uint8_t* bytes, size_t length); + + // Called by the platform backend when the response body finishes cleanly. + void MarkResponseComplete(); + + // Called by the platform backend when a transport error aborts the transfer. + void MarkFailed(std::string_view message, + HttpErrorClass err_class = kHttpErrorOther); + + // Non-blocking drain of up to `max_bytes` from the request body queue. + // Sets `out_eof` to true when the queue is empty and the caller finished + // writing. + size_t PopRequestBytes(uint8_t* dest, size_t max_bytes, bool* out_eof); +}; + +// Registry entry points behind the flat bridge in `http_bridge.h`. +// `CreateOperation` always returns a handle; an operation whose method, +// headers, or content length are invalid is created already failed with +// `kHttpErrorInvalidRequest`. +int64_t CreateOperation(HttpRequestOptions options); +std::shared_ptr FindOperation(int64_t handle); +void StartOperation(int64_t handle); +void CancelOperation(int64_t handle); +void DestroyOperation(int64_t handle); +void CancelAllOperations(); + +// Enqueues an event onto the global completion queue consumed by +// `HttpWaitNextEventInternal`. +void PostCompletionEvent(int64_t handle, HttpEventKind kind); + +// Platform-specific entry point implemented in `http_transport_{curl,apple}`. +void StartPlatformHttpOperation(const std::shared_ptr& op); + +// Case-insensitive ASCII equality helper shared by platform backends. +bool AsciiEqualsIgnoreCase(std::string_view a, std::string_view b); + +// Trims leading and trailing ASCII whitespace. +std::string_view TrimAsciiWhitespace(std::string_view s); + +// Validates an RFC 9110 HTTP method (non-empty `tchar` token). +bool IsValidHttpMethod(std::string_view method); + +// Validates an RFC 9110 HTTP header field-name (non-empty `tchar` token). +bool IsValidHeaderName(std::string_view name); + +// Validates an HTTP header field-value (rejects CR, LF, NUL, and non-HTAB +// control characters). +bool IsValidHeaderValue(std::string_view value); + +// Parses `Name\tValue\n` header lines into ordered pairs, preserving duplicate +// header names. Returns false if any line lacks the tab separator or contains +// CR, LF, NUL, an invalid header token name, or an invalid header value. +bool TryParsePackedHeaders( + std::string_view packed, + std::vector>* out); + +// Returns true if `url` starts with `http://` or `https://` (ASCII +// case-insensitive), has at least one character after the scheme, and contains +// no control characters or whitespace. Does not otherwise parse the URL. +bool IsHttpOrHttpsUrl(std::string_view url); + +} // namespace http +} // namespace firebase + +#endif // FIREBASE_APP_HTTP_HTTP_TRANSPORT_H_ diff --git a/app/http/http_transport_apple.mm b/app/http/http_transport_apple.mm new file mode 100644 index 0000000000..ca20931c3c --- /dev/null +++ b/app/http/http_transport_apple.mm @@ -0,0 +1,1088 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport.h" +#include "app/http/http_transport_apple_internal.h" + +#if !__has_feature(objc_arc) +#error "http_transport_apple.mm requires Objective-C ARC (-fobjc-arc)." +#endif + +@class FIRFirebaseHttpStreamBridge; +@class FIRFirebaseHttpSessionDelegate; + +namespace firebase { +namespace http { +namespace { + +NSString* ToNSString(std::string_view s) { + NSString* ns = [[NSString alloc] initWithBytes:s.data() + length:s.size() + encoding:NSUTF8StringEncoding]; + if (ns == nil) { + ns = [[NSString alloc] initWithBytes:s.data() + length:s.size() + encoding:NSISOLatin1StringEncoding]; + } + return ns != nil ? ns : @""; +} + +std::string FromNSString(NSString* ns) { + if (ns == nil) { + return std::string(); + } + const char* utf8 = [ns UTF8String]; + return utf8 != nullptr ? std::string(utf8) : std::string(); +} + +std::string ToLowerAscii(std::string_view s) { + std::string out(s.size(), '\0'); + for (size_t i = 0; i < s.size(); ++i) { + out[i] = static_cast(std::tolower(static_cast(s[i]))); + } + return out; +} + +bool IsSecureTransportCertError(NSInteger code) { + // Exact OSStatus codes from for server/client + // certificate and hostname verification failures (excludes TLS protocol, + // cipher negotiation, and handshake-alert failures which stay Connect). + switch (code) { + case -9807: // errSSLXCertChainInvalid + case -9808: // errSSLBadCert + case -9812: // errSSLUnknownRootCert + case -9813: // errSSLNoRootCert + case -9814: // errSSLCertExpired + case -9815: // errSSLCertNotYetValid + case -9825: // errSSLPeerBadCert + case -9826: // errSSLPeerUnsupportedCert + case -9827: // errSSLPeerCertRevoked + case -9828: // errSSLPeerCertExpired + case -9829: // errSSLPeerCertUnknown + case -9831: // errSSLPeerUnknownCA + case -9842: // errSSLClientCertRequested + case -9843: // errSSLHostNameMismatch + return true; + default: + return false; + } +} + +} // namespace + +HttpErrorClass ClassifyNSError(NSError* error) { + // First walk the full error chain to detect certificate verification failures + // even when iOS NSURLSession / ATS wraps them inside a top-level + // NSURLErrorSecureConnectionFailed (-1200). + NSError* cert_scan = error; + for (int depth = 0; cert_scan != nil && depth < 6; ++depth) { + NSString* domain = cert_scan.domain; + NSInteger code = cert_scan.code; + if ([domain isEqualToString:NSURLErrorDomain]) { + switch (code) { + case NSURLErrorServerCertificateHasBadDate: + case NSURLErrorServerCertificateUntrusted: + case NSURLErrorServerCertificateHasUnknownRoot: + case NSURLErrorServerCertificateNotYetValid: + case NSURLErrorClientCertificateRejected: + case NSURLErrorClientCertificateRequired: + return kHttpErrorCertificate; + default: + break; + } + } else if ([domain isEqualToString:@"kCFErrorDomainCFNetwork"]) { + if (code <= -1201 && code >= -1206) { + return kHttpErrorCertificate; + } + } else if ([domain isEqualToString:NSOSStatusErrorDomain] && + IsSecureTransportCertError(code)) { + return kHttpErrorCertificate; + } + + if (cert_scan.userInfo[NSURLErrorFailingURLPeerTrustErrorKey] != nil) { + return kHttpErrorCertificate; + } + NSNumber* stream_domain = cert_scan.userInfo[@"_kCFStreamErrorDomainKey"]; + NSNumber* stream_code = cert_scan.userInfo[@"_kCFStreamErrorCodeKey"]; + if ([stream_domain isKindOfClass:[NSNumber class]] && stream_domain.integerValue == 3 && + [stream_code isKindOfClass:[NSNumber class]] && + IsSecureTransportCertError(stream_code.integerValue)) { + return kHttpErrorCertificate; + } + + id underlying = cert_scan.userInfo[NSUnderlyingErrorKey]; + if ([underlying isKindOfClass:[NSError class]]) { + cert_scan = static_cast(underlying); + } else { + break; + } + } + + NSError* current = error; + for (int depth = 0; current != nil && depth < 6; ++depth) { + NSString* domain = current.domain; + NSInteger code = current.code; + if ([domain isEqualToString:NSURLErrorDomain]) { + switch (code) { + case NSURLErrorCancelled: + return kHttpErrorCanceled; + case NSURLErrorTimedOut: + return kHttpErrorTimeout; + case NSURLErrorServerCertificateHasBadDate: + case NSURLErrorServerCertificateUntrusted: + case NSURLErrorServerCertificateHasUnknownRoot: + case NSURLErrorServerCertificateNotYetValid: + case NSURLErrorClientCertificateRejected: + case NSURLErrorClientCertificateRequired: + return kHttpErrorCertificate; + // App Transport Security refused a cleartext URL before any I/O. + case NSURLErrorAppTransportSecurityRequiresSecureConnection: + return kHttpErrorInvalidRequest; + case NSURLErrorSecureConnectionFailed: + case NSURLErrorCannotFindHost: + case NSURLErrorCannotConnectToHost: + case NSURLErrorNetworkConnectionLost: + case NSURLErrorDNSLookupFailed: + case NSURLErrorNotConnectedToInternet: + case NSURLErrorInternationalRoamingOff: + case NSURLErrorCallIsActive: + case NSURLErrorDataNotAllowed: + return kHttpErrorConnect; + default: + break; + } + } else if ([domain isEqualToString:@"kCFErrorDomainCFNetwork"]) { + // Same numbering as NSURLError: -1200 is a failed TLS handshake, -1201 to + // -1206 are the server and client certificate errors. + if (code == -1200) { + return kHttpErrorConnect; + } + if (code <= -1201 && code >= -1206) { + return kHttpErrorCertificate; + } + if (code == -1001) { + return kHttpErrorTimeout; + } + } else if ([domain isEqualToString:NSPOSIXErrorDomain]) { + return kHttpErrorConnect; + } + + id underlying = current.userInfo[NSUnderlyingErrorKey]; + if ([underlying isKindOfClass:[NSError class]]) { + current = static_cast(underlying); + } else { + break; + } + } + return kHttpErrorOther; +} + +namespace { + +struct AppleSessionSlot { + NSURLSession* session = nil; + FIRFirebaseHttpSessionDelegate* delegate = nil; + bool pooled = false; +}; + +struct AppleTransferState { + std::shared_ptr op; + std::shared_ptr session_slot; + NSURLSessionDataTask* task = nil; + NSOutputStream* body_output_stream = nil; + FIRFirebaseHttpStreamBridge* stream_bridge = nil; + bool task_started = false; + bool task_suspended = false; + bool body_closed = false; + bool slot_released = false; + bool response_started = false; + std::atomic any_body_bytes_popped{false}; + std::vector pending_write_chunk; + size_t pending_write_offset = 0; + std::mutex state_mutex; +}; + +void CancelAppleTransferTask(const std::shared_ptr& state); +void ReleaseSessionSlot(const std::shared_ptr& slot, bool cancel_now); + +} // namespace +} // namespace http +} // namespace firebase + +@interface FIRFirebaseHttpStreamBridge : NSObject +- (instancetype)initWithState:(std::shared_ptr)state; +- (void)scheduleOutputStream:(NSOutputStream*)outputStream; +- (void)pumpWriteStream; +- (void)closeWriteStream; +@end + +@implementation FIRFirebaseHttpStreamBridge { + std::shared_ptr _state; + NSOutputStream* _ownedStream; + // NSStream.delegate is an unsafe_unretained (assign) property. Retain `self` + // explicitly from `scheduleOutputStream:` until `closeOnStreamThread` clears + // `stream.delegate = nil` and removes `stream` from the run loop. + FIRFirebaseHttpStreamBridge* _selfRetain; +} + ++ (NSThread*)streamThread { + static NSThread* sThread = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + dispatch_semaphore_t ready = dispatch_semaphore_create(0); + sThread = [[NSThread alloc] initWithTarget:self + selector:@selector(streamThreadMain:) + object:ready]; + sThread.name = @"com.google.firebase.http.stream"; + sThread.qualityOfService = NSQualityOfServiceUserInitiated; + [sThread start]; + // Wait until `streamThreadMain:` has created its NSRunLoop and attached its + // keep-alive port so the first `performSelector:onThread:` is never dropped. + dispatch_semaphore_wait(ready, DISPATCH_TIME_FOREVER); + }); + return sThread; +} + ++ (void)streamThreadMain:(id)readySemaphore { + @autoreleasepool { + NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; + [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; + if (readySemaphore != nil) { + dispatch_semaphore_signal(static_cast(readySemaphore)); + } + while (true) { + @autoreleasepool { + [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; + } + } + } +} + +- (instancetype)initWithState:(std::shared_ptr)state { + self = [super init]; + if (self != nil) { + _state = std::move(state); + } + return self; +} + +- (void)scheduleOutputStream:(NSOutputStream*)outputStream { + _ownedStream = outputStream; + _selfRetain = self; + [self performSelector:@selector(openOnStreamThread:) + onThread:[FIRFirebaseHttpStreamBridge streamThread] + withObject:outputStream + waitUntilDone:NO]; +} + +- (void)openOnStreamThread:(NSOutputStream*)outputStream { + auto state = _state; + if (!state || state->op->IsCanceled()) { + [self closeOnStreamThread]; + return; + } + bool active = false; + { + std::lock_guard lock(state->state_mutex); + active = !state->body_closed && state->body_output_stream == outputStream; + } + if (!active) { + outputStream.delegate = nil; + [outputStream close]; + _ownedStream = nil; + _state.reset(); + _selfRetain = nil; + return; + } + outputStream.delegate = self; + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [outputStream open]; + [self pumpOnStreamThread]; +} + +- (void)pumpWriteStream { + [self performSelector:@selector(pumpOnStreamThread) + onThread:[FIRFirebaseHttpStreamBridge streamThread] + withObject:nil + waitUntilDone:NO]; +} + +- (void)closeWriteStream { + [self performSelector:@selector(closeOnStreamThread) + onThread:[FIRFirebaseHttpStreamBridge streamThread] + withObject:nil + waitUntilDone:NO]; +} + +- (void)closeOnStreamThread { + auto state = _state; + NSOutputStream* stream = _ownedStream; + _ownedStream = nil; + bool close_write = false; + if (state) { + std::lock_guard lock(state->state_mutex); + if (state->stream_bridge == self) { + state->stream_bridge = nil; + } + if (state->body_output_stream == stream) { + state->body_closed = true; + state->body_output_stream = nil; + // After the response has started NSURLSession no longer asks for a new + // body stream, so the upload is over. Before that, `didReceiveResponse` + // closes the write side when it finds the stream already closed. + close_write = state->response_started; + } + } + if (close_write) { + state->op->MarkRequestWriteClosed(); + } + if (stream != nil) { + stream.delegate = nil; + [stream close]; + [stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + } + _state.reset(); + _selfRetain = nil; +} + +- (void)pumpOnStreamThread { + auto state = _state; + if (!state || state->op->IsCanceled()) { + [self closeOnStreamThread]; + return; + } + + NSOutputStream* stream = nil; + { + std::lock_guard lock(state->state_mutex); + if (state->body_closed || state->body_output_stream != _ownedStream || _ownedStream == nil) { + return; + } + stream = _ownedStream; + } + + constexpr size_t kSliceSize = 64 * 1024; + while ([stream hasSpaceAvailable]) { + if (state->pending_write_offset >= state->pending_write_chunk.size()) { + bool eof = false; + size_t popped = 0; + { + // Pop under `state_mutex` so `needNewBodyStream` either sees these + // bytes as taken or has already replaced this stream; it must never + // swap streams while a pop for the old one is in flight. + std::lock_guard lock(state->state_mutex); + if (state->body_output_stream != stream) { + return; + } + state->pending_write_chunk.resize(kSliceSize); + state->pending_write_offset = 0; + popped = state->op->PopRequestBytes(state->pending_write_chunk.data(), kSliceSize, &eof); + state->pending_write_chunk.resize(popped); + if (popped > 0) { + state->any_body_bytes_popped.store(true, std::memory_order_release); + } + } + if (popped == 0) { + if (eof) { + [self closeOnStreamThread]; + } + return; + } + } + + const uint8_t* ptr = state->pending_write_chunk.data() + state->pending_write_offset; + NSUInteger rem = + static_cast(state->pending_write_chunk.size() - state->pending_write_offset); + NSInteger written = [stream write:ptr maxLength:rem]; + if (written > 0) { + state->pending_write_offset += static_cast(written); + } else if (written < 0) { + // NSURLSession closes the bound input stream early when the server sends + // an early final response (such as a 413 or a 3xx). Do NOT call + // MarkFailed or cancel the task here; close the upload pipe and + // wake any blocked caller so NSURLSession can deliver the valid HTTP + // response or report the real transport NSError via didCompleteWithError. + state->op->MarkRequestWriteClosed(); + [self closeOnStreamThread]; + return; + } else { + break; + } + } +} + +- (void)stream:(NSStream*)aStream handleEvent:(NSStreamEvent)eventCode { + switch (eventCode) { + case NSStreamEventHasSpaceAvailable: + [self pumpOnStreamThread]; + break; + case NSStreamEventErrorOccurred: + case NSStreamEventEndEncountered: { + auto state = _state; + // With no body bytes consumed yet, NSURLSession may be about to ask for + // a fresh body stream (`needNewBodyStream`). Leave the upload pipe open + // so that stream can send the body from the start; if a response comes + // instead, `closeOnStreamThread` or `didReceiveResponse` closes it. + if (state && state->any_body_bytes_popped.load(std::memory_order_acquire)) { + state->op->MarkRequestWriteClosed(); + } + [self closeOnStreamThread]; + break; + } + default: + break; + } +} + +@end + +@interface FIRFirebaseHttpSessionDelegate : NSObject +- (void)registerState:(std::shared_ptr)state + forTaskKey:(NSString*)key; +- (std::shared_ptr)takeState:(NSURLSessionTask*)task; +@end + +@implementation FIRFirebaseHttpSessionDelegate { + std::mutex _mapMutex; + std::unordered_map> _tasks; +} + +- (std::shared_ptr)findState:(NSURLSessionTask*)task { + NSString* desc = task.taskDescription; + if (desc == nil) { + return nullptr; + } + std::string key = firebase::http::FromNSString(desc); + std::lock_guard lock(_mapMutex); + auto it = _tasks.find(key); + return it != _tasks.end() ? it->second : nullptr; +} + +- (std::shared_ptr)takeState:(NSURLSessionTask*)task { + NSString* desc = task.taskDescription; + if (desc == nil) { + return nullptr; + } + std::string key = firebase::http::FromNSString(desc); + std::lock_guard lock(_mapMutex); + auto it = _tasks.find(key); + if (it == _tasks.end()) { + return nullptr; + } + auto state = std::move(it->second); + _tasks.erase(it); + return state; +} + +- (void)registerState:(std::shared_ptr)state + forTaskKey:(NSString*)key { + std::string k = firebase::http::FromNSString(key); + std::lock_guard lock(_mapMutex); + _tasks[k] = std::move(state); +} + +- (void)URLSession:(NSURLSession*)session + task:(NSURLSessionTask*)task + needNewBodyStream:(void (^)(NSInputStream* _Nullable bodyStream))completionHandler { + auto state = [self findState:task]; + if (!state || state->op->IsCanceled()) { + completionHandler(nil); + return; + } + + // NSURLSession asks for a new body stream when it resends the request (for + // example after a stale keep-alive connection was reset). The upload pipe + // cannot be rewound: bytes already popped from it are gone. So the request + // can only start over while nothing has been popped; the old stream's + // teardown leaves the pipe open in that case (see `stream:handleEvent:`). + NSInputStream* in_stream = nil; + NSOutputStream* out_stream = nil; + [NSStream getBoundStreamsWithBufferSize:firebase::http::kMaxRequestBufferBytes + inputStream:&in_stream + outputStream:&out_stream]; + FIRFirebaseHttpStreamBridge* old_bridge = nil; + FIRFirebaseHttpStreamBridge* new_bridge = + [[FIRFirebaseHttpStreamBridge alloc] initWithState:state]; + bool can_restart = false; + { + std::lock_guard lock(state->state_mutex); + can_restart = !state->any_body_bytes_popped.load(std::memory_order_acquire); + if (can_restart) { + old_bridge = state->stream_bridge; + state->body_closed = false; + state->body_output_stream = out_stream; + state->stream_bridge = new_bridge; + } + } + if (!can_restart) { + state->op->MarkFailed("Request body cannot be replayed.", firebase::http::kHttpErrorConnect); + [task cancel]; + completionHandler(nil); + return; + } + if (old_bridge != nil) { + [old_bridge closeWriteStream]; + } + [new_bridge scheduleOutputStream:out_stream]; + completionHandler(in_stream); +} + +- (void)URLSession:(NSURLSession*)session + task:(NSURLSessionTask*)task + willPerformHTTPRedirection:(NSHTTPURLResponse*)response + newRequest:(NSURLRequest*)request + completionHandler:(void (^)(NSURLRequest* _Nullable))handler { + // The caller follows redirects. Refusing the redirect makes NSURLSession + // deliver the 3xx as the final response, with its `Location` header, through + // `didReceiveResponse`. + handler(nil); +} + +- (void)URLSession:(NSURLSession*)session + dataTask:(NSURLSessionDataTask*)dataTask + didReceiveResponse:(NSURLResponse*)response + completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { + auto state = [self findState:dataTask]; + if (!state || state->op->IsCanceled()) { + completionHandler(NSURLSessionResponseCancel); + return; + } + + if (![response isKindOfClass:[NSHTTPURLResponse class]]) { + state->op->MarkFailed("Unexpected non-HTTP URLResponse.", firebase::http::kHttpErrorOther); + completionHandler(NSURLSessionResponseCancel); + return; + } + + auto* httpResp = static_cast(response); + int32_t status = static_cast(httpResp.statusCode); + std::vector> headers; + NSDictionary* fields = httpResp.allHeaderFields; + for (id rawKey in fields) { + id rawVal = [fields objectForKey:rawKey]; + if ([rawKey isKindOfClass:[NSString class]] && [rawVal isKindOfClass:[NSString class]]) { + headers.emplace_back(firebase::http::FromNSString(static_cast(rawKey)), + firebase::http::FromNSString(static_cast(rawVal))); + } + } + + bool upload_stream_closed = false; + { + std::lock_guard lock(state->state_mutex); + state->response_started = true; + upload_stream_closed = state->body_closed; + } + // NSHTTPURLResponse does not expose the server's reason phrase. Report none; + // the caller substitutes its own default. + state->op->CommitResponseHeaders(status, "", std::move(headers)); + if (upload_stream_closed) { + // The upload stream ended before the response and left the pipe open in + // case of a restart (see `stream:handleEvent:`). No restart can follow now. + state->op->MarkRequestWriteClosed(); + } + completionHandler(NSURLSessionResponseAllow); +} + +- (void)URLSession:(NSURLSession*)session + dataTask:(NSURLSessionDataTask*)dataTask + didReceiveData:(NSData*)data { + auto state = [self findState:dataTask]; + if (!state || state->op->IsCanceled() || data == nil || data.length == 0) { + return; + } + + // Push incoming bytes in bounded slices and enforce true socket backpressure: + // `[dataTask suspend]` alone is asynchronous in CFNetwork and can allow tens + // of MiB to enqueue before taking effect. Because each active task runs on + // its own serial NSOperationQueue (from AppleSessionPool), suspending the + // task and waiting on `op->resp_cv` here bounds both `resp_buffered_bytes` + // and process resident memory without head-of-line blocking other concurrent + // requests. + constexpr size_t kSliceBytes = 256 * 1024; + [data enumerateByteRangesUsingBlock:^(const void* bytes, NSRange byteRange, BOOL* stop) { + const auto* ptr = static_cast(bytes); + size_t remaining = static_cast(byteRange.length); + size_t offset = 0; + while (remaining > 0) { + if (state->op->IsCanceled()) { + *stop = YES; + return; + } + size_t take = (std::min)(remaining, kSliceBytes); + bool over_high_water = state->op->PushResponseBytes(ptr + offset, take); + offset += take; + remaining -= take; + + if (over_high_water && !state->op->IsCanceled()) { + bool did_suspend = false; + { + std::lock_guard slock(state->state_mutex); + if (!state->task_suspended && !state->op->IsCanceled() && state->task != nil) { + state->task_suspended = true; + [state->task suspend]; + did_suspend = true; + } + } + { + std::unique_lock op_lock(state->op->mutex); + state->op->resp_cv.wait(op_lock, [&state]() { + return state->op->resp_buffered_bytes <= firebase::http::kLowWaterResponseBytes || + state->op->IsCanceled() || state->op->failed; + }); + } + if (did_suspend) { + std::lock_guard slock(state->state_mutex); + if (state->task_suspended && state->task != nil) { + state->task_suspended = false; + [state->task resume]; + } + } + } + } + }]; +} + +- (void)URLSession:(NSURLSession*)session + task:(NSURLSessionTask*)task + didCompleteWithError:(NSError*)error { + auto state = [self takeState:task]; + if (!state) { + return; + } + FIRFirebaseHttpStreamBridge* bridge = nil; + std::shared_ptr slot_to_release; + { + std::lock_guard lock(state->state_mutex); + state->task = nil; + state->task_suspended = false; + bridge = state->stream_bridge; + state->stream_bridge = nil; + if (!state->slot_released) { + state->slot_released = true; + slot_to_release = std::move(state->session_slot); + } + } + if (bridge != nil) { + [bridge closeWriteStream]; + } + if (slot_to_release) { + firebase::http::ReleaseSessionSlot(slot_to_release, /*cancel_now=*/false); + } + if (state->op->IsCanceled()) { + return; + } + if (error != nil) { + firebase::http::HttpErrorClass err_class = firebase::http::ClassifyNSError(error); + state->op->MarkFailed(firebase::http::FromNSString([error localizedDescription]), err_class); + } else { + state->op->MarkResponseComplete(); + } +} + +@end + +namespace firebase { +namespace http { + +NSURLSessionConfiguration* MakeBaseSessionConfig() { + NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + config.URLCache = nil; + config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever; + config.HTTPShouldSetCookies = NO; + config.HTTPMaximumConnectionsPerHost = 16; + // NSURLSession does not expose a connect-only timeout separate from the idle + // read timeout (`timeoutIntervalForRequest`). Keep these high so idle SSE + // streams are never killed; TCP connect relies on the OS SYN timeout, and + // caller CancellationTokens / watchdogs govern request lifetimes. + config.timeoutIntervalForRequest = 86400.0; + config.timeoutIntervalForResource = 86400.0; + return config; +} + +NSDictionary* MakeProxyDictionary(std::string_view proxy_url) { + NSURLComponents* proxy = [NSURLComponents componentsWithString:ToNSString(proxy_url)]; + NSString* scheme = proxy.scheme.lowercaseString; + bool is_https = [scheme isEqualToString:@"https"]; + NSString* host = proxy.host; + if (host.length >= 2 && [host hasPrefix:@"["] && [host hasSuffix:@"]"]) { + // IPv6 literal: the proxy dictionary takes the address without brackets. + host = [host substringWithRange:NSMakeRange(1, host.length - 2)]; + } + NSInteger port = proxy.port != nil ? proxy.port.integerValue : (is_https ? 443 : 80); + // Proxy credentials in the URL cannot be passed to NSURLSession this way. + if ((!is_https && ![scheme isEqualToString:@"http"]) || host.length == 0 || + proxy.user != nil || proxy.password != nil || port < 1 || port > 65535) { + return nil; + } + return @{ + @"HTTPEnable" : @YES, + @"HTTPProxy" : host, + @"HTTPPort" : @(port), + @"HTTPSEnable" : @YES, + @"HTTPSProxy" : host, + @"HTTPSPort" : @(port), + }; +} + +namespace { + +std::shared_ptr CreateSessionSlot(NSURLSessionConfiguration* config, + bool pooled) { + auto slot = std::make_shared(); + slot->pooled = pooled; + slot->delegate = [[FIRFirebaseHttpSessionDelegate alloc] init]; + NSOperationQueue* queue = [[NSOperationQueue alloc] init]; + queue.name = @"com.google.firebase.http.delegate"; + queue.maxConcurrentOperationCount = 1; + queue.qualityOfService = NSQualityOfServiceUserInitiated; + slot->session = [NSURLSession sessionWithConfiguration:config + delegate:slot->delegate + delegateQueue:queue]; + return slot; +} + +// Pool of reusable NSURLSessions (each with its own serial NSOperationQueue) so +// at most one in-flight task occupies a delegate queue at any time. This gives: +// - Warm connections for sequential requests: each in-flight request holds +// its own session, so concurrent requests do not share connections, but an +// idle pooled session is reused by a later request. +// - True bounded download memory via blocking in `didReceiveData:` without +// head-of-line blocking other concurrent transfers or SSE streams. +// - Zero session leaks when >16 requests overlap (overflow slots are +// invalidated cleanly on completion). +class AppleSessionPool { + public: + static AppleSessionPool& Instance() { + static auto* pool = new AppleSessionPool(); + return *pool; + } + + std::shared_ptr AcquireDefault() { + std::lock_guard lock(mutex_); + if (!idle_.empty()) { + auto slot = std::move(idle_.back()); + idle_.pop_back(); + return slot; + } + if (created_pooled_ < kMaxPooledSessions) { + ++created_pooled_; + return CreateSessionSlot(MakeBaseSessionConfig(), /*pooled=*/true); + } + return CreateSessionSlot(MakeBaseSessionConfig(), /*pooled=*/false); + } + + void Release(const std::shared_ptr& slot, bool cancel_now) { + if (!slot) { + return; + } + if (slot->pooled) { + std::lock_guard lock(mutex_); + idle_.push_back(slot); + return; + } + if (slot->session != nil) { + if (cancel_now) { + [slot->session invalidateAndCancel]; + } else { + [slot->session finishTasksAndInvalidate]; + } + slot->session = nil; + } + } + + private: + static constexpr size_t kMaxPooledSessions = 16; + std::mutex mutex_; + std::vector> idle_; + size_t created_pooled_ = 0; +}; + +void ReleaseSessionSlot(const std::shared_ptr& slot, bool cancel_now) { + AppleSessionPool::Instance().Release(slot, cancel_now); +} + +void CancelAppleTransferTask(const std::shared_ptr& state) { + if (!state) { + return; + } + FIRFirebaseHttpStreamBridge* bridge = nil; + NSURLSessionDataTask* t = nil; + FIRFirebaseHttpSessionDelegate* del = nil; + std::shared_ptr unstarted_slot; + bool was_suspended = false; + bool was_started = false; + { + std::lock_guard slock(state->state_mutex); + bridge = state->stream_bridge; + state->stream_bridge = nil; + t = state->task; + was_suspended = state->task_suspended; + was_started = state->task_started; + state->task_suspended = false; + state->task = nil; + if (state->session_slot) { + del = state->session_slot->delegate; + if (!was_started && !state->slot_released) { + state->slot_released = true; + unstarted_slot = std::move(state->session_slot); + } + } + } + if (bridge != nil) { + [bridge closeWriteStream]; + } + if (t != nil) { + if (!was_started && del != nil) { + // NSURLSession does not fire `didCompleteWithError:` for a task canceled + // before its initial `resume`; remove from `_tasks` here to avoid a leak. + [del takeState:t]; + } + // Balance any active suspend before cancelling; NSURLSession asserts if a + // task is cancelled or deallocated with suspend > 0. + if (was_suspended) { + [t resume]; + } + [t cancel]; + } + if (unstarted_slot) { + ReleaseSessionSlot(unstarted_slot, /*cancel_now=*/true); + } +} + +} // namespace + +void StartPlatformHttpOperation(const std::shared_ptr& op) { + @autoreleasepool { + if (op->IsCanceled()) { + return; + } + if (!IsHttpOrHttpsUrl(op->url)) { + op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", + kHttpErrorInvalidRequest); + return; + } + + bool is_get = AsciiEqualsIgnoreCase(op->method, "GET"); + bool is_head = AsciiEqualsIgnoreCase(op->method, "HEAD"); + if ((is_get || is_head) && + (op->content_length > 0 || op->content_length == kChunkedRequestContent)) { + op->MarkFailed("GET and HEAD requests cannot send a request body.", + kHttpErrorInvalidRequest); + return; + } + + NSURL* ns_url = [NSURL URLWithString:ToNSString(op->url)]; + if (ns_url == nil) { + op->MarkFailed("Invalid request URL.", kHttpErrorInvalidRequest); + return; + } + if (ns_url.user != nil || ns_url.password != nil) { + op->MarkFailed("Request URL must not contain user information.", kHttpErrorInvalidRequest); + return; + } + + // Validate proxy URL upfront and never silently fall back to direct. + std::shared_ptr slot; + if (!op->proxy_url.empty()) { + NSDictionary* proxy = MakeProxyDictionary(op->proxy_url); + if (proxy == nil) { + op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorInvalidRequest); + return; + } + NSURLSessionConfiguration* config = MakeBaseSessionConfig(); + config.connectionProxyDictionary = proxy; + slot = CreateSessionSlot(config, /*pooled=*/false); + } else { + slot = AppleSessionPool::Instance().AcquireDefault(); + } + + NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:ns_url]; + req.HTTPMethod = ToNSString(op->method); + req.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + req.HTTPShouldHandleCookies = NO; + + bool has_content_length = false; + bool has_accept_encoding = false; + std::unordered_set seen_headers; + for (const auto& kv : op->request_headers) { + if (AsciiEqualsIgnoreCase(kv.first, "Content-Length")) { + has_content_length = true; + } else if (AsciiEqualsIgnoreCase(kv.first, "Accept-Encoding")) { + has_accept_encoding = true; + } + NSString* field = ToNSString(kv.first); + NSString* value = ToNSString(kv.second); + if (seen_headers.insert(ToLowerAscii(kv.first)).second) { + [req setValue:value forHTTPHeaderField:field]; + } else { + [req addValue:value forHTTPHeaderField:field]; + } + } + if (!has_accept_encoding) { + // Match .NET HttpClientHandler (AutomaticDecompression = None) and + // Desktop libcurl so NSURLSession does not inject `Accept-Encoding: gzip`, + // strip Content-Length, buffer SSE frames, or corrupt Range offsets. + [req setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"]; + } + + auto state = std::make_shared(); + state->op = op; + state->session_slot = slot; + + FIRFirebaseHttpStreamBridge* stream_bridge = nil; + NSOutputStream* out_stream = nil; + if (op->content_length == 0 && !is_get && !is_head) { + req.HTTPBody = [NSData data]; + if (!has_content_length) { + [req setValue:@"0" forHTTPHeaderField:@"Content-Length"]; + } + } else if (op->content_length > 0 || op->content_length == kChunkedRequestContent) { + NSInputStream* in_stream = nil; + [NSStream getBoundStreamsWithBufferSize:kMaxRequestBufferBytes + inputStream:&in_stream + outputStream:&out_stream]; + req.HTTPBodyStream = in_stream; + if (op->content_length > 0 && !has_content_length) { + [req setValue:[NSString + stringWithFormat:@"%lld", static_cast(op->content_length)] + forHTTPHeaderField:@"Content-Length"]; + } + stream_bridge = [[FIRFirebaseHttpStreamBridge alloc] initWithState:state]; + state->body_output_stream = out_stream; + state->stream_bridge = stream_bridge; + } else if (!has_content_length && (AsciiEqualsIgnoreCase(op->method, "POST") || + AsciiEqualsIgnoreCase(op->method, "PUT") || + AsciiEqualsIgnoreCase(op->method, "PATCH"))) { + req.HTTPBody = [NSData data]; + [req setValue:@"0" forHTTPHeaderField:@"Content-Length"]; + } + + NSURLSessionDataTask* task = [slot->session dataTaskWithRequest:req]; + NSString* key = [NSString stringWithFormat:@"%lld", static_cast(op->id)]; + task.taskDescription = key; + { + // Write `state->task` under `state_mutex` before registering or starting + // the stream thread (P4). + std::lock_guard slock(state->state_mutex); + state->task = task; + } + + [slot->delegate registerState:state forTaskKey:key]; + + bool already_canceled = false; + { + std::weak_ptr weak_state = state; + std::lock_guard lock(op->mutex); + if (op->IsCanceled()) { + already_canceled = true; + } else { + if (stream_bridge != nil) { + op->on_request_data_changed = [weak_state]() { + auto locked = weak_state.lock(); + if (!locked) { + return; + } + FIRFirebaseHttpStreamBridge* bridge = nil; + { + std::lock_guard slock(locked->state_mutex); + bridge = locked->stream_bridge; + } + if (bridge != nil) { + [bridge pumpWriteStream]; + } + }; + } + op->on_cancel = [weak_state]() { CancelAppleTransferTask(weak_state.lock()); }; + } + } + + if (already_canceled) { + [slot->delegate takeState:task]; + std::shared_ptr to_release; + { + std::lock_guard slock(state->state_mutex); + state->stream_bridge = nil; + state->body_output_stream = nil; + state->body_closed = true; + state->task = nil; + if (!state->slot_released) { + state->slot_released = true; + to_release = std::move(state->session_slot); + } + } + [task cancel]; + if (to_release) { + ReleaseSessionSlot(to_release, /*cancel_now=*/true); + } + return; + } + + // Coordinate initial `[task resume]` with `CancelAppleTransferTask` under + // `state_mutex` so a cancel racing before `resume` cannot leave a never- + // resumed task stranded in `_tasks` or leak a session slot. + bool should_cleanup_unstarted = false; + bool started_now = false; + std::shared_ptr unstarted_release; + { + std::lock_guard slock(state->state_mutex); + if (state->task != nil && !op->IsCanceled()) { + state->task_started = true; + started_now = true; + [task resume]; + } else if (state->task != nil) { + state->task = nil; + state->stream_bridge = nil; + state->body_output_stream = nil; + state->body_closed = true; + should_cleanup_unstarted = true; + if (!state->slot_released) { + state->slot_released = true; + unstarted_release = std::move(state->session_slot); + } + } + } + if (started_now && stream_bridge != nil && out_stream != nil) { + [stream_bridge scheduleOutputStream:out_stream]; + } + if (should_cleanup_unstarted) { + [slot->delegate takeState:task]; + [task cancel]; + if (unstarted_release) { + ReleaseSessionSlot(unstarted_release, /*cancel_now=*/true); + } + } + } +} + +} // namespace http +} // namespace firebase diff --git a/app/http/http_transport_apple_internal.h b/app/http/http_transport_apple_internal.h new file mode 100644 index 0000000000..4b0f2d6c55 --- /dev/null +++ b/app/http/http_transport_apple_internal.h @@ -0,0 +1,47 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Helpers shared by the Apple backends (`http_transport_apple.mm` and +// `websocket_apple.mm`). Defined in `http_transport_apple.mm`. + +#ifndef FIREBASE_APP_HTTP_HTTP_TRANSPORT_APPLE_INTERNAL_H_ +#define FIREBASE_APP_HTTP_HTTP_TRANSPORT_APPLE_INTERNAL_H_ + +#import + +#include + +#include "app/http/http_transport.h" + +namespace firebase { +namespace http { + +// Maps an NSURLSession error, or one of its underlying errors, to an error +// class. +HttpErrorClass ClassifyNSError(NSError* error); + +// Returns a new ephemeral session configuration without cache or cookies. +NSURLSessionConfiguration* MakeBaseSessionConfig(); + +// Returns the `connectionProxyDictionary` for an `http` or `https` proxy URL, +// or nil when `proxy_url` cannot be used. The port defaults to 80 for `http` +// and 443 for `https`. +NSDictionary* MakeProxyDictionary(std::string_view proxy_url); + +} // namespace http +} // namespace firebase + +#endif // FIREBASE_APP_HTTP_HTTP_TRANSPORT_APPLE_INTERNAL_H_ diff --git a/app/http/http_transport_common.cc b/app/http/http_transport_common.cc new file mode 100644 index 0000000000..1cd45c2f32 --- /dev/null +++ b/app/http/http_transport_common.cc @@ -0,0 +1,828 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +#include "app/http/http_transport.h" +#include "app/http/websocket.h" + +namespace firebase { +namespace http { +namespace { + +struct CompletionQueue { + std::mutex mutex; + std::condition_variable cv; + std::deque events; + bool wake_requested = false; +}; + +CompletionQueue& GetCompletionQueue() { + static auto* queue = new CompletionQueue(); + return *queue; +} + +struct OperationRegistry { + std::mutex mutex; + int64_t next_id = 1; + std::unordered_map> operations; +}; + +OperationRegistry& GetRegistry() { + static auto* registry = new OperationRegistry(); + return *registry; +} + +bool HasControlOrWhitespace(std::string_view s) { + for (unsigned char ch : s) { + if (ch <= 0x20 || ch == 0x7F) { + return true; + } + } + return false; +} + +// Trims only HTTP OWS (SP and HTAB) so control characters like CR/LF/VT/FF +// remain visible to header validation instead of being silently stripped. +std::string_view TrimHttpOws(std::string_view s) { + while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) { + s.remove_prefix(1); + } + while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) { + s.remove_suffix(1); + } + return s; +} + +bool IsHttpTchar(unsigned char ch) { + if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || + (ch >= '0' && ch <= '9')) { + return true; + } + switch (ch) { + case '!': + case '#': + case '$': + case '%': + case '&': + case '\'': + case '*': + case '+': + case '-': + case '.': + case '^': + case '_': + case '`': + case '|': + case '~': + return true; + default: + return false; + } +} + +void CancelOperationObject(const std::shared_ptr& op) { + if (!op) { + return; + } + bool expected = false; + if (!op->canceled.compare_exchange_strong(expected, true, + std::memory_order_acq_rel)) { + return; + } + + int64_t handle = op->id; + std::function cancel_hook; + bool notify_req = false; + bool notify_headers = false; + bool notify_body = false; + { + std::lock_guard lock(op->mutex); + if (!op->failed && op->error_class == kHttpErrorNone) { + op->error_class = kHttpErrorCanceled; + } + cancel_hook = std::move(op->on_cancel); + op->on_cancel = nullptr; + op->on_request_data_changed = nullptr; + op->on_response_space_available = nullptr; + if (op->req_space_armed) { + op->req_space_armed = false; + notify_req = true; + } + if (op->resp_headers_armed) { + op->resp_headers_armed = false; + notify_headers = true; + } + if (op->resp_read_armed) { + op->resp_read_armed = false; + notify_body = true; + } + } + op->req_cv.notify_all(); + op->resp_cv.notify_all(); + if (cancel_hook) { + cancel_hook(); + } + if (notify_req) { + PostCompletionEvent(handle, kHttpEventRequestSpaceAvailable); + } + if (notify_headers) { + PostCompletionEvent(handle, kHttpEventResponseHeadersReady); + } + if (notify_body) { + PostCompletionEvent(handle, kHttpEventResponseBodyAvailable); + } +} + +} // namespace + +bool IsValidHeaderName(std::string_view name) { + if (name.empty()) { + return false; + } + for (unsigned char ch : name) { + if (!IsHttpTchar(ch)) { + return false; + } + } + return true; +} + +bool IsValidHttpMethod(std::string_view method) { + // A method is a token, the same grammar as a header field-name. + return IsValidHeaderName(method); +} + +bool IsValidHeaderValue(std::string_view value) { + for (unsigned char ch : value) { + if (ch == '\0' || ch == '\r' || ch == '\n' || + (ch < 0x20 && ch != '\t') || ch == 0x7F) { + return false; + } + } + return true; +} + +bool TryParsePackedHeaders( + std::string_view packed, + std::vector>* out) { + if (out == nullptr) { + return false; + } + out->clear(); + if (packed.find('\0') != std::string_view::npos) { + return false; + } + + size_t pos = 0; + while (pos < packed.size()) { + size_t nl = packed.find('\n', pos); + std::string_view line = nl == std::string_view::npos + ? packed.substr(pos) + : packed.substr(pos, nl - pos); + pos = nl == std::string_view::npos ? packed.size() : nl + 1; + if (!line.empty() && line.back() == '\r') { + line.remove_suffix(1); + } + if (line.empty()) { + continue; + } + // Reject any interior CR (header injection). + if (line.find('\r') != std::string_view::npos) { + out->clear(); + return false; + } + size_t sep = line.find('\t'); + if (sep == std::string_view::npos || sep == 0) { + out->clear(); + return false; + } + std::string_view name = line.substr(0, sep); + std::string_view value = TrimHttpOws(line.substr(sep + 1)); + if (!IsValidHeaderName(name) || !IsValidHeaderValue(value)) { + out->clear(); + return false; + } + out->emplace_back(std::string(name), std::string(value)); + } + return true; +} + +bool AsciiEqualsIgnoreCase(std::string_view a, std::string_view b) { + if (a.size() != b.size()) { + return false; + } + for (size_t i = 0; i < a.size(); ++i) { + if (std::tolower(static_cast(a[i])) != + std::tolower(static_cast(b[i]))) { + return false; + } + } + return true; +} + +std::string_view TrimAsciiWhitespace(std::string_view s) { + while (!s.empty() && + std::isspace(static_cast(s.front())) != 0) { + s.remove_prefix(1); + } + while (!s.empty() && + std::isspace(static_cast(s.back())) != 0) { + s.remove_suffix(1); + } + return s; +} + +bool IsHttpOrHttpsUrl(std::string_view url) { + for (std::string_view scheme : + {std::string_view("http://"), std::string_view("https://")}) { + if (url.size() > scheme.size() && + AsciiEqualsIgnoreCase(url.substr(0, scheme.size()), scheme)) { + return !HasControlOrWhitespace(url); + } + } + return false; +} + +void PostCompletionEvent(int64_t handle, HttpEventKind kind) { + if (handle <= 0 || kind == kHttpEventNone) { + return; + } + int64_t packed = (handle << 8) | (static_cast(kind) & 0xFF); + auto& q = GetCompletionQueue(); + { + std::lock_guard lock(q.mutex); + q.events.push_back(packed); + } + q.cv.notify_one(); +} + +int64_t AllocateTransportHandle() { + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + return reg.next_id++; +} + +int64_t CreateOperation(HttpRequestOptions options) { + auto op = std::make_shared(); + op->method = options.method.empty() ? "GET" : std::move(options.method); + op->url = std::move(options.url); + op->request_headers = std::move(options.headers); + op->proxy_url = std::move(options.proxy_url); + op->content_length = options.content_length; + if (op->content_length == kNoRequestContent || op->content_length == 0) { + op->req_eof = true; + } + + std::string validation_error; + if (!IsValidHttpMethod(op->method)) { + validation_error = "Invalid HTTP request method."; + } else if (op->content_length < kNoRequestContent) { + validation_error = "Invalid request content_length."; + } else { + for (const auto& kv : op->request_headers) { + if (!IsValidHeaderName(kv.first) || !IsValidHeaderValue(kv.second)) { + validation_error = "Invalid HTTP request header."; + break; + } + } + } + + auto& reg = GetRegistry(); + int64_t id = 0; + { + std::lock_guard lock(reg.mutex); + id = reg.next_id++; + op->id = id; + reg.operations.emplace(id, op); + } + if (!validation_error.empty()) { + op->MarkFailed(validation_error, kHttpErrorInvalidRequest); + } + return id; +} + +std::shared_ptr FindOperation(int64_t handle) { + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + auto it = reg.operations.find(handle); + return it != reg.operations.end() ? it->second : nullptr; +} + +void StartOperation(int64_t handle) { + auto op = FindOperation(handle); + if (!op) { + return; + } + if (op->started.exchange(true, std::memory_order_acq_rel)) { + return; + } + { + std::lock_guard lock(op->mutex); + if (op->failed || op->IsCanceled()) { + return; + } + } + StartPlatformHttpOperation(op); +} + +void CancelOperation(int64_t handle) { + CancelOperationObject(FindOperation(handle)); +} + +void DestroyOperation(int64_t handle) { + CancelOperation(handle); + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + reg.operations.erase(handle); +} + +void CancelAllOperations() { + std::vector> snapshot; + { + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + snapshot.reserve(reg.operations.size()); + for (auto& kv : reg.operations) { + snapshot.push_back(std::move(kv.second)); + } + reg.operations.clear(); + } + for (const auto& op : snapshot) { + CancelOperationObject(op); + } + CancelAllWebSockets(); + HttpWakeEventPumpInternal(); +} + +void HttpOperation::CommitResponseHeaders( + int32_t status, std::string_view reason, + std::vector> headers) { + bool notify = false; + { + std::lock_guard lock(mutex); + if (headers_ready || failed || IsCanceled()) { + return; + } + status_code = status; + reason_phrase.assign(reason.data(), reason.size()); + response_headers = std::move(headers); + headers_ready = true; + if (resp_headers_armed) { + resp_headers_armed = false; + notify = true; + } + } + if (notify) { + PostCompletionEvent(id, kHttpEventResponseHeadersReady); + } +} + +void HttpOperation::MarkRequestWriteClosed() { + bool notify_req = false; + { + std::lock_guard lock(mutex); + req_write_closed = true; + req_chunks.clear(); + req_buffered_bytes = 0; + on_request_data_changed = nullptr; + if (req_space_armed) { + req_space_armed = false; + notify_req = true; + } + } + req_cv.notify_all(); + if (notify_req) { + PostCompletionEvent(id, kHttpEventRequestSpaceAvailable); + } +} + +bool HttpOperation::PushResponseBytes(const uint8_t* bytes, size_t length) { + if (length == 0) { + std::lock_guard lock(mutex); + return resp_buffered_bytes >= kMaxResponseBufferBytes; + } + ByteChunk chunk; + chunk.data.assign(bytes, bytes + length); + + bool notify = false; + bool over_high_water = false; + { + std::lock_guard lock(mutex); + if (failed || IsCanceled()) { + return false; + } + resp_buffered_bytes += length; + resp_chunks.push_back(std::move(chunk)); + over_high_water = resp_buffered_bytes >= kMaxResponseBufferBytes; + if (resp_read_armed) { + resp_read_armed = false; + notify = true; + } + } + if (notify) { + PostCompletionEvent(id, kHttpEventResponseBodyAvailable); + } + return over_high_water; +} + +void HttpOperation::MarkResponseComplete() { + bool notify_req = false; + bool notify_headers = false; + bool notify_body = false; + { + std::lock_guard lock(mutex); + resp_eof = true; + req_write_closed = true; + req_chunks.clear(); + req_buffered_bytes = 0; + on_request_data_changed = nullptr; + on_response_space_available = nullptr; + on_cancel = nullptr; + if (req_space_armed) { + req_space_armed = false; + notify_req = true; + } + if (resp_headers_armed) { + resp_headers_armed = false; + notify_headers = true; + } + if (resp_read_armed) { + resp_read_armed = false; + notify_body = true; + } + } + req_cv.notify_all(); + if (notify_req) { + PostCompletionEvent(id, kHttpEventRequestSpaceAvailable); + } + if (notify_headers) { + PostCompletionEvent(id, kHttpEventResponseHeadersReady); + } + if (notify_body) { + PostCompletionEvent(id, kHttpEventResponseBodyAvailable); + } +} + +void HttpOperation::MarkFailed(std::string_view message, + HttpErrorClass err_class) { + bool notify_req = false; + bool notify_headers = false; + bool notify_body = false; + { + std::lock_guard lock(mutex); + if (!failed) { + failed = true; + error_class = err_class == kHttpErrorNone ? kHttpErrorOther : err_class; + error_message.assign(message.data(), message.size()); + } + req_write_closed = true; + on_request_data_changed = nullptr; + on_response_space_available = nullptr; + on_cancel = nullptr; + if (req_space_armed) { + req_space_armed = false; + notify_req = true; + } + if (resp_headers_armed) { + resp_headers_armed = false; + notify_headers = true; + } + if (resp_read_armed) { + resp_read_armed = false; + notify_body = true; + } + } + req_cv.notify_all(); + resp_cv.notify_all(); + if (notify_req) { + PostCompletionEvent(id, kHttpEventRequestSpaceAvailable); + } + if (notify_headers) { + PostCompletionEvent(id, kHttpEventResponseHeadersReady); + } + if (notify_body) { + PostCompletionEvent(id, kHttpEventResponseBodyAvailable); + } +} + +size_t HttpOperation::PopRequestBytes(uint8_t* dest, size_t max_bytes, + bool* out_eof) { + size_t copied = 0; + bool notify_space = false; + { + std::lock_guard lock(mutex); + while (copied < max_bytes && !req_chunks.empty()) { + ByteChunk& front = req_chunks.front(); + size_t take = (std::min)(max_bytes - copied, front.remaining()); + std::memcpy(dest + copied, front.data.data() + front.offset, take); + front.offset += take; + copied += take; + req_buffered_bytes -= take; + if (front.remaining() == 0) { + req_chunks.pop_front(); + } + } + if (out_eof != nullptr) { + *out_eof = req_chunks.empty() && req_eof; + } + if (req_space_armed && req_buffered_bytes <= kLowWaterRequestBytes) { + req_space_armed = false; + notify_space = true; + } + } + if (notify_space) { + PostCompletionEvent(id, kHttpEventRequestSpaceAvailable); + } + return copied; +} + +} // namespace http + +int64_t HttpCreateRequestInternal(const char* method, const char* url, + const char* headers_packed, + const char* proxy_url, + int64_t content_length) { + http::HttpRequestOptions options; + options.method = method != nullptr ? method : "GET"; + options.url = url != nullptr ? url : ""; + bool invalid_headers = false; + if (headers_packed != nullptr && headers_packed[0] != '\0') { + if (!http::TryParsePackedHeaders(headers_packed, &options.headers)) { + invalid_headers = true; + } + } + if (proxy_url != nullptr && proxy_url[0] != '\0') { + options.proxy_url = proxy_url; + } + options.content_length = content_length; + int64_t handle = http::CreateOperation(std::move(options)); + if (invalid_headers) { + if (auto op = http::FindOperation(handle)) { + op->MarkFailed("Invalid HTTP request header.", + http::kHttpErrorInvalidRequest); + } + } + return handle; +} + +void HttpStartRequestInternal(int64_t handle) { http::StartOperation(handle); } + +int32_t HttpTryWriteRequestBodyInternal(int64_t handle, void* data, + int32_t length) { + if (length < 0 || data == nullptr) { + return -1; + } + auto op = http::FindOperation(handle); + if (!op) { + return -1; + } + if (length == 0) { + std::lock_guard lock(op->mutex); + if (op->failed || op->IsCanceled()) { + return -1; + } + if (op->req_write_closed || op->resp_eof) { + return http::kHttpWriteClosed; + } + return 0; + } + + std::function notify_backend; + int32_t to_write = 0; + { + std::lock_guard lock(op->mutex); + if (op->failed || op->IsCanceled()) { + return -1; + } + if (op->req_write_closed || op->resp_eof) { + return http::kHttpWriteClosed; + } + size_t available = + op->req_buffered_bytes < http::kMaxRequestBufferBytes + ? http::kMaxRequestBufferBytes - op->req_buffered_bytes + : 0; + size_t accepted = (std::min)(static_cast(length), available); + if (accepted > 0) { + http::ByteChunk chunk; + const auto* src = static_cast(data); + chunk.data.assign(src, src + accepted); + op->req_chunks.push_back(std::move(chunk)); + op->req_buffered_bytes += accepted; + to_write = static_cast(accepted); + notify_backend = op->on_request_data_changed; + } + if (accepted < static_cast(length)) { + op->req_space_armed = true; + } + } + if (to_write > 0) { + op->req_cv.notify_all(); + if (notify_backend) { + notify_backend(); + } + } + return to_write; +} + +void HttpFinishRequestBodyInternal(int64_t handle) { + auto op = http::FindOperation(handle); + if (!op) { + return; + } + std::function notify_backend; + { + std::lock_guard lock(op->mutex); + if (op->req_write_closed) { + return; + } + op->req_eof = true; + notify_backend = op->on_request_data_changed; + } + op->req_cv.notify_all(); + if (notify_backend) { + notify_backend(); + } +} + +int32_t HttpPollResponseHeadersInternal(int64_t handle) { + auto op = http::FindOperation(handle); + if (!op) { + return -1; + } + std::lock_guard lock(op->mutex); + if (op->IsCanceled() || (op->failed && !op->headers_ready)) { + return -1; + } + if (op->headers_ready) { + return op->status_code; + } + if (op->resp_eof) { + return -1; + } + op->resp_headers_armed = true; + return 0; +} + +std::string HttpGetResponseHeadersInternal(int64_t handle) { + auto op = http::FindOperation(handle); + if (!op) { + return std::string(); + } + std::lock_guard lock(op->mutex); + std::string out; + out.append(op->reason_phrase); + out.push_back('\n'); + for (const auto& kv : op->response_headers) { + out.append(kv.first); + out.push_back('\t'); + out.append(kv.second); + out.push_back('\n'); + } + return out; +} + +int32_t HttpTryReadResponseBodyInternal(int64_t handle, void* dest, + int32_t max_length) { + if (max_length <= 0 || dest == nullptr) { + return http::kHttpReadErrorOrCanceled; + } + auto op = http::FindOperation(handle); + if (!op) { + return http::kHttpReadErrorOrCanceled; + } + + size_t copied = 0; + bool crossed_low_water = false; + std::function resume_backend; + { + std::lock_guard lock(op->mutex); + if (op->IsCanceled()) { + return http::kHttpReadErrorOrCanceled; + } + size_t before = op->resp_buffered_bytes; + auto* out = static_cast(dest); + size_t want = static_cast(max_length); + while (copied < want && !op->resp_chunks.empty()) { + http::ByteChunk& front = op->resp_chunks.front(); + size_t take = (std::min)(want - copied, front.remaining()); + std::memcpy(out + copied, front.data.data() + front.offset, take); + front.offset += take; + copied += take; + op->resp_buffered_bytes -= take; + if (front.remaining() == 0) { + op->resp_chunks.pop_front(); + } + } + if (copied > 0) { + if (before >= http::kLowWaterResponseBytes && + op->resp_buffered_bytes <= http::kLowWaterResponseBytes) { + crossed_low_water = true; + resume_backend = op->on_response_space_available; + } + } else { + if (op->failed) { + return http::kHttpReadErrorOrCanceled; + } + if (op->resp_eof) { + return 0; + } + op->resp_read_armed = true; + return http::kHttpReadWouldBlock; + } + } + + if (crossed_low_water) { + op->resp_cv.notify_all(); + if (resume_backend) { + resume_backend(); + } + } else if (copied > 0) { + op->resp_cv.notify_all(); + } + return static_cast(copied); +} + +std::string HttpGetErrorInternal(int64_t handle) { + auto op = http::FindOperation(handle); + if (!op) { + return std::string(); + } + std::lock_guard lock(op->mutex); + return op->error_message; +} + +int32_t HttpGetErrorClassInternal(int64_t handle) { + auto op = http::FindOperation(handle); + if (!op) { + return http::kHttpErrorOther; + } + std::lock_guard lock(op->mutex); + if (op->IsCanceled() && !op->failed) { + return http::kHttpErrorCanceled; + } + return static_cast(op->error_class); +} + +void HttpCancelRequestInternal(int64_t handle) { + http::CancelOperation(handle); +} + +void HttpDestroyRequestInternal(int64_t handle) { + http::DestroyOperation(handle); +} + +void HttpCancelAllRequestsInternal() { http::CancelAllOperations(); } + +int64_t HttpWaitNextEventInternal(int32_t timeout_ms) { + auto& q = http::GetCompletionQueue(); + std::unique_lock lock(q.mutex); + if (q.events.empty() && !q.wake_requested && timeout_ms != 0) { + if (timeout_ms < 0) { + q.cv.wait(lock, [&q] { return !q.events.empty() || q.wake_requested; }); + } else { + q.cv.wait_for(lock, std::chrono::milliseconds(timeout_ms), + [&q] { return !q.events.empty() || q.wake_requested; }); + } + } + if (q.wake_requested) { + q.wake_requested = false; + if (q.events.empty()) { + return 0; + } + } + if (q.events.empty()) { + return 0; + } + int64_t ev = q.events.front(); + q.events.pop_front(); + return ev; +} + +void HttpWakeEventPumpInternal() { + auto& q = http::GetCompletionQueue(); + { + std::lock_guard lock(q.mutex); + q.wake_requested = true; + } + q.cv.notify_all(); +} + +} // namespace firebase diff --git a/app/http/http_transport_curl.cc b/app/http/http_transport_curl.cc new file mode 100644 index 0000000000..500c7933fc --- /dev/null +++ b/app/http/http_transport_curl.cc @@ -0,0 +1,715 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport.h" +#include "app/http/http_transport_curl_internal.h" +#if defined(__ANDROID__) +#include "app/http/http_transport_curl_platform.h" +#endif // defined(__ANDROID__) +#include "app/rest/curl/curl_handles.h" +#include "app/rest/curl/tls_policy.h" +#include "curl/curl.h" + +namespace firebase { +namespace http { +namespace { + +using ::firebase::rest::curl::ApplyOpt; + +bool HasHeaderIgnoreCase( + const std::vector>& headers, + std::string_view target) { + for (const auto& kv : headers) { + if (AsciiEqualsIgnoreCase(kv.first, target)) { + return true; + } + } + return false; +} + +bool AppendSList(::firebase::rest::curl::UniqueSList* list, const char* line) { + curl_slist* next = curl_slist_append(list->get(), line); + if (next == nullptr) { + return false; + } + list->release(); + list->reset(next); + return true; +} + +} // namespace + +HttpErrorClass ClassifyCurlError(CURLcode code, bool canceled) { + if (canceled) { + return kHttpErrorCanceled; + } + switch (code) { + case CURLE_OPERATION_TIMEDOUT: + return kHttpErrorTimeout; + // The peer certificate or host name was rejected, or the local trust or + // client certificate configuration is unusable. + case CURLE_PEER_FAILED_VERIFICATION: + case CURLE_SSL_CACERT_BADFILE: + case CURLE_SSL_CRL_BADFILE: + case CURLE_SSL_ISSUER_ERROR: + case CURLE_SSL_PINNEDPUBKEYNOTMATCH: + case CURLE_SSL_INVALIDCERTSTATUS: + case CURLE_SSL_CERTPROBLEM: + case CURLE_SSL_CLIENTCERT: + return kHttpErrorCertificate; + // Name resolution, TCP, and TLS handshake or record failures. + case CURLE_COULDNT_RESOLVE_PROXY: + case CURLE_COULDNT_RESOLVE_HOST: + case CURLE_COULDNT_CONNECT: + case CURLE_GOT_NOTHING: + case CURLE_SEND_ERROR: + case CURLE_RECV_ERROR: + case CURLE_PARTIAL_FILE: + case CURLE_INTERFACE_FAILED: + case CURLE_SSL_CONNECT_ERROR: + case CURLE_SSL_CIPHER: + case CURLE_USE_SSL_FAILED: + case CURLE_SSL_SHUTDOWN_FAILED: + case CURLE_SSL_ENGINE_NOTFOUND: + case CURLE_SSL_ENGINE_SETFAILED: + case CURLE_SSL_ENGINE_INITFAILED: + return kHttpErrorConnect; + // libcurl rejected the URL before opening a connection (malformed, or + // carrying userinfo, which CURLOPT_DISALLOW_USERNAME_IN_URL refuses). + case CURLE_URL_MALFORMAT: + case CURLE_LOGIN_DENIED: + return kHttpErrorInvalidRequest; + default: + return kHttpErrorOther; + } +} + +std::optional ApplyCurlConnectionOptions( + CURL* easy, const char* protocols, const std::string& proxy_url) { + // A TLS policy that cannot be applied is a local setup failure, not a + // rejected peer certificate. + CURLcode tls_rc = ::firebase::rest::curl::ApplyTlsPolicy(easy); + if (tls_rc != CURLE_OK) { + return CurlSetupError{kHttpErrorOther, curl_easy_strerror(tls_rc)}; + } +#if defined(__ANDROID__) + // Key-exchange groups and the system trust store for the bundled BoringSSL. + // Without trusted roots the connection fails here; it never connects + // unverified. + CURLcode android_tls_rc = ApplyAndroidTlsSettings(easy); + if (android_tls_rc == CURLE_SSL_CACERT_BADFILE) { + return CurlSetupError{kHttpErrorCertificate, kAndroidNoTrustedRootsError}; + } + if (android_tls_rc != CURLE_OK) { + return CurlSetupError{kHttpErrorOther, curl_easy_strerror(android_tls_rc)}; + } +#endif // defined(__ANDROID__) + + CURLcode opt_err = CURLE_OK; + ApplyOpt(easy, CURLOPT_NOSIGNAL, 1L, &opt_err); + ApplyOpt(easy, CURLOPT_PROTOCOLS_STR, protocols, &opt_err); + ApplyOpt(easy, CURLOPT_UNRESTRICTED_AUTH, 0L, &opt_err); + // Never turn `user:password@` in a URL into Basic credentials. + ApplyOpt(easy, CURLOPT_DISALLOW_USERNAME_IN_URL, 1L, &opt_err); + // Redirects are not followed: a 3xx is delivered as an ordinary response. + ApplyOpt(easy, CURLOPT_FOLLOWLOCATION, 0L, &opt_err); + ApplyOpt(easy, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L, &opt_err); + ApplyOpt(easy, CURLOPT_TCP_NODELAY, 1L, &opt_err); + ApplyOpt(easy, CURLOPT_CONNECTTIMEOUT_MS, 60000L, &opt_err); + ApplyOpt(easy, CURLOPT_TIMEOUT_MS, 0L, &opt_err); + if (!proxy_url.empty()) { + ApplyOpt(easy, CURLOPT_PROXY, proxy_url.c_str(), &opt_err); + } + if (opt_err != CURLE_OK) { + return CurlSetupError{ClassifyCurlError(opt_err, /*canceled=*/false), + curl_easy_strerror(opt_err)}; + } + return std::nullopt; +} + +namespace { + +struct CurlTransfer { + std::shared_ptr op; + ::firebase::rest::curl::UniqueEasy easy; + ::firebase::rest::curl::UniqueSList headers; + char error_buf[CURL_ERROR_SIZE] = {}; + bool upload_paused = false; + bool download_paused = false; + bool headers_committed = false; + // True while the request body pipe still feeds this transfer. + bool request_body_open = false; + // Total request body bytes returned to libcurl from `OnCurlRead`. + uint64_t bytes_fed_to_curl = 0; + + int32_t staged_status = 0; + std::string staged_reason; + std::vector> staged_headers; + + void CommitStagedHeadersIfNeeded() { + if (headers_committed || staged_status <= 0) { + return; + } + headers_committed = true; + op->CommitResponseHeaders(staged_status, staged_reason, + std::move(staged_headers)); + staged_headers.clear(); + } +}; + +size_t OnCurlHeader(char* buffer, size_t size, size_t nitems, void* userdata) { + auto* transfer = static_cast(userdata); + size_t total = size * nitems; + if (transfer == nullptr || transfer->op->IsCanceled()) { + return 0; + } + + std::string_view line(buffer, total); + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) { + line.remove_suffix(1); + } + + if (line.empty()) { + if (transfer->staged_status >= 200) { + transfer->CommitStagedHeadersIfNeeded(); + if (transfer->staged_status >= 300 && transfer->request_body_open) { + // libcurl stops sending the request body once a final status >= 300 + // arrives (CURLOPT_KEEP_SENDING_ON_ERROR is off), so wake a writer + // waiting for pipe space. The headers are already committed. + transfer->request_body_open = false; + transfer->op->MarkRequestWriteClosed(); + } + } + return total; + } + + if (line.size() >= 5 && line.substr(0, 5) == "HTTP/") { + transfer->staged_headers.clear(); + transfer->staged_reason.clear(); + transfer->staged_status = 0; + + size_t sp1 = line.find(' '); + if (sp1 != std::string_view::npos) { + std::string_view rest = TrimAsciiWhitespace(line.substr(sp1 + 1)); + size_t sp2 = rest.find(' '); + std::string_view code_str = + sp2 == std::string_view::npos ? rest : rest.substr(0, sp2); + int32_t parsed = 0; + auto [ptr, ec] = std::from_chars( + code_str.data(), code_str.data() + code_str.size(), parsed); + if (ec == std::errc() && parsed > 0) { + transfer->staged_status = parsed; + } + if (sp2 != std::string_view::npos) { + std::string_view reason = TrimAsciiWhitespace(rest.substr(sp2 + 1)); + transfer->staged_reason.assign(reason.data(), reason.size()); + } + } + return total; + } + + size_t colon = line.find(':'); + if (colon != std::string_view::npos && colon > 0) { + std::string_view name = TrimAsciiWhitespace(line.substr(0, colon)); + std::string_view value = TrimAsciiWhitespace(line.substr(colon + 1)); + if (!name.empty()) { + transfer->staged_headers.emplace_back(std::string(name), + std::string(value)); + } + } + return total; +} + +size_t OnCurlWrite(char* ptr, size_t size, size_t nmemb, void* userdata) { + auto* transfer = static_cast(userdata); + size_t total = size * nmemb; + if (transfer == nullptr || transfer->op->IsCanceled()) { + return 0; + } + transfer->CommitStagedHeadersIfNeeded(); + if (total == 0) { + return 0; + } + + { + std::lock_guard lock(transfer->op->mutex); + if (transfer->op->resp_buffered_bytes >= kMaxResponseBufferBytes) { + transfer->download_paused = true; + return CURL_WRITEFUNC_PAUSE; + } + } + + transfer->op->PushResponseBytes(reinterpret_cast(ptr), total); + return total; +} + +size_t OnCurlRead(char* buffer, size_t size, size_t nitems, void* userdata) { + auto* transfer = static_cast(userdata); + size_t cap = size * nitems; + if (transfer == nullptr || transfer->op->IsCanceled()) { + return CURL_READFUNC_ABORT; + } + if (cap == 0) { + return 0; + } + if (!transfer->request_body_open) { + // The pipe was closed after an early response. libcurl may still ask for + // bytes while it reads a response marked `Connection: close`; ending the + // body here would fail a fixed-length upload, so stay paused instead. + transfer->upload_paused = true; + return CURL_READFUNC_PAUSE; + } + + bool eof = false; + size_t n = transfer->op->PopRequestBytes(reinterpret_cast(buffer), + cap, &eof); + if (n > 0) { + transfer->bytes_fed_to_curl += static_cast(n); + return n; + } + if (eof) { + return 0; + } + transfer->upload_paused = true; + return CURL_READFUNC_PAUSE; +} + +class CurlHttpEngine { + public: + static CurlHttpEngine& Instance() { + static auto* engine = new CurlHttpEngine(); + return *engine; + } + + void StartOperation(const std::shared_ptr& op) { + int64_t id = op->id; + { + std::lock_guard lock(op->mutex); + if (op->IsCanceled()) { + return; + } + op->on_request_data_changed = [this, id]() { EnqueueResumeUpload(id); }; + op->on_response_space_available = [this, id]() { + EnqueueResumeDownload(id); + }; + op->on_cancel = [this, id]() { EnqueueCancel(id); }; + } + + { + std::lock_guard lock(mutex_); + pending_starts_.push_back(op); + } + WakeLoop(); + } + + private: + CurlHttpEngine() { + // Share reference-counted curl_global_init lifetime with firebase_rest_lib + // without spawning an unused CurlThread, ensuring App::Dispose() never + // tears down libcurl globals underneath active HTTP operations. + ::firebase::rest::curl::AcquireCurlGlobal(); + + multi_.reset(curl_multi_init()); + if (multi_ != nullptr) { + curl_multi_setopt(multi_.get(), CURLMOPT_MAX_HOST_CONNECTIONS, 16L); + curl_multi_setopt(multi_.get(), CURLMOPT_MAX_TOTAL_CONNECTIONS, 64L); + } + worker_ = std::thread([this]() { RunLoop(); }); + worker_.detach(); + } + + void EnqueueResumeUpload(int64_t id) { + { + std::lock_guard lock(mutex_); + pending_upload_resumes_.push_back(id); + } + WakeLoop(); + } + + void EnqueueResumeDownload(int64_t id) { + { + std::lock_guard lock(mutex_); + pending_download_resumes_.push_back(id); + } + WakeLoop(); + } + + void EnqueueCancel(int64_t id) { + { + std::lock_guard lock(mutex_); + pending_cancels_.push_back(id); + } + WakeLoop(); + } + + void WakeLoop() { + if (multi_ != nullptr) { + curl_multi_wakeup(multi_.get()); + } + cv_.notify_one(); + } + + std::unique_ptr BuildTransfer( + const std::shared_ptr& op) { + if (!IsHttpOrHttpsUrl(op->url)) { + op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", + kHttpErrorInvalidRequest); + return nullptr; + } + + const int64_t content_length = op->content_length; + bool is_get = AsciiEqualsIgnoreCase(op->method, "GET"); + bool is_head = AsciiEqualsIgnoreCase(op->method, "HEAD"); + if ((is_get || is_head) && + (content_length > 0 || content_length == kChunkedRequestContent)) { + op->MarkFailed("GET and HEAD requests cannot send a request body.", + kHttpErrorInvalidRequest); + return nullptr; + } + + ::firebase::rest::curl::UniqueEasy easy(curl_easy_init()); + if (easy == nullptr) { + op->MarkFailed("Failed to initialize native libcurl handle.", + kHttpErrorOther); + return nullptr; + } + + if (auto setup_error = ApplyCurlConnectionOptions(easy.get(), "http,https", + op->proxy_url)) { + op->MarkFailed(setup_error->message, setup_error->error_class); + return nullptr; + } + + auto transfer = std::make_unique(); + transfer->op = op; + transfer->error_buf[0] = '\0'; + + CURL* raw_easy = easy.get(); + CURLcode opt_err = CURLE_OK; + ApplyOpt(raw_easy, CURLOPT_ERRORBUFFER, transfer->error_buf, &opt_err); + ApplyOpt(raw_easy, CURLOPT_BUFFERSIZE, 256L * 1024L, &opt_err); + ApplyOpt(raw_easy, CURLOPT_UPLOAD_BUFFERSIZE, 256L * 1024L, &opt_err); + + ApplyOpt(raw_easy, CURLOPT_URL, op->url.c_str(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_PRIVATE, transfer.get(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_HEADERFUNCTION, OnCurlHeader, &opt_err); + ApplyOpt(raw_easy, CURLOPT_HEADERDATA, transfer.get(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_WRITEFUNCTION, OnCurlWrite, &opt_err); + ApplyOpt(raw_easy, CURLOPT_WRITEDATA, transfer.get(), &opt_err); + + bool has_expect = HasHeaderIgnoreCase(op->request_headers, "Expect"); + bool has_transfer_encoding = + HasHeaderIgnoreCase(op->request_headers, "Transfer-Encoding"); + bool has_content_length = + HasHeaderIgnoreCase(op->request_headers, "Content-Length"); + + ::firebase::rest::curl::UniqueSList header_list; + for (const auto& kv : op->request_headers) { + std::string line; + line.reserve(kv.first.size() + kv.second.size() + 2); + line.append(kv.first); + line.append(": "); + line.append(kv.second); + if (!AppendSList(&header_list, line.c_str())) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + } + if (!has_expect) { + // Disable libcurl's automatic "Expect: 100-continue" wait on uploads. + if (!AppendSList(&header_list, "Expect:")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + } + + bool no_body = content_length == kNoRequestContent || + ((is_get || is_head) && content_length == 0); + if (no_body) { + if (is_head) { + ApplyOpt(raw_easy, CURLOPT_NOBODY, 1L, &opt_err); + } else if (is_get) { + ApplyOpt(raw_easy, CURLOPT_HTTPGET, 1L, &opt_err); + } else { + ApplyOpt(raw_easy, CURLOPT_CUSTOMREQUEST, op->method.c_str(), &opt_err); + if (!has_content_length && + (AsciiEqualsIgnoreCase(op->method, "POST") || + AsciiEqualsIgnoreCase(op->method, "PUT") || + AsciiEqualsIgnoreCase(op->method, "PATCH"))) { + if (!AppendSList(&header_list, "Content-Length: 0")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + } + } + } else { + transfer->request_body_open = true; + ApplyOpt(raw_easy, CURLOPT_UPLOAD, 1L, &opt_err); + ApplyOpt(raw_easy, CURLOPT_CUSTOMREQUEST, op->method.c_str(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_READFUNCTION, OnCurlRead, &opt_err); + ApplyOpt(raw_easy, CURLOPT_READDATA, transfer.get(), &opt_err); + if (content_length >= 0) { + ApplyOpt(raw_easy, CURLOPT_INFILESIZE_LARGE, + static_cast(content_length), &opt_err); + } else if (!has_transfer_encoding) { + if (!AppendSList(&header_list, "Transfer-Encoding: chunked")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + } + } + + transfer->headers = std::move(header_list); + if (transfer->headers != nullptr) { + ApplyOpt(raw_easy, CURLOPT_HTTPHEADER, transfer->headers.get(), &opt_err); + } + + if (opt_err != CURLE_OK) { + op->MarkFailed(curl_easy_strerror(opt_err), + ClassifyCurlError(opt_err, op->IsCanceled())); + return nullptr; + } + + transfer->easy = std::move(easy); + return transfer; + } + + void FailAllActive(CURLMcode mc) { + std::string err = curl_multi_strerror(mc); + std::unordered_map> failed; + failed.swap(active_); + for (auto& kv : failed) { + if (kv.second) { + curl_multi_remove_handle(multi_.get(), kv.second->easy.get()); + if (!kv.second->op->IsCanceled()) { + kv.second->op->MarkFailed(err, kHttpErrorOther); + } + } + } + } + + void RunLoop() { + while (true) { + std::deque> starts; + std::vector upload_resumes; + std::vector download_resumes; + std::vector cancels; + + { + std::unique_lock lock(mutex_); + if (active_.empty() && pending_starts_.empty() && + pending_cancels_.empty()) { + cv_.wait(lock, [this]() { + return !pending_starts_.empty() || !pending_cancels_.empty(); + }); + } + starts.swap(pending_starts_); + upload_resumes.swap(pending_upload_resumes_); + download_resumes.swap(pending_download_resumes_); + cancels.swap(pending_cancels_); + } + + for (int64_t id : cancels) { + auto it = active_.find(id); + if (it != active_.end()) { + curl_multi_remove_handle(multi_.get(), it->second->easy.get()); + active_.erase(it); + } + } + + for (const auto& op : starts) { + if (op->IsCanceled() || active_.find(op->id) != active_.end()) { + continue; + } + if (multi_ == nullptr) { + op->MarkFailed("Native libcurl multi engine failed to initialize.", + kHttpErrorOther); + continue; + } + auto transfer = BuildTransfer(op); + if (!transfer) { + continue; + } + CURLMcode mc = + curl_multi_add_handle(multi_.get(), transfer->easy.get()); + if (mc != CURLM_OK) { + op->MarkFailed(curl_multi_strerror(mc), kHttpErrorOther); + continue; + } + active_.emplace(op->id, std::move(transfer)); + } + + auto apply_pause_mask = [](CurlTransfer& t) { + int mask = (t.upload_paused ? CURLPAUSE_SEND : CURLPAUSE_SEND_CONT) | + (t.download_paused ? CURLPAUSE_RECV : CURLPAUSE_RECV_CONT); + curl_easy_pause(t.easy.get(), mask); + }; + + for (int64_t id : upload_resumes) { + auto it = active_.find(id); + if (it != active_.end() && it->second->upload_paused) { + it->second->upload_paused = false; + apply_pause_mask(*it->second); + } + } + + for (int64_t id : download_resumes) { + auto it = active_.find(id); + if (it != active_.end() && it->second->download_paused) { + it->second->download_paused = false; + apply_pause_mask(*it->second); + } + } + + if (active_.empty()) { + continue; + } + + int still_running = 0; + CURLMcode perform_rc = curl_multi_perform(multi_.get(), &still_running); + if (perform_rc != CURLM_OK && perform_rc != CURLM_CALL_MULTI_PERFORM) { + FailAllActive(perform_rc); + continue; + } + + int msgs_left = 0; + while (CURLMsg* msg = curl_multi_info_read(multi_.get(), &msgs_left)) { + if (msg->msg != CURLMSG_DONE) { + continue; + } + // Extract fields from `msg` before `curl_multi_remove_handle()`, which + // invalidates the CURLMsg pointer returned by `curl_multi_info_read()`. + CURL* easy_handle = msg->easy_handle; + CURLcode result = msg->data.result; + CurlTransfer* raw_transfer = nullptr; + curl_easy_getinfo(easy_handle, CURLINFO_PRIVATE, &raw_transfer); + if (raw_transfer == nullptr) { + curl_multi_remove_handle(multi_.get(), easy_handle); + continue; + } + + int64_t id = raw_transfer->op->id; + auto it = active_.find(id); + std::unique_ptr owned_transfer; + curl_multi_remove_handle(multi_.get(), easy_handle); + if (it != active_.end()) { + owned_transfer = std::move(it->second); + active_.erase(it); + } + if (!owned_transfer) { + continue; + } + + if (!owned_transfer->op->IsCanceled()) { + if (result == CURLE_OK) { + if (!owned_transfer->headers_committed) { + long code = 0; // NOLINT + curl_easy_getinfo(owned_transfer->easy.get(), + CURLINFO_RESPONSE_CODE, &code); + if (owned_transfer->staged_status <= 0 && code > 0) { + owned_transfer->staged_status = static_cast(code); + } + owned_transfer->CommitStagedHeadersIfNeeded(); + } + owned_transfer->op->MarkResponseComplete(); + } else { + std::string err = owned_transfer->error_buf[0] != '\0' + ? std::string(owned_transfer->error_buf) + : std::string(curl_easy_strerror(result)); + owned_transfer->op->MarkFailed( + err, ClassifyCurlError(result, owned_transfer->op->IsCanceled())); + } + } + } + + if (!active_.empty()) { + // libcurl pauses socket writes (`Curl_xfer_pause_send`) whenever + // `OnCurlRead` returns `CURL_READFUNC_PAUSE`, even if bytes from an + // earlier read are still buffered in `data->req.sendbuf` after EAGAIN. + // While any paused upload still has unflushed bytes, poll briefly and + // bump it so `Curl_req_send_more` flushes `sendbuf` onto the wire. + std::vector stranded_uploads; + for (const auto& kv : active_) { + const CurlTransfer& t = *kv.second; + if (t.upload_paused && t.request_body_open && + t.bytes_fed_to_curl > 0) { + curl_off_t sent = 0; + if (curl_easy_getinfo(t.easy.get(), CURLINFO_SIZE_UPLOAD_T, + &sent) == CURLE_OK && + sent >= 0 && + static_cast(sent) < t.bytes_fed_to_curl) { + stranded_uploads.push_back(kv.first); + } + } + } + int poll_timeout_ms = stranded_uploads.empty() ? 1000 : 10; + int numfds = 0; + CURLMcode poll_rc = curl_multi_poll(multi_.get(), nullptr, 0, + poll_timeout_ms, &numfds); + if (poll_rc != CURLM_OK) { + FailAllActive(poll_rc); + } else { + for (int64_t id : stranded_uploads) { + auto it = active_.find(id); + if (it != active_.end() && it->second->upload_paused && + it->second->request_body_open) { + it->second->upload_paused = false; + apply_pause_mask(*it->second); + } + } + } + } + } + } + + ::firebase::rest::curl::UniqueMulti multi_; + std::mutex mutex_; + std::condition_variable cv_; + std::deque> pending_starts_; + std::vector pending_upload_resumes_; + std::vector pending_download_resumes_; + std::vector pending_cancels_; + std::unordered_map> active_; + std::thread worker_; +}; + +} // namespace + +void StartPlatformHttpOperation(const std::shared_ptr& op) { + CurlHttpEngine::Instance().StartOperation(op); +} + +} // namespace http +} // namespace firebase diff --git a/app/http/http_transport_curl_android.cc b/app/http/http_transport_curl_android.cc new file mode 100644 index 0000000000..64798930f8 --- /dev/null +++ b/app/http/http_transport_curl_android.cc @@ -0,0 +1,232 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport_curl_platform.h" +#include "app/rest/curl/curl_handles.h" +#include "curl/curl.h" +#include "openssl/bio.h" +#include "openssl/err.h" +#include "openssl/pem.h" +#include "openssl/ssl.h" +#include "openssl/x509.h" + +namespace firebase { +namespace http { +namespace { + +using ::firebase::rest::curl::ApplyOpt; + +// Where Android keeps the system CA certificates, one file per certificate, +// most preferred first. Android 14 and later ship them in the updatable +// Conscrypt module; older releases only have the system partition copy. +constexpr const char* kSystemCaDirectories[] = { + "/apex/com.android.conscrypt/cacerts", + "/system/etc/security/cacerts", +}; + +#ifdef FIREBASE_HTTP_BUNDLED_BORINGSSL +// Key-exchange groups offered in the TLS handshake, most preferred first: the +// post-quantum hybrid, then the classical groups for servers without it. +constexpr char kKeyExchangeGroups[] = "X25519MLKEM768:X25519:P-256:P-384"; +#endif // FIREBASE_HTTP_BUNDLED_BORINGSSL + +constexpr std::string_view kPemCertificateBegin = "-----BEGIN CERTIFICATE-----"; +constexpr std::string_view kPemCertificateEnd = "-----END CERTIFICATE-----"; + +// Returns the contents of the regular file at `path`, or an empty string. +std::string ReadRegularFile(const std::string& path) { + std::string contents; + struct stat st; + if (stat(path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) { + return contents; + } + FILE* file = fopen(path.c_str(), "rbe"); + if (file == nullptr) { + return contents; + } + char buffer[4096]; + size_t read = 0; + while ((read = fread(buffer, 1, sizeof(buffer), file)) > 0) { + contents.append(buffer, read); + } + fclose(file); + return contents; +} + +// Returns every PEM certificate block in `contents`, each followed by a +// newline. +std::string ExtractPemCertificates(std::string_view contents) { + std::string pem; + size_t position = 0; + while (true) { + size_t begin = contents.find(kPemCertificateBegin, position); + if (begin == std::string_view::npos) { + break; + } + size_t end = + contents.find(kPemCertificateEnd, begin + kPemCertificateBegin.size()); + if (end == std::string_view::npos) { + break; + } + end += kPemCertificateEnd.size(); + pem.append(contents.substr(begin, end - begin)); + pem.push_back('\n'); + position = end; + } + return pem; +} + +// Parses the certificates in `pem` into a new store. Returns nullptr when none +// could be parsed. +X509_STORE* NewStoreFromPem(const std::string& pem) { + BIO* bio = BIO_new_mem_buf(pem.data(), static_cast(pem.size())); + X509_STORE* store = X509_STORE_new(); + int added = 0; + if (bio != nullptr && store != nullptr) { + // A block that does not parse is skipped rather than ending the load. The + // loop ends when the buffer is used up, or when a read consumes nothing. + size_t remaining = BIO_pending(bio); + while (remaining > 0) { + X509* certificate = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); + if (certificate != nullptr) { + added += X509_STORE_add_cert(store, certificate); + X509_free(certificate); + } + size_t left = BIO_pending(bio); + if (left >= remaining) { + break; + } + remaining = left; + } + } + BIO_free(bio); + // Reaching the end of the buffer, or a bad block, queues errors on this + // thread that must not be mistaken for a later TLS failure. + ERR_clear_error(); + if (added == 0) { + X509_STORE_free(store); + return nullptr; + } + return store; +} + +// CURLOPT_SSL_CTX_FUNCTION callback. libcurl calls it for each new TLS +// connection once it has finished setting up `ssl_ctx`, so nothing libcurl +// does afterwards replaces `store`, which is then the only store the peer's +// chain is verified against. An error return aborts the connection. +CURLcode UseTrustStore(CURL* /*easy*/, void* ssl_ctx, void* store) { + return SSL_CTX_set1_verify_cert_store(static_cast(ssl_ctx), + static_cast(store)) == 1 + ? CURLE_OK + : CURLE_SSL_CACERT_BADFILE; +} + +} // namespace + +CURLcode ApplyAndroidTlsSettings(CURL* easy) { + // Never destroyed: easy handles keep pointing into it. + static internal::TrustStore* const system_roots = + new internal::TrustStore(std::vector( + std::begin(kSystemCaDirectories), std::end(kSystemCaDirectories))); + return system_roots->ApplyTo(easy); +} + +namespace internal { + +TrustStore::TrustStore(std::vector directories) + : directories_(std::move(directories)) {} + +TrustStore::~TrustStore() { X509_STORE_free(store_); } + +CURLcode TrustStore::ApplyTo(CURL* easy) { + std::lock_guard lock(mutex_); + if (store_ == nullptr) { + ++load_count_; + for (const std::string& directory : directories_) { + std::string pem = ReadPemCertificatesFromDirectory(directory); + X509_STORE* store = pem.empty() ? nullptr : NewStoreFromPem(pem); + if (store != nullptr) { + store_ = store; + pem_ = std::move(pem); + break; + } + } + if (store_ == nullptr) { + return CURLE_SSL_CACERT_BADFILE; + } + } + + CURLcode first_error = CURLE_OK; +#ifdef FIREBASE_HTTP_BUNDLED_BORINGSSL + ApplyOpt(easy, CURLOPT_SSL_EC_CURVES, kKeyExchangeGroups, &first_error); +#endif // FIREBASE_HTTP_BUNDLED_BORINGSSL + + // The connection to the server gets the parsed store rather than + // CURLOPT_CAINFO_BLOB: libcurl parses a CA blob again for every new + // connection (it only reuses the store it builds from a CA file or + // directory), which here would mean every system certificate each time. + // Clear any default CA path/bundle so libcurl relies solely on UseTrustStore. + ApplyOpt(easy, CURLOPT_CAINFO, static_cast(nullptr), + &first_error); + ApplyOpt(easy, CURLOPT_CAPATH, static_cast(nullptr), + &first_error); + ApplyOpt(easy, CURLOPT_SSL_CTX_FUNCTION, UseTrustStore, &first_error); + ApplyOpt(easy, CURLOPT_SSL_CTX_DATA, store_, &first_error); + + // The TLS leg to an HTTPS proxy is rare enough to keep the blob. + curl_blob blob; + blob.data = const_cast(pem_.data()); + blob.len = pem_.size(); + blob.flags = CURL_BLOB_NOCOPY; + ApplyOpt(easy, CURLOPT_PROXY_CAINFO_BLOB, &blob, &first_error); + return first_error; +} + +int TrustStore::load_count() const { + std::lock_guard lock(mutex_); + return load_count_; +} + +std::string ReadPemCertificatesFromDirectory(const std::string& directory) { + std::string pem; + DIR* dir = opendir(directory.c_str()); + if (dir == nullptr) { + return pem; + } + while (const dirent* entry = readdir(dir)) { + pem.append(ExtractPemCertificates( + ReadRegularFile(directory + "/" + entry->d_name))); + } + closedir(dir); + return pem; +} + +} // namespace internal + +} // namespace http +} // namespace firebase diff --git a/app/http/http_transport_curl_internal.h b/app/http/http_transport_curl_internal.h new file mode 100644 index 0000000000..c90aa1d87d --- /dev/null +++ b/app/http/http_transport_curl_internal.h @@ -0,0 +1,53 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Pieces of the libcurl HTTP backend that the libcurl WebSocket backend +// shares. Not for use outside `app/http`. + +#ifndef FIREBASE_APP_HTTP_HTTP_TRANSPORT_CURL_INTERNAL_H_ +#define FIREBASE_APP_HTTP_HTTP_TRANSPORT_CURL_INTERNAL_H_ + +#include +#include + +#include "app/http/http_transport.h" +#include "curl/curl.h" + +namespace firebase { +namespace http { + +struct CurlSetupError { + HttpErrorClass error_class = kHttpErrorOther; + std::string message; +}; + +// Applies the options every connection of this transport needs, for HTTP and +// WebSocket alike: the allowed protocols, the SDK TLS policy, the proxy, the +// connect timeout, no signals, no credentials taken from the URL, and no +// redirect following. This is the only place for connection-level setup. +// +// `protocols` is the `CURLOPT_PROTOCOLS_STR` value. An empty `proxy_url` sets +// no proxy option. Returns the failure, or nullopt on success. +std::optional ApplyCurlConnectionOptions( + CURL* easy, const char* protocols, const std::string& proxy_url); + +// Maps a libcurl result to the error class reported through the bridge. +HttpErrorClass ClassifyCurlError(CURLcode code, bool canceled); + +} // namespace http +} // namespace firebase + +#endif // FIREBASE_APP_HTTP_HTTP_TRANSPORT_CURL_INTERNAL_H_ diff --git a/app/http/http_transport_curl_platform.h b/app/http/http_transport_curl_platform.h new file mode 100644 index 0000000000..72b7545c7b --- /dev/null +++ b/app/http/http_transport_curl_platform.h @@ -0,0 +1,96 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Platform-specific pieces of the libcurl backend (`http_transport_curl.cc`). +// Internal to `firebase_http_transport`. + +#ifndef FIREBASE_APP_HTTP_HTTP_TRANSPORT_CURL_PLATFORM_H_ +#define FIREBASE_APP_HTTP_HTTP_TRANSPORT_CURL_PLATFORM_H_ + +#include +#include +#include + +#include "curl/curl.h" + +struct x509_store_st; // The TLS library's X509_STORE. + +namespace firebase { +namespace http { + +// Message for the failure reported when `ApplyAndroidTlsSettings` returns +// `CURLE_SSL_CACERT_BADFILE`. +inline constexpr char kAndroidNoTrustedRootsError[] = + "No trusted CA certificates could be read from the Android system store."; + +// Android only. The libcurl backend calls this for every easy handle, after +// `firebase::rest::curl::ApplyTlsPolicy`, which leaves peer and host name +// verification on. libcurl is linked against a bundled BoringSSL there, which +// knows nothing about Android's trust store, so this applies the process-wide +// `internal::TrustStore` of the system CA certificates, read from +// `/apex/com.android.conscrypt/cacerts` or, when that has no certificates, +// `/system/etc/security/cacerts`. +// +// Returns `CURLE_SSL_CACERT_BADFILE` when no certificate could be loaded; the +// caller must then fail the request rather than connect. Otherwise returns the +// first error from `curl_easy_setopt`, or `CURLE_OK`. +CURLcode ApplyAndroidTlsSettings(CURL* easy); + +namespace internal { + +// Returns the PEM certificate blocks of every regular file in `directory`, +// concatenated. Anything else in those files (Android appends a text dump of +// each certificate) is dropped. Returns an empty string when the directory +// cannot be read or holds no PEM certificate. +std::string ReadPemCertificatesFromDirectory(const std::string& directory); + +// The CA certificates found in a list of directories, parsed once and shared +// by every connection. Thread-safe. Must outlive the easy handles it is applied +// to. +class TrustStore { + public: + // `directories` are tried in order; the first one holding certificates is + // used. + explicit TrustStore(std::vector directories); + ~TrustStore(); + TrustStore(const TrustStore&) = delete; + TrustStore& operator=(const TrustStore&) = delete; + + // Makes `easy` verify servers against these certificates, and offer the + // key-exchange groups `X25519MLKEM768:X25519:P-256:P-384` when built with + // `FIREBASE_HTTP_BUNDLED_BORINGSSL`. The certificates are loaded by the first + // call; a load that finds none is repeated by the next call. Returns as + // `ApplyAndroidTlsSettings` does. + CURLcode ApplyTo(CURL* easy); + + // How many times the directories have been read and parsed. + int load_count() const; + + private: + const std::vector directories_; + mutable std::mutex mutex_; + // Both are set together by a successful load and never change afterwards. + x509_store_st* store_ = nullptr; + std::string pem_; + int load_count_ = 0; +}; + +} // namespace internal + +} // namespace http +} // namespace firebase + +#endif // FIREBASE_APP_HTTP_HTTP_TRANSPORT_CURL_PLATFORM_H_ diff --git a/app/http/tests/CMakeLists.txt b/app/http/tests/CMakeLists.txt new file mode 100644 index 0000000000..73aa51d43d --- /dev/null +++ b/app/http/tests/CMakeLists.txt @@ -0,0 +1,46 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +firebase_cpp_cc_test(firebase_app_http_common_test + SOURCES + http_transport_common_test.cc + DEPENDS + firebase_http_transport +) + +firebase_cpp_cc_test(firebase_app_http_curl_test + SOURCES + http_transport_curl_test.cc + DEPENDS + firebase_http_transport +) + +firebase_cpp_cc_test(firebase_app_websocket_common_test + SOURCES + websocket_common_test.cc + DEPENDS + firebase_http_transport +) + +firebase_cpp_cc_test(firebase_app_websocket_curl_test + SOURCES + websocket_curl_test.cc + DEPENDS + firebase_http_transport +) + +if(WIN32) + target_link_libraries(firebase_app_http_curl_test PRIVATE ws2_32) + target_link_libraries(firebase_app_websocket_curl_test PRIVATE ws2_32) +endif() diff --git a/app/http/tests/http_transport_common_test.cc b/app/http/tests/http_transport_common_test.cc new file mode 100644 index 0000000000..b0dd596386 --- /dev/null +++ b/app/http/tests/http_transport_common_test.cc @@ -0,0 +1,413 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace http { +namespace { + +TEST(HttpTransportCommonTest, IsHttpOrHttpsUrlChecksSchemeOnly) { + EXPECT_TRUE(IsHttpOrHttpsUrl("http://localhost/foo?bar=1")); + EXPECT_TRUE( + IsHttpOrHttpsUrl("HTTPS://FireBaseStorage.GoogleAPIs.com/v0/b/x")); + EXPECT_TRUE(IsHttpOrHttpsUrl("HtTp://127.0.0.1:5001/proj/us/fn")); + EXPECT_TRUE(IsHttpOrHttpsUrl("https://[::1]:8443/path")); + EXPECT_TRUE(IsHttpOrHttpsUrl("http://x")); + + EXPECT_FALSE(IsHttpOrHttpsUrl("")); + EXPECT_FALSE(IsHttpOrHttpsUrl("http://")); + EXPECT_FALSE(IsHttpOrHttpsUrl("https://")); + EXPECT_FALSE(IsHttpOrHttpsUrl("file:///etc/passwd")); + EXPECT_FALSE(IsHttpOrHttpsUrl("ftp://example.com/a")); + EXPECT_FALSE(IsHttpOrHttpsUrl("httpx://example.com/a")); + EXPECT_FALSE(IsHttpOrHttpsUrl("http:/example.com/a")); + EXPECT_FALSE(IsHttpOrHttpsUrl("example.com/a")); + // Whitespace and control characters are rejected anywhere in the URL. + EXPECT_FALSE(IsHttpOrHttpsUrl(" http://example.com/a")); + EXPECT_FALSE(IsHttpOrHttpsUrl("http://example.com/a ")); + EXPECT_FALSE(IsHttpOrHttpsUrl("http://example.com/a b")); + EXPECT_FALSE(IsHttpOrHttpsUrl("http://example.com/a\tb")); + EXPECT_FALSE(IsHttpOrHttpsUrl("http://example.com/a\r\nHost: other")); + EXPECT_FALSE(IsHttpOrHttpsUrl("http://example.com/a\x7f")); + EXPECT_FALSE( + IsHttpOrHttpsUrl(std::string_view("http://example.com/a\0b", 22))); +} + +TEST(HttpTransportCommonTest, IsValidHttpMethodRequiresToken) { + EXPECT_TRUE(IsValidHttpMethod("GET")); + EXPECT_TRUE(IsValidHttpMethod("PATCH")); + EXPECT_TRUE(IsValidHttpMethod("M-SEARCH")); + EXPECT_TRUE(IsValidHttpMethod("get")); + + EXPECT_FALSE(IsValidHttpMethod("")); + EXPECT_FALSE(IsValidHttpMethod("GE T")); + EXPECT_FALSE(IsValidHttpMethod("GET\r\n")); + EXPECT_FALSE(IsValidHttpMethod("GET/1")); + EXPECT_FALSE(IsValidHttpMethod("G:ET")); + EXPECT_FALSE(IsValidHttpMethod(std::string_view("GET\0", 4))); +} + +TEST(HttpTransportCommonTest, ParsePackedHeadersPreservesDuplicates) { + std::vector> headers; + ASSERT_TRUE(TryParsePackedHeaders( + "Authorization\tBearer tok\n" + "X-Multi\tfirst\r\n" + "X-Multi\tsecond\n" + "Content-Type\tapplication/json\n", + &headers)); + ASSERT_EQ(headers.size(), 4u); + EXPECT_EQ(headers[0], std::make_pair(std::string("Authorization"), + std::string("Bearer tok"))); + EXPECT_EQ(headers[1], + std::make_pair(std::string("X-Multi"), std::string("first"))); + EXPECT_EQ(headers[2], + std::make_pair(std::string("X-Multi"), std::string("second"))); + EXPECT_EQ(headers[3], std::make_pair(std::string("Content-Type"), + std::string("application/json"))); + + // The separator is a tab; `Name: Value` lines are not accepted. + EXPECT_FALSE( + TryParsePackedHeaders("Content-Type: application/json\n", &headers)); + EXPECT_TRUE(headers.empty()); +} + +TEST(HttpTransportCommonTest, HeaderValidationRejectsCrLfNulAndBadTokens) { + EXPECT_TRUE(IsValidHeaderName("X-Custom-Token_1")); + EXPECT_FALSE(IsValidHeaderName("")); + EXPECT_FALSE(IsValidHeaderName("Bad Name")); + EXPECT_FALSE(IsValidHeaderName("Bad:Name")); + EXPECT_FALSE(IsValidHeaderName("Bad\rName")); + EXPECT_FALSE(IsValidHeaderName("Bad\nName")); + EXPECT_FALSE(IsValidHeaderName(std::string_view("Bad\0Name", 8))); + + EXPECT_TRUE(IsValidHeaderValue("application/json; charset=utf-8")); + EXPECT_TRUE(IsValidHeaderValue("tab\tok")); + EXPECT_FALSE(IsValidHeaderValue("bad\rvalue")); + EXPECT_FALSE(IsValidHeaderValue("bad\nvalue")); + EXPECT_FALSE(IsValidHeaderValue(std::string_view("bad\0value", 9))); + EXPECT_FALSE(IsValidHeaderValue("bad\x01value")); + + std::vector> out; + EXPECT_FALSE(TryParsePackedHeaders("X-Foo\tbar\rInjected: 1\n", &out)); + EXPECT_FALSE( + TryParsePackedHeaders(std::string_view("X-Foo\tbar\0baz\n", 14), &out)); + EXPECT_FALSE(TryParsePackedHeaders("Bad Name\tval\n", &out)); + EXPECT_FALSE(TryParsePackedHeaders("X-Foo\tbar\nno-separator-line\n", &out)); + + // CreateOperation also rejects CR/LF in header values. + HttpRequestOptions opts; + opts.method = "GET"; + opts.url = "http://127.0.0.1:80/test"; + opts.headers.emplace_back("X-Test", "val\r\nInjected: 1"); + int64_t h = CreateOperation(std::move(opts)); + EXPECT_EQ(HttpPollResponseHeadersInternal(h), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorInvalidRequest); + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCommonTest, CreateOperationRejectsInvalidMethod) { + HttpRequestOptions opts; + opts.method = "GET\r\nX-Injected: 1"; + opts.url = "http://127.0.0.1:80/method"; + int64_t h = CreateOperation(std::move(opts)); + EXPECT_EQ(HttpPollResponseHeadersInternal(h), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorInvalidRequest); + EXPECT_EQ(HttpGetErrorInternal(h), "Invalid HTTP request method."); + HttpDestroyRequestInternal(h); + + int64_t bridged = HttpCreateRequestInternal( + "PO ST", "http://127.0.0.1:80/bridged-method", "", "", kNoRequestContent); + EXPECT_EQ(HttpPollResponseHeadersInternal(bridged), -1); + EXPECT_EQ(HttpGetErrorClassInternal(bridged), kHttpErrorInvalidRequest); + HttpDestroyRequestInternal(bridged); +} + +TEST(HttpTransportCommonTest, InvalidReadWriteArgsAndContentLength) { + int64_t bad_len = HttpCreateRequestInternal( + "POST", "http://127.0.0.1:80/bad-len", "", "", -3); + EXPECT_EQ(HttpPollResponseHeadersInternal(bad_len), -1); + EXPECT_EQ(HttpGetErrorClassInternal(bad_len), kHttpErrorInvalidRequest); + EXPECT_FALSE(HttpGetErrorInternal(bad_len).empty()); + HttpDestroyRequestInternal(bad_len); + + int64_t h = HttpCreateRequestInternal("POST", "http://127.0.0.1:80/args", "", + "", 16); + ASSERT_GT(h, 0); + uint8_t buf[16] = {}; + // S5: invalid read arguments must return error (-1), never 0 (EOF). + EXPECT_EQ(HttpTryReadResponseBodyInternal(h, nullptr, 16), + kHttpReadErrorOrCanceled); + EXPECT_EQ(HttpTryReadResponseBodyInternal(h, buf, 0), + kHttpReadErrorOrCanceled); + EXPECT_EQ(HttpTryReadResponseBodyInternal(h, buf, -4), + kHttpReadErrorOrCanceled); + + // Invalid write arguments return -1. + EXPECT_EQ(HttpTryWriteRequestBodyInternal(h, nullptr, 16), -1); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(h, buf, -1), -1); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(h, buf, 0), 0); + + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCommonTest, ErrorClassAndCancelAllOperations) { + int64_t h1 = HttpCreateRequestInternal("GET", "http://127.0.0.1:80/a", "", "", + kNoRequestContent); + int64_t h2 = HttpCreateRequestInternal("GET", "http://127.0.0.1:80/b", "", "", + kNoRequestContent); + ASSERT_GT(h1, 0); + ASSERT_GT(h2, 0); + + auto op1 = FindOperation(h1); + ASSERT_NE(op1, nullptr); + op1->MarkFailed("certificate verify failed", kHttpErrorCertificate); + EXPECT_EQ(HttpGetErrorClassInternal(h1), kHttpErrorCertificate); + + HttpCancelRequestInternal(h2); + EXPECT_EQ(HttpGetErrorClassInternal(h2), kHttpErrorCanceled); + + int64_t h3 = HttpCreateRequestInternal("GET", "http://127.0.0.1:80/c", "", "", + kNoRequestContent); + auto op3 = FindOperation(h3); + ASSERT_NE(op3, nullptr); + HttpCancelAllRequestsInternal(); + EXPECT_TRUE(op3->IsCanceled()); + EXPECT_EQ(FindOperation(h1), nullptr); + EXPECT_EQ(FindOperation(h2), nullptr); + EXPECT_EQ(FindOperation(h3), nullptr); +} + +TEST(HttpTransportCommonTest, WakeEventPumpUnblocksInfiniteWait) { + // Drain any stale events left by earlier unit tests. + while (HttpWaitNextEventInternal(0) != 0) { + } + + std::mutex mu; + std::condition_variable cv; + bool thread_started = false; + std::atomic wait_result{-1}; + + std::thread waiter([&]() { + { + std::lock_guard lock(mu); + thread_started = true; + } + cv.notify_one(); + wait_result.store(HttpWaitNextEventInternal(-1), std::memory_order_release); + }); + + { + std::unique_lock lock(mu); + cv.wait(lock, [&]() { return thread_started; }); + } + HttpWakeEventPumpInternal(); + waiter.join(); + EXPECT_EQ(wait_result.load(std::memory_order_acquire), 0); +} + +TEST(HttpTransportCommonTest, RequestAndResponsePipeWatermarksAndCancel) { + int64_t handle = HttpCreateRequestInternal( + "POST", "http://127.0.0.1:80/upload", "X-Test\t1\n", "", + static_cast(kMaxRequestBufferBytes + 1024)); + ASSERT_GT(handle, 0); + auto op = FindOperation(handle); + ASSERT_NE(op, nullptr); + + // Fill upload buffer beyond kMaxRequestBufferBytes to test cap & arming. + std::vector upload_buf(kMaxRequestBufferBytes + 1024, 0xAB); + int32_t accepted = HttpTryWriteRequestBodyInternal( + handle, upload_buf.data(), static_cast(upload_buf.size())); + EXPECT_EQ(static_cast(accepted), kMaxRequestBufferBytes); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, upload_buf.data(), 16), 0); + + // Drain below low-water mark so space-available event fires. + std::vector drain(kMaxRequestBufferBytes); + bool eof = false; + size_t popped = + op->PopRequestBytes(drain.data(), kMaxRequestBufferBytes, &eof); + EXPECT_EQ(popped, kMaxRequestBufferBytes); + EXPECT_FALSE(eof); + + // Commit response headers and push response bytes over high-water mark. + EXPECT_EQ(HttpPollResponseHeadersInternal(handle), 0); + op->CommitResponseHeaders(200, "OK", {{"X-A", "1"}, {"X-A", "2"}}); + EXPECT_EQ(HttpPollResponseHeadersInternal(handle), 200); + EXPECT_EQ(HttpGetResponseHeadersInternal(handle), "OK\nX-A\t1\nX-A\t2\n"); + + std::atomic resumed{false}; + { + std::lock_guard lock(op->mutex); + op->on_response_space_available = [&resumed]() { resumed.store(true); }; + } + std::vector big(kMaxResponseBufferBytes, 0x5A); + EXPECT_TRUE(op->PushResponseBytes(big.data(), big.size())); + + std::vector out(kMaxResponseBufferBytes); + int32_t read_n = HttpTryReadResponseBodyInternal( + handle, out.data(), static_cast(out.size())); + EXPECT_EQ(static_cast(read_n), kMaxResponseBufferBytes); + EXPECT_TRUE(resumed.load()); + + // Next read when empty returns WouldBlock until canceled. + EXPECT_EQ(HttpTryReadResponseBodyInternal(handle, out.data(), 64), + kHttpReadWouldBlock); + HttpCancelRequestInternal(handle); + EXPECT_EQ(HttpTryReadResponseBodyInternal(handle, out.data(), 64), + kHttpReadErrorOrCanceled); + + HttpDestroyRequestInternal(handle); + EXPECT_EQ(FindOperation(handle), nullptr); +} + +TEST(HttpTransportCommonTest, MarkResponseCompleteWakesBlockedUploader) { + while (HttpWaitNextEventInternal(0) != 0) { + } + int64_t handle = HttpCreateRequestInternal( + "PUT", "http://127.0.0.1:80/early-413", "", "", + static_cast(kMaxRequestBufferBytes * 2)); + ASSERT_GT(handle, 0); + auto op = FindOperation(handle); + ASSERT_NE(op, nullptr); + + // Fill request buffer past high-water mark so req_space_armed is set. + std::vector chunk(kMaxRequestBufferBytes + 1024, 0xCC); + int32_t accepted = HttpTryWriteRequestBodyInternal( + handle, chunk.data(), static_cast(chunk.size())); + EXPECT_EQ(static_cast(accepted), kMaxRequestBufferBytes); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 64), 0); + + // Server completes an early clean response without draining the upload. + op->CommitResponseHeaders(413, "Payload Too Large", {}); + op->MarkResponseComplete(); + + // Completion queue must wake the armed uploader and subsequent writes report + // the closed write side immediately instead of blocking forever. + int64_t ev = HttpWaitNextEventInternal(1000); + EXPECT_EQ(ev >> 8, handle); + EXPECT_EQ(static_cast(ev & 0xFF), + kHttpEventRequestSpaceAvailable); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 64), + kHttpWriteClosed); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 0), + kHttpWriteClosed); + EXPECT_EQ(HttpGetErrorClassInternal(handle), kHttpErrorNone); + + HttpDestroyRequestInternal(handle); +} + +TEST(HttpTransportCommonTest, MarkRequestWriteClosedWakesBlockedUploader) { + while (HttpWaitNextEventInternal(0) != 0) { + } + int64_t handle = HttpCreateRequestInternal( + "PUT", "http://127.0.0.1:80/early-429", "", "", + static_cast(kMaxRequestBufferBytes * 3)); + ASSERT_GT(handle, 0); + auto op = FindOperation(handle); + ASSERT_NE(op, nullptr); + + std::vector chunk(kMaxRequestBufferBytes + 2048, 0xDD); + int32_t accepted = HttpTryWriteRequestBodyInternal( + handle, chunk.data(), static_cast(chunk.size())); + EXPECT_EQ(static_cast(accepted), kMaxRequestBufferBytes); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 32), 0); + + // The backend stops consuming the body while the response is still open. + op->CommitResponseHeaders(429, "Too Many Requests", {}); + op->MarkRequestWriteClosed(); + + int64_t ev = HttpWaitNextEventInternal(1000); + EXPECT_EQ(ev >> 8, handle); + EXPECT_EQ(static_cast(ev & 0xFF), + kHttpEventRequestSpaceAvailable); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 32), + kHttpWriteClosed); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 0), + kHttpWriteClosed); + + // Finishing the body is a no-op once the write side is closed. + HttpFinishRequestBodyInternal(handle); + { + std::lock_guard lock(op->mutex); + EXPECT_FALSE(op->req_eof); + } + EXPECT_EQ(HttpPollResponseHeadersInternal(handle), 429); + EXPECT_EQ(HttpGetErrorClassInternal(handle), kHttpErrorNone); + + // A later failure takes precedence over the closed write side. + op->MarkFailed("connection reset", kHttpErrorConnect); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 32), -1); + EXPECT_EQ(HttpGetErrorClassInternal(handle), kHttpErrorConnect); + + HttpDestroyRequestInternal(handle); +} + +TEST(HttpTransportCommonTest, WriteAfterCancelReturnsError) { + int64_t handle = + HttpCreateRequestInternal("POST", "http://127.0.0.1:80/canceled-upload", + "", "", kChunkedRequestContent); + ASSERT_GT(handle, 0); + auto op = FindOperation(handle); + ASSERT_NE(op, nullptr); + + uint8_t bytes[48] = {}; + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, bytes, sizeof(bytes)), + static_cast(sizeof(bytes))); + + // Cancellation takes precedence over a completed response. + op->CommitResponseHeaders(200, "OK", {}); + op->MarkResponseComplete(); + HttpCancelRequestInternal(handle); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, bytes, sizeof(bytes)), -1); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, bytes, 0), -1); + EXPECT_EQ(HttpGetErrorClassInternal(handle), kHttpErrorCanceled); + + HttpDestroyRequestInternal(handle); +} + +TEST(HttpTransportCommonTest, StartOperationSingleStartFlag) { + int64_t handle = HttpCreateRequestInternal("GET", "http://127.0.0.1:80/once", + "", "", kNoRequestContent); + ASSERT_GT(handle, 0); + auto op = FindOperation(handle); + ASSERT_NE(op, nullptr); + + // Cancel before calling StartOperation twice; second StartOperation must be + // a no-op via the atomic `started` guard. + HttpCancelRequestInternal(handle); + EXPECT_FALSE(op->started.load()); + StartOperation(handle); + EXPECT_TRUE(op->started.load()); + StartOperation(handle); + EXPECT_TRUE(op->started.load()); + + HttpDestroyRequestInternal(handle); +} + +} // namespace +} // namespace http +} // namespace firebase diff --git a/app/http/tests/http_transport_curl_test.cc b/app/http/tests/http_transport_curl_test.cc new file mode 100644 index 0000000000..6dfd36f029 --- /dev/null +++ b/app/http/tests/http_transport_curl_test.cc @@ -0,0 +1,1723 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +using SocketFd = SOCKET; +constexpr SocketFd kInvalidSocket = INVALID_SOCKET; +#else +#include +#include +#include +#include +#include +#include +#include +using SocketFd = int; +constexpr SocketFd kInvalidSocket = -1; +#endif + +#include "app/http/http_transport.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace http { +namespace { + +void EnsureSocketSubsystemInitialized() { +#if defined(_WIN32) + static std::once_flag wsa_once; + std::call_once(wsa_once, []() { + WSADATA data{}; + WSAStartup(MAKEWORD(2, 2), &data); + }); +#else + static std::once_flag sigpipe_once; + std::call_once(sigpipe_once, []() { std::signal(SIGPIPE, SIG_IGN); }); +#endif +} + +void CloseSocket(SocketFd fd) { + if (fd == kInvalidSocket) return; +#if defined(_WIN32) + closesocket(fd); +#else + close(fd); +#endif +} + +void ShutdownWrite(SocketFd fd) { + if (fd == kInvalidSocket) return; +#if defined(_WIN32) + shutdown(fd, SD_SEND); +#else + shutdown(fd, SHUT_WR); +#endif +} + +bool WaitForSocketReadable(SocketFd fd, int timeout_ms) { + fd_set read_fds; + FD_ZERO(&read_fds); + FD_SET(fd, &read_fds); + timeval tv{}; + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; +#if defined(_WIN32) + int ready = select(0, &read_fds, nullptr, nullptr, &tv); +#else + int ready = select(fd + 1, &read_fds, nullptr, nullptr, &tv); +#endif + return ready > 0; +} + +bool WaitForSocketWritable(SocketFd fd, int timeout_ms) { + fd_set write_fds; + FD_ZERO(&write_fds); + FD_SET(fd, &write_fds); + timeval tv{}; + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; +#if defined(_WIN32) + int ready = select(0, nullptr, &write_fds, nullptr, &tv); +#else + int ready = select(fd + 1, nullptr, &write_fds, nullptr, &tv); +#endif + return ready > 0; +} + +void SetNonBlocking(SocketFd fd) { +#if defined(_WIN32) + u_long enabled = 1; + ioctlsocket(fd, FIONBIO, &enabled); +#else + fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); +#endif +} + +// Sends what a non-blocking socket accepts right now. Returns the number of +// bytes sent, 0 if the socket buffer is full, or -1 on any other error. +int SendSome(SocketFd fd, const char* data, size_t len) { +#if defined(_WIN32) + int n = send(fd, data, static_cast(len), 0); + if (n < 0) { + return WSAGetLastError() == WSAEWOULDBLOCK ? 0 : -1; + } + return n; +#else +#ifdef MSG_NOSIGNAL + constexpr int kSendFlags = MSG_NOSIGNAL; +#else + constexpr int kSendFlags = 0; +#endif + ssize_t n = send(fd, data, len, kSendFlags); + if (n < 0) { + return (errno == EAGAIN || errno == EWOULDBLOCK) ? 0 : -1; + } + return static_cast(n); +#endif +} + +// Returns a loopback port that nothing listens on. +int ClosedLoopbackPort() { + SocketFd probe = socket(AF_INET, SOCK_STREAM, 0); + EXPECT_NE(probe, kInvalidSocket); + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; + EXPECT_EQ(bind(probe, reinterpret_cast(&addr), sizeof(addr)), 0); + sockaddr_in bound{}; +#if defined(_WIN32) + int bound_len = sizeof(bound); +#else + socklen_t bound_len = sizeof(bound); +#endif + EXPECT_EQ(getsockname(probe, reinterpret_cast(&bound), &bound_len), + 0); + CloseSocket(probe); + return ntohs(bound.sin_port); +} + +bool WaitForPeerClose(SocketFd fd, int timeout_ms) { + auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + char drain[4096]; + while (true) { + auto now = std::chrono::steady_clock::now(); + if (now >= deadline) { + return false; + } + int rem_ms = static_cast( + std::chrono::duration_cast(deadline - now) + .count()); + if (rem_ms <= 0) rem_ms = 1; + if (!WaitForSocketReadable(fd, rem_ms)) { + return false; + } +#if defined(_WIN32) + int n = recv(fd, drain, sizeof(drain), 0); +#else + ssize_t n = recv(fd, drain, sizeof(drain), 0); +#endif + if (n <= 0) { + return true; + } + } +} + +bool SendAll(SocketFd fd, const char* data, size_t len) { + size_t sent = 0; + while (sent < len) { +#if defined(_WIN32) + int n = send(fd, data + sent, static_cast(len - sent), 0); +#else +#ifdef MSG_NOSIGNAL + constexpr int kSendFlags = MSG_NOSIGNAL; +#else + constexpr int kSendFlags = 0; +#endif + ssize_t n = send(fd, data + sent, len - sent, kSendFlags); +#endif + if (n <= 0) { + return false; + } + sent += static_cast(n); + } + return true; +} + +bool SendAll(SocketFd fd, std::string_view s) { + return SendAll(fd, s.data(), s.size()); +} + +// Reads from `fd` until the request head and `body_bytes` bytes after it have +// arrived. Use only for requests whose body is not chunked. +bool ReadRequestHeadAndBody(SocketFd fd, size_t body_bytes) { + std::string head; + size_t body_received = 0; + bool head_complete = false; + char tmp[16384]; + while (!head_complete || body_received < body_bytes) { +#if defined(_WIN32) + int n = recv(fd, tmp, sizeof(tmp), 0); +#else + ssize_t n = recv(fd, tmp, sizeof(tmp), 0); +#endif + if (n <= 0) { + return false; + } + if (head_complete) { + body_received += static_cast(n); + continue; + } + head.append(tmp, static_cast(n)); + size_t head_end = head.find("\r\n\r\n"); + if (head_end != std::string::npos) { + head_complete = true; + body_received = head.size() - (head_end + 4); + } + } + return true; +} + +// Deterministic body byte for `offset`; unlike a short repeating pattern it +// exposes dropped, duplicated, or reordered blocks. +uint8_t PatternByte(size_t offset) { + return static_cast((static_cast(offset) * 2654435761u) >> + 24); +} + +struct ParsedRequest { + std::string method; + std::string target; + std::vector> headers; + std::string body; + + std::string GetHeader(std::string_view name) const { + for (const auto& kv : headers) { + if (AsciiEqualsIgnoreCase(kv.first, name)) { + return kv.second; + } + } + return {}; + } + + bool HasHeader(std::string_view name) const { + for (const auto& kv : headers) { + if (AsciiEqualsIgnoreCase(kv.first, name)) { + return true; + } + } + return false; + } +}; + +// Minimal in-process HTTP/1.1 loopback test server for deterministic HTTP & SSE +// integration testing (supports chunked uploads, SSE trickle streams, idle +// stalls, raw connection handlers, and concurrent connections). +class LoopbackHttpServer { + public: + using Handler = std::function; + // Handles an accepted connection itself; the server reads nothing first. + using RawHandler = std::function; + + // When `raw_handler` is set it serves every connection and `handler` is not + // used. + explicit LoopbackHttpServer(Handler handler, RawHandler raw_handler = nullptr) + : handler_(std::move(handler)), raw_handler_(std::move(raw_handler)) { + EnsureSocketSubsystemInitialized(); + SocketFd fd = socket(AF_INET, SOCK_STREAM, 0); + listen_fd_.store(fd, std::memory_order_release); + EXPECT_NE(fd, kInvalidSocket); + + int reuse = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, + reinterpret_cast(&reuse), sizeof(reuse)); + + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; + EXPECT_EQ(bind(fd, reinterpret_cast(&addr), sizeof(addr)), 0); + EXPECT_EQ(listen(fd, 32), 0); + + sockaddr_in bound{}; +#if defined(_WIN32) + int bound_len = sizeof(bound); +#else + socklen_t bound_len = sizeof(bound); +#endif + EXPECT_EQ(getsockname(fd, reinterpret_cast(&bound), &bound_len), + 0); + port_ = ntohs(bound.sin_port); + + accept_thread_ = std::thread([this]() { AcceptLoop(); }); + } + + ~LoopbackHttpServer() { Stop(); } + + void Stop() { + if (stopped_.exchange(true)) { + return; + } + if (port_ > 0) { + SocketFd wake = socket(AF_INET, SOCK_STREAM, 0); + if (wake != kInvalidSocket) { + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = htons(static_cast(port_)); + (void)connect(wake, reinterpret_cast(&addr), sizeof(addr)); + CloseSocket(wake); + } + } + if (accept_thread_.joinable()) { + accept_thread_.join(); + } + SocketFd to_close = + listen_fd_.exchange(kInvalidSocket, std::memory_order_acq_rel); + if (to_close != kInvalidSocket) { + CloseSocket(to_close); + } + std::vector to_join; + { + std::lock_guard lock(workers_mutex_); + to_join.swap(workers_); + } + for (auto& t : to_join) { + if (t.joinable()) { + t.join(); + } + } + } + + int port() const { return port_; } + + std::string Url(std::string_view path) const { + return "http://127.0.0.1:" + std::to_string(port_) + std::string(path); + } + + private: + void AcceptLoop() { + while (!stopped_.load()) { + SocketFd fd = listen_fd_.load(std::memory_order_acquire); + if (fd == kInvalidSocket) { + break; + } + if (!WaitForSocketReadable(fd, 50)) { + continue; + } + if (stopped_.load()) { + break; + } + sockaddr_in client_addr{}; +#if defined(_WIN32) + int len = sizeof(client_addr); +#else + socklen_t len = sizeof(client_addr); +#endif + SocketFd client = + accept(fd, reinterpret_cast(&client_addr), &len); + if (client == kInvalidSocket) { + if (stopped_.load()) break; + continue; + } + if (stopped_.load()) { + CloseSocket(client); + break; + } + int nodelay = 1; + setsockopt(client, IPPROTO_TCP, TCP_NODELAY, + reinterpret_cast(&nodelay), sizeof(nodelay)); +#ifdef SO_NOSIGPIPE + int nosigpipe = 1; + setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, + reinterpret_cast(&nosigpipe), sizeof(nosigpipe)); +#endif + std::lock_guard lock(workers_mutex_); + workers_.emplace_back([this, client]() { + HandleClient(client); + CloseSocket(client); + }); + } + } + + static bool ReadHttpRequest(SocketFd fd, ParsedRequest* out) { + std::string buf; + char tmp[4096]; + size_t header_end = std::string::npos; + while (header_end == std::string::npos) { +#if defined(_WIN32) + int n = recv(fd, tmp, sizeof(tmp), 0); +#else + ssize_t n = recv(fd, tmp, sizeof(tmp), 0); +#endif + if (n <= 0) return false; + buf.append(tmp, static_cast(n)); + header_end = buf.find("\r\n\r\n"); + } + + std::string header_block = buf.substr(0, header_end); + std::string remainder = buf.substr(header_end + 4); + + size_t line_end = header_block.find("\r\n"); + std::string req_line = line_end == std::string::npos + ? header_block + : header_block.substr(0, line_end); + size_t sp1 = req_line.find(' '); + size_t sp2 = sp1 == std::string::npos ? std::string::npos + : req_line.find(' ', sp1 + 1); + if (sp1 == std::string::npos || sp2 == std::string::npos) { + return false; + } + out->method = req_line.substr(0, sp1); + out->target = req_line.substr(sp1 + 1, sp2 - (sp1 + 1)); + + size_t pos = + line_end == std::string::npos ? header_block.size() : line_end + 2; + while (pos < header_block.size()) { + size_t next = header_block.find("\r\n", pos); + std::string_view line = + next == std::string::npos + ? std::string_view(header_block).substr(pos) + : std::string_view(header_block).substr(pos, next - pos); + pos = next == std::string::npos ? header_block.size() : next + 2; + size_t colon = line.find(':'); + if (colon != std::string_view::npos && colon > 0) { + out->headers.emplace_back( + std::string(TrimAsciiWhitespace(line.substr(0, colon))), + std::string(TrimAsciiWhitespace(line.substr(colon + 1)))); + } + } + + std::string te = out->GetHeader("Transfer-Encoding"); + if (AsciiEqualsIgnoreCase(te, "chunked")) { + std::string raw = std::move(remainder); + auto ensure = [&](size_t need) -> bool { + while (raw.size() < need) { +#if defined(_WIN32) + int n = recv(fd, tmp, sizeof(tmp), 0); +#else + ssize_t n = recv(fd, tmp, sizeof(tmp), 0); +#endif + if (n <= 0) return false; + raw.append(tmp, static_cast(n)); + } + return true; + }; + while (true) { + size_t crlf = raw.find("\r\n"); + while (crlf == std::string::npos) { + if (!ensure(raw.size() + 1)) return false; + crlf = raw.find("\r\n"); + } + size_t chunk_len = static_cast( + std::strtoull(raw.substr(0, crlf).c_str(), nullptr, 16)); + raw.erase(0, crlf + 2); + if (chunk_len == 0) { + ensure(2); + break; + } + if (!ensure(chunk_len + 2)) return false; + out->body.append(raw.data(), chunk_len); + raw.erase(0, chunk_len + 2); + } + } else { + std::string cl = out->GetHeader("Content-Length"); + size_t content_len = + cl.empty() + ? 0 + : static_cast(std::strtoull(cl.c_str(), nullptr, 10)); + out->body = std::move(remainder); + while (out->body.size() < content_len) { +#if defined(_WIN32) + int n = recv(fd, tmp, sizeof(tmp), 0); +#else + ssize_t n = recv(fd, tmp, sizeof(tmp), 0); +#endif + if (n <= 0) return false; + out->body.append(tmp, static_cast(n)); + } + if (out->body.size() > content_len) { + out->body.resize(content_len); + } + } + return true; + } + + void HandleClient(SocketFd fd) { + if (raw_handler_) { + raw_handler_(fd); + return; + } + ParsedRequest req; + if (!ReadHttpRequest(fd, &req)) { + return; + } + handler_(req, fd); + } + + Handler handler_; + RawHandler raw_handler_; + std::atomic listen_fd_{kInvalidSocket}; + int port_ = 0; + std::atomic stopped_{false}; + std::thread accept_thread_; + std::mutex workers_mutex_; + std::vector workers_; +}; + +// Event-driven test helper that asserts exact completion events using blocking +// `HttpWaitNextEventInternal` calls (never polling in a sleep loop, T2). +class BlockingEventDemux { + public: + void DrainStale() { + buffered_.clear(); + while (HttpWaitNextEventInternal(0) != 0) { + } + } + + bool WaitFor(int64_t handle, HttpEventKind expected_kind, int timeout_ms) { + auto& q = buffered_[handle]; + for (auto it = q.begin(); it != q.end(); ++it) { + if (*it == expected_kind) { + q.erase(it); + return true; + } + } + + auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(timeout_ms); + while (true) { + auto now = std::chrono::steady_clock::now(); + if (now >= deadline) { + return false; + } + int32_t rem_ms = static_cast( + std::chrono::duration_cast(deadline - now) + .count()); + if (rem_ms <= 0) { + rem_ms = 1; + } + int64_t ev = HttpWaitNextEventInternal(rem_ms); + if (ev == 0) { + return false; + } + int64_t ev_handle = ev >> 8; + auto ev_kind = static_cast(ev & 0xFF); + if (ev_handle == handle && ev_kind == expected_kind) { + return true; + } + buffered_[ev_handle].push_back(ev_kind); + } + } + + private: + std::unordered_map> buffered_; +}; + +int32_t WaitHeaders(BlockingEventDemux* demux, int64_t handle, + int timeout_ms = 5000) { + int32_t status = HttpPollResponseHeadersInternal(handle); + if (status != 0) { + return status; + } + EXPECT_TRUE( + demux->WaitFor(handle, kHttpEventResponseHeadersReady, timeout_ms)) + << "Timed out waiting for kHttpEventResponseHeadersReady on handle " + << handle; + return HttpPollResponseHeadersInternal(handle); +} + +bool ReadAllBody(BlockingEventDemux* demux, int64_t handle, std::string* out, + int timeout_ms = 10000) { + auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + char buf[16384]; + while (true) { + int32_t n = HttpTryReadResponseBodyInternal(handle, buf, sizeof(buf)); + if (n > 0) { + out->append(buf, static_cast(n)); + continue; + } + if (n == 0) { + return true; + } + if (n == kHttpReadErrorOrCanceled) { + return false; + } + auto now = std::chrono::steady_clock::now(); + if (now >= deadline) { + return false; + } + int rem_ms = static_cast( + std::chrono::duration_cast(deadline - now) + .count()); + if (!demux->WaitFor(handle, kHttpEventResponseBodyAvailable, + (std::max)(rem_ms, 1))) { + ADD_FAILURE() << "Expected kHttpEventResponseBodyAvailable event"; + return false; + } + } +} + +// Result of `WriteBody` when the deadline passed before every byte was +// accepted. +constexpr int32_t kWriteTimedOut = 1; + +// Writes `len` request body bytes without finishing the body. Returns 0 once +// every byte was accepted, the negative result of +// `HttpTryWriteRequestBodyInternal` if it refused a write, or `kWriteTimedOut`. +int32_t WriteBody(BlockingEventDemux* demux, int64_t handle, + const uint8_t* data, size_t len, int timeout_ms = 10000) { + auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + size_t offset = 0; + while (offset < len) { + int32_t to_send = static_cast( + (std::min)(len - offset, static_cast(65536))); + int32_t n = HttpTryWriteRequestBodyInternal( + handle, const_cast(data + offset), to_send); + if (n < 0) return n; + if (n > 0) { + offset += static_cast(n); + continue; + } + auto now = std::chrono::steady_clock::now(); + if (now >= deadline) { + return kWriteTimedOut; + } + int rem_ms = static_cast( + std::chrono::duration_cast(deadline - now) + .count()); + if (!demux->WaitFor(handle, kHttpEventRequestSpaceAvailable, + (std::max)(rem_ms, 1))) { + ADD_FAILURE() << "Expected kHttpEventRequestSpaceAvailable event"; + return kWriteTimedOut; + } + } + return 0; +} + +bool WriteAllBody(BlockingEventDemux* demux, int64_t handle, + const uint8_t* data, size_t len, int timeout_ms = 10000) { + if (WriteBody(demux, handle, data, len, timeout_ms) != 0) { + return false; + } + HttpFinishRequestBodyInternal(handle); + return true; +} + +TEST(HttpTransportCurlTest, GetBasic200AndMultiValueHeaders) { + BlockingEventDemux demux; + demux.DrainStale(); + + LoopbackHttpServer server([](const ParsedRequest& req, SocketFd fd) { + EXPECT_EQ(req.method, "GET"); + EXPECT_EQ(req.target, "/hello"); + EXPECT_EQ(req.GetHeader("X-Client"), "firebase-cpp"); + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Set-Cookie: a=1\r\n" + "Set-Cookie: b=2\r\n" + "Content-Length: 5\r\n" + "Connection: close\r\n" + "\r\n" + "world"); + }); + + int64_t h = HttpCreateRequestInternal("GET", server.Url("/hello").c_str(), + "X-Client\tfirebase-cpp\n", "", + kNoRequestContent); + HttpStartRequestInternal(h); + ASSERT_EQ(WaitHeaders(&demux, h), 200); + + std::string raw_headers = HttpGetResponseHeadersInternal(h); + EXPECT_NE(raw_headers.find("Set-Cookie\ta=1\n"), std::string::npos); + EXPECT_NE(raw_headers.find("Set-Cookie\tb=2\n"), std::string::npos); + + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, h, &body)); + EXPECT_EQ(body, "world"); + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, ZeroLengthGetAndHeadStayGetAndHead) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::mutex mu; + std::string get_method; + std::string head_method; + LoopbackHttpServer server([&](const ParsedRequest& req, SocketFd fd) { + if (req.target == "/zero-get") { + { + std::lock_guard lock(mu); + get_method = req.method; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: close\r\n\r\nok"); + } else if (req.target == "/zero-head") { + { + std::lock_guard lock(mu); + head_method = req.method; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 1234\r\n" + "Connection: close\r\n\r\n"); + } + }); + + int64_t h1 = HttpCreateRequestInternal("GET", server.Url("/zero-get").c_str(), + "", "", 0); + HttpStartRequestInternal(h1); + ASSERT_EQ(WaitHeaders(&demux, h1), 200); + std::string b1; + ASSERT_TRUE(ReadAllBody(&demux, h1, &b1)); + EXPECT_EQ(b1, "ok"); + HttpDestroyRequestInternal(h1); + + int64_t h2 = HttpCreateRequestInternal( + "HEAD", server.Url("/zero-head").c_str(), "", "", 0); + HttpStartRequestInternal(h2); + ASSERT_EQ(WaitHeaders(&demux, h2), 200); + std::string b2; + ASSERT_TRUE(ReadAllBody(&demux, h2, &b2)); + EXPECT_TRUE(b2.empty()); + HttpDestroyRequestInternal(h2); + + std::lock_guard lock(mu); + EXPECT_EQ(get_method, "GET"); + EXPECT_EQ(head_method, "HEAD"); +} + +TEST(HttpTransportCurlTest, PostJsonAndError400And204NoContent) { + BlockingEventDemux demux; + demux.DrainStale(); + + LoopbackHttpServer server([](const ParsedRequest& req, SocketFd fd) { + if (req.target == "/callable") { + EXPECT_EQ(req.method, "POST"); + EXPECT_EQ(req.body, "{\"data\":{\"msg\":\"hi\"}}"); + std::string resp = "{\"result\":{\"echo\":\"hi\"}}"; + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: application/json\r\n" + "Content-Length: " + + std::to_string(resp.size()) + + "\r\nConnection: close\r\n\r\n" + resp); + } else if (req.target == "/err400") { + std::string resp = "{\"error\":{\"status\":\"INVALID_ARGUMENT\"}}"; + SendAll(fd, + "HTTP/1.1 400 Bad Request\r\n" + "Content-Type: application/json\r\n" + "Content-Length: " + + std::to_string(resp.size()) + + "\r\nConnection: close\r\n\r\n" + resp); + } else if (req.target == "/delete") { + EXPECT_EQ(req.method, "DELETE"); + SendAll(fd, + "HTTP/1.1 204 No Content\r\n" + "Connection: close\r\n\r\n"); + } + }); + + // 1. JSON POST + const std::string payload = "{\"data\":{\"msg\":\"hi\"}}"; + int64_t h1 = + HttpCreateRequestInternal("POST", server.Url("/callable").c_str(), + "Content-Type\tapplication/json\n", "", + static_cast(payload.size())); + HttpStartRequestInternal(h1); + ASSERT_TRUE(WriteAllBody(&demux, h1, + reinterpret_cast(payload.data()), + payload.size())); + ASSERT_EQ(WaitHeaders(&demux, h1), 200); + std::string body1; + ASSERT_TRUE(ReadAllBody(&demux, h1, &body1)); + EXPECT_EQ(body1, "{\"result\":{\"echo\":\"hi\"}}"); + HttpDestroyRequestInternal(h1); + + // 2. 400 error JSON body preserved + int64_t h2 = HttpCreateRequestInternal("POST", server.Url("/err400").c_str(), + "", "", 0); + HttpStartRequestInternal(h2); + ASSERT_EQ(WaitHeaders(&demux, h2), 400); + std::string body2; + ASSERT_TRUE(ReadAllBody(&demux, h2, &body2)); + EXPECT_EQ(body2, "{\"error\":{\"status\":\"INVALID_ARGUMENT\"}}"); + HttpDestroyRequestInternal(h2); + + // 3. 204 No Content + int64_t h3 = HttpCreateRequestInternal( + "DELETE", server.Url("/delete").c_str(), "", "", kNoRequestContent); + HttpStartRequestInternal(h3); + ASSERT_EQ(WaitHeaders(&demux, h3), 204); + std::string body3; + ASSERT_TRUE(ReadAllBody(&demux, h3, &body3)); + EXPECT_TRUE(body3.empty()); + HttpDestroyRequestInternal(h3); +} + +TEST(HttpTransportCurlTest, SseTrickleStreamingImmediateDelivery) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::mutex gate_mu; + std::condition_variable gate_cv; + int client_acked_chunk = 0; + + LoopbackHttpServer server([&](const ParsedRequest& req, SocketFd fd) { + EXPECT_EQ(req.method, "POST"); + EXPECT_EQ(req.GetHeader("Accept"), "text/event-stream"); + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "Transfer-Encoding: chunked\r\n" + "Connection: close\r\n" + "\r\n"); + + auto send_chunk = [&](std::string_view sse) { + char hex[32]; + std::snprintf(hex, sizeof(hex), "%zx\r\n", sse.size()); + SendAll(fd, hex); + SendAll(fd, sse); + SendAll(fd, "\r\n"); + }; + + send_chunk("data: {\"seq\":1}\n\n"); + { + std::unique_lock lock(gate_mu); + ASSERT_TRUE(gate_cv.wait_for(lock, std::chrono::seconds(5), + [&]() { return client_acked_chunk >= 1; })); + } + + send_chunk("data: {\"seq\":2}\n\n"); + { + std::unique_lock lock(gate_mu); + ASSERT_TRUE(gate_cv.wait_for(lock, std::chrono::seconds(5), + [&]() { return client_acked_chunk >= 2; })); + } + + send_chunk("data: {\"seq\":3}\n\n"); + SendAll(fd, "0\r\n\r\n"); + }); + + const std::string req_body = "{\"prompt\":\"stream\"}"; + int64_t h = HttpCreateRequestInternal( + "POST", server.Url("/sse").c_str(), + "Accept\ttext/event-stream\nContent-Type\tapplication/json\n", "", + static_cast(req_body.size())); + HttpStartRequestInternal(h); + ASSERT_TRUE(WriteAllBody(&demux, h, + reinterpret_cast(req_body.data()), + req_body.size())); + ASSERT_EQ(WaitHeaders(&demux, h), 200); + + auto read_until = [&](std::string* accum, std::string_view needle) -> bool { + char buf[1024]; + while (accum->find(needle) == std::string::npos) { + int32_t n = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); + if (n > 0) { + accum->append(buf, static_cast(n)); + } else if (n == 0 || n == kHttpReadErrorOrCanceled) { + break; + } else { + if (!demux.WaitFor(h, kHttpEventResponseBodyAvailable, 5000)) { + return false; + } + } + } + return accum->find(needle) != std::string::npos; + }; + + std::string accum; + ASSERT_TRUE(read_until(&accum, "data: {\"seq\":1}\n\n")); + { + std::lock_guard lock(gate_mu); + client_acked_chunk = 1; + } + gate_cv.notify_all(); + + ASSERT_TRUE(read_until(&accum, "data: {\"seq\":2}\n\n")); + { + std::lock_guard lock(gate_mu); + client_acked_chunk = 2; + } + gate_cv.notify_all(); + + std::string rest; + ASSERT_TRUE(ReadAllBody(&demux, h, &rest)); + accum.append(rest); + EXPECT_NE(accum.find("data: {\"seq\":3}\n\n"), std::string::npos); + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, SseIdleCancelUnblocksPromptly) { + BlockingEventDemux demux; + demux.DrainStale(); + + // T1: Server explicitly waits for peer socket close (EOF/RST) on cancel. + std::mutex close_mu; + std::condition_variable close_cv; + bool server_observed_close = false; + + LoopbackHttpServer server([&](const ParsedRequest&, SocketFd fd) { + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "12\r\ndata: {\"ok\":true}\n\r\n"); + bool closed = WaitForPeerClose(fd, 5000); + { + std::lock_guard lock(close_mu); + server_observed_close = closed; + } + close_cv.notify_all(); + }); + + int64_t h = HttpCreateRequestInternal("GET", server.Url("/hang").c_str(), + "Accept\ttext/event-stream\n", "", + kNoRequestContent); + HttpStartRequestInternal(h); + ASSERT_EQ(WaitHeaders(&demux, h), 200); + + // Read the first SSE chunk using blocking event waits (T2). + std::string got; + char buf[512]; + while (got.empty()) { + int32_t n = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); + if (n > 0) { + got.append(buf, static_cast(n)); + } else { + ASSERT_EQ(n, kHttpReadWouldBlock); + ASSERT_TRUE(demux.WaitFor(h, kHttpEventResponseBodyAvailable, 5000)); + } + } + EXPECT_EQ(got, "data: {\"ok\":true}\n"); + + // Arm a read while server is silent, then signal canceler via cv (T3: no + // sleep-based synchronization). + ASSERT_EQ(HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)), + kHttpReadWouldBlock); + std::mutex cancel_mu; + std::condition_variable cancel_cv; + bool armed = false; + std::thread canceler([&]() { + { + std::unique_lock lock(cancel_mu); + cancel_cv.wait(lock, [&]() { return armed; }); + } + HttpCancelRequestInternal(h); + }); + + auto t0 = std::chrono::steady_clock::now(); + { + std::lock_guard lock(cancel_mu); + armed = true; + } + cancel_cv.notify_one(); + + ASSERT_TRUE(demux.WaitFor(h, kHttpEventResponseBodyAvailable, 3000)); + int32_t rc = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); + canceler.join(); + + auto elapsed_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0) + .count(); + EXPECT_EQ(rc, kHttpReadErrorOrCanceled); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorCanceled); + EXPECT_LT(elapsed_ms, 1000); + + // Assert the TCP socket actually closed from HttpCancelRequestInternal alone, + // BEFORE HttpDestroyRequestInternal is called (T1). + { + std::unique_lock lock(close_mu); + EXPECT_TRUE(close_cv.wait_for(lock, std::chrono::seconds(3), + [&]() { return server_observed_close; })) + << "Server did not observe TCP socket closure after cancel"; + } + + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, RedirectResponsesAreDeliveredNotFollowed) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::mutex mu; + std::vector seen_requests; + LoopbackHttpServer server([&](const ParsedRequest& req, SocketFd fd) { + { + std::lock_guard lock(mu); + seen_requests.push_back(req.method + " " + req.target + " " + req.body); + } + // "/redirect/" answers with that status and points at + // "/target/", which must never be requested. + const std::string prefix = "/redirect/"; + if (req.target.rfind(prefix, 0) != 0) { + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 8\r\n" + "Connection: close\r\n\r\nfollowed"); + return; + } + std::string status = req.target.substr(prefix.size()); + std::string body = "moved-" + status; + SendAll(fd, "HTTP/1.1 " + status + + " Redirect\r\n" + "Location: /target/" + + status + + "\r\n" + "Content-Length: " + + std::to_string(body.size()) + + "\r\nConnection: close\r\n\r\n" + body); + }); + + std::vector expected_requests; + for (int status : {301, 302, 303, 307, 308}) { + SCOPED_TRACE(status); + const std::string code = std::to_string(status); + int64_t h = HttpCreateRequestInternal( + "GET", server.Url("/redirect/" + code).c_str(), "", "", + kNoRequestContent); + HttpStartRequestInternal(h); + ASSERT_EQ(WaitHeaders(&demux, h), status); + EXPECT_NE(HttpGetResponseHeadersInternal(h).find("Location\t/target/" + + code + "\n"), + std::string::npos); + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, h, &body)); + EXPECT_EQ(body, "moved-" + code); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorNone); + HttpDestroyRequestInternal(h); + expected_requests.push_back("GET /redirect/" + code + " "); + } + + // A request with a body gets the 3xx as its response too. + const std::string upload = "not-replayed"; + int64_t h_post = + HttpCreateRequestInternal("POST", server.Url("/redirect/307").c_str(), "", + "", static_cast(upload.size())); + HttpStartRequestInternal(h_post); + ASSERT_TRUE(WriteAllBody(&demux, h_post, + reinterpret_cast(upload.data()), + upload.size())); + ASSERT_EQ(WaitHeaders(&demux, h_post), 307); + std::string post_body; + ASSERT_TRUE(ReadAllBody(&demux, h_post, &post_body)); + EXPECT_EQ(post_body, "moved-307"); + EXPECT_EQ(HttpGetErrorClassInternal(h_post), kHttpErrorNone); + HttpDestroyRequestInternal(h_post); + expected_requests.push_back("POST /redirect/307 not-replayed"); + + // Exactly one request per operation reached the server. + std::lock_guard lock(mu); + EXPECT_EQ(seen_requests, expected_requests); +} + +TEST(HttpTransportCurlTest, InvalidRequestsFailWithoutConnecting) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::atomic connections{0}; + LoopbackHttpServer server(nullptr, + [&](SocketFd) { connections.fetch_add(1); }); + + struct Case { + const char* name; + const char* method; + std::string url; + const char* headers; + int64_t content_length; + }; + const std::string port = std::to_string(server.port()); + const Case cases[] = { + {"method with a space", "GE T", server.Url("/m1"), "", kNoRequestContent}, + {"method with CRLF", "GET\r\nX-Injected: 1", server.Url("/m2"), "", + kNoRequestContent}, + {"header value with CR", "GET", server.Url("/h1"), + "X-Test\tvalue\rInjected: 1\n", kNoRequestContent}, + {"header line without separator", "GET", server.Url("/h2"), + "X-Test\tvalue\nmalformed_line\n", kNoRequestContent}, + {"header in colon form", "GET", server.Url("/h3"), "X-Test: value\n", + kNoRequestContent}, + {"header name with a space", "GET", server.Url("/h4"), + "Bad Name\tvalue\n", kNoRequestContent}, + {"content length below the sentinels", "POST", server.Url("/c1"), "", -3}, + {"GET with a request body", "GET", server.Url("/c2"), "", 4}, + {"scheme other than http(s)", "GET", "ftp://127.0.0.1:" + port + "/s1", + "", kNoRequestContent}, + {"URL with whitespace", "GET", server.Url("/s2 x"), "", + kNoRequestContent}, + {"URL rejected by libcurl", "GET", "http://127.0.0.1:99999/s3", "", + kNoRequestContent}, + {"URL with userinfo", "GET", "http://user:pass@127.0.0.1:" + port + "/s4", + "", kNoRequestContent}, + }; + for (const Case& c : cases) { + SCOPED_TRACE(c.name); + int64_t h = HttpCreateRequestInternal(c.method, c.url.c_str(), c.headers, + "", c.content_length); + HttpStartRequestInternal(h); + EXPECT_EQ(WaitHeaders(&demux, h), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorInvalidRequest); + EXPECT_FALSE(HttpGetErrorInternal(h).empty()); + HttpDestroyRequestInternal(h); + } + + EXPECT_EQ(connections.load(), 0); +} + +TEST(HttpTransportCurlTest, ProxyUrlReachesLibcurlUnchanged) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::atomic direct_connections{0}; + LoopbackHttpServer server(nullptr, + [&](SocketFd) { direct_connections.fetch_add(1); }); + + // libcurl understands SOCKS proxy URLs. Nothing listens on the proxy port, + // so the transfer fails to connect instead of being rejected as invalid or + // going to the server directly. + const std::string proxy = + "socks5://127.0.0.1:" + std::to_string(ClosedLoopbackPort()); + int64_t h = HttpCreateRequestInternal("GET", server.Url("/via-proxy").c_str(), + "", proxy.c_str(), kNoRequestContent); + HttpStartRequestInternal(h); + EXPECT_EQ(WaitHeaders(&demux, h), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorConnect); + HttpDestroyRequestInternal(h); + + EXPECT_EQ(direct_connections.load(), 0); +} + +TEST(HttpTransportCurlTest, ErrorClassesConnectAndTlsHandshake) { + BlockingEventDemux demux; + demux.DrainStale(); + + // 1. Connect error against a closed loopback port. + EnsureSocketSubsystemInitialized(); + SocketFd probe = socket(AF_INET, SOCK_STREAM, 0); + ASSERT_NE(probe, kInvalidSocket); + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; + ASSERT_EQ(bind(probe, reinterpret_cast(&addr), sizeof(addr)), 0); + sockaddr_in bound{}; +#if defined(_WIN32) + int blen = sizeof(bound); +#else + socklen_t blen = sizeof(bound); +#endif + ASSERT_EQ(getsockname(probe, reinterpret_cast(&bound), &blen), 0); + int closed_port = ntohs(bound.sin_port); + CloseSocket(probe); + + std::string closed_url = + "http://127.0.0.1:" + std::to_string(closed_port) + "/refused"; + int64_t h_conn = HttpCreateRequestInternal("GET", closed_url.c_str(), "", "", + kNoRequestContent); + HttpStartRequestInternal(h_conn); + EXPECT_EQ(WaitHeaders(&demux, h_conn), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h_conn), kHttpErrorConnect); + HttpDestroyRequestInternal(h_conn); + + // 2. A TLS handshake rejected by the peer is a connect failure: no + // certificate was verified. + SocketFd tls_listen = socket(AF_INET, SOCK_STREAM, 0); + ASSERT_NE(tls_listen, kInvalidSocket); + int reuse = 1; + setsockopt(tls_listen, SOL_SOCKET, SO_REUSEADDR, + reinterpret_cast(&reuse), sizeof(reuse)); + sockaddr_in taddr{}; + taddr.sin_family = AF_INET; + taddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + taddr.sin_port = 0; + ASSERT_EQ(bind(tls_listen, reinterpret_cast(&taddr), sizeof(taddr)), + 0); + ASSERT_EQ(listen(tls_listen, 4), 0); + sockaddr_in tbound{}; +#if defined(_WIN32) + int tblen = sizeof(tbound); +#else + socklen_t tblen = sizeof(tbound); +#endif + ASSERT_EQ( + getsockname(tls_listen, reinterpret_cast(&tbound), &tblen), 0); + int tls_port = ntohs(tbound.sin_port); + + std::atomic stop_tls_server{false}; + std::thread bad_tls_server([tls_listen, &stop_tls_server]() { + while (!stop_tls_server.load(std::memory_order_acquire)) { + if (!WaitForSocketReadable(tls_listen, 50)) { + continue; + } + sockaddr_in cli{}; +#if defined(_WIN32) + int clen = sizeof(cli); +#else + socklen_t clen = sizeof(cli); +#endif + SocketFd c = + accept(tls_listen, reinterpret_cast(&cli), &clen); + if (c == kInvalidSocket) { + break; + } + char buf[512]; + (void)recv(c, buf, sizeof(buf), 0); + // Respond with a TLS 1.2 fatal handshake_failure alert. + const char kTlsAlert[] = {0x15, 0x03, 0x03, 0x00, 0x02, 0x02, 0x28}; + SendAll(c, kTlsAlert, sizeof(kTlsAlert)); + ShutdownWrite(c); + CloseSocket(c); + } + CloseSocket(tls_listen); + }); + + std::string https_url = + "https://127.0.0.1:" + std::to_string(tls_port) + "/bad-tls"; + int64_t h_tls = HttpCreateRequestInternal("GET", https_url.c_str(), "", "", + kNoRequestContent); + HttpStartRequestInternal(h_tls); + EXPECT_EQ(WaitHeaders(&demux, h_tls), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h_tls), kHttpErrorConnect); + HttpDestroyRequestInternal(h_tls); + stop_tls_server.store(true, std::memory_order_release); + bad_tls_server.join(); + + // 3. A server that closes the connection during the TLS handshake. + LoopbackHttpServer closing_server(nullptr, [](SocketFd fd) { + // Wait for the ClientHello, then close without answering. + char hello[4096]; + (void)recv(fd, hello, sizeof(hello), 0); + }); + std::string closing_url = + "https://127.0.0.1:" + std::to_string(closing_server.port()) + + "/closed-in-handshake"; + int64_t h_closed = HttpCreateRequestInternal("GET", closing_url.c_str(), "", + "", kNoRequestContent); + HttpStartRequestInternal(h_closed); + EXPECT_EQ(WaitHeaders(&demux, h_closed), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h_closed), kHttpErrorConnect); + HttpDestroyRequestInternal(h_closed); +} + +TEST(HttpTransportCurlTest, + StreamingChunkedUploadAndLargeDownloadBackpressure) { + BlockingEventDemux demux; + demux.DrainStale(); + + constexpr size_t kUploadSize = 1024 * 1024; // 1 MiB (> 256 KiB pipe) + // Far more than the 2 MiB response buffer plus what the socket buffers of + // both ends can hold, so the server cannot send it all to a stalled reader. + constexpr size_t kDownloadSize = 64 * 1024 * 1024; + // How long the server waits for socket space before reporting a stall. + constexpr int kStallMs = 500; + + std::vector expected_upload(kUploadSize); + for (size_t i = 0; i < kUploadSize; ++i) { + expected_upload[i] = static_cast((i * 31 + 7) & 0xFF); + } + + std::mutex upload_mu; + std::string server_received_upload; + std::mutex dl_mu; + std::condition_variable dl_cv; + bool dl_stalled = false; + size_t dl_sent_at_stall = 0; + bool dl_finished = false; + LoopbackHttpServer server([&](const ParsedRequest& req, SocketFd fd) { + if (req.target == "/upload") { + { + std::lock_guard lock(upload_mu); + server_received_upload = req.body; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: close\r\n\r\nok"); + } else if (req.target == "/download") { + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: " + + std::to_string(kDownloadSize) + + "\r\nConnection: close\r\n\r\n"); + // Send without blocking so the server can tell when the client stopped + // taking bytes. + SetNonBlocking(fd); + std::vector block(64 * 1024); + size_t sent = 0; + int stalls = 0; + while (sent < kDownloadSize) { + size_t block_len = (std::min)(block.size(), kDownloadSize - sent); + for (size_t i = 0; i < block_len; ++i) { + block[i] = static_cast(PatternByte(sent + i)); + } + size_t block_sent = 0; + while (block_sent < block_len) { + if (!WaitForSocketWritable(fd, kStallMs)) { + { + std::lock_guard lock(dl_mu); + if (!dl_stalled) { + dl_stalled = true; + dl_sent_at_stall = sent + block_sent; + } + } + dl_cv.notify_all(); + // Give up after 30 s without progress so a broken client cannot + // hang the test. + if (++stalls >= 30000 / kStallMs) { + return; + } + continue; + } + stalls = 0; + int n = + SendSome(fd, block.data() + block_sent, block_len - block_sent); + if (n < 0) { + return; + } + block_sent += static_cast(n); + } + sent += block_len; + } + { + std::lock_guard lock(dl_mu); + dl_finished = true; + } + dl_cv.notify_all(); + } + }); + + // 1. Unknown-length chunked streaming upload. + int64_t h_up = HttpCreateRequestInternal( + "PUT", server.Url("/upload").c_str(), + "Content-Type\tapplication/octet-stream\n", "", kChunkedRequestContent); + HttpStartRequestInternal(h_up); + ASSERT_TRUE( + WriteAllBody(&demux, h_up, expected_upload.data(), expected_upload.size())); + ASSERT_EQ(WaitHeaders(&demux, h_up), 200); + std::string up_resp; + ASSERT_TRUE(ReadAllBody(&demux, h_up, &up_resp)); + EXPECT_EQ(up_resp, "ok"); + { + std::lock_guard lock(upload_mu); + ASSERT_EQ(server_received_upload.size(), expected_upload.size()); + EXPECT_EQ(std::memcmp(server_received_upload.data(), expected_upload.data(), + expected_upload.size()), + 0); + } + HttpDestroyRequestInternal(h_up); + + // 2. Download far larger than kMaxResponseBufferBytes with a reader that + // does not read. The transport must stop taking bytes from the socket once + // its buffer is full, which the server observes as being unable to send the + // rest of the body. + int64_t h_dl = HttpCreateRequestInternal( + "GET", server.Url("/download").c_str(), "", "", kNoRequestContent); + HttpStartRequestInternal(h_dl); + ASSERT_EQ(WaitHeaders(&demux, h_dl), 200); + { + std::unique_lock lock(dl_mu); + ASSERT_TRUE(dl_cv.wait_for(lock, std::chrono::seconds(30), + [&]() { return dl_stalled || dl_finished; })); + EXPECT_FALSE(dl_finished) + << "The server sent the whole body although nothing was read"; + EXPECT_TRUE(dl_stalled); + EXPECT_LT(dl_sent_at_stall, kDownloadSize); + } + + auto dl_op = FindOperation(h_dl); + ASSERT_NE(dl_op, nullptr); + auto buffered_bytes = [&dl_op]() { + std::lock_guard lock(dl_op->mutex); + return dl_op->resp_buffered_bytes; + }; + // The bound is checked before each libcurl write callback, so at most one + // callback's worth of bytes (CURLOPT_BUFFERSIZE, 256 KiB) lands above it. + constexpr size_t kBufferedLimit = kMaxResponseBufferBytes + 256 * 1024; + EXPECT_LE(buffered_bytes(), kBufferedLimit); + + // Reading resumes the transfer and the whole body arrives intact. + std::vector dl_buf(64 * 1024); + size_t dl_received = 0; + size_t dl_mismatches = 0; + size_t dl_max_buffered = 0; + while (true) { + dl_max_buffered = (std::max)(dl_max_buffered, buffered_bytes()); + int32_t n = HttpTryReadResponseBodyInternal( + h_dl, dl_buf.data(), static_cast(dl_buf.size())); + if (n > 0) { + for (int32_t i = 0; i < n; ++i) { + if (static_cast(dl_buf[i]) != PatternByte(dl_received + i)) { + ++dl_mismatches; + } + } + dl_received += static_cast(n); + continue; + } + if (n == 0) { + break; + } + ASSERT_EQ(n, kHttpReadWouldBlock); + ASSERT_TRUE(demux.WaitFor(h_dl, kHttpEventResponseBodyAvailable, 15000)); + } + EXPECT_EQ(dl_received, kDownloadSize); + EXPECT_EQ(dl_mismatches, 0u); + EXPECT_LE(dl_max_buffered, kBufferedLimit); + { + std::unique_lock lock(dl_mu); + EXPECT_TRUE(dl_cv.wait_for(lock, std::chrono::seconds(5), + [&]() { return dl_finished; })); + } + HttpDestroyRequestInternal(h_dl); +} + +TEST(HttpTransportCurlTest, ConcurrentMixedTransfers) { + BlockingEventDemux demux; + demux.DrainStale(); + + LoopbackHttpServer server([](const ParsedRequest& req, SocketFd fd) { + if (req.target.rfind("/echo/", 0) == 0) { + std::string payload(64 * 1024, req.target.back()); + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: " + + std::to_string(payload.size()) + + "\r\nConnection: close\r\n\r\n" + payload); + } else if (req.target.rfind("/sse/", 0) == 0) { + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "Transfer-Encoding: chunked\r\n" + "Connection: close\r\n\r\n"); + for (int i = 0; i < 4; ++i) { + std::string evt = + "data: " + req.target + "#" + std::to_string(i) + "\n\n"; + char hex[32]; + std::snprintf(hex, sizeof(hex), "%zx\r\n", evt.size()); + SendAll(fd, hex); + SendAll(fd, evt); + SendAll(fd, "\r\n"); + } + SendAll(fd, "0\r\n\r\n"); + } + }); + + constexpr int kOps = 6; + std::vector handles; + handles.reserve(kOps); + for (int i = 0; i < 3; ++i) { + char tag = static_cast('A' + i); + std::string url = server.Url(std::string("/echo/") + tag); + int64_t h = HttpCreateRequestInternal("GET", url.c_str(), "", "", + kNoRequestContent); + HttpStartRequestInternal(h); + handles.push_back(h); + } + for (int i = 0; i < 3; ++i) { + std::string url = server.Url("/sse/" + std::to_string(i)); + int64_t h = HttpCreateRequestInternal("GET", url.c_str(), + "Accept\ttext/event-stream\n", "", + kNoRequestContent); + HttpStartRequestInternal(h); + handles.push_back(h); + } + + for (int i = 0; i < 3; ++i) { + ASSERT_EQ(WaitHeaders(&demux, handles[i]), 200); + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, handles[i], &body)); + EXPECT_EQ(body.size(), 64u * 1024u); + EXPECT_EQ(body.front(), static_cast('A' + i)); + EXPECT_EQ(body.back(), static_cast('A' + i)); + HttpDestroyRequestInternal(handles[i]); + } + for (int i = 3; i < 6; ++i) { + ASSERT_EQ(WaitHeaders(&demux, handles[i]), 200); + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, handles[i], &body)); + std::string expected_last = + "data: /sse/" + std::to_string(i - 3) + "#3\n\n"; + EXPECT_NE(body.find(expected_last), std::string::npos); + HttpDestroyRequestInternal(handles[i]); + } +} + +TEST(HttpTransportCurlTest, EarlyServerResponseEndsLargeUploadWithoutError) { + BlockingEventDemux demux; + demux.DrainStale(); + + constexpr size_t kUploadSize = 2 * 1024 * 1024; + constexpr size_t kSentBeforeReject = 512 * 1024; + constexpr int kIterations = 50; + + // The server answers 413 once the request head and the first + // kSentBeforeReject body bytes arrived, so the client is in the middle of + // its upload. It then keeps the socket open until the client closes it, so + // the response is never lost to a reset caused by unread request bytes. Every + // other response carries `Connection: close`, which changes how libcurl + // winds the upload down. + std::atomic connections{0}; + LoopbackHttpServer server(nullptr, [&](SocketFd fd) { + int index = connections.fetch_add(1); + if (!ReadRequestHeadAndBody(fd, kSentBeforeReject)) { + ADD_FAILURE() << "Connection closed before the request arrived"; + return; + } + std::string response = + "HTTP/1.1 413 Payload Too Large\r\n" + "Content-Length: 9\r\n"; + if (index % 2 == 1) { + response += "Connection: close\r\n"; + } + response += "\r\ntoo large"; + SendAll(fd, response); + EXPECT_TRUE(WaitForPeerClose(fd, 5000)); + }); + + std::vector payload(kUploadSize, 0x42); + for (int i = 0; i < kIterations; ++i) { + SCOPED_TRACE(i); + int64_t h = HttpCreateRequestInternal( + "PUT", server.Url("/early-reject/" + std::to_string(i)).c_str(), + "Content-Type\tapplication/octet-stream\n", "", + static_cast(kUploadSize)); + HttpStartRequestInternal(h); + + // The server responds only after it received these bytes, so the + // transport accepts all of them. + ASSERT_EQ(WriteBody(&demux, h, payload.data(), kSentBeforeReject), 0); + ASSERT_EQ(WaitHeaders(&demux, h), 413); + + // The rest of the body is turned away without failing the operation. + EXPECT_EQ(WriteBody(&demux, h, payload.data() + kSentBeforeReject, + kUploadSize - kSentBeforeReject), + kHttpWriteClosed); + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, h, &body)); + EXPECT_EQ(body, "too large"); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorNone); + EXPECT_TRUE(HttpGetErrorInternal(h).empty()); + auto op = FindOperation(h); + ASSERT_NE(op, nullptr); + EXPECT_FALSE(op->IsCanceled()); + HttpDestroyRequestInternal(h); + } + + EXPECT_EQ(connections.load(), kIterations); +} + +TEST(HttpTransportCurlTest, EarlyErrorResponseStopsUploadBeforeBodyCompletes) { + BlockingEventDemux demux; + demux.DrainStale(); + + constexpr size_t kUploadSize = 3 * 1024 * 1024; + constexpr size_t kSentBeforeReject = 300 * 1024; + + // The server sends the status line and headers of a 429, then holds the + // response body back until the client's writer has been turned away. + std::mutex mu; + std::condition_variable cv; + bool writer_stopped = false; + LoopbackHttpServer server(nullptr, [&](SocketFd fd) { + if (!ReadRequestHeadAndBody(fd, kSentBeforeReject)) { + ADD_FAILURE() << "Connection closed before the request arrived"; + return; + } + SendAll(fd, + "HTTP/1.1 429 Too Many Requests\r\n" + "Content-Length: 11\r\n" + "\r\n"); + { + std::unique_lock lock(mu); + EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), + [&]() { return writer_stopped; })); + } + SendAll(fd, "retry later"); + EXPECT_TRUE(WaitForPeerClose(fd, 5000)); + }); + + std::vector payload(kUploadSize, 0x37); + int64_t h = + HttpCreateRequestInternal("POST", server.Url("/early-429").c_str(), + "Content-Type\tapplication/octet-stream\n", "", + static_cast(kUploadSize)); + HttpStartRequestInternal(h); + ASSERT_EQ(WriteBody(&demux, h, payload.data(), kSentBeforeReject), 0); + ASSERT_EQ(WaitHeaders(&demux, h), 429); + + // The writer is turned away while the response body is still outstanding. + EXPECT_EQ(WriteBody(&demux, h, payload.data() + kSentBeforeReject, + kUploadSize - kSentBeforeReject), + kHttpWriteClosed); + char probe[32]; + EXPECT_EQ(HttpTryReadResponseBodyInternal(h, probe, sizeof(probe)), + kHttpReadWouldBlock); + { + std::lock_guard lock(mu); + writer_stopped = true; + } + cv.notify_all(); + + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, h, &body)); + EXPECT_EQ(body, "retry later"); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorNone); + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, WriteAfterResponseCompleteAndAfterCancel) { + BlockingEventDemux demux; + demux.DrainStale(); + + // 1. After the response completed, a write reports the closed write side. + LoopbackHttpServer server([](const ParsedRequest& req, SocketFd fd) { + EXPECT_EQ(req.body, "ping"); + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 4\r\n" + "Connection: close\r\n\r\npong"); + }); + const std::string request_body = "ping"; + int64_t h_done = + HttpCreateRequestInternal("POST", server.Url("/done").c_str(), "", "", + static_cast(request_body.size())); + HttpStartRequestInternal(h_done); + ASSERT_TRUE(WriteAllBody( + &demux, h_done, reinterpret_cast(request_body.data()), + request_body.size())); + ASSERT_EQ(WaitHeaders(&demux, h_done), 200); + std::string response_body; + ASSERT_TRUE(ReadAllBody(&demux, h_done, &response_body)); + EXPECT_EQ(response_body, "pong"); + + uint8_t late[8] = {}; + EXPECT_EQ(HttpTryWriteRequestBodyInternal(h_done, late, sizeof(late)), + kHttpWriteClosed); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(h_done, late, 0), kHttpWriteClosed); + HttpFinishRequestBodyInternal(h_done); + EXPECT_EQ(HttpGetErrorClassInternal(h_done), kHttpErrorNone); + HttpDestroyRequestInternal(h_done); + + // 2. After cancellation of a transfer in flight, a write reports an error. + std::mutex connect_mu; + std::condition_variable connect_cv; + bool server_connected = false; + LoopbackHttpServer hanging_server(nullptr, [&](SocketFd fd) { + { + std::lock_guard lock(connect_mu); + server_connected = true; + } + connect_cv.notify_all(); + // Never respond; hold the connection until the client drops it. + (void)WaitForPeerClose(fd, 5000); + }); + int64_t h_cancel = + HttpCreateRequestInternal("POST", hanging_server.Url("/cancel").c_str(), + "", "", kChunkedRequestContent); + HttpStartRequestInternal(h_cancel); + uint8_t early[16] = {}; + EXPECT_EQ(HttpTryWriteRequestBodyInternal(h_cancel, early, sizeof(early)), + static_cast(sizeof(early))); + { + std::unique_lock lock(connect_mu); + ASSERT_TRUE(connect_cv.wait_for(lock, std::chrono::seconds(5), + [&]() { return server_connected; })); + } + HttpCancelRequestInternal(h_cancel); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(h_cancel, early, sizeof(early)), + -1); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(h_cancel, early, 0), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h_cancel), kHttpErrorCanceled); + HttpDestroyRequestInternal(h_cancel); +} + +} // namespace +} // namespace http +} // namespace firebase diff --git a/app/http/tests/websocket_common_test.cc b/app/http/tests/websocket_common_test.cc new file mode 100644 index 0000000000..b285869502 --- /dev/null +++ b/app/http/tests/websocket_common_test.cc @@ -0,0 +1,794 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Tests of the shared WebSocket queueing code. No connection is made: each +// test plays the backend by calling the `WebSocketOperation` methods. + +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/websocket.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace http { +namespace { + +void DrainEvents() { + while (HttpWaitNextEventInternal(0) != 0) { + } +} + +void ExpectEvent(int64_t handle, HttpEventKind kind) { + int64_t event = HttpWaitNextEventInternal(1000); + EXPECT_EQ(event >> 8, handle); + EXPECT_EQ(static_cast(event & 0xFF), kind); +} + +void ExpectNoEvent() { EXPECT_EQ(HttpWaitNextEventInternal(0), 0); } + +// Creates a socket and plays a backend that opened it. +int64_t CreateOpenSocket(const char* url) { + int64_t handle = WebSocketCreateInternal(url, "", "", ""); + auto ws = FindWebSocket(handle); + EXPECT_NE(ws, nullptr); + if (ws) { + ws->MarkOpen(""); + } + return handle; +} + +int32_t SendText(int64_t handle, std::string text, bool end_of_message) { + return WebSocketTrySendInternal(handle, kWebSocketText, text.data(), + static_cast(text.size()), + end_of_message); +} + +std::vector Bytes(const std::string& text) { + return std::vector(text.begin(), text.end()); +} + +std::string Text(const std::vector& bytes) { + return std::string(bytes.begin(), bytes.end()); +} + +// Receives into a buffer of `max_length` bytes and appends them to `out`. +int64_t Receive(int64_t handle, int32_t max_length, std::string* out) { + std::string buffer(static_cast(max_length), '\0'); + int64_t result = + WebSocketTryReceiveInternal(handle, buffer.data(), max_length); + if (result >= 0) { + out->append(buffer.data(), static_cast(result >> 8)); + } + return result; +} + +TEST(WebSocketCommonTest, CreateValidatesUrlHeadersAndSubprotocols) { + DrainEvents(); + struct Case { + const char* name; + const char* url; + const char* headers; + const char* subprotocols; + }; + const Case invalid[] = { + {"http scheme", "http://127.0.0.1:9/a", "", ""}, + {"no scheme", "127.0.0.1:9/b", "", ""}, + {"scheme only", "ws://", "", ""}, + {"whitespace in URL", "ws://127.0.0.1:9/c d", "", ""}, + {"header name with a space", "ws://127.0.0.1:9/e", "Bad Name\tv\n", ""}, + {"header value with CR", "ws://127.0.0.1:9/f", "X-A\tv\rX-B: 1\n", ""}, + {"header in colon form", "ws://127.0.0.1:9/g", "X-A: v\n", ""}, + {"subprotocol with a space", "ws://127.0.0.1:9/h", "", "chat, bad one"}, + {"empty subprotocol entry", "ws://127.0.0.1:9/i", "", "chat,,other"}, + {"trailing comma", "ws://127.0.0.1:9/j", "", "chat,"}, + }; + for (const Case& c : invalid) { + SCOPED_TRACE(c.name); + int64_t handle = + WebSocketCreateInternal(c.url, c.headers, c.subprotocols, ""); + ASSERT_GT(handle, 0); + EXPECT_EQ(WebSocketPollOpenInternal(handle), -1); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorInvalidRequest); + EXPECT_FALSE(WebSocketGetErrorInternal(handle).empty()); + // Connecting a failed socket does nothing. + WebSocketConnectInternal(handle); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorInvalidRequest); + WebSocketDestroyInternal(handle); + } + ExpectNoEvent(); + + int64_t handle = WebSocketCreateInternal( + "WSS://Example.com/socket", "X-First\tone\nX-Second\ttwo\n", + " chat.v1 , chat.v2 ", "http://127.0.0.1:3128"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketConnecting); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorNone); + EXPECT_EQ(ws->url, "WSS://Example.com/socket"); + EXPECT_EQ(ws->proxy_url, "http://127.0.0.1:3128"); + EXPECT_EQ(ws->subprotocols, (std::vector{"chat.v1", "chat.v2"})); + ASSERT_EQ(ws->request_headers.size(), 2u); + EXPECT_EQ(ws->request_headers[0], + std::make_pair(std::string("X-First"), std::string("one"))); + EXPECT_EQ(ws->request_headers[1], + std::make_pair(std::string("X-Second"), std::string("two"))); + WebSocketDestroyInternal(handle); + EXPECT_EQ(FindWebSocket(handle), nullptr); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); +} + +TEST(WebSocketCommonTest, HandlesShareTheHttpIdSpace) { + int64_t http_before = HttpCreateRequestInternal( + "GET", "http://127.0.0.1:9/before", "", "", kNoRequestContent); + int64_t socket = WebSocketCreateInternal("ws://127.0.0.1:9/ids", "", "", ""); + int64_t http_after = HttpCreateRequestInternal( + "GET", "http://127.0.0.1:9/after", "", "", kNoRequestContent); + EXPECT_EQ(socket, http_before + 1); + EXPECT_EQ(http_after, socket + 1); + EXPECT_EQ(FindOperation(socket), nullptr); + EXPECT_EQ(FindWebSocket(http_before), nullptr); + HttpDestroyRequestInternal(http_before); + HttpDestroyRequestInternal(http_after); + WebSocketDestroyInternal(socket); +} + +TEST(WebSocketCommonTest, PollOpenArmsTheOpenEvent) { + DrainEvents(); + + int64_t opened = WebSocketCreateInternal("ws://127.0.0.1:9/open", "", "", ""); + EXPECT_EQ(WebSocketPollOpenInternal(opened), 0); + ExpectNoEvent(); + FindWebSocket(opened)->MarkOpen("chat.v2"); + ExpectEvent(opened, kHttpEventWebSocketOpen); + EXPECT_EQ(WebSocketPollOpenInternal(opened), 1); + EXPECT_EQ(WebSocketGetStateInternal(opened), kWebSocketOpen); + EXPECT_EQ(WebSocketGetSubprotocolInternal(opened), "chat.v2"); + + int64_t refused = + WebSocketCreateInternal("ws://127.0.0.1:9/refused", "", "", ""); + EXPECT_EQ(WebSocketPollOpenInternal(refused), 0); + FindWebSocket(refused)->MarkFailed("connection refused", kHttpErrorConnect); + ExpectEvent(refused, kHttpEventWebSocketOpen); + EXPECT_EQ(WebSocketPollOpenInternal(refused), -1); + EXPECT_EQ(WebSocketGetStateInternal(refused), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(refused), kHttpErrorConnect); + EXPECT_EQ(WebSocketGetErrorInternal(refused), "connection refused"); + + // Without a poll nothing is armed, so nothing is posted. + int64_t quiet = WebSocketCreateInternal("ws://127.0.0.1:9/quiet", "", "", ""); + FindWebSocket(quiet)->MarkOpen(""); + ExpectNoEvent(); + + WebSocketDestroyInternal(opened); + WebSocketDestroyInternal(refused); + WebSocketDestroyInternal(quiet); +} + +TEST(WebSocketCommonTest, SendCollectsFragmentsIntoOneMessage) { + int64_t connecting = + WebSocketCreateInternal("ws://127.0.0.1:9/early", "", "", ""); + EXPECT_EQ(SendText(connecting, "too early", true), -1); + WebSocketDestroyInternal(connecting); + + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/fragments"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + int notifications = 0; + { + std::lock_guard lock(ws->mutex); + ws->on_outgoing_available = [¬ifications]() { ++notifications; }; + } + + // Nothing is handed to the backend before the last fragment. + EXPECT_EQ(SendText(handle, "he", false), 1); + EXPECT_EQ(notifications, 0); + EXPECT_EQ(ws->PopOutgoing().kind, WebSocketOperation::Outgoing::kNone); + + // The type of the first fragment applies to the whole message. + std::string tail = "llo"; + EXPECT_EQ( + WebSocketTrySendInternal(handle, kWebSocketBinary, tail.data(), 3, true), + 1); + EXPECT_EQ(notifications, 1); + WebSocketOperation::Outgoing first = ws->PopOutgoing(); + ASSERT_EQ(first.kind, WebSocketOperation::Outgoing::kMessage); + EXPECT_EQ(first.message.type, kWebSocketText); + EXPECT_EQ(Text(first.message.data), "hello"); + + // An empty message needs no buffer, and a buffer with length 0 is fine. + char unused = 'u'; + for (void* data : + {static_cast(nullptr), static_cast(&unused)}) { + EXPECT_EQ(WebSocketTrySendInternal(handle, kWebSocketBinary, data, 0, true), + 1); + WebSocketOperation::Outgoing empty = ws->PopOutgoing(); + ASSERT_EQ(empty.kind, WebSocketOperation::Outgoing::kMessage); + EXPECT_EQ(empty.message.type, kWebSocketBinary); + EXPECT_TRUE(empty.message.data.empty()); + } + EXPECT_EQ(notifications, 3); + + // An empty last fragment ends the message. + EXPECT_EQ(SendText(handle, "whole", false), 1); + EXPECT_EQ(WebSocketTrySendInternal(handle, kWebSocketText, &unused, 0, true), + 1); + EXPECT_EQ(notifications, 4); + WebSocketOperation::Outgoing ended = ws->PopOutgoing(); + ASSERT_EQ(ended.kind, WebSocketOperation::Outgoing::kMessage); + EXPECT_EQ(Text(ended.message.data), "whole"); + EXPECT_EQ(ws->PopOutgoing().kind, WebSocketOperation::Outgoing::kNone); + + // Invalid arguments. + char byte = 'x'; + EXPECT_EQ(WebSocketTrySendInternal(handle, 3, &byte, 1, true), -1); + EXPECT_EQ(WebSocketTrySendInternal(handle, kWebSocketText, &byte, -1, true), + -1); + EXPECT_EQ(WebSocketTrySendInternal(handle, kWebSocketText, nullptr, 1, true), + -1); + EXPECT_EQ( + WebSocketTrySendInternal(handle + 1000, kWebSocketText, &byte, 1, true), + -1); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketOpen); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCommonTest, SendQueueBoundArmsTheSendSpaceEvent) { + DrainEvents(); + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/send-bound"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + + // A message being collected is not held back by the bound: with an empty + // queue, fragments beyond 1 MiB are still accepted. + std::vector fragment(700 * 1024, 0x11); + for (bool last : {false, true}) { + EXPECT_EQ( + WebSocketTrySendInternal(handle, kWebSocketBinary, fragment.data(), + static_cast(fragment.size()), last), + 1); + } + + // The queue now holds 1.4 MiB, so the next fragment is refused. + EXPECT_EQ(SendText(handle, "blocked", true), 0); + ExpectNoEvent(); + + WebSocketOperation::Outgoing big = ws->PopOutgoing(); + ASSERT_EQ(big.kind, WebSocketOperation::Outgoing::kMessage); + EXPECT_EQ(big.message.data.size(), 2 * fragment.size()); + ExpectEvent(handle, kHttpEventWebSocketSendSpace); + ExpectNoEvent(); + + EXPECT_EQ(SendText(handle, "accepted", true), 1); + WebSocketOperation::Outgoing small = ws->PopOutgoing(); + ASSERT_EQ(small.kind, WebSocketOperation::Outgoing::kMessage); + EXPECT_EQ(Text(small.message.data), "accepted"); + ExpectNoEvent(); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCommonTest, OversizeSendIsRejectedAndTheSocketStaysOpen) { + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/oversize"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + + // Exactly the limit is accepted; one more byte is not. + std::vector half(kMaxWebSocketMessageBytes / 2, 0x22); + for (int i = 0; i < 2; ++i) { + ASSERT_EQ( + WebSocketTrySendInternal(handle, kWebSocketBinary, half.data(), + static_cast(half.size()), false), + 1); + } + uint8_t extra = 0x33; + EXPECT_EQ(WebSocketTrySendInternal(handle, kWebSocketBinary, &extra, 1, true), + -1); + + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketOpen); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorNone); + + // The rejected message is gone and the next one is unaffected. + EXPECT_EQ(SendText(handle, "next", true), 1); + WebSocketOperation::Outgoing next = ws->PopOutgoing(); + ASSERT_EQ(next.kind, WebSocketOperation::Outgoing::kMessage); + EXPECT_EQ(Text(next.message.data), "next"); + EXPECT_EQ(ws->PopOutgoing().kind, WebSocketOperation::Outgoing::kNone); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCommonTest, ReceiveHandsOutMessagesInPiecesWithFlags) { + DrainEvents(); + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/receive"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + + // Nothing buffered arms the event; the next message posts it once. + std::string got; + EXPECT_EQ(Receive(handle, 8, &got), kWebSocketReceiveWouldBlock); + ExpectNoEvent(); + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketText, Bytes("hello world"))); + ExpectEvent(handle, kHttpEventWebSocketReceive); + EXPECT_FALSE( + ws->PushReceivedMessage(kWebSocketBinary, Bytes("\x01\x02\x03"))); + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketText, {})); + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketBinary, {})); + ExpectNoEvent(); + + // A text message read 4 bytes at a time: the last piece carries bit 0. + EXPECT_EQ(Receive(handle, 4, &got), 4 << 8); + EXPECT_EQ(Receive(handle, 4, &got), 4 << 8); + EXPECT_EQ(Receive(handle, 4, &got), (3 << 8) | kWebSocketReceiveEndOfMessage); + EXPECT_EQ(got, "hello world"); + + // A binary message that fits carries both bits. + std::string binary; + EXPECT_EQ(Receive(handle, 16, &binary), + (3 << 8) | kWebSocketReceiveEndOfMessage | kWebSocketReceiveBinary); + EXPECT_EQ(binary, "\x01\x02\x03"); + + // Empty messages are delivered as zero bytes with the end flag. + std::string none; + EXPECT_EQ(Receive(handle, 16, &none), kWebSocketReceiveEndOfMessage); + EXPECT_EQ(WebSocketTryReceiveInternal(handle, nullptr, 0), + kWebSocketReceiveEndOfMessage | kWebSocketReceiveBinary); + EXPECT_TRUE(none.empty()); + EXPECT_EQ(Receive(handle, 16, &none), kWebSocketReceiveWouldBlock); + + // Invalid arguments. + char byte = 0; + EXPECT_EQ(WebSocketTryReceiveInternal(handle, &byte, -1), + kWebSocketReceiveError); + EXPECT_EQ(WebSocketTryReceiveInternal(handle, nullptr, 1), + kWebSocketReceiveError); + EXPECT_EQ(WebSocketTryReceiveInternal(handle + 1000, &byte, 1), + kWebSocketReceiveError); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCommonTest, ZeroLengthReceivePeeksAtTheHeadMessage) { + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/peek"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + + // Nothing buffered. + EXPECT_EQ(WebSocketTryReceiveInternal(handle, nullptr, 0), + kWebSocketReceiveWouldBlock); + + // A message with content is described but not consumed. + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketBinary, Bytes("abc"))); + char unused = 0; + EXPECT_EQ(WebSocketTryReceiveInternal(handle, nullptr, 0), + kWebSocketReceiveBinary); + EXPECT_EQ(WebSocketTryReceiveInternal(handle, &unused, 0), + kWebSocketReceiveBinary); + std::string got; + EXPECT_EQ(Receive(handle, 8, &got), + (3 << 8) | kWebSocketReceiveEndOfMessage | kWebSocketReceiveBinary); + EXPECT_EQ(got, "abc"); + + // An empty message is consumed, because that is all there is of it. + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketText, {})); + EXPECT_EQ(WebSocketTryReceiveInternal(handle, nullptr, 0), + kWebSocketReceiveEndOfMessage); + EXPECT_EQ(WebSocketTryReceiveInternal(handle, nullptr, 0), + kWebSocketReceiveWouldBlock); + + // Closed by the peer. + ws->MarkPeerClosed(1000, "done"); + EXPECT_EQ(WebSocketTryReceiveInternal(handle, nullptr, 0), + kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), 1000); + EXPECT_EQ(WebSocketGetCloseReasonInternal(handle), "done"); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCommonTest, ReceiveQueueBoundPausesAndResumesTheBackend) { + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/receive-bound"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + int resumes = 0; + { + std::lock_guard lock(ws->mutex); + ws->on_receive_space_available = [&resumes]() { ++resumes; }; + } + + // The fourth 1 MiB message reaches the 4 MiB bound. + const size_t kMessage = 1024 * 1024; + for (int i = 0; i < 3; ++i) { + EXPECT_FALSE(ws->PushReceivedMessage( + kWebSocketBinary, std::vector(kMessage, 0x40 + i))); + } + EXPECT_TRUE(ws->PushReceivedMessage(kWebSocketBinary, + std::vector(kMessage, 0x43))); + + // The backend is resumed once, when the queue is down to 2 MiB. + std::string message; + int64_t whole_message = (static_cast(kMessage) << 8) | + kWebSocketReceiveEndOfMessage | + kWebSocketReceiveBinary; + EXPECT_EQ(Receive(handle, static_cast(kMessage), &message), + whole_message); + EXPECT_EQ(resumes, 0); + EXPECT_EQ(Receive(handle, static_cast(kMessage), &message), + whole_message); + EXPECT_EQ(resumes, 1); + EXPECT_EQ(Receive(handle, static_cast(kMessage), &message), + whole_message); + EXPECT_EQ(Receive(handle, static_cast(kMessage), &message), + whole_message); + EXPECT_EQ(resumes, 1); + ASSERT_EQ(message.size(), 4 * kMessage); + EXPECT_EQ(message.front(), 0x40); + EXPECT_EQ(message.back(), 0x43); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCommonTest, PeerCloseIsReportedAfterQueuedMessages) { + DrainEvents(); + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/peer-close"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + + // An armed reader is told about the message and, armed again, about the + // peer's close. + std::string none; + EXPECT_EQ(Receive(handle, 32, &none), kWebSocketReceiveWouldBlock); + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketText, Bytes("last words"))); + ExpectEvent(handle, kHttpEventWebSocketReceive); + EXPECT_EQ(WebSocketTryReceiveInternal(handle, nullptr, 0), 0); + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), 0); + ws->MarkPeerClosed(4001, "server shutting down"); + ExpectNoEvent(); + // Anything after the peer's Close frame is dropped. + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketText, Bytes("too late"))); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketCloseReceived); + EXPECT_EQ(WebSocketPollOpenInternal(handle), 1); + + std::string got; + EXPECT_EQ(Receive(handle, 32, &got), + (10 << 8) | kWebSocketReceiveEndOfMessage); + EXPECT_EQ(got, "last words"); + // The code and reason are readable as soon as "closed" is returned. + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), 4001); + EXPECT_EQ(WebSocketGetCloseReasonInternal(handle), "server shutting down"); + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveClosed); + + // The reply is sent only when the caller closes. Until the transport is + // gone the socket then reports "nothing buffered" instead of "closed". + EXPECT_EQ(ws->PopOutgoing().kind, WebSocketOperation::Outgoing::kNone); + WebSocketCloseInternal(handle, 1000, "acknowledged"); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketCloseReceived); + WebSocketOperation::Outgoing reply = ws->PopOutgoing(); + ASSERT_EQ(reply.kind, WebSocketOperation::Outgoing::kClose); + EXPECT_EQ(reply.close_code, 1000); + EXPECT_EQ(reply.close_reason, "acknowledged"); + EXPECT_EQ(ws->PopOutgoing().kind, WebSocketOperation::Outgoing::kNone); + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveWouldBlock); + + ws->MarkClosed(); + ExpectEvent(handle, kHttpEventWebSocketReceive); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketClosed); + EXPECT_EQ(WebSocketPollOpenInternal(handle), -1); + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), 4001); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorNone); + WebSocketDestroyInternal(handle); + + // A Close frame without a status code is reported as 1005. A reader that + // is waiting when it arrives gets the receive event. + int64_t no_status = CreateOpenSocket("ws://127.0.0.1:9/no-status"); + EXPECT_EQ(Receive(no_status, 32, &none), kWebSocketReceiveWouldBlock); + FindWebSocket(no_status)->MarkPeerClosed(kWebSocketCloseNoStatus, ""); + ExpectEvent(no_status, kHttpEventWebSocketReceive); + EXPECT_EQ(Receive(no_status, 32, &none), kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetCloseCodeInternal(no_status), 1005); + EXPECT_TRUE(WebSocketGetCloseReasonInternal(no_status).empty()); + WebSocketDestroyInternal(no_status); +} + +TEST(WebSocketCommonTest, LocalCloseFollowsQueuedMessages) { + DrainEvents(); + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/local-close"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + int notifications = 0; + { + std::lock_guard lock(ws->mutex); + ws->on_outgoing_available = [¬ifications]() { ++notifications; }; + } + + EXPECT_EQ(SendText(handle, "queued first", true), 1); + EXPECT_EQ(SendText(handle, "never finished", false), 1); + const std::string long_reason(130, 'r'); + WebSocketCloseInternal(handle, 1001, long_reason.c_str()); + EXPECT_EQ(notifications, 2); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketCloseSent); + EXPECT_EQ(SendText(handle, "after close", true), -1); + + // Closing again changes nothing. + WebSocketCloseInternal(handle, 1002, "second call"); + EXPECT_EQ(notifications, 2); + + // The queued message goes out, then one Close; the unfinished message is + // dropped and the reason is cut to what fits a Close frame. + WebSocketOperation::Outgoing message = ws->PopOutgoing(); + ASSERT_EQ(message.kind, WebSocketOperation::Outgoing::kMessage); + EXPECT_EQ(Text(message.message.data), "queued first"); + WebSocketOperation::Outgoing close = ws->PopOutgoing(); + ASSERT_EQ(close.kind, WebSocketOperation::Outgoing::kClose); + EXPECT_EQ(close.close_code, 1001); + EXPECT_EQ(close.close_reason, + std::string(kMaxWebSocketCloseReasonBytes, 'r')); + EXPECT_EQ(ws->PopOutgoing().kind, WebSocketOperation::Outgoing::kNone); + + // The peer may still send messages before its own Close frame. + std::string got; + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveWouldBlock); + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketText, Bytes("still coming"))); + ExpectEvent(handle, kHttpEventWebSocketReceive); + EXPECT_EQ(Receive(handle, 32, &got), + (12 << 8) | kWebSocketReceiveEndOfMessage); + EXPECT_EQ(got, "still coming"); + + // The peer's Close frame posts the receive event to a waiting reader. + // "Closed" is reported once the transport is gone, with the peer's code. + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveWouldBlock); + ws->MarkPeerClosed(1000, "peer reason"); + ExpectEvent(handle, kHttpEventWebSocketReceive); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketCloseSent); + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveWouldBlock); + ws->MarkClosed(); + ExpectEvent(handle, kHttpEventWebSocketReceive); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketClosed); + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), 1000); + EXPECT_EQ(WebSocketGetCloseReasonInternal(handle), "peer reason"); + WebSocketDestroyInternal(handle); + + // Code 0 asks for a Close frame without a status code. + int64_t bare = CreateOpenSocket("ws://127.0.0.1:9/bare-close"); + WebSocketCloseInternal(bare, 0, nullptr); + WebSocketOperation::Outgoing bare_close = FindWebSocket(bare)->PopOutgoing(); + ASSERT_EQ(bare_close.kind, WebSocketOperation::Outgoing::kClose); + EXPECT_EQ(bare_close.close_code, 0); + EXPECT_TRUE(bare_close.close_reason.empty()); + WebSocketDestroyInternal(bare); +} + +TEST(WebSocketCommonTest, FailureAfterLocalCloseWakesTheReader) { + DrainEvents(); + std::string got; + + // The transport fails before the peer answers the Close. + int64_t unanswered = CreateOpenSocket("ws://127.0.0.1:9/close-unanswered"); + WebSocketCloseInternal(unanswered, 1000, "bye"); + EXPECT_EQ(Receive(unanswered, 32, &got), kWebSocketReceiveWouldBlock); + FindWebSocket(unanswered)->MarkFailed("connection reset", kHttpErrorConnect); + ExpectEvent(unanswered, kHttpEventWebSocketReceive); + EXPECT_EQ(Receive(unanswered, 32, &got), kWebSocketReceiveError); + EXPECT_EQ(WebSocketGetStateInternal(unanswered), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(unanswered), kHttpErrorConnect); + WebSocketDestroyInternal(unanswered); + + // The transport fails after the peer's Close frame, with the reader armed + // again in between. + int64_t answered = CreateOpenSocket("ws://127.0.0.1:9/close-answered"); + auto ws = FindWebSocket(answered); + ASSERT_NE(ws, nullptr); + WebSocketCloseInternal(answered, 1001, "leaving"); + EXPECT_EQ(Receive(answered, 32, &got), kWebSocketReceiveWouldBlock); + ws->MarkPeerClosed(1011, "peer error"); + ExpectEvent(answered, kHttpEventWebSocketReceive); + EXPECT_EQ(Receive(answered, 32, &got), kWebSocketReceiveWouldBlock); + ws->MarkFailed("timed out", kHttpErrorTimeout); + ExpectEvent(answered, kHttpEventWebSocketReceive); + EXPECT_EQ(Receive(answered, 32, &got), kWebSocketReceiveError); + EXPECT_EQ(WebSocketGetStateInternal(answered), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(answered), kHttpErrorTimeout); + ExpectNoEvent(); + WebSocketDestroyInternal(answered); +} + +TEST(WebSocketCommonTest, FailureDropsQueuedMessages) { + DrainEvents(); + int64_t handle = CreateOpenSocket("ws://127.0.0.1:9/failure"); + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + + EXPECT_FALSE(ws->PushReceivedMessage(kWebSocketText, Bytes("unread"))); + EXPECT_EQ(SendText(handle, "unsent", true), 1); + ws->MarkFailed("connection reset", kHttpErrorConnect); + + // The state changes at once and the unread message is gone. + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + std::string got; + EXPECT_EQ(Receive(handle, 32, &got), kWebSocketReceiveError); + EXPECT_TRUE(got.empty()); + EXPECT_EQ(SendText(handle, "after failure", true), -1); + EXPECT_EQ(ws->PopOutgoing().kind, WebSocketOperation::Outgoing::kNone); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorConnect); + EXPECT_EQ(WebSocketGetErrorInternal(handle), "connection reset"); + + // Later reports from the backend do not change the outcome. + ws->MarkClosed(); + ws->MarkFailed("second failure", kHttpErrorTimeout); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorInternal(handle), "connection reset"); + ExpectNoEvent(); + WebSocketDestroyInternal(handle); + + // A failure wakes a blocked reader and a blocked writer. + int64_t blocked = CreateOpenSocket("ws://127.0.0.1:9/failure-blocked"); + EXPECT_EQ(Receive(blocked, 32, &got), kWebSocketReceiveWouldBlock); + std::vector filler(kMaxWebSocketSendQueueBytes, 0x66); + EXPECT_EQ(WebSocketTrySendInternal(blocked, kWebSocketBinary, filler.data(), + static_cast(filler.size()), true), + 1); + EXPECT_EQ(SendText(blocked, "blocked", true), 0); + FindWebSocket(blocked)->MarkFailed("timed out", kHttpErrorTimeout); + ExpectEvent(blocked, kHttpEventWebSocketReceive); + ExpectEvent(blocked, kHttpEventWebSocketSendSpace); + ExpectNoEvent(); + EXPECT_EQ(SendText(blocked, "after failure", true), -1); + EXPECT_EQ(WebSocketGetErrorClassInternal(blocked), kHttpErrorTimeout); + WebSocketDestroyInternal(blocked); +} + +TEST(WebSocketCommonTest, DestroyDropsTheTransportAndIsSafeWhenClosed) { + DrainEvents(); + + // Destroying an open socket cancels it: the backend is told to drop the + // connection, even with a Close frame still queued. + int64_t open = CreateOpenSocket("ws://127.0.0.1:9/destroy-open"); + auto open_ws = FindWebSocket(open); + ASSERT_NE(open_ws, nullptr); + int cancels = 0; + { + std::lock_guard lock(open_ws->mutex); + open_ws->on_cancel = [&cancels]() { ++cancels; }; + } + WebSocketCloseInternal(open, 1000, "queued, never sent"); + WebSocketDestroyInternal(open); + EXPECT_EQ(cancels, 1); + EXPECT_EQ(FindWebSocket(open), nullptr); + EXPECT_EQ(open_ws->PopOutgoing().kind, WebSocketOperation::Outgoing::kNone); + { + std::lock_guard lock(open_ws->mutex); + EXPECT_EQ(open_ws->state, kWebSocketAborted); + } + + // Cancel and destroy on a closed socket leave it closed. + int64_t closed = CreateOpenSocket("ws://127.0.0.1:9/destroy-closed"); + auto closed_ws = FindWebSocket(closed); + ASSERT_NE(closed_ws, nullptr); + closed_ws->MarkPeerClosed(1000, "bye"); + closed_ws->MarkClosed(); + WebSocketCancelInternal(closed); + EXPECT_EQ(WebSocketGetStateInternal(closed), kWebSocketClosed); + EXPECT_EQ(WebSocketGetErrorClassInternal(closed), kHttpErrorNone); + WebSocketDestroyInternal(closed); + WebSocketDestroyInternal(closed); + { + std::lock_guard lock(closed_ws->mutex); + EXPECT_EQ(closed_ws->state, kWebSocketClosed); + } + ExpectNoEvent(); +} + +TEST(WebSocketCommonTest, CancelWakesEveryWaiter) { + DrainEvents(); + + // A connecting socket waiting to open. + int64_t connecting = + WebSocketCreateInternal("ws://127.0.0.1:9/cancel-connecting", "", "", ""); + EXPECT_EQ(WebSocketPollOpenInternal(connecting), 0); + WebSocketCancelInternal(connecting); + ExpectEvent(connecting, kHttpEventWebSocketOpen); + EXPECT_EQ(WebSocketPollOpenInternal(connecting), -1); + EXPECT_EQ(WebSocketGetStateInternal(connecting), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(connecting), kHttpErrorCanceled); + + // An open socket with a blocked reader and a blocked writer. + int64_t open = CreateOpenSocket("ws://127.0.0.1:9/cancel-open"); + auto ws = FindWebSocket(open); + ASSERT_NE(ws, nullptr); + int cancels = 0; + { + std::lock_guard lock(ws->mutex); + ws->on_cancel = [&cancels]() { ++cancels; }; + } + std::string got; + EXPECT_EQ(Receive(open, 8, &got), kWebSocketReceiveWouldBlock); + std::vector filler(kMaxWebSocketSendQueueBytes, 0x55); + EXPECT_EQ(WebSocketTrySendInternal(open, kWebSocketBinary, filler.data(), + static_cast(filler.size()), true), + 1); + EXPECT_EQ(SendText(open, "blocked", true), 0); + ExpectNoEvent(); + + WebSocketCancelInternal(open); + EXPECT_EQ(cancels, 1); + ExpectEvent(open, kHttpEventWebSocketReceive); + ExpectEvent(open, kHttpEventWebSocketSendSpace); + ExpectNoEvent(); + EXPECT_EQ(Receive(open, 8, &got), kWebSocketReceiveError); + EXPECT_EQ(SendText(open, "after cancel", true), -1); + EXPECT_EQ(WebSocketGetStateInternal(open), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(open), kHttpErrorCanceled); + + // Canceling again, or a late report from the backend, changes nothing. + WebSocketCancelInternal(open); + ws->MarkFailed("late failure", kHttpErrorConnect); + EXPECT_EQ(cancels, 1); + EXPECT_EQ(WebSocketGetErrorClassInternal(open), kHttpErrorCanceled); + + // Closing a socket that never opened cancels it. + int64_t closed_early = + WebSocketCreateInternal("ws://127.0.0.1:9/close-early", "", "", ""); + WebSocketCloseInternal(closed_early, 1000, "never opened"); + EXPECT_EQ(WebSocketGetStateInternal(closed_early), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(closed_early), kHttpErrorCanceled); + + WebSocketDestroyInternal(connecting); + WebSocketDestroyInternal(open); + WebSocketDestroyInternal(closed_early); +} + +TEST(WebSocketCommonTest, CancelAllRequestsAbortsWebSockets) { + DrainEvents(); + int64_t connecting = + WebSocketCreateInternal("ws://127.0.0.1:9/all-connecting", "", "", ""); + int64_t open = CreateOpenSocket("ws://127.0.0.1:9/all-open"); + auto connecting_ws = FindWebSocket(connecting); + auto open_ws = FindWebSocket(open); + ASSERT_NE(connecting_ws, nullptr); + ASSERT_NE(open_ws, nullptr); + std::string got; + EXPECT_EQ(Receive(open, 8, &got), kWebSocketReceiveWouldBlock); + + HttpCancelAllRequestsInternal(); + + EXPECT_EQ(FindWebSocket(connecting), nullptr); + EXPECT_EQ(FindWebSocket(open), nullptr); + for (const auto& ws : {connecting_ws, open_ws}) { + std::lock_guard lock(ws->mutex); + EXPECT_EQ(ws->state, kWebSocketAborted); + EXPECT_EQ(ws->error_class, kHttpErrorCanceled); + } + // The armed reader is told, then the pump wake-up reports "no event". + ExpectEvent(open, kHttpEventWebSocketReceive); + ExpectNoEvent(); +} + +TEST(WebSocketCommonTest, KeepaliveIntervalDefaultsTo45Seconds) { + EXPECT_EQ(WebSocketKeepaliveInterval(), std::chrono::seconds(45)); + SetWebSocketKeepaliveIntervalForTesting(std::chrono::milliseconds(70)); + EXPECT_EQ(WebSocketKeepaliveInterval(), std::chrono::milliseconds(70)); + SetWebSocketKeepaliveIntervalForTesting( + std::chrono::seconds(kWebSocketKeepaliveSeconds)); +} + +} // namespace +} // namespace http +} // namespace firebase diff --git a/app/http/tests/websocket_curl_test.cc b/app/http/tests/websocket_curl_test.cc new file mode 100644 index 0000000000..47f9049886 --- /dev/null +++ b/app/http/tests/websocket_curl_test.cc @@ -0,0 +1,1402 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Tests of the libcurl WebSocket backend against a small RFC 6455 server on +// the loopback interface. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include +#include +using SocketFd = SOCKET; +constexpr SocketFd kInvalidSocket = INVALID_SOCKET; +#else +#include +#include +#include +#include +#include +#include +#include +using SocketFd = int; +constexpr SocketFd kInvalidSocket = -1; +#endif + +#include "app/http/websocket.h" +#include "app/src/base64.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace http { +namespace { + +// ---- Sockets --------------------------------------------------------------- + +void EnsureSocketSubsystemInitialized() { +#if defined(_WIN32) + static std::once_flag wsa_once; + std::call_once(wsa_once, []() { + WSADATA data{}; + WSAStartup(MAKEWORD(2, 2), &data); + }); +#else + static std::once_flag sigpipe_once; + std::call_once(sigpipe_once, []() { std::signal(SIGPIPE, SIG_IGN); }); +#endif +} + +void CloseSocket(SocketFd fd) { +#if defined(_WIN32) + closesocket(fd); +#else + close(fd); +#endif +} + +bool WaitForSocket(SocketFd fd, bool for_write, int timeout_ms) { + fd_set fds; + FD_ZERO(&fds); + FD_SET(fd, &fds); + timeval tv{}; + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; +#if defined(_WIN32) + int nfds = 0; +#else + int nfds = fd + 1; +#endif + return select(nfds, for_write ? nullptr : &fds, for_write ? &fds : nullptr, + nullptr, &tv) > 0; +} + +void SetNonBlocking(SocketFd fd) { +#if defined(_WIN32) + u_long enabled = 1; + ioctlsocket(fd, FIONBIO, &enabled); +#else + fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK); +#endif +} + +#if !defined(_WIN32) && defined(MSG_NOSIGNAL) +constexpr int kSendFlags = MSG_NOSIGNAL; +#else +constexpr int kSendFlags = 0; +#endif + +// Sends what a non-blocking socket accepts right now. Returns the number of +// bytes sent, 0 if the socket buffer is full, or -1 on any other error. +int SendSome(SocketFd fd, const char* data, size_t len) { +#if defined(_WIN32) + int n = send(fd, data, static_cast(len), 0); + if (n < 0) { + return WSAGetLastError() == WSAEWOULDBLOCK ? 0 : -1; + } + return n; +#else + ssize_t n = send(fd, data, len, kSendFlags); + if (n < 0) { + return (errno == EAGAIN || errno == EWOULDBLOCK) ? 0 : -1; + } + return static_cast(n); +#endif +} + +bool SendAll(SocketFd fd, std::string_view bytes) { + size_t sent = 0; + while (sent < bytes.size()) { +#if defined(_WIN32) + int n = + send(fd, bytes.data() + sent, static_cast(bytes.size() - sent), 0); +#else + ssize_t n = send(fd, bytes.data() + sent, bytes.size() - sent, kSendFlags); +#endif + if (n <= 0) { + return false; + } + sent += static_cast(n); + } + return true; +} + +// Returns a loopback port that nothing listens on. +int ClosedLoopbackPort() { + EnsureSocketSubsystemInitialized(); + SocketFd probe = socket(AF_INET, SOCK_STREAM, 0); + EXPECT_NE(probe, kInvalidSocket); + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; + EXPECT_EQ(bind(probe, reinterpret_cast(&addr), sizeof(addr)), 0); + sockaddr_in bound{}; +#if defined(_WIN32) + int bound_len = sizeof(bound); +#else + socklen_t bound_len = sizeof(bound); +#endif + EXPECT_EQ(getsockname(probe, reinterpret_cast(&bound), &bound_len), + 0); + CloseSocket(probe); + return ntohs(bound.sin_port); +} + +// ---- RFC 6455 server side -------------------------------------------------- + +std::string Sha1(std::string_view input) { + uint32_t h[5] = {0x67452301u, 0xEFCDAB89u, 0x98BADCFEu, 0x10325476u, + 0xC3D2E1F0u}; + std::string message(input); + const uint64_t bit_length = static_cast(message.size()) * 8; + message.push_back('\x80'); + while (message.size() % 64 != 56) { + message.push_back('\0'); + } + for (int shift = 56; shift >= 0; shift -= 8) { + message.push_back(static_cast((bit_length >> shift) & 0xFF)); + } + auto rotl = [](uint32_t value, int bits) { + return (value << bits) | (value >> (32 - bits)); + }; + for (size_t block = 0; block < message.size(); block += 64) { + uint32_t w[80]; + for (int i = 0; i < 16; ++i) { + const auto* p = + reinterpret_cast(message.data()) + block + i * 4; + w[i] = (static_cast(p[0]) << 24) | + (static_cast(p[1]) << 16) | + (static_cast(p[2]) << 8) | p[3]; + } + for (int i = 16; i < 80; ++i) { + w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1); + } + uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4]; + for (int i = 0; i < 80; ++i) { + uint32_t f = 0; + uint32_t k = 0; + if (i < 20) { + f = (b & c) | (~b & d); + k = 0x5A827999u; + } else if (i < 40) { + f = b ^ c ^ d; + k = 0x6ED9EBA1u; + } else if (i < 60) { + f = (b & c) | (b & d) | (c & d); + k = 0x8F1BBCDCu; + } else { + f = b ^ c ^ d; + k = 0xCA62C1D6u; + } + uint32_t next = rotl(a, 5) + f + e + k + w[i]; + e = d; + d = c; + c = rotl(b, 30); + b = a; + a = next; + } + h[0] += a; + h[1] += b; + h[2] += c; + h[3] += d; + h[4] += e; + } + std::string digest; + for (uint32_t word : h) { + for (int shift = 24; shift >= 0; shift -= 8) { + digest.push_back(static_cast((word >> shift) & 0xFF)); + } + } + return digest; +} + +// The Sec-WebSocket-Accept value for a Sec-WebSocket-Key. +std::string AcceptKey(std::string_view key) { + std::string accept; + firebase::internal::Base64EncodeWithPadding( + Sha1(std::string(key) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"), &accept); + return accept; +} + +constexpr uint8_t kOpContinuation = 0x0; +constexpr uint8_t kOpText = 0x1; +constexpr uint8_t kOpBinary = 0x2; +constexpr uint8_t kOpClose = 0x8; +constexpr uint8_t kOpPing = 0x9; +constexpr uint8_t kOpPong = 0xA; + +struct Frame { + uint8_t opcode = 0; + bool fin = true; + bool masked = false; + std::string payload; + + // Status code and reason of a Close frame. + int CloseCode() const { + if (payload.size() < 2) { + return 0; + } + return (static_cast(payload[0]) << 8) | + static_cast(payload[1]); + } + std::string CloseReason() const { + return payload.size() > 2 ? payload.substr(2) : std::string(); + } +}; + +// Header of an unmasked (server to client) frame. +std::string FrameHeader(uint8_t opcode, uint64_t payload_length, bool fin) { + std::string header; + header.push_back(static_cast((fin ? 0x80 : 0x00) | opcode)); + if (payload_length < 126) { + header.push_back(static_cast(payload_length)); + } else if (payload_length <= 0xFFFF) { + header.push_back(126); + header.push_back(static_cast((payload_length >> 8) & 0xFF)); + header.push_back(static_cast(payload_length & 0xFF)); + } else { + header.push_back(127); + for (int shift = 56; shift >= 0; shift -= 8) { + header.push_back(static_cast((payload_length >> shift) & 0xFF)); + } + } + return header; +} + +std::string ClosePayload(int code, std::string_view reason) { + std::string payload; + payload.push_back(static_cast((code >> 8) & 0xFF)); + payload.push_back(static_cast(code & 0xFF)); + payload.append(reason); + return payload; +} + +// The server end of one accepted connection. +class ServerConnection { + public: + explicit ServerConnection(SocketFd fd) : fd_(fd) {} + + SocketFd fd() const { return fd_; } + const std::string& request_line() const { return request_line_; } + + std::string Header(std::string_view name) const { + for (const auto& kv : headers_) { + if (AsciiEqualsIgnoreCase(kv.first, name)) { + return kv.second; + } + } + return {}; + } + + // Reads the opening request up to the blank line. + bool ReadRequest() { + std::string head; + while (head.find("\r\n\r\n") == std::string::npos) { + char byte = 0; + if (!ReadExact(&byte, 1)) { + return false; + } + head.push_back(byte); + } + size_t pos = head.find("\r\n"); + request_line_ = head.substr(0, pos); + pos += 2; + while (pos < head.size()) { + size_t end = head.find("\r\n", pos); + std::string_view line = std::string_view(head).substr(pos, end - pos); + pos = end + 2; + size_t colon = line.find(':'); + if (colon != std::string_view::npos) { + headers_.emplace_back( + std::string(TrimAsciiWhitespace(line.substr(0, colon))), + std::string(TrimAsciiWhitespace(line.substr(colon + 1)))); + } + } + return true; + } + + // Answers the request read by `ReadRequest` with 101 Switching Protocols. + bool Accept(std::string_view subprotocol = {}) { + std::string response = + "HTTP/1.1 101 Switching Protocols\r\n" + "Upgrade: websocket\r\n" + "Connection: Upgrade\r\n" + "Sec-WebSocket-Accept: " + + AcceptKey(Header("Sec-WebSocket-Key")) + "\r\n"; + if (!subprotocol.empty()) { + response += + "Sec-WebSocket-Protocol: " + std::string(subprotocol) + "\r\n"; + } + response += "\r\n"; + return SendAll(fd_, response); + } + + bool ReadRequestAndAccept() { return ReadRequest() && Accept(); } + + bool SendFrame(uint8_t opcode, std::string_view payload, bool fin = true) { + return SendAll( + fd_, FrameHeader(opcode, payload.size(), fin) + std::string(payload)); + } + + bool SendClose(int code, std::string_view reason) { + return SendFrame(kOpClose, ClosePayload(code, reason)); + } + + // Reads one frame from the client. Returns nullopt when the connection + // ended or nothing arrived in time. + std::optional ReadFrame(int timeout_ms = 5000) { + uint8_t head[2]; + if (!ReadExact(reinterpret_cast(head), 2, timeout_ms)) { + return std::nullopt; + } + Frame frame; + frame.fin = (head[0] & 0x80) != 0; + frame.opcode = head[0] & 0x0F; + frame.masked = (head[1] & 0x80) != 0; + uint64_t length = head[1] & 0x7F; + if (length >= 126) { + uint8_t extended[8]; + size_t extended_size = length == 126 ? 2 : 8; + if (!ReadExact(reinterpret_cast(extended), extended_size, + timeout_ms)) { + return std::nullopt; + } + length = 0; + for (size_t i = 0; i < extended_size; ++i) { + length = (length << 8) | extended[i]; + } + } + uint8_t mask[4] = {}; + if (frame.masked && + !ReadExact(reinterpret_cast(mask), 4, timeout_ms)) { + return std::nullopt; + } + frame.payload.resize(static_cast(length)); + if (length > 0 && + !ReadExact(frame.payload.data(), frame.payload.size(), timeout_ms)) { + return std::nullopt; + } + if (frame.masked) { + for (size_t i = 0; i < frame.payload.size(); ++i) { + frame.payload[i] = static_cast( + static_cast(frame.payload[i]) ^ mask[i % 4]); + } + } + return frame; + } + + // Discards input until the client closes the connection. + bool WaitForPeerClose(int timeout_ms) { + auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(timeout_ms); + char drain[4096]; + while (true) { + auto remaining = std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()); + if (remaining.count() <= 0 || + !WaitForSocket(fd_, /*for_write=*/false, + static_cast(remaining.count()))) { + return false; + } + auto n = recv(fd_, drain, sizeof(drain), 0); + if (n == 0) { + return true; + } + if (n < 0) { +#if defined(_WIN32) + if (WSAGetLastError() == WSAEWOULDBLOCK) continue; +#else + if (errno == EAGAIN || errno == EWOULDBLOCK) continue; +#endif + return true; // Reset by the client. + } + } + } + + private: + bool ReadExact(char* dest, size_t size, int timeout_ms = 5000) { + size_t got = 0; + while (got < size) { + if (!WaitForSocket(fd_, /*for_write=*/false, timeout_ms)) { + return false; + } +#if defined(_WIN32) + int n = recv(fd_, dest + got, static_cast(size - got), 0); +#else + ssize_t n = recv(fd_, dest + got, size - got, 0); +#endif + if (n <= 0) { + return false; + } + got += static_cast(n); + } + return true; + } + + SocketFd fd_; + std::string request_line_; + std::vector> headers_; +}; + +// Answers data frames with the same frame, pings with pongs, and a Close with +// the same Close, after which it closes the connection. +void ServeEcho(ServerConnection& connection) { + while (auto frame = connection.ReadFrame()) { + switch (frame->opcode) { + case kOpText: + case kOpBinary: + connection.SendFrame(frame->opcode, frame->payload); + break; + case kOpPing: + connection.SendFrame(kOpPong, frame->payload); + break; + case kOpClose: + connection.SendFrame(kOpClose, frame->payload); + return; + default: + break; + } + } +} + +// Listens on a loopback port and runs `handler` for each connection on its own +// thread. The connection is closed when the handler returns. +class WebSocketTestServer { + public: + using Handler = std::function; + + explicit WebSocketTestServer(Handler handler) : handler_(std::move(handler)) { + EnsureSocketSubsystemInitialized(); + listen_fd_ = socket(AF_INET, SOCK_STREAM, 0); + EXPECT_NE(listen_fd_, kInvalidSocket); + int reuse = 1; + setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, + reinterpret_cast(&reuse), sizeof(reuse)); + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; + EXPECT_EQ( + bind(listen_fd_, reinterpret_cast(&addr), sizeof(addr)), 0); + EXPECT_EQ(listen(listen_fd_, 64), 0); + sockaddr_in bound{}; +#if defined(_WIN32) + int bound_len = sizeof(bound); +#else + socklen_t bound_len = sizeof(bound); +#endif + EXPECT_EQ(getsockname(listen_fd_, reinterpret_cast(&bound), + &bound_len), + 0); + port_ = ntohs(bound.sin_port); + accept_thread_ = std::thread([this]() { AcceptLoop(); }); + } + + ~WebSocketTestServer() { + stopped_.store(true); + accept_thread_.join(); + CloseSocket(listen_fd_); + for (auto& worker : workers_) { + worker.join(); + } + } + + int port() const { return port_; } + + std::string Url(std::string_view path) const { + return "ws://127.0.0.1:" + std::to_string(port_) + std::string(path); + } + + private: + void AcceptLoop() { + while (!stopped_.load()) { + if (!WaitForSocket(listen_fd_, /*for_write=*/false, 20)) { + continue; + } + SocketFd client = accept(listen_fd_, nullptr, nullptr); + if (client == kInvalidSocket) { + continue; + } + int nodelay = 1; + setsockopt(client, IPPROTO_TCP, TCP_NODELAY, + reinterpret_cast(&nodelay), sizeof(nodelay)); +#ifdef SO_NOSIGPIPE + int nosigpipe = 1; + setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, + reinterpret_cast(&nosigpipe), sizeof(nosigpipe)); +#endif + workers_.emplace_back([this, client]() { + ServerConnection connection(client); + handler_(connection); + CloseSocket(client); + }); + } + } + + Handler handler_; + SocketFd listen_fd_ = kInvalidSocket; + int port_ = 0; + std::atomic stopped_{false}; + std::thread accept_thread_; + // Only the accept thread adds workers; the destructor reads them after + // joining it. + std::vector workers_; +}; + +// Hands values from a server thread to the test thread. +template +class Mailbox { + public: + void Put(T value) { + { + std::lock_guard lock(mutex_); + values_.push_back(std::move(value)); + } + cv_.notify_all(); + } + + // Returns the next value, or nullopt if none arrives in time. + std::optional Take(int timeout_ms = 5000) { + std::unique_lock lock(mutex_); + if (!cv_.wait_for(lock, std::chrono::milliseconds(timeout_ms), + [this]() { return !values_.empty(); })) { + return std::nullopt; + } + T value = std::move(values_.front()); + values_.pop_front(); + return value; + } + + private: + std::mutex mutex_; + std::condition_variable cv_; + std::deque values_; +}; + +// ---- Client side ----------------------------------------------------------- + +// Waits for specific events with blocking `HttpWaitNextEventInternal` calls, +// keeping events of other handles for later. +class BlockingEventDemux { + public: + void DrainStale() { + buffered_.clear(); + while (HttpWaitNextEventInternal(0) != 0) { + } + } + + bool WaitFor(int64_t handle, HttpEventKind kind, int timeout_ms) { + auto& queue = buffered_[handle]; + for (auto it = queue.begin(); it != queue.end(); ++it) { + if (*it == kind) { + queue.erase(it); + return true; + } + } + auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(timeout_ms); + while (true) { + auto remaining = std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()); + if (remaining.count() <= 0) { + return false; + } + int64_t event = + HttpWaitNextEventInternal(static_cast(remaining.count())); + if (event == 0) { + return false; + } + int64_t event_handle = event >> 8; + auto event_kind = static_cast(event & 0xFF); + if (event_handle == handle && event_kind == kind) { + return true; + } + buffered_[event_handle].push_back(event_kind); + } + } + + private: + std::unordered_map> buffered_; +}; + +int64_t Connect(const std::string& url, const char* headers = "", + const char* subprotocols = "") { + int64_t handle = + WebSocketCreateInternal(url.c_str(), headers, subprotocols, ""); + WebSocketConnectInternal(handle); + return handle; +} + +// Returns true once the socket is open, false if it failed or timed out. +bool WaitOpen(BlockingEventDemux* demux, int64_t handle, + int timeout_ms = 5000) { + while (true) { + int32_t result = WebSocketPollOpenInternal(handle); + if (result != 0) { + return result == 1; + } + if (!demux->WaitFor(handle, kHttpEventWebSocketOpen, timeout_ms)) { + ADD_FAILURE() << "Timed out waiting for the socket to open"; + return false; + } + } +} + +// Sends one message in fragments of at most `fragment_size` bytes. +bool SendMessage(BlockingEventDemux* demux, int64_t handle, + WebSocketMessageType type, std::string_view data, + size_t fragment_size = static_cast(-1)) { + size_t offset = 0; + do { + size_t n = (std::min)(fragment_size, data.size() - offset); + bool last = offset + n == data.size(); + int32_t result = WebSocketTrySendInternal( + handle, type, const_cast(data.data()) + offset, + static_cast(n), last); + if (result < 0) { + return false; + } + if (result == 0) { + if (!demux->WaitFor(handle, kHttpEventWebSocketSendSpace, 5000)) { + ADD_FAILURE() << "Timed out waiting for send space"; + return false; + } + continue; + } + offset += n; + } while (offset < data.size()); + return true; +} + +// `status` of `Received` when nothing arrived in time. +constexpr int64_t kReceiveTimedOut = 1; + +struct Received { + // 0 for a message, a negative `WebSocketTryReceiveInternal` result, or + // `kReceiveTimedOut`. + int64_t status = 0; + WebSocketMessageType type = kWebSocketText; + std::string data; +}; + +// Receives one whole message, or the reason there is none. +Received ReceiveMessage(BlockingEventDemux* demux, int64_t handle, + int timeout_ms = 5000) { + Received received; + std::vector buffer(64 * 1024); + while (true) { + int64_t result = WebSocketTryReceiveInternal( + handle, buffer.data(), static_cast(buffer.size())); + if (result >= 0) { + received.data.append(buffer.data(), static_cast(result >> 8)); + received.type = (result & kWebSocketReceiveBinary) ? kWebSocketBinary + : kWebSocketText; + if (result & kWebSocketReceiveEndOfMessage) { + return received; + } + continue; + } + if (result != kWebSocketReceiveWouldBlock) { + received.status = result; + return received; + } + if (!demux->WaitFor(handle, kHttpEventWebSocketReceive, timeout_ms)) { + received.status = kReceiveTimedOut; + return received; + } + } +} + +// Deterministic byte for `offset`; exposes dropped, duplicated, or reordered +// data. +uint8_t PatternByte(size_t offset) { + return static_cast((static_cast(offset) * 2654435761u) >> + 24); +} + +std::string PatternBytes(size_t offset, size_t size) { + std::string bytes(size, '\0'); + for (size_t i = 0; i < size; ++i) { + bytes[i] = static_cast(PatternByte(offset + i)); + } + return bytes; +} + +// ---- Tests ----------------------------------------------------------------- + +TEST(WebSocketCurlTest, TestServerComputesTheRfc6455AcceptKey) { + // The example of RFC 6455 section 1.3. + EXPECT_EQ(AcceptKey("dGhlIHNhbXBsZSBub25jZQ=="), + "s3pPLMBiTxaQ9kYGzzhZRbK+xOo="); +} + +TEST(WebSocketCurlTest, TextAndBinaryEcho) { + BlockingEventDemux demux; + demux.DrainStale(); + + struct Request { + std::string line; + std::string upgrade; + std::string version; + std::string custom; + }; + Mailbox requests; + Mailbox frames_masked; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequest()) { + return; + } + requests.Put({connection.request_line(), connection.Header("Upgrade"), + connection.Header("Sec-WebSocket-Version"), + connection.Header("X-Test-Header")}); + connection.Accept(); + while (auto frame = connection.ReadFrame()) { + frames_masked.Put(frame->masked); + connection.SendFrame(frame->opcode, frame->payload); + if (frame->opcode == kOpClose) { + return; + } + } + }); + + int64_t handle = Connect(server.Url("/echo"), "X-Test-Header\tfirebase-ws\n"); + ASSERT_TRUE(WaitOpen(&demux, handle)); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketOpen); + EXPECT_TRUE(WebSocketGetSubprotocolInternal(handle).empty()); + + auto request = requests.Take(); + ASSERT_TRUE(request.has_value()); + EXPECT_EQ(request->line, "GET /echo HTTP/1.1"); + EXPECT_TRUE(AsciiEqualsIgnoreCase(request->upgrade, "websocket")); + EXPECT_EQ(request->version, "13"); + EXPECT_EQ(request->custom, "firebase-ws"); + + ASSERT_TRUE(SendMessage(&demux, handle, kWebSocketText, "hello websocket")); + Received text = ReceiveMessage(&demux, handle); + EXPECT_EQ(text.status, 0); + EXPECT_EQ(text.type, kWebSocketText); + EXPECT_EQ(text.data, "hello websocket"); + + const std::string binary_payload("\x00\x01\xfe\xff", 4); + ASSERT_TRUE(SendMessage(&demux, handle, kWebSocketBinary, binary_payload)); + Received binary = ReceiveMessage(&demux, handle); + EXPECT_EQ(binary.status, 0); + EXPECT_EQ(binary.type, kWebSocketBinary); + EXPECT_EQ(binary.data, binary_payload); + + // An empty message survives the round trip. + ASSERT_TRUE(SendMessage(&demux, handle, kWebSocketText, "")); + Received empty = ReceiveMessage(&demux, handle); + EXPECT_EQ(empty.status, 0); + EXPECT_EQ(empty.type, kWebSocketText); + EXPECT_TRUE(empty.data.empty()); + + // Every frame a client sends is masked. + for (int i = 0; i < 3; ++i) { + EXPECT_EQ(frames_masked.Take(), std::optional(true)); + } + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, FragmentedServerMessageArrivesAsOne) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox client_frames; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + // Three fragments with a ping between them. + connection.SendFrame(kOpText, "one-", /*fin=*/false); + connection.SendFrame(kOpPing, "between fragments"); + connection.SendFrame(kOpContinuation, "two-", /*fin=*/false); + connection.SendFrame(kOpContinuation, "three", /*fin=*/true); + if (auto frame = connection.ReadFrame()) { + client_frames.Put(*frame); + } + connection.WaitForPeerClose(5000); + }); + + int64_t handle = Connect(server.Url("/fragments")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + Received message = ReceiveMessage(&demux, handle); + EXPECT_EQ(message.status, 0); + EXPECT_EQ(message.type, kWebSocketText); + EXPECT_EQ(message.data, "one-two-three"); + + auto pong = client_frames.Take(); + ASSERT_TRUE(pong.has_value()); + EXPECT_EQ(pong->opcode, kOpPong); + EXPECT_EQ(pong->payload, "between fragments"); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, OneMebibyteEchoArrivesIntact) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox frame_sizes; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + while (auto frame = connection.ReadFrame()) { + frame_sizes.Put(frame->payload.size()); + connection.SendFrame(frame->opcode, frame->payload); + } + }); + + const size_t kSize = 1024 * 1024; + const std::string payload = PatternBytes(0, kSize); + int64_t handle = Connect(server.Url("/large")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + // Written in 100000-byte fragments, sent as one message. + ASSERT_TRUE(SendMessage(&demux, handle, kWebSocketBinary, payload, 100000)); + EXPECT_EQ(frame_sizes.Take(), std::optional(kSize)); + + Received echo = ReceiveMessage(&demux, handle, 15000); + EXPECT_EQ(echo.status, 0); + EXPECT_EQ(echo.type, kWebSocketBinary); + ASSERT_EQ(echo.data.size(), kSize); + EXPECT_TRUE(echo.data == payload); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, ServerMessageOver16MiBClosesWith1009) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox close_codes; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + // Announce one byte more than the limit and start sending it. + SendAll(connection.fd(), + FrameHeader(kOpBinary, kMaxWebSocketMessageBytes + 1, true) + + std::string(4096, 'x')); + while (auto frame = connection.ReadFrame()) { + if (frame->opcode == kOpClose) { + close_codes.Put(frame->CloseCode()); + return; + } + } + }); + + // The frame can arrive together with the handshake response, so the socket + // may fail before the caller sees it open. + int64_t handle = Connect(server.Url("/too-big")); + Received received = ReceiveMessage(&demux, handle); + EXPECT_EQ(received.status, kWebSocketReceiveError); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorOther); + EXPECT_NE(WebSocketGetErrorInternal(handle).find("16 MiB"), + std::string::npos); + + EXPECT_EQ(close_codes.Take(), + std::optional(kWebSocketCloseMessageTooBig)); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, ServerInitiatedCloseReportsCodeAndReason) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox client_frames; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + connection.SendFrame(kOpText, "before the close"); + connection.SendClose(4001, "server going away"); + if (auto frame = connection.ReadFrame()) { + client_frames.Put(*frame); + } + // Returning closes the connection, which ends the closing handshake. + }); + + int64_t handle = Connect(server.Url("/server-close")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + + // The message sent before the Close frame is delivered first. + Received message = ReceiveMessage(&demux, handle); + EXPECT_EQ(message.status, 0); + EXPECT_EQ(message.data, "before the close"); + Received closed = ReceiveMessage(&demux, handle); + EXPECT_EQ(closed.status, kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketCloseReceived); + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), 4001); + EXPECT_EQ(WebSocketGetCloseReasonInternal(handle), "server going away"); + + // The reply goes out when the caller closes. + WebSocketCloseInternal(handle, 1000, "client ack"); + auto reply = client_frames.Take(); + ASSERT_TRUE(reply.has_value()); + EXPECT_EQ(reply->opcode, kOpClose); + EXPECT_EQ(reply->CloseCode(), 1000); + EXPECT_EQ(reply->CloseReason(), "client ack"); + + Received done = ReceiveMessage(&demux, handle); + EXPECT_EQ(done.status, kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketClosed); + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), 4001); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorNone); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, ClientCloseCompletesTheHandshake) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox client_frames; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + while (auto frame = connection.ReadFrame()) { + client_frames.Put(*frame); + if (frame->opcode == kOpClose) { + connection.SendClose(3005, "server ack"); + return; + } + } + }); + + int64_t handle = Connect(server.Url("/client-close")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + ASSERT_TRUE(SendMessage(&demux, handle, kWebSocketText, "sent before close")); + WebSocketCloseInternal(handle, 1000, "client done"); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketCloseSent); + EXPECT_FALSE(SendMessage(&demux, handle, kWebSocketText, "after close")); + + // The queued message is sent before the Close frame. + auto first = client_frames.Take(); + ASSERT_TRUE(first.has_value()); + EXPECT_EQ(first->opcode, kOpText); + EXPECT_EQ(first->payload, "sent before close"); + auto second = client_frames.Take(); + ASSERT_TRUE(second.has_value()); + EXPECT_EQ(second->opcode, kOpClose); + EXPECT_EQ(second->CloseCode(), 1000); + EXPECT_EQ(second->CloseReason(), "client done"); + + // Closed is reported with the peer's code and reason. + Received closed = ReceiveMessage(&demux, handle); + EXPECT_EQ(closed.status, kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketClosed); + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), 3005); + EXPECT_EQ(WebSocketGetCloseReasonInternal(handle), "server ack"); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorNone); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, CloseCompletesWhenTheServerKeepsTheConnectionOpen) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox client_closed_connection; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + auto frame = connection.ReadFrame(); + if (!frame || frame->opcode != kOpClose) { + return; + } + // Answer the Close frame but leave closing the connection to the client. + connection.SendFrame(kOpClose, ""); + client_closed_connection.Put(connection.WaitForPeerClose(5000)); + }); + + int64_t handle = Connect(server.Url("/lazy-close")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + WebSocketCloseInternal(handle, 1000, "closing"); + Received closed = ReceiveMessage(&demux, handle); + EXPECT_EQ(closed.status, kWebSocketReceiveClosed); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketClosed); + // The server's Close frame carried no status code. + EXPECT_EQ(WebSocketGetCloseCodeInternal(handle), kWebSocketCloseNoStatus); + EXPECT_TRUE(WebSocketGetCloseReasonInternal(handle).empty()); + EXPECT_EQ(client_closed_connection.Take(), std::optional(true)); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, ServerPingIsAnswered) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox client_frames; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + connection.SendFrame(kOpPing, "ping payload"); + if (auto frame = connection.ReadFrame()) { + client_frames.Put(*frame); + } + ServeEcho(connection); + }); + + int64_t handle = Connect(server.Url("/ping")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + auto pong = client_frames.Take(); + ASSERT_TRUE(pong.has_value()); + EXPECT_EQ(pong->opcode, kOpPong); + EXPECT_EQ(pong->payload, "ping payload"); + EXPECT_TRUE(pong->masked); + + // The ping is not surfaced as a message and the socket keeps working. + ASSERT_TRUE(SendMessage(&demux, handle, kWebSocketText, "after ping")); + Received echo = ReceiveMessage(&demux, handle); + EXPECT_EQ(echo.status, 0); + EXPECT_EQ(echo.data, "after ping"); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, KeepalivePingIsSentAfterSilence) { + BlockingEventDemux demux; + demux.DrainStale(); + + struct RestoreKeepalive { + ~RestoreKeepalive() { + SetWebSocketKeepaliveIntervalForTesting( + std::chrono::seconds(kWebSocketKeepaliveSeconds)); + } + } restore; + SetWebSocketKeepaliveIntervalForTesting(std::chrono::milliseconds(60)); + + Mailbox client_frames; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + // Say nothing: the first frame from the client must be its ping. + if (auto frame = connection.ReadFrame()) { + client_frames.Put(*frame); + connection.SendFrame(kOpPong, frame->payload); + } + connection.WaitForPeerClose(5000); + }); + + int64_t handle = Connect(server.Url("/keepalive")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + auto ping = client_frames.Take(); + ASSERT_TRUE(ping.has_value()); + EXPECT_EQ(ping->opcode, kOpPing); + EXPECT_TRUE(ping->payload.empty()); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketOpen); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, CancelDuringBlockedReceiveReturnsPromptly) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox connection_dropped; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + connection_dropped.Put(connection.WaitForPeerClose(5000)); + }); + + int64_t handle = Connect(server.Url("/cancel")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + char byte = 0; + ASSERT_EQ(WebSocketTryReceiveInternal(handle, &byte, 1), + kWebSocketReceiveWouldBlock); + + auto start = std::chrono::steady_clock::now(); + WebSocketCancelInternal(handle); + ASSERT_TRUE(demux.WaitFor(handle, kHttpEventWebSocketReceive, 3000)); + EXPECT_EQ(WebSocketTryReceiveInternal(handle, &byte, 1), + kWebSocketReceiveError); + auto elapsed = std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + EXPECT_LT(elapsed.count(), 1000); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorCanceled); + + // The connection is dropped by the cancel alone, before the handle is + // destroyed. + EXPECT_EQ(connection_dropped.Take(), std::optional(true)); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, ConnectionRefusedGivesConnect) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::string url = + "ws://127.0.0.1:" + std::to_string(ClosedLoopbackPort()) + "/refused"; + int64_t handle = Connect(url); + EXPECT_FALSE(WaitOpen(&demux, handle)); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorConnect); + EXPECT_FALSE(WebSocketGetErrorInternal(handle).empty()); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, RefusedUpgradeGivesOtherWithTheStatus) { + BlockingEventDemux demux; + demux.DrainStale(); + + WebSocketTestServer server([](ServerConnection& connection) { + if (!connection.ReadRequest()) { + return; + } + SendAll(connection.fd(), + "HTTP/1.1 404 Not Found\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"); + connection.WaitForPeerClose(5000); + }); + + int64_t handle = Connect(server.Url("/missing")); + EXPECT_FALSE(WaitOpen(&demux, handle)); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorOther); + EXPECT_NE(WebSocketGetErrorInternal(handle).find("404"), std::string::npos); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, ConnectionDroppedWithoutCloseFrameGivesConnect) { + BlockingEventDemux demux; + demux.DrainStale(); + + WebSocketTestServer server([](ServerConnection& connection) { + // Open the socket, then drop the connection without a Close frame. + connection.ReadRequestAndAccept(); + }); + + int64_t handle = Connect(server.Url("/dropped")); + Received received = ReceiveMessage(&demux, handle); + EXPECT_EQ(received.status, kWebSocketReceiveError); + EXPECT_EQ(WebSocketGetStateInternal(handle), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(handle), kHttpErrorConnect); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, SubprotocolIsRequestedAndReported) { + BlockingEventDemux demux; + demux.DrainStale(); + + Mailbox requested; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequest()) { + return; + } + requested.Put(connection.Header("Sec-WebSocket-Protocol")); + // "/other" answers with a subprotocol the client did not ask for. + connection.Accept(connection.request_line() == "GET /other HTTP/1.1" + ? "not.requested" + : "chat.v2"); + ServeEcho(connection); + }); + + int64_t handle = Connect(server.Url("/chat"), "", "chat.v1, chat.v2"); + ASSERT_TRUE(WaitOpen(&demux, handle)); + EXPECT_EQ(requested.Take(), std::optional("chat.v1, chat.v2")); + EXPECT_EQ(WebSocketGetSubprotocolInternal(handle), "chat.v2"); + WebSocketDestroyInternal(handle); + + int64_t rejected = Connect(server.Url("/other"), "", "chat.v3"); + Received received = ReceiveMessage(&demux, rejected); + EXPECT_EQ(received.status, kWebSocketReceiveError); + EXPECT_EQ(WebSocketGetStateInternal(rejected), kWebSocketAborted); + EXPECT_EQ(WebSocketGetErrorClassInternal(rejected), kHttpErrorOther); + EXPECT_NE(WebSocketGetErrorInternal(rejected).find("subprotocol"), + std::string::npos); + WebSocketDestroyInternal(rejected); +} + +TEST(WebSocketCurlTest, ReceiveBackpressureBoundsBufferedBytes) { + BlockingEventDemux demux; + demux.DrainStale(); + + // 64 MiB in 1 MiB messages: far more than the 4 MiB receive queue plus what + // the socket buffers of both ends can hold. + constexpr size_t kMessageSize = 1024 * 1024; + constexpr size_t kMessageCount = 64; + // How long the server waits for socket space before reporting a stall. + constexpr int kStallMs = 500; + + enum class ServerEvent { kStalled, kFinished }; + Mailbox server_events; + WebSocketTestServer server([&](ServerConnection& connection) { + if (!connection.ReadRequestAndAccept()) { + return; + } + // Send without blocking so the server can tell when the client stopped + // taking bytes. + SetNonBlocking(connection.fd()); + bool reported_stall = false; + int stalls = 0; + for (size_t i = 0; i < kMessageCount; ++i) { + std::string frame = FrameHeader(kOpBinary, kMessageSize, true) + + PatternBytes(i * kMessageSize, kMessageSize); + size_t sent = 0; + while (sent < frame.size()) { + if (!WaitForSocket(connection.fd(), /*for_write=*/true, kStallMs)) { + if (!reported_stall) { + reported_stall = true; + server_events.Put(ServerEvent::kStalled); + } + // Give up after 30 s without progress so a broken client cannot + // hang the test. + if (++stalls >= 30000 / kStallMs) { + return; + } + continue; + } + stalls = 0; + int n = + SendSome(connection.fd(), frame.data() + sent, frame.size() - sent); + if (n < 0) { + return; + } + sent += static_cast(n); + } + } + server_events.Put(ServerEvent::kFinished); + connection.WaitForPeerClose(5000); + }); + + int64_t handle = Connect(server.Url("/flood")); + ASSERT_TRUE(WaitOpen(&demux, handle)); + + // Read nothing. The backend must stop taking bytes from the socket once the + // receive queue is full, which the server sees as being unable to send. + auto first_event = server_events.Take(30000); + ASSERT_TRUE(first_event.has_value()); + EXPECT_EQ(*first_event, ServerEvent::kStalled) + << "The server sent everything although nothing was read"; + + auto ws = FindWebSocket(handle); + ASSERT_NE(ws, nullptr); + auto buffered_bytes = [&ws]() { + std::lock_guard lock(ws->mutex); + return ws->receive_queue_bytes; + }; + // The message that reaches the bound is still queued whole. + constexpr size_t kBufferedLimit = + kMaxWebSocketReceiveQueueBytes + kMessageSize; + EXPECT_LE(buffered_bytes(), kBufferedLimit); + + // Reading resumes the transfer and every message arrives intact, in order. + size_t max_buffered = 0; + for (size_t i = 0; i < kMessageCount; ++i) { + max_buffered = (std::max)(max_buffered, buffered_bytes()); + Received message = ReceiveMessage(&demux, handle, 15000); + ASSERT_EQ(message.status, 0) << "message " << i; + EXPECT_EQ(message.type, kWebSocketBinary); + ASSERT_EQ(message.data.size(), kMessageSize) << "message " << i; + ASSERT_TRUE(message.data == PatternBytes(i * kMessageSize, kMessageSize)) + << "message " << i; + } + EXPECT_LE(max_buffered, kBufferedLimit); + EXPECT_EQ(server_events.Take(), + std::optional(ServerEvent::kFinished)); + WebSocketDestroyInternal(handle); +} + +TEST(WebSocketCurlTest, TwentySocketsAtOnce) { + BlockingEventDemux demux; + demux.DrainStale(); + + WebSocketTestServer server([](ServerConnection& connection) { + if (connection.ReadRequestAndAccept()) { + ServeEcho(connection); + } + }); + + constexpr int kSockets = 20; + std::vector handles; + for (int i = 0; i < kSockets; ++i) { + handles.push_back(Connect(server.Url("/many/" + std::to_string(i)))); + } + for (int i = 0; i < kSockets; ++i) { + SCOPED_TRACE(i); + ASSERT_TRUE(WaitOpen(&demux, handles[i])); + ASSERT_TRUE(SendMessage(&demux, handles[i], kWebSocketText, + "socket-" + std::to_string(i))); + } + for (int i = 0; i < kSockets; ++i) { + SCOPED_TRACE(i); + Received echo = ReceiveMessage(&demux, handles[i]); + EXPECT_EQ(echo.status, 0); + EXPECT_EQ(echo.data, "socket-" + std::to_string(i)); + } + for (int64_t handle : handles) { + WebSocketDestroyInternal(handle); + } +} + +TEST(WebSocketCurlTest, SlowHandshakeDoesNotStallOtherSockets) { + BlockingEventDemux demux; + demux.DrainStale(); + + // "/stuck" never gets an answer to its opening request. + WebSocketTestServer server([](ServerConnection& connection) { + if (!connection.ReadRequest()) { + return; + } + if (connection.request_line() == "GET /stuck HTTP/1.1") { + connection.WaitForPeerClose(5000); + return; + } + connection.Accept(); + ServeEcho(connection); + }); + + int64_t stuck = Connect(server.Url("/stuck")); + int64_t working = Connect(server.Url("/working")); + ASSERT_TRUE(WaitOpen(&demux, working)); + ASSERT_TRUE(SendMessage(&demux, working, kWebSocketText, "not stalled")); + Received echo = ReceiveMessage(&demux, working); + EXPECT_EQ(echo.status, 0); + EXPECT_EQ(echo.data, "not stalled"); + EXPECT_EQ(WebSocketGetStateInternal(stuck), kWebSocketConnecting); + + WebSocketDestroyInternal(working); + WebSocketDestroyInternal(stuck); +} + +} // namespace +} // namespace http +} // namespace firebase diff --git a/app/http/websocket.h b/app/http/websocket.h new file mode 100644 index 0000000000..d0ec8ed650 --- /dev/null +++ b/app/http/websocket.h @@ -0,0 +1,231 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Internal interface between the WebSocket bridge (`WebSocket*Internal` in +// `http_bridge.h`), the shared queueing code in `websocket_common.cc`, and the +// platform backends (`websocket_curl.cc`, `websocket_apple.mm`). +// +// The shared code owns every queue. A backend only moves whole messages: it +// takes them from `WebSocketOperation::PopOutgoing` and hands received ones to +// `WebSocketOperation::PushReceivedMessage`. Fragmentation on the wire, +// answering pings, and keepalive pings are the backend's job. + +#ifndef FIREBASE_APP_HTTP_WEBSOCKET_H_ +#define FIREBASE_APP_HTTP_WEBSOCKET_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport.h" + +namespace firebase { +namespace http { + +// Values returned by `WebSocketGetStateInternal`. +enum WebSocketState : int32_t { + kWebSocketConnecting = 0, + kWebSocketOpen = 1, + // The caller asked to close; the peer's Close frame or the end of the + // transport is still outstanding. + kWebSocketCloseSent = 2, + // The peer sent a Close frame and the caller has not asked to close yet. + kWebSocketCloseReceived = 3, + // The closing handshake finished and the transport is gone. + kWebSocketClosed = 4, + // Failed or canceled. + kWebSocketAborted = 5, +}; + +enum WebSocketMessageType : int32_t { + kWebSocketText = 1, + kWebSocketBinary = 2, +}; + +// Whole messages queued for sending. A send is refused while the queue holds +// this much or more. +inline constexpr size_t kMaxWebSocketSendQueueBytes = 1024 * 1024; +// Received messages not yet handed to the caller. The backend stops reading +// from the network at or above the first value and resumes at or below the +// second. +inline constexpr size_t kMaxWebSocketReceiveQueueBytes = 4 * 1024 * 1024; +inline constexpr size_t kLowWaterWebSocketReceiveBytes = 2 * 1024 * 1024; +// Largest message in either direction. +inline constexpr size_t kMaxWebSocketMessageBytes = 16 * 1024 * 1024; +// A backend sends a ping after this long without traffic in either direction. +inline constexpr int kWebSocketKeepaliveSeconds = 45; + +// RFC 6455 section 7.4.1 status codes the transport produces itself. +inline constexpr int32_t kWebSocketCloseNoStatus = 1005; +inline constexpr int32_t kWebSocketCloseMessageTooBig = 1009; +// Longest Close reason that fits a control frame next to the status code. +inline constexpr size_t kMaxWebSocketCloseReasonBytes = 123; + +// Negative results of `WebSocketTryReceiveInternal`. +inline constexpr int64_t kWebSocketReceiveError = -1; +inline constexpr int64_t kWebSocketReceiveWouldBlock = -2; +inline constexpr int64_t kWebSocketReceiveClosed = -3; +// Flag bits in the low byte of a non-negative `WebSocketTryReceiveInternal` +// result. +inline constexpr int64_t kWebSocketReceiveEndOfMessage = 1; +inline constexpr int64_t kWebSocketReceiveBinary = 2; + +struct WebSocketMessage { + WebSocketMessageType type = kWebSocketText; + std::vector data; +}; + +// Shared state of one WebSocket, held by `std::shared_ptr` in the registry and +// by the backend so that canceling or destroying the handle never races with +// backend threads. Every method may be called from any thread. +struct WebSocketOperation { + // What the backend has to put on the wire next. + struct Outgoing { + enum Kind { kNone, kMessage, kClose }; + Kind kind = kNone; + // Set for `kMessage`. + WebSocketMessage message; + // Set for `kClose`. A `close_code` of 0 means a Close frame without a + // status code. + int32_t close_code = 0; + std::string close_reason; + }; + + // Request, fixed at creation. + int64_t id = 0; + std::string url; + std::vector> request_headers; + std::vector subprotocols; + std::string proxy_url; + + // ---- Called by the backend ---------------------------------------------- + + // The opening handshake succeeded. `negotiated_subprotocol` is empty when + // the server selected none. + void MarkOpen(std::string_view negotiated_subprotocol); + + // Queues one whole received message. Returns true when the receive queue is + // now at or above `kMaxWebSocketReceiveQueueBytes`: the backend must stop + // reading from the network until `on_receive_space_available` runs. + // Messages pushed after a failure, cancellation, or close are dropped. + bool PushReceivedMessage(WebSocketMessageType type, + std::vector data); + + // The peer's Close frame arrived. Pass `kWebSocketCloseNoStatus` when the + // frame carried no status code. Messages queued before it are still + // delivered. The shared code does not answer the frame: the reply is the + // `kClose` that `PopOutgoing` returns once the caller asks to close. + void MarkPeerClosed(int32_t code, std::string_view reason); + + // The peer's Close frame was received and the transport is gone. This is + // the only transition to `kWebSocketClosed`. Use `MarkFailed` when the + // transport ends without a Close frame from the peer. + void MarkClosed(); + + // The connection failed. Moves to `kWebSocketAborted`, drops every queued + // message in both directions, and wakes every waiter. Ignored once the + // socket is closed, failed, or canceled. + void MarkFailed(std::string_view message, HttpErrorClass error_class); + + // Takes the next thing to send: queued messages in order, then the Close + // requested by the caller (returned once), otherwise `kNone`. Taking a + // message frees send-queue space. + Outgoing PopOutgoing(); + + // Hooks set by the backend when it starts, run outside `mutex`, possibly on + // the caller's thread. They are cleared when the socket closes, fails, or is + // canceled. + // `on_outgoing_available`: `PopOutgoing` has something new. + // `on_receive_space_available`: the receive queue drained to the low-water + // mark after `PushReceivedMessage` returned true. + // `on_cancel`: the socket was canceled; drop the transport at once without + // a closing handshake. + std::function on_outgoing_available; + std::function on_receive_space_available; + std::function on_cancel; + + // ---- State, guarded by `mutex` ------------------------------------------- + + mutable std::mutex mutex; + WebSocketState state = kWebSocketConnecting; + std::atomic started{false}; + std::string negotiated_subprotocol; + + // Send side. `send_partial` collects the fragments of the message the caller + // is writing; only whole messages enter `send_queue`. + std::deque send_queue; + size_t send_queue_bytes = 0; + WebSocketMessage send_partial; + bool send_partial_active = false; + bool close_requested = false; + bool close_popped = false; + int32_t local_close_code = 0; + std::string local_close_reason; + + // Receive side. `receive_offset` counts the bytes of the front message that + // were already handed to the caller. + std::deque receive_queue; + size_t receive_offset = 0; + size_t receive_queue_bytes = 0; + bool receive_backend_paused = false; + bool peer_closed = false; + int32_t close_code = 0; + std::string close_reason; + + // Terminal failure. + HttpErrorClass error_class = kHttpErrorNone; + std::string error_message; + + // Events the caller asked for by polling. + bool open_armed = false; + bool receive_armed = false; + bool send_space_armed = false; +}; + +// Returns the socket for `handle`, or null. +std::shared_ptr FindWebSocket(int64_t handle); + +// Aborts and forgets every WebSocket. Called by `CancelAllOperations`. +void CancelAllWebSockets(); + +// Returns the next handle from the id space shared with HTTP operations. +// Defined in `http_transport_common.cc`. +int64_t AllocateTransportHandle(); + +// Starts the connection. Implemented once per backend. The backend sets the +// hooks, then reports through the `Mark*` methods. +void StartPlatformWebSocket(const std::shared_ptr& ws); + +// The silence after which a backend sends a keepalive ping: +// `kWebSocketKeepaliveSeconds` unless a test changed it. Backends read it +// whenever they schedule the next ping. +std::chrono::milliseconds WebSocketKeepaliveInterval(); +void SetWebSocketKeepaliveIntervalForTesting( + std::chrono::milliseconds interval); + +} // namespace http +} // namespace firebase + +#endif // FIREBASE_APP_HTTP_WEBSOCKET_H_ diff --git a/app/http/websocket_apple.mm b/app/http/websocket_apple.mm new file mode 100644 index 0000000000..4d03c4cda8 --- /dev/null +++ b/app/http/websocket_apple.mm @@ -0,0 +1,557 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// WebSocket backend for iOS and tvOS on `NSURLSessionWebSocketTask`. + +#import + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport.h" +#include "app/http/http_transport_apple_internal.h" +#include "app/http/websocket.h" + +#if !__has_feature(objc_arc) +#error "websocket_apple.mm requires Objective-C ARC (-fobjc-arc)." +#endif + +namespace firebase { +namespace http { +namespace { + +NSString* ToNSString(std::string_view s) { + NSString* ns = [[NSString alloc] initWithBytes:s.data() + length:s.size() + encoding:NSUTF8StringEncoding]; + if (ns == nil) { + ns = [[NSString alloc] initWithBytes:s.data() + length:s.size() + encoding:NSISOLatin1StringEncoding]; + } + return ns != nil ? ns : @""; +} + +std::string FromNSString(NSString* ns) { + if (ns == nil) { + return std::string(); + } + const char* utf8 = [ns UTF8String]; + return utf8 != nullptr ? std::string(utf8) : std::string(); +} + +} // namespace +} // namespace http +} // namespace firebase + +// Runs one WebSocket on its own NSURLSession. The session's delegate queue is +// serial. Everything that changes after `init` is used only on that queue: by +// the delegate callbacks, by the completion handlers NSURLSession calls there, +// and by the work the four methods below schedule. Those four methods may be +// called from any thread and return at once. +@interface FIRFirebaseHttpWebSocketDelegate : NSObject +- (instancetype)initWithOperation:(std::shared_ptr)ws + configuration:(NSURLSessionConfiguration*)configuration + request:(NSURLRequest*)request; +- (void)start; +- (void)outgoingAvailable; +- (void)receiveSpaceAvailable; +- (void)cancel; +@end + +@implementation FIRFirebaseHttpWebSocketDelegate { + std::shared_ptr _ws; + NSOperationQueue* _queue; + NSURLSessionConfiguration* _configuration; + NSURLRequest* _request; + // The session retains this object until it is invalidated, which `teardown` + // does on every path that ends the socket. + NSURLSession* _session; + NSURLSessionWebSocketTask* _task; + // Last traffic in either direction, for the keepalive ping. + std::chrono::steady_clock::time_point _lastActivity; + bool _opened; + // A `sendMessage:` or `receiveMessage` completion handler is outstanding. + bool _sending; + bool _receiving; + // `PushReceivedMessage` asked to stop reading. + bool _receivePaused; + // A receive failed: NSURLSession has nothing more to deliver. + bool _receiveEnded; + // The caller's Close was taken from `PopOutgoing`. + bool _localCloseSent; + // The peer's Close is known. It is reported with `MarkPeerClosed` only after + // the messages that arrived before it. + bool _peerCloseReceived; + int32_t _peerCloseCode; + std::string _peerCloseReason; + // `MarkPeerClosed` was called. + bool _peerCloseReported; + bool _taskCompleted; + // The operation has its final state and the session is invalidated. + bool _finished; +} + +- (instancetype)initWithOperation:(std::shared_ptr)ws + configuration:(NSURLSessionConfiguration*)configuration + request:(NSURLRequest*)request { + self = [super init]; + if (self != nil) { + _ws = std::move(ws); + _configuration = configuration; + _request = [request copy]; + _queue = [[NSOperationQueue alloc] init]; + _queue.name = @"com.google.firebase.http.websocket"; + _queue.maxConcurrentOperationCount = 1; + _queue.qualityOfService = NSQualityOfServiceUserInitiated; + } + return self; +} + +// Entry points. Any thread; each only schedules work on the delegate queue. + +- (void)start { + [_queue addOperationWithBlock:^{ + [self startOnQueue]; + }]; +} + +- (void)outgoingAvailable { + [_queue addOperationWithBlock:^{ + [self drainOutgoing]; + }]; +} + +- (void)receiveSpaceAvailable { + [_queue addOperationWithBlock:^{ + self->_receivePaused = false; + [self receiveNext]; + }]; +} + +- (void)cancel { + [_queue addOperationWithBlock:^{ + if (!self->_finished) { + [self teardown]; + } + }]; +} + +- (void)keepaliveTimerFired { + [_queue addOperationWithBlock:^{ + [self checkKeepalive]; + }]; +} + +// Everything below runs on the delegate queue. + +- (void)startOnQueue { + if (_finished) { + return; // Canceled before the session was created. + } + _session = [NSURLSession sessionWithConfiguration:_configuration + delegate:self + delegateQueue:_queue]; + _task = [_session webSocketTaskWithRequest:_request]; + _task.maximumMessageSize = static_cast(firebase::http::kMaxWebSocketMessageBytes); + [_task resume]; +} + +// Drops the transport. The caller has already given the operation its final +// state, so every later callback returns on `_finished`. +- (void)teardown { + _finished = true; + [_session invalidateAndCancel]; + _session = nil; + _task = nil; +} + +- (void)failWithMessage:(std::string_view)message + errorClass:(firebase::http::HttpErrorClass)errorClass { + _ws->MarkFailed(message, errorClass); + [self teardown]; +} + +// The socket is closed once both Close frames were exchanged and the task +// has ended. +- (void)finishIfClosed { + if (!_finished && _peerCloseReported && _localCloseSent && _taskCompleted) { + _ws->MarkClosed(); + [self teardown]; + } +} + +- (void)recordPeerCloseCode:(NSURLSessionWebSocketCloseCode)code reason:(NSData*)reason { + _peerCloseReceived = true; + _peerCloseCode = code > 0 ? static_cast(code) : firebase::http::kWebSocketCloseNoStatus; + _peerCloseReason.clear(); + if (reason.length > 0) { + _peerCloseReason.assign(static_cast(reason.bytes), reason.length); + } +} + +// Reports the recorded Close once. Shared code drops messages pushed after +// this, so it is called only when no more can arrive. +- (void)reportPeerClose { + if (_finished || _peerCloseReported) { + return; + } + _peerCloseReported = true; + _ws->MarkPeerClosed(_peerCloseCode, _peerCloseReason); + [self finishIfClosed]; +} + +- (void)receiveNext { + if (_finished || _receiving || _receivePaused || _receiveEnded || _taskCompleted) { + return; + } + _receiving = true; + __weak FIRFirebaseHttpWebSocketDelegate* weakSelf = self; + [_task receiveMessageWithCompletionHandler:^(NSURLSessionWebSocketMessage* message, + NSError* error) { + [weakSelf didReceiveMessage:message error:error]; + }]; +} + +- (void)didReceiveMessage:(NSURLSessionWebSocketMessage*)message error:(NSError*)error { + _receiving = false; + if (_finished) { + return; + } + if (error != nil || message == nil) { + // Nothing more to read. If the peer closed, every message before its + // Close is queued now. Otherwise the task is ending and + // `didCompleteWithError` reports why; failing here could turn a clean + // close into an error. + _receiveEnded = true; + if (_peerCloseReceived) { + [self reportPeerClose]; + } + return; + } + _lastActivity = std::chrono::steady_clock::now(); + + firebase::http::WebSocketMessageType type = firebase::http::kWebSocketBinary; + NSData* payload = message.data; + if (message.type == NSURLSessionWebSocketMessageTypeString) { + type = firebase::http::kWebSocketText; + payload = [message.string dataUsingEncoding:NSUTF8StringEncoding]; + } + std::vector bytes; + if (payload.length > 0) { + const auto* first = static_cast(payload.bytes); + bytes.assign(first, first + payload.length); + } + + // Ask for the next message only after this one is queued, and not at all + // while the receive queue is full: `receiveSpaceAvailable` resumes. + _receivePaused = _ws->PushReceivedMessage(type, std::move(bytes)); + [self receiveNext]; +} + +- (void)drainOutgoing { + // One message at a time: the next is taken when the previous send completes. + while (!_finished && !_sending && !_localCloseSent) { + auto out = _ws->PopOutgoing(); + if (out.kind == firebase::http::WebSocketOperation::Outgoing::kNone) { + return; + } + if (out.kind == firebase::http::WebSocketOperation::Outgoing::kClose) { + _localCloseSent = true; + if (!_taskCompleted) { + // RFC 6455 section 7.4.1 forbids sending 1005 (No Status Received) on + // the wire, and NSURLSessionWebSocketTask requires a wire-valid close + // code. Fall back to Normal Closure (1000) with no reason when the + // caller did not supply a wire-valid status code. + NSURLSessionWebSocketCloseCode code = NSURLSessionWebSocketCloseCodeNormalClosure; + NSData* reason = nil; + if (out.close_code > 0 && out.close_code != firebase::http::kWebSocketCloseNoStatus) { + code = static_cast(out.close_code); + if (!out.close_reason.empty()) { + reason = [NSData dataWithBytes:out.close_reason.data() + length:out.close_reason.size()]; + } + } + [_task cancelWithCloseCode:code reason:reason]; + } + [self finishIfClosed]; + return; + } + if (_taskCompleted) { + // The peer closed and the transport is gone: only the caller's Close is + // still awaited. + continue; + } + + const std::vector& data = out.message.data; + NSURLSessionWebSocketMessage* message = nil; + if (out.message.type == firebase::http::kWebSocketText) { + NSString* text = @""; + if (!data.empty()) { + text = [[NSString alloc] initWithBytes:data.data() + length:data.size() + encoding:NSUTF8StringEncoding]; + } + if (text == nil) { + [self failWithMessage:"WebSocket text message is not valid UTF-8." + errorClass:firebase::http::kHttpErrorOther]; + return; + } + message = [[NSURLSessionWebSocketMessage alloc] initWithString:text]; + } else { + NSData* binary = [NSData data]; + if (!data.empty()) { + binary = [NSData dataWithBytes:data.data() length:data.size()]; + } + message = [[NSURLSessionWebSocketMessage alloc] initWithData:binary]; + } + _sending = true; + __weak FIRFirebaseHttpWebSocketDelegate* weakSelf = self; + [_task sendMessage:message + completionHandler:^(NSError* error) { + [weakSelf didSendWithError:error]; + }]; + } +} + +- (void)didSendWithError:(NSError*)error { + _sending = false; + if (_finished) { + return; + } + if (error == nil) { + _lastActivity = std::chrono::steady_clock::now(); + } + // After an error the task is ending and `didCompleteWithError` reports why. + // Keep draining so that the caller's Close is still taken. + [self drainOutgoing]; +} + +- (void)scheduleKeepaliveAfter:(std::chrono::milliseconds)delay { + __weak FIRFirebaseHttpWebSocketDelegate* weakSelf = self; + int64_t delay_ns = std::chrono::duration_cast(delay).count(); + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay_ns), + dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{ + [weakSelf keepaliveTimerFired]; + }); +} + +// Sends a ping when nothing was sent or received for the keepalive interval. +// One timer is pending at a time; it stops once either side has closed. +- (void)checkKeepalive { + if (_finished || _localCloseSent || _peerCloseReceived) { + return; + } + std::chrono::milliseconds interval = firebase::http::WebSocketKeepaliveInterval(); + auto now = std::chrono::steady_clock::now(); + auto idle = std::chrono::duration_cast(now - _lastActivity); + if (idle < interval) { + [self scheduleKeepaliveAfter:interval - idle]; + return; + } + _lastActivity = now; + __weak FIRFirebaseHttpWebSocketDelegate* weakSelf = self; + [_task sendPingWithPongReceiveHandler:^(NSError* error) { + [weakSelf didReceivePongWithError:error]; + }]; + [self scheduleKeepaliveAfter:interval]; +} + +- (void)didReceivePongWithError:(NSError*)error { + if (_finished) { + return; + } + if (error == nil) { + _lastActivity = std::chrono::steady_clock::now(); + return; + } + // A ping also fails when the socket is closing; that is not a lost + // connection. + if (_localCloseSent || _peerCloseReceived || + _task.closeCode != NSURLSessionWebSocketCloseCodeInvalid) { + return; + } + std::string message = "WebSocket keepalive ping failed: " + + firebase::http::FromNSString(error.localizedDescription); + [self failWithMessage:message errorClass:firebase::http::kHttpErrorConnect]; +} + +- (void)URLSession:(NSURLSession*)session + webSocketTask:(NSURLSessionWebSocketTask*)webSocketTask + didOpenWithProtocol:(NSString*)subprotocol { + if (_finished) { + return; + } + _opened = true; + _lastActivity = std::chrono::steady_clock::now(); + _ws->MarkOpen(firebase::http::FromNSString(subprotocol)); + [self receiveNext]; + [self scheduleKeepaliveAfter:firebase::http::WebSocketKeepaliveInterval()]; +} + +- (void)URLSession:(NSURLSession*)session + webSocketTask:(NSURLSessionWebSocketTask*)webSocketTask + didCloseWithCode:(NSURLSessionWebSocketCloseCode)closeCode + reason:(NSData*)reason { + if (_finished || _peerCloseReceived) { + return; + } + [self recordPeerCloseCode:closeCode reason:reason]; + // Messages that arrived before the Close may still be unread. Report the + // Close when the receive loop finds nothing more: when the outstanding + // receive fails, when the one started here fails, or, if the loop is paused, + // when the one started on resume fails. Task completion is the fallback. + if (_receiveEnded) { + [self reportPeerClose]; + } else { + [self receiveNext]; + } +} + +- (void)URLSession:(NSURLSession*)session + task:(NSURLSessionTask*)task + willPerformHTTPRedirection:(NSHTTPURLResponse*)response + newRequest:(NSURLRequest*)request + completionHandler:(void (^)(NSURLRequest* _Nullable))handler { + // No backend follows redirects. Refusing makes the 3xx the handshake + // response, which fails the handshake below. + handler(nil); +} + +- (void)URLSession:(NSURLSession*)session + task:(NSURLSessionTask*)task + didCompleteWithError:(NSError*)error { + if (_finished) { + return; + } + _taskCompleted = true; + if (!_peerCloseReceived && _localCloseSent) { + // NSURLSession does not always report the peer's Close after ours was + // sent. The task ending after our Close is a clean close; take the code + // and reason from the task when it has them. + NSURLSessionWebSocketCloseCode code = _task.closeCode; + NSData* reason = code != NSURLSessionWebSocketCloseCodeInvalid ? _task.closeReason : nil; + [self recordPeerCloseCode:code reason:reason]; + } + if (_peerCloseReceived) { + // A Close was exchanged, so however the task ended this is a close, not a + // failure. Nothing more can be read or sent: report the peer's Close if + // the receive loop has not, and take what the caller queued, up to its + // Close. + [self reportPeerClose]; + _sending = false; + [self drainOutgoing]; + [self finishIfClosed]; + return; + } + + NSInteger handshake_status = 0; + if (!_opened && [task.response isKindOfClass:[NSHTTPURLResponse class]]) { + handshake_status = static_cast(task.response).statusCode; + } + if (handshake_status != 0 && handshake_status != 101) { + std::string message = "WebSocket handshake failed with HTTP status " + + std::to_string(handshake_status) + "."; + [self failWithMessage:message errorClass:firebase::http::kHttpErrorOther]; + } else if (error != nil) { + std::string message = firebase::http::FromNSString(error.localizedDescription); + [self failWithMessage:message errorClass:firebase::http::ClassifyNSError(error)]; + } else { + [self failWithMessage:"WebSocket connection ended without a Close frame from the peer." + errorClass:firebase::http::kHttpErrorConnect]; + } +} + +@end + +namespace firebase { +namespace http { + +void StartPlatformWebSocket(const std::shared_ptr& ws) { + @autoreleasepool { + NSURL* url = [NSURL URLWithString:ToNSString(ws->url)]; + NSString* scheme = url.scheme.lowercaseString; + if (![scheme isEqualToString:@"ws"] && ![scheme isEqualToString:@"wss"]) { + ws->MarkFailed("Unsupported URI scheme; only ws and wss are allowed.", + kHttpErrorInvalidRequest); + return; + } + if (url.user != nil || url.password != nil) { + ws->MarkFailed("Request URL must not contain user information.", kHttpErrorInvalidRequest); + return; + } + + NSURLSessionConfiguration* config = MakeBaseSessionConfig(); + if (!ws->proxy_url.empty()) { + NSDictionary* proxy = MakeProxyDictionary(ws->proxy_url); + if (proxy == nil) { + ws->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorInvalidRequest); + return; + } + config.connectionProxyDictionary = proxy; + } + + NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url]; + for (const auto& header : ws->request_headers) { + // A new request has no fields, so this keeps repeated names as a list. + [request addValue:ToNSString(header.second) forHTTPHeaderField:ToNSString(header.first)]; + } + if (!ws->subprotocols.empty()) { + std::string offered; + for (const std::string& subprotocol : ws->subprotocols) { + if (!offered.empty()) { + offered += ", "; + } + offered += subprotocol; + } + [request setValue:ToNSString(offered) forHTTPHeaderField:@"Sec-WebSocket-Protocol"]; + } + + FIRFirebaseHttpWebSocketDelegate* delegate = + [[FIRFirebaseHttpWebSocketDelegate alloc] initWithOperation:ws + configuration:config + request:request]; + // The hooks hold the delegate weakly: the operation is owned by the + // delegate, so a strong reference would be a cycle. + __weak FIRFirebaseHttpWebSocketDelegate* weak_delegate = delegate; + bool connecting = false; + { + // Checked under `mutex` so that a cancel either finds `on_cancel` or + // prevents the start. + std::lock_guard lock(ws->mutex); + connecting = ws->state == kWebSocketConnecting; + if (connecting) { + ws->on_outgoing_available = [weak_delegate]() { [weak_delegate outgoingAvailable]; }; + ws->on_receive_space_available = [weak_delegate]() { + [weak_delegate receiveSpaceAvailable]; + }; + ws->on_cancel = [weak_delegate]() { [weak_delegate cancel]; }; + } + } + if (connecting) { + [delegate start]; + } + } +} + +} // namespace http +} // namespace firebase diff --git a/app/http/websocket_common.cc b/app/http/websocket_common.cc new file mode 100644 index 0000000000..9be2f53cd8 --- /dev/null +++ b/app/http/websocket_common.cc @@ -0,0 +1,599 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "app/http/websocket.h" + +namespace firebase { +namespace http { +namespace { + +struct WebSocketRegistry { + std::mutex mutex; + std::unordered_map> sockets; +}; + +WebSocketRegistry& GetWebSocketRegistry() { + static auto* registry = new WebSocketRegistry(); + return *registry; +} + +std::atomic& KeepaliveIntervalMs() { + static std::atomic interval_ms{ + static_cast(kWebSocketKeepaliveSeconds) * 1000}; + return interval_ms; +} + +bool IsWsOrWssUrl(std::string_view url) { + for (unsigned char ch : url) { + if (ch <= 0x20 || ch == 0x7F) { + return false; + } + } + for (std::string_view scheme : + {std::string_view("ws://"), std::string_view("wss://")}) { + if (url.size() > scheme.size() && + AsciiEqualsIgnoreCase(url.substr(0, scheme.size()), scheme)) { + return true; + } + } + return false; +} + +// Splits a comma separated subprotocol list. Returns nullopt if an entry is +// not a token. +std::optional> ParseSubprotocols( + std::string_view list) { + std::vector subprotocols; + if (TrimAsciiWhitespace(list).empty()) { + return subprotocols; + } + while (true) { + size_t comma = list.find(','); + std::string_view entry = TrimAsciiWhitespace(list.substr(0, comma)); + if (!IsValidHeaderName(entry)) { + return std::nullopt; + } + subprotocols.emplace_back(entry); + if (comma == std::string_view::npos) { + return subprotocols; + } + list.remove_prefix(comma + 1); + } +} + +// The armed events to post once `mutex` is released. +struct PendingEvents { + bool open = false; + bool receive = false; + bool send_space = false; + + void Post(int64_t handle) const { + if (open) { + PostCompletionEvent(handle, kHttpEventWebSocketOpen); + } + if (receive) { + PostCompletionEvent(handle, kHttpEventWebSocketReceive); + } + if (send_space) { + PostCompletionEvent(handle, kHttpEventWebSocketSendSpace); + } + } +}; + +// Disarms every armed event of `ws`. Requires `ws->mutex`. +PendingEvents TakeAllArmedEvents(WebSocketOperation* ws) { + PendingEvents events; + events.open = ws->open_armed; + events.receive = ws->receive_armed; + events.send_space = ws->send_space_armed; + ws->open_armed = false; + ws->receive_armed = false; + ws->send_space_armed = false; + return events; +} + +bool IsFinished(const WebSocketOperation& ws) { + return ws.state == kWebSocketClosed || ws.state == kWebSocketAborted; +} + +// Drops everything queued and detaches the backend. Requires `ws->mutex`. +void ReleaseQueuesAndHooks(WebSocketOperation* ws) { + ws->send_queue.clear(); + ws->send_queue_bytes = 0; + ws->send_partial = WebSocketMessage(); + ws->send_partial_active = false; + ws->on_outgoing_available = nullptr; + ws->on_receive_space_available = nullptr; + ws->on_cancel = nullptr; +} + +void CancelWebSocket(const std::shared_ptr& ws) { + if (!ws) { + return; + } + std::function cancel_hook; + PendingEvents events; + { + std::lock_guard lock(ws->mutex); + if (IsFinished(*ws)) { + return; + } + ws->state = kWebSocketAborted; + ws->error_class = kHttpErrorCanceled; + cancel_hook = std::move(ws->on_cancel); + ws->receive_queue.clear(); + ws->receive_queue_bytes = 0; + ws->receive_offset = 0; + ReleaseQueuesAndHooks(ws.get()); + events = TakeAllArmedEvents(ws.get()); + } + if (cancel_hook) { + cancel_hook(); + } + events.Post(ws->id); +} + +} // namespace + +void WebSocketOperation::MarkOpen(std::string_view subprotocol) { + PendingEvents events; + { + std::lock_guard lock(mutex); + if (state != kWebSocketConnecting) { + return; + } + state = kWebSocketOpen; + negotiated_subprotocol.assign(subprotocol.data(), subprotocol.size()); + events.open = open_armed; + open_armed = false; + } + events.Post(id); +} + +bool WebSocketOperation::PushReceivedMessage(WebSocketMessageType type, + std::vector data) { + PendingEvents events; + bool full = false; + { + std::lock_guard lock(mutex); + if (IsFinished(*this) || peer_closed) { + return false; + } + receive_queue_bytes += data.size(); + WebSocketMessage message; + message.type = type; + message.data = std::move(data); + receive_queue.push_back(std::move(message)); + full = receive_queue_bytes >= kMaxWebSocketReceiveQueueBytes; + if (full) { + receive_backend_paused = true; + } + events.receive = receive_armed; + receive_armed = false; + } + events.Post(id); + return full; +} + +void WebSocketOperation::MarkPeerClosed(int32_t code, std::string_view reason) { + PendingEvents events; + { + std::lock_guard lock(mutex); + if (IsFinished(*this) || peer_closed) { + return; + } + peer_closed = true; + close_code = code > 0 ? code : kWebSocketCloseNoStatus; + close_reason.assign(reason.data(), reason.size()); + if (state == kWebSocketOpen) { + state = kWebSocketCloseReceived; + } + events.receive = receive_armed; + receive_armed = false; + } + events.Post(id); +} + +void WebSocketOperation::MarkClosed() { + PendingEvents events; + { + std::lock_guard lock(mutex); + if (IsFinished(*this)) { + return; + } + state = kWebSocketClosed; + ReleaseQueuesAndHooks(this); + events = TakeAllArmedEvents(this); + } + events.Post(id); +} + +void WebSocketOperation::MarkFailed(std::string_view message, + HttpErrorClass failure_class) { + PendingEvents events; + { + std::lock_guard lock(mutex); + if (IsFinished(*this)) { + return; + } + state = kWebSocketAborted; + error_class = + failure_class == kHttpErrorNone ? kHttpErrorOther : failure_class; + error_message.assign(message.data(), message.size()); + receive_queue.clear(); + receive_queue_bytes = 0; + receive_offset = 0; + ReleaseQueuesAndHooks(this); + events = TakeAllArmedEvents(this); + } + events.Post(id); +} + +WebSocketOperation::Outgoing WebSocketOperation::PopOutgoing() { + Outgoing out; + PendingEvents events; + { + std::lock_guard lock(mutex); + if (IsFinished(*this)) { + return out; + } + if (!send_queue.empty()) { + out.kind = Outgoing::kMessage; + out.message = std::move(send_queue.front()); + send_queue.pop_front(); + send_queue_bytes -= out.message.data.size(); + if (send_space_armed && send_queue_bytes < kMaxWebSocketSendQueueBytes) { + send_space_armed = false; + events.send_space = true; + } + } else if (close_requested && !close_popped) { + close_popped = true; + out.kind = Outgoing::kClose; + out.close_code = local_close_code; + out.close_reason = local_close_reason; + } + } + events.Post(id); + return out; +} + +std::shared_ptr FindWebSocket(int64_t handle) { + auto& reg = GetWebSocketRegistry(); + std::lock_guard lock(reg.mutex); + auto it = reg.sockets.find(handle); + return it != reg.sockets.end() ? it->second : nullptr; +} + +void CancelAllWebSockets() { + std::vector> snapshot; + { + auto& reg = GetWebSocketRegistry(); + std::lock_guard lock(reg.mutex); + snapshot.reserve(reg.sockets.size()); + for (auto& kv : reg.sockets) { + snapshot.push_back(std::move(kv.second)); + } + reg.sockets.clear(); + } + for (const auto& ws : snapshot) { + CancelWebSocket(ws); + } +} + +std::chrono::milliseconds WebSocketKeepaliveInterval() { + return std::chrono::milliseconds( + KeepaliveIntervalMs().load(std::memory_order_relaxed)); +} + +void SetWebSocketKeepaliveIntervalForTesting( + std::chrono::milliseconds interval) { + KeepaliveIntervalMs().store(interval.count(), std::memory_order_relaxed); +} + +} // namespace http + +int64_t WebSocketCreateInternal(const char* url, const char* headers_packed, + const char* subprotocols, + const char* proxy_url) { + auto ws = std::make_shared(); + ws->url = url != nullptr ? url : ""; + if (proxy_url != nullptr) { + ws->proxy_url = proxy_url; + } + + std::string validation_error; + if (!http::IsWsOrWssUrl(ws->url)) { + validation_error = "Unsupported URI scheme; only ws and wss are allowed."; + } else if (headers_packed != nullptr && headers_packed[0] != '\0' && + !http::TryParsePackedHeaders(headers_packed, + &ws->request_headers)) { + validation_error = "Invalid WebSocket request header."; + } else if (subprotocols != nullptr) { + auto parsed = http::ParseSubprotocols(subprotocols); + if (parsed) { + ws->subprotocols = std::move(*parsed); + } else { + validation_error = "Invalid WebSocket subprotocol."; + } + } + + ws->id = http::AllocateTransportHandle(); + { + auto& reg = http::GetWebSocketRegistry(); + std::lock_guard lock(reg.mutex); + reg.sockets.emplace(ws->id, ws); + } + if (!validation_error.empty()) { + ws->MarkFailed(validation_error, http::kHttpErrorInvalidRequest); + } + return ws->id; +} + +void WebSocketConnectInternal(int64_t handle) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return; + } + if (ws->started.exchange(true, std::memory_order_acq_rel)) { + return; + } + { + std::lock_guard lock(ws->mutex); + if (ws->state != http::kWebSocketConnecting) { + return; + } + } + http::StartPlatformWebSocket(ws); +} + +int32_t WebSocketPollOpenInternal(int64_t handle) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return -1; + } + std::lock_guard lock(ws->mutex); + switch (ws->state) { + case http::kWebSocketConnecting: + ws->open_armed = true; + return 0; + case http::kWebSocketOpen: + case http::kWebSocketCloseSent: + case http::kWebSocketCloseReceived: + return 1; + case http::kWebSocketClosed: + case http::kWebSocketAborted: + return -1; + } + return -1; +} + +std::string WebSocketGetSubprotocolInternal(int64_t handle) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return std::string(); + } + std::lock_guard lock(ws->mutex); + return ws->negotiated_subprotocol; +} + +int32_t WebSocketTrySendInternal(int64_t handle, int32_t message_type, + void* data, int32_t length, + bool end_of_message) { + if (length < 0 || (length > 0 && data == nullptr) || + (message_type != http::kWebSocketText && + message_type != http::kWebSocketBinary)) { + return -1; + } + auto ws = http::FindWebSocket(handle); + if (!ws) { + return -1; + } + + std::function notify_backend; + { + std::lock_guard lock(ws->mutex); + bool can_send = ws->state == http::kWebSocketOpen || + ws->state == http::kWebSocketCloseReceived; + if (!can_send || ws->close_requested) { + return -1; + } + if (ws->send_queue_bytes >= http::kMaxWebSocketSendQueueBytes) { + ws->send_space_armed = true; + return 0; + } + http::WebSocketMessage& partial = ws->send_partial; + if (!ws->send_partial_active) { + partial.type = static_cast(message_type); + partial.data.clear(); + ws->send_partial_active = true; + } + if (partial.data.size() + static_cast(length) > + http::kMaxWebSocketMessageBytes) { + partial = http::WebSocketMessage(); + ws->send_partial_active = false; + return -1; + } + const auto* bytes = static_cast(data); + partial.data.insert(partial.data.end(), bytes, bytes + length); + if (end_of_message) { + ws->send_queue_bytes += partial.data.size(); + ws->send_queue.push_back(std::move(partial)); + partial = http::WebSocketMessage(); + ws->send_partial_active = false; + notify_backend = ws->on_outgoing_available; + } + } + if (notify_backend) { + notify_backend(); + } + return 1; +} + +int64_t WebSocketTryReceiveInternal(int64_t handle, void* dest, + int32_t max_length) { + if (max_length < 0 || (max_length > 0 && dest == nullptr)) { + return http::kWebSocketReceiveError; + } + auto ws = http::FindWebSocket(handle); + if (!ws) { + return http::kWebSocketReceiveError; + } + + int64_t result = 0; + std::function resume_backend; + { + std::lock_guard lock(ws->mutex); + if (ws->state == http::kWebSocketAborted) { + return http::kWebSocketReceiveError; + } + if (ws->receive_queue.empty()) { + // After the caller asked to close, "closed" is reported only once the + // transport is gone, so the caller can rely on the final state. + if (ws->state == http::kWebSocketClosed || + (ws->peer_closed && !ws->close_requested)) { + return http::kWebSocketReceiveClosed; + } + ws->receive_armed = true; + return http::kWebSocketReceiveWouldBlock; + } + + http::WebSocketMessage& front = ws->receive_queue.front(); + size_t copied = (std::min)(static_cast(max_length), + front.data.size() - ws->receive_offset); + if (copied > 0) { + std::memcpy(dest, front.data.data() + ws->receive_offset, copied); + } + ws->receive_offset += copied; + ws->receive_queue_bytes -= copied; + result = static_cast(copied) << 8; + if (front.type == http::kWebSocketBinary) { + result |= http::kWebSocketReceiveBinary; + } + if (ws->receive_offset == front.data.size()) { + result |= http::kWebSocketReceiveEndOfMessage; + ws->receive_queue.pop_front(); + ws->receive_offset = 0; + } + if (ws->receive_backend_paused && + ws->receive_queue_bytes <= http::kLowWaterWebSocketReceiveBytes) { + ws->receive_backend_paused = false; + resume_backend = ws->on_receive_space_available; + } + } + if (resume_backend) { + resume_backend(); + } + return result; +} + +void WebSocketCloseInternal(int64_t handle, int32_t code, const char* reason) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return; + } + std::function notify_backend; + bool cancel = false; + { + std::lock_guard lock(ws->mutex); + if (ws->state == http::kWebSocketConnecting) { + cancel = true; + } else if ((ws->state == http::kWebSocketOpen || + ws->state == http::kWebSocketCloseReceived) && + !ws->close_requested) { + ws->close_requested = true; + ws->local_close_code = code > 0 ? code : 0; + ws->local_close_reason = reason != nullptr ? reason : ""; + if (ws->local_close_reason.size() > http::kMaxWebSocketCloseReasonBytes) { + ws->local_close_reason.resize(http::kMaxWebSocketCloseReasonBytes); + } + // A message the caller never finished cannot be sent. + ws->send_partial = http::WebSocketMessage(); + ws->send_partial_active = false; + if (ws->state == http::kWebSocketOpen) { + ws->state = http::kWebSocketCloseSent; + } + notify_backend = ws->on_outgoing_available; + } + } + if (cancel) { + http::CancelWebSocket(ws); + } else if (notify_backend) { + notify_backend(); + } +} + +int32_t WebSocketGetStateInternal(int64_t handle) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return http::kWebSocketAborted; + } + std::lock_guard lock(ws->mutex); + return static_cast(ws->state); +} + +int32_t WebSocketGetCloseCodeInternal(int64_t handle) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return 0; + } + std::lock_guard lock(ws->mutex); + return ws->close_code; +} + +std::string WebSocketGetCloseReasonInternal(int64_t handle) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return std::string(); + } + std::lock_guard lock(ws->mutex); + return ws->close_reason; +} + +std::string WebSocketGetErrorInternal(int64_t handle) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return std::string(); + } + std::lock_guard lock(ws->mutex); + return ws->error_message; +} + +int32_t WebSocketGetErrorClassInternal(int64_t handle) { + auto ws = http::FindWebSocket(handle); + if (!ws) { + return http::kHttpErrorOther; + } + std::lock_guard lock(ws->mutex); + return static_cast(ws->error_class); +} + +void WebSocketCancelInternal(int64_t handle) { + http::CancelWebSocket(http::FindWebSocket(handle)); +} + +void WebSocketDestroyInternal(int64_t handle) { + http::CancelWebSocket(http::FindWebSocket(handle)); + auto& reg = http::GetWebSocketRegistry(); + std::lock_guard lock(reg.mutex); + reg.sockets.erase(handle); +} + +} // namespace firebase diff --git a/app/http/websocket_curl.cc b/app/http/websocket_curl.cc new file mode 100644 index 0000000000..e8031345bf --- /dev/null +++ b/app/http/websocket_curl.cc @@ -0,0 +1,762 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// libcurl WebSocket backend. +// +// Every socket is an easy handle on one multi handle driven by one worker +// thread, so connecting, sending, and receiving never block each other. +// libcurl's callback model is used: +// - Receiving: `CURLOPT_WRITEFUNCTION` gets pieces of frames and +// `curl_ws_meta` describes them. Frames are reassembled into messages here. +// Returning `CURL_WRITEFUNC_PAUSE` stops reading from the socket while the +// shared receive queue is full. +// - Sending: `CURLOPT_READFUNCTION` (with `CURLOPT_UPLOAD`) announces each +// frame with `curl_ws_start_frame` and then supplies its payload. +// Returning `CURL_READFUNC_PAUSE` parks the sender until there is +// something to send. +// - Pings: in this model libcurl only queues its automatic pong behind the +// next outgoing frame, so `CURLWS_NOAUTOPONG` is set and the pong is sent +// from here. A ping is sent after a period without traffic. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport_curl_internal.h" +#include "app/http/websocket.h" +#include "app/rest/curl/curl_handles.h" +#include "curl/curl.h" + +namespace firebase { +namespace http { +namespace { + +using ::firebase::rest::curl::ApplyOpt; +using Clock = std::chrono::steady_clock; + +// Once both Close frames were exchanged the server is expected to close the +// connection (RFC 6455 section 7.1.1). The client closes it after this long. +constexpr std::chrono::seconds kCloseGrace{1}; + +// A frame on its way out. `flags` is one of CURLWS_TEXT, CURLWS_BINARY, +// CURLWS_PING, CURLWS_PONG, or CURLWS_CLOSE. +struct OutgoingFrame { + unsigned int flags = 0; + std::vector payload; +}; + +// Builds a Close frame payload. Without a status code, or with the "no status" +// code that must not appear on the wire, the payload is empty. +std::vector EncodeClosePayload(int32_t code, std::string_view reason) { + std::vector payload; + if (code <= 0 || code == kWebSocketCloseNoStatus) { + return payload; + } + payload.reserve(2 + reason.size()); + payload.push_back(static_cast((code >> 8) & 0xFF)); + payload.push_back(static_cast(code & 0xFF)); + payload.insert(payload.end(), reason.begin(), reason.end()); + return payload; +} + +// One socket. Only the worker thread touches it. +struct CurlWebSocket { + std::shared_ptr ws; + ::firebase::rest::curl::UniqueEasy easy; + ::firebase::rest::curl::UniqueSList headers; + char error_buf[CURL_ERROR_SIZE] = {}; + + // Opening handshake. + int32_t status = 0; + std::string subprotocol; + std::string handshake_error; + bool open = false; + + // Receiving. `frame_received` counts the payload bytes seen of the frame + // that is arriving; `message` collects the data frames of one message and + // `control` the payload of one control frame. + bool receive_paused = false; + bool receive_blocked = false; + bool wants_receive = false; + curl_off_t frame_received = 0; + bool message_active = false; + WebSocketMessageType message_type = kWebSocketText; + std::vector message; + std::vector control; + bool peer_closed = false; + bool discard_input = false; + + // Sending. `control_out` holds pongs, keepalive pings, and a Close sent + // after a protocol failure; `out` is the frame being handed to libcurl. + bool send_paused = false; + bool wants_send = false; + std::deque control_out; + OutgoingFrame out; + size_t out_offset = 0; + bool out_active = false; + bool close_sent = false; + + // Set after a protocol failure was reported: the socket only lingers to + // deliver its Close frame. + bool failing = false; + + Clock::time_point last_activity; + std::optional close_deadline; +}; + +void StartCloseGrace(CurlWebSocket* t) { + if (!t->close_deadline) { + t->close_deadline = Clock::now() + kCloseGrace; + } +} + +size_t OnWebSocketHeader(char* buffer, size_t size, size_t nitems, + void* userdata) { + auto* t = static_cast(userdata); + size_t total = size * nitems; + + std::string_view line(buffer, total); + while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) { + line.remove_suffix(1); + } + + if (line.empty()) { + if (t->status == 101 && !t->open) { + const auto& requested = t->ws->subprotocols; + if (!t->subprotocol.empty() && + std::find(requested.begin(), requested.end(), t->subprotocol) == + requested.end()) { + t->handshake_error = + "The server selected a WebSocket subprotocol that was not " + "requested."; + return 0; + } + t->open = true; + t->last_activity = Clock::now(); + t->ws->MarkOpen(t->subprotocol); + } + return total; + } + + if (line.size() >= 5 && line.substr(0, 5) == "HTTP/") { + t->status = 0; + t->subprotocol.clear(); + size_t space = line.find(' '); + if (space != std::string_view::npos) { + std::string_view rest = TrimAsciiWhitespace(line.substr(space + 1)); + std::string_view code = rest.substr(0, rest.find(' ')); + int32_t parsed = 0; + auto [end, ec] = + std::from_chars(code.data(), code.data() + code.size(), parsed); + if (ec == std::errc() && parsed > 0) { + t->status = parsed; + } + } + return total; + } + + size_t colon = line.find(':'); + if (colon != std::string_view::npos && + AsciiEqualsIgnoreCase(TrimAsciiWhitespace(line.substr(0, colon)), + "Sec-WebSocket-Protocol")) { + std::string_view value = TrimAsciiWhitespace(line.substr(colon + 1)); + t->subprotocol.assign(value.data(), value.size()); + } + return total; +} + +// A message larger than the limit is arriving: report the failure now and +// linger only to tell the peer why. +void FailMessageTooBig(CurlWebSocket* t) { + t->discard_input = true; + t->message_active = false; + t->message = std::vector(); + t->control_out.clear(); + t->control_out.push_back( + {CURLWS_CLOSE, + EncodeClosePayload(kWebSocketCloseMessageTooBig, "Message too big")}); + t->failing = true; + t->wants_send = true; + StartCloseGrace(t); + t->ws->MarkFailed("Received a WebSocket message larger than 16 MiB.", + kHttpErrorOther); +} + +void HandlePeerClose(CurlWebSocket* t) { + int32_t code = kWebSocketCloseNoStatus; + std::string_view reason; + if (t->control.size() >= 2) { + code = (static_cast(t->control[0]) << 8) | t->control[1]; + reason = + std::string_view(reinterpret_cast(t->control.data()) + 2, + t->control.size() - 2); + } + t->peer_closed = true; + t->discard_input = true; + t->ws->MarkPeerClosed(code, reason); + if (t->close_sent) { + StartCloseGrace(t); + } +} + +size_t OnWebSocketWrite(char* ptr, size_t size, size_t nmemb, void* userdata) { + auto* t = static_cast(userdata); + size_t total = size * nmemb; + const curl_ws_frame* meta = curl_ws_meta(t->easy.get()); + if (meta == nullptr || t->discard_input) { + return total; + } + // A paused write is delivered again later. An empty frame has nothing to + // deliver again, so it is never refused. + if (t->receive_blocked && total > 0) { + t->receive_paused = true; + return CURL_WRITEFUNC_PAUSE; + } + t->last_activity = Clock::now(); + + // libcurl may split one frame over several calls, and one piece it + // describes over several more, so progress is counted here. + const curl_off_t frame_length = + meta->offset + static_cast(meta->len) + meta->bytesleft; + const bool frame_start = t->frame_received == 0; + const bool is_data = (meta->flags & (CURLWS_TEXT | CURLWS_BINARY)) != 0; + + if (is_data) { + if (frame_start) { + if (!t->message_active) { + t->message_active = true; + t->message_type = + (meta->flags & CURLWS_BINARY) ? kWebSocketBinary : kWebSocketText; + t->message.clear(); + } + if (static_cast(frame_length) > + kMaxWebSocketMessageBytes - t->message.size()) { + FailMessageTooBig(t); + return total; + } + } + t->message.insert(t->message.end(), ptr, ptr + total); + } else { + if (frame_start) { + t->control.clear(); + } + t->control.insert(t->control.end(), ptr, ptr + total); + } + + t->frame_received += static_cast(total); + if (t->frame_received < frame_length) { + return total; + } + t->frame_received = 0; + + if (is_data) { + if ((meta->flags & CURLWS_CONT) == 0) { + t->message_active = false; + if (t->ws->PushReceivedMessage(t->message_type, std::move(t->message))) { + t->receive_blocked = true; + } + t->message = std::vector(); + } + } else if (meta->flags & CURLWS_PING) { + t->control_out.push_back({CURLWS_PONG, std::move(t->control)}); + t->control = std::vector(); + t->wants_send = true; + } else if (meta->flags & CURLWS_CLOSE) { + HandlePeerClose(t); + } + return total; +} + +// Picks the next frame to send into `t->out`. Returns false if there is none. +bool NextOutgoingFrame(CurlWebSocket* t) { + if (t->close_sent) { + return false; // Nothing may follow a Close frame. + } + if (!t->control_out.empty()) { + t->out = std::move(t->control_out.front()); + t->control_out.pop_front(); + return true; + } + if (t->failing || !t->open) { + return false; + } + WebSocketOperation::Outgoing next = t->ws->PopOutgoing(); + switch (next.kind) { + case WebSocketOperation::Outgoing::kMessage: + t->out.flags = + next.message.type == kWebSocketBinary ? CURLWS_BINARY : CURLWS_TEXT; + t->out.payload = std::move(next.message.data); + return true; + case WebSocketOperation::Outgoing::kClose: + t->out.flags = CURLWS_CLOSE; + t->out.payload = EncodeClosePayload(next.close_code, next.close_reason); + return true; + case WebSocketOperation::Outgoing::kNone: + return false; + } + return false; +} + +size_t OnWebSocketRead(char* buffer, size_t size, size_t nitems, + void* userdata) { + auto* t = static_cast(userdata); + size_t capacity = size * nitems; + + if (!t->out_active) { + if (!NextOutgoingFrame(t)) { + t->send_paused = true; + return CURL_READFUNC_PAUSE; + } + if (curl_ws_start_frame(t->easy.get(), t->out.flags, + static_cast(t->out.payload.size())) != + CURLE_OK) { + return CURL_READFUNC_ABORT; + } + t->out_active = true; + t->out_offset = 0; + } + + // After `curl_ws_start_frame`, returning 0 for an empty frame is not taken + // as the end of the upload. + size_t n = (std::min)(capacity, t->out.payload.size() - t->out_offset); + if (n > 0) { + std::memcpy(buffer, t->out.payload.data() + t->out_offset, n); + } + t->out_offset += n; + if (t->out_offset == t->out.payload.size()) { + t->out_active = false; + t->out.payload = std::vector(); + if (t->out.flags == CURLWS_CLOSE) { + t->close_sent = true; + t->control_out.clear(); + if (t->peer_closed || t->failing) { + StartCloseGrace(t); + } + } + } + t->last_activity = Clock::now(); + return n; +} + +class CurlWebSocketEngine { + public: + static CurlWebSocketEngine& Instance() { + static auto* engine = new CurlWebSocketEngine(); + return *engine; + } + + void Start(const std::shared_ptr& ws) { + int64_t id = ws->id; + { + std::lock_guard lock(ws->mutex); + if (ws->state != kWebSocketConnecting) { + return; + } + ws->on_outgoing_available = [this, id]() { + Enqueue(&pending_send_resumes_, id); + }; + ws->on_receive_space_available = [this, id]() { + Enqueue(&pending_receive_resumes_, id); + }; + ws->on_cancel = [this, id]() { Enqueue(&pending_cancels_, id); }; + } + { + std::lock_guard lock(mutex_); + pending_starts_.push_back(ws); + } + WakeLoop(); + } + + private: + CurlWebSocketEngine() { + // Hold a reference on libcurl's global state for the life of the process, + // like the HTTP engine, so App::Dispose() never tears it down underneath + // an open socket. + ::firebase::rest::curl::AcquireCurlGlobal(); + multi_.reset(curl_multi_init()); + worker_ = std::thread([this]() { RunLoop(); }); + worker_.detach(); + } + + void Enqueue(std::vector* queue, int64_t id) { + { + std::lock_guard lock(mutex_); + queue->push_back(id); + } + WakeLoop(); + } + + void WakeLoop() { + if (multi_ != nullptr) { + curl_multi_wakeup(multi_.get()); + } + cv_.notify_one(); + } + + CurlWebSocket* Find(int64_t id) { + auto it = active_.find(id); + return it != active_.end() ? it->second.get() : nullptr; + } + + // Drops the connection of `id` at once. + void Remove(int64_t id) { + auto it = active_.find(id); + if (it != active_.end()) { + curl_multi_remove_handle(multi_.get(), it->second->easy.get()); + active_.erase(it); + } + } + + std::unique_ptr BuildSocket( + const std::shared_ptr& ws) { + ::firebase::rest::curl::UniqueEasy easy(curl_easy_init()); + if (easy == nullptr) { + ws->MarkFailed("Failed to initialize native libcurl handle.", + kHttpErrorOther); + return nullptr; + } + if (auto setup_error = + ApplyCurlConnectionOptions(easy.get(), "ws,wss", ws->proxy_url)) { + ws->MarkFailed(setup_error->message, setup_error->error_class); + return nullptr; + } + + auto t = std::make_unique(); + t->ws = ws; + + curl_slist* header_list = nullptr; + auto append_header = [&header_list](const std::string& line) { + curl_slist* next = curl_slist_append(header_list, line.c_str()); + if (next != nullptr) { + header_list = next; + } + return next != nullptr; + }; + bool headers_ok = true; + for (const auto& kv : ws->request_headers) { + headers_ok = headers_ok && append_header(kv.first + ": " + kv.second); + } + if (!ws->subprotocols.empty()) { + std::string line = "Sec-WebSocket-Protocol: "; + for (size_t i = 0; i < ws->subprotocols.size(); ++i) { + if (i > 0) { + line.append(", "); + } + line.append(ws->subprotocols[i]); + } + headers_ok = headers_ok && append_header(line); + } + t->headers.reset(header_list); + if (!headers_ok) { + ws->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + + CURL* raw_easy = easy.get(); + CURLcode opt_err = CURLE_OK; + ApplyOpt(raw_easy, CURLOPT_ERRORBUFFER, t->error_buf, &opt_err); + ApplyOpt(raw_easy, CURLOPT_URL, ws->url.c_str(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_PRIVATE, t.get(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_HEADERFUNCTION, OnWebSocketHeader, &opt_err); + ApplyOpt(raw_easy, CURLOPT_HEADERDATA, t.get(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_WRITEFUNCTION, OnWebSocketWrite, &opt_err); + ApplyOpt(raw_easy, CURLOPT_WRITEDATA, t.get(), &opt_err); + // Sending through the read callback needs CURLOPT_UPLOAD; the opening + // request is still a GET. + ApplyOpt(raw_easy, CURLOPT_READFUNCTION, OnWebSocketRead, &opt_err); + ApplyOpt(raw_easy, CURLOPT_READDATA, t.get(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_UPLOAD, 1L, &opt_err); + ApplyOpt(raw_easy, CURLOPT_WS_OPTIONS, + static_cast(CURLWS_NOAUTOPONG), // NOLINT + &opt_err); + if (t->headers != nullptr) { + ApplyOpt(raw_easy, CURLOPT_HTTPHEADER, t->headers.get(), &opt_err); + } + if (opt_err != CURLE_OK) { + ws->MarkFailed(curl_easy_strerror(opt_err), + ClassifyCurlError(opt_err, /*canceled=*/false)); + return nullptr; + } + + t->easy = std::move(easy); + return t; + } + + void StartSocket(const std::shared_ptr& ws) { + { + std::lock_guard lock(ws->mutex); + if (ws->state != kWebSocketConnecting) { + return; // Canceled before the worker got to it. + } + } + if (active_.find(ws->id) != active_.end()) { + return; + } + if (multi_ == nullptr) { + ws->MarkFailed("Native libcurl multi engine failed to initialize.", + kHttpErrorOther); + return; + } + auto t = BuildSocket(ws); + if (!t) { + return; + } + CURLMcode mc = curl_multi_add_handle(multi_.get(), t->easy.get()); + if (mc != CURLM_OK) { + ws->MarkFailed(curl_multi_strerror(mc), kHttpErrorOther); + return; + } + active_.emplace(ws->id, std::move(t)); + } + + // Reports how a finished transfer ended. + static void Complete(const CurlWebSocket& t, CURLcode result) { + if (t.failing) { + return; // Already reported. + } + if (t.peer_closed) { + t.ws->MarkClosed(); + return; + } + if (!t.handshake_error.empty()) { + t.ws->MarkFailed(t.handshake_error, kHttpErrorOther); + } else if (result != CURLE_OK) { + t.ws->MarkFailed( + t.error_buf[0] != '\0' ? t.error_buf : curl_easy_strerror(result), + ClassifyCurlError(result, /*canceled=*/false)); + } else if (t.open) { + t.ws->MarkFailed("The WebSocket connection ended without a Close frame.", + kHttpErrorConnect); + } else { + t.ws->MarkFailed("The WebSocket handshake did not complete.", + kHttpErrorOther); + } + } + + void FailAllActive(CURLMcode mc) { + std::string err = curl_multi_strerror(mc); + std::unordered_map> failed; + failed.swap(active_); + for (auto& kv : failed) { + curl_multi_remove_handle(multi_.get(), kv.second->easy.get()); + kv.second->ws->MarkFailed(err, kHttpErrorOther); + } + } + + // Sends keepalive pings that are due and closes connections whose grace + // period after the closing handshake ran out. + void RunTimers() { + const Clock::time_point now = Clock::now(); + const auto keepalive = WebSocketKeepaliveInterval(); + std::vector expired; + for (auto& kv : active_) { + CurlWebSocket& t = *kv.second; + if (t.close_deadline) { + if (now >= *t.close_deadline) { + expired.push_back(kv.first); + } + } else if (IsKeepaliveCandidate(t) && + now - t.last_activity >= keepalive) { + t.control_out.push_back({CURLWS_PING, {}}); + t.wants_send = true; + t.last_activity = now; + } + } + for (int64_t id : expired) { + auto it = active_.find(id); + std::unique_ptr t = std::move(it->second); + curl_multi_remove_handle(multi_.get(), t->easy.get()); + active_.erase(it); + Complete(*t, CURLE_OK); + } + } + + static bool IsKeepaliveCandidate(const CurlWebSocket& t) { + bool closing = t.peer_closed || t.close_sent || + (t.out_active && t.out.flags == CURLWS_CLOSE); + return t.open && !closing && t.control_out.empty(); + } + + // How long the loop may wait in poll before a timer needs it. + int NextTimeoutMs() const { + const Clock::time_point now = Clock::now(); + const auto keepalive = WebSocketKeepaliveInterval(); + Clock::duration wait = std::chrono::seconds(1); + for (const auto& kv : active_) { + const CurlWebSocket& t = *kv.second; + if (t.close_deadline) { + wait = (std::min)(wait, *t.close_deadline - now); + } else if (IsKeepaliveCandidate(t)) { + wait = (std::min)(wait, t.last_activity + keepalive - now); + } + } + auto ms = + std::chrono::duration_cast(wait).count(); + // Round up so the loop does not spin just before a deadline. + return ms < 0 ? 0 : static_cast(ms) + 1; + } + + // Resumes the directions that asked for it. Returns true if any transfer + // was resumed. + bool ApplyResumes() { + bool any = false; + for (auto& kv : active_) { + CurlWebSocket& t = *kv.second; + bool changed = false; + if (t.wants_send) { + t.wants_send = false; + changed = changed || t.send_paused; + t.send_paused = false; + } + if (t.wants_receive) { + t.wants_receive = false; + changed = changed || t.receive_paused; + t.receive_paused = false; + } + if (changed) { + any = true; + // libcurl may call the write callback from inside this call; the + // flags above are already in their new state. + curl_easy_pause( + t.easy.get(), + (t.send_paused ? CURLPAUSE_SEND : CURLPAUSE_SEND_CONT) | + (t.receive_paused ? CURLPAUSE_RECV : CURLPAUSE_RECV_CONT)); + } + } + return any; + } + + void ReadCompletions() { + int msgs_left = 0; + while (CURLMsg* msg = curl_multi_info_read(multi_.get(), &msgs_left)) { + if (msg->msg != CURLMSG_DONE) { + continue; + } + // Copy what is needed before curl_multi_remove_handle() invalidates + // `msg`. + CURL* easy_handle = msg->easy_handle; + CURLcode result = msg->data.result; + CurlWebSocket* raw = nullptr; + curl_easy_getinfo(easy_handle, CURLINFO_PRIVATE, &raw); + curl_multi_remove_handle(multi_.get(), easy_handle); + if (raw == nullptr) { + continue; + } + auto it = active_.find(raw->ws->id); + if (it == active_.end()) { + continue; + } + std::unique_ptr t = std::move(it->second); + active_.erase(it); + Complete(*t, result); + } + } + + void RunLoop() { + while (true) { + std::deque> starts; + std::vector send_resumes; + std::vector receive_resumes; + std::vector cancels; + { + std::unique_lock lock(mutex_); + if (active_.empty() && pending_starts_.empty()) { + // Resumes and cancels only matter for sockets the worker drives. + cv_.wait(lock, [this]() { return !pending_starts_.empty(); }); + } + starts.swap(pending_starts_); + send_resumes.swap(pending_send_resumes_); + receive_resumes.swap(pending_receive_resumes_); + cancels.swap(pending_cancels_); + } + + for (int64_t id : cancels) { + Remove(id); + } + for (const auto& ws : starts) { + StartSocket(ws); + } + for (int64_t id : send_resumes) { + if (CurlWebSocket* t = Find(id)) { + t->wants_send = true; + } + } + for (int64_t id : receive_resumes) { + if (CurlWebSocket* t = Find(id)) { + t->receive_blocked = false; + t->wants_receive = true; + } + } + RunTimers(); + ApplyResumes(); + if (active_.empty()) { + continue; + } + + int still_running = 0; + CURLMcode perform_rc = curl_multi_perform(multi_.get(), &still_running); + if (perform_rc != CURLM_OK) { + FailAllActive(perform_rc); + continue; + } + ReadCompletions(); + + // A callback may have queued a pong or a Close; send it before waiting. + if (ApplyResumes() || active_.empty()) { + continue; + } + int numfds = 0; + CURLMcode poll_rc = + curl_multi_poll(multi_.get(), nullptr, 0, NextTimeoutMs(), &numfds); + if (poll_rc != CURLM_OK) { + FailAllActive(poll_rc); + } + } + } + + ::firebase::rest::curl::UniqueMulti multi_; + std::mutex mutex_; + std::condition_variable cv_; + std::deque> pending_starts_; + std::vector pending_send_resumes_; + std::vector pending_receive_resumes_; + std::vector pending_cancels_; + std::unordered_map> active_; + std::thread worker_; +}; + +} // namespace + +void StartPlatformWebSocket(const std::shared_ptr& ws) { + CurlWebSocketEngine::Instance().Start(ws); +} + +} // namespace http +} // namespace firebase diff --git a/build_scripts/desktop/package.sh b/build_scripts/desktop/package.sh index d58de21eb9..ebde36e167 100755 --- a/build_scripts/desktop/package.sh +++ b/build_scripts/desktop/package.sh @@ -207,6 +207,7 @@ fi # Library dependencies to merge. Each should be a whitespace-delimited list of path globs. readonly deps_firebase_app=" */${prefix}firebase_rest_lib.${ext} +*/${prefix}firebase_http_transport.${ext} " readonly deps_hidden_firebase_app=" */curl-build/lib/${subdir}libcurl${suffix}.${ext} diff --git a/cmake/external/CMakeLists.txt b/cmake/external/CMakeLists.txt index 3cfdd8e830..a9dcf30edb 100644 --- a/cmake/external/CMakeLists.txt +++ b/cmake/external/CMakeLists.txt @@ -34,6 +34,16 @@ if (${FIREBASE_EXTERNAL_PLATFORM} STREQUAL "DESKTOP") include(zlib) endif() +# The Android native HTTP transport (app/http), when it is built, links libcurl +# and its own BoringSSL statically. The platform is quoted because the NDK +# toolchain defines a variable named ANDROID, which if() would otherwise +# dereference. +if ("${FIREBASE_EXTERNAL_PLATFORM}" STREQUAL "ANDROID" AND + FIREBASE_ANDROID_HTTP_CURL) + include(boringssl_android) + include(curl) +endif() + # Support files for the test framework. if(FIREBASE_CPP_BUILD_TESTS OR FIREBASE_CPP_BUILD_STUB_TESTS) include(googletest) diff --git a/cmake/external/boringssl_android.cmake b/cmake/external/boringssl_android.cmake new file mode 100644 index 0000000000..59b4fa33b6 --- /dev/null +++ b/cmake/external/boringssl_android.cmake @@ -0,0 +1,50 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# BoringSSL used only by the Android build of the native HTTP transport +# (app/http), where libcurl links it statically. Desktop builds keep the pin in +# boringssl.cmake. + +include(ExternalProject) + +if(TARGET boringssl_android OR NOT DOWNLOAD_BORINGSSL_ANDROID) + return() +endif() + +# BoringSSL release 0.20260929.0, committed 2026-09-29. Supports the +# X25519MLKEM768 key-exchange group and ships pregenerated assembly, so it +# builds with CMake and the NDK toolchain alone (no Go, Perl or NASM). +# +# This is the newest release that libcurl 8.23.0 compiles against: from +# 0.20261020.0 on, BoringSSL declares ASN1_STRING_get_length(), which collides +# with the static fallback of that name in curl 8.23.0's lib/vtls/openssl.c. +# Move this pin forward together with the libcurl pin in curl.cmake. +set(commit 427ec40cc8edc545253289232e885708c409e5ea) + +ExternalProject_Add( + boringssl_android + + DOWNLOAD_DIR ${FIREBASE_DOWNLOAD_DIR} + DOWNLOAD_NAME boringssl-${commit}.tar.gz + URL https://github.com/google/boringssl/archive/${commit}.tar.gz + URL_HASH SHA256=54f6eacb3121a1bf7690e185f987ee5c30a6aa0b42b6dad17872992be113cd9b + + PREFIX ${PROJECT_BINARY_DIR} + + CONFIGURE_COMMAND "" + BUILD_COMMAND "" + INSTALL_COMMAND "" + TEST_COMMAND "" + HTTP_HEADER "${EXTERNAL_PROJECT_HTTP_HEADER}" +) diff --git a/cmake/external_rules.cmake b/cmake/external_rules.cmake index 813f9a779c..c99605d326 100644 --- a/cmake/external_rules.cmake +++ b/cmake/external_rules.cmake @@ -47,6 +47,7 @@ function(download_external_sources) endif() endfunction() check_use_local_directory(BORINGSSL) + check_use_local_directory(BORINGSSL_ANDROID) check_use_local_directory(CURL) check_use_local_directory(FLATBUFFERS) check_use_local_directory(ZLIB) @@ -77,7 +78,9 @@ function(download_external_sources) -DCMAKE_INSTALL_PREFIX=${FIREBASE_INSTALL_DIR} -DFIREBASE_DOWNLOAD_DIR=${FIREBASE_DOWNLOAD_DIR} -DFIREBASE_EXTERNAL_PLATFORM=${external_platform} + -DFIREBASE_ANDROID_HTTP_CURL=${FIREBASE_ANDROID_HTTP_CURL} -DDOWNLOAD_BORINGSSL=${DOWNLOAD_BORINGSSL} + -DDOWNLOAD_BORINGSSL_ANDROID=${DOWNLOAD_BORINGSSL_ANDROID} -DDOWNLOAD_CURL=${DOWNLOAD_CURL} -DDOWNLOAD_FLATBUFFERS=${DOWNLOAD_FLATBUFFERS} -DDOWNLOAD_GOOGLETEST=${FIREBASE_DOWNLOAD_GTEST} @@ -271,6 +274,90 @@ function(build_external_dependencies) endif() endfunction() +# Builds, at configure time, the BoringSSL that the Android native HTTP +# transport (app/http) links statically through libcurl. It has to exist before +# libcurl is configured, because libcurl's configure checks link against it. +# Sets BORINGSSL_ANDROID_SOURCE_DIR and BORINGSSL_ANDROID_BINARY_DIR in the +# caller's scope. +function(build_android_boringssl) + if(NOT EXISTS "${BORINGSSL_ANDROID_SOURCE_DIR}") + set(BORINGSSL_ANDROID_SOURCE_DIR + "${PROJECT_BINARY_DIR}/external/src/boringssl_android") + endif() + if(NOT EXISTS "${BORINGSSL_ANDROID_SOURCE_DIR}/CMakeLists.txt") + message(FATAL_ERROR "BoringSSL for the Android HTTP transport was not " + "downloaded to ${BORINGSSL_ANDROID_SOURCE_DIR}. See " + "${PROJECT_BINARY_DIR}/external/output_cmake_build.txt") + endif() + set(BORINGSSL_ANDROID_BINARY_DIR + "${PROJECT_BINARY_DIR}/external/src/boringssl_android-build") + file(MAKE_DIRECTORY "${BORINGSSL_ANDROID_BINARY_DIR}") + + # As in build_external_dependencies, drop the environment of the current + # build so it cannot leak into the sub-build. + if(CMAKE_HOST_SYSTEM_NAME STREQUAL "Windows") + set(ENV_COMMAND "") + else() + set(ENV_COMMAND env -i PATH=$ENV{PATH} HOME=$ENV{HOME}) + endif() + + # Always an optimized build, whatever the SDK's build type is: unoptimized + # cryptography is far slower. Symbols are hidden so that the shared library + # the transport is linked into does not export them. + execute_process( + COMMAND + ${ENV_COMMAND} ${CMAKE_COMMAND} + -G ${CMAKE_GENERATOR} + -DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM} + -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE} + -DANDROID_ABI=${ANDROID_ABI} + -DANDROID_PLATFORM=${ANDROID_PLATFORM} + -DANDROID_STL=${ANDROID_STL} + -DCMAKE_BUILD_TYPE=Release + -DBUILD_SHARED_LIBS=OFF + -DBUILD_TESTING=OFF + -DCMAKE_POSITION_INDEPENDENT_CODE=ON + -DCMAKE_C_VISIBILITY_PRESET=hidden + -DCMAKE_CXX_VISIBILITY_PRESET=hidden + -DCMAKE_VISIBILITY_INLINES_HIDDEN=ON + ${BORINGSSL_ANDROID_SOURCE_DIR} + WORKING_DIRECTORY ${BORINGSSL_ANDROID_BINARY_DIR} + OUTPUT_FILE ${BORINGSSL_ANDROID_BINARY_DIR}/output_cmake_config.txt + ERROR_FILE ${BORINGSSL_ANDROID_BINARY_DIR}/output_cmake_config.txt + RESULT_VARIABLE boringssl_configure_status + ) + if(NOT boringssl_configure_status EQUAL 0) + message(FATAL_ERROR "Android BoringSSL configure failed " + "(${boringssl_configure_status}). See " + "${BORINGSSL_ANDROID_BINARY_DIR}/output_cmake_config.txt") + endif() + + # Run the build in parallel if we know how. + if(CMAKE_GENERATOR STREQUAL "Unix Makefiles") + set(cmake_build_args -- -j) + endif() + + execute_process( + COMMAND + ${ENV_COMMAND} ${CMAKE_COMMAND} --build . --target ssl crypto + ${cmake_build_args} + WORKING_DIRECTORY ${BORINGSSL_ANDROID_BINARY_DIR} + OUTPUT_FILE ${BORINGSSL_ANDROID_BINARY_DIR}/output_cmake_build.txt + ERROR_FILE ${BORINGSSL_ANDROID_BINARY_DIR}/output_cmake_build.txt + RESULT_VARIABLE boringssl_build_status + ) + if(NOT boringssl_build_status EQUAL 0) + message(FATAL_ERROR "Android BoringSSL build failed " + "(${boringssl_build_status}). See " + "${BORINGSSL_ANDROID_BINARY_DIR}/output_cmake_build.txt") + endif() + + set(BORINGSSL_ANDROID_SOURCE_DIR "${BORINGSSL_ANDROID_SOURCE_DIR}" + PARENT_SCOPE) + set(BORINGSSL_ANDROID_BINARY_DIR "${BORINGSSL_ANDROID_BINARY_DIR}" + PARENT_SCOPE) +endfunction() + # Populates directory variables for the given name to the location that name # would be in after a call to download_external_sources, if the variable is # not already a valid directory.