From e5f0561683d11bc45d839ffa7df9a6ccba33e173 Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Thu, 26 Nov 2026 22:18:28 +0000 Subject: [PATCH 01/16] [App] Add cross-platform streaming native HTTP transport (firebase_http_transport) Adds a shared platform-native streaming HTTP transport under app/http/ backed by: - Desktop: libcurl multi-handle (sharing firebase_rest_lib curl/TLS policy) - Apple (iOS/tvOS): ARC NSURLSession with NSStream bound-stream uploads - Android: JNI HttpURLConnection on a bounded worker pool + async cancel dispatcher Includes a flat C/SWIG handle bridge (app/http/http_bridge.h) for Unity consumption and desktop unit + loopback HTTP/SSE gtest coverage. --- app/CMakeLists.txt | 4 + app/http/CMakeLists.txt | 92 ++ app/http/http_bridge.h | 90 ++ app/http/http_transport.h | 232 ++++ app/http/http_transport_android.cc | 1193 ++++++++++++++++++ app/http/http_transport_apple.mm | 803 ++++++++++++ app/http/http_transport_common.cc | 850 +++++++++++++ app/http/http_transport_curl.cc | 660 ++++++++++ app/http/tests/CMakeLists.txt | 31 + app/http/tests/http_transport_common_test.cc | 292 +++++ app/http/tests/http_transport_curl_test.cc | 1067 ++++++++++++++++ build_scripts/desktop/package.sh | 1 + 12 files changed, 5315 insertions(+) create mode 100644 app/http/CMakeLists.txt create mode 100644 app/http/http_bridge.h create mode 100644 app/http/http_transport.h create mode 100644 app/http/http_transport_android.cc create mode 100644 app/http/http_transport_apple.mm create mode 100644 app/http/http_transport_common.cc create mode 100644 app/http/http_transport_curl.cc create mode 100644 app/http/tests/CMakeLists.txt create mode 100644 app/http/tests/http_transport_common_test.cc create mode 100644 app/http/tests/http_transport_curl_test.cc diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 5cc8f879b7..5b2c268308 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -390,6 +390,10 @@ if (NOT ANDROID AND NOT IOS) add_subdirectory(rest) endif() +# Cross-platform native streaming HTTP transport (Desktop libcurl, iOS/tvOS +# NSURLSession, Android JNI HttpURLConnection). +add_subdirectory(http) + 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..fa7c31af34 --- /dev/null +++ b/app/http/CMakeLists.txt @@ -0,0 +1,92 @@ +# 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) + +if(ANDROID) + list(APPEND http_transport_SRCS http_transport_android.cc) +elseif(IOS) + list(APPEND http_transport_SRCS http_transport_apple.mm) +else() + list(APPEND http_transport_SRCS http_transport_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) + # Android uses JNI HttpURLConnection directly via firebase_app's JNI helpers. +elseif(IOS) + set_source_files_properties(http_transport_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..0bfa842e45 --- /dev/null +++ b/app/http/http_bridge.h @@ -0,0 +1,90 @@ +/* + * 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 bytes accepted (`0` when full), or `-1` on failure or +// cancellation. +int32_t HttpTryWriteRequestBodyInternal(int64_t handle, void* data, + int32_t length); + +// Marks the end of the request body stream for `handle`. +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 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); + +// 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); + +// 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(); + +} // 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..724e7c2084 --- /dev/null +++ b/app/http/http_transport.h @@ -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. + */ + +// Cross-platform streaming HTTP transport backed by platform-native stacks: +// - Desktop (Linux / macOS / Windows): libcurl multi-handle (sharing +// `firebase_rest_lib`'s TLS policy and ref-counted curl initialization). +// - Apple mobile (iOS / tvOS): ARC NSURLSession with bound-stream uploads. +// - Android: JNI HttpURLConnection on a bounded worker thread pool. +// +// Supports full-duplex streaming uploads and downloads with bounded socket +// backpressure, immediate incremental delivery for Server-Sent Events (SSE), +// deterministic cancellation, and uniform RFC 3986 redirect/credential policy. + +#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 + +#if defined(__ANDROID__) +#include +#endif // defined(__ANDROID__) + +#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, +}; + +// 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; + +// Maximum number of HTTP redirects followed per operation across all backends. +inline constexpr int kMaxRedirects = 10; + +// 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; + +struct ByteChunk { + std::vector data; + size_t offset = 0; + + size_t remaining() const { return data.size() - offset; } +}; + +// Request parameters used when creating an `HttpOperation` from C++ directly. +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_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; + 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 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); + + // 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); +}; + +// C++17 registry entry points backing both direct C++ callers and the flat +// SWIG bridge in `http_bridge.h`. +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); + +// 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,android}`. +void StartPlatformHttpOperation(const std::shared_ptr& op); + +#if defined(__ANDROID__) +// Optionally registers the process `JavaVM*` early (e.g., from `JNI_OnLoad`). +// If not called explicitly, the Android backend falls back to resolving the +// active `JavaVM*` from `firebase::util::GetJNIEnvFromApp()`. +void SetAndroidJavaVM(JavaVM* vm); +#endif // defined(__ANDROID__) + +// 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); + +// Parses `Name\tValue\n` (or `Name: Value\n`) header lines into ordered pairs, +// preserving duplicate header names. +std::vector> ParsePackedHeaders( + std::string_view packed); + +struct UrlOrigin { + std::string scheme; + std::string host; + int port = 0; +}; + +// Parses scheme (`http` or `https` only), lowercased host, and effective port +// (`80` / `443` when omitted) from an absolute HTTP(S) URL. +std::optional ParseUrlOrigin(std::string_view url); + +bool IsHttpOrHttpsUrl(std::string_view url); +bool IsHttpsUrl(std::string_view url); +bool IsSameOrigin(std::string_view url_a, std::string_view url_b); + +// Returns true for headers that must never be forwarded across a cross-origin +// redirect (`Authorization`, `Proxy-Authorization`, `X-Firebase-AppCheck`, +// `x-goog-api-key`). +bool IsSensitiveRedirectHeader(std::string_view header_name); + +// Resolves an HTTP `Location` header against `current_url`, rejecting +// non-HTTP(S) schemes and `https` -> `http` scheme downgrades. +std::optional ResolveRedirectUrl(std::string_view current_url, + std::string_view location); + +// Parses `[http[s]://]host[:port][/...]` into `(host, port)` for proxy setup. +std::optional> ParseProxyHostPort( + std::string_view proxy_url); + +} // namespace http +} // namespace firebase + +#endif // FIREBASE_APP_HTTP_HTTP_TRANSPORT_H_ diff --git a/app/http/http_transport_android.cc b/app/http/http_transport_android.cc new file mode 100644 index 0000000000..cf5ec855c9 --- /dev/null +++ b/app/http/http_transport_android.cc @@ -0,0 +1,1193 @@ +/* + * 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 "app/http/http_transport.h" +#include "app/src/util_android.h" + +namespace firebase { +namespace http { +namespace { + +std::atomic g_android_jvm{nullptr}; + +JavaVM* ResolveJavaVM() { + JavaVM* vm = g_android_jvm.load(std::memory_order_acquire); + if (vm != nullptr) { + return vm; + } + JNIEnv* env = ::firebase::util::GetJNIEnvFromApp(); + if (env != nullptr && env->GetJavaVM(&vm) == JNI_OK && vm != nullptr) { + g_android_jvm.store(vm, std::memory_order_release); + return vm; + } + return nullptr; +} + +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; +} + +template +class LocalRef { + public: + LocalRef(JNIEnv* env, T ref) : env_(env), ref_(ref) {} + ~LocalRef() { reset(); } + + LocalRef(const LocalRef&) = delete; + LocalRef& operator=(const LocalRef&) = delete; + + LocalRef(LocalRef&& other) noexcept : env_(other.env_), ref_(other.ref_) { + other.ref_ = nullptr; + } + + LocalRef& operator=(LocalRef&& other) noexcept { + if (this != &other) { + reset(); + env_ = other.env_; + ref_ = other.ref_; + other.ref_ = nullptr; + } + return *this; + } + + T get() const { return ref_; } + explicit operator bool() const { return ref_ != nullptr; } + + void reset(T next = nullptr) { + if (ref_ != nullptr && env_ != nullptr) { + env_->DeleteLocalRef(ref_); + } + ref_ = next; + } + + private: + JNIEnv* env_ = nullptr; + T ref_ = nullptr; +}; + +struct JniCache { + bool initialized = false; + + jclass url_cls = nullptr; + jmethodID url_ctor = nullptr; + jmethodID url_open_conn = nullptr; + jmethodID url_open_conn_proxy = nullptr; + + jclass proxy_cls = nullptr; + jmethodID proxy_ctor = nullptr; + jobject proxy_type_http = nullptr; + + jclass inet_sock_addr_cls = nullptr; + jmethodID inet_sock_addr_ctor = nullptr; + + jclass http_conn_cls = nullptr; + jmethodID set_request_method = nullptr; + jmethodID set_request_property = nullptr; + jmethodID add_request_property = nullptr; + jmethodID set_use_caches = nullptr; + jmethodID set_connect_timeout = nullptr; + jmethodID set_read_timeout = nullptr; + jmethodID set_instance_follow_redirects = nullptr; + jmethodID set_do_output = nullptr; + jmethodID set_fixed_len_streaming = nullptr; + jmethodID set_chunked_streaming = nullptr; + jmethodID get_output_stream = nullptr; + jmethodID get_response_code = nullptr; + jmethodID get_response_message = nullptr; + jmethodID get_header_fields = nullptr; + jmethodID get_input_stream = nullptr; + jmethodID get_error_stream = nullptr; + jmethodID disconnect = nullptr; + + jclass output_stream_cls = nullptr; + jmethodID output_write = nullptr; + jmethodID output_flush = nullptr; + jmethodID output_close = nullptr; + + jclass input_stream_cls = nullptr; + jmethodID input_read = nullptr; + jmethodID input_close = nullptr; + + jclass map_cls = nullptr; + jmethodID map_entry_set = nullptr; + + jclass set_cls = nullptr; + jmethodID set_iterator = nullptr; + + jclass iter_cls = nullptr; + jmethodID iter_has_next = nullptr; + jmethodID iter_next = nullptr; + + jclass entry_cls = nullptr; + jmethodID entry_get_key = nullptr; + jmethodID entry_get_value = nullptr; + + jclass list_cls = nullptr; + jmethodID list_size = nullptr; + jmethodID list_get = nullptr; + + jclass throwable_cls = nullptr; + jmethodID throwable_to_string = nullptr; +}; + +JniCache& GetJniCache() { + static auto* cache = new JniCache(); + return *cache; +} + +std::string JStringToStdString(JNIEnv* env, jstring jstr) { + if (jstr == nullptr) { + return std::string(); + } + const char* chars = env->GetStringUTFChars(jstr, nullptr); + if (chars == nullptr) { + if (env->ExceptionCheck()) { + env->ExceptionClear(); + } + return std::string(); + } + std::string out(chars); + env->ReleaseStringUTFChars(jstr, chars); + return out; +} + +std::optional TakeJniException(JNIEnv* env) { + if (!env->ExceptionCheck()) { + return std::nullopt; + } + LocalRef ex(env, env->ExceptionOccurred()); + env->ExceptionClear(); + if (!ex) { + return std::string("Unknown JNI exception"); + } + auto& c = GetJniCache(); + if (c.throwable_to_string != nullptr) { + LocalRef msg(env, static_cast(env->CallObjectMethod( + ex.get(), c.throwable_to_string))); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + return std::string("Java exception thrown during HTTP request"); + } + return JStringToStdString(env, msg.get()); + } + return std::string("Java exception thrown during HTTP request"); +} + +jclass CacheGlobalClass(JNIEnv* env, const char* name) { + LocalRef local(env, env->FindClass(name)); + if (env->ExceptionCheck() || !local) { + env->ExceptionClear(); + return nullptr; + } + jobject global = env->NewGlobalRef(local.get()); + if (env->ExceptionCheck() || global == nullptr) { + env->ExceptionClear(); + return nullptr; + } + return static_cast(global); +} + +jmethodID CacheMethod(JNIEnv* env, jclass cls, const char* name, + const char* sig, bool* ok) { + if (!*ok || cls == nullptr) { + *ok = false; + return nullptr; + } + jmethodID mid = env->GetMethodID(cls, name, sig); + if (env->ExceptionCheck() || mid == nullptr) { + env->ExceptionClear(); + *ok = false; + return nullptr; + } + return mid; +} + +bool EnsureJniInitialized(JNIEnv* env) { + static std::mutex init_mutex; + std::lock_guard lock(init_mutex); + auto& c = GetJniCache(); + if (c.initialized) { + return true; + } + + bool ok = true; + c.throwable_cls = CacheGlobalClass(env, "java/lang/Throwable"); + c.throwable_to_string = CacheMethod(env, c.throwable_cls, "toString", + "()Ljava/lang/String;", &ok); + if (!ok) { + return false; + } + + c.url_cls = CacheGlobalClass(env, "java/net/URL"); + c.proxy_cls = CacheGlobalClass(env, "java/net/Proxy"); + c.inet_sock_addr_cls = CacheGlobalClass(env, "java/net/InetSocketAddress"); + c.http_conn_cls = CacheGlobalClass(env, "java/net/HttpURLConnection"); + c.output_stream_cls = CacheGlobalClass(env, "java/io/OutputStream"); + c.input_stream_cls = CacheGlobalClass(env, "java/io/InputStream"); + c.map_cls = CacheGlobalClass(env, "java/util/Map"); + c.set_cls = CacheGlobalClass(env, "java/util/Set"); + c.iter_cls = CacheGlobalClass(env, "java/util/Iterator"); + c.entry_cls = CacheGlobalClass(env, "java/util/Map$Entry"); + c.list_cls = CacheGlobalClass(env, "java/util/List"); + + if (!c.url_cls || !c.proxy_cls || !c.inet_sock_addr_cls || !c.http_conn_cls || + !c.output_stream_cls || !c.input_stream_cls || !c.map_cls || !c.set_cls || + !c.iter_cls || !c.entry_cls || !c.list_cls) { + return false; + } + + LocalRef proxy_type_cls(env, env->FindClass("java/net/Proxy$Type")); + if (env->ExceptionCheck() || !proxy_type_cls) { + env->ExceptionClear(); + return false; + } + jfieldID http_field = env->GetStaticFieldID(proxy_type_cls.get(), "HTTP", + "Ljava/net/Proxy$Type;"); + if (env->ExceptionCheck() || http_field == nullptr) { + env->ExceptionClear(); + return false; + } + LocalRef http_enum( + env, env->GetStaticObjectField(proxy_type_cls.get(), http_field)); + if (env->ExceptionCheck() || !http_enum) { + env->ExceptionClear(); + return false; + } + c.proxy_type_http = env->NewGlobalRef(http_enum.get()); + if (env->ExceptionCheck() || c.proxy_type_http == nullptr) { + env->ExceptionClear(); + return false; + } + + c.url_ctor = + CacheMethod(env, c.url_cls, "", "(Ljava/lang/String;)V", &ok); + c.url_open_conn = CacheMethod(env, c.url_cls, "openConnection", + "()Ljava/net/URLConnection;", &ok); + c.url_open_conn_proxy = + CacheMethod(env, c.url_cls, "openConnection", + "(Ljava/net/Proxy;)Ljava/net/URLConnection;", &ok); + + c.proxy_ctor = + CacheMethod(env, c.proxy_cls, "", + "(Ljava/net/Proxy$Type;Ljava/net/SocketAddress;)V", &ok); + c.inet_sock_addr_ctor = CacheMethod(env, c.inet_sock_addr_cls, "", + "(Ljava/lang/String;I)V", &ok); + + c.set_request_method = CacheMethod(env, c.http_conn_cls, "setRequestMethod", + "(Ljava/lang/String;)V", &ok); + c.set_request_property = + CacheMethod(env, c.http_conn_cls, "setRequestProperty", + "(Ljava/lang/String;Ljava/lang/String;)V", &ok); + c.add_request_property = + CacheMethod(env, c.http_conn_cls, "addRequestProperty", + "(Ljava/lang/String;Ljava/lang/String;)V", &ok); + c.set_use_caches = + CacheMethod(env, c.http_conn_cls, "setUseCaches", "(Z)V", &ok); + c.set_connect_timeout = + CacheMethod(env, c.http_conn_cls, "setConnectTimeout", "(I)V", &ok); + c.set_read_timeout = + CacheMethod(env, c.http_conn_cls, "setReadTimeout", "(I)V", &ok); + c.set_instance_follow_redirects = CacheMethod( + env, c.http_conn_cls, "setInstanceFollowRedirects", "(Z)V", &ok); + c.set_do_output = + CacheMethod(env, c.http_conn_cls, "setDoOutput", "(Z)V", &ok); + c.set_fixed_len_streaming = CacheMethod( + env, c.http_conn_cls, "setFixedLengthStreamingMode", "(J)V", &ok); + c.set_chunked_streaming = + CacheMethod(env, c.http_conn_cls, "setChunkedStreamingMode", "(I)V", &ok); + c.get_output_stream = CacheMethod(env, c.http_conn_cls, "getOutputStream", + "()Ljava/io/OutputStream;", &ok); + c.get_response_code = + CacheMethod(env, c.http_conn_cls, "getResponseCode", "()I", &ok); + c.get_response_message = CacheMethod( + env, c.http_conn_cls, "getResponseMessage", "()Ljava/lang/String;", &ok); + c.get_header_fields = CacheMethod(env, c.http_conn_cls, "getHeaderFields", + "()Ljava/util/Map;", &ok); + c.get_input_stream = CacheMethod(env, c.http_conn_cls, "getInputStream", + "()Ljava/io/InputStream;", &ok); + c.get_error_stream = CacheMethod(env, c.http_conn_cls, "getErrorStream", + "()Ljava/io/InputStream;", &ok); + c.disconnect = CacheMethod(env, c.http_conn_cls, "disconnect", "()V", &ok); + + c.output_write = + CacheMethod(env, c.output_stream_cls, "write", "([BII)V", &ok); + c.output_flush = CacheMethod(env, c.output_stream_cls, "flush", "()V", &ok); + c.output_close = CacheMethod(env, c.output_stream_cls, "close", "()V", &ok); + + c.input_read = CacheMethod(env, c.input_stream_cls, "read", "([BII)I", &ok); + c.input_close = CacheMethod(env, c.input_stream_cls, "close", "()V", &ok); + + c.map_entry_set = + CacheMethod(env, c.map_cls, "entrySet", "()Ljava/util/Set;", &ok); + c.set_iterator = + CacheMethod(env, c.set_cls, "iterator", "()Ljava/util/Iterator;", &ok); + c.iter_has_next = CacheMethod(env, c.iter_cls, "hasNext", "()Z", &ok); + c.iter_next = + CacheMethod(env, c.iter_cls, "next", "()Ljava/lang/Object;", &ok); + c.entry_get_key = + CacheMethod(env, c.entry_cls, "getKey", "()Ljava/lang/Object;", &ok); + c.entry_get_value = + CacheMethod(env, c.entry_cls, "getValue", "()Ljava/lang/Object;", &ok); + c.list_size = CacheMethod(env, c.list_cls, "size", "()I", &ok); + c.list_get = + CacheMethod(env, c.list_cls, "get", "(I)Ljava/lang/Object;", &ok); + + if (!ok) { + return false; + } + + c.initialized = true; + return true; +} + +struct AndroidCancelHandle { + std::mutex mutex; + jobject conn_global = nullptr; + jobject out_stream_global = nullptr; + jobject in_stream_global = nullptr; + + void ClearAll(JNIEnv* env) { + std::lock_guard lock(mutex); + if (in_stream_global != nullptr) { + env->DeleteGlobalRef(in_stream_global); + in_stream_global = nullptr; + } + if (out_stream_global != nullptr) { + env->DeleteGlobalRef(out_stream_global); + out_stream_global = nullptr; + } + if (conn_global != nullptr) { + env->DeleteGlobalRef(conn_global); + conn_global = nullptr; + } + } + + void AbortNow(JNIEnv* env) { + if (env == nullptr) { + return; + } + auto& c = GetJniCache(); + jobject conn_ref = nullptr; + jobject in_ref = nullptr; + jobject out_ref = nullptr; + { + std::lock_guard lock(mutex); + if (conn_global != nullptr) { + conn_ref = env->NewLocalRef(conn_global); + } + if (in_stream_global != nullptr) { + in_ref = env->NewLocalRef(in_stream_global); + } + if (out_stream_global != nullptr) { + out_ref = env->NewLocalRef(out_stream_global); + } + } + LocalRef local_conn(env, conn_ref); + LocalRef local_in(env, in_ref); + LocalRef local_out(env, out_ref); + + // Call conn.disconnect() FIRST to unblock any worker thread waiting inside + // InputStream.read() / OutputStream.write() before closing the streams, + // avoiding cross-thread stream monitor contention in OkHttp/Conscrypt. + if (local_conn && c.disconnect != nullptr) { + env->CallVoidMethod(local_conn.get(), c.disconnect); + if (env->ExceptionCheck()) env->ExceptionClear(); + } + if (local_in && c.input_close != nullptr) { + env->CallVoidMethod(local_in.get(), c.input_close); + if (env->ExceptionCheck()) env->ExceptionClear(); + } + if (local_out && c.output_close != nullptr) { + env->CallVoidMethod(local_out.get(), c.output_close); + if (env->ExceptionCheck()) env->ExceptionClear(); + } + } +}; + +// Dedicated background dispatcher for asynchronous JNI socket cancellation so +// `HttpCancelRequestInternal` / `HttpDestroyRequestInternal` invoked on the +// Android UI or Unity main thread never triggers `NetworkOnMainThreadException` +// or blocks the caller on Java stream teardown. +class AndroidCancelDispatcher { + public: + static AndroidCancelDispatcher& Instance() { + static auto* dispatcher = new AndroidCancelDispatcher(); + return *dispatcher; + } + + void Enqueue(const std::shared_ptr& handle) { + bool start_thread = false; + { + std::lock_guard lock(mutex_); + queue_.push_back(handle); + if (!started_) { + started_ = true; + start_thread = true; + } + } + cv_.notify_one(); + if (start_thread) { + std::thread([this]() { RunLoop(); }).detach(); + } + } + + private: + static JNIEnv* AttachCancelThread(JavaVM** out_vm, bool* out_attached) { + JavaVM* vm = ResolveJavaVM(); + if (vm == nullptr) { + return nullptr; + } + JNIEnv* env = nullptr; + jint status = vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); + if (status == JNI_EDETACHED) { + JavaVMAttachArgs args{}; + args.version = JNI_VERSION_1_6; + args.name = const_cast("FirebaseHttpCancel"); + args.group = nullptr; + if (vm->AttachCurrentThread(&env, &args) == JNI_OK) { + *out_vm = vm; + *out_attached = true; + } else { + return nullptr; + } + } else if (status == JNI_OK) { + *out_vm = vm; + } + return env; + } + + void RunLoop() { + JavaVM* vm = nullptr; + bool attached = false; + JNIEnv* env = AttachCancelThread(&vm, &attached); + while (true) { + std::shared_ptr next; + { + std::unique_lock lock(mutex_); + cv_.wait(lock, [this]() { return !queue_.empty(); }); + next = std::move(queue_.front()); + queue_.pop_front(); + } + if (env == nullptr) { + env = AttachCancelThread(&vm, &attached); + } + if (env != nullptr && next) { + next->AbortNow(env); + } + } + } + + std::mutex mutex_; + std::condition_variable cv_; + std::deque> queue_; + bool started_ = false; +}; + +bool IsRedirectStatus(int32_t status) { + return status == 301 || status == 302 || status == 303 || status == 307 || + status == 308; +} + +std::string_view FindHeaderValueIgnoreCase( + const std::vector>& headers, + std::string_view target) { + for (const auto& kv : headers) { + if (AsciiEqualsIgnoreCase(kv.first, target)) { + return kv.second; + } + } + return {}; +} + +void ExecuteAndroidOperation(JNIEnv* env, + const std::shared_ptr& op) { + if (!EnsureJniInitialized(env)) { + op->MarkFailed("Failed to initialize Android JNI HTTP bindings."); + return; + } + if (!IsHttpOrHttpsUrl(op->url)) { + op->MarkFailed("Unsupported URI scheme; only http and https are allowed."); + return; + } + + auto cancel_handle = std::make_shared(); + { + std::lock_guard lock(op->mutex); + if (op->IsCanceled()) { + return; + } + op->on_cancel = [cancel_handle]() { + AndroidCancelDispatcher::Instance().Enqueue(cancel_handle); + }; + } + + bool completed_cleanly = false; + struct CleanupGuard { + JNIEnv* env; + std::shared_ptr handle; + bool* completed_cleanly; + ~CleanupGuard() { + if (!*completed_cleanly) { + handle->AbortNow(env); + } + handle->ClearAll(env); + } + } guard{env, cancel_handle, &completed_cleanly}; + + auto& c = GetJniCache(); + std::string current_url = op->url; + std::string active_method = op->method; + std::vector> active_headers = + op->request_headers; + int64_t active_content_len = op->content_length; + + for (int redirect_count = 0; redirect_count <= kMaxRedirects; + ++redirect_count) { + cancel_handle->ClearAll(env); + + LocalRef jurl_str(env, env->NewStringUTF(current_url.c_str())); + if (auto ex = TakeJniException(env); ex || !jurl_str) { + op->MarkFailed(ex.value_or("Failed to allocate JNI URL string")); + return; + } + LocalRef jurl( + env, env->NewObject(c.url_cls, c.url_ctor, jurl_str.get())); + if (auto ex = TakeJniException(env); ex || !jurl) { + op->MarkFailed(ex.value_or("Invalid URL")); + return; + } + + LocalRef conn(env, nullptr); + if (auto proxy_hp = ParseProxyHostPort(op->proxy_url)) { + LocalRef jhost(env, env->NewStringUTF(proxy_hp->first.c_str())); + if (auto ex = TakeJniException(env); ex || !jhost) { + op->MarkFailed(ex.value_or("Failed to allocate proxy host string")); + return; + } + LocalRef jsock_addr( + env, + env->NewObject(c.inet_sock_addr_cls, c.inet_sock_addr_ctor, + jhost.get(), static_cast(proxy_hp->second))); + if (auto ex = TakeJniException(env); ex || !jsock_addr) { + op->MarkFailed(ex.value_or("Failed to construct proxy socket address")); + return; + } + LocalRef jproxy( + env, env->NewObject(c.proxy_cls, c.proxy_ctor, c.proxy_type_http, + jsock_addr.get())); + if (auto ex = TakeJniException(env); ex || !jproxy) { + op->MarkFailed(ex.value_or("Failed to construct Java Proxy")); + return; + } + conn.reset(env->CallObjectMethod(jurl.get(), c.url_open_conn_proxy, + jproxy.get())); + } else { + conn.reset(env->CallObjectMethod(jurl.get(), c.url_open_conn)); + } + if (auto ex = TakeJniException(env); ex || !conn) { + op->MarkFailed(ex.value_or("Failed to open HttpURLConnection")); + return; + } + if (env->IsInstanceOf(conn.get(), c.http_conn_cls) != JNI_TRUE) { + op->MarkFailed( + "Unsupported URI scheme; URLConnection is not an HttpURLConnection."); + return; + } + + { + jobject g_conn = env->NewGlobalRef(conn.get()); + if (auto ex = TakeJniException(env); ex || g_conn == nullptr) { + op->MarkFailed(ex.value_or("Failed to retain HttpURLConnection")); + return; + } + std::lock_guard lock(cancel_handle->mutex); + cancel_handle->conn_global = g_conn; + } + if (op->IsCanceled()) { + return; + } + + env->CallVoidMethod(conn.get(), c.set_use_caches, JNI_FALSE); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + env->CallVoidMethod(conn.get(), c.set_connect_timeout, 60000); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + env->CallVoidMethod(conn.get(), c.set_read_timeout, 0); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + // Handle redirects explicitly so cross-origin redirects strip sensitive + // Firebase credentials and HTTPS -> HTTP downgrades are rejected. + env->CallVoidMethod(conn.get(), c.set_instance_follow_redirects, JNI_FALSE); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + + LocalRef jmethod(env, env->NewStringUTF(active_method.c_str())); + if (auto ex = TakeJniException(env); ex || !jmethod) { + op->MarkFailed(ex.value_or("Failed to allocate HTTP method string")); + return; + } + env->CallVoidMethod(conn.get(), c.set_request_method, jmethod.get()); + if (auto ex = TakeJniException(env)) { + if (AsciiEqualsIgnoreCase(active_method, "PATCH")) { + // Fallback for HttpURLConnection implementations that reject PATCH. + LocalRef jpost(env, env->NewStringUTF("POST")); + if (auto ex_post = TakeJniException(env); ex_post || !jpost) { + op->MarkFailed(ex_post.value_or("Failed to allocate POST string")); + return; + } + LocalRef joverride_k( + env, env->NewStringUTF("X-HTTP-Method-Override")); + if (auto ex_k = TakeJniException(env); ex_k || !joverride_k) { + op->MarkFailed(ex_k.value_or("Failed to allocate override header")); + return; + } + LocalRef joverride_v(env, env->NewStringUTF("PATCH")); + if (auto ex_v = TakeJniException(env); ex_v || !joverride_v) { + op->MarkFailed(ex_v.value_or("Failed to allocate PATCH string")); + return; + } + env->CallVoidMethod(conn.get(), c.set_request_method, jpost.get()); + if (auto ex2 = TakeJniException(env)) { + op->MarkFailed(*ex2); + return; + } + env->CallVoidMethod(conn.get(), c.set_request_property, + joverride_k.get(), joverride_v.get()); + if (auto ex3 = TakeJniException(env)) { + op->MarkFailed(*ex3); + return; + } + } else { + op->MarkFailed(*ex); + return; + } + } + + bool has_accept_encoding = false; + std::unordered_set seen_headers; + for (const auto& kv : active_headers) { + if (AsciiEqualsIgnoreCase(kv.first, "Accept-Encoding")) { + has_accept_encoding = true; + } + LocalRef jk(env, env->NewStringUTF(kv.first.c_str())); + if (auto ex = TakeJniException(env); ex || !jk) { + op->MarkFailed(ex.value_or("Failed to allocate header name")); + return; + } + LocalRef jv(env, env->NewStringUTF(kv.second.c_str())); + if (auto ex = TakeJniException(env); ex || !jv) { + op->MarkFailed(ex.value_or("Failed to allocate header value")); + return; + } + jmethodID header_mid = seen_headers.insert(ToLowerAscii(kv.first)).second + ? c.set_request_property + : c.add_request_property; + env->CallVoidMethod(conn.get(), header_mid, jk.get(), jv.get()); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + } + if (!has_accept_encoding) { + // Match .NET HttpClientHandler (AutomaticDecompression = None) and + // Desktop libcurl so Android's OkHttp BridgeInterceptor does not inject + // `Accept-Encoding: gzip`, strip Content-Length, buffer SSE frames, or + // corrupt Range ETag / byte offsets. + LocalRef jae_k(env, env->NewStringUTF("Accept-Encoding")); + if (auto ex = TakeJniException(env); ex || !jae_k) { + op->MarkFailed(ex.value_or("Failed to allocate Accept-Encoding key")); + return; + } + LocalRef jae_v(env, env->NewStringUTF("identity")); + if (auto ex = TakeJniException(env); ex || !jae_v) { + op->MarkFailed(ex.value_or("Failed to allocate identity value")); + return; + } + env->CallVoidMethod(conn.get(), c.set_request_property, jae_k.get(), + jae_v.get()); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + } + + // Stream request body if present. Never call setDoOutput(true) on bodyless + // GET/HEAD/DELETE requests because HttpURLConnection rewrites GET -> POST. + bool send_body = active_content_len >= 0 || + active_content_len == kChunkedRequestContent || + (active_content_len == kNoRequestContent && + (AsciiEqualsIgnoreCase(active_method, "POST") || + AsciiEqualsIgnoreCase(active_method, "PUT") || + AsciiEqualsIgnoreCase(active_method, "PATCH"))); + if (send_body) { + env->CallVoidMethod(conn.get(), c.set_do_output, JNI_TRUE); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + if (active_content_len == kNoRequestContent || active_content_len == 0) { + env->CallVoidMethod(conn.get(), c.set_fixed_len_streaming, + static_cast(0)); + } else if (active_content_len > 0) { + env->CallVoidMethod(conn.get(), c.set_fixed_len_streaming, + static_cast(active_content_len)); + } else { + env->CallVoidMethod(conn.get(), c.set_chunked_streaming, + static_cast(65536)); + } + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + + LocalRef out_stream( + env, env->CallObjectMethod(conn.get(), c.get_output_stream)); + if (auto ex = TakeJniException(env); ex || !out_stream) { + if (!op->IsCanceled()) { + op->MarkFailed(ex.value_or("Failed to open request OutputStream")); + } + return; + } + { + jobject g_out = env->NewGlobalRef(out_stream.get()); + if (auto ex = TakeJniException(env); ex || g_out == nullptr) { + op->MarkFailed(ex.value_or("Failed to retain request OutputStream")); + return; + } + std::lock_guard lock(cancel_handle->mutex); + cancel_handle->out_stream_global = g_out; + } + + if (active_content_len > 0 || + active_content_len == kChunkedRequestContent) { + constexpr size_t kWriteSlice = 64 * 1024; + LocalRef jwrite_buf( + env, env->NewByteArray(static_cast(kWriteSlice))); + if (auto ex = TakeJniException(env); ex || !jwrite_buf) { + op->MarkFailed(ex.value_or("Failed to allocate JNI write buffer")); + return; + } + std::vector scratch(kWriteSlice); + while (!op->IsCanceled()) { + bool eof = false; + size_t n = op->PopRequestBytes(scratch.data(), kWriteSlice, &eof); + if (n > 0) { + env->SetByteArrayRegion( + jwrite_buf.get(), 0, static_cast(n), + reinterpret_cast(scratch.data())); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + env->CallVoidMethod(out_stream.get(), c.output_write, + jwrite_buf.get(), 0, static_cast(n)); + if (auto ex = TakeJniException(env)) { + if (!op->IsCanceled()) op->MarkFailed(*ex); + return; + } + } else if (eof) { + break; + } else { + std::unique_lock lock(op->mutex); + op->req_cv.wait(lock, [&op]() { + return !op->req_chunks.empty() || op->req_eof || op->failed || + op->IsCanceled(); + }); + } + } + } + + env->CallVoidMethod(out_stream.get(), c.output_flush); + if (env->ExceptionCheck()) env->ExceptionClear(); + env->CallVoidMethod(out_stream.get(), c.output_close); + if (auto ex = TakeJniException(env)) { + if (!op->IsCanceled()) op->MarkFailed(*ex); + return; + } + { + std::lock_guard lock(cancel_handle->mutex); + if (cancel_handle->out_stream_global != nullptr) { + env->DeleteGlobalRef(cancel_handle->out_stream_global); + cancel_handle->out_stream_global = nullptr; + } + } + } + + if (op->IsCanceled()) { + return; + } + + jint status_code = env->CallIntMethod(conn.get(), c.get_response_code); + if (auto ex = TakeJniException(env)) { + if (!op->IsCanceled()) op->MarkFailed(*ex); + return; + } + LocalRef jreason(env, static_cast(env->CallObjectMethod( + conn.get(), c.get_response_message))); + if (env->ExceptionCheck()) env->ExceptionClear(); + std::string reason = JStringToStdString(env, jreason.get()); + + std::vector> resp_headers; + LocalRef header_map( + env, env->CallObjectMethod(conn.get(), c.get_header_fields)); + if (!TakeJniException(env) && header_map) { + LocalRef entry_set( + env, env->CallObjectMethod(header_map.get(), c.map_entry_set)); + if (!TakeJniException(env) && entry_set) { + LocalRef iter( + env, env->CallObjectMethod(entry_set.get(), c.set_iterator)); + if (!TakeJniException(env) && iter) { + while (true) { + jboolean has_next = + env->CallBooleanMethod(iter.get(), c.iter_has_next); + if (TakeJniException(env) || has_next != JNI_TRUE) { + break; + } + LocalRef entry( + env, env->CallObjectMethod(iter.get(), c.iter_next)); + if (TakeJniException(env) || !entry) break; + LocalRef jkey( + env, static_cast( + env->CallObjectMethod(entry.get(), c.entry_get_key))); + if (TakeJniException(env) || !jkey) { + // HttpURLConnection maps the status line under a null key. + continue; + } + std::string key_str = JStringToStdString(env, jkey.get()); + if (key_str.empty()) continue; + + LocalRef val_list( + env, env->CallObjectMethod(entry.get(), c.entry_get_value)); + if (TakeJniException(env) || !val_list) continue; + jint count = env->CallIntMethod(val_list.get(), c.list_size); + if (TakeJniException(env)) continue; + for (jint i = 0; i < count; ++i) { + LocalRef jval(env, + static_cast(env->CallObjectMethod( + val_list.get(), c.list_get, i))); + if (TakeJniException(env)) break; + if (jval) { + resp_headers.emplace_back(key_str, + JStringToStdString(env, jval.get())); + } + } + } + } + } + } + + std::string_view location = + FindHeaderValueIgnoreCase(resp_headers, "Location"); + if (IsRedirectStatus(static_cast(status_code)) && + !location.empty()) { + // Drain/close response stream on the redirect hop so the pooled socket + // stays reusable before following. + LocalRef redir_stream( + env, env->CallObjectMethod(conn.get(), c.get_input_stream)); + if (env->ExceptionCheck()) env->ExceptionClear(); + if (redir_stream) { + env->CallVoidMethod(redir_stream.get(), c.input_close); + if (env->ExceptionCheck()) env->ExceptionClear(); + } + + if (redirect_count == kMaxRedirects) { + op->MarkFailed("Maximum HTTP redirects exceeded."); + return; + } + auto resolved = ResolveRedirectUrl(current_url, location); + if (!resolved || (IsHttpsUrl(op->url) && !IsHttpsUrl(*resolved))) { + op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect."); + return; + } + bool same_origin = IsSameOrigin(op->url, *resolved) && + IsSameOrigin(current_url, *resolved); + if (status_code == 303 || + ((status_code == 301 || status_code == 302) && + !AsciiEqualsIgnoreCase(active_method, "GET") && + !AsciiEqualsIgnoreCase(active_method, "HEAD"))) { + active_method = "GET"; + active_content_len = kNoRequestContent; + } else if (active_content_len != kNoRequestContent && + active_content_len != 0) { + op->MarkFailed("Cannot replay streamed request body across redirect."); + return; + } + + if (!same_origin || active_content_len == kNoRequestContent) { + std::vector> filtered; + filtered.reserve(active_headers.size()); + for (const auto& kv : active_headers) { + if (!same_origin && (IsSensitiveRedirectHeader(kv.first) || + AsciiEqualsIgnoreCase(kv.first, "Host"))) { + continue; + } + if (active_content_len == kNoRequestContent && + (AsciiEqualsIgnoreCase(kv.first, "Content-Type") || + AsciiEqualsIgnoreCase(kv.first, "Content-Length") || + AsciiEqualsIgnoreCase(kv.first, "Transfer-Encoding"))) { + continue; + } + filtered.push_back(kv); + } + active_headers = std::move(filtered); + } + current_url = std::move(*resolved); + continue; + } + + op->CommitResponseHeaders(static_cast(status_code), reason, + std::move(resp_headers)); + if (op->IsCanceled()) { + return; + } + + LocalRef in_stream( + env, env->CallObjectMethod(conn.get(), c.get_input_stream)); + if (env->ExceptionCheck() || !in_stream) { + env->ExceptionClear(); + in_stream.reset(env->CallObjectMethod(conn.get(), c.get_error_stream)); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + in_stream.reset(nullptr); + } + } + + if (!in_stream) { + completed_cleanly = true; + op->MarkResponseComplete(); + return; + } + + { + jobject g_in = env->NewGlobalRef(in_stream.get()); + if (auto ex = TakeJniException(env); ex || g_in == nullptr) { + op->MarkFailed(ex.value_or("Failed to retain response InputStream")); + return; + } + std::lock_guard lock(cancel_handle->mutex); + cancel_handle->in_stream_global = g_in; + } + if (op->IsCanceled()) { + return; + } + + constexpr size_t kReadSlice = 64 * 1024; + LocalRef jread_buf( + env, env->NewByteArray(static_cast(kReadSlice))); + if (auto ex = TakeJniException(env); ex || !jread_buf) { + op->MarkFailed(ex.value_or("Failed to allocate JNI read buffer")); + return; + } + std::vector read_scratch(kReadSlice); + + while (!op->IsCanceled()) { + jint n = + env->CallIntMethod(in_stream.get(), c.input_read, jread_buf.get(), 0, + static_cast(kReadSlice)); + if (auto ex = TakeJniException(env)) { + if (!op->IsCanceled()) op->MarkFailed(*ex); + return; + } + if (n < 0) { + break; + } + if (n == 0) { + continue; + } + env->GetByteArrayRegion(jread_buf.get(), 0, n, + reinterpret_cast(read_scratch.data())); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(*ex); + return; + } + bool over_high_water = + op->PushResponseBytes(read_scratch.data(), static_cast(n)); + if (over_high_water && !op->IsCanceled()) { + std::unique_lock lock(op->mutex); + op->resp_cv.wait(lock, [&op]() { + return op->resp_buffered_bytes <= kLowWaterResponseBytes || + op->IsCanceled() || op->failed; + }); + } + } + + if (op->IsCanceled()) { + return; + } + + // Close the response stream so Android's ConnectionPool can reuse the live + // TLS connection; do not call conn.disconnect() on normal completion. + env->CallVoidMethod(in_stream.get(), c.input_close); + if (env->ExceptionCheck()) env->ExceptionClear(); + completed_cleanly = true; + op->MarkResponseComplete(); + return; + } +} + +class AndroidHttpThreadPool { + public: + static AndroidHttpThreadPool& Instance() { + static auto* pool = new AndroidHttpThreadPool(); + return *pool; + } + + void Enqueue(const std::shared_ptr& op) { + // Capture JavaVM on the caller thread if an App is already initialized so + // newly spawned workers immediately see a cached JavaVM*. + (void)ResolveJavaVM(); + bool spawn_worker = false; + { + std::lock_guard lock(mutex_); + queue_.push_back(op); + if (queue_.size() > idle_workers_ + starting_workers_ && + active_workers_ < kMaxWorkers) { + ++active_workers_; + ++starting_workers_; + spawn_worker = true; + } + } + cv_.notify_one(); + if (spawn_worker) { + std::thread([this]() { WorkerLoop(); }).detach(); + } + } + + private: + // Matches Desktop's CURLMOPT_MAX_TOTAL_CONNECTIONS (64) so concurrent open + // SSE / GetStreamAsync() streams never starve short requests. + static constexpr size_t kMaxWorkers = 64; + + static JNIEnv* AttachWorkerThread(JavaVM** out_vm, bool* out_attached) { + JavaVM* vm = ResolveJavaVM(); + if (vm == nullptr) { + return nullptr; + } + JNIEnv* env = nullptr; + jint status = vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); + if (status == JNI_EDETACHED) { + JavaVMAttachArgs args{}; + args.version = JNI_VERSION_1_6; + args.name = const_cast("FirebaseHttpWorker"); + args.group = nullptr; + if (vm->AttachCurrentThread(&env, &args) == JNI_OK) { + *out_vm = vm; + *out_attached = true; + } else { + return nullptr; + } + } else if (status == JNI_OK) { + *out_vm = vm; + } + return env; + } + + void WorkerLoop() { + JavaVM* vm = nullptr; + bool attached = false; + JNIEnv* env = AttachWorkerThread(&vm, &attached); + + { + std::lock_guard lock(mutex_); + --starting_workers_; + } + + while (true) { + std::shared_ptr next; + { + std::unique_lock lock(mutex_); + if (queue_.empty()) { + ++idle_workers_; + bool has_work = cv_.wait_for(lock, std::chrono::seconds(30), + [this]() { return !queue_.empty(); }); + --idle_workers_; + if (!has_work) { + --active_workers_; + break; + } + } + next = std::move(queue_.front()); + queue_.pop_front(); + } + + if (env == nullptr) { + env = AttachWorkerThread(&vm, &attached); + } + if (env == nullptr) { + next->MarkFailed("Android JavaVM / JNIEnv is unavailable."); + } else { + ExecuteAndroidOperation(env, next); + } + } + + if (attached && vm != nullptr) { + vm->DetachCurrentThread(); + } + } + + std::mutex mutex_; + std::condition_variable cv_; + std::deque> queue_; + size_t active_workers_ = 0; + size_t idle_workers_ = 0; + size_t starting_workers_ = 0; +}; + +} // namespace + +void SetAndroidJavaVM(JavaVM* vm) { + if (vm != nullptr) { + g_android_jvm.store(vm, std::memory_order_release); + } +} + +void StartPlatformHttpOperation(const std::shared_ptr& op) { + AndroidHttpThreadPool::Instance().Enqueue(op); +} + +} // namespace http +} // namespace firebase diff --git a/app/http/http_transport_apple.mm b/app/http/http_transport_apple.mm new file mode 100644 index 0000000000..65d8c691b3 --- /dev/null +++ b/app/http/http_transport_apple.mm @@ -0,0 +1,803 @@ +/* + * 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 "app/http/http_transport.h" + +#if !__has_feature(objc_arc) +#error "http_transport_apple.mm requires Objective-C ARC (-fobjc-arc)." +#endif + +@class FIRFirebaseHttpStreamBridge; + +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; +} + +struct AppleTransferState { + std::shared_ptr op; + NSURLSessionDataTask* task = nil; + NSOutputStream* body_output_stream = nil; + FIRFirebaseHttpStreamBridge* stream_bridge = nil; + bool task_started = false; + bool task_suspended = false; + bool body_closed = false; + int redirect_count = 0; + std::vector pending_write_chunk; + size_t pending_write_offset = 0; + std::mutex state_mutex; +}; + +void CancelAppleTransferTask(const std::shared_ptr& state); + +} // 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; + // 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 { + _selfRetain = self; + [self performSelector:@selector(openOnStreamThread:) + onThread:[FIRFirebaseHttpStreamBridge streamThread] + withObject:outputStream + waitUntilDone:NO]; +} + +- (void)openOnStreamThread:(NSOutputStream*)outputStream { + 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; + if (!state) { + _selfRetain = nil; + return; + } + NSOutputStream* stream = nil; + { + std::lock_guard lock(state->state_mutex); + state->stream_bridge = nil; + if (!state->body_closed && state->body_output_stream != nil) { + state->body_closed = true; + stream = state->body_output_stream; + state->body_output_stream = nil; + } + } + 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 == nil) { + return; + } + stream = state->body_output_stream; + } + + constexpr size_t kSliceSize = 64 * 1024; + while ([stream hasSpaceAvailable]) { + if (state->pending_write_offset >= state->pending_write_chunk.size()) { + state->pending_write_chunk.resize(kSliceSize); + state->pending_write_offset = 0; + bool eof = false; + size_t popped = + state->op->PopRequestBytes(state->pending_write_chunk.data(), kSliceSize, &eof); + state->pending_write_chunk.resize(popped); + 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) { + NSError* err = [stream streamError]; + std::string msg = err != nil ? firebase::http::FromNSString([err localizedDescription]) + : "Request body stream write failed."; + // Record the stream error before cancelling the task so an asynchronous + // `didCompleteWithError:NSURLErrorCancelled` cannot overwrite `msg`. + state->op->MarkFailed(msg); + firebase::http::CancelAppleTransferTask(state); + [self closeOnStreamThread]; + return; + } else { + break; + } + } +} + +- (void)stream:(NSStream*)aStream handleEvent:(NSStreamEvent)eventCode { + switch (eventCode) { + case NSStreamEventHasSpaceAvailable: + [self pumpOnStreamThread]; + break; + case NSStreamEventErrorOccurred: { + NSError* err = [aStream streamError]; + std::string msg = err != nil ? firebase::http::FromNSString([err localizedDescription]) + : "Request body stream error."; + auto state = _state; + if (state) { + state->op->MarkFailed(msg); + firebase::http::CancelAppleTransferTask(state); + } + [self closeOnStreamThread]; + break; + } + case NSStreamEventEndEncountered: + [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 + willPerformHTTPRedirection:(NSHTTPURLResponse*)response + newRequest:(NSURLRequest*)request + completionHandler:(void (^)(NSURLRequest* _Nullable))handler { + auto state = [self findState:task]; + if (state) { + bool exceeded = false; + { + std::lock_guard lock(state->state_mutex); + if (state->redirect_count >= firebase::http::kMaxRedirects) { + exceeded = true; + } else { + ++state->redirect_count; + } + } + if (exceeded) { + state->op->MarkFailed("Maximum HTTP redirects exceeded."); + [task cancel]; + handler(nil); + return; + } + } + + std::string orig_url = firebase::http::FromNSString(task.originalRequest.URL.absoluteString); + NSString* prev_ns = + response.URL != nil ? response.URL.absoluteString : task.currentRequest.URL.absoluteString; + std::string prev_url = firebase::http::FromNSString(prev_ns); + std::string next_url = firebase::http::FromNSString(request.URL.absoluteString); + bool was_https = firebase::http::IsHttpsUrl(orig_url) || firebase::http::IsHttpsUrl(prev_url); + if (!firebase::http::IsHttpOrHttpsUrl(next_url) || + (was_https && !firebase::http::IsHttpsUrl(next_url))) { + // Fail the operation and cancel the task on non-HTTP(S) schemes or + // HTTPS -> HTTP downgrades; passing handler(nil) alone would complete the + // task with the raw 3xx response as success. + if (state) { + state->op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect."); + } + [task cancel]; + handler(nil); + return; + } + + if (!firebase::http::IsSameOrigin(orig_url, next_url) || + !firebase::http::IsSameOrigin(prev_url, next_url)) { + NSMutableURLRequest* sanitized = [request mutableCopy]; + [sanitized setValue:nil forHTTPHeaderField:@"Authorization"]; + [sanitized setValue:nil forHTTPHeaderField:@"Proxy-Authorization"]; + [sanitized setValue:nil forHTTPHeaderField:@"X-Firebase-AppCheck"]; + [sanitized setValue:nil forHTTPHeaderField:@"x-goog-api-key"]; + handler(sanitized); + return; + } + + // CFNetwork strips the reserved Authorization header when constructing + // `newRequest` even on same-origin redirects. Copy it from `currentRequest` + // (never `originalRequest`, so a credential stripped on an earlier + // cross-origin hop can never be resurrected on a later bounce back). + NSString* cur_auth = [task.currentRequest valueForHTTPHeaderField:@"Authorization"]; + if (cur_auth != nil && [request valueForHTTPHeaderField:@"Authorization"] == nil) { + NSMutableURLRequest* preserved = [request mutableCopy]; + [preserved setValue:cur_auth forHTTPHeaderField:@"Authorization"]; + handler(preserved); + return; + } + + handler(request); +} + +- (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."); + completionHandler(NSURLSessionResponseCancel); + return; + } + + auto* httpResp = static_cast(response); + int32_t status = static_cast(httpResp.statusCode); + std::string reason = firebase::http::FromNSString( + [NSHTTPURLResponse localizedStringForStatusCode: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))); + } + } + + state->op->CommitResponseHeaders(status, reason, std::move(headers)); + 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; + } + + __block bool over_high_water = false; + [data enumerateByteRangesUsingBlock:^(const void* bytes, NSRange byteRange, BOOL* stop) { + if (byteRange.length > 0) { + if (state->op->PushResponseBytes(static_cast(bytes), + static_cast(byteRange.length))) { + over_high_water = true; + } + } + }]; + + if (over_high_water) { + std::lock_guard lock(state->state_mutex); + if (!state->task_suspended && !state->op->IsCanceled() && state->task != nil) { + // Re-verify buffered byte count under `op->mutex` while holding + // `state_mutex` (`state_mutex -> op->mutex` lock order) so a concurrent + // consumer read draining the buffer to 0 cannot race past + // `task_suspended` and leave the task suspended permanently. + bool still_above_low_water = false; + { + std::lock_guard op_lock(state->op->mutex); + still_above_low_water = + state->op->resp_buffered_bytes > firebase::http::kLowWaterResponseBytes; + } + if (still_above_low_water) { + state->task_suspended = true; + [state->task suspend]; + } + } + } +} + +- (void)URLSession:(NSURLSession*)session + task:(NSURLSessionTask*)task + didCompleteWithError:(NSError*)error { + auto state = [self takeState:task]; + if (!state) { + return; + } + FIRFirebaseHttpStreamBridge* bridge = nil; + { + std::lock_guard lock(state->state_mutex); + state->task = nil; + state->task_suspended = false; + bridge = state->stream_bridge; + state->stream_bridge = nil; + } + if (bridge != nil) { + [bridge closeWriteStream]; + } + if (state->op->IsCanceled()) { + return; + } + if (error != nil) { + state->op->MarkFailed(firebase::http::FromNSString([error localizedDescription])); + } else { + state->op->MarkResponseComplete(); + } +} + +@end + +namespace firebase { +namespace http { +namespace { + +NSURLSessionConfiguration* MakeBaseSessionConfig() { + NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + config.URLCache = nil; + config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever; + config.HTTPShouldSetCookies = NO; + config.HTTPMaximumConnectionsPerHost = 16; + // Timeouts are governed by the caller's CancellationToken / watchdog so + // long-lived SSE streams are never prematurely killed while idle. + config.timeoutIntervalForRequest = 86400.0; + config.timeoutIntervalForResource = 86400.0; + return config; +} + +FIRFirebaseHttpSessionDelegate* SharedSessionDelegate() { + static FIRFirebaseHttpSessionDelegate* sDelegate = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sDelegate = [[FIRFirebaseHttpSessionDelegate alloc] init]; + }); + return sDelegate; +} + +NSOperationQueue* SharedDelegateQueue() { + static NSOperationQueue* sQueue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sQueue = [[NSOperationQueue alloc] init]; + sQueue.name = @"com.google.firebase.http.delegate"; + // NSURLSession requires a serial delegate queue to preserve ordering + // between `didReceiveResponse:`, `didReceiveData:`, and + // `didCompleteWithError:` callbacks. + sQueue.maxConcurrentOperationCount = 1; + sQueue.qualityOfService = NSQualityOfServiceUserInitiated; + }); + return sQueue; +} + +void CancelAppleTransferTask(const std::shared_ptr& state) { + if (!state) { + return; + } + FIRFirebaseHttpStreamBridge* bridge = nil; + NSURLSessionDataTask* t = nil; + 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 (bridge != nil) { + [bridge closeWriteStream]; + } + if (t != nil) { + if (!was_started) { + // NSURLSession does not fire `didCompleteWithError:` for a task canceled + // before its initial `resume`; remove from `_tasks` here to avoid a leak. + [SharedSessionDelegate() 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]; + } +} + +NSURLSession* SharedDefaultSession() { + static NSURLSession* sSession = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sSession = [NSURLSession sessionWithConfiguration:MakeBaseSessionConfig() + delegate:SharedSessionDelegate() + delegateQueue:SharedDelegateQueue()]; + }); + return sSession; +} + +NSURLSession* SessionForProxy(std::string_view proxy_url) { + auto proxy_hp = ParseProxyHostPort(proxy_url); + if (!proxy_hp) { + return SharedDefaultSession(); + } + + static auto* proxy_mutex = new std::mutex(); + static auto* proxy_sessions = new std::unordered_map(); + static auto* proxy_lru = new std::deque(); + constexpr size_t kMaxCachedProxySessions = 8; + + std::string cache_key = proxy_hp->first + ":" + std::to_string(proxy_hp->second); + NSURLSession* evicted = nil; + NSURLSession* result = nil; + { + std::lock_guard lock(*proxy_mutex); + auto it = proxy_sessions->find(cache_key); + if (it != proxy_sessions->end()) { + return it->second; + } + + NSString* host = ToNSString(proxy_hp->first); + NSNumber* port = @(proxy_hp->second); + NSURLSessionConfiguration* config = MakeBaseSessionConfig(); + config.connectionProxyDictionary = @{ + @"HTTPEnable" : @YES, + @"HTTPProxy" : host, + @"HTTPPort" : port, + @"HTTPSEnable" : @YES, + @"HTTPSProxy" : host, + @"HTTPSPort" : port, + }; + result = [NSURLSession sessionWithConfiguration:config + delegate:SharedSessionDelegate() + delegateQueue:SharedDelegateQueue()]; + if (proxy_sessions->size() >= kMaxCachedProxySessions && !proxy_lru->empty()) { + std::string oldest = std::move(proxy_lru->front()); + proxy_lru->pop_front(); + auto old_it = proxy_sessions->find(oldest); + if (old_it != proxy_sessions->end()) { + evicted = old_it->second; + proxy_sessions->erase(old_it); + } + } + proxy_sessions->emplace(cache_key, result); + proxy_lru->push_back(std::move(cache_key)); + } + if (evicted != nil && evicted != SharedDefaultSession()) { + [evicted finishTasksAndInvalidate]; + } + return result; +} + +} // 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."); + return; + } + + NSURL* ns_url = [NSURL URLWithString:ToNSString(op->url)]; + if (ns_url == nil) { + op->MarkFailed("Invalid request URL."); + return; + } + + 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; + + FIRFirebaseHttpStreamBridge* stream_bridge = nil; + if (op->content_length == 0) { + 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; + NSOutputStream* out_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"]; + } + state->body_output_stream = out_stream; + stream_bridge = [[FIRFirebaseHttpStreamBridge alloc] initWithState:state]; + state->stream_bridge = stream_bridge; + [stream_bridge scheduleOutputStream:out_stream]; + } 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"]; + } + + NSURLSession* session = SessionForProxy(op->proxy_url); + NSURLSessionDataTask* task = [session dataTaskWithRequest:req]; + NSString* key = [NSString stringWithFormat:@"%lld", static_cast(op->id)]; + task.taskDescription = key; + state->task = task; + + [SharedSessionDelegate() 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_response_space_available = [weak_state]() { + auto locked = weak_state.lock(); + if (!locked) { + return; + } + std::lock_guard slock(locked->state_mutex); + if (locked->task_suspended && locked->task != nil && !locked->op->IsCanceled()) { + locked->task_suspended = false; + [locked->task resume]; + } + }; + op->on_cancel = [weak_state]() { CancelAppleTransferTask(weak_state.lock()); }; + } + } + + if (already_canceled) { + [SharedSessionDelegate() takeState:task]; + { + std::lock_guard slock(state->state_mutex); + state->stream_bridge = nil; + state->task = nil; + } + if (stream_bridge != nil) { + [stream_bridge closeWriteStream]; + } + [task cancel]; + return; + } + + // Coordinate initial `[task resume]` with `CancelAppleTransferTask` under + // `state_mutex` so a cancel racing before `resume` cannot leave a never- + // resumed task stranded in `SharedSessionDelegate()._tasks`. + bool should_cleanup_unstarted = false; + { + std::lock_guard slock(state->state_mutex); + if (state->task != nil && !op->IsCanceled()) { + state->task_started = true; + [task resume]; + } else if (state->task != nil) { + state->task = nil; + should_cleanup_unstarted = true; + } + } + if (should_cleanup_unstarted) { + [SharedSessionDelegate() takeState:task]; + [task cancel]; + } + } +} + +} // namespace http +} // namespace firebase diff --git a/app/http/http_transport_common.cc b/app/http/http_transport_common.cc new file mode 100644 index 0000000000..efe646ec4e --- /dev/null +++ b/app/http/http_transport_common.cc @@ -0,0 +1,850 @@ +/* + * 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 "app/http/http_transport.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; +} + +bool HasControlChars(std::string_view s) { + for (unsigned char ch : s) { + if (ch < 0x20 || ch == 0x7F) { + return true; + } + } + return false; +} + +} // namespace + +std::vector> ParsePackedHeaders( + std::string_view packed) { + std::vector> result; + 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; + } + size_t sep = line.find('\t'); + if (sep == std::string_view::npos) { + sep = line.find(':'); + } + if (sep == std::string_view::npos || sep == 0) { + continue; + } + std::string_view name = TrimAsciiWhitespace(line.substr(0, sep)); + std::string_view value = TrimAsciiWhitespace(line.substr(sep + 1)); + if (!name.empty()) { + result.emplace_back(std::string(name), std::string(value)); + } + } + return result; +} + +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; +} + +std::optional ParseUrlOrigin(std::string_view url) { + url = TrimAsciiWhitespace(url); + size_t scheme_end = url.find("://"); + if (scheme_end == std::string_view::npos || scheme_end == 0) { + return std::nullopt; + } + std::string_view raw_scheme = url.substr(0, scheme_end); + int default_port = 0; + std::string norm_scheme; + if (AsciiEqualsIgnoreCase(raw_scheme, "http")) { + norm_scheme = "http"; + default_port = 80; + } else if (AsciiEqualsIgnoreCase(raw_scheme, "https")) { + norm_scheme = "https"; + default_port = 443; + } else { + return std::nullopt; + } + + std::string_view rest = url.substr(scheme_end + 3); + size_t path_pos = rest.find_first_of("/?#"); + std::string_view authority = + path_pos == std::string_view::npos ? rest : rest.substr(0, path_pos); + // Reject backslashes (which WHATWG/OkHttp treat as path delimiters, enabling + // `https://evil.com\@trusted.com` authority confusion) and control/whitespace + // characters inside authority. + if (authority.find('\\') != std::string_view::npos || + HasControlOrWhitespace(authority)) { + return std::nullopt; + } + size_t at_pos = authority.rfind('@'); + if (at_pos != std::string_view::npos) { + authority = authority.substr(at_pos + 1); + } + if (authority.empty()) { + return std::nullopt; + } + + std::string_view host_sv; + std::string_view port_sv; + if (authority.front() == '[') { + size_t close = authority.find(']'); + if (close == std::string_view::npos || close <= 1) { + return std::nullopt; + } + host_sv = authority.substr(0, close + 1); + if (close + 1 < authority.size()) { + if (authority[close + 1] != ':') { + return std::nullopt; + } + port_sv = authority.substr(close + 2); + } + } else { + size_t colon = authority.rfind(':'); + if (colon != std::string_view::npos) { + host_sv = authority.substr(0, colon); + port_sv = authority.substr(colon + 1); + } else { + host_sv = authority; + } + if (host_sv.find_first_of(":[]") != std::string_view::npos) { + return std::nullopt; + } + } + if (host_sv.empty()) { + return std::nullopt; + } + + int port = default_port; + if (!port_sv.empty()) { + int parsed = 0; + auto [ptr, ec] = std::from_chars(port_sv.data(), + port_sv.data() + port_sv.size(), parsed); + if (ec != std::errc() || ptr != port_sv.data() + port_sv.size() || + parsed <= 0 || parsed > 65535) { + return std::nullopt; + } + port = parsed; + } + + std::string norm_host(host_sv.size(), '\0'); + for (size_t i = 0; i < host_sv.size(); ++i) { + norm_host[i] = + static_cast(std::tolower(static_cast(host_sv[i]))); + } + + UrlOrigin out; + out.scheme = std::move(norm_scheme); + out.host = std::move(norm_host); + out.port = port; + return out; +} + +bool IsHttpOrHttpsUrl(std::string_view url) { + return ParseUrlOrigin(url).has_value(); +} + +bool IsHttpsUrl(std::string_view url) { + auto origin = ParseUrlOrigin(url); + return origin.has_value() && origin->scheme == "https"; +} + +bool IsSameOrigin(std::string_view url_a, std::string_view url_b) { + auto a = ParseUrlOrigin(url_a); + auto b = ParseUrlOrigin(url_b); + if (!a || !b) { + return false; + } + return a->scheme == b->scheme && a->host == b->host && a->port == b->port; +} + +bool IsSensitiveRedirectHeader(std::string_view header_name) { + return AsciiEqualsIgnoreCase(header_name, "Authorization") || + AsciiEqualsIgnoreCase(header_name, "Proxy-Authorization") || + AsciiEqualsIgnoreCase(header_name, "X-Firebase-AppCheck") || + AsciiEqualsIgnoreCase(header_name, "x-goog-api-key"); +} + +std::optional ResolveRedirectUrl(std::string_view current_url, + std::string_view location) { + current_url = TrimAsciiWhitespace(current_url); + location = TrimAsciiWhitespace(location); + if (location.empty() || HasControlChars(location)) { + return std::nullopt; + } + // Reject leading backslashes or `/\` prefixes to prevent WHATWG/OkHttp + // scheme-relative authority confusion (`\/evil.com`, `/\evil.com`). + if (location.front() == '\\' || + (location.size() >= 2 && location[0] == '/' && location[1] == '\\')) { + return std::nullopt; + } + auto base_origin = ParseUrlOrigin(current_url); + if (!base_origin) { + return std::nullopt; + } + + // Detect an RFC 3986 leading URI scheme (`:` occurring before `/`, `\`, `?`, + // or `#`) so relative URLs containing `://` in query/fragment stay relative + // while non-HTTP(S) schemes like `data:`, `file:/...`, or `mailto:` are + // passed to `ParseUrlOrigin` and rejected. + size_t first_delim = location.find_first_of(":/\\?#"); + if (first_delim == 0 && location[0] == ':') { + return std::nullopt; + } + bool has_scheme_prefix = first_delim != std::string_view::npos && + first_delim > 0 && location[first_delim] == ':'; + + std::string candidate; + if (has_scheme_prefix) { + candidate.assign(location.data(), location.size()); + } else if (location.size() >= 2 && location[0] == '/' && location[1] == '/') { + candidate = base_origin->scheme + ":" + std::string(location); + } else { + size_t scheme_end = current_url.find("://"); + size_t auth_start = scheme_end + 3; + size_t path_pos = current_url.find_first_of("/?#", auth_start); + std::string_view origin_prefix = path_pos == std::string_view::npos + ? current_url + : current_url.substr(0, path_pos); + std::string_view base_path = "/"; + if (path_pos != std::string_view::npos && current_url[path_pos] == '/') { + size_t q_pos = current_url.find_first_of("?#", path_pos); + base_path = q_pos == std::string_view::npos + ? current_url.substr(path_pos) + : current_url.substr(path_pos, q_pos - path_pos); + } + + if (location.front() == '/') { + candidate = std::string(origin_prefix) + std::string(location); + } else if (location.front() == '?') { + candidate = std::string(origin_prefix) + std::string(base_path) + + std::string(location); + } else if (location.front() == '#') { + size_t frag_pos = current_url.find('#'); + std::string_view without_frag = frag_pos == std::string_view::npos + ? current_url + : current_url.substr(0, frag_pos); + candidate = std::string(without_frag) + std::string(location); + } else { + size_t last_slash = base_path.rfind('/'); + std::string_view dir = last_slash == std::string_view::npos + ? std::string_view("/") + : base_path.substr(0, last_slash + 1); + candidate = + std::string(origin_prefix) + std::string(dir) + std::string(location); + } + } + + auto next_origin = ParseUrlOrigin(candidate); + if (!next_origin) { + return std::nullopt; + } + if (base_origin->scheme == "https" && next_origin->scheme != "https") { + return std::nullopt; + } + return candidate; +} + +std::optional> ParseProxyHostPort( + std::string_view proxy_url) { + proxy_url = TrimAsciiWhitespace(proxy_url); + if (proxy_url.empty()) { + return std::nullopt; + } + std::string normalized; + if (proxy_url.find("://") == std::string_view::npos) { + normalized = "http://" + std::string(proxy_url); + proxy_url = normalized; + } + auto origin = ParseUrlOrigin(proxy_url); + if (!origin) { + return std::nullopt; + } + std::string host = origin->host; + if (host.size() >= 2 && host.front() == '[' && host.back() == ']') { + host = host.substr(1, host.size() - 2); + } + if (host.empty()) { + return std::nullopt; + } + return std::make_pair(std::move(host), origin->port); +} + +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 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; + } + + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + int64_t id = reg.next_id++; + op->id = id; + reg.operations.emplace(id, std::move(op)); + 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; + } + StartPlatformHttpOperation(op); +} + +void CancelOperation(int64_t handle) { + auto op = FindOperation(handle); + if (!op) { + return; + } + bool expected = false; + if (!op->canceled.compare_exchange_strong(expected, true, + std::memory_order_acq_rel)) { + return; + } + + std::function cancel_hook; + bool notify_req = false; + bool notify_headers = false; + bool notify_body = false; + { + std::lock_guard lock(op->mutex); + 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); + } +} + +void DestroyOperation(int64_t handle) { + CancelOperation(handle); + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + reg.operations.erase(handle); +} + +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); + } +} + +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_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) { + bool notify_req = false; + bool notify_headers = false; + bool notify_body = false; + { + std::lock_guard lock(mutex); + if (!failed) { + failed = true; + error_message.assign(message.data(), message.size()); + } + 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 : ""; + if (headers_packed != nullptr && headers_packed[0] != '\0') { + options.headers = http::ParsePackedHeaders(headers_packed); + } + if (proxy_url != nullptr && proxy_url[0] != '\0') { + options.proxy_url = proxy_url; + } + options.content_length = content_length; + return http::CreateOperation(std::move(options)); +} + +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 0; + } + auto op = http::FindOperation(handle); + if (!op) { + return -1; + } + + std::function notify_backend; + int32_t to_write = 0; + { + std::lock_guard lock(op->mutex); + if (op->failed || op->resp_eof || op->IsCanceled()) { + return -1; + } + 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); + 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 0; + } + 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; +} + +void HttpCancelRequestInternal(int64_t handle) { + http::CancelOperation(handle); +} + +void HttpDestroyRequestInternal(int64_t handle) { + http::DestroyOperation(handle); +} + +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..df6f48968a --- /dev/null +++ b/app/http/http_transport_curl.cc @@ -0,0 +1,660 @@ +/* + * 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 "app/http/http_transport.h" +#include "app/rest/curl/curl_handles.h" +#include "app/rest/curl/tls_policy.h" +#include "curl/curl.h" + +namespace firebase { +namespace http { +namespace { + +bool HasHeaderIgnoreCase( + const std::vector>& headers, + std::string_view target) { + for (const auto& kv : headers) { + if (AsciiEqualsIgnoreCase(kv.first, target)) { + return true; + } + } + return false; +} + +std::string_view FindHeaderValueIgnoreCase( + const std::vector>& headers, + std::string_view target) { + for (const auto& kv : headers) { + if (AsciiEqualsIgnoreCase(kv.first, target)) { + return kv.second; + } + } + return {}; +} + +bool IsRedirectStatus(int32_t status) { + return status == 301 || status == 302 || status == 303 || status == 307 || + status == 308; +} + +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; + + std::string current_url; + std::string active_method; + std::vector> active_headers; + int64_t active_content_length = kNoRequestContent; + int redirect_count = 0; + + std::string redirect_url; + int32_t redirect_status = 0; + size_t redirect_body_drained = 0; + std::string redirect_blocked_error; + + 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; + } + if (!transfer->redirect_url.empty()) { + // Ignore any trailing headers (e.g. chunked trailers) on a 3xx redirect + // response whose Location has already been captured. + return total; + } + + 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) { + std::string_view location = + FindHeaderValueIgnoreCase(transfer->staged_headers, "Location"); + if (IsRedirectStatus(transfer->staged_status) && !location.empty()) { + auto resolved = ResolveRedirectUrl(transfer->current_url, location); + if (!resolved || + (IsHttpsUrl(transfer->op->url) && !IsHttpsUrl(*resolved))) { + transfer->redirect_blocked_error = + "Blocked unsafe or scheme-downgraded HTTP redirect."; + return 0; + } + // Route all HTTP redirects manually through HandleRedirect so + // 301/302/303 -> GET rewrites (clearing CURLOPT_UPLOAD and + // CURLOPT_CUSTOMREQUEST), kMaxRedirects, and cross-origin sensitive + // header stripping match Android and Apple identically. + transfer->redirect_url = std::move(*resolved); + transfer->redirect_status = transfer->staged_status; + if (transfer->active_content_length != kNoRequestContent && + transfer->active_content_length != 0) { + return 0; + } + return total; + } + transfer->CommitStagedHeadersIfNeeded(); + } + 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; + } + if (!transfer->redirect_url.empty()) { + // Drain small 3xx bodies so keep-alive connections remain pooled in + // multi_, capping at 64 KiB so oversized redirect bodies abort promptly. + constexpr size_t kMaxRedirectBodyDrainBytes = 64 * 1024; + transfer->redirect_body_drained += total; + if (transfer->redirect_body_drained > kMaxRedirectBodyDrainBytes) { + return 0; + } + return total; + } + 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; + } + + bool eof = false; + size_t n = transfer->op->PopRequestBytes(reinterpret_cast(buffer), + cap, &eof); + if (n > 0) { + 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, std::string target_url, + std::string method, + std::vector> request_headers, + int64_t content_length, int redirect_count) { + if (!IsHttpOrHttpsUrl(target_url)) { + op->MarkFailed( + "Unsupported URI scheme; only http and https are allowed."); + return nullptr; + } + + ::firebase::rest::curl::UniqueEasy easy(curl_easy_init()); + if (easy == nullptr) { + op->MarkFailed("Failed to initialize native libcurl handle."); + return nullptr; + } + + CURLcode tls_rc = ::firebase::rest::curl::ApplyTlsPolicy(easy.get()); + if (tls_rc != CURLE_OK) { + op->MarkFailed(curl_easy_strerror(tls_rc)); + return nullptr; + } + + auto transfer = std::make_unique(); + transfer->op = op; + transfer->current_url = std::move(target_url); + transfer->active_method = std::move(method); + transfer->active_headers = std::move(request_headers); + transfer->active_content_length = content_length; + transfer->redirect_count = redirect_count; + transfer->error_buf[0] = '\0'; + + CURL* raw_easy = easy.get(); + curl_easy_setopt(raw_easy, CURLOPT_ERRORBUFFER, transfer->error_buf); + curl_easy_setopt(raw_easy, CURLOPT_NOSIGNAL, 1L); + curl_easy_setopt(raw_easy, CURLOPT_PROTOCOLS_STR, "http,https"); + curl_easy_setopt(raw_easy, CURLOPT_UNRESTRICTED_AUTH, 0L); + // Redirects are followed manually via HandleRedirect so method rewrites, + // redirect limits, HTTPS downgrade blocking, and cross-origin header + // stripping stay consistent with Android and Apple. + curl_easy_setopt(raw_easy, CURLOPT_FOLLOWLOCATION, 0L); + curl_easy_setopt(raw_easy, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L); + curl_easy_setopt(raw_easy, CURLOPT_TCP_NODELAY, 1L); + curl_easy_setopt(raw_easy, CURLOPT_BUFFERSIZE, 256L * 1024L); + curl_easy_setopt(raw_easy, CURLOPT_UPLOAD_BUFFERSIZE, 256L * 1024L); + curl_easy_setopt(raw_easy, CURLOPT_CONNECTTIMEOUT_MS, 60000L); + curl_easy_setopt(raw_easy, CURLOPT_TIMEOUT_MS, 0L); + + curl_easy_setopt(raw_easy, CURLOPT_URL, transfer->current_url.c_str()); + curl_easy_setopt(raw_easy, CURLOPT_PRIVATE, transfer.get()); + curl_easy_setopt(raw_easy, CURLOPT_HEADERFUNCTION, OnCurlHeader); + curl_easy_setopt(raw_easy, CURLOPT_HEADERDATA, transfer.get()); + curl_easy_setopt(raw_easy, CURLOPT_WRITEFUNCTION, OnCurlWrite); + curl_easy_setopt(raw_easy, CURLOPT_WRITEDATA, transfer.get()); + + if (!op->proxy_url.empty()) { + curl_easy_setopt(raw_easy, CURLOPT_PROXY, op->proxy_url.c_str()); + } + + bool has_expect = HasHeaderIgnoreCase(transfer->active_headers, "Expect"); + bool has_transfer_encoding = + HasHeaderIgnoreCase(transfer->active_headers, "Transfer-Encoding"); + bool has_content_length = + HasHeaderIgnoreCase(transfer->active_headers, "Content-Length"); + + curl_slist* raw_headers = nullptr; + for (const auto& kv : transfer->active_headers) { + std::string line; + line.reserve(kv.first.size() + kv.second.size() + 2); + line.append(kv.first); + line.append(": "); + line.append(kv.second); + raw_headers = curl_slist_append(raw_headers, line.c_str()); + } + if (!has_expect) { + // Disable libcurl's automatic "Expect: 100-continue" wait on uploads. + raw_headers = curl_slist_append(raw_headers, "Expect:"); + } + + if (content_length == kNoRequestContent) { + if (AsciiEqualsIgnoreCase(transfer->active_method, "HEAD")) { + curl_easy_setopt(raw_easy, CURLOPT_NOBODY, 1L); + } else if (AsciiEqualsIgnoreCase(transfer->active_method, "GET")) { + curl_easy_setopt(raw_easy, CURLOPT_HTTPGET, 1L); + } else { + curl_easy_setopt(raw_easy, CURLOPT_CUSTOMREQUEST, + transfer->active_method.c_str()); + if (!has_content_length && + (AsciiEqualsIgnoreCase(transfer->active_method, "POST") || + AsciiEqualsIgnoreCase(transfer->active_method, "PUT") || + AsciiEqualsIgnoreCase(transfer->active_method, "PATCH"))) { + raw_headers = curl_slist_append(raw_headers, "Content-Length: 0"); + } + } + } else { + curl_easy_setopt(raw_easy, CURLOPT_UPLOAD, 1L); + curl_easy_setopt(raw_easy, CURLOPT_CUSTOMREQUEST, + transfer->active_method.c_str()); + curl_easy_setopt(raw_easy, CURLOPT_READFUNCTION, OnCurlRead); + curl_easy_setopt(raw_easy, CURLOPT_READDATA, transfer.get()); + if (content_length >= 0) { + curl_easy_setopt(raw_easy, CURLOPT_INFILESIZE_LARGE, + static_cast(content_length)); + } else if (!has_transfer_encoding) { + raw_headers = + curl_slist_append(raw_headers, "Transfer-Encoding: chunked"); + } + } + + transfer->headers.reset(raw_headers); + if (transfer->headers != nullptr) { + curl_easy_setopt(raw_easy, CURLOPT_HTTPHEADER, transfer->headers.get()); + } + transfer->easy = std::move(easy); + return transfer; + } + + 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."); + continue; + } + auto transfer = + BuildTransfer(op, op->url, op->method, op->request_headers, + op->content_length, 0); + if (!transfer) { + continue; + } + CURLMcode mc = + curl_multi_add_handle(multi_.get(), transfer->easy.get()); + if (mc != CURLM_OK) { + op->MarkFailed(curl_multi_strerror(mc)); + 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; + curl_multi_perform(multi_.get(), &still_running); + + bool added_redirect = false; + 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 (!owned_transfer->redirect_blocked_error.empty()) { + owned_transfer->op->MarkFailed( + owned_transfer->redirect_blocked_error); + } else if (!owned_transfer->redirect_url.empty()) { + if (HandleRedirect(std::move(owned_transfer))) { + added_redirect = true; + } + } else 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); + } + } + } + + if (added_redirect) { + // Drive newly added redirect handles immediately with + // curl_multi_perform rather than sleeping up to 1000 ms in + // curl_multi_poll first. + continue; + } + + if (!active_.empty()) { + int numfds = 0; + curl_multi_poll(multi_.get(), nullptr, 0, 1000, &numfds); + } + } + } + + bool HandleRedirect(std::unique_ptr prev) { + if (!prev) { + return false; + } + auto op = prev->op; + if (prev->redirect_count >= kMaxRedirects) { + op->MarkFailed("Maximum HTTP redirects exceeded."); + return false; + } + + int32_t status = prev->redirect_status; + std::string next_method = prev->active_method; + int64_t next_content_len = prev->active_content_length; + if (status == 303 || ((status == 301 || status == 302) && + !AsciiEqualsIgnoreCase(next_method, "GET") && + !AsciiEqualsIgnoreCase(next_method, "HEAD"))) { + next_method = "GET"; + next_content_len = kNoRequestContent; + } else if (next_content_len != kNoRequestContent && next_content_len != 0) { + op->MarkFailed("Cannot replay streamed request body across redirect."); + return false; + } + + bool same_origin = IsSameOrigin(op->url, prev->redirect_url) && + IsSameOrigin(prev->current_url, prev->redirect_url); + std::vector> filtered; + filtered.reserve(prev->active_headers.size()); + for (const auto& kv : prev->active_headers) { + if (!same_origin && (IsSensitiveRedirectHeader(kv.first) || + AsciiEqualsIgnoreCase(kv.first, "Host"))) { + continue; + } + if (next_content_len == kNoRequestContent && + (AsciiEqualsIgnoreCase(kv.first, "Content-Type") || + AsciiEqualsIgnoreCase(kv.first, "Content-Length") || + AsciiEqualsIgnoreCase(kv.first, "Transfer-Encoding"))) { + continue; + } + filtered.push_back(kv); + } + + auto next_transfer = BuildTransfer( + op, std::move(prev->redirect_url), std::move(next_method), + std::move(filtered), next_content_len, prev->redirect_count + 1); + if (!next_transfer) { + return false; + } + CURLMcode mc = + curl_multi_add_handle(multi_.get(), next_transfer->easy.get()); + if (mc != CURLM_OK) { + op->MarkFailed(curl_multi_strerror(mc)); + return false; + } + active_.emplace(op->id, std::move(next_transfer)); + return true; + } + + ::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/tests/CMakeLists.txt b/app/http/tests/CMakeLists.txt new file mode 100644 index 0000000000..0d5ed5bb16 --- /dev/null +++ b/app/http/tests/CMakeLists.txt @@ -0,0 +1,31 @@ +# 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 +) + +if(WIN32) + target_link_libraries(firebase_app_http_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..cfde58cca7 --- /dev/null +++ b/app/http/tests/http_transport_common_test.cc @@ -0,0 +1,292 @@ +/* + * 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 "gtest/gtest.h" + +namespace firebase { +namespace http { +namespace { + +TEST(HttpTransportCommonTest, ParseUrlOriginStandardAndDefaults) { + auto https = ParseUrlOrigin("HTTPS://FireBaseStorage.GoogleAPIs.com/v0/b/x"); + ASSERT_TRUE(https.has_value()); + EXPECT_EQ(https->scheme, "https"); + EXPECT_EQ(https->host, "firebasestorage.googleapis.com"); + EXPECT_EQ(https->port, 443); + + auto http = ParseUrlOrigin("http://localhost/foo?bar=1"); + ASSERT_TRUE(http.has_value()); + EXPECT_EQ(http->scheme, "http"); + EXPECT_EQ(http->host, "localhost"); + EXPECT_EQ(http->port, 80); + + auto explicit_port = ParseUrlOrigin("http://127.0.0.1:5001/proj/us/fn"); + ASSERT_TRUE(explicit_port.has_value()); + EXPECT_EQ(explicit_port->scheme, "http"); + EXPECT_EQ(explicit_port->host, "127.0.0.1"); + EXPECT_EQ(explicit_port->port, 5001); + + auto ipv6 = ParseUrlOrigin("https://[::1]:8443/path"); + ASSERT_TRUE(ipv6.has_value()); + EXPECT_EQ(ipv6->host, "[::1]"); + EXPECT_EQ(ipv6->port, 8443); + + auto userinfo = ParseUrlOrigin("https://user:pass@Example.COM/p"); + ASSERT_TRUE(userinfo.has_value()); + EXPECT_EQ(userinfo->host, "example.com"); + EXPECT_EQ(userinfo->port, 443); +} + +TEST(HttpTransportCommonTest, ParseUrlOriginRejectsUnsafeInputs) { + EXPECT_FALSE(ParseUrlOrigin("").has_value()); + EXPECT_FALSE(ParseUrlOrigin("file:///etc/passwd").has_value()); + EXPECT_FALSE(ParseUrlOrigin("ftp://example.com/a").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://evil.com\\@trusted.com/p").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://bad host/p").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://example.com:0/p").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://example.com:70000/p").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://example.com:abc/p").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://[::1/p").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://[]/p").has_value()); +} + +TEST(HttpTransportCommonTest, IsSameOriginComparesNormalizedTuples) { + EXPECT_TRUE( + IsSameOrigin("https://Example.COM/a", "HTTPS://example.com:443/b")); + EXPECT_TRUE(IsSameOrigin("http://localhost/a", "http://localhost:80/b")); + EXPECT_FALSE(IsSameOrigin("https://example.com/a", "http://example.com/a")); + EXPECT_FALSE( + IsSameOrigin("http://127.0.0.1:8080/a", "http://127.0.0.1:8081/a")); + EXPECT_FALSE( + IsSameOrigin("https://a.example.com/", "https://b.example.com/")); + EXPECT_FALSE(IsSameOrigin("not-a-url", "https://example.com/")); +} + +TEST(HttpTransportCommonTest, SensitiveRedirectHeadersMatchCaseInsensitively) { + EXPECT_TRUE(IsSensitiveRedirectHeader("Authorization")); + EXPECT_TRUE(IsSensitiveRedirectHeader("authorization")); + EXPECT_TRUE(IsSensitiveRedirectHeader("Proxy-Authorization")); + EXPECT_TRUE(IsSensitiveRedirectHeader("X-Firebase-AppCheck")); + EXPECT_TRUE(IsSensitiveRedirectHeader("x-firebase-appcheck")); + EXPECT_TRUE(IsSensitiveRedirectHeader("x-goog-api-key")); + EXPECT_TRUE(IsSensitiveRedirectHeader("X-Goog-Api-Key")); + EXPECT_FALSE(IsSensitiveRedirectHeader("Content-Type")); + EXPECT_FALSE(IsSensitiveRedirectHeader("X-Custom-Header")); +} + +TEST(HttpTransportCommonTest, ResolveRedirectUrlRfc3986Forms) { + const std::string base = + "https://storage.example.com/v0/b/my-bucket/o?a=1#frag"; + + EXPECT_EQ(ResolveRedirectUrl(base, "https://cdn.example.com/file"), + "https://cdn.example.com/file"); + EXPECT_EQ(ResolveRedirectUrl(base, "//cdn.example.com/file"), + "https://cdn.example.com/file"); + EXPECT_EQ(ResolveRedirectUrl(base, "/new/path?x=2"), + "https://storage.example.com/new/path?x=2"); + EXPECT_EQ(ResolveRedirectUrl(base, "?next=1"), + "https://storage.example.com/v0/b/my-bucket/o?next=1"); + EXPECT_EQ(ResolveRedirectUrl(base, "#other"), + "https://storage.example.com/v0/b/my-bucket/o?a=1#other"); + EXPECT_EQ(ResolveRedirectUrl(base, "sibling.bin"), + "https://storage.example.com/v0/b/my-bucket/sibling.bin"); + EXPECT_EQ(ResolveRedirectUrl(base, "next?redir=http://ignored.example/x"), + "https://storage.example.com/v0/b/my-bucket/next?redir=http://" + "ignored.example/x"); +} + +TEST(HttpTransportCommonTest, ResolveRedirectUrlBlocksDowngradesAndConfusion) { + const std::string https_base = "https://example.com/a/b"; + EXPECT_FALSE( + ResolveRedirectUrl(https_base, "http://example.com/a/b").has_value()); + EXPECT_FALSE( + ResolveRedirectUrl(https_base, "file:///etc/passwd").has_value()); + EXPECT_FALSE( + ResolveRedirectUrl(https_base, "data:text/plain,hi").has_value()); + EXPECT_FALSE( + ResolveRedirectUrl(https_base, "javascript:alert(1)").has_value()); + EXPECT_FALSE(ResolveRedirectUrl(https_base, "\\\\evil.com/x").has_value()); + EXPECT_FALSE(ResolveRedirectUrl(https_base, "/\\evil.com/x").has_value()); + EXPECT_FALSE(ResolveRedirectUrl(https_base, "/bad\r\nHeader: 1").has_value()); + EXPECT_FALSE(ResolveRedirectUrl(https_base, "").has_value()); + EXPECT_FALSE(ResolveRedirectUrl(https_base, ":no-scheme").has_value()); + + // HTTP -> HTTP and HTTP -> HTTPS are both allowed. + EXPECT_EQ(ResolveRedirectUrl("http://127.0.0.1:8080/a", "/b"), + "http://127.0.0.1:8080/b"); + EXPECT_EQ( + ResolveRedirectUrl("http://127.0.0.1:8080/a", "https://example.com/b"), + "https://example.com/b"); +} + +TEST(HttpTransportCommonTest, ParseProxyHostPort) { + auto p1 = ParseProxyHostPort("http://127.0.0.1:8888"); + ASSERT_TRUE(p1.has_value()); + EXPECT_EQ(p1->first, "127.0.0.1"); + EXPECT_EQ(p1->second, 8888); + + auto p2 = ParseProxyHostPort("proxy.local:3128"); + ASSERT_TRUE(p2.has_value()); + EXPECT_EQ(p2->first, "proxy.local"); + EXPECT_EQ(p2->second, 3128); + + auto p3 = ParseProxyHostPort("http://[::1]:8080/"); + ASSERT_TRUE(p3.has_value()); + EXPECT_EQ(p3->first, "::1"); + EXPECT_EQ(p3->second, 8080); + + EXPECT_FALSE(ParseProxyHostPort("").has_value()); + EXPECT_FALSE(ParseProxyHostPort("socks5://127.0.0.1:1080").has_value()); +} + +TEST(HttpTransportCommonTest, ParsePackedHeadersPreservesDuplicates) { + auto headers = ParsePackedHeaders( + "Authorization\tBearer tok\n" + "X-Multi\tfirst\r\n" + "X-Multi\tsecond\n" + "Content-Type: application/json\n"); + 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"))); +} + +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) { + 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 fail + // immediately instead of blocking forever. + bool saw_req_space_event = false; + for (int i = 0; i < 8; ++i) { + int64_t ev = HttpWaitNextEventInternal(0); + if (ev == 0) { + break; + } + if ((ev >> 8) == handle && static_cast(ev & 0xFF) == + kHttpEventRequestSpaceAvailable) { + saw_req_space_event = true; + } + } + EXPECT_TRUE(saw_req_space_event); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 64), -1); + + 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..3aba6d0861 --- /dev/null +++ b/app/http/tests/http_transport_curl_test.cc @@ -0,0 +1,1067 @@ +/* + * 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 + +#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 +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 +} + +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()); +} + +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, redirects, and concurrent connections). +class LoopbackHttpServer { + public: + using Handler = std::function; + + explicit LoopbackHttpServer(Handler handler) : handler_(std::move(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; + } + // Wake AcceptLoop() portably across Linux, macOS, and Windows (where + // shutdown() on an unconnected listening socket returns ENOTCONN / + // WSAENOTCONN without waking accept()). `select()` with a 50 ms timeout in + // AcceptLoop() also guarantees termination if self-connect is refused. + 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; + } + fd_set read_fds; + FD_ZERO(&read_fds); + FD_SET(fd, &read_fds); + timeval tv{}; + tv.tv_sec = 0; + tv.tv_usec = 50 * 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 + if (ready <= 0) { + 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) { + // Consume trailing CRLF after 0-length chunk. + 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) { + ParsedRequest req; + if (!ReadHttpRequest(fd, &req)) { + return; + } + handler_(req, fd); + } + + Handler handler_; + std::atomic listen_fd_{kInvalidSocket}; + int port_ = 0; + std::atomic stopped_{false}; + std::thread accept_thread_; + std::mutex workers_mutex_; + std::vector workers_; +}; + +// Synchronously drives an operation via the flat bridge API until response +// headers arrive (returning HTTP status code or -1 on error/cancel). +int32_t WaitHeaders(int64_t handle, int timeout_ms = 5000) { + auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + while (std::chrono::steady_clock::now() < deadline) { + int32_t status = HttpPollResponseHeadersInternal(handle); + if (status != 0) { + return status; + } + HttpWaitNextEventInternal(50); + } + return 0; +} + +bool ReadAllBody(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 (std::chrono::steady_clock::now() < deadline) { + 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; + } + HttpWaitNextEventInternal(50); + } + return false; +} + +bool WriteAllBody(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 && std::chrono::steady_clock::now() < deadline) { + 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 false; + if (n > 0) { + offset += static_cast(n); + continue; + } + HttpWaitNextEventInternal(50); + } + if (offset != len) return false; + HttpFinishRequestBodyInternal(handle); + return true; +} + +TEST(HttpTransportCurlTest, GetBasic200AndMultiValueHeaders) { + 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(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(h, &body)); + EXPECT_EQ(body, "world"); + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, PostJsonAndError400And204NoContent) { + 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(h1, reinterpret_cast(payload.data()), + payload.size())); + ASSERT_EQ(WaitHeaders(h1), 200); + std::string body1; + ASSERT_TRUE(ReadAllBody(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(h2), 400); + std::string body2; + ASSERT_TRUE(ReadAllBody(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(h3), 204); + std::string body3; + ASSERT_TRUE(ReadAllBody(h3, &body3)); + EXPECT_TRUE(body3.empty()); + HttpDestroyRequestInternal(h3); +} + +TEST(HttpTransportCurlTest, SseTrickleStreamingImmediateDelivery) { + // Deterministic barrier: server does NOT send chunk 2 until the client has + // already received and parsed chunk 1! Any intermediate buffering would time + // out and fail this test. + 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(h, reinterpret_cast(req_body.data()), + req_body.size())); + ASSERT_EQ(WaitHeaders(h), 200); + + auto read_until = [&](std::string* accum, std::string_view needle) -> bool { + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + char buf[1024]; + while (accum->find(needle) == std::string::npos && + std::chrono::steady_clock::now() < deadline) { + 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 { + HttpWaitNextEventInternal(25); + } + } + 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(h, &rest)); + accum.append(rest); + EXPECT_NE(accum.find("data: {\"seq\":3}\n\n"), std::string::npos); + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, SseIdleCancelUnblocksPromptly) { + std::mutex stop_mu; + std::condition_variable stop_cv; + bool release_server = 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"); + std::unique_lock lock(stop_mu); + stop_cv.wait_for(lock, std::chrono::seconds(10), + [&]() { return release_server; }); + }); + + int64_t h = HttpCreateRequestInternal("GET", server.Url("/hang").c_str(), + "Accept\ttext/event-stream\n", "", + kNoRequestContent); + HttpStartRequestInternal(h); + ASSERT_EQ(WaitHeaders(h), 200); + + // Read the first SSE chunk. + std::string got; + char buf[512]; + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (got.empty() && std::chrono::steady_clock::now() < deadline) { + int32_t n = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); + if (n > 0) { + got.append(buf, static_cast(n)); + } else { + HttpWaitNextEventInternal(25); + } + } + EXPECT_EQ(got, "data: {\"ok\":true}\n"); + + // Arm a read while server is silent, then cancel from another thread. + ASSERT_EQ(HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)), + kHttpReadWouldBlock); + auto t0 = std::chrono::steady_clock::now(); + std::thread canceler([h]() { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + HttpCancelRequestInternal(h); + }); + + int32_t rc = kHttpReadWouldBlock; + while (rc == kHttpReadWouldBlock && + std::chrono::steady_clock::now() - t0 < std::chrono::seconds(3)) { + HttpWaitNextEventInternal(50); + 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_LT(elapsed_ms, 1000); + + HttpDestroyRequestInternal(h); + { + std::lock_guard lock(stop_mu); + release_server = true; + } + stop_cv.notify_all(); +} + +TEST(HttpTransportCurlTest, + RedirectsSameOriginPreservesAuthAndCrossOriginStrips) { + std::string observed_b_auth; + std::string observed_b_appcheck; + std::string observed_b_apikey; + std::string observed_b_safe; + std::string observed_b_method; + std::mutex obs_mu; + + LoopbackHttpServer server_b([&](const ParsedRequest& req, SocketFd fd) { + { + std::lock_guard lock(obs_mu); + observed_b_method = req.method; + observed_b_auth = req.GetHeader("Authorization"); + observed_b_appcheck = req.GetHeader("X-Firebase-AppCheck"); + observed_b_apikey = req.GetHeader("x-goog-api-key"); + observed_b_safe = req.GetHeader("X-Safe"); + } + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 4\r\n" + "Connection: close\r\n\r\ndone"); + }); + + std::string observed_same_origin_auth; + std::string observed_same_origin_method; + LoopbackHttpServer server_a([&](const ParsedRequest& req, SocketFd fd) { + if (req.target == "/same-302") { + SendAll(fd, + "HTTP/1.1 302 Found\r\n" + "Location: /same-target\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n\r\n"); + } else if (req.target == "/same-target") { + { + std::lock_guard lock(obs_mu); + observed_same_origin_method = req.method; + observed_same_origin_auth = req.GetHeader("Authorization"); + } + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: close\r\n\r\nok"); + } else if (req.target == "/cross-307") { + SendAll(fd, + "HTTP/1.1 307 Temporary Redirect\r\n" + "Location: " + + server_b.Url("/final") + + "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + } else if (req.target == "/loop") { + SendAll(fd, + "HTTP/1.1 302 Found\r\n" + "Location: /loop\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n\r\n"); + } else if (req.target == "/unsafe") { + SendAll(fd, + "HTTP/1.1 302 Found\r\n" + "Location: file:///etc/passwd\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n\r\n"); + } + }); + + // 1. Same-origin 302 POST -> GET rewrites method and preserves Authorization. + int64_t h1 = HttpCreateRequestInternal( + "POST", server_a.Url("/same-302").c_str(), + "Authorization\tBearer secret\nContent-Type\tapplication/json\n", "", 0); + HttpStartRequestInternal(h1); + ASSERT_EQ(WaitHeaders(h1), 200); + std::string b1; + ASSERT_TRUE(ReadAllBody(h1, &b1)); + EXPECT_EQ(b1, "ok"); + { + std::lock_guard lock(obs_mu); + EXPECT_EQ(observed_same_origin_method, "GET"); + EXPECT_EQ(observed_same_origin_auth, "Bearer secret"); + } + HttpDestroyRequestInternal(h1); + + // 2. Cross-origin 307 strips sensitive headers, forwards safe headers. + int64_t h2 = + HttpCreateRequestInternal("GET", server_a.Url("/cross-307").c_str(), + "Authorization\tBearer secret\n" + "X-Firebase-AppCheck\tappcheck-tok\n" + "x-goog-api-key\tapi-key\n" + "X-Safe\tkeep-me\n", + "", kNoRequestContent); + HttpStartRequestInternal(h2); + ASSERT_EQ(WaitHeaders(h2), 200); + std::string b2; + ASSERT_TRUE(ReadAllBody(h2, &b2)); + EXPECT_EQ(b2, "done"); + { + std::lock_guard lock(obs_mu); + EXPECT_EQ(observed_b_method, "GET"); + EXPECT_TRUE(observed_b_auth.empty()); + EXPECT_TRUE(observed_b_appcheck.empty()); + EXPECT_TRUE(observed_b_apikey.empty()); + EXPECT_EQ(observed_b_safe, "keep-me"); + } + HttpDestroyRequestInternal(h2); + + // 3. Infinite redirect loop fails once kMaxRedirects is exceeded. + int64_t h3 = HttpCreateRequestInternal("GET", server_a.Url("/loop").c_str(), + "", "", kNoRequestContent); + HttpStartRequestInternal(h3); + EXPECT_EQ(WaitHeaders(h3), -1); + EXPECT_NE(HttpGetErrorInternal(h3).find("Maximum HTTP redirects"), + std::string::npos); + HttpDestroyRequestInternal(h3); + + // 4. Non-HTTP(S) redirect target is blocked. + int64_t h4 = HttpCreateRequestInternal("GET", server_a.Url("/unsafe").c_str(), + "", "", kNoRequestContent); + HttpStartRequestInternal(h4); + EXPECT_EQ(WaitHeaders(h4), -1); + EXPECT_NE(HttpGetErrorInternal(h4).find("Blocked unsafe"), std::string::npos); + HttpDestroyRequestInternal(h4); +} + +TEST(HttpTransportCurlTest, + StreamingChunkedUploadAndLargeDownloadBackpressure) { + constexpr size_t kUploadSize = 1024 * 1024; // 1 MiB (> 256 KiB pipe) + constexpr size_t kDownloadSize = 4 * 1024 * 1024; // 4 MiB (> 2 MiB pipe) + + std::vector expected_upload(kUploadSize); + for (size_t i = 0; i < kUploadSize; ++i) { + expected_upload[i] = static_cast((i * 31 + 7) & 0xFF); + } + std::vector expected_download(kDownloadSize); + for (size_t i = 0; i < kDownloadSize; ++i) { + expected_download[i] = static_cast((i * 17 + 3) & 0xFF); + } + + std::mutex upload_mu; + std::string server_received_upload; + 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(expected_download.size()) + + "\r\nConnection: close\r\n\r\n"); + SendAll(fd, reinterpret_cast(expected_download.data()), + expected_download.size()); + } + }); + + // 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(h_up, expected_upload.data(), expected_upload.size())); + ASSERT_EQ(WaitHeaders(h_up), 200); + std::string up_resp; + ASSERT_TRUE(ReadAllBody(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. Large download exceeding kMaxResponseBufferBytes with intentional slow + // drain to trigger CURL_WRITEFUNC_PAUSE + low-water resume. + int64_t h_dl = HttpCreateRequestInternal( + "GET", server.Url("/download").c_str(), "", "", kNoRequestContent); + HttpStartRequestInternal(h_dl); + ASSERT_EQ(WaitHeaders(h_dl), 200); + + // Pause reading briefly so curl fills the 2 MiB buffer and hits + // WRITEFUNC_PAUSE. + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + + std::string dl_body; + dl_body.reserve(kDownloadSize); + ASSERT_TRUE(ReadAllBody(h_dl, &dl_body, 15000)); + ASSERT_EQ(dl_body.size(), expected_download.size()); + EXPECT_EQ(std::memcmp(dl_body.data(), expected_download.data(), + expected_download.size()), + 0); + HttpDestroyRequestInternal(h_dl); +} + +TEST(HttpTransportCurlTest, ConcurrentMixedTransfers) { + 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"); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + 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(handles[i]), 200); + std::string body; + ASSERT_TRUE(ReadAllBody(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(handles[i]), 200); + std::string body; + ASSERT_TRUE(ReadAllBody(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, EarlyServerResponseUnblocksLargeUpload) { + // Server sends an immediate 413 response with Content-Length: 0 and closes + // as soon as request headers arrive, without reading the >256 KiB upload + // body. Verifies MarkResponseComplete() wakes the blocked request-body writer + // instead of hanging forever. + EnsureSocketSubsystemInitialized(); + SocketFd listen_fd = socket(AF_INET, SOCK_STREAM, 0); + ASSERT_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; + ASSERT_EQ(bind(listen_fd, reinterpret_cast(&addr), sizeof(addr)), + 0); + ASSERT_EQ(listen(listen_fd, 4), 0); + sockaddr_in bound{}; +#if defined(_WIN32) + int bound_len = sizeof(bound); +#else + socklen_t bound_len = sizeof(bound); +#endif + ASSERT_EQ( + getsockname(listen_fd, reinterpret_cast(&bound), &bound_len), + 0); + int raw_port = ntohs(bound.sin_port); + + std::thread raw_server([listen_fd]() { + sockaddr_in client_addr{}; +#if defined(_WIN32) + int len = sizeof(client_addr); +#else + socklen_t len = sizeof(client_addr); +#endif + SocketFd c = + accept(listen_fd, reinterpret_cast(&client_addr), &len); + if (c != kInvalidSocket) { +#ifdef SO_NOSIGPIPE + int nosigpipe = 1; + setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, + reinterpret_cast(&nosigpipe), sizeof(nosigpipe)); +#endif + std::string hdrs; + char tmp[1024]; + while (hdrs.find("\r\n\r\n") == std::string::npos) { +#if defined(_WIN32) + int n = recv(c, tmp, sizeof(tmp), 0); +#else + ssize_t n = recv(c, tmp, sizeof(tmp), 0); +#endif + if (n <= 0) break; + hdrs.append(tmp, static_cast(n)); + } + SendAll(c, + "HTTP/1.1 413 Payload Too Large\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"); + CloseSocket(c); + } + CloseSocket(listen_fd); + }); + + constexpr size_t kLargeUpload = 2 * 1024 * 1024; + std::string url = + "http://127.0.0.1:" + std::to_string(raw_port) + "/early-reject"; + int64_t h = HttpCreateRequestInternal( + "PUT", url.c_str(), "Content-Type\tapplication/octet-stream\n", "", + static_cast(kLargeUpload)); + HttpStartRequestInternal(h); + + std::vector payload(kLargeUpload, 0x42); + auto t0 = std::chrono::steady_clock::now(); + // WriteAllBody should terminate promptly (returning false once 413 completes) + // rather than blocking until its 5s timeout. + bool finished_upload = WriteAllBody(h, payload.data(), payload.size(), 5000); + auto elapsed_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0) + .count(); + EXPECT_FALSE(finished_upload); + EXPECT_LT(elapsed_ms, 3000); + EXPECT_EQ(WaitHeaders(h, 2000), 413); + + HttpDestroyRequestInternal(h); + raw_server.join(); +} + +} // namespace +} // 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} From 65563486906f6f3eaff5181febbe613db8d4e185 Mon Sep 17 00:00:00 2001 From: Austin Benoit Date: Fri, 27 Nov 2026 13:51:26 -0500 Subject: [PATCH 02/16] [App][HTTP] Harden shared validation, error classes, Cookie strip, and cancel-all (S1-S5, C3, U2) --- app/http/http_bridge.h | 20 +- app/http/http_transport.h | 81 ++++++- app/http/http_transport_common.cc | 353 +++++++++++++++++++++++------- 3 files changed, 368 insertions(+), 86 deletions(-) diff --git a/app/http/http_bridge.h b/app/http/http_bridge.h index 0bfa842e45..f93e3915c9 100644 --- a/app/http/http_bridge.h +++ b/app/http/http_bridge.h @@ -44,8 +44,8 @@ int64_t HttpCreateRequestInternal(const char* method, const char* url, void HttpStartRequestInternal(int64_t handle); // Non-blocking write of up to `length` request body bytes into the bounded -// upload pipe. Returns bytes accepted (`0` when full), or `-1` on failure or -// cancellation. +// upload pipe. Returns bytes accepted (`0` when full), or `-1` on failure, +// invalid arguments, early server response, or cancellation. int32_t HttpTryWriteRequestBodyInternal(int64_t handle, void* data, int32_t length); @@ -63,19 +63,33 @@ 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 transport error or cancellation. +// 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, I/O abort) +// 3 = TLS (certificate verification, handshake, SSL policy failure) +// 4 = Timeout (connect or transfer timeout) +// 5 = Other (invalid request/arguments, redirect policy, protocol, unknown) +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. diff --git a/app/http/http_transport.h b/app/http/http_transport.h index 724e7c2084..901ed648c8 100644 --- a/app/http/http_transport.h +++ b/app/http/http_transport.h @@ -20,9 +20,35 @@ // - Apple mobile (iOS / tvOS): ARC NSURLSession with bound-stream uploads. // - Android: JNI HttpURLConnection on a bounded worker thread pool. // -// Supports full-duplex streaming uploads and downloads with bounded socket -// backpressure, immediate incremental delivery for Server-Sent Events (SSE), -// deterministic cancellation, and uniform RFC 3986 redirect/credential policy. +// Streaming and platform behavioral guarantees: +// - Bounded backpressure in both directions (`kMaxRequestBufferBytes` upload +// pipe, `kMaxResponseBufferBytes` download buffer) and immediate +// incremental delivery for Server-Sent Events (SSE) on all three backends. +// - Desktop (libcurl) and Apple (NSURLSession) stream request uploads and +// response downloads concurrently (full-duplex). Android's +// `HttpURLConnection` is half-duplex (streams the request body before +// reading response headers), and on upload write failure it still reads and +// delivers an early HTTP 4xx/5xx response when the server sent one. +// - Uniform redirect and credential policy across all three backends: +// up to `kMaxRedirects`, RFC 3986 relative resolution (percent-encoding +// spaces in path/query/fragment), rejection of non-HTTP(S) targets, +// URL userinfo, and `https` -> `http` downgrades, 301/302/303 method +// rewrite to `GET` (keeping `GET` and `HEAD`), rejection of non-replayable +// streamed request bodies across 307/308, and cross-origin stripping of +// `Authorization`, `Proxy-Authorization`, `Cookie`, `X-Firebase-AppCheck`, +// `x-goog-api-key`, and `Host`. +// - Connect timeout: Desktop (libcurl) and Android (`HttpURLConnection`) +// enforce a 60-second connect timeout. Apple (`NSURLSession`) does not +// expose a connect-only timeout separate from idle read timeout, so it +// relies on the OS TCP connect timeout while keeping +// `timeoutIntervalForRequest` high so idle SSE streams are not terminated. +// - Response headers and reason phrases: Desktop and Android return the +// server-sent reason phrase and preserve duplicate response headers as +// separate entries. Apple's `NSHTTPURLResponse` does not expose raw +// HTTP/1.1 reason phrases or unmerged header lists, so Apple returns +// canonical RFC 9110 English reason phrases (falling back to +// `localizedStringForStatusCode:`) and coalesces duplicate response headers +// per `NSHTTPURLResponse.allHeaderFields`. #ifndef FIREBASE_APP_HTTP_HTTP_TRANSPORT_H_ #define FIREBASE_APP_HTTP_HTTP_TRANSPORT_H_ @@ -59,6 +85,17 @@ enum HttpEventKind : int32_t { kHttpEventResponseBodyAvailable = 3, }; +// Structured terminal failure categories returned by +// `HttpGetErrorClassInternal`. +enum HttpErrorClass : int32_t { + kHttpErrorNone = 0, + kHttpErrorCanceled = 1, + kHttpErrorConnect = 2, + kHttpErrorTls = 3, + kHttpErrorTimeout = 4, + kHttpErrorOther = 5, +}; + // 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; @@ -113,6 +150,7 @@ struct HttpOperation { 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). @@ -132,6 +170,7 @@ struct HttpOperation { 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. @@ -146,6 +185,12 @@ struct HttpOperation { int32_t status, std::string_view reason, std::vector> headers); + // Called by the platform backend when it stops consuming request body bytes + // (for example on an early 4xx response or a 301-303 redirect to GET) so a + // caller blocked in `HttpTryWriteRequestBodyInternal` wakes promptly without + // failing the response. + 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 @@ -156,7 +201,8 @@ struct HttpOperation { void MarkResponseComplete(); // Called by the platform backend when a transport error aborts the transfer. - void MarkFailed(std::string_view message); + 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 @@ -171,6 +217,7 @@ 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`. @@ -193,8 +240,21 @@ 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 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` (or `Name: Value\n`) header lines into ordered pairs, -// preserving duplicate header names. +// preserving duplicate header names. Returns false if any line contains CR, +// LF, NUL, an invalid header token name, or an invalid header value. +bool TryParsePackedHeaders( + std::string_view packed, + std::vector>* out); + +// Convenience wrapper returning parsed headers, or an empty vector if invalid. std::vector> ParsePackedHeaders( std::string_view packed); @@ -205,7 +265,8 @@ struct UrlOrigin { }; // Parses scheme (`http` or `https` only), lowercased host, and effective port -// (`80` / `443` when omitted) from an absolute HTTP(S) URL. +// (`80` / `443` when omitted) from an absolute HTTP(S) URL. Rejects URLs whose +// authority contains userinfo (`@`), backslashes, whitespace, or controls. std::optional ParseUrlOrigin(std::string_view url); bool IsHttpOrHttpsUrl(std::string_view url); @@ -213,12 +274,14 @@ bool IsHttpsUrl(std::string_view url); bool IsSameOrigin(std::string_view url_a, std::string_view url_b); // Returns true for headers that must never be forwarded across a cross-origin -// redirect (`Authorization`, `Proxy-Authorization`, `X-Firebase-AppCheck`, -// `x-goog-api-key`). +// redirect (`Authorization`, `Proxy-Authorization`, `Cookie`, +// `X-Firebase-AppCheck`, `x-goog-api-key`). bool IsSensitiveRedirectHeader(std::string_view header_name); // Resolves an HTTP `Location` header against `current_url`, rejecting -// non-HTTP(S) schemes and `https` -> `http` scheme downgrades. +// non-HTTP(S) schemes, userinfo, and `https` -> `http` scheme downgrades, and +// percent-encoding ASCII spaces in the path/query/fragment so all backends +// behave identically. std::optional ResolveRedirectUrl(std::string_view current_url, std::string_view location); diff --git a/app/http/http_transport_common.cc b/app/http/http_transport_common.cc index efe646ec4e..c89c4da7df 100644 --- a/app/http/http_transport_common.cc +++ b/app/http/http_transport_common.cc @@ -68,11 +68,133 @@ bool HasControlChars(std::string_view s) { 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 -std::vector> ParsePackedHeaders( - std::string_view packed) { - std::vector> result; +bool IsValidHeaderName(std::string_view name) { + if (name.empty()) { + return false; + } + for (unsigned char ch : name) { + if (!IsHttpTchar(ch)) { + return false; + } + } + return true; +} + +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); @@ -86,18 +208,35 @@ std::vector> ParsePackedHeaders( 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 = line.find(':'); } if (sep == std::string_view::npos || sep == 0) { - continue; + out->clear(); + return false; } - std::string_view name = TrimAsciiWhitespace(line.substr(0, sep)); - std::string_view value = TrimAsciiWhitespace(line.substr(sep + 1)); - if (!name.empty()) { - result.emplace_back(std::string(name), std::string(value)); + 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; +} + +std::vector> ParsePackedHeaders( + std::string_view packed) { + std::vector> result; + if (!TryParsePackedHeaders(packed, &result)) { + result.clear(); } return result; } @@ -150,17 +289,15 @@ std::optional ParseUrlOrigin(std::string_view url) { size_t path_pos = rest.find_first_of("/?#"); std::string_view authority = path_pos == std::string_view::npos ? rest : rest.substr(0, path_pos); - // Reject backslashes (which WHATWG/OkHttp treat as path delimiters, enabling - // `https://evil.com\@trusted.com` authority confusion) and control/whitespace - // characters inside authority. - if (authority.find('\\') != std::string_view::npos || + // Reject userinfo (`@`, where parsers disagree on first vs. last `@`), + // backslashes (which WHATWG/OkHttp treat as path delimiters, enabling + // `https://evil.com\@trusted.com` authority confusion), and control or + // whitespace characters inside authority. + if (authority.find('@') != std::string_view::npos || + authority.find('\\') != std::string_view::npos || HasControlOrWhitespace(authority)) { return std::nullopt; } - size_t at_pos = authority.rfind('@'); - if (at_pos != std::string_view::npos) { - authority = authority.substr(at_pos + 1); - } if (authority.empty()) { return std::nullopt; } @@ -241,6 +378,7 @@ bool IsSameOrigin(std::string_view url_a, std::string_view url_b) { bool IsSensitiveRedirectHeader(std::string_view header_name) { return AsciiEqualsIgnoreCase(header_name, "Authorization") || AsciiEqualsIgnoreCase(header_name, "Proxy-Authorization") || + AsciiEqualsIgnoreCase(header_name, "Cookie") || AsciiEqualsIgnoreCase(header_name, "X-Firebase-AppCheck") || AsciiEqualsIgnoreCase(header_name, "x-goog-api-key"); } @@ -322,6 +460,23 @@ std::optional ResolveRedirectUrl(std::string_view current_url, if (base_origin->scheme == "https" && next_origin->scheme != "https") { return std::nullopt; } + + // Percent-encode ASCII spaces in the path/query/fragment so libcurl + // (`CURLOPT_URL`), NSURL, and java.net.URL all handle redirect targets + // containing spaces identically (spaces in the authority were already + // rejected by `ParseUrlOrigin` above). + if (candidate.find(' ') != std::string::npos) { + std::string encoded; + encoded.reserve(candidate.size() + 8); + for (char ch : candidate) { + if (ch == ' ') { + encoded.append("%20"); + } else { + encoded.push_back(ch); + } + } + candidate = std::move(encoded); + } return candidate; } @@ -374,11 +529,29 @@ int64_t CreateOperation(HttpRequestOptions options) { op->req_eof = true; } + std::string validation_error; + 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(); - std::lock_guard lock(reg.mutex); - int64_t id = reg.next_id++; - op->id = id; - reg.operations.emplace(id, std::move(op)); + 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, kHttpErrorOther); + } return id; } @@ -397,57 +570,17 @@ void StartOperation(int64_t handle) { if (op->started.exchange(true, std::memory_order_acq_rel)) { return; } - StartPlatformHttpOperation(op); -} - -void CancelOperation(int64_t handle) { - auto op = FindOperation(handle); - if (!op) { - return; - } - bool expected = false; - if (!op->canceled.compare_exchange_strong(expected, true, - std::memory_order_acq_rel)) { - return; - } - - std::function cancel_hook; - bool notify_req = false; - bool notify_headers = false; - bool notify_body = false; { std::lock_guard lock(op->mutex); - 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; + if (op->failed || op->IsCanceled()) { + return; } } - 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); - } + StartPlatformHttpOperation(op); +} + +void CancelOperation(int64_t handle) { + CancelOperationObject(FindOperation(handle)); } void DestroyOperation(int64_t handle) { @@ -457,6 +590,23 @@ void DestroyOperation(int64_t handle) { 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); + } + HttpWakeEventPumpInternal(); +} + void HttpOperation::CommitResponseHeaders( int32_t status, std::string_view reason, std::vector> headers) { @@ -480,6 +630,25 @@ void HttpOperation::CommitResponseHeaders( } } +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); @@ -516,6 +685,7 @@ void HttpOperation::MarkResponseComplete() { { std::lock_guard lock(mutex); resp_eof = true; + req_write_closed = true; req_chunks.clear(); req_buffered_bytes = 0; on_request_data_changed = nullptr; @@ -546,7 +716,8 @@ void HttpOperation::MarkResponseComplete() { } } -void HttpOperation::MarkFailed(std::string_view message) { +void HttpOperation::MarkFailed(std::string_view message, + HttpErrorClass err_class) { bool notify_req = false; bool notify_headers = false; bool notify_body = false; @@ -554,8 +725,10 @@ void HttpOperation::MarkFailed(std::string_view message) { 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; @@ -625,33 +798,51 @@ int64_t HttpCreateRequestInternal(const char* method, const char* url, 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') { - options.headers = http::ParsePackedHeaders(headers_packed); + 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; - return http::CreateOperation(std::move(options)); + int64_t handle = http::CreateOperation(std::move(options)); + if (invalid_headers) { + if (auto op = http::FindOperation(handle)) { + op->MarkFailed("Invalid HTTP request header.", http::kHttpErrorOther); + } + } + 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 0; + 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->resp_eof || op->req_write_closed || + op->IsCanceled()) { + return -1; + } + return 0; + } std::function notify_backend; int32_t to_write = 0; { std::lock_guard lock(op->mutex); - if (op->failed || op->resp_eof || op->IsCanceled()) { + if (op->failed || op->resp_eof || op->req_write_closed || + op->IsCanceled()) { return -1; } size_t available = @@ -738,7 +929,7 @@ std::string HttpGetResponseHeadersInternal(int64_t handle) { int32_t HttpTryReadResponseBodyInternal(int64_t handle, void* dest, int32_t max_length) { if (max_length <= 0 || dest == nullptr) { - return 0; + return http::kHttpReadErrorOrCanceled; } auto op = http::FindOperation(handle); if (!op) { @@ -805,6 +996,18 @@ std::string HttpGetErrorInternal(int64_t handle) { 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); } @@ -813,6 +1016,8 @@ 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); From 2c1cea3fd89fc7f551c63d4a7f2cdf35991f17a8 Mon Sep 17 00:00:00 2001 From: Austin Benoit Date: Fri, 27 Nov 2026 13:51:27 -0500 Subject: [PATCH 03/16] [App][HTTP] Fix curl HEAD-on-303, check setopt/slist/multi calls, and classify errors (C1, C2, S4) --- app/http/http_transport_curl.cc | 231 ++++++++++++++++++++++++-------- 1 file changed, 174 insertions(+), 57 deletions(-) diff --git a/app/http/http_transport_curl.cc b/app/http/http_transport_curl.cc index df6f48968a..1d4f156b79 100644 --- a/app/http/http_transport_curl.cc +++ b/app/http/http_transport_curl.cc @@ -37,6 +37,8 @@ namespace firebase { namespace http { namespace { +using ::firebase::rest::curl::ApplyOpt; + bool HasHeaderIgnoreCase( const std::vector>& headers, std::string_view target) { @@ -64,6 +66,53 @@ bool IsRedirectStatus(int32_t status) { status == 308; } +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; +} + +HttpErrorClass ClassifyCurlError(CURLcode code, bool canceled) { + if (canceled) { + return kHttpErrorCanceled; + } + switch (code) { + case CURLE_OPERATION_TIMEDOUT: + return kHttpErrorTimeout; + case CURLE_SSL_CONNECT_ERROR: + case CURLE_PEER_FAILED_VERIFICATION: + case CURLE_SSL_ENGINE_NOTFOUND: + case CURLE_SSL_ENGINE_SETFAILED: + case CURLE_SSL_CERTPROBLEM: + case CURLE_SSL_CIPHER: + case CURLE_SSL_CACERT_BADFILE: + case CURLE_SSL_SHUTDOWN_FAILED: + case CURLE_SSL_CRL_BADFILE: + case CURLE_SSL_ISSUER_ERROR: + case CURLE_SSL_PINNEDPUBKEYNOTMATCH: + case CURLE_SSL_INVALIDCERTSTATUS: + case CURLE_USE_SSL_FAILED: + case CURLE_SSL_ENGINE_INITFAILED: + case CURLE_SSL_CLIENTCERT: + return kHttpErrorTls; + 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: + return kHttpErrorConnect; + default: + return kHttpErrorOther; + } +} + struct CurlTransfer { std::shared_ptr op; ::firebase::rest::curl::UniqueEasy easy; @@ -319,20 +368,35 @@ class CurlHttpEngine { std::vector> request_headers, int64_t content_length, int redirect_count) { if (!IsHttpOrHttpsUrl(target_url)) { - op->MarkFailed( - "Unsupported URI scheme; only http and https are allowed."); + op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", + kHttpErrorOther); + return nullptr; + } + + if (!op->proxy_url.empty() && !ParseProxyHostPort(op->proxy_url)) { + op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorOther); + return nullptr; + } + + bool is_get = AsciiEqualsIgnoreCase(method, "GET"); + bool is_head = AsciiEqualsIgnoreCase(method, "HEAD"); + if ((is_get || is_head) && + (content_length > 0 || content_length == kChunkedRequestContent)) { + op->MarkFailed("GET and HEAD requests cannot send a request body.", + kHttpErrorOther); return nullptr; } ::firebase::rest::curl::UniqueEasy easy(curl_easy_init()); if (easy == nullptr) { - op->MarkFailed("Failed to initialize native libcurl handle."); + op->MarkFailed("Failed to initialize native libcurl handle.", + kHttpErrorOther); return nullptr; } CURLcode tls_rc = ::firebase::rest::curl::ApplyTlsPolicy(easy.get()); if (tls_rc != CURLE_OK) { - op->MarkFailed(curl_easy_strerror(tls_rc)); + op->MarkFailed(curl_easy_strerror(tls_rc), kHttpErrorTls); return nullptr; } @@ -346,30 +410,31 @@ class CurlHttpEngine { transfer->error_buf[0] = '\0'; CURL* raw_easy = easy.get(); - curl_easy_setopt(raw_easy, CURLOPT_ERRORBUFFER, transfer->error_buf); - curl_easy_setopt(raw_easy, CURLOPT_NOSIGNAL, 1L); - curl_easy_setopt(raw_easy, CURLOPT_PROTOCOLS_STR, "http,https"); - curl_easy_setopt(raw_easy, CURLOPT_UNRESTRICTED_AUTH, 0L); + CURLcode opt_err = CURLE_OK; + ApplyOpt(raw_easy, CURLOPT_ERRORBUFFER, transfer->error_buf, &opt_err); + ApplyOpt(raw_easy, CURLOPT_NOSIGNAL, 1L, &opt_err); + ApplyOpt(raw_easy, CURLOPT_PROTOCOLS_STR, "http,https", &opt_err); + ApplyOpt(raw_easy, CURLOPT_UNRESTRICTED_AUTH, 0L, &opt_err); // Redirects are followed manually via HandleRedirect so method rewrites, // redirect limits, HTTPS downgrade blocking, and cross-origin header // stripping stay consistent with Android and Apple. - curl_easy_setopt(raw_easy, CURLOPT_FOLLOWLOCATION, 0L); - curl_easy_setopt(raw_easy, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L); - curl_easy_setopt(raw_easy, CURLOPT_TCP_NODELAY, 1L); - curl_easy_setopt(raw_easy, CURLOPT_BUFFERSIZE, 256L * 1024L); - curl_easy_setopt(raw_easy, CURLOPT_UPLOAD_BUFFERSIZE, 256L * 1024L); - curl_easy_setopt(raw_easy, CURLOPT_CONNECTTIMEOUT_MS, 60000L); - curl_easy_setopt(raw_easy, CURLOPT_TIMEOUT_MS, 0L); - - curl_easy_setopt(raw_easy, CURLOPT_URL, transfer->current_url.c_str()); - curl_easy_setopt(raw_easy, CURLOPT_PRIVATE, transfer.get()); - curl_easy_setopt(raw_easy, CURLOPT_HEADERFUNCTION, OnCurlHeader); - curl_easy_setopt(raw_easy, CURLOPT_HEADERDATA, transfer.get()); - curl_easy_setopt(raw_easy, CURLOPT_WRITEFUNCTION, OnCurlWrite); - curl_easy_setopt(raw_easy, CURLOPT_WRITEDATA, transfer.get()); + ApplyOpt(raw_easy, CURLOPT_FOLLOWLOCATION, 0L, &opt_err); + ApplyOpt(raw_easy, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L, &opt_err); + ApplyOpt(raw_easy, CURLOPT_TCP_NODELAY, 1L, &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_CONNECTTIMEOUT_MS, 60000L, &opt_err); + ApplyOpt(raw_easy, CURLOPT_TIMEOUT_MS, 0L, &opt_err); + + ApplyOpt(raw_easy, CURLOPT_URL, transfer->current_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); if (!op->proxy_url.empty()) { - curl_easy_setopt(raw_easy, CURLOPT_PROXY, op->proxy_url.c_str()); + ApplyOpt(raw_easy, CURLOPT_PROXY, op->proxy_url.c_str(), &opt_err); } bool has_expect = HasHeaderIgnoreCase(transfer->active_headers, "Expect"); @@ -378,58 +443,96 @@ class CurlHttpEngine { bool has_content_length = HasHeaderIgnoreCase(transfer->active_headers, "Content-Length"); - curl_slist* raw_headers = nullptr; + ::firebase::rest::curl::UniqueSList header_list; for (const auto& kv : transfer->active_headers) { std::string line; line.reserve(kv.first.size() + kv.second.size() + 2); line.append(kv.first); line.append(": "); line.append(kv.second); - raw_headers = curl_slist_append(raw_headers, line.c_str()); + 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. - raw_headers = curl_slist_append(raw_headers, "Expect:"); + if (!AppendSList(&header_list, "Expect:")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } } - if (content_length == kNoRequestContent) { - if (AsciiEqualsIgnoreCase(transfer->active_method, "HEAD")) { - curl_easy_setopt(raw_easy, CURLOPT_NOBODY, 1L); - } else if (AsciiEqualsIgnoreCase(transfer->active_method, "GET")) { - curl_easy_setopt(raw_easy, CURLOPT_HTTPGET, 1L); + 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 { - curl_easy_setopt(raw_easy, CURLOPT_CUSTOMREQUEST, - transfer->active_method.c_str()); + ApplyOpt(raw_easy, CURLOPT_CUSTOMREQUEST, + transfer->active_method.c_str(), &opt_err); if (!has_content_length && (AsciiEqualsIgnoreCase(transfer->active_method, "POST") || AsciiEqualsIgnoreCase(transfer->active_method, "PUT") || AsciiEqualsIgnoreCase(transfer->active_method, "PATCH"))) { - raw_headers = curl_slist_append(raw_headers, "Content-Length: 0"); + if (!AppendSList(&header_list, "Content-Length: 0")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } } } } else { - curl_easy_setopt(raw_easy, CURLOPT_UPLOAD, 1L); - curl_easy_setopt(raw_easy, CURLOPT_CUSTOMREQUEST, - transfer->active_method.c_str()); - curl_easy_setopt(raw_easy, CURLOPT_READFUNCTION, OnCurlRead); - curl_easy_setopt(raw_easy, CURLOPT_READDATA, transfer.get()); + ApplyOpt(raw_easy, CURLOPT_UPLOAD, 1L, &opt_err); + ApplyOpt(raw_easy, CURLOPT_CUSTOMREQUEST, transfer->active_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) { - curl_easy_setopt(raw_easy, CURLOPT_INFILESIZE_LARGE, - static_cast(content_length)); + ApplyOpt(raw_easy, CURLOPT_INFILESIZE_LARGE, + static_cast(content_length), &opt_err); } else if (!has_transfer_encoding) { - raw_headers = - curl_slist_append(raw_headers, "Transfer-Encoding: chunked"); + if (!AppendSList(&header_list, "Transfer-Encoding: chunked")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } } } - transfer->headers.reset(raw_headers); + transfer->headers = std::move(header_list); if (transfer->headers != nullptr) { - curl_easy_setopt(raw_easy, CURLOPT_HTTPHEADER, transfer->headers.get()); + 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; @@ -464,7 +567,8 @@ class CurlHttpEngine { continue; } if (multi_ == nullptr) { - op->MarkFailed("Native libcurl multi engine failed to initialize."); + op->MarkFailed("Native libcurl multi engine failed to initialize.", + kHttpErrorOther); continue; } auto transfer = @@ -476,7 +580,7 @@ class CurlHttpEngine { CURLMcode mc = curl_multi_add_handle(multi_.get(), transfer->easy.get()); if (mc != CURLM_OK) { - op->MarkFailed(curl_multi_strerror(mc)); + op->MarkFailed(curl_multi_strerror(mc), kHttpErrorOther); continue; } active_.emplace(op->id, std::move(transfer)); @@ -509,7 +613,11 @@ class CurlHttpEngine { } int still_running = 0; - curl_multi_perform(multi_.get(), &still_running); + 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; + } bool added_redirect = false; int msgs_left = 0; @@ -543,7 +651,7 @@ class CurlHttpEngine { if (!owned_transfer->op->IsCanceled()) { if (!owned_transfer->redirect_blocked_error.empty()) { owned_transfer->op->MarkFailed( - owned_transfer->redirect_blocked_error); + owned_transfer->redirect_blocked_error, kHttpErrorOther); } else if (!owned_transfer->redirect_url.empty()) { if (HandleRedirect(std::move(owned_transfer))) { added_redirect = true; @@ -563,7 +671,8 @@ class CurlHttpEngine { 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); + owned_transfer->op->MarkFailed( + err, ClassifyCurlError(result, owned_transfer->op->IsCanceled())); } } } @@ -577,7 +686,11 @@ class CurlHttpEngine { if (!active_.empty()) { int numfds = 0; - curl_multi_poll(multi_.get(), nullptr, 0, 1000, &numfds); + CURLMcode poll_rc = + curl_multi_poll(multi_.get(), nullptr, 0, 1000, &numfds); + if (poll_rc != CURLM_OK) { + FailAllActive(poll_rc); + } } } } @@ -588,20 +701,24 @@ class CurlHttpEngine { } auto op = prev->op; if (prev->redirect_count >= kMaxRedirects) { - op->MarkFailed("Maximum HTTP redirects exceeded."); + op->MarkFailed("Maximum HTTP redirects exceeded.", kHttpErrorOther); return false; } int32_t status = prev->redirect_status; std::string next_method = prev->active_method; int64_t next_content_len = prev->active_content_length; - if (status == 303 || ((status == 301 || status == 302) && - !AsciiEqualsIgnoreCase(next_method, "GET") && - !AsciiEqualsIgnoreCase(next_method, "HEAD"))) { + if ((status == 301 || status == 302 || status == 303) && + !AsciiEqualsIgnoreCase(next_method, "GET") && + !AsciiEqualsIgnoreCase(next_method, "HEAD")) { next_method = "GET"; next_content_len = kNoRequestContent; + op->MarkRequestWriteClosed(); + } else if (status == 303 && AsciiEqualsIgnoreCase(next_method, "HEAD")) { + next_content_len = kNoRequestContent; } else if (next_content_len != kNoRequestContent && next_content_len != 0) { - op->MarkFailed("Cannot replay streamed request body across redirect."); + op->MarkFailed("Cannot replay streamed request body across redirect.", + kHttpErrorOther); return false; } @@ -632,7 +749,7 @@ class CurlHttpEngine { CURLMcode mc = curl_multi_add_handle(multi_.get(), next_transfer->easy.get()); if (mc != CURLM_OK) { - op->MarkFailed(curl_multi_strerror(mc)); + op->MarkFailed(curl_multi_strerror(mc), kHttpErrorOther); return false; } active_.emplace(op->id, std::move(next_transfer)); From 73094b4b278d108c9d74a238c9a8ed2cf1b336be Mon Sep 17 00:00:00 2001 From: Austin Benoit Date: Fri, 27 Nov 2026 13:51:27 -0500 Subject: [PATCH 04/16] [App][HTTP] Fix Apple early stream close, memory backpressure, proxy, locking, and errors (P1-P5, S3, S4) --- app/http/http_transport_apple.mm | 725 +++++++++++++++++++++++-------- 1 file changed, 539 insertions(+), 186 deletions(-) diff --git a/app/http/http_transport_apple.mm b/app/http/http_transport_apple.mm index 65d8c691b3..475178b587 100644 --- a/app/http/http_transport_apple.mm +++ b/app/http/http_transport_apple.mm @@ -16,6 +16,8 @@ #import +#include +#include #include #include #include @@ -35,6 +37,7 @@ #endif @class FIRFirebaseHttpStreamBridge; +@class FIRFirebaseHttpSessionDelegate; namespace firebase { namespace http { @@ -68,21 +71,145 @@ return out; } +std::string CanonicalReasonPhrase(int32_t status) { + switch (status) { + case 200: + return "OK"; + case 201: + return "Created"; + case 202: + return "Accepted"; + case 204: + return "No Content"; + case 206: + return "Partial Content"; + case 301: + return "Moved Permanently"; + case 302: + return "Found"; + case 303: + return "See Other"; + case 304: + return "Not Modified"; + case 307: + return "Temporary Redirect"; + case 308: + return "Permanent Redirect"; + case 400: + return "Bad Request"; + case 401: + return "Unauthorized"; + case 403: + return "Forbidden"; + case 404: + return "Not Found"; + case 405: + return "Method Not Allowed"; + case 408: + return "Request Timeout"; + case 409: + return "Conflict"; + case 410: + return "Gone"; + case 412: + return "Precondition Failed"; + case 413: + return "Payload Too Large"; + case 416: + return "Range Not Satisfiable"; + case 429: + return "Too Many Requests"; + case 500: + return "Internal Server Error"; + case 502: + return "Bad Gateway"; + case 503: + return "Service Unavailable"; + case 504: + return "Gateway Timeout"; + default: + return FromNSString([NSHTTPURLResponse localizedStringForStatusCode:status]); + } +} + +HttpErrorClass ClassifyNSError(NSError* error) { + 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 NSURLErrorSecureConnectionFailed: + case NSURLErrorServerCertificateHasBadDate: + case NSURLErrorServerCertificateUntrusted: + case NSURLErrorServerCertificateHasUnknownRoot: + case NSURLErrorServerCertificateNotYetValid: + case NSURLErrorClientCertificateRejected: + case NSURLErrorClientCertificateRequired: + case NSURLErrorAppTransportSecurityRequiresSecureConnection: + return kHttpErrorTls; + 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"]) { + if (code <= -1200 && code >= -1206) { + return kHttpErrorTls; + } + 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; +} + +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; int redirect_count = 0; + 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 @@ -97,6 +224,7 @@ - (void)closeWriteStream; @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. @@ -145,6 +273,7 @@ - (instancetype)initWithState:(std::shared_ptrop->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]; @@ -175,17 +322,15 @@ - (void)closeWriteStream { - (void)closeOnStreamThread { auto state = _state; - if (!state) { - _selfRetain = nil; - return; - } - NSOutputStream* stream = nil; - { + NSOutputStream* stream = _ownedStream; + _ownedStream = nil; + if (state) { std::lock_guard lock(state->state_mutex); - state->stream_bridge = nil; - if (!state->body_closed && state->body_output_stream != nil) { + if (state->stream_bridge == self) { + state->stream_bridge = nil; + } + if (state->body_output_stream == stream) { state->body_closed = true; - stream = state->body_output_stream; state->body_output_stream = nil; } } @@ -208,10 +353,10 @@ - (void)pumpOnStreamThread { NSOutputStream* stream = nil; { std::lock_guard lock(state->state_mutex); - if (state->body_closed || state->body_output_stream == nil) { + if (state->body_closed || state->body_output_stream != _ownedStream || _ownedStream == nil) { return; } - stream = state->body_output_stream; + stream = _ownedStream; } constexpr size_t kSliceSize = 64 * 1024; @@ -223,7 +368,9 @@ - (void)pumpOnStreamThread { size_t popped = state->op->PopRequestBytes(state->pending_write_chunk.data(), kSliceSize, &eof); state->pending_write_chunk.resize(popped); - if (popped == 0) { + if (popped > 0) { + state->any_body_bytes_popped.store(true, std::memory_order_release); + } else { if (eof) { [self closeOnStreamThread]; } @@ -238,13 +385,12 @@ - (void)pumpOnStreamThread { if (written > 0) { state->pending_write_offset += static_cast(written); } else if (written < 0) { - NSError* err = [stream streamError]; - std::string msg = err != nil ? firebase::http::FromNSString([err localizedDescription]) - : "Request body stream write failed."; - // Record the stream error before cancelling the task so an asynchronous - // `didCompleteWithError:NSURLErrorCancelled` cannot overwrite `msg`. - state->op->MarkFailed(msg); - firebase::http::CancelAppleTransferTask(state); + // NSURLSession closes the bound input stream early when the server sends + // an immediate 4xx/5xx (such as 413) or a 301-303 redirect to GET. 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 { @@ -258,21 +404,15 @@ - (void)stream:(NSStream*)aStream handleEvent:(NSStreamEvent)eventCode { case NSStreamEventHasSpaceAvailable: [self pumpOnStreamThread]; break; - case NSStreamEventErrorOccurred: { - NSError* err = [aStream streamError]; - std::string msg = err != nil ? firebase::http::FromNSString([err localizedDescription]) - : "Request body stream error."; + case NSStreamEventErrorOccurred: + case NSStreamEventEndEncountered: { auto state = _state; if (state) { - state->op->MarkFailed(msg); - firebase::http::CancelAppleTransferTask(state); + state->op->MarkRequestWriteClosed(); } [self closeOnStreamThread]; break; } - case NSStreamEventEndEncountered: - [self closeOnStreamThread]; - break; default: break; } @@ -325,12 +465,61 @@ - (void)registerState:(std::shared_ptr)state _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; + } + + if (state->any_body_bytes_popped.load(std::memory_order_acquire)) { + bool is_redirect = false; + { + std::lock_guard lock(state->state_mutex); + is_redirect = state->redirect_count > 0; + } + state->op->MarkFailed(is_redirect ? "Cannot replay streamed request body across redirect." + : "Cannot replay streamed request body.", + firebase::http::kHttpErrorOther); + [task cancel]; + completionHandler(nil); + return; + } + + // No bytes were consumed from the upload pipe yet (for example NSURLSession + // retrying a request on a stale keep-alive connection before sending body + // bytes). Supply a fresh bound stream pair. + 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]; + { + std::lock_guard lock(state->state_mutex); + old_bridge = state->stream_bridge; + state->body_closed = false; + state->body_output_stream = out_stream; + state->stream_bridge = new_bridge; + } + 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 { auto state = [self findState:task]; + int32_t status = static_cast(response.statusCode); if (state) { bool exceeded = false; { @@ -342,7 +531,7 @@ - (void)URLSession:(NSURLSession*)session } } if (exceeded) { - state->op->MarkFailed("Maximum HTTP redirects exceeded."); + state->op->MarkFailed("Maximum HTTP redirects exceeded.", firebase::http::kHttpErrorOther); [task cancel]; handler(nil); return; @@ -353,7 +542,41 @@ - (void)URLSession:(NSURLSession*)session NSString* prev_ns = response.URL != nil ? response.URL.absoluteString : task.currentRequest.URL.absoluteString; std::string prev_url = firebase::http::FromNSString(prev_ns); - std::string next_url = firebase::http::FromNSString(request.URL.absoluteString); + + // Resolve Location through the shared RFC 3986 redirect validator so userinfo + // rejection, spaces, non-HTTP(S) schemes, and HTTPS -> HTTP downgrades match + // Desktop and Android identically. + NSString* raw_location = nil; + for (id rawKey in response.allHeaderFields) { + if ([rawKey isKindOfClass:[NSString class]] && + firebase::http::AsciiEqualsIgnoreCase( + firebase::http::FromNSString(static_cast(rawKey)), "Location")) { + id val = response.allHeaderFields[rawKey]; + if ([val isKindOfClass:[NSString class]]) { + raw_location = static_cast(val); + } + break; + } + } + + std::string next_url; + if (raw_location != nil) { + auto resolved = + firebase::http::ResolveRedirectUrl(prev_url, firebase::http::FromNSString(raw_location)); + if (!resolved) { + if (state) { + state->op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect.", + firebase::http::kHttpErrorOther); + } + [task cancel]; + handler(nil); + return; + } + next_url = std::move(*resolved); + } else { + next_url = firebase::http::FromNSString(request.URL.absoluteString); + } + bool was_https = firebase::http::IsHttpsUrl(orig_url) || firebase::http::IsHttpsUrl(prev_url); if (!firebase::http::IsHttpOrHttpsUrl(next_url) || (was_https && !firebase::http::IsHttpsUrl(next_url))) { @@ -361,21 +584,78 @@ - (void)URLSession:(NSURLSession*)session // HTTPS -> HTTP downgrades; passing handler(nil) alone would complete the // task with the raw 3xx response as success. if (state) { - state->op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect."); + state->op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect.", + firebase::http::kHttpErrorOther); } [task cancel]; handler(nil); return; } + std::string cur_method = firebase::http::FromNSString(task.currentRequest.HTTPMethod); + bool has_streamed_body = + state && (state->op->content_length > 0 || + state->op->content_length == firebase::http::kChunkedRequestContent); + bool rewrites_to_get = (status == 301 || status == 302 || status == 303) && + !firebase::http::AsciiEqualsIgnoreCase(cur_method, "GET") && + !firebase::http::AsciiEqualsIgnoreCase(cur_method, "HEAD"); + + if (!rewrites_to_get && (status == 307 || status == 308) && has_streamed_body) { + if (state) { + state->op->MarkFailed("Cannot replay streamed request body across redirect.", + firebase::http::kHttpErrorOther); + } + [task cancel]; + handler(nil); + return; + } + + NSMutableURLRequest* next_req = [request mutableCopy]; + NSURL* validated_ns_url = [NSURL URLWithString:firebase::http::ToNSString(next_url)]; + if (validated_ns_url != nil) { + next_req.URL = validated_ns_url; + } + + if (rewrites_to_get) { + next_req.HTTPMethod = @"GET"; + next_req.HTTPBody = nil; + next_req.HTTPBodyStream = nil; + [next_req setValue:nil forHTTPHeaderField:@"Content-Type"]; + [next_req setValue:nil forHTTPHeaderField:@"Content-Length"]; + [next_req setValue:nil forHTTPHeaderField:@"Transfer-Encoding"]; + if (state) { + state->op->MarkRequestWriteClosed(); + FIRFirebaseHttpStreamBridge* bridge = nil; + { + std::lock_guard lock(state->state_mutex); + bridge = state->stream_bridge; + state->stream_bridge = nil; + } + if (bridge != nil) { + [bridge closeWriteStream]; + } + } + } else if (status == 303 && firebase::http::AsciiEqualsIgnoreCase(cur_method, "HEAD")) { + next_req.HTTPMethod = @"HEAD"; + next_req.HTTPBody = nil; + next_req.HTTPBodyStream = nil; + } + if (!firebase::http::IsSameOrigin(orig_url, next_url) || !firebase::http::IsSameOrigin(prev_url, next_url)) { - NSMutableURLRequest* sanitized = [request mutableCopy]; - [sanitized setValue:nil forHTTPHeaderField:@"Authorization"]; - [sanitized setValue:nil forHTTPHeaderField:@"Proxy-Authorization"]; - [sanitized setValue:nil forHTTPHeaderField:@"X-Firebase-AppCheck"]; - [sanitized setValue:nil forHTTPHeaderField:@"x-goog-api-key"]; - handler(sanitized); + NSDictionary* fields = [next_req.allHTTPHeaderFields copy]; + for (NSString* key in fields) { + if (firebase::http::IsSensitiveRedirectHeader(firebase::http::FromNSString(key)) || + firebase::http::AsciiEqualsIgnoreCase(firebase::http::FromNSString(key), "Host")) { + [next_req setValue:nil forHTTPHeaderField:key]; + } + } + [next_req setValue:nil forHTTPHeaderField:@"Authorization"]; + [next_req setValue:nil forHTTPHeaderField:@"Proxy-Authorization"]; + [next_req setValue:nil forHTTPHeaderField:@"Cookie"]; + [next_req setValue:nil forHTTPHeaderField:@"X-Firebase-AppCheck"]; + [next_req setValue:nil forHTTPHeaderField:@"x-goog-api-key"]; + handler(next_req); return; } @@ -384,14 +664,11 @@ - (void)URLSession:(NSURLSession*)session // (never `originalRequest`, so a credential stripped on an earlier // cross-origin hop can never be resurrected on a later bounce back). NSString* cur_auth = [task.currentRequest valueForHTTPHeaderField:@"Authorization"]; - if (cur_auth != nil && [request valueForHTTPHeaderField:@"Authorization"] == nil) { - NSMutableURLRequest* preserved = [request mutableCopy]; - [preserved setValue:cur_auth forHTTPHeaderField:@"Authorization"]; - handler(preserved); - return; + if (cur_auth != nil && [next_req valueForHTTPHeaderField:@"Authorization"] == nil) { + [next_req setValue:cur_auth forHTTPHeaderField:@"Authorization"]; } - handler(request); + handler(next_req); } - (void)URLSession:(NSURLSession*)session @@ -405,15 +682,14 @@ - (void)URLSession:(NSURLSession*)session } if (![response isKindOfClass:[NSHTTPURLResponse class]]) { - state->op->MarkFailed("Unexpected non-HTTP URLResponse."); + 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::string reason = firebase::http::FromNSString( - [NSHTTPURLResponse localizedStringForStatusCode:httpResp.statusCode]); + std::string reason = firebase::http::CanonicalReasonPhrase(status); std::vector> headers; NSDictionary* fields = httpResp.allHeaderFields; for (id rawKey in fields) { @@ -436,35 +712,55 @@ - (void)URLSession:(NSURLSession*)session return; } - __block bool over_high_water = false; + // 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) { - if (byteRange.length > 0) { - if (state->op->PushResponseBytes(static_cast(bytes), - static_cast(byteRange.length))) { - over_high_water = true; - } - } - }]; - - if (over_high_water) { - std::lock_guard lock(state->state_mutex); - if (!state->task_suspended && !state->op->IsCanceled() && state->task != nil) { - // Re-verify buffered byte count under `op->mutex` while holding - // `state_mutex` (`state_mutex -> op->mutex` lock order) so a concurrent - // consumer read draining the buffer to 0 cannot race past - // `task_suspended` and leave the task suspended permanently. - bool still_above_low_water = false; - { - std::lock_guard op_lock(state->op->mutex); - still_above_low_water = - state->op->resp_buffered_bytes > firebase::http::kLowWaterResponseBytes; + 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; } - if (still_above_low_water) { - state->task_suspended = true; - [state->task suspend]; + 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 @@ -475,21 +771,30 @@ - (void)URLSession:(NSURLSession*)session 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) { - state->op->MarkFailed(firebase::http::FromNSString([error localizedDescription])); + firebase::http::HttpErrorClass err_class = firebase::http::ClassifyNSError(error); + state->op->MarkFailed(firebase::http::FromNSString([error localizedDescription]), err_class); } else { state->op->MarkResponseComplete(); } @@ -508,35 +813,86 @@ - (void)URLSession:(NSURLSession*)session config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever; config.HTTPShouldSetCookies = NO; config.HTTPMaximumConnectionsPerHost = 16; - // Timeouts are governed by the caller's CancellationToken / watchdog so - // long-lived SSE streams are never prematurely killed while idle. + // 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; } -FIRFirebaseHttpSessionDelegate* SharedSessionDelegate() { - static FIRFirebaseHttpSessionDelegate* sDelegate = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - sDelegate = [[FIRFirebaseHttpSessionDelegate alloc] init]; - }); - return sDelegate; +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; } -NSOperationQueue* SharedDelegateQueue() { - static NSOperationQueue* sQueue = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - sQueue = [[NSOperationQueue alloc] init]; - sQueue.name = @"com.google.firebase.http.delegate"; - // NSURLSession requires a serial delegate queue to preserve ordering - // between `didReceiveResponse:`, `didReceiveData:`, and - // `didCompleteWithError:` callbacks. - sQueue.maxConcurrentOperationCount = 1; - sQueue.qualityOfService = NSQualityOfServiceUserInitiated; - }); - return sQueue; +// 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: +// - HTTP/2 and TLS keep-alive reuse across up to 16 concurrent connections. +// - 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) { @@ -545,6 +901,8 @@ void CancelAppleTransferTask(const std::shared_ptr& state) { } FIRFirebaseHttpStreamBridge* bridge = nil; NSURLSessionDataTask* t = nil; + FIRFirebaseHttpSessionDelegate* del = nil; + std::shared_ptr unstarted_slot; bool was_suspended = false; bool was_started = false; { @@ -556,15 +914,22 @@ void CancelAppleTransferTask(const std::shared_ptr& state) { 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) { + 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. - [SharedSessionDelegate() takeState:t]; + [del takeState:t]; } // Balance any active suspend before cancelling; NSURLSession asserts if a // task is cancelled or deallocated with suspend > 0. @@ -573,70 +938,9 @@ void CancelAppleTransferTask(const std::shared_ptr& state) { } [t cancel]; } -} - -NSURLSession* SharedDefaultSession() { - static NSURLSession* sSession = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - sSession = [NSURLSession sessionWithConfiguration:MakeBaseSessionConfig() - delegate:SharedSessionDelegate() - delegateQueue:SharedDelegateQueue()]; - }); - return sSession; -} - -NSURLSession* SessionForProxy(std::string_view proxy_url) { - auto proxy_hp = ParseProxyHostPort(proxy_url); - if (!proxy_hp) { - return SharedDefaultSession(); - } - - static auto* proxy_mutex = new std::mutex(); - static auto* proxy_sessions = new std::unordered_map(); - static auto* proxy_lru = new std::deque(); - constexpr size_t kMaxCachedProxySessions = 8; - - std::string cache_key = proxy_hp->first + ":" + std::to_string(proxy_hp->second); - NSURLSession* evicted = nil; - NSURLSession* result = nil; - { - std::lock_guard lock(*proxy_mutex); - auto it = proxy_sessions->find(cache_key); - if (it != proxy_sessions->end()) { - return it->second; - } - - NSString* host = ToNSString(proxy_hp->first); - NSNumber* port = @(proxy_hp->second); - NSURLSessionConfiguration* config = MakeBaseSessionConfig(); - config.connectionProxyDictionary = @{ - @"HTTPEnable" : @YES, - @"HTTPProxy" : host, - @"HTTPPort" : port, - @"HTTPSEnable" : @YES, - @"HTTPSProxy" : host, - @"HTTPSPort" : port, - }; - result = [NSURLSession sessionWithConfiguration:config - delegate:SharedSessionDelegate() - delegateQueue:SharedDelegateQueue()]; - if (proxy_sessions->size() >= kMaxCachedProxySessions && !proxy_lru->empty()) { - std::string oldest = std::move(proxy_lru->front()); - proxy_lru->pop_front(); - auto old_it = proxy_sessions->find(oldest); - if (old_it != proxy_sessions->end()) { - evicted = old_it->second; - proxy_sessions->erase(old_it); - } - } - proxy_sessions->emplace(cache_key, result); - proxy_lru->push_back(std::move(cache_key)); - } - if (evicted != nil && evicted != SharedDefaultSession()) { - [evicted finishTasksAndInvalidate]; + if (unstarted_slot) { + ReleaseSessionSlot(unstarted_slot, /*cancel_now=*/true); } - return result; } } // namespace @@ -647,16 +951,49 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { return; } if (!IsHttpOrHttpsUrl(op->url)) { - op->MarkFailed("Unsupported URI scheme; only http and https are allowed."); + op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", + kHttpErrorOther); + 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.", kHttpErrorOther); return; } NSURL* ns_url = [NSURL URLWithString:ToNSString(op->url)]; if (ns_url == nil) { - op->MarkFailed("Invalid request URL."); + op->MarkFailed("Invalid request URL.", kHttpErrorOther); return; } + // Validate proxy URL upfront and never silently fall back to direct. + std::shared_ptr slot; + if (!op->proxy_url.empty()) { + auto proxy_hp = ParseProxyHostPort(op->proxy_url); + if (!proxy_hp) { + op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorOther); + return; + } + NSString* host = ToNSString(proxy_hp->first); + NSNumber* port = @(proxy_hp->second); + NSURLSessionConfiguration* config = MakeBaseSessionConfig(); + config.connectionProxyDictionary = @{ + @"HTTPEnable" : @YES, + @"HTTPProxy" : host, + @"HTTPPort" : port, + @"HTTPSEnable" : @YES, + @"HTTPSProxy" : host, + @"HTTPSPort" : port, + }; + slot = CreateSessionSlot(config, /*pooled=*/false); + } else { + slot = AppleSessionPool::Instance().AcquireDefault(); + } + NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:ns_url]; req.HTTPMethod = ToNSString(op->method); req.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData; @@ -688,16 +1025,17 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { auto state = std::make_shared(); state->op = op; + state->session_slot = slot; FIRFirebaseHttpStreamBridge* stream_bridge = nil; - if (op->content_length == 0) { + 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; - NSOutputStream* out_stream = nil; [NSStream getBoundStreamsWithBufferSize:kMaxRequestBufferBytes inputStream:&in_stream outputStream:&out_stream]; @@ -707,10 +1045,9 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { stringWithFormat:@"%lld", static_cast(op->content_length)] forHTTPHeaderField:@"Content-Length"]; } - state->body_output_stream = out_stream; stream_bridge = [[FIRFirebaseHttpStreamBridge alloc] initWithState:state]; + state->body_output_stream = out_stream; state->stream_bridge = stream_bridge; - [stream_bridge scheduleOutputStream:out_stream]; } else if (!has_content_length && (AsciiEqualsIgnoreCase(op->method, "POST") || AsciiEqualsIgnoreCase(op->method, "PUT") || AsciiEqualsIgnoreCase(op->method, "PATCH"))) { @@ -718,13 +1055,17 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { [req setValue:@"0" forHTTPHeaderField:@"Content-Length"]; } - NSURLSession* session = SessionForProxy(op->proxy_url); - NSURLSessionDataTask* task = [session dataTaskWithRequest:req]; + NSURLSessionDataTask* task = [slot->session dataTaskWithRequest:req]; NSString* key = [NSString stringWithFormat:@"%lld", static_cast(op->id)]; task.taskDescription = key; - state->task = task; + { + // Write `state->task` under `state_mutex` before registering or starting + // the stream thread (P4). + std::lock_guard slock(state->state_mutex); + state->task = task; + } - [SharedSessionDelegate() registerState:state forTaskKey:key]; + [slot->delegate registerState:state forTaskKey:key]; bool already_canceled = false; { @@ -749,52 +1090,64 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { } }; } - op->on_response_space_available = [weak_state]() { - auto locked = weak_state.lock(); - if (!locked) { - return; - } - std::lock_guard slock(locked->state_mutex); - if (locked->task_suspended && locked->task != nil && !locked->op->IsCanceled()) { - locked->task_suspended = false; - [locked->task resume]; - } - }; op->on_cancel = [weak_state]() { CancelAppleTransferTask(weak_state.lock()); }; } } if (already_canceled) { - [SharedSessionDelegate() takeState:task]; + [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 (stream_bridge != nil) { - [stream_bridge closeWriteStream]; + 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 `SharedSessionDelegate()._tasks`. + // 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) { - [SharedSessionDelegate() takeState:task]; + [slot->delegate takeState:task]; [task cancel]; + if (unstarted_release) { + ReleaseSessionSlot(unstarted_release, /*cancel_now=*/true); + } } } } From 8f6b46b0f7182bd4bd02b0db76f702422b7927e1 Mon Sep 17 00:00:00 2001 From: Austin Benoit Date: Fri, 27 Nov 2026 13:51:27 -0500 Subject: [PATCH 05/16] [App][HTTP] Fix Android GET/HEAD body, early 4xx, HEAD-on-303, proxy, util reuse, and split (A1-A5, S4) --- app/http/http_transport_android.cc | 1257 ++++++++++++++++------------ 1 file changed, 730 insertions(+), 527 deletions(-) diff --git a/app/http/http_transport_android.cc b/app/http/http_transport_android.cc index cf5ec855c9..e07b500555 100644 --- a/app/http/http_transport_android.cc +++ b/app/http/http_transport_android.cc @@ -54,6 +54,14 @@ JavaVM* ResolveJavaVM() { return nullptr; } +JNIEnv* ResolveThreadsafeJNIEnv() { + JavaVM* vm = ResolveJavaVM(); + if (vm == nullptr) { + return nullptr; + } + return ::firebase::util::GetThreadsafeJNIEnv(vm); +} + std::string ToLowerAscii(std::string_view s) { std::string out(s.size(), '\0'); for (size_t i = 0; i < s.size(); ++i) { @@ -100,6 +108,11 @@ class LocalRef { T ref_ = nullptr; }; +struct JniExceptionInfo { + std::string message; + HttpErrorClass error_class = kHttpErrorOther; +}; + struct JniCache { bool initialized = false; @@ -163,6 +176,17 @@ struct JniCache { jclass throwable_cls = nullptr; jmethodID throwable_to_string = nullptr; + jmethodID throwable_get_cause = nullptr; + + // Optional exception classes for structured error classification (S4). + jclass ssl_ex_cls = nullptr; + jclass cert_ex_cls = nullptr; + jclass socket_timeout_ex_cls = nullptr; + jclass connect_ex_cls = nullptr; + jclass unknown_host_ex_cls = nullptr; + jclass no_route_ex_cls = nullptr; + jclass socket_ex_cls = nullptr; + jclass eof_ex_cls = nullptr; }; JniCache& GetJniCache() { @@ -170,30 +194,87 @@ JniCache& GetJniCache() { return *cache; } -std::string JStringToStdString(JNIEnv* env, jstring jstr) { - if (jstr == nullptr) { - return std::string(); +HttpErrorClass ClassifyJavaException(JNIEnv* env, jthrowable root_ex) { + auto& c = GetJniCache(); + if (root_ex == nullptr) { + return kHttpErrorOther; } - const char* chars = env->GetStringUTFChars(jstr, nullptr); - if (chars == nullptr) { + + HttpErrorClass best = kHttpErrorOther; + LocalRef current(env, env->NewLocalRef(root_ex)); + for (int depth = 0; current && depth < 8; ++depth) { + if ((c.ssl_ex_cls != nullptr && + env->IsInstanceOf(current.get(), c.ssl_ex_cls) == JNI_TRUE) || + (c.cert_ex_cls != nullptr && + env->IsInstanceOf(current.get(), c.cert_ex_cls) == JNI_TRUE)) { + return kHttpErrorTls; + } + if (c.socket_timeout_ex_cls != nullptr && + env->IsInstanceOf(current.get(), c.socket_timeout_ex_cls) == JNI_TRUE) { + if (best == kHttpErrorOther) { + best = kHttpErrorTimeout; + } + } else if ((c.connect_ex_cls != nullptr && + env->IsInstanceOf(current.get(), c.connect_ex_cls) == + JNI_TRUE) || + (c.unknown_host_ex_cls != nullptr && + env->IsInstanceOf(current.get(), c.unknown_host_ex_cls) == + JNI_TRUE) || + (c.no_route_ex_cls != nullptr && + env->IsInstanceOf(current.get(), c.no_route_ex_cls) == + JNI_TRUE) || + (c.socket_ex_cls != nullptr && + env->IsInstanceOf(current.get(), c.socket_ex_cls) == + JNI_TRUE) || + (c.eof_ex_cls != nullptr && + env->IsInstanceOf(current.get(), c.eof_ex_cls) == JNI_TRUE)) { + if (best == kHttpErrorOther) { + best = kHttpErrorConnect; + } + } + + if (c.throwable_get_cause == nullptr) { + break; + } + jobject next = env->CallObjectMethod(current.get(), c.throwable_get_cause); if (env->ExceptionCheck()) { env->ExceptionClear(); + break; + } + if (next == nullptr || env->IsSameObject(current.get(), next) == JNI_TRUE) { + if (next != nullptr) { + env->DeleteLocalRef(next); + } + break; } - return std::string(); + current.reset(next); } - std::string out(chars); - env->ReleaseStringUTFChars(jstr, chars); - return out; + return best; } -std::optional TakeJniException(JNIEnv* env) { +std::optional TakeJniException(JNIEnv* env) { if (!env->ExceptionCheck()) { return std::nullopt; } LocalRef ex(env, env->ExceptionOccurred()); env->ExceptionClear(); + JniExceptionInfo info; if (!ex) { - return std::string("Unknown JNI exception"); + info.message = "Unknown JNI exception"; + return info; + } + info.error_class = ClassifyJavaException(env, ex.get()); + + // Reuse firebase::util::GetMessageFromException when util_android has been + // initialized, falling back to cached Throwable.toString() if HTTP is used + // before FirebaseApp initialization. + if (::firebase::util::throwable::GetClass() != nullptr && + ::firebase::util::throwable::GetMethodId( + ::firebase::util::throwable::kToString) != nullptr) { + info.message = ::firebase::util::GetMessageFromException(env, ex.get()); + if (!info.message.empty()) { + return info; + } } auto& c = GetJniCache(); if (c.throwable_to_string != nullptr) { @@ -201,11 +282,16 @@ std::optional TakeJniException(JNIEnv* env) { ex.get(), c.throwable_to_string))); if (env->ExceptionCheck()) { env->ExceptionClear(); - return std::string("Java exception thrown during HTTP request"); + info.message = "Java exception thrown during HTTP request"; + return info; + } + info.message = ::firebase::util::JStringToString(env, msg.get()); + if (!info.message.empty()) { + return info; } - return JStringToStdString(env, msg.get()); } - return std::string("Java exception thrown during HTTP request"); + info.message = "Java exception thrown during HTTP request"; + return info; } jclass CacheGlobalClass(JNIEnv* env, const char* name) { @@ -249,10 +335,26 @@ bool EnsureJniInitialized(JNIEnv* env) { c.throwable_cls = CacheGlobalClass(env, "java/lang/Throwable"); c.throwable_to_string = CacheMethod(env, c.throwable_cls, "toString", "()Ljava/lang/String;", &ok); + c.throwable_get_cause = CacheMethod(env, c.throwable_cls, "getCause", + "()Ljava/lang/Throwable;", &ok); if (!ok) { return false; } + // Exception classes for structured error classification (best-effort; all + // exist on Android API 1+). + c.ssl_ex_cls = CacheGlobalClass(env, "javax/net/ssl/SSLException"); + c.cert_ex_cls = + CacheGlobalClass(env, "java/security/cert/CertificateException"); + c.socket_timeout_ex_cls = + CacheGlobalClass(env, "java/net/SocketTimeoutException"); + c.connect_ex_cls = CacheGlobalClass(env, "java/net/ConnectException"); + c.unknown_host_ex_cls = + CacheGlobalClass(env, "java/net/UnknownHostException"); + c.no_route_ex_cls = CacheGlobalClass(env, "java/net/NoRouteToHostException"); + c.socket_ex_cls = CacheGlobalClass(env, "java/net/SocketException"); + c.eof_ex_cls = CacheGlobalClass(env, "java/io/EOFException"); + c.url_cls = CacheGlobalClass(env, "java/net/URL"); c.proxy_cls = CacheGlobalClass(env, "java/net/Proxy"); c.inet_sock_addr_cls = CacheGlobalClass(env, "java/net/InetSocketAddress"); @@ -397,6 +499,14 @@ struct AndroidCancelHandle { } } + void ClearOutputStream(JNIEnv* env) { + std::lock_guard lock(mutex); + if (out_stream_global != nullptr) { + env->DeleteGlobalRef(out_stream_global); + out_stream_global = nullptr; + } + } + void AbortNow(JNIEnv* env) { if (env == nullptr) { return; @@ -467,34 +577,8 @@ class AndroidCancelDispatcher { } private: - static JNIEnv* AttachCancelThread(JavaVM** out_vm, bool* out_attached) { - JavaVM* vm = ResolveJavaVM(); - if (vm == nullptr) { - return nullptr; - } - JNIEnv* env = nullptr; - jint status = vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); - if (status == JNI_EDETACHED) { - JavaVMAttachArgs args{}; - args.version = JNI_VERSION_1_6; - args.name = const_cast("FirebaseHttpCancel"); - args.group = nullptr; - if (vm->AttachCurrentThread(&env, &args) == JNI_OK) { - *out_vm = vm; - *out_attached = true; - } else { - return nullptr; - } - } else if (status == JNI_OK) { - *out_vm = vm; - } - return env; - } - void RunLoop() { - JavaVM* vm = nullptr; - bool attached = false; - JNIEnv* env = AttachCancelThread(&vm, &attached); + JNIEnv* env = ResolveThreadsafeJNIEnv(); while (true) { std::shared_ptr next; { @@ -504,7 +588,7 @@ class AndroidCancelDispatcher { queue_.pop_front(); } if (env == nullptr) { - env = AttachCancelThread(&vm, &attached); + env = ResolveThreadsafeJNIEnv(); } if (env != nullptr && next) { next->AbortNow(env); @@ -534,537 +618,685 @@ std::string_view FindHeaderValueIgnoreCase( return {}; } -void ExecuteAndroidOperation(JNIEnv* env, - const std::shared_ptr& op) { - if (!EnsureJniInitialized(env)) { - op->MarkFailed("Failed to initialize Android JNI HTTP bindings."); - return; +struct AndroidHopState { + std::string current_url; + std::string active_method; + std::vector> active_headers; + int64_t active_content_len = kNoRequestContent; +}; + +struct AndroidResponseHead { + int32_t status_code = 0; + std::string reason; + std::vector> headers; +}; + +// Opens and configures a Java HttpURLConnection for one request hop. +LocalRef BuildAndroidRequestConnection( + JNIEnv* env, const std::shared_ptr& op, + const std::shared_ptr& cancel_handle, + const AndroidHopState& hop) { + auto& c = GetJniCache(); + LocalRef empty(env, nullptr); + + LocalRef jurl_str(env, env->NewStringUTF(hop.current_url.c_str())); + if (auto ex = TakeJniException(env); ex || !jurl_str) { + op->MarkFailed(ex ? ex->message : "Failed to allocate JNI URL string", + ex ? ex->error_class : kHttpErrorOther); + return empty; } - if (!IsHttpOrHttpsUrl(op->url)) { - op->MarkFailed("Unsupported URI scheme; only http and https are allowed."); - return; + LocalRef jurl( + env, env->NewObject(c.url_cls, c.url_ctor, jurl_str.get())); + if (auto ex = TakeJniException(env); ex || !jurl) { + op->MarkFailed(ex ? ex->message : "Invalid URL", + ex ? ex->error_class : kHttpErrorOther); + return empty; } - auto cancel_handle = std::make_shared(); - { - std::lock_guard lock(op->mutex); - if (op->IsCanceled()) { - return; + LocalRef conn(env, nullptr); + if (!op->proxy_url.empty()) { + auto proxy_hp = ParseProxyHostPort(op->proxy_url); + if (!proxy_hp) { + op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorOther); + return empty; } - op->on_cancel = [cancel_handle]() { - AndroidCancelDispatcher::Instance().Enqueue(cancel_handle); - }; + LocalRef jhost(env, env->NewStringUTF(proxy_hp->first.c_str())); + if (auto ex = TakeJniException(env); ex || !jhost) { + op->MarkFailed(ex ? ex->message : "Failed to allocate proxy host string", + ex ? ex->error_class : kHttpErrorOther); + return empty; + } + LocalRef jsock_addr( + env, env->NewObject(c.inet_sock_addr_cls, c.inet_sock_addr_ctor, + jhost.get(), static_cast(proxy_hp->second))); + if (auto ex = TakeJniException(env); ex || !jsock_addr) { + op->MarkFailed( + ex ? ex->message : "Failed to construct proxy socket address", + ex ? ex->error_class : kHttpErrorOther); + return empty; + } + LocalRef jproxy( + env, env->NewObject(c.proxy_cls, c.proxy_ctor, c.proxy_type_http, + jsock_addr.get())); + if (auto ex = TakeJniException(env); ex || !jproxy) { + op->MarkFailed(ex ? ex->message : "Failed to construct Java Proxy", + ex ? ex->error_class : kHttpErrorOther); + return empty; + } + conn.reset(env->CallObjectMethod(jurl.get(), c.url_open_conn_proxy, + jproxy.get())); + } else { + conn.reset(env->CallObjectMethod(jurl.get(), c.url_open_conn)); + } + if (auto ex = TakeJniException(env); ex || !conn) { + op->MarkFailed(ex ? ex->message : "Failed to open HttpURLConnection", + ex ? ex->error_class : kHttpErrorConnect); + return empty; + } + if (env->IsInstanceOf(conn.get(), c.http_conn_cls) != JNI_TRUE) { + op->MarkFailed( + "Unsupported URI scheme; URLConnection is not an HttpURLConnection.", + kHttpErrorOther); + return empty; } - bool completed_cleanly = false; - struct CleanupGuard { - JNIEnv* env; - std::shared_ptr handle; - bool* completed_cleanly; - ~CleanupGuard() { - if (!*completed_cleanly) { - handle->AbortNow(env); - } - handle->ClearAll(env); + { + jobject g_conn = env->NewGlobalRef(conn.get()); + if (auto ex = TakeJniException(env); ex || g_conn == nullptr) { + op->MarkFailed(ex ? ex->message : "Failed to retain HttpURLConnection", + ex ? ex->error_class : kHttpErrorOther); + return empty; } - } guard{env, cancel_handle, &completed_cleanly}; - - auto& c = GetJniCache(); - std::string current_url = op->url; - std::string active_method = op->method; - std::vector> active_headers = - op->request_headers; - int64_t active_content_len = op->content_length; - - for (int redirect_count = 0; redirect_count <= kMaxRedirects; - ++redirect_count) { - cancel_handle->ClearAll(env); + std::lock_guard lock(cancel_handle->mutex); + cancel_handle->conn_global = g_conn; + } + if (op->IsCanceled()) { + return empty; + } - LocalRef jurl_str(env, env->NewStringUTF(current_url.c_str())); - if (auto ex = TakeJniException(env); ex || !jurl_str) { - op->MarkFailed(ex.value_or("Failed to allocate JNI URL string")); - return; - } - LocalRef jurl( - env, env->NewObject(c.url_cls, c.url_ctor, jurl_str.get())); - if (auto ex = TakeJniException(env); ex || !jurl) { - op->MarkFailed(ex.value_or("Invalid URL")); - return; - } + env->CallVoidMethod(conn.get(), c.set_use_caches, JNI_FALSE); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(ex->message, ex->error_class); + return empty; + } + env->CallVoidMethod(conn.get(), c.set_connect_timeout, 60000); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(ex->message, ex->error_class); + return empty; + } + env->CallVoidMethod(conn.get(), c.set_read_timeout, 0); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(ex->message, ex->error_class); + return empty; + } + // Handle redirects explicitly so cross-origin redirects strip sensitive + // Firebase credentials and HTTPS -> HTTP downgrades are rejected. + env->CallVoidMethod(conn.get(), c.set_instance_follow_redirects, JNI_FALSE); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(ex->message, ex->error_class); + return empty; + } - LocalRef conn(env, nullptr); - if (auto proxy_hp = ParseProxyHostPort(op->proxy_url)) { - LocalRef jhost(env, env->NewStringUTF(proxy_hp->first.c_str())); - if (auto ex = TakeJniException(env); ex || !jhost) { - op->MarkFailed(ex.value_or("Failed to allocate proxy host string")); - return; + LocalRef jmethod(env, env->NewStringUTF(hop.active_method.c_str())); + if (auto ex = TakeJniException(env); ex || !jmethod) { + op->MarkFailed(ex ? ex->message : "Failed to allocate HTTP method string", + ex ? ex->error_class : kHttpErrorOther); + return empty; + } + env->CallVoidMethod(conn.get(), c.set_request_method, jmethod.get()); + if (auto ex = TakeJniException(env)) { + if (AsciiEqualsIgnoreCase(hop.active_method, "PATCH")) { + // Fallback for HttpURLConnection implementations that reject PATCH. + LocalRef jpost(env, env->NewStringUTF("POST")); + LocalRef joverride_k( + env, env->NewStringUTF("X-HTTP-Method-Override")); + LocalRef joverride_v(env, env->NewStringUTF("PATCH")); + if (auto ex_alloc = TakeJniException(env); + ex_alloc || !jpost || !joverride_k || !joverride_v) { + op->MarkFailed( + ex_alloc ? ex_alloc->message : "Failed to allocate PATCH override", + ex_alloc ? ex_alloc->error_class : kHttpErrorOther); + return empty; } - LocalRef jsock_addr( - env, - env->NewObject(c.inet_sock_addr_cls, c.inet_sock_addr_ctor, - jhost.get(), static_cast(proxy_hp->second))); - if (auto ex = TakeJniException(env); ex || !jsock_addr) { - op->MarkFailed(ex.value_or("Failed to construct proxy socket address")); - return; + env->CallVoidMethod(conn.get(), c.set_request_method, jpost.get()); + if (auto ex2 = TakeJniException(env)) { + op->MarkFailed(ex2->message, ex2->error_class); + return empty; } - LocalRef jproxy( - env, env->NewObject(c.proxy_cls, c.proxy_ctor, c.proxy_type_http, - jsock_addr.get())); - if (auto ex = TakeJniException(env); ex || !jproxy) { - op->MarkFailed(ex.value_or("Failed to construct Java Proxy")); - return; + env->CallVoidMethod(conn.get(), c.set_request_property, + joverride_k.get(), joverride_v.get()); + if (auto ex3 = TakeJniException(env)) { + op->MarkFailed(ex3->message, ex3->error_class); + return empty; } - conn.reset(env->CallObjectMethod(jurl.get(), c.url_open_conn_proxy, - jproxy.get())); } else { - conn.reset(env->CallObjectMethod(jurl.get(), c.url_open_conn)); - } - if (auto ex = TakeJniException(env); ex || !conn) { - op->MarkFailed(ex.value_or("Failed to open HttpURLConnection")); - return; - } - if (env->IsInstanceOf(conn.get(), c.http_conn_cls) != JNI_TRUE) { - op->MarkFailed( - "Unsupported URI scheme; URLConnection is not an HttpURLConnection."); - return; + op->MarkFailed(ex->message, ex->error_class); + return empty; } + } - { - jobject g_conn = env->NewGlobalRef(conn.get()); - if (auto ex = TakeJniException(env); ex || g_conn == nullptr) { - op->MarkFailed(ex.value_or("Failed to retain HttpURLConnection")); - return; - } - std::lock_guard lock(cancel_handle->mutex); - cancel_handle->conn_global = g_conn; + bool has_accept_encoding = false; + std::unordered_set seen_headers; + for (const auto& kv : hop.active_headers) { + if (AsciiEqualsIgnoreCase(kv.first, "Accept-Encoding")) { + has_accept_encoding = true; } - if (op->IsCanceled()) { - return; + LocalRef jk(env, env->NewStringUTF(kv.first.c_str())); + if (auto ex = TakeJniException(env); ex || !jk) { + op->MarkFailed(ex ? ex->message : "Failed to allocate header name", + ex ? ex->error_class : kHttpErrorOther); + return empty; } - - env->CallVoidMethod(conn.get(), c.set_use_caches, JNI_FALSE); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; + LocalRef jv(env, env->NewStringUTF(kv.second.c_str())); + if (auto ex = TakeJniException(env); ex || !jv) { + op->MarkFailed(ex ? ex->message : "Failed to allocate header value", + ex ? ex->error_class : kHttpErrorOther); + return empty; } - env->CallVoidMethod(conn.get(), c.set_connect_timeout, 60000); + jmethodID header_mid = seen_headers.insert(ToLowerAscii(kv.first)).second + ? c.set_request_property + : c.add_request_property; + env->CallVoidMethod(conn.get(), header_mid, jk.get(), jv.get()); if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; + op->MarkFailed(ex->message, ex->error_class); + return empty; } - env->CallVoidMethod(conn.get(), c.set_read_timeout, 0); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; + } + if (!has_accept_encoding) { + // Match .NET HttpClientHandler (AutomaticDecompression = None) and + // Desktop libcurl so Android's OkHttp BridgeInterceptor does not inject + // `Accept-Encoding: gzip`, strip Content-Length, buffer SSE frames, or + // corrupt Range ETag / byte offsets. + LocalRef jae_k(env, env->NewStringUTF("Accept-Encoding")); + LocalRef jae_v(env, env->NewStringUTF("identity")); + if (auto ex = TakeJniException(env); ex || !jae_k || !jae_v) { + op->MarkFailed(ex ? ex->message : "Failed to allocate Accept-Encoding", + ex ? ex->error_class : kHttpErrorOther); + return empty; } - // Handle redirects explicitly so cross-origin redirects strip sensitive - // Firebase credentials and HTTPS -> HTTP downgrades are rejected. - env->CallVoidMethod(conn.get(), c.set_instance_follow_redirects, JNI_FALSE); + env->CallVoidMethod(conn.get(), c.set_request_property, jae_k.get(), + jae_v.get()); if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; + op->MarkFailed(ex->message, ex->error_class); + return empty; } + } - LocalRef jmethod(env, env->NewStringUTF(active_method.c_str())); - if (auto ex = TakeJniException(env); ex || !jmethod) { - op->MarkFailed(ex.value_or("Failed to allocate HTTP method string")); - return; + return conn; +} + +// Streams request body bytes when the HTTP method permits a body. +// Returns true if the caller should proceed to ReadAndroidResponseHeaders +// (including when an upload write failed mid-stream and an early 4xx response +// may be readable via getResponseCode()), or false if the operation already +// failed or was canceled. +bool SendAndroidRequestBody( + JNIEnv* env, const std::shared_ptr& op, + const std::shared_ptr& cancel_handle, jobject conn, + const AndroidHopState& hop, std::optional* out_write_err) { + auto& c = GetJniCache(); + + // Never call setDoOutput(true) on GET or HEAD because HttpURLConnection + // silently rewrites GET into POST (A1). + bool is_get_or_head = AsciiEqualsIgnoreCase(hop.active_method, "GET") || + AsciiEqualsIgnoreCase(hop.active_method, "HEAD"); + if (is_get_or_head) { + if (hop.active_content_len > 0 || + hop.active_content_len == kChunkedRequestContent) { + op->MarkFailed("GET and HEAD requests cannot send a request body.", + kHttpErrorOther); + return false; } - env->CallVoidMethod(conn.get(), c.set_request_method, jmethod.get()); - if (auto ex = TakeJniException(env)) { - if (AsciiEqualsIgnoreCase(active_method, "PATCH")) { - // Fallback for HttpURLConnection implementations that reject PATCH. - LocalRef jpost(env, env->NewStringUTF("POST")); - if (auto ex_post = TakeJniException(env); ex_post || !jpost) { - op->MarkFailed(ex_post.value_or("Failed to allocate POST string")); - return; - } - LocalRef joverride_k( - env, env->NewStringUTF("X-HTTP-Method-Override")); - if (auto ex_k = TakeJniException(env); ex_k || !joverride_k) { - op->MarkFailed(ex_k.value_or("Failed to allocate override header")); - return; - } - LocalRef joverride_v(env, env->NewStringUTF("PATCH")); - if (auto ex_v = TakeJniException(env); ex_v || !joverride_v) { - op->MarkFailed(ex_v.value_or("Failed to allocate PATCH string")); - return; - } - env->CallVoidMethod(conn.get(), c.set_request_method, jpost.get()); - if (auto ex2 = TakeJniException(env)) { - op->MarkFailed(*ex2); - return; + return true; + } + + bool send_body = + hop.active_content_len >= 0 || + hop.active_content_len == kChunkedRequestContent || + (hop.active_content_len == kNoRequestContent && + (AsciiEqualsIgnoreCase(hop.active_method, "POST") || + AsciiEqualsIgnoreCase(hop.active_method, "PUT") || + AsciiEqualsIgnoreCase(hop.active_method, "PATCH"))); + if (!send_body) { + return true; + } + + env->CallVoidMethod(conn, c.set_do_output, JNI_TRUE); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(ex->message, ex->error_class); + return false; + } + if (hop.active_content_len == kNoRequestContent || + hop.active_content_len == 0) { + env->CallVoidMethod(conn, c.set_fixed_len_streaming, static_cast(0)); + } else if (hop.active_content_len > 0) { + env->CallVoidMethod(conn, c.set_fixed_len_streaming, + static_cast(hop.active_content_len)); + } else { + env->CallVoidMethod(conn, c.set_chunked_streaming, static_cast(65536)); + } + if (auto ex = TakeJniException(env)) { + op->MarkFailed(ex->message, ex->error_class); + return false; + } + + LocalRef out_stream(env, + env->CallObjectMethod(conn, c.get_output_stream)); + if (auto ex = TakeJniException(env); ex || !out_stream) { + if (!op->IsCanceled()) { + op->MarkFailed(ex ? ex->message : "Failed to open request OutputStream", + ex ? ex->error_class : kHttpErrorConnect); + } + return false; + } + { + jobject g_out = env->NewGlobalRef(out_stream.get()); + if (auto ex = TakeJniException(env); ex || g_out == nullptr) { + op->MarkFailed(ex ? ex->message : "Failed to retain request OutputStream", + ex ? ex->error_class : kHttpErrorOther); + return false; + } + std::lock_guard lock(cancel_handle->mutex); + cancel_handle->out_stream_global = g_out; + } + + bool write_failed = false; + if (hop.active_content_len > 0 || + hop.active_content_len == kChunkedRequestContent) { + constexpr size_t kWriteSlice = 64 * 1024; + LocalRef jwrite_buf( + env, env->NewByteArray(static_cast(kWriteSlice))); + if (auto ex = TakeJniException(env); ex || !jwrite_buf) { + cancel_handle->ClearOutputStream(env); + op->MarkFailed(ex ? ex->message : "Failed to allocate JNI write buffer", + ex ? ex->error_class : kHttpErrorOther); + return false; + } + std::vector scratch(kWriteSlice); + while (!op->IsCanceled()) { + bool eof = false; + size_t n = op->PopRequestBytes(scratch.data(), kWriteSlice, &eof); + if (n > 0) { + env->SetByteArrayRegion(jwrite_buf.get(), 0, static_cast(n), + reinterpret_cast(scratch.data())); + if (auto ex = TakeJniException(env)) { + cancel_handle->ClearOutputStream(env); + op->MarkFailed(ex->message, ex->error_class); + return false; } - env->CallVoidMethod(conn.get(), c.set_request_property, - joverride_k.get(), joverride_v.get()); - if (auto ex3 = TakeJniException(env)) { - op->MarkFailed(*ex3); - return; + env->CallVoidMethod(out_stream.get(), c.output_write, jwrite_buf.get(), + 0, static_cast(n)); + if (auto ex = TakeJniException(env)) { + if (op->IsCanceled()) { + cancel_handle->ClearOutputStream(env); + return false; + } + // The server may have sent an early 4xx (such as 413) and closed + // its read side. Save the write exception, close the upload pipe so + // the caller stops writing, and fall through to try getResponseCode() + // before failing the operation (A2). + *out_write_err = std::move(*ex); + write_failed = true; + op->MarkRequestWriteClosed(); + break; } + } else if (eof) { + break; } else { - op->MarkFailed(*ex); - return; + std::unique_lock lock(op->mutex); + op->req_cv.wait(lock, [&op]() { + return !op->req_chunks.empty() || op->req_eof || op->failed || + op->IsCanceled(); + }); } } + } - bool has_accept_encoding = false; - std::unordered_set seen_headers; - for (const auto& kv : active_headers) { - if (AsciiEqualsIgnoreCase(kv.first, "Accept-Encoding")) { - has_accept_encoding = true; - } - LocalRef jk(env, env->NewStringUTF(kv.first.c_str())); - if (auto ex = TakeJniException(env); ex || !jk) { - op->MarkFailed(ex.value_or("Failed to allocate header name")); - return; - } - LocalRef jv(env, env->NewStringUTF(kv.second.c_str())); - if (auto ex = TakeJniException(env); ex || !jv) { - op->MarkFailed(ex.value_or("Failed to allocate header value")); - return; - } - jmethodID header_mid = seen_headers.insert(ToLowerAscii(kv.first)).second - ? c.set_request_property - : c.add_request_property; - env->CallVoidMethod(conn.get(), header_mid, jk.get(), jv.get()); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; - } - } - if (!has_accept_encoding) { - // Match .NET HttpClientHandler (AutomaticDecompression = None) and - // Desktop libcurl so Android's OkHttp BridgeInterceptor does not inject - // `Accept-Encoding: gzip`, strip Content-Length, buffer SSE frames, or - // corrupt Range ETag / byte offsets. - LocalRef jae_k(env, env->NewStringUTF("Accept-Encoding")); - if (auto ex = TakeJniException(env); ex || !jae_k) { - op->MarkFailed(ex.value_or("Failed to allocate Accept-Encoding key")); - return; - } - LocalRef jae_v(env, env->NewStringUTF("identity")); - if (auto ex = TakeJniException(env); ex || !jae_v) { - op->MarkFailed(ex.value_or("Failed to allocate identity value")); - return; - } - env->CallVoidMethod(conn.get(), c.set_request_property, jae_k.get(), - jae_v.get()); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; - } + if (!write_failed) { + env->CallVoidMethod(out_stream.get(), c.output_flush); + if (env->ExceptionCheck()) env->ExceptionClear(); + } + env->CallVoidMethod(out_stream.get(), c.output_close); + if (auto ex = TakeJniException(env)) { + if (!write_failed && !op->IsCanceled()) { + *out_write_err = std::move(*ex); + op->MarkRequestWriteClosed(); } + } + cancel_handle->ClearOutputStream(env); + return !op->IsCanceled(); +} - // Stream request body if present. Never call setDoOutput(true) on bodyless - // GET/HEAD/DELETE requests because HttpURLConnection rewrites GET -> POST. - bool send_body = active_content_len >= 0 || - active_content_len == kChunkedRequestContent || - (active_content_len == kNoRequestContent && - (AsciiEqualsIgnoreCase(active_method, "POST") || - AsciiEqualsIgnoreCase(active_method, "PUT") || - AsciiEqualsIgnoreCase(active_method, "PATCH"))); - if (send_body) { - env->CallVoidMethod(conn.get(), c.set_do_output, JNI_TRUE); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; - } - if (active_content_len == kNoRequestContent || active_content_len == 0) { - env->CallVoidMethod(conn.get(), c.set_fixed_len_streaming, - static_cast(0)); - } else if (active_content_len > 0) { - env->CallVoidMethod(conn.get(), c.set_fixed_len_streaming, - static_cast(active_content_len)); - } else { - env->CallVoidMethod(conn.get(), c.set_chunked_streaming, - static_cast(65536)); - } - if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; - } +// Reads HTTP status code, reason phrase, and response headers from `conn`. +bool ReadAndroidResponseHeaders( + JNIEnv* env, const std::shared_ptr& op, jobject conn, + const std::optional& write_err, + AndroidResponseHead* out_head) { + auto& c = GetJniCache(); - LocalRef out_stream( - env, env->CallObjectMethod(conn.get(), c.get_output_stream)); - if (auto ex = TakeJniException(env); ex || !out_stream) { - if (!op->IsCanceled()) { - op->MarkFailed(ex.value_or("Failed to open request OutputStream")); - } - return; + jint status_code = env->CallIntMethod(conn, c.get_response_code); + if (auto ex = TakeJniException(env)) { + if (!op->IsCanceled()) { + if (write_err && ex->error_class == kHttpErrorOther && + write_err->error_class != kHttpErrorOther) { + op->MarkFailed(write_err->message, write_err->error_class); + } else { + op->MarkFailed(ex->message, ex->error_class); } - { - jobject g_out = env->NewGlobalRef(out_stream.get()); - if (auto ex = TakeJniException(env); ex || g_out == nullptr) { - op->MarkFailed(ex.value_or("Failed to retain request OutputStream")); - return; - } - std::lock_guard lock(cancel_handle->mutex); - cancel_handle->out_stream_global = g_out; + } + return false; + } + if (status_code <= 0) { + if (!op->IsCanceled()) { + if (write_err) { + op->MarkFailed(write_err->message, write_err->error_class); + } else { + op->MarkFailed("HttpURLConnection returned invalid HTTP status code.", + kHttpErrorOther); } + } + return false; + } - if (active_content_len > 0 || - active_content_len == kChunkedRequestContent) { - constexpr size_t kWriteSlice = 64 * 1024; - LocalRef jwrite_buf( - env, env->NewByteArray(static_cast(kWriteSlice))); - if (auto ex = TakeJniException(env); ex || !jwrite_buf) { - op->MarkFailed(ex.value_or("Failed to allocate JNI write buffer")); - return; - } - std::vector scratch(kWriteSlice); - while (!op->IsCanceled()) { - bool eof = false; - size_t n = op->PopRequestBytes(scratch.data(), kWriteSlice, &eof); - if (n > 0) { - env->SetByteArrayRegion( - jwrite_buf.get(), 0, static_cast(n), - reinterpret_cast(scratch.data())); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); - return; - } - env->CallVoidMethod(out_stream.get(), c.output_write, - jwrite_buf.get(), 0, static_cast(n)); - if (auto ex = TakeJniException(env)) { - if (!op->IsCanceled()) op->MarkFailed(*ex); - return; - } - } else if (eof) { + out_head->status_code = static_cast(status_code); + LocalRef jreason( + env, + static_cast(env->CallObjectMethod(conn, c.get_response_message))); + if (env->ExceptionCheck()) env->ExceptionClear(); + out_head->reason = ::firebase::util::JStringToString(env, jreason.get()); + out_head->headers.clear(); + + LocalRef header_map(env, + env->CallObjectMethod(conn, c.get_header_fields)); + if (!TakeJniException(env) && header_map) { + LocalRef entry_set( + env, env->CallObjectMethod(header_map.get(), c.map_entry_set)); + if (!TakeJniException(env) && entry_set) { + LocalRef iter( + env, env->CallObjectMethod(entry_set.get(), c.set_iterator)); + if (!TakeJniException(env) && iter) { + while (true) { + jboolean has_next = + env->CallBooleanMethod(iter.get(), c.iter_has_next); + if (TakeJniException(env) || has_next != JNI_TRUE) { break; - } else { - std::unique_lock lock(op->mutex); - op->req_cv.wait(lock, [&op]() { - return !op->req_chunks.empty() || op->req_eof || op->failed || - op->IsCanceled(); - }); + } + LocalRef entry(env, + env->CallObjectMethod(iter.get(), c.iter_next)); + if (TakeJniException(env) || !entry) break; + LocalRef jkey( + env, static_cast( + env->CallObjectMethod(entry.get(), c.entry_get_key))); + if (TakeJniException(env) || !jkey) { + // HttpURLConnection maps the status line under a null key. + continue; + } + std::string key_str = + ::firebase::util::JStringToString(env, jkey.get()); + if (key_str.empty()) continue; + + LocalRef val_list( + env, env->CallObjectMethod(entry.get(), c.entry_get_value)); + if (TakeJniException(env) || !val_list) continue; + jint count = env->CallIntMethod(val_list.get(), c.list_size); + if (TakeJniException(env)) continue; + for (jint i = 0; i < count; ++i) { + LocalRef jval(env, + static_cast(env->CallObjectMethod( + val_list.get(), c.list_get, i))); + if (TakeJniException(env)) break; + if (jval) { + out_head->headers.emplace_back( + key_str, ::firebase::util::JStringToString(env, jval.get())); + } } } } + } + } + return true; +} - env->CallVoidMethod(out_stream.get(), c.output_flush); - if (env->ExceptionCheck()) env->ExceptionClear(); - env->CallVoidMethod(out_stream.get(), c.output_close); - if (auto ex = TakeJniException(env)) { - if (!op->IsCanceled()) op->MarkFailed(*ex); - return; +// Updates `hop` for a 3xx redirect response. Returns true to continue to the +// next redirect hop, or false after marking `op` failed. +bool ApplyAndroidRedirect(JNIEnv* env, const std::shared_ptr& op, + jobject conn, int redirect_count, int32_t status_code, + std::string_view location, AndroidHopState* hop) { + auto& c = GetJniCache(); + + // Close the redirect response stream so Android's ConnectionPool can reuse + // the socket before following the redirect. + LocalRef redir_stream( + env, env->CallObjectMethod(conn, c.get_input_stream)); + if (env->ExceptionCheck()) env->ExceptionClear(); + if (redir_stream) { + env->CallVoidMethod(redir_stream.get(), c.input_close); + if (env->ExceptionCheck()) env->ExceptionClear(); + } + + if (redirect_count == kMaxRedirects) { + op->MarkFailed("Maximum HTTP redirects exceeded.", kHttpErrorOther); + return false; + } + auto resolved = ResolveRedirectUrl(hop->current_url, location); + if (!resolved || (IsHttpsUrl(op->url) && !IsHttpsUrl(*resolved))) { + op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect.", + kHttpErrorOther); + return false; + } + bool same_origin = + IsSameOrigin(op->url, *resolved) && IsSameOrigin(hop->current_url, *resolved); + if ((status_code == 301 || status_code == 302 || status_code == 303) && + !AsciiEqualsIgnoreCase(hop->active_method, "GET") && + !AsciiEqualsIgnoreCase(hop->active_method, "HEAD")) { + hop->active_method = "GET"; + hop->active_content_len = kNoRequestContent; + op->MarkRequestWriteClosed(); + } else if (status_code == 303 && + AsciiEqualsIgnoreCase(hop->active_method, "HEAD")) { + hop->active_content_len = kNoRequestContent; + } else if (hop->active_content_len != kNoRequestContent && + hop->active_content_len != 0) { + op->MarkFailed("Cannot replay streamed request body across redirect.", + kHttpErrorOther); + return false; + } + + if (!same_origin || hop->active_content_len == kNoRequestContent) { + std::vector> filtered; + filtered.reserve(hop->active_headers.size()); + for (const auto& kv : hop->active_headers) { + if (!same_origin && (IsSensitiveRedirectHeader(kv.first) || + AsciiEqualsIgnoreCase(kv.first, "Host"))) { + continue; } - { - std::lock_guard lock(cancel_handle->mutex); - if (cancel_handle->out_stream_global != nullptr) { - env->DeleteGlobalRef(cancel_handle->out_stream_global); - cancel_handle->out_stream_global = nullptr; - } + if (hop->active_content_len == kNoRequestContent && + (AsciiEqualsIgnoreCase(kv.first, "Content-Type") || + AsciiEqualsIgnoreCase(kv.first, "Content-Length") || + AsciiEqualsIgnoreCase(kv.first, "Transfer-Encoding"))) { + continue; } + filtered.push_back(kv); } + hop->active_headers = std::move(filtered); + } + hop->current_url = std::move(*resolved); + return true; +} - if (op->IsCanceled()) { - return; - } +// Streams response body bytes from `conn` into `op` with bounded backpressure. +// Returns true on clean EOF. +bool ReadAndroidResponseBody( + JNIEnv* env, const std::shared_ptr& op, + const std::shared_ptr& cancel_handle, jobject conn) { + auto& c = GetJniCache(); - jint status_code = env->CallIntMethod(conn.get(), c.get_response_code); - if (auto ex = TakeJniException(env)) { - if (!op->IsCanceled()) op->MarkFailed(*ex); - return; - } - LocalRef jreason(env, static_cast(env->CallObjectMethod( - conn.get(), c.get_response_message))); - if (env->ExceptionCheck()) env->ExceptionClear(); - std::string reason = JStringToStdString(env, jreason.get()); - - std::vector> resp_headers; - LocalRef header_map( - env, env->CallObjectMethod(conn.get(), c.get_header_fields)); - if (!TakeJniException(env) && header_map) { - LocalRef entry_set( - env, env->CallObjectMethod(header_map.get(), c.map_entry_set)); - if (!TakeJniException(env) && entry_set) { - LocalRef iter( - env, env->CallObjectMethod(entry_set.get(), c.set_iterator)); - if (!TakeJniException(env) && iter) { - while (true) { - jboolean has_next = - env->CallBooleanMethod(iter.get(), c.iter_has_next); - if (TakeJniException(env) || has_next != JNI_TRUE) { - break; - } - LocalRef entry( - env, env->CallObjectMethod(iter.get(), c.iter_next)); - if (TakeJniException(env) || !entry) break; - LocalRef jkey( - env, static_cast( - env->CallObjectMethod(entry.get(), c.entry_get_key))); - if (TakeJniException(env) || !jkey) { - // HttpURLConnection maps the status line under a null key. - continue; - } - std::string key_str = JStringToStdString(env, jkey.get()); - if (key_str.empty()) continue; - - LocalRef val_list( - env, env->CallObjectMethod(entry.get(), c.entry_get_value)); - if (TakeJniException(env) || !val_list) continue; - jint count = env->CallIntMethod(val_list.get(), c.list_size); - if (TakeJniException(env)) continue; - for (jint i = 0; i < count; ++i) { - LocalRef jval(env, - static_cast(env->CallObjectMethod( - val_list.get(), c.list_get, i))); - if (TakeJniException(env)) break; - if (jval) { - resp_headers.emplace_back(key_str, - JStringToStdString(env, jval.get())); - } - } - } - } - } + LocalRef in_stream(env, + env->CallObjectMethod(conn, c.get_input_stream)); + if (env->ExceptionCheck() || !in_stream) { + env->ExceptionClear(); + in_stream.reset(env->CallObjectMethod(conn, c.get_error_stream)); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + in_stream.reset(nullptr); } + } - std::string_view location = - FindHeaderValueIgnoreCase(resp_headers, "Location"); - if (IsRedirectStatus(static_cast(status_code)) && - !location.empty()) { - // Drain/close response stream on the redirect hop so the pooled socket - // stays reusable before following. - LocalRef redir_stream( - env, env->CallObjectMethod(conn.get(), c.get_input_stream)); - if (env->ExceptionCheck()) env->ExceptionClear(); - if (redir_stream) { - env->CallVoidMethod(redir_stream.get(), c.input_close); - if (env->ExceptionCheck()) env->ExceptionClear(); - } + if (!in_stream) { + op->MarkResponseComplete(); + return true; + } - if (redirect_count == kMaxRedirects) { - op->MarkFailed("Maximum HTTP redirects exceeded."); - return; - } - auto resolved = ResolveRedirectUrl(current_url, location); - if (!resolved || (IsHttpsUrl(op->url) && !IsHttpsUrl(*resolved))) { - op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect."); - return; - } - bool same_origin = IsSameOrigin(op->url, *resolved) && - IsSameOrigin(current_url, *resolved); - if (status_code == 303 || - ((status_code == 301 || status_code == 302) && - !AsciiEqualsIgnoreCase(active_method, "GET") && - !AsciiEqualsIgnoreCase(active_method, "HEAD"))) { - active_method = "GET"; - active_content_len = kNoRequestContent; - } else if (active_content_len != kNoRequestContent && - active_content_len != 0) { - op->MarkFailed("Cannot replay streamed request body across redirect."); - return; - } + { + jobject g_in = env->NewGlobalRef(in_stream.get()); + if (auto ex = TakeJniException(env); ex || g_in == nullptr) { + op->MarkFailed(ex ? ex->message : "Failed to retain response InputStream", + ex ? ex->error_class : kHttpErrorOther); + return false; + } + std::lock_guard lock(cancel_handle->mutex); + cancel_handle->in_stream_global = g_in; + } + if (op->IsCanceled()) { + return false; + } - if (!same_origin || active_content_len == kNoRequestContent) { - std::vector> filtered; - filtered.reserve(active_headers.size()); - for (const auto& kv : active_headers) { - if (!same_origin && (IsSensitiveRedirectHeader(kv.first) || - AsciiEqualsIgnoreCase(kv.first, "Host"))) { - continue; - } - if (active_content_len == kNoRequestContent && - (AsciiEqualsIgnoreCase(kv.first, "Content-Type") || - AsciiEqualsIgnoreCase(kv.first, "Content-Length") || - AsciiEqualsIgnoreCase(kv.first, "Transfer-Encoding"))) { - continue; - } - filtered.push_back(kv); - } - active_headers = std::move(filtered); + constexpr size_t kReadSlice = 64 * 1024; + LocalRef jread_buf( + env, env->NewByteArray(static_cast(kReadSlice))); + if (auto ex = TakeJniException(env); ex || !jread_buf) { + op->MarkFailed(ex ? ex->message : "Failed to allocate JNI read buffer", + ex ? ex->error_class : kHttpErrorOther); + return false; + } + std::vector read_scratch(kReadSlice); + + while (!op->IsCanceled()) { + jint n = env->CallIntMethod(in_stream.get(), c.input_read, jread_buf.get(), + 0, static_cast(kReadSlice)); + if (auto ex = TakeJniException(env)) { + if (!op->IsCanceled()) { + op->MarkFailed(ex->message, ex->error_class); } - current_url = std::move(*resolved); + return false; + } + if (n < 0) { + break; + } + if (n == 0) { continue; } + env->GetByteArrayRegion(jread_buf.get(), 0, n, + reinterpret_cast(read_scratch.data())); + if (auto ex = TakeJniException(env)) { + op->MarkFailed(ex->message, ex->error_class); + return false; + } + bool over_high_water = + op->PushResponseBytes(read_scratch.data(), static_cast(n)); + if (over_high_water && !op->IsCanceled()) { + std::unique_lock lock(op->mutex); + op->resp_cv.wait(lock, [&op]() { + return op->resp_buffered_bytes <= kLowWaterResponseBytes || + op->IsCanceled() || op->failed; + }); + } + } + + if (op->IsCanceled()) { + return false; + } - op->CommitResponseHeaders(static_cast(status_code), reason, - std::move(resp_headers)); + // Close the response stream so Android's ConnectionPool can reuse the live + // TLS connection; do not call conn.disconnect() on normal completion. + env->CallVoidMethod(in_stream.get(), c.input_close); + if (env->ExceptionCheck()) env->ExceptionClear(); + op->MarkResponseComplete(); + return true; +} + +void ExecuteAndroidOperation(JNIEnv* env, + const std::shared_ptr& op) { + if (!EnsureJniInitialized(env)) { + op->MarkFailed("Failed to initialize Android JNI HTTP bindings.", + kHttpErrorOther); + return; + } + if (!IsHttpOrHttpsUrl(op->url)) { + op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", + kHttpErrorOther); + return; + } + + auto cancel_handle = std::make_shared(); + { + std::lock_guard lock(op->mutex); if (op->IsCanceled()) { return; } + op->on_cancel = [cancel_handle]() { + AndroidCancelDispatcher::Instance().Enqueue(cancel_handle); + }; + } - LocalRef in_stream( - env, env->CallObjectMethod(conn.get(), c.get_input_stream)); - if (env->ExceptionCheck() || !in_stream) { - env->ExceptionClear(); - in_stream.reset(env->CallObjectMethod(conn.get(), c.get_error_stream)); - if (env->ExceptionCheck()) { - env->ExceptionClear(); - in_stream.reset(nullptr); + bool completed_cleanly = false; + struct CleanupGuard { + JNIEnv* env; + std::shared_ptr handle; + bool* completed_cleanly; + ~CleanupGuard() { + if (!*completed_cleanly) { + handle->AbortNow(env); } + handle->ClearAll(env); } + } guard{env, cancel_handle, &completed_cleanly}; - if (!in_stream) { - completed_cleanly = true; - op->MarkResponseComplete(); + AndroidHopState hop; + hop.current_url = op->url; + hop.active_method = op->method; + hop.active_headers = op->request_headers; + hop.active_content_len = op->content_length; + + for (int redirect_count = 0; redirect_count <= kMaxRedirects; + ++redirect_count) { + cancel_handle->ClearAll(env); + + LocalRef conn = + BuildAndroidRequestConnection(env, op, cancel_handle, hop); + if (!conn) { return; } - { - jobject g_in = env->NewGlobalRef(in_stream.get()); - if (auto ex = TakeJniException(env); ex || g_in == nullptr) { - op->MarkFailed(ex.value_or("Failed to retain response InputStream")); - return; - } - std::lock_guard lock(cancel_handle->mutex); - cancel_handle->in_stream_global = g_in; - } - if (op->IsCanceled()) { + std::optional write_err; + if (!SendAndroidRequestBody(env, op, cancel_handle, conn.get(), hop, + &write_err)) { return; } - constexpr size_t kReadSlice = 64 * 1024; - LocalRef jread_buf( - env, env->NewByteArray(static_cast(kReadSlice))); - if (auto ex = TakeJniException(env); ex || !jread_buf) { - op->MarkFailed(ex.value_or("Failed to allocate JNI read buffer")); + AndroidResponseHead head; + if (!ReadAndroidResponseHeaders(env, op, conn.get(), write_err, &head)) { return; } - std::vector read_scratch(kReadSlice); - while (!op->IsCanceled()) { - jint n = - env->CallIntMethod(in_stream.get(), c.input_read, jread_buf.get(), 0, - static_cast(kReadSlice)); - if (auto ex = TakeJniException(env)) { - if (!op->IsCanceled()) op->MarkFailed(*ex); - return; - } - if (n < 0) { - break; - } - if (n == 0) { - continue; - } - env->GetByteArrayRegion(jread_buf.get(), 0, n, - reinterpret_cast(read_scratch.data())); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(*ex); + std::string_view location = + FindHeaderValueIgnoreCase(head.headers, "Location"); + if (IsRedirectStatus(head.status_code) && !location.empty()) { + if (!ApplyAndroidRedirect(env, op, conn.get(), redirect_count, + head.status_code, location, &hop)) { return; } - bool over_high_water = - op->PushResponseBytes(read_scratch.data(), static_cast(n)); - if (over_high_water && !op->IsCanceled()) { - std::unique_lock lock(op->mutex); - op->resp_cv.wait(lock, [&op]() { - return op->resp_buffered_bytes <= kLowWaterResponseBytes || - op->IsCanceled() || op->failed; - }); - } + continue; } + op->CommitResponseHeaders(head.status_code, head.reason, + std::move(head.headers)); if (op->IsCanceled()) { return; } - // Close the response stream so Android's ConnectionPool can reuse the live - // TLS connection; do not call conn.disconnect() on normal completion. - env->CallVoidMethod(in_stream.get(), c.input_close); - if (env->ExceptionCheck()) env->ExceptionClear(); - completed_cleanly = true; - op->MarkResponseComplete(); + completed_cleanly = + ReadAndroidResponseBody(env, op, cancel_handle, conn.get()); return; } } @@ -1102,34 +1334,8 @@ class AndroidHttpThreadPool { // SSE / GetStreamAsync() streams never starve short requests. static constexpr size_t kMaxWorkers = 64; - static JNIEnv* AttachWorkerThread(JavaVM** out_vm, bool* out_attached) { - JavaVM* vm = ResolveJavaVM(); - if (vm == nullptr) { - return nullptr; - } - JNIEnv* env = nullptr; - jint status = vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6); - if (status == JNI_EDETACHED) { - JavaVMAttachArgs args{}; - args.version = JNI_VERSION_1_6; - args.name = const_cast("FirebaseHttpWorker"); - args.group = nullptr; - if (vm->AttachCurrentThread(&env, &args) == JNI_OK) { - *out_vm = vm; - *out_attached = true; - } else { - return nullptr; - } - } else if (status == JNI_OK) { - *out_vm = vm; - } - return env; - } - void WorkerLoop() { - JavaVM* vm = nullptr; - bool attached = false; - JNIEnv* env = AttachWorkerThread(&vm, &attached); + JNIEnv* env = ResolveThreadsafeJNIEnv(); { std::lock_guard lock(mutex_); @@ -1155,18 +1361,15 @@ class AndroidHttpThreadPool { } if (env == nullptr) { - env = AttachWorkerThread(&vm, &attached); + env = ResolveThreadsafeJNIEnv(); } if (env == nullptr) { - next->MarkFailed("Android JavaVM / JNIEnv is unavailable."); + next->MarkFailed("Android JavaVM / JNIEnv is unavailable.", + kHttpErrorOther); } else { ExecuteAndroidOperation(env, next); } } - - if (attached && vm != nullptr) { - vm->DetachCurrentThread(); - } } std::mutex mutex_; From 9cc6737e7743c2a97e7401980ed38ffcc699710f Mon Sep 17 00:00:00 2001 From: Austin Benoit Date: Fri, 27 Nov 2026 13:51:27 -0500 Subject: [PATCH 06/16] [App][HTTP] Strengthen HTTP transport tests with socket-close, blocking events, and new cases (T1-T4) --- app/http/tests/http_transport_common_test.cc | 165 ++++- app/http/tests/http_transport_curl_test.cc | 706 ++++++++++++++++--- 2 files changed, 740 insertions(+), 131 deletions(-) diff --git a/app/http/tests/http_transport_common_test.cc b/app/http/tests/http_transport_common_test.cc index cfde58cca7..c3ba45eebf 100644 --- a/app/http/tests/http_transport_common_test.cc +++ b/app/http/tests/http_transport_common_test.cc @@ -15,8 +15,12 @@ */ #include +#include +#include #include +#include #include +#include #include #include @@ -50,11 +54,6 @@ TEST(HttpTransportCommonTest, ParseUrlOriginStandardAndDefaults) { ASSERT_TRUE(ipv6.has_value()); EXPECT_EQ(ipv6->host, "[::1]"); EXPECT_EQ(ipv6->port, 8443); - - auto userinfo = ParseUrlOrigin("https://user:pass@Example.COM/p"); - ASSERT_TRUE(userinfo.has_value()); - EXPECT_EQ(userinfo->host, "example.com"); - EXPECT_EQ(userinfo->port, 443); } TEST(HttpTransportCommonTest, ParseUrlOriginRejectsUnsafeInputs) { @@ -62,6 +61,10 @@ TEST(HttpTransportCommonTest, ParseUrlOriginRejectsUnsafeInputs) { EXPECT_FALSE(ParseUrlOrigin("file:///etc/passwd").has_value()); EXPECT_FALSE(ParseUrlOrigin("ftp://example.com/a").has_value()); EXPECT_FALSE(ParseUrlOrigin("https://evil.com\\@trusted.com/p").has_value()); + // Userinfo must be rejected (S1) because parsers disagree on multiple `@`. + EXPECT_FALSE(ParseUrlOrigin("https://user:pass@Example.COM/p").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://a@b@c.example.com/p").has_value()); + EXPECT_FALSE(ParseUrlOrigin("https://@example.com/p").has_value()); EXPECT_FALSE(ParseUrlOrigin("https://bad host/p").has_value()); EXPECT_FALSE(ParseUrlOrigin("https://example.com:0/p").has_value()); EXPECT_FALSE(ParseUrlOrigin("https://example.com:70000/p").has_value()); @@ -86,6 +89,8 @@ TEST(HttpTransportCommonTest, SensitiveRedirectHeadersMatchCaseInsensitively) { EXPECT_TRUE(IsSensitiveRedirectHeader("Authorization")); EXPECT_TRUE(IsSensitiveRedirectHeader("authorization")); EXPECT_TRUE(IsSensitiveRedirectHeader("Proxy-Authorization")); + EXPECT_TRUE(IsSensitiveRedirectHeader("Cookie")); + EXPECT_TRUE(IsSensitiveRedirectHeader("cookie")); EXPECT_TRUE(IsSensitiveRedirectHeader("X-Firebase-AppCheck")); EXPECT_TRUE(IsSensitiveRedirectHeader("x-firebase-appcheck")); EXPECT_TRUE(IsSensitiveRedirectHeader("x-goog-api-key")); @@ -113,6 +118,9 @@ TEST(HttpTransportCommonTest, ResolveRedirectUrlRfc3986Forms) { EXPECT_EQ(ResolveRedirectUrl(base, "next?redir=http://ignored.example/x"), "https://storage.example.com/v0/b/my-bucket/next?redir=http://" "ignored.example/x"); + // Spaces in path/query are percent-encoded (C3). + EXPECT_EQ(ResolveRedirectUrl(base, "/my folder/file name.txt?q=a b"), + "https://storage.example.com/my%20folder/file%20name.txt?q=a%20b"); } TEST(HttpTransportCommonTest, ResolveRedirectUrlBlocksDowngradesAndConfusion) { @@ -128,6 +136,11 @@ TEST(HttpTransportCommonTest, ResolveRedirectUrlBlocksDowngradesAndConfusion) { EXPECT_FALSE(ResolveRedirectUrl(https_base, "\\\\evil.com/x").has_value()); EXPECT_FALSE(ResolveRedirectUrl(https_base, "/\\evil.com/x").has_value()); EXPECT_FALSE(ResolveRedirectUrl(https_base, "/bad\r\nHeader: 1").has_value()); + EXPECT_FALSE( + ResolveRedirectUrl(https_base, "https://user:pass@example.com/x") + .has_value()); + EXPECT_FALSE( + ResolveRedirectUrl(https_base, "https://bad host/x").has_value()); EXPECT_FALSE(ResolveRedirectUrl(https_base, "").has_value()); EXPECT_FALSE(ResolveRedirectUrl(https_base, ":no-scheme").has_value()); @@ -157,14 +170,17 @@ TEST(HttpTransportCommonTest, ParseProxyHostPort) { EXPECT_FALSE(ParseProxyHostPort("").has_value()); EXPECT_FALSE(ParseProxyHostPort("socks5://127.0.0.1:1080").has_value()); + EXPECT_FALSE(ParseProxyHostPort("http://user:pass@proxy:8080").has_value()); } TEST(HttpTransportCommonTest, ParsePackedHeadersPreservesDuplicates) { - auto headers = ParsePackedHeaders( + std::vector> headers; + ASSERT_TRUE(TryParsePackedHeaders( "Authorization\tBearer tok\n" "X-Multi\tfirst\r\n" "X-Multi\tsecond\n" - "Content-Type: application/json\n"); + "Content-Type: application/json\n", + &headers)); ASSERT_EQ(headers.size(), 4u); EXPECT_EQ(headers[0], std::make_pair(std::string("Authorization"), std::string("Bearer tok"))); @@ -176,6 +192,123 @@ TEST(HttpTransportCommonTest, ParsePackedHeadersPreservesDuplicates) { std::string("application/json"))); } +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)); + + // Direct C++ 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), kHttpErrorOther); + HttpDestroyRequestInternal(h); +} + +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), kHttpErrorOther); + 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", kHttpErrorTls); + EXPECT_EQ(HttpGetErrorClassInternal(h1), kHttpErrorTls); + + 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", "", @@ -231,6 +364,8 @@ TEST(HttpTransportCommonTest, RequestAndResponsePipeWatermarksAndCancel) { } TEST(HttpTransportCommonTest, MarkResponseCompleteWakesBlockedUploader) { + while (HttpWaitNextEventInternal(0) != 0) { + } int64_t handle = HttpCreateRequestInternal( "PUT", "http://127.0.0.1:80/early-413", "", "", static_cast(kMaxRequestBufferBytes * 2)); @@ -251,18 +386,10 @@ TEST(HttpTransportCommonTest, MarkResponseCompleteWakesBlockedUploader) { // Completion queue must wake the armed uploader and subsequent writes fail // immediately instead of blocking forever. - bool saw_req_space_event = false; - for (int i = 0; i < 8; ++i) { - int64_t ev = HttpWaitNextEventInternal(0); - if (ev == 0) { - break; - } - if ((ev >> 8) == handle && static_cast(ev & 0xFF) == - kHttpEventRequestSpaceAvailable) { - saw_req_space_event = true; - } - } - EXPECT_TRUE(saw_req_space_event); + int64_t ev = HttpWaitNextEventInternal(1000); + EXPECT_EQ(ev >> 8, handle); + EXPECT_EQ(static_cast(ev & 0xFF), + kHttpEventRequestSpaceAvailable); EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 64), -1); HttpDestroyRequestInternal(handle); diff --git a/app/http/tests/http_transport_curl_test.cc b/app/http/tests/http_transport_curl_test.cc index 3aba6d0861..b01e7af696 100644 --- a/app/http/tests/http_transport_curl_test.cc +++ b/app/http/tests/http_transport_curl_test.cc @@ -14,6 +14,7 @@ * limitations under the License. */ +#include #include #include #include @@ -21,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +30,7 @@ #include #include #include +#include #include #include @@ -79,6 +82,57 @@ void CloseSocket(SocketFd 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 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) { @@ -172,10 +226,6 @@ class LoopbackHttpServer { if (stopped_.exchange(true)) { return; } - // Wake AcceptLoop() portably across Linux, macOS, and Windows (where - // shutdown() on an unconnected listening socket returns ENOTCONN / - // WSAENOTCONN without waking accept()). `select()` with a 50 ms timeout in - // AcceptLoop() also guarantees termination if self-connect is refused. if (port_ > 0) { SocketFd wake = socket(AF_INET, SOCK_STREAM, 0); if (wake != kInvalidSocket) { @@ -220,18 +270,7 @@ class LoopbackHttpServer { if (fd == kInvalidSocket) { break; } - fd_set read_fds; - FD_ZERO(&read_fds); - FD_SET(fd, &read_fds); - timeval tv{}; - tv.tv_sec = 0; - tv.tv_usec = 50 * 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 - if (ready <= 0) { + if (!WaitForSocketReadable(fd, 50)) { continue; } if (stopped_.load()) { @@ -342,7 +381,6 @@ class LoopbackHttpServer { std::strtoull(raw.substr(0, crlf).c_str(), nullptr, 16)); raw.erase(0, crlf + 2); if (chunk_len == 0) { - // Consume trailing CRLF after 0-length chunk. ensure(2); break; } @@ -390,26 +428,74 @@ class LoopbackHttpServer { std::vector workers_; }; -// Synchronously drives an operation via the flat bridge API until response -// headers arrive (returning HTTP status code or -1 on error/cancel). -int32_t WaitHeaders(int64_t handle, int timeout_ms = 5000) { - auto deadline = - std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); - while (std::chrono::steady_clock::now() < deadline) { - int32_t status = HttpPollResponseHeadersInternal(handle); - if (status != 0) { - return status; +// 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; + } } - HttpWaitNextEventInternal(50); + + 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; } - return 0; + EXPECT_TRUE( + demux->WaitFor(handle, kHttpEventResponseHeadersReady, timeout_ms)) + << "Timed out waiting for kHttpEventResponseHeadersReady on handle " + << handle; + return HttpPollResponseHeadersInternal(handle); } -bool ReadAllBody(int64_t handle, std::string* out, int timeout_ms = 10000) { +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 (std::chrono::steady_clock::now() < deadline) { + while (true) { int32_t n = HttpTryReadResponseBodyInternal(handle, buf, sizeof(buf)); if (n > 0) { out->append(buf, static_cast(n)); @@ -421,17 +507,27 @@ bool ReadAllBody(int64_t handle, std::string* out, int timeout_ms = 10000) { if (n == kHttpReadErrorOrCanceled) { return false; } - HttpWaitNextEventInternal(50); + 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; + } } - return false; } -bool WriteAllBody(int64_t handle, const uint8_t* data, size_t len, - int timeout_ms = 10000) { +bool WriteAllBody(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 && std::chrono::steady_clock::now() < deadline) { + while (offset < len) { int32_t to_send = static_cast( (std::min)(len - offset, static_cast(65536))); int32_t n = HttpTryWriteRequestBodyInternal( @@ -441,14 +537,27 @@ bool WriteAllBody(int64_t handle, const uint8_t* data, size_t len, offset += static_cast(n); continue; } - HttpWaitNextEventInternal(50); + 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, kHttpEventRequestSpaceAvailable, + (std::max)(rem_ms, 1))) { + ADD_FAILURE() << "Expected kHttpEventRequestSpaceAvailable event"; + return false; + } } - if (offset != len) 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"); @@ -468,19 +577,74 @@ TEST(HttpTransportCurlTest, GetBasic200AndMultiValueHeaders) { "X-Client\tfirebase-cpp\n", "", kNoRequestContent); HttpStartRequestInternal(h); - ASSERT_EQ(WaitHeaders(h), 200); + 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(h, &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"); @@ -515,11 +679,12 @@ TEST(HttpTransportCurlTest, PostJsonAndError400And204NoContent) { "Content-Type\tapplication/json\n", "", static_cast(payload.size())); HttpStartRequestInternal(h1); - ASSERT_TRUE(WriteAllBody(h1, reinterpret_cast(payload.data()), + ASSERT_TRUE(WriteAllBody(&demux, h1, + reinterpret_cast(payload.data()), payload.size())); - ASSERT_EQ(WaitHeaders(h1), 200); + ASSERT_EQ(WaitHeaders(&demux, h1), 200); std::string body1; - ASSERT_TRUE(ReadAllBody(h1, &body1)); + ASSERT_TRUE(ReadAllBody(&demux, h1, &body1)); EXPECT_EQ(body1, "{\"result\":{\"echo\":\"hi\"}}"); HttpDestroyRequestInternal(h1); @@ -527,9 +692,9 @@ TEST(HttpTransportCurlTest, PostJsonAndError400And204NoContent) { int64_t h2 = HttpCreateRequestInternal("POST", server.Url("/err400").c_str(), "", "", 0); HttpStartRequestInternal(h2); - ASSERT_EQ(WaitHeaders(h2), 400); + ASSERT_EQ(WaitHeaders(&demux, h2), 400); std::string body2; - ASSERT_TRUE(ReadAllBody(h2, &body2)); + ASSERT_TRUE(ReadAllBody(&demux, h2, &body2)); EXPECT_EQ(body2, "{\"error\":{\"status\":\"INVALID_ARGUMENT\"}}"); HttpDestroyRequestInternal(h2); @@ -537,17 +702,17 @@ TEST(HttpTransportCurlTest, PostJsonAndError400And204NoContent) { int64_t h3 = HttpCreateRequestInternal( "DELETE", server.Url("/delete").c_str(), "", "", kNoRequestContent); HttpStartRequestInternal(h3); - ASSERT_EQ(WaitHeaders(h3), 204); + ASSERT_EQ(WaitHeaders(&demux, h3), 204); std::string body3; - ASSERT_TRUE(ReadAllBody(h3, &body3)); + ASSERT_TRUE(ReadAllBody(&demux, h3, &body3)); EXPECT_TRUE(body3.empty()); HttpDestroyRequestInternal(h3); } TEST(HttpTransportCurlTest, SseTrickleStreamingImmediateDelivery) { - // Deterministic barrier: server does NOT send chunk 2 until the client has - // already received and parsed chunk 1! Any intermediate buffering would time - // out and fail this test. + BlockingEventDemux demux; + demux.DrainStale(); + std::mutex gate_mu; std::condition_variable gate_cv; int client_acked_chunk = 0; @@ -594,22 +759,23 @@ TEST(HttpTransportCurlTest, SseTrickleStreamingImmediateDelivery) { "Accept\ttext/event-stream\nContent-Type\tapplication/json\n", "", static_cast(req_body.size())); HttpStartRequestInternal(h); - ASSERT_TRUE(WriteAllBody(h, reinterpret_cast(req_body.data()), + ASSERT_TRUE(WriteAllBody(&demux, h, + reinterpret_cast(req_body.data()), req_body.size())); - ASSERT_EQ(WaitHeaders(h), 200); + ASSERT_EQ(WaitHeaders(&demux, h), 200); auto read_until = [&](std::string* accum, std::string_view needle) -> bool { - auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); char buf[1024]; - while (accum->find(needle) == std::string::npos && - std::chrono::steady_clock::now() < deadline) { + 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 { - HttpWaitNextEventInternal(25); + if (!demux.WaitFor(h, kHttpEventResponseBodyAvailable, 5000)) { + return false; + } } } return accum->find(needle) != std::string::npos; @@ -631,16 +797,20 @@ TEST(HttpTransportCurlTest, SseTrickleStreamingImmediateDelivery) { gate_cv.notify_all(); std::string rest; - ASSERT_TRUE(ReadAllBody(h, &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) { - std::mutex stop_mu; - std::condition_variable stop_cv; - bool release_server = false; + 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, @@ -649,65 +819,86 @@ TEST(HttpTransportCurlTest, SseIdleCancelUnblocksPromptly) { "Transfer-Encoding: chunked\r\n" "\r\n" "12\r\ndata: {\"ok\":true}\n\r\n"); - std::unique_lock lock(stop_mu); - stop_cv.wait_for(lock, std::chrono::seconds(10), - [&]() { return release_server; }); + 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(h), 200); + ASSERT_EQ(WaitHeaders(&demux, h), 200); - // Read the first SSE chunk. + // Read the first SSE chunk using blocking event waits (T2). std::string got; char buf[512]; - auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); - while (got.empty() && std::chrono::steady_clock::now() < deadline) { + while (got.empty()) { int32_t n = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); if (n > 0) { got.append(buf, static_cast(n)); } else { - HttpWaitNextEventInternal(25); + 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 cancel from another thread. + // 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); - auto t0 = std::chrono::steady_clock::now(); - std::thread canceler([h]() { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); + 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); }); - int32_t rc = kHttpReadWouldBlock; - while (rc == kHttpReadWouldBlock && - std::chrono::steady_clock::now() - t0 < std::chrono::seconds(3)) { - HttpWaitNextEventInternal(50); - rc = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); + 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); - HttpDestroyRequestInternal(h); + // Assert the TCP socket actually closed from HttpCancelRequestInternal alone, + // BEFORE HttpDestroyRequestInternal is called (T1). { - std::lock_guard lock(stop_mu); - release_server = true; + 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"; } - stop_cv.notify_all(); + + HttpDestroyRequestInternal(h); } TEST(HttpTransportCurlTest, RedirectsSameOriginPreservesAuthAndCrossOriginStrips) { + BlockingEventDemux demux; + demux.DrainStale(); + std::string observed_b_auth; + std::string observed_b_cookie; std::string observed_b_appcheck; std::string observed_b_apikey; std::string observed_b_safe; @@ -719,6 +910,7 @@ TEST(HttpTransportCurlTest, std::lock_guard lock(obs_mu); observed_b_method = req.method; observed_b_auth = req.GetHeader("Authorization"); + observed_b_cookie = req.GetHeader("Cookie"); observed_b_appcheck = req.GetHeader("X-Firebase-AppCheck"); observed_b_apikey = req.GetHeader("x-goog-api-key"); observed_b_safe = req.GetHeader("X-Safe"); @@ -731,6 +923,10 @@ TEST(HttpTransportCurlTest, std::string observed_same_origin_auth; std::string observed_same_origin_method; + std::string observed_301_method; + std::string observed_303_post_method; + std::string observed_303_head_method; + std::string observed_space_target; LoopbackHttpServer server_a([&](const ParsedRequest& req, SocketFd fd) { if (req.target == "/same-302") { SendAll(fd, @@ -748,6 +944,68 @@ TEST(HttpTransportCurlTest, "HTTP/1.1 200 OK\r\n" "Content-Length: 2\r\n" "Connection: close\r\n\r\nok"); + } else if (req.target == "/post-301") { + SendAll(fd, + "HTTP/1.1 301 Moved Permanently\r\n" + "Location: /after-301\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n\r\n"); + } else if (req.target == "/after-301") { + { + std::lock_guard lock(obs_mu); + observed_301_method = req.method; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: " + "close\r\n\r\n301"); + } else if (req.target == "/post-303") { + SendAll(fd, + "HTTP/1.1 303 See Other\r\n" + "Location: /after-303-post\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n\r\n"); + } else if (req.target == "/after-303-post") { + { + std::lock_guard lock(obs_mu); + observed_303_post_method = req.method; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: " + "close\r\n\r\n303"); + } else if (req.target == "/head-303") { + SendAll(fd, + "HTTP/1.1 303 See Other\r\n" + "Location: /after-303-head\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n\r\n"); + } else if (req.target == "/after-303-head") { + { + std::lock_guard lock(obs_mu); + observed_303_head_method = req.method; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\nContent-Length: 42\r\nConnection: " + "close\r\n\r\n"); + } else if (req.target == "/body-307") { + SendAll(fd, + "HTTP/1.1 307 Temporary Redirect\r\n" + "Location: /never-reached\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n\r\n"); + } else if (req.target == "/space-redir") { + SendAll(fd, + "HTTP/1.1 302 Found\r\n" + "Location: /path with space\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n\r\n"); + } else if (req.target == "/path%20with%20space") { + { + std::lock_guard lock(obs_mu); + observed_space_target = req.target; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: " + "close\r\n\r\nspace"); } else if (req.target == "/cross-307") { SendAll(fd, "HTTP/1.1 307 Temporary Redirect\r\n" @@ -774,9 +1032,9 @@ TEST(HttpTransportCurlTest, "POST", server_a.Url("/same-302").c_str(), "Authorization\tBearer secret\nContent-Type\tapplication/json\n", "", 0); HttpStartRequestInternal(h1); - ASSERT_EQ(WaitHeaders(h1), 200); + ASSERT_EQ(WaitHeaders(&demux, h1), 200); std::string b1; - ASSERT_TRUE(ReadAllBody(h1, &b1)); + ASSERT_TRUE(ReadAllBody(&demux, h1, &b1)); EXPECT_EQ(b1, "ok"); { std::lock_guard lock(obs_mu); @@ -785,49 +1043,253 @@ TEST(HttpTransportCurlTest, } HttpDestroyRequestInternal(h1); - // 2. Cross-origin 307 strips sensitive headers, forwards safe headers. + // 2. Cross-origin 307 strips sensitive headers (including Cookie, S3), + // forwards safe headers. int64_t h2 = HttpCreateRequestInternal("GET", server_a.Url("/cross-307").c_str(), "Authorization\tBearer secret\n" + "Cookie\tsession=xyz\n" "X-Firebase-AppCheck\tappcheck-tok\n" "x-goog-api-key\tapi-key\n" "X-Safe\tkeep-me\n", "", kNoRequestContent); HttpStartRequestInternal(h2); - ASSERT_EQ(WaitHeaders(h2), 200); + ASSERT_EQ(WaitHeaders(&demux, h2), 200); std::string b2; - ASSERT_TRUE(ReadAllBody(h2, &b2)); + ASSERT_TRUE(ReadAllBody(&demux, h2, &b2)); EXPECT_EQ(b2, "done"); { std::lock_guard lock(obs_mu); EXPECT_EQ(observed_b_method, "GET"); EXPECT_TRUE(observed_b_auth.empty()); + EXPECT_TRUE(observed_b_cookie.empty()); EXPECT_TRUE(observed_b_appcheck.empty()); EXPECT_TRUE(observed_b_apikey.empty()); EXPECT_EQ(observed_b_safe, "keep-me"); } HttpDestroyRequestInternal(h2); - // 3. Infinite redirect loop fails once kMaxRedirects is exceeded. + // 3. 301 POST -> GET and 303 POST -> GET (T4). + int64_t h_301 = HttpCreateRequestInternal( + "POST", server_a.Url("/post-301").c_str(), "", "", 0); + HttpStartRequestInternal(h_301); + ASSERT_EQ(WaitHeaders(&demux, h_301), 200); + std::string b_301; + ASSERT_TRUE(ReadAllBody(&demux, h_301, &b_301)); + EXPECT_EQ(b_301, "301"); + HttpDestroyRequestInternal(h_301); + + int64_t h_303 = HttpCreateRequestInternal( + "POST", server_a.Url("/post-303").c_str(), "", "", 0); + HttpStartRequestInternal(h_303); + ASSERT_EQ(WaitHeaders(&demux, h_303), 200); + std::string b_303; + ASSERT_TRUE(ReadAllBody(&demux, h_303, &b_303)); + EXPECT_EQ(b_303, "303"); + HttpDestroyRequestInternal(h_303); + + // 4. HEAD on 303 must stay HEAD (C1, T4). + int64_t h_head = HttpCreateRequestInternal( + "HEAD", server_a.Url("/head-303").c_str(), "", "", kNoRequestContent); + HttpStartRequestInternal(h_head); + ASSERT_EQ(WaitHeaders(&demux, h_head), 200); + std::string b_head; + ASSERT_TRUE(ReadAllBody(&demux, h_head, &b_head)); + EXPECT_TRUE(b_head.empty()); + HttpDestroyRequestInternal(h_head); + + // 5. 307 with streamed body fails cleanly (T4). + const std::string body_307 = "cannot-replay"; + int64_t h_307 = HttpCreateRequestInternal( + "POST", server_a.Url("/body-307").c_str(), "", "", + static_cast(body_307.size())); + HttpStartRequestInternal(h_307); + ASSERT_TRUE(WriteAllBody(&demux, h_307, + reinterpret_cast(body_307.data()), + body_307.size())); + EXPECT_EQ(WaitHeaders(&demux, h_307), -1); + EXPECT_NE(HttpGetErrorInternal(h_307).find("Cannot replay"), + std::string::npos); + HttpDestroyRequestInternal(h_307); + + // 6. Redirect target containing a space is percent-encoded (C3). + int64_t h_sp = HttpCreateRequestInternal( + "GET", server_a.Url("/space-redir").c_str(), "", "", kNoRequestContent); + HttpStartRequestInternal(h_sp); + ASSERT_EQ(WaitHeaders(&demux, h_sp), 200); + std::string b_sp; + ASSERT_TRUE(ReadAllBody(&demux, h_sp, &b_sp)); + EXPECT_EQ(b_sp, "space"); + HttpDestroyRequestInternal(h_sp); + + { + std::lock_guard lock(obs_mu); + EXPECT_EQ(observed_301_method, "GET"); + EXPECT_EQ(observed_303_post_method, "GET"); + EXPECT_EQ(observed_303_head_method, "HEAD"); + EXPECT_EQ(observed_space_target, "/path%20with%20space"); + } + + // 7. Infinite redirect loop fails once kMaxRedirects is exceeded. int64_t h3 = HttpCreateRequestInternal("GET", server_a.Url("/loop").c_str(), "", "", kNoRequestContent); HttpStartRequestInternal(h3); - EXPECT_EQ(WaitHeaders(h3), -1); + EXPECT_EQ(WaitHeaders(&demux, h3), -1); EXPECT_NE(HttpGetErrorInternal(h3).find("Maximum HTTP redirects"), std::string::npos); HttpDestroyRequestInternal(h3); - // 4. Non-HTTP(S) redirect target is blocked. + // 8. Non-HTTP(S) redirect target is blocked. int64_t h4 = HttpCreateRequestInternal("GET", server_a.Url("/unsafe").c_str(), "", "", kNoRequestContent); HttpStartRequestInternal(h4); - EXPECT_EQ(WaitHeaders(h4), -1); + EXPECT_EQ(WaitHeaders(&demux, h4), -1); EXPECT_NE(HttpGetErrorInternal(h4).find("Blocked unsafe"), std::string::npos); HttpDestroyRequestInternal(h4); } +TEST(HttpTransportCurlTest, BadProxyAndInvalidHeadersFailWithoutConnecting) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::atomic hits{0}; + LoopbackHttpServer server([&](const ParsedRequest&, SocketFd fd) { + hits.fetch_add(1); + SendAll(fd, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); + }); + + // Bad proxy URL (socks5://) must fail, never connect direct (T4). + int64_t h1 = HttpCreateRequestInternal("GET", server.Url("/p").c_str(), "", + "socks5://127.0.0.1:1080", + kNoRequestContent); + HttpStartRequestInternal(h1); + EXPECT_EQ(WaitHeaders(&demux, h1), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h1), kHttpErrorOther); + HttpDestroyRequestInternal(h1); + + // Header containing CR injection must fail without connecting (S2, T4). + int64_t h2 = HttpCreateRequestInternal( + "GET", server.Url("/h").c_str(), "X-Test\tvalue\rInjected: 1\n", "", + kNoRequestContent); + HttpStartRequestInternal(h2); + EXPECT_EQ(WaitHeaders(&demux, h2), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h2), kHttpErrorOther); + HttpDestroyRequestInternal(h2); + + // Header containing LF injection (line without separator) must fail (S2, T4). + int64_t h3 = HttpCreateRequestInternal( + "GET", server.Url("/h2").c_str(), "X-Test\tvalue\nmalformed_line\n", "", + kNoRequestContent); + HttpStartRequestInternal(h3); + EXPECT_EQ(WaitHeaders(&demux, h3), -1); + EXPECT_EQ(HttpGetErrorClassInternal(h3), kHttpErrorOther); + HttpDestroyRequestInternal(h3); + + EXPECT_EQ(hits.load(), 0); +} + +TEST(HttpTransportCurlTest, ErrorClassesConnectAndTls) { + 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. TLS handshake failure when speaking HTTPS to a non-TLS endpoint. + 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 so every TLS stack + // (OpenSSL/BoringSSL, SecureTransport/Network.framework, Conscrypt) + // classifies the failure as kHttpErrorTls even if it retries once. + 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), kHttpErrorTls); + HttpDestroyRequestInternal(h_tls); + stop_tls_server.store(true, std::memory_order_release); + bad_tls_server.join(); +} + TEST(HttpTransportCurlTest, StreamingChunkedUploadAndLargeDownloadBackpressure) { + BlockingEventDemux demux; + demux.DrainStale(); + constexpr size_t kUploadSize = 1024 * 1024; // 1 MiB (> 256 KiB pipe) constexpr size_t kDownloadSize = 4 * 1024 * 1024; // 4 MiB (> 2 MiB pipe) @@ -869,10 +1331,10 @@ TEST(HttpTransportCurlTest, "Content-Type\tapplication/octet-stream\n", "", kChunkedRequestContent); HttpStartRequestInternal(h_up); ASSERT_TRUE( - WriteAllBody(h_up, expected_upload.data(), expected_upload.size())); - ASSERT_EQ(WaitHeaders(h_up), 200); + WriteAllBody(&demux, h_up, expected_upload.data(), expected_upload.size())); + ASSERT_EQ(WaitHeaders(&demux, h_up), 200); std::string up_resp; - ASSERT_TRUE(ReadAllBody(h_up, &up_resp)); + ASSERT_TRUE(ReadAllBody(&demux, h_up, &up_resp)); EXPECT_EQ(up_resp, "ok"); { std::lock_guard lock(upload_mu); @@ -883,20 +1345,34 @@ TEST(HttpTransportCurlTest, } HttpDestroyRequestInternal(h_up); - // 2. Large download exceeding kMaxResponseBufferBytes with intentional slow - // drain to trigger CURL_WRITEFUNC_PAUSE + low-water resume. + // 2. Large download exceeding kMaxResponseBufferBytes: wait until the + // native buffer actually crosses kMaxResponseBufferBytes (explicit condition + // instead of a fixed sleep, T3) to deterministically exercise pause/resume. int64_t h_dl = HttpCreateRequestInternal( "GET", server.Url("/download").c_str(), "", "", kNoRequestContent); HttpStartRequestInternal(h_dl); - ASSERT_EQ(WaitHeaders(h_dl), 200); + ASSERT_EQ(WaitHeaders(&demux, h_dl), 200); - // Pause reading briefly so curl fills the 2 MiB buffer and hits - // WRITEFUNC_PAUSE. - std::this_thread::sleep_for(std::chrono::milliseconds(100)); + auto dl_op = FindOperation(h_dl); + ASSERT_NE(dl_op, nullptr); + auto hw_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + bool hit_high_water = false; + while (std::chrono::steady_clock::now() < hw_deadline) { + { + std::lock_guard lock(dl_op->mutex); + if (dl_op->resp_buffered_bytes >= kMaxResponseBufferBytes || + dl_op->resp_eof) { + hit_high_water = dl_op->resp_buffered_bytes >= kMaxResponseBufferBytes; + break; + } + } + std::this_thread::yield(); + } + EXPECT_TRUE(hit_high_water); std::string dl_body; dl_body.reserve(kDownloadSize); - ASSERT_TRUE(ReadAllBody(h_dl, &dl_body, 15000)); + ASSERT_TRUE(ReadAllBody(&demux, h_dl, &dl_body, 15000)); ASSERT_EQ(dl_body.size(), expected_download.size()); EXPECT_EQ(std::memcmp(dl_body.data(), expected_download.data(), expected_download.size()), @@ -905,6 +1381,9 @@ TEST(HttpTransportCurlTest, } 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()); @@ -927,7 +1406,6 @@ TEST(HttpTransportCurlTest, ConcurrentMixedTransfers) { SendAll(fd, hex); SendAll(fd, evt); SendAll(fd, "\r\n"); - std::this_thread::sleep_for(std::chrono::milliseconds(10)); } SendAll(fd, "0\r\n\r\n"); } @@ -954,18 +1432,18 @@ TEST(HttpTransportCurlTest, ConcurrentMixedTransfers) { } for (int i = 0; i < 3; ++i) { - ASSERT_EQ(WaitHeaders(handles[i]), 200); + ASSERT_EQ(WaitHeaders(&demux, handles[i]), 200); std::string body; - ASSERT_TRUE(ReadAllBody(handles[i], &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(handles[i]), 200); + ASSERT_EQ(WaitHeaders(&demux, handles[i]), 200); std::string body; - ASSERT_TRUE(ReadAllBody(handles[i], &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); @@ -974,10 +1452,13 @@ TEST(HttpTransportCurlTest, ConcurrentMixedTransfers) { } TEST(HttpTransportCurlTest, EarlyServerResponseUnblocksLargeUpload) { - // Server sends an immediate 413 response with Content-Length: 0 and closes - // as soon as request headers arrive, without reading the >256 KiB upload - // body. Verifies MarkResponseComplete() wakes the blocked request-body writer - // instead of hanging forever. + BlockingEventDemux demux; + demux.DrainStale(); + + // Server sends an immediate 413 response with Content-Length: 0 as soon as + // request headers arrive, then performs an RFC 9112 section 9.6 lingering + // close (shutdown write + drain until peer closes) so the client reliably + // receives the 413 rather than racing a BSD TCP RST from unread upload bytes. EnsureSocketSubsystemInitialized(); SocketFd listen_fd = socket(AF_INET, SOCK_STREAM, 0); ASSERT_NE(listen_fd, kInvalidSocket); @@ -1033,6 +1514,8 @@ TEST(HttpTransportCurlTest, EarlyServerResponseUnblocksLargeUpload) { "Content-Length: 0\r\n" "Connection: close\r\n" "\r\n"); + ShutdownWrite(c); + (void)WaitForPeerClose(c, 1000); CloseSocket(c); } CloseSocket(listen_fd); @@ -1048,15 +1531,14 @@ TEST(HttpTransportCurlTest, EarlyServerResponseUnblocksLargeUpload) { std::vector payload(kLargeUpload, 0x42); auto t0 = std::chrono::steady_clock::now(); - // WriteAllBody should terminate promptly (returning false once 413 completes) - // rather than blocking until its 5s timeout. - bool finished_upload = WriteAllBody(h, payload.data(), payload.size(), 5000); + bool finished_upload = + WriteAllBody(&demux, h, payload.data(), payload.size(), 5000); auto elapsed_ms = std::chrono::duration_cast( std::chrono::steady_clock::now() - t0) .count(); EXPECT_FALSE(finished_upload); EXPECT_LT(elapsed_ms, 3000); - EXPECT_EQ(WaitHeaders(h, 2000), 413); + EXPECT_EQ(WaitHeaders(&demux, h, 2000), 413); HttpDestroyRequestInternal(h); raw_server.join(); From 831910b0eb3530e49289b3752e8af9b768191d48 Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 30 Nov 2026 18:41:42 +0000 Subject: [PATCH 07/16] [App][HTTP] Return redirects to the caller, narrow error classes, and signal a closed request body - Backends no longer follow redirects; a 3xx is delivered as an ordinary response. Remove the URL parser, origin and credential helpers, and the manual redirect re-issue in the curl backend. - HttpTryWriteRequestBodyInternal returns -2 when the transport stopped consuming the body (early response or completed response) instead of -1, so a valid early 4xx is not turned into a failure by the caller. - Error classes: Certificate (peer or host name verification) is separate from Connect (handshake and connection failures); add InvalidRequest for failures detected before any network I/O. Validate the request method. - Pass the proxy URL to libcurl unchanged; refuse userinfo in request URLs. - Tests: early 413 x50, 3xx delivery, invalid requests, proxy pass-through, handshake error classes, and a backpressure test that fails when the receive pause is removed. --- app/http/http_bridge.h | 22 +- app/http/http_transport.h | 139 ++- app/http/http_transport_common.cc | 291 +----- app/http/http_transport_curl.cc | 245 ++--- app/http/tests/http_transport_common_test.cc | 284 +++--- app/http/tests/http_transport_curl_test.cc | 964 +++++++++++-------- 6 files changed, 868 insertions(+), 1077 deletions(-) diff --git a/app/http/http_bridge.h b/app/http/http_bridge.h index f93e3915c9..ded600e472 100644 --- a/app/http/http_bridge.h +++ b/app/http/http_bridge.h @@ -44,12 +44,19 @@ int64_t HttpCreateRequestInternal(const char* method, const char* url, void HttpStartRequestInternal(int64_t handle); // Non-blocking write of up to `length` request body bytes into the bounded -// upload pipe. Returns bytes accepted (`0` when full), or `-1` on failure, -// invalid arguments, early server response, or cancellation. +// 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`. +// 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 @@ -74,10 +81,13 @@ std::string HttpGetErrorInternal(int64_t handle); // Returns the structured error class for `handle`: // 0 = None // 1 = Canceled -// 2 = Connect (DNS, refused, reset, unreachable, I/O abort) -// 3 = TLS (certificate verification, handshake, SSL policy failure) +// 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 (invalid request/arguments, redirect policy, protocol, unknown) +// 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. diff --git a/app/http/http_transport.h b/app/http/http_transport.h index 901ed648c8..1ac55a48ca 100644 --- a/app/http/http_transport.h +++ b/app/http/http_transport.h @@ -14,39 +14,36 @@ * limitations under the License. */ -// Cross-platform streaming HTTP transport backed by platform-native stacks: -// - Desktop (Linux / macOS / Windows): libcurl multi-handle (sharing -// `firebase_rest_lib`'s TLS policy and ref-counted curl initialization). -// - Apple mobile (iOS / tvOS): ARC NSURLSession with bound-stream uploads. -// - Android: JNI HttpURLConnection on a bounded worker thread pool. +// 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. // -// Streaming and platform behavioral guarantees: -// - Bounded backpressure in both directions (`kMaxRequestBufferBytes` upload -// pipe, `kMaxResponseBufferBytes` download buffer) and immediate -// incremental delivery for Server-Sent Events (SSE) on all three backends. -// - Desktop (libcurl) and Apple (NSURLSession) stream request uploads and -// response downloads concurrently (full-duplex). Android's -// `HttpURLConnection` is half-duplex (streams the request body before -// reading response headers), and on upload write failure it still reads and -// delivers an early HTTP 4xx/5xx response when the server sent one. -// - Uniform redirect and credential policy across all three backends: -// up to `kMaxRedirects`, RFC 3986 relative resolution (percent-encoding -// spaces in path/query/fragment), rejection of non-HTTP(S) targets, -// URL userinfo, and `https` -> `http` downgrades, 301/302/303 method -// rewrite to `GET` (keeping `GET` and `HEAD`), rejection of non-replayable -// streamed request bodies across 307/308, and cross-origin stripping of -// `Authorization`, `Proxy-Authorization`, `Cookie`, `X-Firebase-AppCheck`, -// `x-goog-api-key`, and `Host`. -// - Connect timeout: Desktop (libcurl) and Android (`HttpURLConnection`) -// enforce a 60-second connect timeout. Apple (`NSURLSession`) does not -// expose a connect-only timeout separate from idle read timeout, so it -// relies on the OS TCP connect timeout while keeping -// `timeoutIntervalForRequest` high so idle SSE streams are not terminated. -// - Response headers and reason phrases: Desktop and Android return the -// server-sent reason phrase and preserve duplicate response headers as -// separate entries. Apple's `NSHTTPURLResponse` does not expose raw -// HTTP/1.1 reason phrases or unmerged header lists, so Apple returns -// canonical RFC 9110 English reason phrases (falling back to +// 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 returns canonical +// RFC 9110 English reason phrases (falling back to // `localizedStringForStatusCode:`) and coalesces duplicate response headers // per `NSHTTPURLResponse.allHeaderFields`. @@ -61,7 +58,6 @@ #include #include #include -#include #include #include #include @@ -90,10 +86,16 @@ enum HttpEventKind : int32_t { 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, - kHttpErrorTls = 3, + // 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 @@ -103,9 +105,6 @@ inline constexpr size_t kLowWaterRequestBytes = 128 * 1024; inline constexpr size_t kMaxResponseBufferBytes = 2 * 1024 * 1024; inline constexpr size_t kLowWaterResponseBytes = 1 * 1024 * 1024; -// Maximum number of HTTP redirects followed per operation across all backends. -inline constexpr int kMaxRedirects = 10; - // 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. @@ -115,6 +114,11 @@ inline constexpr int64_t kChunkedRequestContent = -1; 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; @@ -122,7 +126,7 @@ struct ByteChunk { size_t remaining() const { return data.size() - offset; } }; -// Request parameters used when creating an `HttpOperation` from C++ directly. +// Request parameters for `CreateOperation`. struct HttpRequestOptions { std::string method = "GET"; std::string url; @@ -186,9 +190,11 @@ struct HttpOperation { std::vector> headers); // Called by the platform backend when it stops consuming request body bytes - // (for example on an early 4xx response or a 301-303 redirect to GET) so a - // caller blocked in `HttpTryWriteRequestBodyInternal` wakes promptly without - // failing the response. + // 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. @@ -210,8 +216,10 @@ struct HttpOperation { size_t PopRequestBytes(uint8_t* dest, size_t max_bytes, bool* out_eof); }; -// C++17 registry entry points backing both direct C++ callers and the flat -// SWIG bridge in `http_bridge.h`. +// 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); @@ -240,6 +248,9 @@ 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); @@ -247,47 +258,17 @@ bool IsValidHeaderName(std::string_view name); // control characters). bool IsValidHeaderValue(std::string_view value); -// Parses `Name\tValue\n` (or `Name: Value\n`) header lines into ordered pairs, -// preserving duplicate header names. Returns false if any line contains CR, -// LF, NUL, an invalid header token name, or an invalid header 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); -// Convenience wrapper returning parsed headers, or an empty vector if invalid. -std::vector> ParsePackedHeaders( - std::string_view packed); - -struct UrlOrigin { - std::string scheme; - std::string host; - int port = 0; -}; - -// Parses scheme (`http` or `https` only), lowercased host, and effective port -// (`80` / `443` when omitted) from an absolute HTTP(S) URL. Rejects URLs whose -// authority contains userinfo (`@`), backslashes, whitespace, or controls. -std::optional ParseUrlOrigin(std::string_view url); - +// 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); -bool IsHttpsUrl(std::string_view url); -bool IsSameOrigin(std::string_view url_a, std::string_view url_b); - -// Returns true for headers that must never be forwarded across a cross-origin -// redirect (`Authorization`, `Proxy-Authorization`, `Cookie`, -// `X-Firebase-AppCheck`, `x-goog-api-key`). -bool IsSensitiveRedirectHeader(std::string_view header_name); - -// Resolves an HTTP `Location` header against `current_url`, rejecting -// non-HTTP(S) schemes, userinfo, and `https` -> `http` scheme downgrades, and -// percent-encoding ASCII spaces in the path/query/fragment so all backends -// behave identically. -std::optional ResolveRedirectUrl(std::string_view current_url, - std::string_view location); - -// Parses `[http[s]://]host[:port][/...]` into `(host, port)` for proxy setup. -std::optional> ParseProxyHostPort( - std::string_view proxy_url); } // namespace http } // namespace firebase diff --git a/app/http/http_transport_common.cc b/app/http/http_transport_common.cc index c89c4da7df..3d1d4f885b 100644 --- a/app/http/http_transport_common.cc +++ b/app/http/http_transport_common.cc @@ -16,7 +16,6 @@ #include #include -#include #include #include #include @@ -59,15 +58,6 @@ bool HasControlOrWhitespace(std::string_view s) { return false; } -bool HasControlChars(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) { @@ -174,6 +164,11 @@ bool IsValidHeaderName(std::string_view name) { 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' || @@ -214,9 +209,6 @@ bool TryParsePackedHeaders( return false; } size_t sep = line.find('\t'); - if (sep == std::string_view::npos) { - sep = line.find(':'); - } if (sep == std::string_view::npos || sep == 0) { out->clear(); return false; @@ -232,15 +224,6 @@ bool TryParsePackedHeaders( return true; } -std::vector> ParsePackedHeaders( - std::string_view packed) { - std::vector> result; - if (!TryParsePackedHeaders(packed, &result)) { - result.clear(); - } - return result; -} - bool AsciiEqualsIgnoreCase(std::string_view a, std::string_view b) { if (a.size() != b.size()) { return false; @@ -266,243 +249,15 @@ std::string_view TrimAsciiWhitespace(std::string_view s) { return s; } -std::optional ParseUrlOrigin(std::string_view url) { - url = TrimAsciiWhitespace(url); - size_t scheme_end = url.find("://"); - if (scheme_end == std::string_view::npos || scheme_end == 0) { - return std::nullopt; - } - std::string_view raw_scheme = url.substr(0, scheme_end); - int default_port = 0; - std::string norm_scheme; - if (AsciiEqualsIgnoreCase(raw_scheme, "http")) { - norm_scheme = "http"; - default_port = 80; - } else if (AsciiEqualsIgnoreCase(raw_scheme, "https")) { - norm_scheme = "https"; - default_port = 443; - } else { - return std::nullopt; - } - - std::string_view rest = url.substr(scheme_end + 3); - size_t path_pos = rest.find_first_of("/?#"); - std::string_view authority = - path_pos == std::string_view::npos ? rest : rest.substr(0, path_pos); - // Reject userinfo (`@`, where parsers disagree on first vs. last `@`), - // backslashes (which WHATWG/OkHttp treat as path delimiters, enabling - // `https://evil.com\@trusted.com` authority confusion), and control or - // whitespace characters inside authority. - if (authority.find('@') != std::string_view::npos || - authority.find('\\') != std::string_view::npos || - HasControlOrWhitespace(authority)) { - return std::nullopt; - } - if (authority.empty()) { - return std::nullopt; - } - - std::string_view host_sv; - std::string_view port_sv; - if (authority.front() == '[') { - size_t close = authority.find(']'); - if (close == std::string_view::npos || close <= 1) { - return std::nullopt; - } - host_sv = authority.substr(0, close + 1); - if (close + 1 < authority.size()) { - if (authority[close + 1] != ':') { - return std::nullopt; - } - port_sv = authority.substr(close + 2); - } - } else { - size_t colon = authority.rfind(':'); - if (colon != std::string_view::npos) { - host_sv = authority.substr(0, colon); - port_sv = authority.substr(colon + 1); - } else { - host_sv = authority; - } - if (host_sv.find_first_of(":[]") != std::string_view::npos) { - return std::nullopt; - } - } - if (host_sv.empty()) { - return std::nullopt; - } - - int port = default_port; - if (!port_sv.empty()) { - int parsed = 0; - auto [ptr, ec] = std::from_chars(port_sv.data(), - port_sv.data() + port_sv.size(), parsed); - if (ec != std::errc() || ptr != port_sv.data() + port_sv.size() || - parsed <= 0 || parsed > 65535) { - return std::nullopt; - } - port = parsed; - } - - std::string norm_host(host_sv.size(), '\0'); - for (size_t i = 0; i < host_sv.size(); ++i) { - norm_host[i] = - static_cast(std::tolower(static_cast(host_sv[i]))); - } - - UrlOrigin out; - out.scheme = std::move(norm_scheme); - out.host = std::move(norm_host); - out.port = port; - return out; -} - bool IsHttpOrHttpsUrl(std::string_view url) { - return ParseUrlOrigin(url).has_value(); -} - -bool IsHttpsUrl(std::string_view url) { - auto origin = ParseUrlOrigin(url); - return origin.has_value() && origin->scheme == "https"; -} - -bool IsSameOrigin(std::string_view url_a, std::string_view url_b) { - auto a = ParseUrlOrigin(url_a); - auto b = ParseUrlOrigin(url_b); - if (!a || !b) { - return false; - } - return a->scheme == b->scheme && a->host == b->host && a->port == b->port; -} - -bool IsSensitiveRedirectHeader(std::string_view header_name) { - return AsciiEqualsIgnoreCase(header_name, "Authorization") || - AsciiEqualsIgnoreCase(header_name, "Proxy-Authorization") || - AsciiEqualsIgnoreCase(header_name, "Cookie") || - AsciiEqualsIgnoreCase(header_name, "X-Firebase-AppCheck") || - AsciiEqualsIgnoreCase(header_name, "x-goog-api-key"); -} - -std::optional ResolveRedirectUrl(std::string_view current_url, - std::string_view location) { - current_url = TrimAsciiWhitespace(current_url); - location = TrimAsciiWhitespace(location); - if (location.empty() || HasControlChars(location)) { - return std::nullopt; - } - // Reject leading backslashes or `/\` prefixes to prevent WHATWG/OkHttp - // scheme-relative authority confusion (`\/evil.com`, `/\evil.com`). - if (location.front() == '\\' || - (location.size() >= 2 && location[0] == '/' && location[1] == '\\')) { - return std::nullopt; - } - auto base_origin = ParseUrlOrigin(current_url); - if (!base_origin) { - return std::nullopt; - } - - // Detect an RFC 3986 leading URI scheme (`:` occurring before `/`, `\`, `?`, - // or `#`) so relative URLs containing `://` in query/fragment stay relative - // while non-HTTP(S) schemes like `data:`, `file:/...`, or `mailto:` are - // passed to `ParseUrlOrigin` and rejected. - size_t first_delim = location.find_first_of(":/\\?#"); - if (first_delim == 0 && location[0] == ':') { - return std::nullopt; - } - bool has_scheme_prefix = first_delim != std::string_view::npos && - first_delim > 0 && location[first_delim] == ':'; - - std::string candidate; - if (has_scheme_prefix) { - candidate.assign(location.data(), location.size()); - } else if (location.size() >= 2 && location[0] == '/' && location[1] == '/') { - candidate = base_origin->scheme + ":" + std::string(location); - } else { - size_t scheme_end = current_url.find("://"); - size_t auth_start = scheme_end + 3; - size_t path_pos = current_url.find_first_of("/?#", auth_start); - std::string_view origin_prefix = path_pos == std::string_view::npos - ? current_url - : current_url.substr(0, path_pos); - std::string_view base_path = "/"; - if (path_pos != std::string_view::npos && current_url[path_pos] == '/') { - size_t q_pos = current_url.find_first_of("?#", path_pos); - base_path = q_pos == std::string_view::npos - ? current_url.substr(path_pos) - : current_url.substr(path_pos, q_pos - path_pos); + 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); } - - if (location.front() == '/') { - candidate = std::string(origin_prefix) + std::string(location); - } else if (location.front() == '?') { - candidate = std::string(origin_prefix) + std::string(base_path) + - std::string(location); - } else if (location.front() == '#') { - size_t frag_pos = current_url.find('#'); - std::string_view without_frag = frag_pos == std::string_view::npos - ? current_url - : current_url.substr(0, frag_pos); - candidate = std::string(without_frag) + std::string(location); - } else { - size_t last_slash = base_path.rfind('/'); - std::string_view dir = last_slash == std::string_view::npos - ? std::string_view("/") - : base_path.substr(0, last_slash + 1); - candidate = - std::string(origin_prefix) + std::string(dir) + std::string(location); - } - } - - auto next_origin = ParseUrlOrigin(candidate); - if (!next_origin) { - return std::nullopt; - } - if (base_origin->scheme == "https" && next_origin->scheme != "https") { - return std::nullopt; } - - // Percent-encode ASCII spaces in the path/query/fragment so libcurl - // (`CURLOPT_URL`), NSURL, and java.net.URL all handle redirect targets - // containing spaces identically (spaces in the authority were already - // rejected by `ParseUrlOrigin` above). - if (candidate.find(' ') != std::string::npos) { - std::string encoded; - encoded.reserve(candidate.size() + 8); - for (char ch : candidate) { - if (ch == ' ') { - encoded.append("%20"); - } else { - encoded.push_back(ch); - } - } - candidate = std::move(encoded); - } - return candidate; -} - -std::optional> ParseProxyHostPort( - std::string_view proxy_url) { - proxy_url = TrimAsciiWhitespace(proxy_url); - if (proxy_url.empty()) { - return std::nullopt; - } - std::string normalized; - if (proxy_url.find("://") == std::string_view::npos) { - normalized = "http://" + std::string(proxy_url); - proxy_url = normalized; - } - auto origin = ParseUrlOrigin(proxy_url); - if (!origin) { - return std::nullopt; - } - std::string host = origin->host; - if (host.size() >= 2 && host.front() == '[' && host.back() == ']') { - host = host.substr(1, host.size() - 2); - } - if (host.empty()) { - return std::nullopt; - } - return std::make_pair(std::move(host), origin->port); + return false; } void PostCompletionEvent(int64_t handle, HttpEventKind kind) { @@ -530,7 +285,9 @@ int64_t CreateOperation(HttpRequestOptions options) { } std::string validation_error; - if (op->content_length < kNoRequestContent) { + 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) { @@ -550,7 +307,7 @@ int64_t CreateOperation(HttpRequestOptions options) { reg.operations.emplace(id, op); } if (!validation_error.empty()) { - op->MarkFailed(validation_error, kHttpErrorOther); + op->MarkFailed(validation_error, kHttpErrorInvalidRequest); } return id; } @@ -811,7 +568,8 @@ int64_t HttpCreateRequestInternal(const char* method, const char* url, int64_t handle = http::CreateOperation(std::move(options)); if (invalid_headers) { if (auto op = http::FindOperation(handle)) { - op->MarkFailed("Invalid HTTP request header.", http::kHttpErrorOther); + op->MarkFailed("Invalid HTTP request header.", + http::kHttpErrorInvalidRequest); } } return handle; @@ -830,10 +588,12 @@ int32_t HttpTryWriteRequestBodyInternal(int64_t handle, void* data, } if (length == 0) { std::lock_guard lock(op->mutex); - if (op->failed || op->resp_eof || op->req_write_closed || - op->IsCanceled()) { + if (op->failed || op->IsCanceled()) { return -1; } + if (op->req_write_closed || op->resp_eof) { + return http::kHttpWriteClosed; + } return 0; } @@ -841,10 +601,12 @@ int32_t HttpTryWriteRequestBodyInternal(int64_t handle, void* data, int32_t to_write = 0; { std::lock_guard lock(op->mutex); - if (op->failed || op->resp_eof || op->req_write_closed || - op->IsCanceled()) { + 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 @@ -880,6 +642,9 @@ void HttpFinishRequestBodyInternal(int64_t handle) { 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; } diff --git a/app/http/http_transport_curl.cc b/app/http/http_transport_curl.cc index 1d4f156b79..a0f3de97e3 100644 --- a/app/http/http_transport_curl.cc +++ b/app/http/http_transport_curl.cc @@ -50,22 +50,6 @@ bool HasHeaderIgnoreCase( return false; } -std::string_view FindHeaderValueIgnoreCase( - const std::vector>& headers, - std::string_view target) { - for (const auto& kv : headers) { - if (AsciiEqualsIgnoreCase(kv.first, target)) { - return kv.second; - } - } - return {}; -} - -bool IsRedirectStatus(int32_t status) { - return status == 301 || status == 302 || status == 303 || status == 307 || - status == 308; -} - bool AppendSList(::firebase::rest::curl::UniqueSList* list, const char* line) { curl_slist* next = curl_slist_append(list->get(), line); if (next == nullptr) { @@ -83,22 +67,18 @@ HttpErrorClass ClassifyCurlError(CURLcode code, bool canceled) { switch (code) { case CURLE_OPERATION_TIMEDOUT: return kHttpErrorTimeout; - case CURLE_SSL_CONNECT_ERROR: + // 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_ENGINE_NOTFOUND: - case CURLE_SSL_ENGINE_SETFAILED: - case CURLE_SSL_CERTPROBLEM: - case CURLE_SSL_CIPHER: case CURLE_SSL_CACERT_BADFILE: - case CURLE_SSL_SHUTDOWN_FAILED: case CURLE_SSL_CRL_BADFILE: case CURLE_SSL_ISSUER_ERROR: case CURLE_SSL_PINNEDPUBKEYNOTMATCH: case CURLE_SSL_INVALIDCERTSTATUS: - case CURLE_USE_SSL_FAILED: - case CURLE_SSL_ENGINE_INITFAILED: + case CURLE_SSL_CERTPROBLEM: case CURLE_SSL_CLIENTCERT: - return kHttpErrorTls; + 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: @@ -107,7 +87,19 @@ HttpErrorClass ClassifyCurlError(CURLcode code, bool canceled) { 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; } @@ -121,17 +113,8 @@ struct CurlTransfer { bool upload_paused = false; bool download_paused = false; bool headers_committed = false; - - std::string current_url; - std::string active_method; - std::vector> active_headers; - int64_t active_content_length = kNoRequestContent; - int redirect_count = 0; - - std::string redirect_url; - int32_t redirect_status = 0; - size_t redirect_body_drained = 0; - std::string redirect_blocked_error; + // True while the request body pipe still feeds this transfer. + bool request_body_open = false; int32_t staged_status = 0; std::string staged_reason; @@ -154,11 +137,6 @@ size_t OnCurlHeader(char* buffer, size_t size, size_t nitems, void* userdata) { if (transfer == nullptr || transfer->op->IsCanceled()) { return 0; } - if (!transfer->redirect_url.empty()) { - // Ignore any trailing headers (e.g. chunked trailers) on a 3xx redirect - // response whose Location has already been captured. - return total; - } std::string_view line(buffer, total); while (!line.empty() && (line.back() == '\r' || line.back() == '\n')) { @@ -167,29 +145,14 @@ size_t OnCurlHeader(char* buffer, size_t size, size_t nitems, void* userdata) { if (line.empty()) { if (transfer->staged_status >= 200) { - std::string_view location = - FindHeaderValueIgnoreCase(transfer->staged_headers, "Location"); - if (IsRedirectStatus(transfer->staged_status) && !location.empty()) { - auto resolved = ResolveRedirectUrl(transfer->current_url, location); - if (!resolved || - (IsHttpsUrl(transfer->op->url) && !IsHttpsUrl(*resolved))) { - transfer->redirect_blocked_error = - "Blocked unsafe or scheme-downgraded HTTP redirect."; - return 0; - } - // Route all HTTP redirects manually through HandleRedirect so - // 301/302/303 -> GET rewrites (clearing CURLOPT_UPLOAD and - // CURLOPT_CUSTOMREQUEST), kMaxRedirects, and cross-origin sensitive - // header stripping match Android and Apple identically. - transfer->redirect_url = std::move(*resolved); - transfer->redirect_status = transfer->staged_status; - if (transfer->active_content_length != kNoRequestContent && - transfer->active_content_length != 0) { - return 0; - } - return total; - } 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; } @@ -237,16 +200,6 @@ size_t OnCurlWrite(char* ptr, size_t size, size_t nmemb, void* userdata) { if (transfer == nullptr || transfer->op->IsCanceled()) { return 0; } - if (!transfer->redirect_url.empty()) { - // Drain small 3xx bodies so keep-alive connections remain pooled in - // multi_, capping at 64 KiB so oversized redirect bodies abort promptly. - constexpr size_t kMaxRedirectBodyDrainBytes = 64 * 1024; - transfer->redirect_body_drained += total; - if (transfer->redirect_body_drained > kMaxRedirectBodyDrainBytes) { - return 0; - } - return total; - } transfer->CommitStagedHeadersIfNeeded(); if (total == 0) { return 0; @@ -273,6 +226,13 @@ size_t OnCurlRead(char* buffer, size_t size, size_t nitems, void* userdata) { 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), @@ -363,27 +323,20 @@ class CurlHttpEngine { } std::unique_ptr BuildTransfer( - const std::shared_ptr& op, std::string target_url, - std::string method, - std::vector> request_headers, - int64_t content_length, int redirect_count) { - if (!IsHttpOrHttpsUrl(target_url)) { + const std::shared_ptr& op) { + if (!IsHttpOrHttpsUrl(op->url)) { op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", - kHttpErrorOther); - return nullptr; - } - - if (!op->proxy_url.empty() && !ParseProxyHostPort(op->proxy_url)) { - op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorOther); + kHttpErrorInvalidRequest); return nullptr; } - bool is_get = AsciiEqualsIgnoreCase(method, "GET"); - bool is_head = AsciiEqualsIgnoreCase(method, "HEAD"); + 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.", - kHttpErrorOther); + kHttpErrorInvalidRequest); return nullptr; } @@ -396,17 +349,12 @@ class CurlHttpEngine { CURLcode tls_rc = ::firebase::rest::curl::ApplyTlsPolicy(easy.get()); if (tls_rc != CURLE_OK) { - op->MarkFailed(curl_easy_strerror(tls_rc), kHttpErrorTls); + op->MarkFailed(curl_easy_strerror(tls_rc), kHttpErrorCertificate); return nullptr; } auto transfer = std::make_unique(); transfer->op = op; - transfer->current_url = std::move(target_url); - transfer->active_method = std::move(method); - transfer->active_headers = std::move(request_headers); - transfer->active_content_length = content_length; - transfer->redirect_count = redirect_count; transfer->error_buf[0] = '\0'; CURL* raw_easy = easy.get(); @@ -415,9 +363,9 @@ class CurlHttpEngine { ApplyOpt(raw_easy, CURLOPT_NOSIGNAL, 1L, &opt_err); ApplyOpt(raw_easy, CURLOPT_PROTOCOLS_STR, "http,https", &opt_err); ApplyOpt(raw_easy, CURLOPT_UNRESTRICTED_AUTH, 0L, &opt_err); - // Redirects are followed manually via HandleRedirect so method rewrites, - // redirect limits, HTTPS downgrade blocking, and cross-origin header - // stripping stay consistent with Android and Apple. + // Never turn `user:password@` in a URL into Basic credentials. + ApplyOpt(raw_easy, CURLOPT_DISALLOW_USERNAME_IN_URL, 1L, &opt_err); + // Redirects are not followed: a 3xx is delivered as an ordinary response. ApplyOpt(raw_easy, CURLOPT_FOLLOWLOCATION, 0L, &opt_err); ApplyOpt(raw_easy, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L, &opt_err); ApplyOpt(raw_easy, CURLOPT_TCP_NODELAY, 1L, &opt_err); @@ -426,7 +374,7 @@ class CurlHttpEngine { ApplyOpt(raw_easy, CURLOPT_CONNECTTIMEOUT_MS, 60000L, &opt_err); ApplyOpt(raw_easy, CURLOPT_TIMEOUT_MS, 0L, &opt_err); - ApplyOpt(raw_easy, CURLOPT_URL, transfer->current_url.c_str(), &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); @@ -437,14 +385,14 @@ class CurlHttpEngine { ApplyOpt(raw_easy, CURLOPT_PROXY, op->proxy_url.c_str(), &opt_err); } - bool has_expect = HasHeaderIgnoreCase(transfer->active_headers, "Expect"); + bool has_expect = HasHeaderIgnoreCase(op->request_headers, "Expect"); bool has_transfer_encoding = - HasHeaderIgnoreCase(transfer->active_headers, "Transfer-Encoding"); + HasHeaderIgnoreCase(op->request_headers, "Transfer-Encoding"); bool has_content_length = - HasHeaderIgnoreCase(transfer->active_headers, "Content-Length"); + HasHeaderIgnoreCase(op->request_headers, "Content-Length"); ::firebase::rest::curl::UniqueSList header_list; - for (const auto& kv : transfer->active_headers) { + for (const auto& kv : op->request_headers) { std::string line; line.reserve(kv.first.size() + kv.second.size() + 2); line.append(kv.first); @@ -473,12 +421,11 @@ class CurlHttpEngine { } else if (is_get) { ApplyOpt(raw_easy, CURLOPT_HTTPGET, 1L, &opt_err); } else { - ApplyOpt(raw_easy, CURLOPT_CUSTOMREQUEST, - transfer->active_method.c_str(), &opt_err); + ApplyOpt(raw_easy, CURLOPT_CUSTOMREQUEST, op->method.c_str(), &opt_err); if (!has_content_length && - (AsciiEqualsIgnoreCase(transfer->active_method, "POST") || - AsciiEqualsIgnoreCase(transfer->active_method, "PUT") || - AsciiEqualsIgnoreCase(transfer->active_method, "PATCH"))) { + (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); @@ -487,9 +434,9 @@ class CurlHttpEngine { } } } else { + transfer->request_body_open = true; ApplyOpt(raw_easy, CURLOPT_UPLOAD, 1L, &opt_err); - ApplyOpt(raw_easy, CURLOPT_CUSTOMREQUEST, transfer->active_method.c_str(), - &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) { @@ -571,9 +518,7 @@ class CurlHttpEngine { kHttpErrorOther); continue; } - auto transfer = - BuildTransfer(op, op->url, op->method, op->request_headers, - op->content_length, 0); + auto transfer = BuildTransfer(op); if (!transfer) { continue; } @@ -619,7 +564,6 @@ class CurlHttpEngine { continue; } - bool added_redirect = false; int msgs_left = 0; while (CURLMsg* msg = curl_multi_info_read(multi_.get(), &msgs_left)) { if (msg->msg != CURLMSG_DONE) { @@ -649,14 +593,7 @@ class CurlHttpEngine { } if (!owned_transfer->op->IsCanceled()) { - if (!owned_transfer->redirect_blocked_error.empty()) { - owned_transfer->op->MarkFailed( - owned_transfer->redirect_blocked_error, kHttpErrorOther); - } else if (!owned_transfer->redirect_url.empty()) { - if (HandleRedirect(std::move(owned_transfer))) { - added_redirect = true; - } - } else if (result == CURLE_OK) { + if (result == CURLE_OK) { if (!owned_transfer->headers_committed) { long code = 0; // NOLINT curl_easy_getinfo(owned_transfer->easy.get(), @@ -677,13 +614,6 @@ class CurlHttpEngine { } } - if (added_redirect) { - // Drive newly added redirect handles immediately with - // curl_multi_perform rather than sleeping up to 1000 ms in - // curl_multi_poll first. - continue; - } - if (!active_.empty()) { int numfds = 0; CURLMcode poll_rc = @@ -695,67 +625,6 @@ class CurlHttpEngine { } } - bool HandleRedirect(std::unique_ptr prev) { - if (!prev) { - return false; - } - auto op = prev->op; - if (prev->redirect_count >= kMaxRedirects) { - op->MarkFailed("Maximum HTTP redirects exceeded.", kHttpErrorOther); - return false; - } - - int32_t status = prev->redirect_status; - std::string next_method = prev->active_method; - int64_t next_content_len = prev->active_content_length; - if ((status == 301 || status == 302 || status == 303) && - !AsciiEqualsIgnoreCase(next_method, "GET") && - !AsciiEqualsIgnoreCase(next_method, "HEAD")) { - next_method = "GET"; - next_content_len = kNoRequestContent; - op->MarkRequestWriteClosed(); - } else if (status == 303 && AsciiEqualsIgnoreCase(next_method, "HEAD")) { - next_content_len = kNoRequestContent; - } else if (next_content_len != kNoRequestContent && next_content_len != 0) { - op->MarkFailed("Cannot replay streamed request body across redirect.", - kHttpErrorOther); - return false; - } - - bool same_origin = IsSameOrigin(op->url, prev->redirect_url) && - IsSameOrigin(prev->current_url, prev->redirect_url); - std::vector> filtered; - filtered.reserve(prev->active_headers.size()); - for (const auto& kv : prev->active_headers) { - if (!same_origin && (IsSensitiveRedirectHeader(kv.first) || - AsciiEqualsIgnoreCase(kv.first, "Host"))) { - continue; - } - if (next_content_len == kNoRequestContent && - (AsciiEqualsIgnoreCase(kv.first, "Content-Type") || - AsciiEqualsIgnoreCase(kv.first, "Content-Length") || - AsciiEqualsIgnoreCase(kv.first, "Transfer-Encoding"))) { - continue; - } - filtered.push_back(kv); - } - - auto next_transfer = BuildTransfer( - op, std::move(prev->redirect_url), std::move(next_method), - std::move(filtered), next_content_len, prev->redirect_count + 1); - if (!next_transfer) { - return false; - } - CURLMcode mc = - curl_multi_add_handle(multi_.get(), next_transfer->easy.get()); - if (mc != CURLM_OK) { - op->MarkFailed(curl_multi_strerror(mc), kHttpErrorOther); - return false; - } - active_.emplace(op->id, std::move(next_transfer)); - return true; - } - ::firebase::rest::curl::UniqueMulti multi_; std::mutex mutex_; std::condition_variable cv_; diff --git a/app/http/tests/http_transport_common_test.cc b/app/http/tests/http_transport_common_test.cc index c3ba45eebf..b0dd596386 100644 --- a/app/http/tests/http_transport_common_test.cc +++ b/app/http/tests/http_transport_common_test.cc @@ -31,146 +31,45 @@ namespace firebase { namespace http { namespace { -TEST(HttpTransportCommonTest, ParseUrlOriginStandardAndDefaults) { - auto https = ParseUrlOrigin("HTTPS://FireBaseStorage.GoogleAPIs.com/v0/b/x"); - ASSERT_TRUE(https.has_value()); - EXPECT_EQ(https->scheme, "https"); - EXPECT_EQ(https->host, "firebasestorage.googleapis.com"); - EXPECT_EQ(https->port, 443); - - auto http = ParseUrlOrigin("http://localhost/foo?bar=1"); - ASSERT_TRUE(http.has_value()); - EXPECT_EQ(http->scheme, "http"); - EXPECT_EQ(http->host, "localhost"); - EXPECT_EQ(http->port, 80); - - auto explicit_port = ParseUrlOrigin("http://127.0.0.1:5001/proj/us/fn"); - ASSERT_TRUE(explicit_port.has_value()); - EXPECT_EQ(explicit_port->scheme, "http"); - EXPECT_EQ(explicit_port->host, "127.0.0.1"); - EXPECT_EQ(explicit_port->port, 5001); - - auto ipv6 = ParseUrlOrigin("https://[::1]:8443/path"); - ASSERT_TRUE(ipv6.has_value()); - EXPECT_EQ(ipv6->host, "[::1]"); - EXPECT_EQ(ipv6->port, 8443); -} - -TEST(HttpTransportCommonTest, ParseUrlOriginRejectsUnsafeInputs) { - EXPECT_FALSE(ParseUrlOrigin("").has_value()); - EXPECT_FALSE(ParseUrlOrigin("file:///etc/passwd").has_value()); - EXPECT_FALSE(ParseUrlOrigin("ftp://example.com/a").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://evil.com\\@trusted.com/p").has_value()); - // Userinfo must be rejected (S1) because parsers disagree on multiple `@`. - EXPECT_FALSE(ParseUrlOrigin("https://user:pass@Example.COM/p").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://a@b@c.example.com/p").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://@example.com/p").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://bad host/p").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://example.com:0/p").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://example.com:70000/p").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://example.com:abc/p").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://[::1/p").has_value()); - EXPECT_FALSE(ParseUrlOrigin("https://[]/p").has_value()); -} - -TEST(HttpTransportCommonTest, IsSameOriginComparesNormalizedTuples) { +TEST(HttpTransportCommonTest, IsHttpOrHttpsUrlChecksSchemeOnly) { + EXPECT_TRUE(IsHttpOrHttpsUrl("http://localhost/foo?bar=1")); EXPECT_TRUE( - IsSameOrigin("https://Example.COM/a", "HTTPS://example.com:443/b")); - EXPECT_TRUE(IsSameOrigin("http://localhost/a", "http://localhost:80/b")); - EXPECT_FALSE(IsSameOrigin("https://example.com/a", "http://example.com/a")); + 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( - IsSameOrigin("http://127.0.0.1:8080/a", "http://127.0.0.1:8081/a")); - EXPECT_FALSE( - IsSameOrigin("https://a.example.com/", "https://b.example.com/")); - EXPECT_FALSE(IsSameOrigin("not-a-url", "https://example.com/")); -} - -TEST(HttpTransportCommonTest, SensitiveRedirectHeadersMatchCaseInsensitively) { - EXPECT_TRUE(IsSensitiveRedirectHeader("Authorization")); - EXPECT_TRUE(IsSensitiveRedirectHeader("authorization")); - EXPECT_TRUE(IsSensitiveRedirectHeader("Proxy-Authorization")); - EXPECT_TRUE(IsSensitiveRedirectHeader("Cookie")); - EXPECT_TRUE(IsSensitiveRedirectHeader("cookie")); - EXPECT_TRUE(IsSensitiveRedirectHeader("X-Firebase-AppCheck")); - EXPECT_TRUE(IsSensitiveRedirectHeader("x-firebase-appcheck")); - EXPECT_TRUE(IsSensitiveRedirectHeader("x-goog-api-key")); - EXPECT_TRUE(IsSensitiveRedirectHeader("X-Goog-Api-Key")); - EXPECT_FALSE(IsSensitiveRedirectHeader("Content-Type")); - EXPECT_FALSE(IsSensitiveRedirectHeader("X-Custom-Header")); -} - -TEST(HttpTransportCommonTest, ResolveRedirectUrlRfc3986Forms) { - const std::string base = - "https://storage.example.com/v0/b/my-bucket/o?a=1#frag"; - - EXPECT_EQ(ResolveRedirectUrl(base, "https://cdn.example.com/file"), - "https://cdn.example.com/file"); - EXPECT_EQ(ResolveRedirectUrl(base, "//cdn.example.com/file"), - "https://cdn.example.com/file"); - EXPECT_EQ(ResolveRedirectUrl(base, "/new/path?x=2"), - "https://storage.example.com/new/path?x=2"); - EXPECT_EQ(ResolveRedirectUrl(base, "?next=1"), - "https://storage.example.com/v0/b/my-bucket/o?next=1"); - EXPECT_EQ(ResolveRedirectUrl(base, "#other"), - "https://storage.example.com/v0/b/my-bucket/o?a=1#other"); - EXPECT_EQ(ResolveRedirectUrl(base, "sibling.bin"), - "https://storage.example.com/v0/b/my-bucket/sibling.bin"); - EXPECT_EQ(ResolveRedirectUrl(base, "next?redir=http://ignored.example/x"), - "https://storage.example.com/v0/b/my-bucket/next?redir=http://" - "ignored.example/x"); - // Spaces in path/query are percent-encoded (C3). - EXPECT_EQ(ResolveRedirectUrl(base, "/my folder/file name.txt?q=a b"), - "https://storage.example.com/my%20folder/file%20name.txt?q=a%20b"); + IsHttpOrHttpsUrl(std::string_view("http://example.com/a\0b", 22))); } -TEST(HttpTransportCommonTest, ResolveRedirectUrlBlocksDowngradesAndConfusion) { - const std::string https_base = "https://example.com/a/b"; - EXPECT_FALSE( - ResolveRedirectUrl(https_base, "http://example.com/a/b").has_value()); - EXPECT_FALSE( - ResolveRedirectUrl(https_base, "file:///etc/passwd").has_value()); - EXPECT_FALSE( - ResolveRedirectUrl(https_base, "data:text/plain,hi").has_value()); - EXPECT_FALSE( - ResolveRedirectUrl(https_base, "javascript:alert(1)").has_value()); - EXPECT_FALSE(ResolveRedirectUrl(https_base, "\\\\evil.com/x").has_value()); - EXPECT_FALSE(ResolveRedirectUrl(https_base, "/\\evil.com/x").has_value()); - EXPECT_FALSE(ResolveRedirectUrl(https_base, "/bad\r\nHeader: 1").has_value()); - EXPECT_FALSE( - ResolveRedirectUrl(https_base, "https://user:pass@example.com/x") - .has_value()); - EXPECT_FALSE( - ResolveRedirectUrl(https_base, "https://bad host/x").has_value()); - EXPECT_FALSE(ResolveRedirectUrl(https_base, "").has_value()); - EXPECT_FALSE(ResolveRedirectUrl(https_base, ":no-scheme").has_value()); - - // HTTP -> HTTP and HTTP -> HTTPS are both allowed. - EXPECT_EQ(ResolveRedirectUrl("http://127.0.0.1:8080/a", "/b"), - "http://127.0.0.1:8080/b"); - EXPECT_EQ( - ResolveRedirectUrl("http://127.0.0.1:8080/a", "https://example.com/b"), - "https://example.com/b"); -} - -TEST(HttpTransportCommonTest, ParseProxyHostPort) { - auto p1 = ParseProxyHostPort("http://127.0.0.1:8888"); - ASSERT_TRUE(p1.has_value()); - EXPECT_EQ(p1->first, "127.0.0.1"); - EXPECT_EQ(p1->second, 8888); - - auto p2 = ParseProxyHostPort("proxy.local:3128"); - ASSERT_TRUE(p2.has_value()); - EXPECT_EQ(p2->first, "proxy.local"); - EXPECT_EQ(p2->second, 3128); - - auto p3 = ParseProxyHostPort("http://[::1]:8080/"); - ASSERT_TRUE(p3.has_value()); - EXPECT_EQ(p3->first, "::1"); - EXPECT_EQ(p3->second, 8080); - - EXPECT_FALSE(ParseProxyHostPort("").has_value()); - EXPECT_FALSE(ParseProxyHostPort("socks5://127.0.0.1:1080").has_value()); - EXPECT_FALSE(ParseProxyHostPort("http://user:pass@proxy:8080").has_value()); +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) { @@ -179,7 +78,7 @@ TEST(HttpTransportCommonTest, ParsePackedHeadersPreservesDuplicates) { "Authorization\tBearer tok\n" "X-Multi\tfirst\r\n" "X-Multi\tsecond\n" - "Content-Type: application/json\n", + "Content-Type\tapplication/json\n", &headers)); ASSERT_EQ(headers.size(), 4u); EXPECT_EQ(headers[0], std::make_pair(std::string("Authorization"), @@ -190,6 +89,11 @@ TEST(HttpTransportCommonTest, ParsePackedHeadersPreservesDuplicates) { 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) { @@ -215,22 +119,39 @@ TEST(HttpTransportCommonTest, HeaderValidationRejectsCrLfNulAndBadTokens) { EXPECT_FALSE(TryParsePackedHeaders("Bad Name\tval\n", &out)); EXPECT_FALSE(TryParsePackedHeaders("X-Foo\tbar\nno-separator-line\n", &out)); - // Direct C++ CreateOperation also rejects CR/LF in header values. + // 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), kHttpErrorOther); + 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), kHttpErrorOther); + EXPECT_EQ(HttpGetErrorClassInternal(bad_len), kHttpErrorInvalidRequest); EXPECT_FALSE(HttpGetErrorInternal(bad_len).empty()); HttpDestroyRequestInternal(bad_len); @@ -264,8 +185,8 @@ TEST(HttpTransportCommonTest, ErrorClassAndCancelAllOperations) { auto op1 = FindOperation(h1); ASSERT_NE(op1, nullptr); - op1->MarkFailed("certificate verify failed", kHttpErrorTls); - EXPECT_EQ(HttpGetErrorClassInternal(h1), kHttpErrorTls); + op1->MarkFailed("certificate verify failed", kHttpErrorCertificate); + EXPECT_EQ(HttpGetErrorClassInternal(h1), kHttpErrorCertificate); HttpCancelRequestInternal(h2); EXPECT_EQ(HttpGetErrorClassInternal(h2), kHttpErrorCanceled); @@ -384,13 +305,86 @@ TEST(HttpTransportCommonTest, MarkResponseCompleteWakesBlockedUploader) { op->CommitResponseHeaders(413, "Payload Too Large", {}); op->MarkResponseComplete(); - // Completion queue must wake the armed uploader and subsequent writes fail - // immediately instead of blocking forever. + // 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(), 64), -1); + 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); } diff --git a/app/http/tests/http_transport_curl_test.cc b/app/http/tests/http_transport_curl_test.cc index b01e7af696..842ca26915 100644 --- a/app/http/tests/http_transport_curl_test.cc +++ b/app/http/tests/http_transport_curl_test.cc @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -44,6 +45,7 @@ using SocketFd = SOCKET; constexpr SocketFd kInvalidSocket = INVALID_SOCKET; #else #include +#include #include #include #include @@ -106,6 +108,74 @@ bool WaitForSocketReadable(SocketFd fd, int timeout_ms) { 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); @@ -158,6 +228,43 @@ 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; @@ -185,12 +292,17 @@ struct ParsedRequest { // Minimal in-process HTTP/1.1 loopback test server for deterministic HTTP & SSE // integration testing (supports chunked uploads, SSE trickle streams, idle -// stalls, redirects, and concurrent connections). +// 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; - explicit LoopbackHttpServer(Handler handler) : handler_(std::move(handler)) { + // 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); @@ -412,6 +524,10 @@ class LoopbackHttpServer { } void HandleClient(SocketFd fd) { + if (raw_handler_) { + raw_handler_(fd); + return; + } ParsedRequest req; if (!ReadHttpRequest(fd, &req)) { return; @@ -420,6 +536,7 @@ class LoopbackHttpServer { } Handler handler_; + RawHandler raw_handler_; std::atomic listen_fd_{kInvalidSocket}; int port_ = 0; std::atomic stopped_{false}; @@ -522,7 +639,14 @@ bool ReadAllBody(BlockingEventDemux* demux, int64_t handle, std::string* out, } } -bool WriteAllBody(BlockingEventDemux* demux, int64_t handle, +// 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); @@ -532,14 +656,14 @@ bool WriteAllBody(BlockingEventDemux* demux, int64_t handle, (std::min)(len - offset, static_cast(65536))); int32_t n = HttpTryWriteRequestBodyInternal( handle, const_cast(data + offset), to_send); - if (n < 0) return false; + if (n < 0) return n; if (n > 0) { offset += static_cast(n); continue; } auto now = std::chrono::steady_clock::now(); if (now >= deadline) { - return false; + return kWriteTimedOut; } int rem_ms = static_cast( std::chrono::duration_cast(deadline - now) @@ -547,9 +671,17 @@ bool WriteAllBody(BlockingEventDemux* demux, int64_t handle, if (!demux->WaitFor(handle, kHttpEventRequestSpaceAvailable, (std::max)(rem_ms, 1))) { ADD_FAILURE() << "Expected kHttpEventRequestSpaceAvailable event"; - return false; + 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; } @@ -892,303 +1024,156 @@ TEST(HttpTransportCurlTest, SseIdleCancelUnblocksPromptly) { HttpDestroyRequestInternal(h); } -TEST(HttpTransportCurlTest, - RedirectsSameOriginPreservesAuthAndCrossOriginStrips) { +TEST(HttpTransportCurlTest, RedirectResponsesAreDeliveredNotFollowed) { BlockingEventDemux demux; demux.DrainStale(); - std::string observed_b_auth; - std::string observed_b_cookie; - std::string observed_b_appcheck; - std::string observed_b_apikey; - std::string observed_b_safe; - std::string observed_b_method; - std::mutex obs_mu; - - LoopbackHttpServer server_b([&](const ParsedRequest& req, SocketFd fd) { + std::mutex mu; + std::vector seen_requests; + LoopbackHttpServer server([&](const ParsedRequest& req, SocketFd fd) { { - std::lock_guard lock(obs_mu); - observed_b_method = req.method; - observed_b_auth = req.GetHeader("Authorization"); - observed_b_cookie = req.GetHeader("Cookie"); - observed_b_appcheck = req.GetHeader("X-Firebase-AppCheck"); - observed_b_apikey = req.GetHeader("x-goog-api-key"); - observed_b_safe = req.GetHeader("X-Safe"); + std::lock_guard lock(mu); + seen_requests.push_back(req.method + " " + req.target + " " + req.body); } - SendAll(fd, - "HTTP/1.1 200 OK\r\n" - "Content-Length: 4\r\n" - "Connection: close\r\n\r\ndone"); - }); - - std::string observed_same_origin_auth; - std::string observed_same_origin_method; - std::string observed_301_method; - std::string observed_303_post_method; - std::string observed_303_head_method; - std::string observed_space_target; - LoopbackHttpServer server_a([&](const ParsedRequest& req, SocketFd fd) { - if (req.target == "/same-302") { - SendAll(fd, - "HTTP/1.1 302 Found\r\n" - "Location: /same-target\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n\r\n"); - } else if (req.target == "/same-target") { - { - std::lock_guard lock(obs_mu); - observed_same_origin_method = req.method; - observed_same_origin_auth = req.GetHeader("Authorization"); - } + // "/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: 2\r\n" - "Connection: close\r\n\r\nok"); - } else if (req.target == "/post-301") { - SendAll(fd, - "HTTP/1.1 301 Moved Permanently\r\n" - "Location: /after-301\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n\r\n"); - } else if (req.target == "/after-301") { - { - std::lock_guard lock(obs_mu); - observed_301_method = req.method; - } - SendAll(fd, - "HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: " - "close\r\n\r\n301"); - } else if (req.target == "/post-303") { - SendAll(fd, - "HTTP/1.1 303 See Other\r\n" - "Location: /after-303-post\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n\r\n"); - } else if (req.target == "/after-303-post") { - { - std::lock_guard lock(obs_mu); - observed_303_post_method = req.method; - } - SendAll(fd, - "HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: " - "close\r\n\r\n303"); - } else if (req.target == "/head-303") { - SendAll(fd, - "HTTP/1.1 303 See Other\r\n" - "Location: /after-303-head\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n\r\n"); - } else if (req.target == "/after-303-head") { - { - std::lock_guard lock(obs_mu); - observed_303_head_method = req.method; - } - SendAll(fd, - "HTTP/1.1 200 OK\r\nContent-Length: 42\r\nConnection: " - "close\r\n\r\n"); - } else if (req.target == "/body-307") { - SendAll(fd, - "HTTP/1.1 307 Temporary Redirect\r\n" - "Location: /never-reached\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n\r\n"); - } else if (req.target == "/space-redir") { - SendAll(fd, - "HTTP/1.1 302 Found\r\n" - "Location: /path with space\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n\r\n"); - } else if (req.target == "/path%20with%20space") { - { - std::lock_guard lock(obs_mu); - observed_space_target = req.target; - } - SendAll(fd, - "HTTP/1.1 200 OK\r\nContent-Length: 5\r\nConnection: " - "close\r\n\r\nspace"); - } else if (req.target == "/cross-307") { - SendAll(fd, - "HTTP/1.1 307 Temporary Redirect\r\n" - "Location: " + - server_b.Url("/final") + - "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); - } else if (req.target == "/loop") { - SendAll(fd, - "HTTP/1.1 302 Found\r\n" - "Location: /loop\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n\r\n"); - } else if (req.target == "/unsafe") { - SendAll(fd, - "HTTP/1.1 302 Found\r\n" - "Location: file:///etc/passwd\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n\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); }); - // 1. Same-origin 302 POST -> GET rewrites method and preserves Authorization. - int64_t h1 = HttpCreateRequestInternal( - "POST", server_a.Url("/same-302").c_str(), - "Authorization\tBearer secret\nContent-Type\tapplication/json\n", "", 0); - HttpStartRequestInternal(h1); - ASSERT_EQ(WaitHeaders(&demux, h1), 200); - std::string b1; - ASSERT_TRUE(ReadAllBody(&demux, h1, &b1)); - EXPECT_EQ(b1, "ok"); - { - std::lock_guard lock(obs_mu); - EXPECT_EQ(observed_same_origin_method, "GET"); - EXPECT_EQ(observed_same_origin_auth, "Bearer secret"); + 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 + " "); } - HttpDestroyRequestInternal(h1); - // 2. Cross-origin 307 strips sensitive headers (including Cookie, S3), - // forwards safe headers. - int64_t h2 = - HttpCreateRequestInternal("GET", server_a.Url("/cross-307").c_str(), - "Authorization\tBearer secret\n" - "Cookie\tsession=xyz\n" - "X-Firebase-AppCheck\tappcheck-tok\n" - "x-goog-api-key\tapi-key\n" - "X-Safe\tkeep-me\n", - "", kNoRequestContent); - HttpStartRequestInternal(h2); - ASSERT_EQ(WaitHeaders(&demux, h2), 200); - std::string b2; - ASSERT_TRUE(ReadAllBody(&demux, h2, &b2)); - EXPECT_EQ(b2, "done"); - { - std::lock_guard lock(obs_mu); - EXPECT_EQ(observed_b_method, "GET"); - EXPECT_TRUE(observed_b_auth.empty()); - EXPECT_TRUE(observed_b_cookie.empty()); - EXPECT_TRUE(observed_b_appcheck.empty()); - EXPECT_TRUE(observed_b_apikey.empty()); - EXPECT_EQ(observed_b_safe, "keep-me"); - } - HttpDestroyRequestInternal(h2); + // 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); +} - // 3. 301 POST -> GET and 303 POST -> GET (T4). - int64_t h_301 = HttpCreateRequestInternal( - "POST", server_a.Url("/post-301").c_str(), "", "", 0); - HttpStartRequestInternal(h_301); - ASSERT_EQ(WaitHeaders(&demux, h_301), 200); - std::string b_301; - ASSERT_TRUE(ReadAllBody(&demux, h_301, &b_301)); - EXPECT_EQ(b_301, "301"); - HttpDestroyRequestInternal(h_301); - - int64_t h_303 = HttpCreateRequestInternal( - "POST", server_a.Url("/post-303").c_str(), "", "", 0); - HttpStartRequestInternal(h_303); - ASSERT_EQ(WaitHeaders(&demux, h_303), 200); - std::string b_303; - ASSERT_TRUE(ReadAllBody(&demux, h_303, &b_303)); - EXPECT_EQ(b_303, "303"); - HttpDestroyRequestInternal(h_303); - - // 4. HEAD on 303 must stay HEAD (C1, T4). - int64_t h_head = HttpCreateRequestInternal( - "HEAD", server_a.Url("/head-303").c_str(), "", "", kNoRequestContent); - HttpStartRequestInternal(h_head); - ASSERT_EQ(WaitHeaders(&demux, h_head), 200); - std::string b_head; - ASSERT_TRUE(ReadAllBody(&demux, h_head, &b_head)); - EXPECT_TRUE(b_head.empty()); - HttpDestroyRequestInternal(h_head); - - // 5. 307 with streamed body fails cleanly (T4). - const std::string body_307 = "cannot-replay"; - int64_t h_307 = HttpCreateRequestInternal( - "POST", server_a.Url("/body-307").c_str(), "", "", - static_cast(body_307.size())); - HttpStartRequestInternal(h_307); - ASSERT_TRUE(WriteAllBody(&demux, h_307, - reinterpret_cast(body_307.data()), - body_307.size())); - EXPECT_EQ(WaitHeaders(&demux, h_307), -1); - EXPECT_NE(HttpGetErrorInternal(h_307).find("Cannot replay"), - std::string::npos); - HttpDestroyRequestInternal(h_307); - - // 6. Redirect target containing a space is percent-encoded (C3). - int64_t h_sp = HttpCreateRequestInternal( - "GET", server_a.Url("/space-redir").c_str(), "", "", kNoRequestContent); - HttpStartRequestInternal(h_sp); - ASSERT_EQ(WaitHeaders(&demux, h_sp), 200); - std::string b_sp; - ASSERT_TRUE(ReadAllBody(&demux, h_sp, &b_sp)); - EXPECT_EQ(b_sp, "space"); - HttpDestroyRequestInternal(h_sp); +TEST(HttpTransportCurlTest, InvalidRequestsFailWithoutConnecting) { + BlockingEventDemux demux; + demux.DrainStale(); - { - std::lock_guard lock(obs_mu); - EXPECT_EQ(observed_301_method, "GET"); - EXPECT_EQ(observed_303_post_method, "GET"); - EXPECT_EQ(observed_303_head_method, "HEAD"); - EXPECT_EQ(observed_space_target, "/path%20with%20space"); - } + std::atomic connections{0}; + LoopbackHttpServer server(nullptr, + [&](SocketFd) { connections.fetch_add(1); }); - // 7. Infinite redirect loop fails once kMaxRedirects is exceeded. - int64_t h3 = HttpCreateRequestInternal("GET", server_a.Url("/loop").c_str(), - "", "", kNoRequestContent); - HttpStartRequestInternal(h3); - EXPECT_EQ(WaitHeaders(&demux, h3), -1); - EXPECT_NE(HttpGetErrorInternal(h3).find("Maximum HTTP redirects"), - std::string::npos); - HttpDestroyRequestInternal(h3); + 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}, + }; + 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); + } - // 8. Non-HTTP(S) redirect target is blocked. - int64_t h4 = HttpCreateRequestInternal("GET", server_a.Url("/unsafe").c_str(), - "", "", kNoRequestContent); - HttpStartRequestInternal(h4); - EXPECT_EQ(WaitHeaders(&demux, h4), -1); - EXPECT_NE(HttpGetErrorInternal(h4).find("Blocked unsafe"), std::string::npos); - HttpDestroyRequestInternal(h4); + EXPECT_EQ(connections.load(), 0); } -TEST(HttpTransportCurlTest, BadProxyAndInvalidHeadersFailWithoutConnecting) { +TEST(HttpTransportCurlTest, ProxyUrlReachesLibcurlUnchanged) { BlockingEventDemux demux; demux.DrainStale(); - std::atomic hits{0}; - LoopbackHttpServer server([&](const ParsedRequest&, SocketFd fd) { - hits.fetch_add(1); - SendAll(fd, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"); - }); - - // Bad proxy URL (socks5://) must fail, never connect direct (T4). - int64_t h1 = HttpCreateRequestInternal("GET", server.Url("/p").c_str(), "", - "socks5://127.0.0.1:1080", - kNoRequestContent); - HttpStartRequestInternal(h1); - EXPECT_EQ(WaitHeaders(&demux, h1), -1); - EXPECT_EQ(HttpGetErrorClassInternal(h1), kHttpErrorOther); - HttpDestroyRequestInternal(h1); - - // Header containing CR injection must fail without connecting (S2, T4). - int64_t h2 = HttpCreateRequestInternal( - "GET", server.Url("/h").c_str(), "X-Test\tvalue\rInjected: 1\n", "", - kNoRequestContent); - HttpStartRequestInternal(h2); - EXPECT_EQ(WaitHeaders(&demux, h2), -1); - EXPECT_EQ(HttpGetErrorClassInternal(h2), kHttpErrorOther); - HttpDestroyRequestInternal(h2); - - // Header containing LF injection (line without separator) must fail (S2, T4). - int64_t h3 = HttpCreateRequestInternal( - "GET", server.Url("/h2").c_str(), "X-Test\tvalue\nmalformed_line\n", "", - kNoRequestContent); - HttpStartRequestInternal(h3); - EXPECT_EQ(WaitHeaders(&demux, h3), -1); - EXPECT_EQ(HttpGetErrorClassInternal(h3), kHttpErrorOther); - HttpDestroyRequestInternal(h3); + 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(hits.load(), 0); + EXPECT_EQ(direct_connections.load(), 0); } -TEST(HttpTransportCurlTest, ErrorClassesConnectAndTls) { +TEST(HttpTransportCurlTest, ErrorClassesConnectAndTlsHandshake) { BlockingEventDemux demux; demux.DrainStale(); @@ -1220,7 +1205,8 @@ TEST(HttpTransportCurlTest, ErrorClassesConnectAndTls) { EXPECT_EQ(HttpGetErrorClassInternal(h_conn), kHttpErrorConnect); HttpDestroyRequestInternal(h_conn); - // 2. TLS handshake failure when speaking HTTPS to a non-TLS endpoint. + // 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; @@ -1262,9 +1248,7 @@ TEST(HttpTransportCurlTest, ErrorClassesConnectAndTls) { } char buf[512]; (void)recv(c, buf, sizeof(buf), 0); - // Respond with a TLS 1.2 fatal handshake_failure alert so every TLS stack - // (OpenSSL/BoringSSL, SecureTransport/Network.framework, Conscrypt) - // classifies the failure as kHttpErrorTls even if it retries once. + // 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); @@ -1279,10 +1263,26 @@ TEST(HttpTransportCurlTest, ErrorClassesConnectAndTls) { kNoRequestContent); HttpStartRequestInternal(h_tls); EXPECT_EQ(WaitHeaders(&demux, h_tls), -1); - EXPECT_EQ(HttpGetErrorClassInternal(h_tls), kHttpErrorTls); + 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, @@ -1290,20 +1290,25 @@ TEST(HttpTransportCurlTest, BlockingEventDemux demux; demux.DrainStale(); - constexpr size_t kUploadSize = 1024 * 1024; // 1 MiB (> 256 KiB pipe) - constexpr size_t kDownloadSize = 4 * 1024 * 1024; // 4 MiB (> 2 MiB pipe) + 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::vector expected_download(kDownloadSize); - for (size_t i = 0; i < kDownloadSize; ++i) { - expected_download[i] = static_cast((i * 17 + 3) & 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") { { @@ -1318,10 +1323,52 @@ TEST(HttpTransportCurlTest, SendAll(fd, "HTTP/1.1 200 OK\r\n" "Content-Length: " + - std::to_string(expected_download.size()) + + std::to_string(kDownloadSize) + "\r\nConnection: close\r\n\r\n"); - SendAll(fd, reinterpret_cast(expected_download.data()), - expected_download.size()); + // 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(); } }); @@ -1345,38 +1392,67 @@ TEST(HttpTransportCurlTest, } HttpDestroyRequestInternal(h_up); - // 2. Large download exceeding kMaxResponseBufferBytes: wait until the - // native buffer actually crosses kMaxResponseBufferBytes (explicit condition - // instead of a fixed sleep, T3) to deterministically exercise pause/resume. + // 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 hw_deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); - bool hit_high_water = false; - while (std::chrono::steady_clock::now() < hw_deadline) { - { - std::lock_guard lock(dl_op->mutex); - if (dl_op->resp_buffered_bytes >= kMaxResponseBufferBytes || - dl_op->resp_eof) { - hit_high_water = dl_op->resp_buffered_bytes >= kMaxResponseBufferBytes; - break; + 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; } - std::this_thread::yield(); + 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; })); } - EXPECT_TRUE(hit_high_water); - - std::string dl_body; - dl_body.reserve(kDownloadSize); - ASSERT_TRUE(ReadAllBody(&demux, h_dl, &dl_body, 15000)); - ASSERT_EQ(dl_body.size(), expected_download.size()); - EXPECT_EQ(std::memcmp(dl_body.data(), expected_download.data(), - expected_download.size()), - 0); HttpDestroyRequestInternal(h_dl); } @@ -1451,97 +1527,193 @@ TEST(HttpTransportCurlTest, ConcurrentMixedTransfers) { } } -TEST(HttpTransportCurlTest, EarlyServerResponseUnblocksLargeUpload) { +TEST(HttpTransportCurlTest, EarlyServerResponseEndsLargeUploadWithoutError) { BlockingEventDemux demux; demux.DrainStale(); - // Server sends an immediate 413 response with Content-Length: 0 as soon as - // request headers arrive, then performs an RFC 9112 section 9.6 lingering - // close (shutdown write + drain until peer closes) so the client reliably - // receives the 413 rather than racing a BSD TCP RST from unread upload bytes. - EnsureSocketSubsystemInitialized(); - SocketFd listen_fd = socket(AF_INET, SOCK_STREAM, 0); - ASSERT_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; - ASSERT_EQ(bind(listen_fd, reinterpret_cast(&addr), sizeof(addr)), - 0); - ASSERT_EQ(listen(listen_fd, 4), 0); - sockaddr_in bound{}; -#if defined(_WIN32) - int bound_len = sizeof(bound); -#else - socklen_t bound_len = sizeof(bound); -#endif - ASSERT_EQ( - getsockname(listen_fd, reinterpret_cast(&bound), &bound_len), - 0); - int raw_port = ntohs(bound.sin_port); + 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::thread raw_server([listen_fd]() { - sockaddr_in client_addr{}; -#if defined(_WIN32) - int len = sizeof(client_addr); -#else - socklen_t len = sizeof(client_addr); -#endif - SocketFd c = - accept(listen_fd, reinterpret_cast(&client_addr), &len); - if (c != kInvalidSocket) { -#ifdef SO_NOSIGPIPE - int nosigpipe = 1; - setsockopt(c, SOL_SOCKET, SO_NOSIGPIPE, - reinterpret_cast(&nosigpipe), sizeof(nosigpipe)); -#endif - std::string hdrs; - char tmp[1024]; - while (hdrs.find("\r\n\r\n") == std::string::npos) { -#if defined(_WIN32) - int n = recv(c, tmp, sizeof(tmp), 0); -#else - ssize_t n = recv(c, tmp, sizeof(tmp), 0); -#endif - if (n <= 0) break; - hdrs.append(tmp, static_cast(n)); - } - SendAll(c, - "HTTP/1.1 413 Payload Too Large\r\n" - "Content-Length: 0\r\n" - "Connection: close\r\n" - "\r\n"); - ShutdownWrite(c); - (void)WaitForPeerClose(c, 1000); - CloseSocket(c); + 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; })); } - CloseSocket(listen_fd); + SendAll(fd, "retry later"); + EXPECT_TRUE(WaitForPeerClose(fd, 5000)); }); - constexpr size_t kLargeUpload = 2 * 1024 * 1024; - std::string url = - "http://127.0.0.1:" + std::to_string(raw_port) + "/early-reject"; - int64_t h = HttpCreateRequestInternal( - "PUT", url.c_str(), "Content-Type\tapplication/octet-stream\n", "", - static_cast(kLargeUpload)); + 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::vector payload(kLargeUpload, 0x42); - auto t0 = std::chrono::steady_clock::now(); - bool finished_upload = - WriteAllBody(&demux, h, payload.data(), payload.size(), 5000); - auto elapsed_ms = std::chrono::duration_cast( - std::chrono::steady_clock::now() - t0) - .count(); - EXPECT_FALSE(finished_upload); - EXPECT_LT(elapsed_ms, 3000); - EXPECT_EQ(WaitHeaders(&demux, h, 2000), 413); - + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, h, &body)); + EXPECT_EQ(body, "retry later"); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorNone); HttpDestroyRequestInternal(h); - raw_server.join(); +} + +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 From 5b3c416717aba43b0d72c3c766d584ab34b43de0 Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 30 Nov 2026 18:41:43 +0000 Subject: [PATCH 08/16] [App][HTTP] Apple: stop following redirects, narrow error classes, fix body-stream restart - Deliver 3xx responses to the caller and remove native redirect handling. - Only certificate NSURLError codes map to Certificate; a failed secure connection maps to Connect. Validation failures use InvalidRequest. - Parse the proxy URL with NSURLComponents. - needNewBodyStream installs a fresh stream only when no body bytes were handed to NSURLSession yet; otherwise the request fails as not replayable. - Report an empty reason phrase; correct the session pool comment. Not yet compiled: no Apple toolchain on the authoring machine. --- app/http/http_transport_apple.mm | 366 +++++++++---------------------- 1 file changed, 104 insertions(+), 262 deletions(-) diff --git a/app/http/http_transport_apple.mm b/app/http/http_transport_apple.mm index 475178b587..dd7c06eb5d 100644 --- a/app/http/http_transport_apple.mm +++ b/app/http/http_transport_apple.mm @@ -71,67 +71,6 @@ return out; } -std::string CanonicalReasonPhrase(int32_t status) { - switch (status) { - case 200: - return "OK"; - case 201: - return "Created"; - case 202: - return "Accepted"; - case 204: - return "No Content"; - case 206: - return "Partial Content"; - case 301: - return "Moved Permanently"; - case 302: - return "Found"; - case 303: - return "See Other"; - case 304: - return "Not Modified"; - case 307: - return "Temporary Redirect"; - case 308: - return "Permanent Redirect"; - case 400: - return "Bad Request"; - case 401: - return "Unauthorized"; - case 403: - return "Forbidden"; - case 404: - return "Not Found"; - case 405: - return "Method Not Allowed"; - case 408: - return "Request Timeout"; - case 409: - return "Conflict"; - case 410: - return "Gone"; - case 412: - return "Precondition Failed"; - case 413: - return "Payload Too Large"; - case 416: - return "Range Not Satisfiable"; - case 429: - return "Too Many Requests"; - case 500: - return "Internal Server Error"; - case 502: - return "Bad Gateway"; - case 503: - return "Service Unavailable"; - case 504: - return "Gateway Timeout"; - default: - return FromNSString([NSHTTPURLResponse localizedStringForStatusCode:status]); - } -} - HttpErrorClass ClassifyNSError(NSError* error) { NSError* current = error; for (int depth = 0; current != nil && depth < 6; ++depth) { @@ -143,15 +82,17 @@ HttpErrorClass ClassifyNSError(NSError* error) { return kHttpErrorCanceled; case NSURLErrorTimedOut: return kHttpErrorTimeout; - case NSURLErrorSecureConnectionFailed: 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 kHttpErrorTls; + return kHttpErrorInvalidRequest; + case NSURLErrorSecureConnectionFailed: case NSURLErrorCannotFindHost: case NSURLErrorCannotConnectToHost: case NSURLErrorNetworkConnectionLost: @@ -165,8 +106,13 @@ HttpErrorClass ClassifyNSError(NSError* error) { break; } } else if ([domain isEqualToString:@"kCFErrorDomainCFNetwork"]) { - if (code <= -1200 && code >= -1206) { - return kHttpErrorTls; + // 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; @@ -201,7 +147,7 @@ HttpErrorClass ClassifyNSError(NSError* error) { bool task_suspended = false; bool body_closed = false; bool slot_released = false; - int redirect_count = 0; + bool response_started = false; std::atomic any_body_bytes_popped{false}; std::vector pending_write_chunk; size_t pending_write_offset = 0; @@ -324,6 +270,7 @@ - (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) { @@ -332,8 +279,15 @@ - (void)closeOnStreamThread { 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]; @@ -362,15 +316,25 @@ - (void)pumpOnStreamThread { constexpr size_t kSliceSize = 64 * 1024; while ([stream hasSpaceAvailable]) { if (state->pending_write_offset >= state->pending_write_chunk.size()) { - state->pending_write_chunk.resize(kSliceSize); - state->pending_write_offset = 0; bool eof = false; - size_t 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); - } else { + 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]; } @@ -386,8 +350,8 @@ - (void)pumpOnStreamThread { state->pending_write_offset += static_cast(written); } else if (written < 0) { // NSURLSession closes the bound input stream early when the server sends - // an immediate 4xx/5xx (such as 413) or a 301-303 redirect to GET. Do - // NOT call MarkFailed or cancel the task here; close the upload pipe and + // 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(); @@ -407,7 +371,11 @@ - (void)stream:(NSStream*)aStream handleEvent:(NSStreamEvent)eventCode { case NSStreamEventErrorOccurred: case NSStreamEventEndEncountered: { auto state = _state; - if (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]; @@ -474,23 +442,11 @@ - (void)URLSession:(NSURLSession*)session return; } - if (state->any_body_bytes_popped.load(std::memory_order_acquire)) { - bool is_redirect = false; - { - std::lock_guard lock(state->state_mutex); - is_redirect = state->redirect_count > 0; - } - state->op->MarkFailed(is_redirect ? "Cannot replay streamed request body across redirect." - : "Cannot replay streamed request body.", - firebase::http::kHttpErrorOther); - [task cancel]; - completionHandler(nil); - return; - } - - // No bytes were consumed from the upload pipe yet (for example NSURLSession - // retrying a request on a stale keep-alive connection before sending body - // bytes). Supply a fresh bound stream pair. + // 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 @@ -499,12 +455,22 @@ - (void)URLSession:(NSURLSession*)session FIRFirebaseHttpStreamBridge* old_bridge = nil; FIRFirebaseHttpStreamBridge* new_bridge = [[FIRFirebaseHttpStreamBridge alloc] initWithState:state]; + bool can_restart = false; { std::lock_guard lock(state->state_mutex); - old_bridge = state->stream_bridge; - state->body_closed = false; - state->body_output_stream = out_stream; - state->stream_bridge = new_bridge; + 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]; @@ -518,157 +484,10 @@ - (void)URLSession:(NSURLSession*)session willPerformHTTPRedirection:(NSHTTPURLResponse*)response newRequest:(NSURLRequest*)request completionHandler:(void (^)(NSURLRequest* _Nullable))handler { - auto state = [self findState:task]; - int32_t status = static_cast(response.statusCode); - if (state) { - bool exceeded = false; - { - std::lock_guard lock(state->state_mutex); - if (state->redirect_count >= firebase::http::kMaxRedirects) { - exceeded = true; - } else { - ++state->redirect_count; - } - } - if (exceeded) { - state->op->MarkFailed("Maximum HTTP redirects exceeded.", firebase::http::kHttpErrorOther); - [task cancel]; - handler(nil); - return; - } - } - - std::string orig_url = firebase::http::FromNSString(task.originalRequest.URL.absoluteString); - NSString* prev_ns = - response.URL != nil ? response.URL.absoluteString : task.currentRequest.URL.absoluteString; - std::string prev_url = firebase::http::FromNSString(prev_ns); - - // Resolve Location through the shared RFC 3986 redirect validator so userinfo - // rejection, spaces, non-HTTP(S) schemes, and HTTPS -> HTTP downgrades match - // Desktop and Android identically. - NSString* raw_location = nil; - for (id rawKey in response.allHeaderFields) { - if ([rawKey isKindOfClass:[NSString class]] && - firebase::http::AsciiEqualsIgnoreCase( - firebase::http::FromNSString(static_cast(rawKey)), "Location")) { - id val = response.allHeaderFields[rawKey]; - if ([val isKindOfClass:[NSString class]]) { - raw_location = static_cast(val); - } - break; - } - } - - std::string next_url; - if (raw_location != nil) { - auto resolved = - firebase::http::ResolveRedirectUrl(prev_url, firebase::http::FromNSString(raw_location)); - if (!resolved) { - if (state) { - state->op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect.", - firebase::http::kHttpErrorOther); - } - [task cancel]; - handler(nil); - return; - } - next_url = std::move(*resolved); - } else { - next_url = firebase::http::FromNSString(request.URL.absoluteString); - } - - bool was_https = firebase::http::IsHttpsUrl(orig_url) || firebase::http::IsHttpsUrl(prev_url); - if (!firebase::http::IsHttpOrHttpsUrl(next_url) || - (was_https && !firebase::http::IsHttpsUrl(next_url))) { - // Fail the operation and cancel the task on non-HTTP(S) schemes or - // HTTPS -> HTTP downgrades; passing handler(nil) alone would complete the - // task with the raw 3xx response as success. - if (state) { - state->op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect.", - firebase::http::kHttpErrorOther); - } - [task cancel]; - handler(nil); - return; - } - - std::string cur_method = firebase::http::FromNSString(task.currentRequest.HTTPMethod); - bool has_streamed_body = - state && (state->op->content_length > 0 || - state->op->content_length == firebase::http::kChunkedRequestContent); - bool rewrites_to_get = (status == 301 || status == 302 || status == 303) && - !firebase::http::AsciiEqualsIgnoreCase(cur_method, "GET") && - !firebase::http::AsciiEqualsIgnoreCase(cur_method, "HEAD"); - - if (!rewrites_to_get && (status == 307 || status == 308) && has_streamed_body) { - if (state) { - state->op->MarkFailed("Cannot replay streamed request body across redirect.", - firebase::http::kHttpErrorOther); - } - [task cancel]; - handler(nil); - return; - } - - NSMutableURLRequest* next_req = [request mutableCopy]; - NSURL* validated_ns_url = [NSURL URLWithString:firebase::http::ToNSString(next_url)]; - if (validated_ns_url != nil) { - next_req.URL = validated_ns_url; - } - - if (rewrites_to_get) { - next_req.HTTPMethod = @"GET"; - next_req.HTTPBody = nil; - next_req.HTTPBodyStream = nil; - [next_req setValue:nil forHTTPHeaderField:@"Content-Type"]; - [next_req setValue:nil forHTTPHeaderField:@"Content-Length"]; - [next_req setValue:nil forHTTPHeaderField:@"Transfer-Encoding"]; - if (state) { - state->op->MarkRequestWriteClosed(); - FIRFirebaseHttpStreamBridge* bridge = nil; - { - std::lock_guard lock(state->state_mutex); - bridge = state->stream_bridge; - state->stream_bridge = nil; - } - if (bridge != nil) { - [bridge closeWriteStream]; - } - } - } else if (status == 303 && firebase::http::AsciiEqualsIgnoreCase(cur_method, "HEAD")) { - next_req.HTTPMethod = @"HEAD"; - next_req.HTTPBody = nil; - next_req.HTTPBodyStream = nil; - } - - if (!firebase::http::IsSameOrigin(orig_url, next_url) || - !firebase::http::IsSameOrigin(prev_url, next_url)) { - NSDictionary* fields = [next_req.allHTTPHeaderFields copy]; - for (NSString* key in fields) { - if (firebase::http::IsSensitiveRedirectHeader(firebase::http::FromNSString(key)) || - firebase::http::AsciiEqualsIgnoreCase(firebase::http::FromNSString(key), "Host")) { - [next_req setValue:nil forHTTPHeaderField:key]; - } - } - [next_req setValue:nil forHTTPHeaderField:@"Authorization"]; - [next_req setValue:nil forHTTPHeaderField:@"Proxy-Authorization"]; - [next_req setValue:nil forHTTPHeaderField:@"Cookie"]; - [next_req setValue:nil forHTTPHeaderField:@"X-Firebase-AppCheck"]; - [next_req setValue:nil forHTTPHeaderField:@"x-goog-api-key"]; - handler(next_req); - return; - } - - // CFNetwork strips the reserved Authorization header when constructing - // `newRequest` even on same-origin redirects. Copy it from `currentRequest` - // (never `originalRequest`, so a credential stripped on an earlier - // cross-origin hop can never be resurrected on a later bounce back). - NSString* cur_auth = [task.currentRequest valueForHTTPHeaderField:@"Authorization"]; - if (cur_auth != nil && [next_req valueForHTTPHeaderField:@"Authorization"] == nil) { - [next_req setValue:cur_auth forHTTPHeaderField:@"Authorization"]; - } - - handler(next_req); + // 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 @@ -689,7 +508,6 @@ - (void)URLSession:(NSURLSession*)session auto* httpResp = static_cast(response); int32_t status = static_cast(httpResp.statusCode); - std::string reason = firebase::http::CanonicalReasonPhrase(status); std::vector> headers; NSDictionary* fields = httpResp.allHeaderFields; for (id rawKey in fields) { @@ -700,7 +518,20 @@ - (void)URLSession:(NSURLSession*)session } } - state->op->CommitResponseHeaders(status, reason, std::move(headers)); + 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); } @@ -839,7 +670,9 @@ - (void)URLSession:(NSURLSession*)session // 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: -// - HTTP/2 and TLS keep-alive reuse across up to 16 concurrent connections. +// - 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 @@ -952,7 +785,7 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { } if (!IsHttpOrHttpsUrl(op->url)) { op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", - kHttpErrorOther); + kHttpErrorInvalidRequest); return; } @@ -960,34 +793,43 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { 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.", kHttpErrorOther); + 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.", kHttpErrorOther); + op->MarkFailed("Invalid request URL.", kHttpErrorInvalidRequest); return; } // Validate proxy URL upfront and never silently fall back to direct. std::shared_ptr slot; if (!op->proxy_url.empty()) { - auto proxy_hp = ParseProxyHostPort(op->proxy_url); - if (!proxy_hp) { - op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorOther); + NSURLComponents* proxy = [NSURLComponents componentsWithString:ToNSString(op->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) { + op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorInvalidRequest); return; } - NSString* host = ToNSString(proxy_hp->first); - NSNumber* port = @(proxy_hp->second); NSURLSessionConfiguration* config = MakeBaseSessionConfig(); config.connectionProxyDictionary = @{ @"HTTPEnable" : @YES, @"HTTPProxy" : host, - @"HTTPPort" : port, + @"HTTPPort" : @(port), @"HTTPSEnable" : @YES, @"HTTPSProxy" : host, - @"HTTPSPort" : port, + @"HTTPSPort" : @(port), }; slot = CreateSessionSlot(config, /*pooled=*/false); } else { From 27d38236737d9b41a2adcf636d948d2e80ebd0d4 Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 30 Nov 2026 19:15:47 +0000 Subject: [PATCH 09/16] [App][HTTP] Add a WebSocket client to the native transport (shared code and libcurl backend) - Bridge: WebSocket*Internal functions in http_bridge.h, sharing the handle id space and the event queue with HTTP operations. - Shared code owns bounded send and receive queues and the close state machine; backends move whole messages. - libcurl backend: one worker thread and multi handle for all sockets, frame reassembly, pong replies, keepalive pings, receive backpressure. - Connection options common to HTTP and WebSockets are applied in one place (ApplyCurlConnectionOptions). - A TLS policy setup failure is class Other, not Certificate. Test that a URL with userinfo is refused. --- app/http/CMakeLists.txt | 15 +- app/http/http_bridge.h | 91 ++ app/http/http_transport.h | 11 +- app/http/http_transport_common.cc | 8 + app/http/http_transport_curl.cc | 58 +- app/http/http_transport_curl_internal.h | 53 + app/http/tests/CMakeLists.txt | 15 + app/http/tests/http_transport_curl_test.cc | 2 + app/http/tests/websocket_common_test.cc | 794 +++++++++++ app/http/tests/websocket_curl_test.cc | 1402 ++++++++++++++++++++ app/http/websocket.h | 231 ++++ app/http/websocket_common.cc | 599 +++++++++ app/http/websocket_curl.cc | 762 +++++++++++ 13 files changed, 4015 insertions(+), 26 deletions(-) create mode 100644 app/http/http_transport_curl_internal.h create mode 100644 app/http/tests/websocket_common_test.cc create mode 100644 app/http/tests/websocket_curl_test.cc create mode 100644 app/http/websocket.h create mode 100644 app/http/websocket_common.cc create mode 100644 app/http/websocket_curl.cc diff --git a/app/http/CMakeLists.txt b/app/http/CMakeLists.txt index fa7c31af34..74761c075c 100644 --- a/app/http/CMakeLists.txt +++ b/app/http/CMakeLists.txt @@ -22,14 +22,21 @@ set(CMAKE_CXX_STANDARD_REQUIRED YES) set(http_transport_SRCS http_bridge.h http_transport.h - http_transport_common.cc) + http_transport_common.cc + websocket.h + websocket_common.cc) if(ANDROID) list(APPEND http_transport_SRCS http_transport_android.cc) elseif(IOS) - list(APPEND http_transport_SRCS http_transport_apple.mm) + list(APPEND http_transport_SRCS + http_transport_apple.mm + websocket_apple.mm) else() - list(APPEND http_transport_SRCS http_transport_curl.cc) + list(APPEND http_transport_SRCS + http_transport_curl.cc + http_transport_curl_internal.h + websocket_curl.cc) endif() add_library(firebase_http_transport STATIC @@ -57,7 +64,7 @@ target_link_libraries(firebase_http_transport if(ANDROID) # Android uses JNI HttpURLConnection directly via firebase_app's JNI helpers. elseif(IOS) - set_source_files_properties(http_transport_apple.mm + set_source_files_properties(http_transport_apple.mm websocket_apple.mm PROPERTIES COMPILE_OPTIONS "-fobjc-arc" ) target_link_libraries(firebase_http_transport diff --git a/app/http/http_bridge.h b/app/http/http_bridge.h index ded600e472..808f1b00bf 100644 --- a/app/http/http_bridge.h +++ b/app/http/http_bridge.h @@ -109,6 +109,97 @@ int64_t HttpWaitNextEventInternal(int32_t timeout_ms); // 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 index 1ac55a48ca..babfe5727e 100644 --- a/app/http/http_transport.h +++ b/app/http/http_transport.h @@ -42,10 +42,9 @@ // - 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 returns canonical -// RFC 9110 English reason phrases (falling back to -// `localizedStringForStatusCode:`) and coalesces duplicate response headers -// per `NSHTTPURLResponse.allHeaderFields`. +// 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_ @@ -79,6 +78,10 @@ enum HttpEventKind : int32_t { kHttpEventRequestSpaceAvailable = 1, kHttpEventResponseHeadersReady = 2, kHttpEventResponseBodyAvailable = 3, + // WebSocket events, see `websocket.h`. + kHttpEventWebSocketOpen = 4, + kHttpEventWebSocketReceive = 5, + kHttpEventWebSocketSendSpace = 6, }; // Structured terminal failure categories returned by diff --git a/app/http/http_transport_common.cc b/app/http/http_transport_common.cc index 3d1d4f885b..1cd45c2f32 100644 --- a/app/http/http_transport_common.cc +++ b/app/http/http_transport_common.cc @@ -21,6 +21,7 @@ #include #include "app/http/http_transport.h" +#include "app/http/websocket.h" namespace firebase { namespace http { @@ -273,6 +274,12 @@ void PostCompletionEvent(int64_t handle, HttpEventKind kind) { 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); @@ -361,6 +368,7 @@ void CancelAllOperations() { for (const auto& op : snapshot) { CancelOperationObject(op); } + CancelAllWebSockets(); HttpWakeEventPumpInternal(); } diff --git a/app/http/http_transport_curl.cc b/app/http/http_transport_curl.cc index a0f3de97e3..eba4271df5 100644 --- a/app/http/http_transport_curl.cc +++ b/app/http/http_transport_curl.cc @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,7 @@ #include #include "app/http/http_transport.h" +#include "app/http/http_transport_curl_internal.h" #include "app/rest/curl/curl_handles.h" #include "app/rest/curl/tls_policy.h" #include "curl/curl.h" @@ -60,6 +62,8 @@ bool AppendSList(::firebase::rest::curl::UniqueSList* list, const char* line) { return true; } +} // namespace + HttpErrorClass ClassifyCurlError(CURLcode code, bool canceled) { if (canceled) { return kHttpErrorCanceled; @@ -105,6 +109,39 @@ HttpErrorClass ClassifyCurlError(CURLcode code, bool canceled) { } } +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)}; + } + + 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; @@ -347,9 +384,9 @@ class CurlHttpEngine { return nullptr; } - CURLcode tls_rc = ::firebase::rest::curl::ApplyTlsPolicy(easy.get()); - if (tls_rc != CURLE_OK) { - op->MarkFailed(curl_easy_strerror(tls_rc), kHttpErrorCertificate); + if (auto setup_error = ApplyCurlConnectionOptions(easy.get(), "http,https", + op->proxy_url)) { + op->MarkFailed(setup_error->message, setup_error->error_class); return nullptr; } @@ -360,19 +397,8 @@ class CurlHttpEngine { CURL* raw_easy = easy.get(); CURLcode opt_err = CURLE_OK; ApplyOpt(raw_easy, CURLOPT_ERRORBUFFER, transfer->error_buf, &opt_err); - ApplyOpt(raw_easy, CURLOPT_NOSIGNAL, 1L, &opt_err); - ApplyOpt(raw_easy, CURLOPT_PROTOCOLS_STR, "http,https", &opt_err); - ApplyOpt(raw_easy, CURLOPT_UNRESTRICTED_AUTH, 0L, &opt_err); - // Never turn `user:password@` in a URL into Basic credentials. - ApplyOpt(raw_easy, CURLOPT_DISALLOW_USERNAME_IN_URL, 1L, &opt_err); - // Redirects are not followed: a 3xx is delivered as an ordinary response. - ApplyOpt(raw_easy, CURLOPT_FOLLOWLOCATION, 0L, &opt_err); - ApplyOpt(raw_easy, CURLOPT_SUPPRESS_CONNECT_HEADERS, 1L, &opt_err); - ApplyOpt(raw_easy, CURLOPT_TCP_NODELAY, 1L, &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_CONNECTTIMEOUT_MS, 60000L, &opt_err); - ApplyOpt(raw_easy, CURLOPT_TIMEOUT_MS, 0L, &opt_err); ApplyOpt(raw_easy, CURLOPT_URL, op->url.c_str(), &opt_err); ApplyOpt(raw_easy, CURLOPT_PRIVATE, transfer.get(), &opt_err); @@ -381,10 +407,6 @@ class CurlHttpEngine { ApplyOpt(raw_easy, CURLOPT_WRITEFUNCTION, OnCurlWrite, &opt_err); ApplyOpt(raw_easy, CURLOPT_WRITEDATA, transfer.get(), &opt_err); - if (!op->proxy_url.empty()) { - ApplyOpt(raw_easy, CURLOPT_PROXY, op->proxy_url.c_str(), &opt_err); - } - bool has_expect = HasHeaderIgnoreCase(op->request_headers, "Expect"); bool has_transfer_encoding = HasHeaderIgnoreCase(op->request_headers, "Transfer-Encoding"); 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/tests/CMakeLists.txt b/app/http/tests/CMakeLists.txt index 0d5ed5bb16..73aa51d43d 100644 --- a/app/http/tests/CMakeLists.txt +++ b/app/http/tests/CMakeLists.txt @@ -26,6 +26,21 @@ firebase_cpp_cc_test(firebase_app_http_curl_test 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_curl_test.cc b/app/http/tests/http_transport_curl_test.cc index 842ca26915..6dfd36f029 100644 --- a/app/http/tests/http_transport_curl_test.cc +++ b/app/http/tests/http_transport_curl_test.cc @@ -1135,6 +1135,8 @@ TEST(HttpTransportCurlTest, InvalidRequestsFailWithoutConnecting) { 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); 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_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 From 92ed1cb44b280c28e271f39b906da2c9699c8911 Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 30 Nov 2026 19:15:47 +0000 Subject: [PATCH 10/16] [App][HTTP] Apple: WebSocket backend on NSURLSessionWebSocketTask One session per socket with a serial delegate queue. The peer's Close is reported after pending messages are read; a close started locally always ends as a clean close. Not yet compiled: no Apple toolchain on the authoring machine. --- app/http/http_transport_apple.mm | 56 ++- app/http/http_transport_apple_internal.h | 47 ++ app/http/websocket_apple.mm | 550 +++++++++++++++++++++++ 3 files changed, 632 insertions(+), 21 deletions(-) create mode 100644 app/http/http_transport_apple_internal.h create mode 100644 app/http/websocket_apple.mm diff --git a/app/http/http_transport_apple.mm b/app/http/http_transport_apple.mm index dd7c06eb5d..978745f2ea 100644 --- a/app/http/http_transport_apple.mm +++ b/app/http/http_transport_apple.mm @@ -31,6 +31,7 @@ #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)." @@ -71,6 +72,8 @@ return out; } +} // namespace + HttpErrorClass ClassifyNSError(NSError* error) { NSError* current = error; for (int depth = 0; current != nil && depth < 6; ++depth) { @@ -131,6 +134,8 @@ HttpErrorClass ClassifyNSError(NSError* error) { return kHttpErrorOther; } +namespace { + struct AppleSessionSlot { NSURLSession* session = nil; FIRFirebaseHttpSessionDelegate* delegate = nil; @@ -635,7 +640,6 @@ - (void)URLSession:(NSURLSession*)session namespace firebase { namespace http { -namespace { NSURLSessionConfiguration* MakeBaseSessionConfig() { NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; @@ -653,6 +657,33 @@ - (void)URLSession:(NSURLSession*)session 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(); @@ -807,30 +838,13 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { // Validate proxy URL upfront and never silently fall back to direct. std::shared_ptr slot; if (!op->proxy_url.empty()) { - NSURLComponents* proxy = [NSURLComponents componentsWithString:ToNSString(op->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) { + NSDictionary* proxy = MakeProxyDictionary(op->proxy_url); + if (proxy == nil) { op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorInvalidRequest); return; } NSURLSessionConfiguration* config = MakeBaseSessionConfig(); - config.connectionProxyDictionary = @{ - @"HTTPEnable" : @YES, - @"HTTPProxy" : host, - @"HTTPPort" : @(port), - @"HTTPSEnable" : @YES, - @"HTTPSProxy" : host, - @"HTTPSPort" : @(port), - }; + config.connectionProxyDictionary = proxy; slot = CreateSessionSlot(config, /*pooled=*/false); } else { slot = AppleSessionPool::Instance().AcquireDefault(); 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/websocket_apple.mm b/app/http/websocket_apple.mm new file mode 100644 index 0000000000..af38c3c60d --- /dev/null +++ b/app/http/websocket_apple.mm @@ -0,0 +1,550 @@ +/* + * 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) { + // A Close frame without a status code cannot carry a reason. + NSURLSessionWebSocketCloseCode code = NSURLSessionWebSocketCloseCodeNoStatusReceived; + NSData* reason = nil; + if (out.close_code > 0) { + 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; + } + + 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 From 0d279b15f12318a7e2f4e3c5c9911351f740fccf Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 30 Nov 2026 19:17:52 +0000 Subject: [PATCH 11/16] [App][HTTP] Use libcurl with a bundled BoringSSL for the Android transport Replace the JNI HttpURLConnection backend with the libcurl backend that desktop uses. curl 8.23.0 and a BoringSSL pin used only for this purpose (0.20260929.0, with X25519MLKEM768) are built per ABI and linked statically with hidden visibility. The system CA store is read from /apex/com.android.conscrypt/cacerts or /system/etc/security/cacerts. The Android settings are applied in ApplyCurlConnectionOptions, so HTTP and WebSocket connections both get them. The transport no longer uses JNI. --- CMakeLists.txt | 55 +- app/CMakeLists.txt | 4 +- app/http/CMakeLists.txt | 28 +- app/http/http_transport.h | 14 +- app/http/http_transport_android.cc | 1396 ----------------------- app/http/http_transport_curl.cc | 15 + app/http/http_transport_curl_android.cc | 157 +++ app/http/http_transport_curl_platform.h | 65 ++ cmake/external/CMakeLists.txt | 8 + cmake/external/boringssl_android.cmake | 50 + cmake/external_rules.cmake | 86 ++ 11 files changed, 462 insertions(+), 1416 deletions(-) delete mode 100644 app/http/http_transport_android.cc create mode 100644 app/http/http_transport_curl_android.cc create mode 100644 app/http/http_transport_curl_platform.h create mode 100644 cmake/external/boringssl_android.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index 36dae1d520..4f1b90c38b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -426,8 +426,48 @@ 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) 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 NOT FIREBASE_CPP_USE_PRIOR_GRADLE_BUILD) + set(FIREBASE_ANDROID_HTTP_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_ANDROID_HTTP_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_ANDROID_HTTP_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 +572,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 5b2c268308..4c1b0f0a1e 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -390,8 +390,8 @@ if (NOT ANDROID AND NOT IOS) add_subdirectory(rest) endif() -# Cross-platform native streaming HTTP transport (Desktop libcurl, iOS/tvOS -# NSURLSession, Android JNI HttpURLConnection). +# Cross-platform native streaming HTTP transport (libcurl on desktop and +# Android, NSURLSession on iOS/tvOS). add_subdirectory(http) if(FIREBASE_CPP_BUILD_TESTS) diff --git a/app/http/CMakeLists.txt b/app/http/CMakeLists.txt index 74761c075c..82a243ac5e 100644 --- a/app/http/CMakeLists.txt +++ b/app/http/CMakeLists.txt @@ -27,7 +27,16 @@ set(http_transport_SRCS websocket_common.cc) if(ANDROID) - list(APPEND http_transport_SRCS http_transport_android.cc) + # 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 @@ -62,7 +71,22 @@ target_link_libraries(firebase_http_transport ) if(ANDROID) - # Android uses JNI HttpURLConnection directly via firebase_app's JNI helpers. + # 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" diff --git a/app/http/http_transport.h b/app/http/http_transport.h index babfe5727e..1dd4bc46f4 100644 --- a/app/http/http_transport.h +++ b/app/http/http_transport.h @@ -62,10 +62,6 @@ #include #include -#if defined(__ANDROID__) -#include -#endif // defined(__ANDROID__) - #include "app/http/http_bridge.h" namespace firebase { @@ -234,17 +230,9 @@ void CancelAllOperations(); // `HttpWaitNextEventInternal`. void PostCompletionEvent(int64_t handle, HttpEventKind kind); -// Platform-specific entry point implemented in -// `http_transport_{curl,apple,android}`. +// Platform-specific entry point implemented in `http_transport_{curl,apple}`. void StartPlatformHttpOperation(const std::shared_ptr& op); -#if defined(__ANDROID__) -// Optionally registers the process `JavaVM*` early (e.g., from `JNI_OnLoad`). -// If not called explicitly, the Android backend falls back to resolving the -// active `JavaVM*` from `firebase::util::GetJNIEnvFromApp()`. -void SetAndroidJavaVM(JavaVM* vm); -#endif // defined(__ANDROID__) - // Case-insensitive ASCII equality helper shared by platform backends. bool AsciiEqualsIgnoreCase(std::string_view a, std::string_view b); diff --git a/app/http/http_transport_android.cc b/app/http/http_transport_android.cc deleted file mode 100644 index e07b500555..0000000000 --- a/app/http/http_transport_android.cc +++ /dev/null @@ -1,1396 +0,0 @@ -/* - * 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 "app/http/http_transport.h" -#include "app/src/util_android.h" - -namespace firebase { -namespace http { -namespace { - -std::atomic g_android_jvm{nullptr}; - -JavaVM* ResolveJavaVM() { - JavaVM* vm = g_android_jvm.load(std::memory_order_acquire); - if (vm != nullptr) { - return vm; - } - JNIEnv* env = ::firebase::util::GetJNIEnvFromApp(); - if (env != nullptr && env->GetJavaVM(&vm) == JNI_OK && vm != nullptr) { - g_android_jvm.store(vm, std::memory_order_release); - return vm; - } - return nullptr; -} - -JNIEnv* ResolveThreadsafeJNIEnv() { - JavaVM* vm = ResolveJavaVM(); - if (vm == nullptr) { - return nullptr; - } - return ::firebase::util::GetThreadsafeJNIEnv(vm); -} - -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; -} - -template -class LocalRef { - public: - LocalRef(JNIEnv* env, T ref) : env_(env), ref_(ref) {} - ~LocalRef() { reset(); } - - LocalRef(const LocalRef&) = delete; - LocalRef& operator=(const LocalRef&) = delete; - - LocalRef(LocalRef&& other) noexcept : env_(other.env_), ref_(other.ref_) { - other.ref_ = nullptr; - } - - LocalRef& operator=(LocalRef&& other) noexcept { - if (this != &other) { - reset(); - env_ = other.env_; - ref_ = other.ref_; - other.ref_ = nullptr; - } - return *this; - } - - T get() const { return ref_; } - explicit operator bool() const { return ref_ != nullptr; } - - void reset(T next = nullptr) { - if (ref_ != nullptr && env_ != nullptr) { - env_->DeleteLocalRef(ref_); - } - ref_ = next; - } - - private: - JNIEnv* env_ = nullptr; - T ref_ = nullptr; -}; - -struct JniExceptionInfo { - std::string message; - HttpErrorClass error_class = kHttpErrorOther; -}; - -struct JniCache { - bool initialized = false; - - jclass url_cls = nullptr; - jmethodID url_ctor = nullptr; - jmethodID url_open_conn = nullptr; - jmethodID url_open_conn_proxy = nullptr; - - jclass proxy_cls = nullptr; - jmethodID proxy_ctor = nullptr; - jobject proxy_type_http = nullptr; - - jclass inet_sock_addr_cls = nullptr; - jmethodID inet_sock_addr_ctor = nullptr; - - jclass http_conn_cls = nullptr; - jmethodID set_request_method = nullptr; - jmethodID set_request_property = nullptr; - jmethodID add_request_property = nullptr; - jmethodID set_use_caches = nullptr; - jmethodID set_connect_timeout = nullptr; - jmethodID set_read_timeout = nullptr; - jmethodID set_instance_follow_redirects = nullptr; - jmethodID set_do_output = nullptr; - jmethodID set_fixed_len_streaming = nullptr; - jmethodID set_chunked_streaming = nullptr; - jmethodID get_output_stream = nullptr; - jmethodID get_response_code = nullptr; - jmethodID get_response_message = nullptr; - jmethodID get_header_fields = nullptr; - jmethodID get_input_stream = nullptr; - jmethodID get_error_stream = nullptr; - jmethodID disconnect = nullptr; - - jclass output_stream_cls = nullptr; - jmethodID output_write = nullptr; - jmethodID output_flush = nullptr; - jmethodID output_close = nullptr; - - jclass input_stream_cls = nullptr; - jmethodID input_read = nullptr; - jmethodID input_close = nullptr; - - jclass map_cls = nullptr; - jmethodID map_entry_set = nullptr; - - jclass set_cls = nullptr; - jmethodID set_iterator = nullptr; - - jclass iter_cls = nullptr; - jmethodID iter_has_next = nullptr; - jmethodID iter_next = nullptr; - - jclass entry_cls = nullptr; - jmethodID entry_get_key = nullptr; - jmethodID entry_get_value = nullptr; - - jclass list_cls = nullptr; - jmethodID list_size = nullptr; - jmethodID list_get = nullptr; - - jclass throwable_cls = nullptr; - jmethodID throwable_to_string = nullptr; - jmethodID throwable_get_cause = nullptr; - - // Optional exception classes for structured error classification (S4). - jclass ssl_ex_cls = nullptr; - jclass cert_ex_cls = nullptr; - jclass socket_timeout_ex_cls = nullptr; - jclass connect_ex_cls = nullptr; - jclass unknown_host_ex_cls = nullptr; - jclass no_route_ex_cls = nullptr; - jclass socket_ex_cls = nullptr; - jclass eof_ex_cls = nullptr; -}; - -JniCache& GetJniCache() { - static auto* cache = new JniCache(); - return *cache; -} - -HttpErrorClass ClassifyJavaException(JNIEnv* env, jthrowable root_ex) { - auto& c = GetJniCache(); - if (root_ex == nullptr) { - return kHttpErrorOther; - } - - HttpErrorClass best = kHttpErrorOther; - LocalRef current(env, env->NewLocalRef(root_ex)); - for (int depth = 0; current && depth < 8; ++depth) { - if ((c.ssl_ex_cls != nullptr && - env->IsInstanceOf(current.get(), c.ssl_ex_cls) == JNI_TRUE) || - (c.cert_ex_cls != nullptr && - env->IsInstanceOf(current.get(), c.cert_ex_cls) == JNI_TRUE)) { - return kHttpErrorTls; - } - if (c.socket_timeout_ex_cls != nullptr && - env->IsInstanceOf(current.get(), c.socket_timeout_ex_cls) == JNI_TRUE) { - if (best == kHttpErrorOther) { - best = kHttpErrorTimeout; - } - } else if ((c.connect_ex_cls != nullptr && - env->IsInstanceOf(current.get(), c.connect_ex_cls) == - JNI_TRUE) || - (c.unknown_host_ex_cls != nullptr && - env->IsInstanceOf(current.get(), c.unknown_host_ex_cls) == - JNI_TRUE) || - (c.no_route_ex_cls != nullptr && - env->IsInstanceOf(current.get(), c.no_route_ex_cls) == - JNI_TRUE) || - (c.socket_ex_cls != nullptr && - env->IsInstanceOf(current.get(), c.socket_ex_cls) == - JNI_TRUE) || - (c.eof_ex_cls != nullptr && - env->IsInstanceOf(current.get(), c.eof_ex_cls) == JNI_TRUE)) { - if (best == kHttpErrorOther) { - best = kHttpErrorConnect; - } - } - - if (c.throwable_get_cause == nullptr) { - break; - } - jobject next = env->CallObjectMethod(current.get(), c.throwable_get_cause); - if (env->ExceptionCheck()) { - env->ExceptionClear(); - break; - } - if (next == nullptr || env->IsSameObject(current.get(), next) == JNI_TRUE) { - if (next != nullptr) { - env->DeleteLocalRef(next); - } - break; - } - current.reset(next); - } - return best; -} - -std::optional TakeJniException(JNIEnv* env) { - if (!env->ExceptionCheck()) { - return std::nullopt; - } - LocalRef ex(env, env->ExceptionOccurred()); - env->ExceptionClear(); - JniExceptionInfo info; - if (!ex) { - info.message = "Unknown JNI exception"; - return info; - } - info.error_class = ClassifyJavaException(env, ex.get()); - - // Reuse firebase::util::GetMessageFromException when util_android has been - // initialized, falling back to cached Throwable.toString() if HTTP is used - // before FirebaseApp initialization. - if (::firebase::util::throwable::GetClass() != nullptr && - ::firebase::util::throwable::GetMethodId( - ::firebase::util::throwable::kToString) != nullptr) { - info.message = ::firebase::util::GetMessageFromException(env, ex.get()); - if (!info.message.empty()) { - return info; - } - } - auto& c = GetJniCache(); - if (c.throwable_to_string != nullptr) { - LocalRef msg(env, static_cast(env->CallObjectMethod( - ex.get(), c.throwable_to_string))); - if (env->ExceptionCheck()) { - env->ExceptionClear(); - info.message = "Java exception thrown during HTTP request"; - return info; - } - info.message = ::firebase::util::JStringToString(env, msg.get()); - if (!info.message.empty()) { - return info; - } - } - info.message = "Java exception thrown during HTTP request"; - return info; -} - -jclass CacheGlobalClass(JNIEnv* env, const char* name) { - LocalRef local(env, env->FindClass(name)); - if (env->ExceptionCheck() || !local) { - env->ExceptionClear(); - return nullptr; - } - jobject global = env->NewGlobalRef(local.get()); - if (env->ExceptionCheck() || global == nullptr) { - env->ExceptionClear(); - return nullptr; - } - return static_cast(global); -} - -jmethodID CacheMethod(JNIEnv* env, jclass cls, const char* name, - const char* sig, bool* ok) { - if (!*ok || cls == nullptr) { - *ok = false; - return nullptr; - } - jmethodID mid = env->GetMethodID(cls, name, sig); - if (env->ExceptionCheck() || mid == nullptr) { - env->ExceptionClear(); - *ok = false; - return nullptr; - } - return mid; -} - -bool EnsureJniInitialized(JNIEnv* env) { - static std::mutex init_mutex; - std::lock_guard lock(init_mutex); - auto& c = GetJniCache(); - if (c.initialized) { - return true; - } - - bool ok = true; - c.throwable_cls = CacheGlobalClass(env, "java/lang/Throwable"); - c.throwable_to_string = CacheMethod(env, c.throwable_cls, "toString", - "()Ljava/lang/String;", &ok); - c.throwable_get_cause = CacheMethod(env, c.throwable_cls, "getCause", - "()Ljava/lang/Throwable;", &ok); - if (!ok) { - return false; - } - - // Exception classes for structured error classification (best-effort; all - // exist on Android API 1+). - c.ssl_ex_cls = CacheGlobalClass(env, "javax/net/ssl/SSLException"); - c.cert_ex_cls = - CacheGlobalClass(env, "java/security/cert/CertificateException"); - c.socket_timeout_ex_cls = - CacheGlobalClass(env, "java/net/SocketTimeoutException"); - c.connect_ex_cls = CacheGlobalClass(env, "java/net/ConnectException"); - c.unknown_host_ex_cls = - CacheGlobalClass(env, "java/net/UnknownHostException"); - c.no_route_ex_cls = CacheGlobalClass(env, "java/net/NoRouteToHostException"); - c.socket_ex_cls = CacheGlobalClass(env, "java/net/SocketException"); - c.eof_ex_cls = CacheGlobalClass(env, "java/io/EOFException"); - - c.url_cls = CacheGlobalClass(env, "java/net/URL"); - c.proxy_cls = CacheGlobalClass(env, "java/net/Proxy"); - c.inet_sock_addr_cls = CacheGlobalClass(env, "java/net/InetSocketAddress"); - c.http_conn_cls = CacheGlobalClass(env, "java/net/HttpURLConnection"); - c.output_stream_cls = CacheGlobalClass(env, "java/io/OutputStream"); - c.input_stream_cls = CacheGlobalClass(env, "java/io/InputStream"); - c.map_cls = CacheGlobalClass(env, "java/util/Map"); - c.set_cls = CacheGlobalClass(env, "java/util/Set"); - c.iter_cls = CacheGlobalClass(env, "java/util/Iterator"); - c.entry_cls = CacheGlobalClass(env, "java/util/Map$Entry"); - c.list_cls = CacheGlobalClass(env, "java/util/List"); - - if (!c.url_cls || !c.proxy_cls || !c.inet_sock_addr_cls || !c.http_conn_cls || - !c.output_stream_cls || !c.input_stream_cls || !c.map_cls || !c.set_cls || - !c.iter_cls || !c.entry_cls || !c.list_cls) { - return false; - } - - LocalRef proxy_type_cls(env, env->FindClass("java/net/Proxy$Type")); - if (env->ExceptionCheck() || !proxy_type_cls) { - env->ExceptionClear(); - return false; - } - jfieldID http_field = env->GetStaticFieldID(proxy_type_cls.get(), "HTTP", - "Ljava/net/Proxy$Type;"); - if (env->ExceptionCheck() || http_field == nullptr) { - env->ExceptionClear(); - return false; - } - LocalRef http_enum( - env, env->GetStaticObjectField(proxy_type_cls.get(), http_field)); - if (env->ExceptionCheck() || !http_enum) { - env->ExceptionClear(); - return false; - } - c.proxy_type_http = env->NewGlobalRef(http_enum.get()); - if (env->ExceptionCheck() || c.proxy_type_http == nullptr) { - env->ExceptionClear(); - return false; - } - - c.url_ctor = - CacheMethod(env, c.url_cls, "", "(Ljava/lang/String;)V", &ok); - c.url_open_conn = CacheMethod(env, c.url_cls, "openConnection", - "()Ljava/net/URLConnection;", &ok); - c.url_open_conn_proxy = - CacheMethod(env, c.url_cls, "openConnection", - "(Ljava/net/Proxy;)Ljava/net/URLConnection;", &ok); - - c.proxy_ctor = - CacheMethod(env, c.proxy_cls, "", - "(Ljava/net/Proxy$Type;Ljava/net/SocketAddress;)V", &ok); - c.inet_sock_addr_ctor = CacheMethod(env, c.inet_sock_addr_cls, "", - "(Ljava/lang/String;I)V", &ok); - - c.set_request_method = CacheMethod(env, c.http_conn_cls, "setRequestMethod", - "(Ljava/lang/String;)V", &ok); - c.set_request_property = - CacheMethod(env, c.http_conn_cls, "setRequestProperty", - "(Ljava/lang/String;Ljava/lang/String;)V", &ok); - c.add_request_property = - CacheMethod(env, c.http_conn_cls, "addRequestProperty", - "(Ljava/lang/String;Ljava/lang/String;)V", &ok); - c.set_use_caches = - CacheMethod(env, c.http_conn_cls, "setUseCaches", "(Z)V", &ok); - c.set_connect_timeout = - CacheMethod(env, c.http_conn_cls, "setConnectTimeout", "(I)V", &ok); - c.set_read_timeout = - CacheMethod(env, c.http_conn_cls, "setReadTimeout", "(I)V", &ok); - c.set_instance_follow_redirects = CacheMethod( - env, c.http_conn_cls, "setInstanceFollowRedirects", "(Z)V", &ok); - c.set_do_output = - CacheMethod(env, c.http_conn_cls, "setDoOutput", "(Z)V", &ok); - c.set_fixed_len_streaming = CacheMethod( - env, c.http_conn_cls, "setFixedLengthStreamingMode", "(J)V", &ok); - c.set_chunked_streaming = - CacheMethod(env, c.http_conn_cls, "setChunkedStreamingMode", "(I)V", &ok); - c.get_output_stream = CacheMethod(env, c.http_conn_cls, "getOutputStream", - "()Ljava/io/OutputStream;", &ok); - c.get_response_code = - CacheMethod(env, c.http_conn_cls, "getResponseCode", "()I", &ok); - c.get_response_message = CacheMethod( - env, c.http_conn_cls, "getResponseMessage", "()Ljava/lang/String;", &ok); - c.get_header_fields = CacheMethod(env, c.http_conn_cls, "getHeaderFields", - "()Ljava/util/Map;", &ok); - c.get_input_stream = CacheMethod(env, c.http_conn_cls, "getInputStream", - "()Ljava/io/InputStream;", &ok); - c.get_error_stream = CacheMethod(env, c.http_conn_cls, "getErrorStream", - "()Ljava/io/InputStream;", &ok); - c.disconnect = CacheMethod(env, c.http_conn_cls, "disconnect", "()V", &ok); - - c.output_write = - CacheMethod(env, c.output_stream_cls, "write", "([BII)V", &ok); - c.output_flush = CacheMethod(env, c.output_stream_cls, "flush", "()V", &ok); - c.output_close = CacheMethod(env, c.output_stream_cls, "close", "()V", &ok); - - c.input_read = CacheMethod(env, c.input_stream_cls, "read", "([BII)I", &ok); - c.input_close = CacheMethod(env, c.input_stream_cls, "close", "()V", &ok); - - c.map_entry_set = - CacheMethod(env, c.map_cls, "entrySet", "()Ljava/util/Set;", &ok); - c.set_iterator = - CacheMethod(env, c.set_cls, "iterator", "()Ljava/util/Iterator;", &ok); - c.iter_has_next = CacheMethod(env, c.iter_cls, "hasNext", "()Z", &ok); - c.iter_next = - CacheMethod(env, c.iter_cls, "next", "()Ljava/lang/Object;", &ok); - c.entry_get_key = - CacheMethod(env, c.entry_cls, "getKey", "()Ljava/lang/Object;", &ok); - c.entry_get_value = - CacheMethod(env, c.entry_cls, "getValue", "()Ljava/lang/Object;", &ok); - c.list_size = CacheMethod(env, c.list_cls, "size", "()I", &ok); - c.list_get = - CacheMethod(env, c.list_cls, "get", "(I)Ljava/lang/Object;", &ok); - - if (!ok) { - return false; - } - - c.initialized = true; - return true; -} - -struct AndroidCancelHandle { - std::mutex mutex; - jobject conn_global = nullptr; - jobject out_stream_global = nullptr; - jobject in_stream_global = nullptr; - - void ClearAll(JNIEnv* env) { - std::lock_guard lock(mutex); - if (in_stream_global != nullptr) { - env->DeleteGlobalRef(in_stream_global); - in_stream_global = nullptr; - } - if (out_stream_global != nullptr) { - env->DeleteGlobalRef(out_stream_global); - out_stream_global = nullptr; - } - if (conn_global != nullptr) { - env->DeleteGlobalRef(conn_global); - conn_global = nullptr; - } - } - - void ClearOutputStream(JNIEnv* env) { - std::lock_guard lock(mutex); - if (out_stream_global != nullptr) { - env->DeleteGlobalRef(out_stream_global); - out_stream_global = nullptr; - } - } - - void AbortNow(JNIEnv* env) { - if (env == nullptr) { - return; - } - auto& c = GetJniCache(); - jobject conn_ref = nullptr; - jobject in_ref = nullptr; - jobject out_ref = nullptr; - { - std::lock_guard lock(mutex); - if (conn_global != nullptr) { - conn_ref = env->NewLocalRef(conn_global); - } - if (in_stream_global != nullptr) { - in_ref = env->NewLocalRef(in_stream_global); - } - if (out_stream_global != nullptr) { - out_ref = env->NewLocalRef(out_stream_global); - } - } - LocalRef local_conn(env, conn_ref); - LocalRef local_in(env, in_ref); - LocalRef local_out(env, out_ref); - - // Call conn.disconnect() FIRST to unblock any worker thread waiting inside - // InputStream.read() / OutputStream.write() before closing the streams, - // avoiding cross-thread stream monitor contention in OkHttp/Conscrypt. - if (local_conn && c.disconnect != nullptr) { - env->CallVoidMethod(local_conn.get(), c.disconnect); - if (env->ExceptionCheck()) env->ExceptionClear(); - } - if (local_in && c.input_close != nullptr) { - env->CallVoidMethod(local_in.get(), c.input_close); - if (env->ExceptionCheck()) env->ExceptionClear(); - } - if (local_out && c.output_close != nullptr) { - env->CallVoidMethod(local_out.get(), c.output_close); - if (env->ExceptionCheck()) env->ExceptionClear(); - } - } -}; - -// Dedicated background dispatcher for asynchronous JNI socket cancellation so -// `HttpCancelRequestInternal` / `HttpDestroyRequestInternal` invoked on the -// Android UI or Unity main thread never triggers `NetworkOnMainThreadException` -// or blocks the caller on Java stream teardown. -class AndroidCancelDispatcher { - public: - static AndroidCancelDispatcher& Instance() { - static auto* dispatcher = new AndroidCancelDispatcher(); - return *dispatcher; - } - - void Enqueue(const std::shared_ptr& handle) { - bool start_thread = false; - { - std::lock_guard lock(mutex_); - queue_.push_back(handle); - if (!started_) { - started_ = true; - start_thread = true; - } - } - cv_.notify_one(); - if (start_thread) { - std::thread([this]() { RunLoop(); }).detach(); - } - } - - private: - void RunLoop() { - JNIEnv* env = ResolveThreadsafeJNIEnv(); - while (true) { - std::shared_ptr next; - { - std::unique_lock lock(mutex_); - cv_.wait(lock, [this]() { return !queue_.empty(); }); - next = std::move(queue_.front()); - queue_.pop_front(); - } - if (env == nullptr) { - env = ResolveThreadsafeJNIEnv(); - } - if (env != nullptr && next) { - next->AbortNow(env); - } - } - } - - std::mutex mutex_; - std::condition_variable cv_; - std::deque> queue_; - bool started_ = false; -}; - -bool IsRedirectStatus(int32_t status) { - return status == 301 || status == 302 || status == 303 || status == 307 || - status == 308; -} - -std::string_view FindHeaderValueIgnoreCase( - const std::vector>& headers, - std::string_view target) { - for (const auto& kv : headers) { - if (AsciiEqualsIgnoreCase(kv.first, target)) { - return kv.second; - } - } - return {}; -} - -struct AndroidHopState { - std::string current_url; - std::string active_method; - std::vector> active_headers; - int64_t active_content_len = kNoRequestContent; -}; - -struct AndroidResponseHead { - int32_t status_code = 0; - std::string reason; - std::vector> headers; -}; - -// Opens and configures a Java HttpURLConnection for one request hop. -LocalRef BuildAndroidRequestConnection( - JNIEnv* env, const std::shared_ptr& op, - const std::shared_ptr& cancel_handle, - const AndroidHopState& hop) { - auto& c = GetJniCache(); - LocalRef empty(env, nullptr); - - LocalRef jurl_str(env, env->NewStringUTF(hop.current_url.c_str())); - if (auto ex = TakeJniException(env); ex || !jurl_str) { - op->MarkFailed(ex ? ex->message : "Failed to allocate JNI URL string", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - LocalRef jurl( - env, env->NewObject(c.url_cls, c.url_ctor, jurl_str.get())); - if (auto ex = TakeJniException(env); ex || !jurl) { - op->MarkFailed(ex ? ex->message : "Invalid URL", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - - LocalRef conn(env, nullptr); - if (!op->proxy_url.empty()) { - auto proxy_hp = ParseProxyHostPort(op->proxy_url); - if (!proxy_hp) { - op->MarkFailed("Invalid or unsupported proxy URL.", kHttpErrorOther); - return empty; - } - LocalRef jhost(env, env->NewStringUTF(proxy_hp->first.c_str())); - if (auto ex = TakeJniException(env); ex || !jhost) { - op->MarkFailed(ex ? ex->message : "Failed to allocate proxy host string", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - LocalRef jsock_addr( - env, env->NewObject(c.inet_sock_addr_cls, c.inet_sock_addr_ctor, - jhost.get(), static_cast(proxy_hp->second))); - if (auto ex = TakeJniException(env); ex || !jsock_addr) { - op->MarkFailed( - ex ? ex->message : "Failed to construct proxy socket address", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - LocalRef jproxy( - env, env->NewObject(c.proxy_cls, c.proxy_ctor, c.proxy_type_http, - jsock_addr.get())); - if (auto ex = TakeJniException(env); ex || !jproxy) { - op->MarkFailed(ex ? ex->message : "Failed to construct Java Proxy", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - conn.reset(env->CallObjectMethod(jurl.get(), c.url_open_conn_proxy, - jproxy.get())); - } else { - conn.reset(env->CallObjectMethod(jurl.get(), c.url_open_conn)); - } - if (auto ex = TakeJniException(env); ex || !conn) { - op->MarkFailed(ex ? ex->message : "Failed to open HttpURLConnection", - ex ? ex->error_class : kHttpErrorConnect); - return empty; - } - if (env->IsInstanceOf(conn.get(), c.http_conn_cls) != JNI_TRUE) { - op->MarkFailed( - "Unsupported URI scheme; URLConnection is not an HttpURLConnection.", - kHttpErrorOther); - return empty; - } - - { - jobject g_conn = env->NewGlobalRef(conn.get()); - if (auto ex = TakeJniException(env); ex || g_conn == nullptr) { - op->MarkFailed(ex ? ex->message : "Failed to retain HttpURLConnection", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - std::lock_guard lock(cancel_handle->mutex); - cancel_handle->conn_global = g_conn; - } - if (op->IsCanceled()) { - return empty; - } - - env->CallVoidMethod(conn.get(), c.set_use_caches, JNI_FALSE); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return empty; - } - env->CallVoidMethod(conn.get(), c.set_connect_timeout, 60000); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return empty; - } - env->CallVoidMethod(conn.get(), c.set_read_timeout, 0); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return empty; - } - // Handle redirects explicitly so cross-origin redirects strip sensitive - // Firebase credentials and HTTPS -> HTTP downgrades are rejected. - env->CallVoidMethod(conn.get(), c.set_instance_follow_redirects, JNI_FALSE); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return empty; - } - - LocalRef jmethod(env, env->NewStringUTF(hop.active_method.c_str())); - if (auto ex = TakeJniException(env); ex || !jmethod) { - op->MarkFailed(ex ? ex->message : "Failed to allocate HTTP method string", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - env->CallVoidMethod(conn.get(), c.set_request_method, jmethod.get()); - if (auto ex = TakeJniException(env)) { - if (AsciiEqualsIgnoreCase(hop.active_method, "PATCH")) { - // Fallback for HttpURLConnection implementations that reject PATCH. - LocalRef jpost(env, env->NewStringUTF("POST")); - LocalRef joverride_k( - env, env->NewStringUTF("X-HTTP-Method-Override")); - LocalRef joverride_v(env, env->NewStringUTF("PATCH")); - if (auto ex_alloc = TakeJniException(env); - ex_alloc || !jpost || !joverride_k || !joverride_v) { - op->MarkFailed( - ex_alloc ? ex_alloc->message : "Failed to allocate PATCH override", - ex_alloc ? ex_alloc->error_class : kHttpErrorOther); - return empty; - } - env->CallVoidMethod(conn.get(), c.set_request_method, jpost.get()); - if (auto ex2 = TakeJniException(env)) { - op->MarkFailed(ex2->message, ex2->error_class); - return empty; - } - env->CallVoidMethod(conn.get(), c.set_request_property, - joverride_k.get(), joverride_v.get()); - if (auto ex3 = TakeJniException(env)) { - op->MarkFailed(ex3->message, ex3->error_class); - return empty; - } - } else { - op->MarkFailed(ex->message, ex->error_class); - return empty; - } - } - - bool has_accept_encoding = false; - std::unordered_set seen_headers; - for (const auto& kv : hop.active_headers) { - if (AsciiEqualsIgnoreCase(kv.first, "Accept-Encoding")) { - has_accept_encoding = true; - } - LocalRef jk(env, env->NewStringUTF(kv.first.c_str())); - if (auto ex = TakeJniException(env); ex || !jk) { - op->MarkFailed(ex ? ex->message : "Failed to allocate header name", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - LocalRef jv(env, env->NewStringUTF(kv.second.c_str())); - if (auto ex = TakeJniException(env); ex || !jv) { - op->MarkFailed(ex ? ex->message : "Failed to allocate header value", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - jmethodID header_mid = seen_headers.insert(ToLowerAscii(kv.first)).second - ? c.set_request_property - : c.add_request_property; - env->CallVoidMethod(conn.get(), header_mid, jk.get(), jv.get()); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return empty; - } - } - if (!has_accept_encoding) { - // Match .NET HttpClientHandler (AutomaticDecompression = None) and - // Desktop libcurl so Android's OkHttp BridgeInterceptor does not inject - // `Accept-Encoding: gzip`, strip Content-Length, buffer SSE frames, or - // corrupt Range ETag / byte offsets. - LocalRef jae_k(env, env->NewStringUTF("Accept-Encoding")); - LocalRef jae_v(env, env->NewStringUTF("identity")); - if (auto ex = TakeJniException(env); ex || !jae_k || !jae_v) { - op->MarkFailed(ex ? ex->message : "Failed to allocate Accept-Encoding", - ex ? ex->error_class : kHttpErrorOther); - return empty; - } - env->CallVoidMethod(conn.get(), c.set_request_property, jae_k.get(), - jae_v.get()); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return empty; - } - } - - return conn; -} - -// Streams request body bytes when the HTTP method permits a body. -// Returns true if the caller should proceed to ReadAndroidResponseHeaders -// (including when an upload write failed mid-stream and an early 4xx response -// may be readable via getResponseCode()), or false if the operation already -// failed or was canceled. -bool SendAndroidRequestBody( - JNIEnv* env, const std::shared_ptr& op, - const std::shared_ptr& cancel_handle, jobject conn, - const AndroidHopState& hop, std::optional* out_write_err) { - auto& c = GetJniCache(); - - // Never call setDoOutput(true) on GET or HEAD because HttpURLConnection - // silently rewrites GET into POST (A1). - bool is_get_or_head = AsciiEqualsIgnoreCase(hop.active_method, "GET") || - AsciiEqualsIgnoreCase(hop.active_method, "HEAD"); - if (is_get_or_head) { - if (hop.active_content_len > 0 || - hop.active_content_len == kChunkedRequestContent) { - op->MarkFailed("GET and HEAD requests cannot send a request body.", - kHttpErrorOther); - return false; - } - return true; - } - - bool send_body = - hop.active_content_len >= 0 || - hop.active_content_len == kChunkedRequestContent || - (hop.active_content_len == kNoRequestContent && - (AsciiEqualsIgnoreCase(hop.active_method, "POST") || - AsciiEqualsIgnoreCase(hop.active_method, "PUT") || - AsciiEqualsIgnoreCase(hop.active_method, "PATCH"))); - if (!send_body) { - return true; - } - - env->CallVoidMethod(conn, c.set_do_output, JNI_TRUE); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return false; - } - if (hop.active_content_len == kNoRequestContent || - hop.active_content_len == 0) { - env->CallVoidMethod(conn, c.set_fixed_len_streaming, static_cast(0)); - } else if (hop.active_content_len > 0) { - env->CallVoidMethod(conn, c.set_fixed_len_streaming, - static_cast(hop.active_content_len)); - } else { - env->CallVoidMethod(conn, c.set_chunked_streaming, static_cast(65536)); - } - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return false; - } - - LocalRef out_stream(env, - env->CallObjectMethod(conn, c.get_output_stream)); - if (auto ex = TakeJniException(env); ex || !out_stream) { - if (!op->IsCanceled()) { - op->MarkFailed(ex ? ex->message : "Failed to open request OutputStream", - ex ? ex->error_class : kHttpErrorConnect); - } - return false; - } - { - jobject g_out = env->NewGlobalRef(out_stream.get()); - if (auto ex = TakeJniException(env); ex || g_out == nullptr) { - op->MarkFailed(ex ? ex->message : "Failed to retain request OutputStream", - ex ? ex->error_class : kHttpErrorOther); - return false; - } - std::lock_guard lock(cancel_handle->mutex); - cancel_handle->out_stream_global = g_out; - } - - bool write_failed = false; - if (hop.active_content_len > 0 || - hop.active_content_len == kChunkedRequestContent) { - constexpr size_t kWriteSlice = 64 * 1024; - LocalRef jwrite_buf( - env, env->NewByteArray(static_cast(kWriteSlice))); - if (auto ex = TakeJniException(env); ex || !jwrite_buf) { - cancel_handle->ClearOutputStream(env); - op->MarkFailed(ex ? ex->message : "Failed to allocate JNI write buffer", - ex ? ex->error_class : kHttpErrorOther); - return false; - } - std::vector scratch(kWriteSlice); - while (!op->IsCanceled()) { - bool eof = false; - size_t n = op->PopRequestBytes(scratch.data(), kWriteSlice, &eof); - if (n > 0) { - env->SetByteArrayRegion(jwrite_buf.get(), 0, static_cast(n), - reinterpret_cast(scratch.data())); - if (auto ex = TakeJniException(env)) { - cancel_handle->ClearOutputStream(env); - op->MarkFailed(ex->message, ex->error_class); - return false; - } - env->CallVoidMethod(out_stream.get(), c.output_write, jwrite_buf.get(), - 0, static_cast(n)); - if (auto ex = TakeJniException(env)) { - if (op->IsCanceled()) { - cancel_handle->ClearOutputStream(env); - return false; - } - // The server may have sent an early 4xx (such as 413) and closed - // its read side. Save the write exception, close the upload pipe so - // the caller stops writing, and fall through to try getResponseCode() - // before failing the operation (A2). - *out_write_err = std::move(*ex); - write_failed = true; - op->MarkRequestWriteClosed(); - break; - } - } else if (eof) { - break; - } else { - std::unique_lock lock(op->mutex); - op->req_cv.wait(lock, [&op]() { - return !op->req_chunks.empty() || op->req_eof || op->failed || - op->IsCanceled(); - }); - } - } - } - - if (!write_failed) { - env->CallVoidMethod(out_stream.get(), c.output_flush); - if (env->ExceptionCheck()) env->ExceptionClear(); - } - env->CallVoidMethod(out_stream.get(), c.output_close); - if (auto ex = TakeJniException(env)) { - if (!write_failed && !op->IsCanceled()) { - *out_write_err = std::move(*ex); - op->MarkRequestWriteClosed(); - } - } - cancel_handle->ClearOutputStream(env); - return !op->IsCanceled(); -} - -// Reads HTTP status code, reason phrase, and response headers from `conn`. -bool ReadAndroidResponseHeaders( - JNIEnv* env, const std::shared_ptr& op, jobject conn, - const std::optional& write_err, - AndroidResponseHead* out_head) { - auto& c = GetJniCache(); - - jint status_code = env->CallIntMethod(conn, c.get_response_code); - if (auto ex = TakeJniException(env)) { - if (!op->IsCanceled()) { - if (write_err && ex->error_class == kHttpErrorOther && - write_err->error_class != kHttpErrorOther) { - op->MarkFailed(write_err->message, write_err->error_class); - } else { - op->MarkFailed(ex->message, ex->error_class); - } - } - return false; - } - if (status_code <= 0) { - if (!op->IsCanceled()) { - if (write_err) { - op->MarkFailed(write_err->message, write_err->error_class); - } else { - op->MarkFailed("HttpURLConnection returned invalid HTTP status code.", - kHttpErrorOther); - } - } - return false; - } - - out_head->status_code = static_cast(status_code); - LocalRef jreason( - env, - static_cast(env->CallObjectMethod(conn, c.get_response_message))); - if (env->ExceptionCheck()) env->ExceptionClear(); - out_head->reason = ::firebase::util::JStringToString(env, jreason.get()); - out_head->headers.clear(); - - LocalRef header_map(env, - env->CallObjectMethod(conn, c.get_header_fields)); - if (!TakeJniException(env) && header_map) { - LocalRef entry_set( - env, env->CallObjectMethod(header_map.get(), c.map_entry_set)); - if (!TakeJniException(env) && entry_set) { - LocalRef iter( - env, env->CallObjectMethod(entry_set.get(), c.set_iterator)); - if (!TakeJniException(env) && iter) { - while (true) { - jboolean has_next = - env->CallBooleanMethod(iter.get(), c.iter_has_next); - if (TakeJniException(env) || has_next != JNI_TRUE) { - break; - } - LocalRef entry(env, - env->CallObjectMethod(iter.get(), c.iter_next)); - if (TakeJniException(env) || !entry) break; - LocalRef jkey( - env, static_cast( - env->CallObjectMethod(entry.get(), c.entry_get_key))); - if (TakeJniException(env) || !jkey) { - // HttpURLConnection maps the status line under a null key. - continue; - } - std::string key_str = - ::firebase::util::JStringToString(env, jkey.get()); - if (key_str.empty()) continue; - - LocalRef val_list( - env, env->CallObjectMethod(entry.get(), c.entry_get_value)); - if (TakeJniException(env) || !val_list) continue; - jint count = env->CallIntMethod(val_list.get(), c.list_size); - if (TakeJniException(env)) continue; - for (jint i = 0; i < count; ++i) { - LocalRef jval(env, - static_cast(env->CallObjectMethod( - val_list.get(), c.list_get, i))); - if (TakeJniException(env)) break; - if (jval) { - out_head->headers.emplace_back( - key_str, ::firebase::util::JStringToString(env, jval.get())); - } - } - } - } - } - } - return true; -} - -// Updates `hop` for a 3xx redirect response. Returns true to continue to the -// next redirect hop, or false after marking `op` failed. -bool ApplyAndroidRedirect(JNIEnv* env, const std::shared_ptr& op, - jobject conn, int redirect_count, int32_t status_code, - std::string_view location, AndroidHopState* hop) { - auto& c = GetJniCache(); - - // Close the redirect response stream so Android's ConnectionPool can reuse - // the socket before following the redirect. - LocalRef redir_stream( - env, env->CallObjectMethod(conn, c.get_input_stream)); - if (env->ExceptionCheck()) env->ExceptionClear(); - if (redir_stream) { - env->CallVoidMethod(redir_stream.get(), c.input_close); - if (env->ExceptionCheck()) env->ExceptionClear(); - } - - if (redirect_count == kMaxRedirects) { - op->MarkFailed("Maximum HTTP redirects exceeded.", kHttpErrorOther); - return false; - } - auto resolved = ResolveRedirectUrl(hop->current_url, location); - if (!resolved || (IsHttpsUrl(op->url) && !IsHttpsUrl(*resolved))) { - op->MarkFailed("Blocked unsafe or scheme-downgraded HTTP redirect.", - kHttpErrorOther); - return false; - } - bool same_origin = - IsSameOrigin(op->url, *resolved) && IsSameOrigin(hop->current_url, *resolved); - if ((status_code == 301 || status_code == 302 || status_code == 303) && - !AsciiEqualsIgnoreCase(hop->active_method, "GET") && - !AsciiEqualsIgnoreCase(hop->active_method, "HEAD")) { - hop->active_method = "GET"; - hop->active_content_len = kNoRequestContent; - op->MarkRequestWriteClosed(); - } else if (status_code == 303 && - AsciiEqualsIgnoreCase(hop->active_method, "HEAD")) { - hop->active_content_len = kNoRequestContent; - } else if (hop->active_content_len != kNoRequestContent && - hop->active_content_len != 0) { - op->MarkFailed("Cannot replay streamed request body across redirect.", - kHttpErrorOther); - return false; - } - - if (!same_origin || hop->active_content_len == kNoRequestContent) { - std::vector> filtered; - filtered.reserve(hop->active_headers.size()); - for (const auto& kv : hop->active_headers) { - if (!same_origin && (IsSensitiveRedirectHeader(kv.first) || - AsciiEqualsIgnoreCase(kv.first, "Host"))) { - continue; - } - if (hop->active_content_len == kNoRequestContent && - (AsciiEqualsIgnoreCase(kv.first, "Content-Type") || - AsciiEqualsIgnoreCase(kv.first, "Content-Length") || - AsciiEqualsIgnoreCase(kv.first, "Transfer-Encoding"))) { - continue; - } - filtered.push_back(kv); - } - hop->active_headers = std::move(filtered); - } - hop->current_url = std::move(*resolved); - return true; -} - -// Streams response body bytes from `conn` into `op` with bounded backpressure. -// Returns true on clean EOF. -bool ReadAndroidResponseBody( - JNIEnv* env, const std::shared_ptr& op, - const std::shared_ptr& cancel_handle, jobject conn) { - auto& c = GetJniCache(); - - LocalRef in_stream(env, - env->CallObjectMethod(conn, c.get_input_stream)); - if (env->ExceptionCheck() || !in_stream) { - env->ExceptionClear(); - in_stream.reset(env->CallObjectMethod(conn, c.get_error_stream)); - if (env->ExceptionCheck()) { - env->ExceptionClear(); - in_stream.reset(nullptr); - } - } - - if (!in_stream) { - op->MarkResponseComplete(); - return true; - } - - { - jobject g_in = env->NewGlobalRef(in_stream.get()); - if (auto ex = TakeJniException(env); ex || g_in == nullptr) { - op->MarkFailed(ex ? ex->message : "Failed to retain response InputStream", - ex ? ex->error_class : kHttpErrorOther); - return false; - } - std::lock_guard lock(cancel_handle->mutex); - cancel_handle->in_stream_global = g_in; - } - if (op->IsCanceled()) { - return false; - } - - constexpr size_t kReadSlice = 64 * 1024; - LocalRef jread_buf( - env, env->NewByteArray(static_cast(kReadSlice))); - if (auto ex = TakeJniException(env); ex || !jread_buf) { - op->MarkFailed(ex ? ex->message : "Failed to allocate JNI read buffer", - ex ? ex->error_class : kHttpErrorOther); - return false; - } - std::vector read_scratch(kReadSlice); - - while (!op->IsCanceled()) { - jint n = env->CallIntMethod(in_stream.get(), c.input_read, jread_buf.get(), - 0, static_cast(kReadSlice)); - if (auto ex = TakeJniException(env)) { - if (!op->IsCanceled()) { - op->MarkFailed(ex->message, ex->error_class); - } - return false; - } - if (n < 0) { - break; - } - if (n == 0) { - continue; - } - env->GetByteArrayRegion(jread_buf.get(), 0, n, - reinterpret_cast(read_scratch.data())); - if (auto ex = TakeJniException(env)) { - op->MarkFailed(ex->message, ex->error_class); - return false; - } - bool over_high_water = - op->PushResponseBytes(read_scratch.data(), static_cast(n)); - if (over_high_water && !op->IsCanceled()) { - std::unique_lock lock(op->mutex); - op->resp_cv.wait(lock, [&op]() { - return op->resp_buffered_bytes <= kLowWaterResponseBytes || - op->IsCanceled() || op->failed; - }); - } - } - - if (op->IsCanceled()) { - return false; - } - - // Close the response stream so Android's ConnectionPool can reuse the live - // TLS connection; do not call conn.disconnect() on normal completion. - env->CallVoidMethod(in_stream.get(), c.input_close); - if (env->ExceptionCheck()) env->ExceptionClear(); - op->MarkResponseComplete(); - return true; -} - -void ExecuteAndroidOperation(JNIEnv* env, - const std::shared_ptr& op) { - if (!EnsureJniInitialized(env)) { - op->MarkFailed("Failed to initialize Android JNI HTTP bindings.", - kHttpErrorOther); - return; - } - if (!IsHttpOrHttpsUrl(op->url)) { - op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", - kHttpErrorOther); - return; - } - - auto cancel_handle = std::make_shared(); - { - std::lock_guard lock(op->mutex); - if (op->IsCanceled()) { - return; - } - op->on_cancel = [cancel_handle]() { - AndroidCancelDispatcher::Instance().Enqueue(cancel_handle); - }; - } - - bool completed_cleanly = false; - struct CleanupGuard { - JNIEnv* env; - std::shared_ptr handle; - bool* completed_cleanly; - ~CleanupGuard() { - if (!*completed_cleanly) { - handle->AbortNow(env); - } - handle->ClearAll(env); - } - } guard{env, cancel_handle, &completed_cleanly}; - - AndroidHopState hop; - hop.current_url = op->url; - hop.active_method = op->method; - hop.active_headers = op->request_headers; - hop.active_content_len = op->content_length; - - for (int redirect_count = 0; redirect_count <= kMaxRedirects; - ++redirect_count) { - cancel_handle->ClearAll(env); - - LocalRef conn = - BuildAndroidRequestConnection(env, op, cancel_handle, hop); - if (!conn) { - return; - } - - std::optional write_err; - if (!SendAndroidRequestBody(env, op, cancel_handle, conn.get(), hop, - &write_err)) { - return; - } - - AndroidResponseHead head; - if (!ReadAndroidResponseHeaders(env, op, conn.get(), write_err, &head)) { - return; - } - - std::string_view location = - FindHeaderValueIgnoreCase(head.headers, "Location"); - if (IsRedirectStatus(head.status_code) && !location.empty()) { - if (!ApplyAndroidRedirect(env, op, conn.get(), redirect_count, - head.status_code, location, &hop)) { - return; - } - continue; - } - - op->CommitResponseHeaders(head.status_code, head.reason, - std::move(head.headers)); - if (op->IsCanceled()) { - return; - } - - completed_cleanly = - ReadAndroidResponseBody(env, op, cancel_handle, conn.get()); - return; - } -} - -class AndroidHttpThreadPool { - public: - static AndroidHttpThreadPool& Instance() { - static auto* pool = new AndroidHttpThreadPool(); - return *pool; - } - - void Enqueue(const std::shared_ptr& op) { - // Capture JavaVM on the caller thread if an App is already initialized so - // newly spawned workers immediately see a cached JavaVM*. - (void)ResolveJavaVM(); - bool spawn_worker = false; - { - std::lock_guard lock(mutex_); - queue_.push_back(op); - if (queue_.size() > idle_workers_ + starting_workers_ && - active_workers_ < kMaxWorkers) { - ++active_workers_; - ++starting_workers_; - spawn_worker = true; - } - } - cv_.notify_one(); - if (spawn_worker) { - std::thread([this]() { WorkerLoop(); }).detach(); - } - } - - private: - // Matches Desktop's CURLMOPT_MAX_TOTAL_CONNECTIONS (64) so concurrent open - // SSE / GetStreamAsync() streams never starve short requests. - static constexpr size_t kMaxWorkers = 64; - - void WorkerLoop() { - JNIEnv* env = ResolveThreadsafeJNIEnv(); - - { - std::lock_guard lock(mutex_); - --starting_workers_; - } - - while (true) { - std::shared_ptr next; - { - std::unique_lock lock(mutex_); - if (queue_.empty()) { - ++idle_workers_; - bool has_work = cv_.wait_for(lock, std::chrono::seconds(30), - [this]() { return !queue_.empty(); }); - --idle_workers_; - if (!has_work) { - --active_workers_; - break; - } - } - next = std::move(queue_.front()); - queue_.pop_front(); - } - - if (env == nullptr) { - env = ResolveThreadsafeJNIEnv(); - } - if (env == nullptr) { - next->MarkFailed("Android JavaVM / JNIEnv is unavailable.", - kHttpErrorOther); - } else { - ExecuteAndroidOperation(env, next); - } - } - } - - std::mutex mutex_; - std::condition_variable cv_; - std::deque> queue_; - size_t active_workers_ = 0; - size_t idle_workers_ = 0; - size_t starting_workers_ = 0; -}; - -} // namespace - -void SetAndroidJavaVM(JavaVM* vm) { - if (vm != nullptr) { - g_android_jvm.store(vm, std::memory_order_release); - } -} - -void StartPlatformHttpOperation(const std::shared_ptr& op) { - AndroidHttpThreadPool::Instance().Enqueue(op); -} - -} // namespace http -} // namespace firebase diff --git a/app/http/http_transport_curl.cc b/app/http/http_transport_curl.cc index eba4271df5..a837aaca57 100644 --- a/app/http/http_transport_curl.cc +++ b/app/http/http_transport_curl.cc @@ -31,6 +31,9 @@ #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" @@ -117,6 +120,18 @@ std::optional ApplyCurlConnectionOptions( 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); diff --git a/app/http/http_transport_curl_android.cc b/app/http/http_transport_curl_android.cc new file mode 100644 index 0000000000..eb9b51750b --- /dev/null +++ b/app/http/http_transport_curl_android.cc @@ -0,0 +1,157 @@ +/* + * 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 "app/http/http_transport_curl_platform.h" +#include "app/rest/curl/curl_handles.h" +#include "curl/curl.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; +} + +// Returns the system CA certificates as one PEM bundle, or nullptr when none +// could be read. A successful read is kept for the life of the process, so +// libcurl can reference it without copying; a failed one is retried by the +// next request. +const std::string* SystemRootsPem() { + static std::mutex* const mutex = new std::mutex(); + static const std::string* roots = nullptr; + std::lock_guard lock(*mutex); + if (roots == nullptr) { + for (const char* directory : kSystemCaDirectories) { + std::string pem = internal::ReadPemCertificatesFromDirectory(directory); + if (!pem.empty()) { + roots = new std::string(std::move(pem)); + break; + } + } + } + return roots; +} + +} // namespace + +CURLcode ApplyAndroidTlsSettings(CURL* easy) { + CURLcode first_error = CURLE_OK; +#ifdef FIREBASE_HTTP_BUNDLED_BORINGSSL + ApplyOpt(easy, CURLOPT_SSL_EC_CURVES, kKeyExchangeGroups, &first_error); +#endif // FIREBASE_HTTP_BUNDLED_BORINGSSL + + const std::string* roots = SystemRootsPem(); + if (roots == nullptr) { + return CURLE_SSL_CACERT_BADFILE; + } + curl_blob blob; + blob.data = const_cast(roots->data()); + blob.len = roots->size(); + blob.flags = CURL_BLOB_NOCOPY; + ApplyOpt(easy, CURLOPT_CAINFO_BLOB, &blob, &first_error); + ApplyOpt(easy, CURLOPT_PROXY_CAINFO_BLOB, &blob, &first_error); + return first_error; +} + +namespace internal { + +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_platform.h b/app/http/http_transport_curl_platform.h new file mode 100644 index 0000000000..0f3ccf568c --- /dev/null +++ b/app/http/http_transport_curl_platform.h @@ -0,0 +1,65 @@ +/* + * 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 "curl/curl.h" + +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: +// - offers the key-exchange groups `X25519MLKEM768:X25519:P-256:P-384` +// (when built with `FIREBASE_HTTP_BUNDLED_BORINGSSL`), and +// - hands libcurl the system CA certificates as an in-memory PEM bundle +// (`CURLOPT_CAINFO_BLOB`, and the same for the TLS leg to an HTTPS proxy). +// The bundle is read once per process, 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 read; 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); + +} // namespace internal + +} // namespace http +} // namespace firebase + +#endif // FIREBASE_APP_HTTP_HTTP_TRANSPORT_CURL_PLATFORM_H_ diff --git a/cmake/external/CMakeLists.txt b/cmake/external/CMakeLists.txt index 3cfdd8e830..46684edb4b 100644 --- a/cmake/external/CMakeLists.txt +++ b/cmake/external/CMakeLists.txt @@ -34,6 +34,14 @@ if (${FIREBASE_EXTERNAL_PLATFORM} STREQUAL "DESKTOP") include(zlib) endif() +# The Android native HTTP transport (app/http) 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") + 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..dfc06894ed 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) @@ -78,6 +79,7 @@ function(download_external_sources) -DFIREBASE_DOWNLOAD_DIR=${FIREBASE_DOWNLOAD_DIR} -DFIREBASE_EXTERNAL_PLATFORM=${external_platform} -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 +273,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. From 346b1718151c150b8d19761ede58b94e1d2f413a Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 30 Nov 2026 18:59:36 +0000 Subject: [PATCH 12/16] [App][HTTP] Android: parse the system roots once into a shared X509_STORE libcurl parses a CURLOPT_CAINFO_BLOB again for every new TLS connection. The roots are now parsed once into an X509_STORE that each connection to the server takes with CURLOPT_SSL_CTX_FUNCTION (SSL_CTX_set1_verify_cert_store). The blob stays for HTTPS proxies. A load that finds no certificates is still retried by the next request. --- app/http/http_transport_curl_android.cc | 114 +++++++++++++++++++----- app/http/http_transport_curl_platform.h | 49 ++++++++-- 2 files changed, 132 insertions(+), 31 deletions(-) diff --git a/app/http/http_transport_curl_android.cc b/app/http/http_transport_curl_android.cc index eb9b51750b..2cd2046f8e 100644 --- a/app/http/http_transport_curl_android.cc +++ b/app/http/http_transport_curl_android.cc @@ -19,14 +19,21 @@ #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 { @@ -94,48 +101,111 @@ std::string ExtractPemCertificates(std::string_view contents) { return pem; } -// Returns the system CA certificates as one PEM bundle, or nullptr when none -// could be read. A successful read is kept for the life of the process, so -// libcurl can reference it without copying; a failed one is retried by the -// next request. -const std::string* SystemRootsPem() { - static std::mutex* const mutex = new std::mutex(); - static const std::string* roots = nullptr; - std::lock_guard lock(*mutex); - if (roots == nullptr) { - for (const char* directory : kSystemCaDirectories) { - std::string pem = internal::ReadPemCertificatesFromDirectory(directory); - if (!pem.empty()) { - roots = new std::string(std::move(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; } } - return roots; + 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 - const std::string* roots = SystemRootsPem(); - if (roots == nullptr) { - return CURLE_SSL_CACERT_BADFILE; - } + // 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. + 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(roots->data()); - blob.len = roots->size(); + blob.data = const_cast(pem_.data()); + blob.len = pem_.size(); blob.flags = CURL_BLOB_NOCOPY; - ApplyOpt(easy, CURLOPT_CAINFO_BLOB, &blob, &first_error); ApplyOpt(easy, CURLOPT_PROXY_CAINFO_BLOB, &blob, &first_error); return first_error; } -namespace internal { +int TrustStore::load_count() const { + std::lock_guard lock(mutex_); + return load_count_; +} std::string ReadPemCertificatesFromDirectory(const std::string& directory) { std::string pem; diff --git a/app/http/http_transport_curl_platform.h b/app/http/http_transport_curl_platform.h index 0f3ccf568c..72b7545c7b 100644 --- a/app/http/http_transport_curl_platform.h +++ b/app/http/http_transport_curl_platform.h @@ -20,10 +20,14 @@ #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 { @@ -35,16 +39,12 @@ inline constexpr char kAndroidNoTrustedRootsError[] = // 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: -// - offers the key-exchange groups `X25519MLKEM768:X25519:P-256:P-384` -// (when built with `FIREBASE_HTTP_BUNDLED_BORINGSSL`), and -// - hands libcurl the system CA certificates as an in-memory PEM bundle -// (`CURLOPT_CAINFO_BLOB`, and the same for the TLS leg to an HTTPS proxy). -// The bundle is read once per process, from -// `/apex/com.android.conscrypt/cacerts` or, when that has no certificates, -// `/system/etc/security/cacerts`. +// 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 read; the +// 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); @@ -57,6 +57,37 @@ namespace internal { // 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 From e1adac5ca28bf36afe459b75091bccacab105884 Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 30 Nov 2026 18:59:36 +0000 Subject: [PATCH 13/16] [App][HTTP] Make the Android transport opt-in (FIREBASE_ANDROID_HTTP_CURL) Off by default: an Android build of the C++ SDK then neither adds app/http nor downloads and builds libcurl and BoringSSL. --- CMakeLists.txt | 19 ++++++++++++------- app/CMakeLists.txt | 7 +++++-- cmake/external/CMakeLists.txt | 10 ++++++---- cmake/external_rules.cmake | 1 + 4 files changed, 24 insertions(+), 13 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4f1b90c38b..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,11 +429,13 @@ if((FIREBASE_INCLUDE_DATABASE AND DESKTOP) AND NOT FIREBASE_INCLUDE_FIRESTORE) add_external_library(leveldb) endif() -# The Android native HTTP transport (app/http) 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 NOT FIREBASE_CPP_USE_PRIOR_GRADLE_BUILD) - set(FIREBASE_ANDROID_HTTP_CURL ON) +# 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.") @@ -462,12 +467,12 @@ if(ANDROID AND NOT FIREBASE_CPP_USE_PRIOR_GRADLE_BUILD) # BoringSSL has the function, so state the result instead. set(HAVE_SSL_SET0_WBIO 1) else() - set(FIREBASE_ANDROID_HTTP_CURL OFF) + 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_ANDROID_HTTP_CURL) +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 diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 4c1b0f0a1e..6d92dc13b4 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -391,8 +391,11 @@ if (NOT ANDROID AND NOT IOS) endif() # Cross-platform native streaming HTTP transport (libcurl on desktop and -# Android, NSURLSession on iOS/tvOS). -add_subdirectory(http) +# 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 diff --git a/cmake/external/CMakeLists.txt b/cmake/external/CMakeLists.txt index 46684edb4b..a9dcf30edb 100644 --- a/cmake/external/CMakeLists.txt +++ b/cmake/external/CMakeLists.txt @@ -34,10 +34,12 @@ if (${FIREBASE_EXTERNAL_PLATFORM} STREQUAL "DESKTOP") include(zlib) endif() -# The Android native HTTP transport (app/http) 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") +# 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() diff --git a/cmake/external_rules.cmake b/cmake/external_rules.cmake index dfc06894ed..c99605d326 100644 --- a/cmake/external_rules.cmake +++ b/cmake/external_rules.cmake @@ -78,6 +78,7 @@ 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} From 3c00d4eb7040eb6028d944f729c2ee70d755a79c Mon Sep 17 00:00:00 2001 From: austinbenoit Date: Mon, 30 Nov 2026 20:06:54 +0000 Subject: [PATCH 14/16] [App][HTTP] Audit fixes: reject URL userinfo on Apple, avoid RFC-forbidden 1005 close code, clear CA defaults on Android --- app/http/http_transport_apple.mm | 4 ++++ app/http/http_transport_curl_android.cc | 5 +++++ app/http/websocket_apple.mm | 13 ++++++++++--- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/app/http/http_transport_apple.mm b/app/http/http_transport_apple.mm index 978745f2ea..dfb3f36ea8 100644 --- a/app/http/http_transport_apple.mm +++ b/app/http/http_transport_apple.mm @@ -834,6 +834,10 @@ void StartPlatformHttpOperation(const std::shared_ptr& op) { 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; diff --git a/app/http/http_transport_curl_android.cc b/app/http/http_transport_curl_android.cc index 2cd2046f8e..64798930f8 100644 --- a/app/http/http_transport_curl_android.cc +++ b/app/http/http_transport_curl_android.cc @@ -190,6 +190,11 @@ CURLcode TrustStore::ApplyTo(CURL* easy) { // 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); diff --git a/app/http/websocket_apple.mm b/app/http/websocket_apple.mm index af38c3c60d..4d03c4cda8 100644 --- a/app/http/websocket_apple.mm +++ b/app/http/websocket_apple.mm @@ -278,10 +278,13 @@ - (void)drainOutgoing { if (out.kind == firebase::http::WebSocketOperation::Outgoing::kClose) { _localCloseSent = true; if (!_taskCompleted) { - // A Close frame without a status code cannot carry a reason. - NSURLSessionWebSocketCloseCode code = NSURLSessionWebSocketCloseCodeNoStatusReceived; + // 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) { + 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() @@ -492,6 +495,10 @@ void StartPlatformWebSocket(const std::shared_ptr& ws) { 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()) { From 54e3cf6e82ed5bef0385d1c12f394b3dfa200149 Mon Sep 17 00:00:00 2001 From: Austin Benoit Date: Tue, 1 Dec 2026 10:44:43 -0500 Subject: [PATCH 15/16] [App][HTTP] Flush stranded libcurl upload sendbuf bytes while paused --- app/http/http_transport_curl.cc | 36 +++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/app/http/http_transport_curl.cc b/app/http/http_transport_curl.cc index a837aaca57..500c7933fc 100644 --- a/app/http/http_transport_curl.cc +++ b/app/http/http_transport_curl.cc @@ -167,6 +167,8 @@ struct CurlTransfer { 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; @@ -290,6 +292,7 @@ size_t OnCurlRead(char* buffer, size_t size, size_t nitems, void* userdata) { 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) { @@ -652,11 +655,40 @@ class CurlHttpEngine { } 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, 1000, &numfds); + 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); + } + } } } } From 076530bf63c7b1504cb59648e742ef520c34e10b Mon Sep 17 00:00:00 2001 From: Austin Benoit Date: Tue, 1 Dec 2026 11:24:31 -0500 Subject: [PATCH 16/16] [App][HTTP] Classify iOS certificate errors wrapped in NSURLErrorSecureConnectionFailed (-1200) --- app/http/http_transport_apple.mm | 72 ++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/app/http/http_transport_apple.mm b/app/http/http_transport_apple.mm index dfb3f36ea8..ca20931c3c 100644 --- a/app/http/http_transport_apple.mm +++ b/app/http/http_transport_apple.mm @@ -72,9 +72,81 @@ 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;