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..f93e3915c9 --- /dev/null +++ b/app/http/http_bridge.h @@ -0,0 +1,104 @@ +/* + * 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, +// invalid arguments, early server response, 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 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. +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..901ed648c8 --- /dev/null +++ b/app/http/http_transport.h @@ -0,0 +1,295 @@ +/* + * 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. +// +// 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_ + +#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, +}; + +// 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; +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_write_closed = false; + bool req_space_armed = false; + + // Response header state (native backend -> caller). + bool headers_ready = false; + int32_t status_code = 0; + std::string reason_phrase; + std::vector> response_headers; + bool resp_headers_armed = false; + + // Response body streaming pipe (native backend -> caller). + std::deque resp_chunks; + size_t resp_buffered_bytes = 0; + bool resp_eof = false; + bool resp_read_armed = false; + + // Terminal failure / cancellation / single-start state. + std::atomic started{false}; + std::atomic canceled{false}; + bool failed = false; + HttpErrorClass error_class = kHttpErrorNone; + std::string error_message; + + // Platform backend hooks invoked outside `mutex` when state changes. + std::function on_request_data_changed; + std::function on_response_space_available; + std::function on_cancel; + + bool IsCanceled() const { return canceled.load(std::memory_order_acquire); } + + // Called by the platform backend once final response status & headers arrive. + void CommitResponseHeaders( + int32_t status, std::string_view reason, + std::vector> headers); + + // Called by the platform backend when it stops consuming request body bytes + // (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 + // `on_response_space_available` fires. + bool PushResponseBytes(const uint8_t* bytes, size_t length); + + // Called by the platform backend when the response body finishes cleanly. + void MarkResponseComplete(); + + // Called by the platform backend when a transport error aborts the transfer. + void MarkFailed(std::string_view message, + HttpErrorClass err_class = kHttpErrorOther); + + // Non-blocking drain of up to `max_bytes` from the request body queue. + // Sets `out_eof` to true when the queue is empty and the caller finished + // writing. + size_t PopRequestBytes(uint8_t* dest, size_t max_bytes, bool* out_eof); +}; + +// 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); +void CancelAllOperations(); + +// Enqueues an event onto the global completion queue consumed by +// `HttpWaitNextEventInternal`. +void PostCompletionEvent(int64_t handle, HttpEventKind kind); + +// Platform-specific entry point implemented in +// `http_transport_{curl,apple,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); + +// 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. 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); + +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); + +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 + +#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..e07b500555 --- /dev/null +++ b/app/http/http_transport_android.cc @@ -0,0 +1,1396 @@ +/* + * 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_apple.mm b/app/http/http_transport_apple.mm new file mode 100644 index 0000000000..475178b587 --- /dev/null +++ b/app/http/http_transport_apple.mm @@ -0,0 +1,1156 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport.h" + +#if !__has_feature(objc_arc) +#error "http_transport_apple.mm requires Objective-C ARC (-fobjc-arc)." +#endif + +@class FIRFirebaseHttpStreamBridge; +@class FIRFirebaseHttpSessionDelegate; + +namespace firebase { +namespace http { +namespace { + +NSString* ToNSString(std::string_view s) { + NSString* ns = [[NSString alloc] initWithBytes:s.data() + length:s.size() + encoding:NSUTF8StringEncoding]; + if (ns == nil) { + ns = [[NSString alloc] initWithBytes:s.data() + length:s.size() + encoding:NSISOLatin1StringEncoding]; + } + return ns != nil ? ns : @""; +} + +std::string FromNSString(NSString* ns) { + if (ns == nil) { + return std::string(); + } + const char* utf8 = [ns UTF8String]; + return utf8 != nullptr ? std::string(utf8) : std::string(); +} + +std::string ToLowerAscii(std::string_view s) { + std::string out(s.size(), '\0'); + for (size_t i = 0; i < s.size(); ++i) { + out[i] = static_cast(std::tolower(static_cast(s[i]))); + } + return out; +} + +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 +} // namespace firebase + +@interface FIRFirebaseHttpStreamBridge : NSObject +- (instancetype)initWithState:(std::shared_ptr)state; +- (void)scheduleOutputStream:(NSOutputStream*)outputStream; +- (void)pumpWriteStream; +- (void)closeWriteStream; +@end + +@implementation FIRFirebaseHttpStreamBridge { + std::shared_ptr _state; + NSOutputStream* _ownedStream; + // NSStream.delegate is an unsafe_unretained (assign) property. Retain `self` + // explicitly from `scheduleOutputStream:` until `closeOnStreamThread` clears + // `stream.delegate = nil` and removes `stream` from the run loop. + FIRFirebaseHttpStreamBridge* _selfRetain; +} + ++ (NSThread*)streamThread { + static NSThread* sThread = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + dispatch_semaphore_t ready = dispatch_semaphore_create(0); + sThread = [[NSThread alloc] initWithTarget:self + selector:@selector(streamThreadMain:) + object:ready]; + sThread.name = @"com.google.firebase.http.stream"; + sThread.qualityOfService = NSQualityOfServiceUserInitiated; + [sThread start]; + // Wait until `streamThreadMain:` has created its NSRunLoop and attached its + // keep-alive port so the first `performSelector:onThread:` is never dropped. + dispatch_semaphore_wait(ready, DISPATCH_TIME_FOREVER); + }); + return sThread; +} + ++ (void)streamThreadMain:(id)readySemaphore { + @autoreleasepool { + NSRunLoop* runLoop = [NSRunLoop currentRunLoop]; + [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; + if (readySemaphore != nil) { + dispatch_semaphore_signal(static_cast(readySemaphore)); + } + while (true) { + @autoreleasepool { + [runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]; + } + } + } +} + +- (instancetype)initWithState:(std::shared_ptr)state { + self = [super init]; + if (self != nil) { + _state = std::move(state); + } + return self; +} + +- (void)scheduleOutputStream:(NSOutputStream*)outputStream { + _ownedStream = outputStream; + _selfRetain = self; + [self performSelector:@selector(openOnStreamThread:) + onThread:[FIRFirebaseHttpStreamBridge streamThread] + withObject:outputStream + waitUntilDone:NO]; +} + +- (void)openOnStreamThread:(NSOutputStream*)outputStream { + auto state = _state; + if (!state || state->op->IsCanceled()) { + [self closeOnStreamThread]; + return; + } + bool active = false; + { + std::lock_guard lock(state->state_mutex); + active = !state->body_closed && state->body_output_stream == outputStream; + } + if (!active) { + outputStream.delegate = nil; + [outputStream close]; + _ownedStream = nil; + _state.reset(); + _selfRetain = nil; + return; + } + outputStream.delegate = self; + [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + [outputStream open]; + [self pumpOnStreamThread]; +} + +- (void)pumpWriteStream { + [self performSelector:@selector(pumpOnStreamThread) + onThread:[FIRFirebaseHttpStreamBridge streamThread] + withObject:nil + waitUntilDone:NO]; +} + +- (void)closeWriteStream { + [self performSelector:@selector(closeOnStreamThread) + onThread:[FIRFirebaseHttpStreamBridge streamThread] + withObject:nil + waitUntilDone:NO]; +} + +- (void)closeOnStreamThread { + auto state = _state; + NSOutputStream* stream = _ownedStream; + _ownedStream = nil; + if (state) { + std::lock_guard lock(state->state_mutex); + if (state->stream_bridge == self) { + state->stream_bridge = nil; + } + if (state->body_output_stream == stream) { + state->body_closed = true; + state->body_output_stream = nil; + } + } + if (stream != nil) { + stream.delegate = nil; + [stream close]; + [stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; + } + _state.reset(); + _selfRetain = nil; +} + +- (void)pumpOnStreamThread { + auto state = _state; + if (!state || state->op->IsCanceled()) { + [self closeOnStreamThread]; + return; + } + + NSOutputStream* stream = nil; + { + std::lock_guard lock(state->state_mutex); + if (state->body_closed || state->body_output_stream != _ownedStream || _ownedStream == nil) { + return; + } + stream = _ownedStream; + } + + constexpr size_t kSliceSize = 64 * 1024; + while ([stream hasSpaceAvailable]) { + if (state->pending_write_offset >= state->pending_write_chunk.size()) { + 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 { + if (eof) { + [self closeOnStreamThread]; + } + return; + } + } + + const uint8_t* ptr = state->pending_write_chunk.data() + state->pending_write_offset; + NSUInteger rem = + static_cast(state->pending_write_chunk.size() - state->pending_write_offset); + NSInteger written = [stream write:ptr maxLength:rem]; + if (written > 0) { + state->pending_write_offset += static_cast(written); + } else if (written < 0) { + // NSURLSession closes the bound input stream early when the server sends + // an 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 { + break; + } + } +} + +- (void)stream:(NSStream*)aStream handleEvent:(NSStreamEvent)eventCode { + switch (eventCode) { + case NSStreamEventHasSpaceAvailable: + [self pumpOnStreamThread]; + break; + case NSStreamEventErrorOccurred: + case NSStreamEventEndEncountered: { + auto state = _state; + if (state) { + state->op->MarkRequestWriteClosed(); + } + [self closeOnStreamThread]; + break; + } + default: + break; + } +} + +@end + +@interface FIRFirebaseHttpSessionDelegate : NSObject +- (void)registerState:(std::shared_ptr)state + forTaskKey:(NSString*)key; +- (std::shared_ptr)takeState:(NSURLSessionTask*)task; +@end + +@implementation FIRFirebaseHttpSessionDelegate { + std::mutex _mapMutex; + std::unordered_map> _tasks; +} + +- (std::shared_ptr)findState:(NSURLSessionTask*)task { + NSString* desc = task.taskDescription; + if (desc == nil) { + return nullptr; + } + std::string key = firebase::http::FromNSString(desc); + std::lock_guard lock(_mapMutex); + auto it = _tasks.find(key); + return it != _tasks.end() ? it->second : nullptr; +} + +- (std::shared_ptr)takeState:(NSURLSessionTask*)task { + NSString* desc = task.taskDescription; + if (desc == nil) { + return nullptr; + } + std::string key = firebase::http::FromNSString(desc); + std::lock_guard lock(_mapMutex); + auto it = _tasks.find(key); + if (it == _tasks.end()) { + return nullptr; + } + auto state = std::move(it->second); + _tasks.erase(it); + return state; +} + +- (void)registerState:(std::shared_ptr)state + forTaskKey:(NSString*)key { + std::string k = firebase::http::FromNSString(key); + std::lock_guard lock(_mapMutex); + _tasks[k] = std::move(state); +} + +- (void)URLSession:(NSURLSession*)session + task:(NSURLSessionTask*)task + needNewBodyStream:(void (^)(NSInputStream* _Nullable bodyStream))completionHandler { + auto state = [self findState:task]; + if (!state || state->op->IsCanceled()) { + completionHandler(nil); + return; + } + + 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; + { + 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); +} + +- (void)URLSession:(NSURLSession*)session + dataTask:(NSURLSessionDataTask*)dataTask + didReceiveResponse:(NSURLResponse*)response + completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { + auto state = [self findState:dataTask]; + if (!state || state->op->IsCanceled()) { + completionHandler(NSURLSessionResponseCancel); + return; + } + + if (![response isKindOfClass:[NSHTTPURLResponse class]]) { + state->op->MarkFailed("Unexpected non-HTTP URLResponse.", firebase::http::kHttpErrorOther); + completionHandler(NSURLSessionResponseCancel); + return; + } + + auto* httpResp = static_cast(response); + int32_t status = static_cast(httpResp.statusCode); + std::string reason = firebase::http::CanonicalReasonPhrase(status); + 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; + } + + // Push incoming bytes in bounded slices and enforce true socket backpressure: + // `[dataTask suspend]` alone is asynchronous in CFNetwork and can allow tens + // of MiB to enqueue before taking effect. Because each active task runs on + // its own serial NSOperationQueue (from AppleSessionPool), suspending the + // task and waiting on `op->resp_cv` here bounds both `resp_buffered_bytes` + // and process resident memory without head-of-line blocking other concurrent + // requests. + constexpr size_t kSliceBytes = 256 * 1024; + [data enumerateByteRangesUsingBlock:^(const void* bytes, NSRange byteRange, BOOL* stop) { + const auto* ptr = static_cast(bytes); + size_t remaining = static_cast(byteRange.length); + size_t offset = 0; + while (remaining > 0) { + if (state->op->IsCanceled()) { + *stop = YES; + return; + } + size_t take = (std::min)(remaining, kSliceBytes); + bool over_high_water = state->op->PushResponseBytes(ptr + offset, take); + offset += take; + remaining -= take; + + if (over_high_water && !state->op->IsCanceled()) { + bool did_suspend = false; + { + std::lock_guard slock(state->state_mutex); + if (!state->task_suspended && !state->op->IsCanceled() && state->task != nil) { + state->task_suspended = true; + [state->task suspend]; + did_suspend = true; + } + } + { + std::unique_lock op_lock(state->op->mutex); + state->op->resp_cv.wait(op_lock, [&state]() { + return state->op->resp_buffered_bytes <= firebase::http::kLowWaterResponseBytes || + state->op->IsCanceled() || state->op->failed; + }); + } + if (did_suspend) { + std::lock_guard slock(state->state_mutex); + if (state->task_suspended && state->task != nil) { + state->task_suspended = false; + [state->task resume]; + } + } + } + } + }]; +} + +- (void)URLSession:(NSURLSession*)session + task:(NSURLSessionTask*)task + didCompleteWithError:(NSError*)error { + auto state = [self takeState:task]; + if (!state) { + return; + } + FIRFirebaseHttpStreamBridge* bridge = nil; + std::shared_ptr slot_to_release; + { + std::lock_guard lock(state->state_mutex); + state->task = nil; + state->task_suspended = false; + bridge = state->stream_bridge; + state->stream_bridge = nil; + if (!state->slot_released) { + state->slot_released = true; + slot_to_release = std::move(state->session_slot); + } + } + if (bridge != nil) { + [bridge closeWriteStream]; + } + if (slot_to_release) { + firebase::http::ReleaseSessionSlot(slot_to_release, /*cancel_now=*/false); + } + if (state->op->IsCanceled()) { + return; + } + if (error != nil) { + firebase::http::HttpErrorClass err_class = firebase::http::ClassifyNSError(error); + state->op->MarkFailed(firebase::http::FromNSString([error localizedDescription]), err_class); + } else { + state->op->MarkResponseComplete(); + } +} + +@end + +namespace firebase { +namespace http { +namespace { + +NSURLSessionConfiguration* MakeBaseSessionConfig() { + NSURLSessionConfiguration* config = [NSURLSessionConfiguration ephemeralSessionConfiguration]; + config.URLCache = nil; + config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData; + config.HTTPCookieAcceptPolicy = NSHTTPCookieAcceptPolicyNever; + config.HTTPShouldSetCookies = NO; + config.HTTPMaximumConnectionsPerHost = 16; + // NSURLSession does not expose a connect-only timeout separate from the idle + // read timeout (`timeoutIntervalForRequest`). Keep these high so idle SSE + // streams are never killed; TCP connect relies on the OS SYN timeout, and + // caller CancellationTokens / watchdogs govern request lifetimes. + config.timeoutIntervalForRequest = 86400.0; + config.timeoutIntervalForResource = 86400.0; + return config; +} + +std::shared_ptr CreateSessionSlot(NSURLSessionConfiguration* config, + bool pooled) { + auto slot = std::make_shared(); + slot->pooled = pooled; + slot->delegate = [[FIRFirebaseHttpSessionDelegate alloc] init]; + NSOperationQueue* queue = [[NSOperationQueue alloc] init]; + queue.name = @"com.google.firebase.http.delegate"; + queue.maxConcurrentOperationCount = 1; + queue.qualityOfService = NSQualityOfServiceUserInitiated; + slot->session = [NSURLSession sessionWithConfiguration:config + delegate:slot->delegate + delegateQueue:queue]; + return slot; +} + +// Pool of reusable NSURLSessions (each with its own serial NSOperationQueue) so +// at most one in-flight task occupies a delegate queue at any time. This gives: +// - 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) { + if (!state) { + return; + } + FIRFirebaseHttpStreamBridge* bridge = nil; + NSURLSessionDataTask* t = nil; + FIRFirebaseHttpSessionDelegate* del = nil; + std::shared_ptr unstarted_slot; + bool was_suspended = false; + bool was_started = false; + { + std::lock_guard slock(state->state_mutex); + bridge = state->stream_bridge; + state->stream_bridge = nil; + t = state->task; + was_suspended = state->task_suspended; + was_started = state->task_started; + state->task_suspended = false; + state->task = nil; + if (state->session_slot) { + del = state->session_slot->delegate; + if (!was_started && !state->slot_released) { + state->slot_released = true; + unstarted_slot = std::move(state->session_slot); + } + } + } + if (bridge != nil) { + [bridge closeWriteStream]; + } + if (t != nil) { + if (!was_started && del != nil) { + // NSURLSession does not fire `didCompleteWithError:` for a task canceled + // before its initial `resume`; remove from `_tasks` here to avoid a leak. + [del takeState:t]; + } + // Balance any active suspend before cancelling; NSURLSession asserts if a + // task is cancelled or deallocated with suspend > 0. + if (was_suspended) { + [t resume]; + } + [t cancel]; + } + if (unstarted_slot) { + ReleaseSessionSlot(unstarted_slot, /*cancel_now=*/true); + } +} + +} // namespace + +void StartPlatformHttpOperation(const std::shared_ptr& op) { + @autoreleasepool { + if (op->IsCanceled()) { + return; + } + if (!IsHttpOrHttpsUrl(op->url)) { + op->MarkFailed("Unsupported URI scheme; only http and https are allowed.", + 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.", 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; + req.HTTPShouldHandleCookies = NO; + + bool has_content_length = false; + bool has_accept_encoding = false; + std::unordered_set seen_headers; + for (const auto& kv : op->request_headers) { + if (AsciiEqualsIgnoreCase(kv.first, "Content-Length")) { + has_content_length = true; + } else if (AsciiEqualsIgnoreCase(kv.first, "Accept-Encoding")) { + has_accept_encoding = true; + } + NSString* field = ToNSString(kv.first); + NSString* value = ToNSString(kv.second); + if (seen_headers.insert(ToLowerAscii(kv.first)).second) { + [req setValue:value forHTTPHeaderField:field]; + } else { + [req addValue:value forHTTPHeaderField:field]; + } + } + if (!has_accept_encoding) { + // Match .NET HttpClientHandler (AutomaticDecompression = None) and + // Desktop libcurl so NSURLSession does not inject `Accept-Encoding: gzip`, + // strip Content-Length, buffer SSE frames, or corrupt Range offsets. + [req setValue:@"identity" forHTTPHeaderField:@"Accept-Encoding"]; + } + + auto state = std::make_shared(); + state->op = op; + state->session_slot = slot; + + FIRFirebaseHttpStreamBridge* stream_bridge = nil; + NSOutputStream* out_stream = nil; + if (op->content_length == 0 && !is_get && !is_head) { + req.HTTPBody = [NSData data]; + if (!has_content_length) { + [req setValue:@"0" forHTTPHeaderField:@"Content-Length"]; + } + } else if (op->content_length > 0 || op->content_length == kChunkedRequestContent) { + NSInputStream* in_stream = nil; + [NSStream getBoundStreamsWithBufferSize:kMaxRequestBufferBytes + inputStream:&in_stream + outputStream:&out_stream]; + req.HTTPBodyStream = in_stream; + if (op->content_length > 0 && !has_content_length) { + [req setValue:[NSString + stringWithFormat:@"%lld", static_cast(op->content_length)] + forHTTPHeaderField:@"Content-Length"]; + } + stream_bridge = [[FIRFirebaseHttpStreamBridge alloc] initWithState:state]; + state->body_output_stream = out_stream; + state->stream_bridge = stream_bridge; + } else if (!has_content_length && (AsciiEqualsIgnoreCase(op->method, "POST") || + AsciiEqualsIgnoreCase(op->method, "PUT") || + AsciiEqualsIgnoreCase(op->method, "PATCH"))) { + req.HTTPBody = [NSData data]; + [req setValue:@"0" forHTTPHeaderField:@"Content-Length"]; + } + + NSURLSessionDataTask* task = [slot->session dataTaskWithRequest:req]; + NSString* key = [NSString stringWithFormat:@"%lld", static_cast(op->id)]; + task.taskDescription = key; + { + // Write `state->task` under `state_mutex` before registering or starting + // the stream thread (P4). + std::lock_guard slock(state->state_mutex); + state->task = task; + } + + [slot->delegate registerState:state forTaskKey:key]; + + bool already_canceled = false; + { + std::weak_ptr weak_state = state; + std::lock_guard lock(op->mutex); + if (op->IsCanceled()) { + already_canceled = true; + } else { + if (stream_bridge != nil) { + op->on_request_data_changed = [weak_state]() { + auto locked = weak_state.lock(); + if (!locked) { + return; + } + FIRFirebaseHttpStreamBridge* bridge = nil; + { + std::lock_guard slock(locked->state_mutex); + bridge = locked->stream_bridge; + } + if (bridge != nil) { + [bridge pumpWriteStream]; + } + }; + } + op->on_cancel = [weak_state]() { CancelAppleTransferTask(weak_state.lock()); }; + } + } + + if (already_canceled) { + [slot->delegate takeState:task]; + std::shared_ptr to_release; + { + std::lock_guard slock(state->state_mutex); + state->stream_bridge = nil; + state->body_output_stream = nil; + state->body_closed = true; + state->task = nil; + if (!state->slot_released) { + state->slot_released = true; + to_release = std::move(state->session_slot); + } + } + [task cancel]; + if (to_release) { + ReleaseSessionSlot(to_release, /*cancel_now=*/true); + } + return; + } + + // Coordinate initial `[task resume]` with `CancelAppleTransferTask` under + // `state_mutex` so a cancel racing before `resume` cannot leave a never- + // resumed task stranded in `_tasks` or leak a session slot. + bool should_cleanup_unstarted = false; + bool started_now = false; + std::shared_ptr unstarted_release; + { + std::lock_guard slock(state->state_mutex); + if (state->task != nil && !op->IsCanceled()) { + state->task_started = true; + started_now = true; + [task resume]; + } else if (state->task != nil) { + state->task = nil; + state->stream_bridge = nil; + state->body_output_stream = nil; + state->body_closed = true; + should_cleanup_unstarted = true; + if (!state->slot_released) { + state->slot_released = true; + unstarted_release = std::move(state->session_slot); + } + } + } + if (started_now && stream_bridge != nil && out_stream != nil) { + [stream_bridge scheduleOutputStream:out_stream]; + } + if (should_cleanup_unstarted) { + [slot->delegate takeState:task]; + [task cancel]; + if (unstarted_release) { + ReleaseSessionSlot(unstarted_release, /*cancel_now=*/true); + } + } + } +} + +} // namespace http +} // namespace firebase diff --git a/app/http/http_transport_common.cc b/app/http/http_transport_common.cc new file mode 100644 index 0000000000..c89c4da7df --- /dev/null +++ b/app/http/http_transport_common.cc @@ -0,0 +1,1055 @@ +/* + * 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; +} + +// Trims only HTTP OWS (SP and HTAB) so control characters like CR/LF/VT/FF +// remain visible to header validation instead of being silently stripped. +std::string_view TrimHttpOws(std::string_view s) { + while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) { + s.remove_prefix(1); + } + while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) { + s.remove_suffix(1); + } + return s; +} + +bool IsHttpTchar(unsigned char ch) { + if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || + (ch >= '0' && ch <= '9')) { + return true; + } + switch (ch) { + case '!': + case '#': + case '$': + case '%': + case '&': + case '\'': + case '*': + case '+': + case '-': + case '.': + case '^': + case '_': + case '`': + case '|': + case '~': + return true; + default: + return false; + } +} + +void CancelOperationObject(const std::shared_ptr& op) { + if (!op) { + return; + } + bool expected = false; + if (!op->canceled.compare_exchange_strong(expected, true, + std::memory_order_acq_rel)) { + return; + } + + int64_t handle = op->id; + std::function cancel_hook; + bool notify_req = false; + bool notify_headers = false; + bool notify_body = false; + { + std::lock_guard lock(op->mutex); + if (!op->failed && op->error_class == kHttpErrorNone) { + op->error_class = kHttpErrorCanceled; + } + cancel_hook = std::move(op->on_cancel); + op->on_cancel = nullptr; + op->on_request_data_changed = nullptr; + op->on_response_space_available = nullptr; + if (op->req_space_armed) { + op->req_space_armed = false; + notify_req = true; + } + if (op->resp_headers_armed) { + op->resp_headers_armed = false; + notify_headers = true; + } + if (op->resp_read_armed) { + op->resp_read_armed = false; + notify_body = true; + } + } + op->req_cv.notify_all(); + op->resp_cv.notify_all(); + if (cancel_hook) { + cancel_hook(); + } + if (notify_req) { + PostCompletionEvent(handle, kHttpEventRequestSpaceAvailable); + } + if (notify_headers) { + PostCompletionEvent(handle, kHttpEventResponseHeadersReady); + } + if (notify_body) { + PostCompletionEvent(handle, kHttpEventResponseBodyAvailable); + } +} + +} // namespace + +bool IsValidHeaderName(std::string_view name) { + if (name.empty()) { + return false; + } + for (unsigned char ch : name) { + if (!IsHttpTchar(ch)) { + return false; + } + } + return true; +} + +bool IsValidHeaderValue(std::string_view value) { + for (unsigned char ch : value) { + if (ch == '\0' || ch == '\r' || ch == '\n' || + (ch < 0x20 && ch != '\t') || ch == 0x7F) { + return false; + } + } + return true; +} + +bool TryParsePackedHeaders( + std::string_view packed, + std::vector>* out) { + if (out == nullptr) { + return false; + } + out->clear(); + if (packed.find('\0') != std::string_view::npos) { + return false; + } + + size_t pos = 0; + while (pos < packed.size()) { + size_t nl = packed.find('\n', pos); + std::string_view line = nl == std::string_view::npos + ? packed.substr(pos) + : packed.substr(pos, nl - pos); + pos = nl == std::string_view::npos ? packed.size() : nl + 1; + if (!line.empty() && line.back() == '\r') { + line.remove_suffix(1); + } + if (line.empty()) { + continue; + } + // Reject any interior CR (header injection). + if (line.find('\r') != std::string_view::npos) { + out->clear(); + return false; + } + size_t sep = line.find('\t'); + if (sep == std::string_view::npos) { + sep = line.find(':'); + } + if (sep == std::string_view::npos || sep == 0) { + out->clear(); + return false; + } + std::string_view name = line.substr(0, sep); + std::string_view value = TrimHttpOws(line.substr(sep + 1)); + if (!IsValidHeaderName(name) || !IsValidHeaderValue(value)) { + out->clear(); + return false; + } + out->emplace_back(std::string(name), std::string(value)); + } + return true; +} + +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; + } + 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 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); + } + + 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); +} + +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; + } + + 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(); + 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; +} + +std::shared_ptr FindOperation(int64_t handle) { + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + auto it = reg.operations.find(handle); + return it != reg.operations.end() ? it->second : nullptr; +} + +void StartOperation(int64_t handle) { + auto op = FindOperation(handle); + if (!op) { + return; + } + if (op->started.exchange(true, std::memory_order_acq_rel)) { + return; + } + { + std::lock_guard lock(op->mutex); + if (op->failed || op->IsCanceled()) { + return; + } + } + StartPlatformHttpOperation(op); +} + +void CancelOperation(int64_t handle) { + CancelOperationObject(FindOperation(handle)); +} + +void DestroyOperation(int64_t handle) { + CancelOperation(handle); + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + reg.operations.erase(handle); +} + +void CancelAllOperations() { + std::vector> snapshot; + { + auto& reg = GetRegistry(); + std::lock_guard lock(reg.mutex); + snapshot.reserve(reg.operations.size()); + for (auto& kv : reg.operations) { + snapshot.push_back(std::move(kv.second)); + } + reg.operations.clear(); + } + for (const auto& op : snapshot) { + CancelOperationObject(op); + } + HttpWakeEventPumpInternal(); +} + +void HttpOperation::CommitResponseHeaders( + int32_t status, std::string_view reason, + std::vector> headers) { + bool notify = false; + { + std::lock_guard lock(mutex); + if (headers_ready || failed || IsCanceled()) { + return; + } + status_code = status; + reason_phrase.assign(reason.data(), reason.size()); + response_headers = std::move(headers); + headers_ready = true; + if (resp_headers_armed) { + resp_headers_armed = false; + notify = true; + } + } + if (notify) { + PostCompletionEvent(id, kHttpEventResponseHeadersReady); + } +} + +void HttpOperation::MarkRequestWriteClosed() { + bool notify_req = false; + { + std::lock_guard lock(mutex); + req_write_closed = true; + req_chunks.clear(); + req_buffered_bytes = 0; + on_request_data_changed = nullptr; + if (req_space_armed) { + req_space_armed = false; + notify_req = true; + } + } + req_cv.notify_all(); + if (notify_req) { + PostCompletionEvent(id, kHttpEventRequestSpaceAvailable); + } +} + +bool HttpOperation::PushResponseBytes(const uint8_t* bytes, size_t length) { + if (length == 0) { + std::lock_guard lock(mutex); + return resp_buffered_bytes >= kMaxResponseBufferBytes; + } + ByteChunk chunk; + chunk.data.assign(bytes, bytes + length); + + bool notify = false; + bool over_high_water = false; + { + std::lock_guard lock(mutex); + if (failed || IsCanceled()) { + return false; + } + resp_buffered_bytes += length; + resp_chunks.push_back(std::move(chunk)); + over_high_water = resp_buffered_bytes >= kMaxResponseBufferBytes; + if (resp_read_armed) { + resp_read_armed = false; + notify = true; + } + } + if (notify) { + PostCompletionEvent(id, kHttpEventResponseBodyAvailable); + } + return over_high_water; +} + +void HttpOperation::MarkResponseComplete() { + bool notify_req = false; + bool notify_headers = false; + bool notify_body = false; + { + std::lock_guard lock(mutex); + resp_eof = true; + req_write_closed = true; + req_chunks.clear(); + req_buffered_bytes = 0; + on_request_data_changed = nullptr; + on_response_space_available = nullptr; + on_cancel = nullptr; + if (req_space_armed) { + req_space_armed = false; + notify_req = true; + } + if (resp_headers_armed) { + resp_headers_armed = false; + notify_headers = true; + } + if (resp_read_armed) { + resp_read_armed = false; + notify_body = true; + } + } + req_cv.notify_all(); + if (notify_req) { + PostCompletionEvent(id, kHttpEventRequestSpaceAvailable); + } + if (notify_headers) { + PostCompletionEvent(id, kHttpEventResponseHeadersReady); + } + if (notify_body) { + PostCompletionEvent(id, kHttpEventResponseBodyAvailable); + } +} + +void HttpOperation::MarkFailed(std::string_view message, + HttpErrorClass err_class) { + bool notify_req = false; + bool notify_headers = false; + bool notify_body = false; + { + std::lock_guard lock(mutex); + if (!failed) { + failed = true; + error_class = err_class == kHttpErrorNone ? kHttpErrorOther : err_class; + error_message.assign(message.data(), message.size()); + } + req_write_closed = true; + on_request_data_changed = nullptr; + on_response_space_available = nullptr; + on_cancel = nullptr; + if (req_space_armed) { + req_space_armed = false; + notify_req = true; + } + if (resp_headers_armed) { + resp_headers_armed = false; + notify_headers = true; + } + if (resp_read_armed) { + resp_read_armed = false; + notify_body = true; + } + } + req_cv.notify_all(); + resp_cv.notify_all(); + if (notify_req) { + PostCompletionEvent(id, kHttpEventRequestSpaceAvailable); + } + if (notify_headers) { + PostCompletionEvent(id, kHttpEventResponseHeadersReady); + } + if (notify_body) { + PostCompletionEvent(id, kHttpEventResponseBodyAvailable); + } +} + +size_t HttpOperation::PopRequestBytes(uint8_t* dest, size_t max_bytes, + bool* out_eof) { + size_t copied = 0; + bool notify_space = false; + { + std::lock_guard lock(mutex); + while (copied < max_bytes && !req_chunks.empty()) { + ByteChunk& front = req_chunks.front(); + size_t take = (std::min)(max_bytes - copied, front.remaining()); + std::memcpy(dest + copied, front.data.data() + front.offset, take); + front.offset += take; + copied += take; + req_buffered_bytes -= take; + if (front.remaining() == 0) { + req_chunks.pop_front(); + } + } + if (out_eof != nullptr) { + *out_eof = req_chunks.empty() && req_eof; + } + if (req_space_armed && req_buffered_bytes <= kLowWaterRequestBytes) { + req_space_armed = false; + notify_space = true; + } + } + if (notify_space) { + PostCompletionEvent(id, kHttpEventRequestSpaceAvailable); + } + return copied; +} + +} // namespace http + +int64_t HttpCreateRequestInternal(const char* method, const char* url, + const char* headers_packed, + const char* proxy_url, + int64_t content_length) { + http::HttpRequestOptions options; + options.method = method != nullptr ? method : "GET"; + options.url = url != nullptr ? url : ""; + bool invalid_headers = false; + if (headers_packed != nullptr && headers_packed[0] != '\0') { + if (!http::TryParsePackedHeaders(headers_packed, &options.headers)) { + invalid_headers = true; + } + } + if (proxy_url != nullptr && proxy_url[0] != '\0') { + options.proxy_url = proxy_url; + } + options.content_length = content_length; + int64_t handle = http::CreateOperation(std::move(options)); + if (invalid_headers) { + if (auto op = http::FindOperation(handle)) { + op->MarkFailed("Invalid HTTP request header.", http::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 -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->req_write_closed || + 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 http::kHttpReadErrorOrCanceled; + } + auto op = http::FindOperation(handle); + if (!op) { + return http::kHttpReadErrorOrCanceled; + } + + size_t copied = 0; + bool crossed_low_water = false; + std::function resume_backend; + { + std::lock_guard lock(op->mutex); + if (op->IsCanceled()) { + return http::kHttpReadErrorOrCanceled; + } + size_t before = op->resp_buffered_bytes; + auto* out = static_cast(dest); + size_t want = static_cast(max_length); + while (copied < want && !op->resp_chunks.empty()) { + http::ByteChunk& front = op->resp_chunks.front(); + size_t take = (std::min)(want - copied, front.remaining()); + std::memcpy(out + copied, front.data.data() + front.offset, take); + front.offset += take; + copied += take; + op->resp_buffered_bytes -= take; + if (front.remaining() == 0) { + op->resp_chunks.pop_front(); + } + } + if (copied > 0) { + if (before >= http::kLowWaterResponseBytes && + op->resp_buffered_bytes <= http::kLowWaterResponseBytes) { + crossed_low_water = true; + resume_backend = op->on_response_space_available; + } + } else { + if (op->failed) { + return http::kHttpReadErrorOrCanceled; + } + if (op->resp_eof) { + return 0; + } + op->resp_read_armed = true; + return http::kHttpReadWouldBlock; + } + } + + if (crossed_low_water) { + op->resp_cv.notify_all(); + if (resume_backend) { + resume_backend(); + } + } else if (copied > 0) { + op->resp_cv.notify_all(); + } + return static_cast(copied); +} + +std::string HttpGetErrorInternal(int64_t handle) { + auto op = http::FindOperation(handle); + if (!op) { + return std::string(); + } + std::lock_guard lock(op->mutex); + return op->error_message; +} + +int32_t HttpGetErrorClassInternal(int64_t handle) { + auto op = http::FindOperation(handle); + if (!op) { + return http::kHttpErrorOther; + } + std::lock_guard lock(op->mutex); + if (op->IsCanceled() && !op->failed) { + return http::kHttpErrorCanceled; + } + return static_cast(op->error_class); +} + +void HttpCancelRequestInternal(int64_t handle) { + http::CancelOperation(handle); +} + +void HttpDestroyRequestInternal(int64_t handle) { + http::DestroyOperation(handle); +} + +void HttpCancelAllRequestsInternal() { http::CancelAllOperations(); } + +int64_t HttpWaitNextEventInternal(int32_t timeout_ms) { + auto& q = http::GetCompletionQueue(); + std::unique_lock lock(q.mutex); + if (q.events.empty() && !q.wake_requested && timeout_ms != 0) { + if (timeout_ms < 0) { + q.cv.wait(lock, [&q] { return !q.events.empty() || q.wake_requested; }); + } else { + q.cv.wait_for(lock, std::chrono::milliseconds(timeout_ms), + [&q] { return !q.events.empty() || q.wake_requested; }); + } + } + if (q.wake_requested) { + q.wake_requested = false; + if (q.events.empty()) { + return 0; + } + } + if (q.events.empty()) { + return 0; + } + int64_t ev = q.events.front(); + q.events.pop_front(); + return ev; +} + +void HttpWakeEventPumpInternal() { + auto& q = http::GetCompletionQueue(); + { + std::lock_guard lock(q.mutex); + q.wake_requested = true; + } + q.cv.notify_all(); +} + +} // namespace firebase diff --git a/app/http/http_transport_curl.cc b/app/http/http_transport_curl.cc new file mode 100644 index 0000000000..1d4f156b79 --- /dev/null +++ b/app/http/http_transport_curl.cc @@ -0,0 +1,777 @@ +/* + * 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 { + +using ::firebase::rest::curl::ApplyOpt; + +bool HasHeaderIgnoreCase( + const std::vector>& headers, + std::string_view target) { + for (const auto& kv : headers) { + if (AsciiEqualsIgnoreCase(kv.first, target)) { + return true; + } + } + return false; +} + +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) { + 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; + ::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.", + 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.", + kHttpErrorOther); + return nullptr; + } + + CURLcode tls_rc = ::firebase::rest::curl::ApplyTlsPolicy(easy.get()); + if (tls_rc != CURLE_OK) { + op->MarkFailed(curl_easy_strerror(tls_rc), kHttpErrorTls); + 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(); + 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. + 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()) { + ApplyOpt(raw_easy, CURLOPT_PROXY, op->proxy_url.c_str(), &opt_err); + } + + 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"); + + ::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); + if (!AppendSList(&header_list, line.c_str())) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + } + if (!has_expect) { + // Disable libcurl's automatic "Expect: 100-continue" wait on uploads. + if (!AppendSList(&header_list, "Expect:")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + } + + bool no_body = content_length == kNoRequestContent || + ((is_get || is_head) && content_length == 0); + if (no_body) { + if (is_head) { + ApplyOpt(raw_easy, CURLOPT_NOBODY, 1L, &opt_err); + } else if (is_get) { + ApplyOpt(raw_easy, CURLOPT_HTTPGET, 1L, &opt_err); + } else { + ApplyOpt(raw_easy, CURLOPT_CUSTOMREQUEST, + 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"))) { + if (!AppendSList(&header_list, "Content-Length: 0")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + } + } + } else { + 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) { + ApplyOpt(raw_easy, CURLOPT_INFILESIZE_LARGE, + static_cast(content_length), &opt_err); + } else if (!has_transfer_encoding) { + if (!AppendSList(&header_list, "Transfer-Encoding: chunked")) { + op->MarkFailed("Out of memory building request headers.", + kHttpErrorOther); + return nullptr; + } + } + } + + transfer->headers = std::move(header_list); + if (transfer->headers != nullptr) { + ApplyOpt(raw_easy, CURLOPT_HTTPHEADER, transfer->headers.get(), &opt_err); + } + + if (opt_err != CURLE_OK) { + op->MarkFailed(curl_easy_strerror(opt_err), + ClassifyCurlError(opt_err, op->IsCanceled())); + return nullptr; + } + + transfer->easy = std::move(easy); + return transfer; + } + + void FailAllActive(CURLMcode mc) { + std::string err = curl_multi_strerror(mc); + std::unordered_map> failed; + failed.swap(active_); + for (auto& kv : failed) { + if (kv.second) { + curl_multi_remove_handle(multi_.get(), kv.second->easy.get()); + if (!kv.second->op->IsCanceled()) { + kv.second->op->MarkFailed(err, kHttpErrorOther); + } + } + } + } + + void RunLoop() { + while (true) { + std::deque> starts; + std::vector upload_resumes; + std::vector download_resumes; + std::vector cancels; + + { + std::unique_lock lock(mutex_); + if (active_.empty() && pending_starts_.empty() && + pending_cancels_.empty()) { + cv_.wait(lock, [this]() { + return !pending_starts_.empty() || !pending_cancels_.empty(); + }); + } + starts.swap(pending_starts_); + upload_resumes.swap(pending_upload_resumes_); + download_resumes.swap(pending_download_resumes_); + cancels.swap(pending_cancels_); + } + + for (int64_t id : cancels) { + auto it = active_.find(id); + if (it != active_.end()) { + curl_multi_remove_handle(multi_.get(), it->second->easy.get()); + active_.erase(it); + } + } + + for (const auto& op : starts) { + if (op->IsCanceled() || active_.find(op->id) != active_.end()) { + continue; + } + if (multi_ == nullptr) { + op->MarkFailed("Native libcurl multi engine failed to initialize.", + kHttpErrorOther); + continue; + } + auto transfer = + BuildTransfer(op, 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), kHttpErrorOther); + continue; + } + active_.emplace(op->id, std::move(transfer)); + } + + auto apply_pause_mask = [](CurlTransfer& t) { + int mask = (t.upload_paused ? CURLPAUSE_SEND : CURLPAUSE_SEND_CONT) | + (t.download_paused ? CURLPAUSE_RECV : CURLPAUSE_RECV_CONT); + curl_easy_pause(t.easy.get(), mask); + }; + + for (int64_t id : upload_resumes) { + auto it = active_.find(id); + if (it != active_.end() && it->second->upload_paused) { + it->second->upload_paused = false; + apply_pause_mask(*it->second); + } + } + + for (int64_t id : download_resumes) { + auto it = active_.find(id); + if (it != active_.end() && it->second->download_paused) { + it->second->download_paused = false; + apply_pause_mask(*it->second); + } + } + + if (active_.empty()) { + continue; + } + + int still_running = 0; + CURLMcode perform_rc = curl_multi_perform(multi_.get(), &still_running); + if (perform_rc != CURLM_OK && perform_rc != CURLM_CALL_MULTI_PERFORM) { + FailAllActive(perform_rc); + continue; + } + + 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, kHttpErrorOther); + } 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, ClassifyCurlError(result, owned_transfer->op->IsCanceled())); + } + } + } + + 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 = + curl_multi_poll(multi_.get(), nullptr, 0, 1000, &numfds); + if (poll_rc != CURLM_OK) { + FailAllActive(poll_rc); + } + } + } + } + + 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_; + 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..c3ba45eebf --- /dev/null +++ b/app/http/tests/http_transport_common_test.cc @@ -0,0 +1,419 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "app/http/http_transport.h" +#include "gtest/gtest.h" + +namespace firebase { +namespace http { +namespace { + +TEST(HttpTransportCommonTest, 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) { + 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("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"); +} + +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, ParsePackedHeadersPreservesDuplicates) { + std::vector> headers; + ASSERT_TRUE(TryParsePackedHeaders( + "Authorization\tBearer tok\n" + "X-Multi\tfirst\r\n" + "X-Multi\tsecond\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"))); + 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, 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", "", + static_cast(kMaxRequestBufferBytes + 1024)); + ASSERT_GT(handle, 0); + auto op = FindOperation(handle); + ASSERT_NE(op, nullptr); + + // Fill upload buffer beyond kMaxRequestBufferBytes to test cap & arming. + std::vector upload_buf(kMaxRequestBufferBytes + 1024, 0xAB); + int32_t accepted = HttpTryWriteRequestBodyInternal( + handle, upload_buf.data(), static_cast(upload_buf.size())); + EXPECT_EQ(static_cast(accepted), kMaxRequestBufferBytes); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, upload_buf.data(), 16), 0); + + // Drain below low-water mark so space-available event fires. + std::vector drain(kMaxRequestBufferBytes); + bool eof = false; + size_t popped = + op->PopRequestBytes(drain.data(), kMaxRequestBufferBytes, &eof); + EXPECT_EQ(popped, kMaxRequestBufferBytes); + EXPECT_FALSE(eof); + + // Commit response headers and push response bytes over high-water mark. + EXPECT_EQ(HttpPollResponseHeadersInternal(handle), 0); + op->CommitResponseHeaders(200, "OK", {{"X-A", "1"}, {"X-A", "2"}}); + EXPECT_EQ(HttpPollResponseHeadersInternal(handle), 200); + EXPECT_EQ(HttpGetResponseHeadersInternal(handle), "OK\nX-A\t1\nX-A\t2\n"); + + std::atomic resumed{false}; + { + std::lock_guard lock(op->mutex); + op->on_response_space_available = [&resumed]() { resumed.store(true); }; + } + std::vector big(kMaxResponseBufferBytes, 0x5A); + EXPECT_TRUE(op->PushResponseBytes(big.data(), big.size())); + + std::vector out(kMaxResponseBufferBytes); + int32_t read_n = HttpTryReadResponseBodyInternal( + handle, out.data(), static_cast(out.size())); + EXPECT_EQ(static_cast(read_n), kMaxResponseBufferBytes); + EXPECT_TRUE(resumed.load()); + + // Next read when empty returns WouldBlock until canceled. + EXPECT_EQ(HttpTryReadResponseBodyInternal(handle, out.data(), 64), + kHttpReadWouldBlock); + HttpCancelRequestInternal(handle); + EXPECT_EQ(HttpTryReadResponseBodyInternal(handle, out.data(), 64), + kHttpReadErrorOrCanceled); + + HttpDestroyRequestInternal(handle); + EXPECT_EQ(FindOperation(handle), nullptr); +} + +TEST(HttpTransportCommonTest, MarkResponseCompleteWakesBlockedUploader) { + while (HttpWaitNextEventInternal(0) != 0) { + } + int64_t handle = HttpCreateRequestInternal( + "PUT", "http://127.0.0.1:80/early-413", "", "", + static_cast(kMaxRequestBufferBytes * 2)); + ASSERT_GT(handle, 0); + auto op = FindOperation(handle); + ASSERT_NE(op, nullptr); + + // Fill request buffer past high-water mark so req_space_armed is set. + std::vector chunk(kMaxRequestBufferBytes + 1024, 0xCC); + int32_t accepted = HttpTryWriteRequestBodyInternal( + handle, chunk.data(), static_cast(chunk.size())); + EXPECT_EQ(static_cast(accepted), kMaxRequestBufferBytes); + EXPECT_EQ(HttpTryWriteRequestBodyInternal(handle, chunk.data(), 64), 0); + + // Server completes an early clean response without draining the upload. + op->CommitResponseHeaders(413, "Payload Too Large", {}); + op->MarkResponseComplete(); + + // Completion queue must wake the armed uploader and subsequent writes fail + // 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), -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..b01e7af696 --- /dev/null +++ b/app/http/tests/http_transport_curl_test.cc @@ -0,0 +1,1549 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#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 +} + +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) { +#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; + } + if (port_ > 0) { + SocketFd wake = socket(AF_INET, SOCK_STREAM, 0); + if (wake != kInvalidSocket) { + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = htons(static_cast(port_)); + (void)connect(wake, reinterpret_cast(&addr), sizeof(addr)); + CloseSocket(wake); + } + } + if (accept_thread_.joinable()) { + accept_thread_.join(); + } + SocketFd to_close = + listen_fd_.exchange(kInvalidSocket, std::memory_order_acq_rel); + if (to_close != kInvalidSocket) { + CloseSocket(to_close); + } + std::vector to_join; + { + std::lock_guard lock(workers_mutex_); + to_join.swap(workers_); + } + for (auto& t : to_join) { + if (t.joinable()) { + t.join(); + } + } + } + + int port() const { return port_; } + + std::string Url(std::string_view path) const { + return "http://127.0.0.1:" + std::to_string(port_) + std::string(path); + } + + private: + void AcceptLoop() { + while (!stopped_.load()) { + SocketFd fd = listen_fd_.load(std::memory_order_acquire); + if (fd == kInvalidSocket) { + break; + } + if (!WaitForSocketReadable(fd, 50)) { + continue; + } + if (stopped_.load()) { + break; + } + sockaddr_in client_addr{}; +#if defined(_WIN32) + int len = sizeof(client_addr); +#else + socklen_t len = sizeof(client_addr); +#endif + SocketFd client = + accept(fd, reinterpret_cast(&client_addr), &len); + if (client == kInvalidSocket) { + if (stopped_.load()) break; + continue; + } + if (stopped_.load()) { + CloseSocket(client); + break; + } + int nodelay = 1; + setsockopt(client, IPPROTO_TCP, TCP_NODELAY, + reinterpret_cast(&nodelay), sizeof(nodelay)); +#ifdef SO_NOSIGPIPE + int nosigpipe = 1; + setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, + reinterpret_cast(&nosigpipe), sizeof(nosigpipe)); +#endif + std::lock_guard lock(workers_mutex_); + workers_.emplace_back([this, client]() { + HandleClient(client); + CloseSocket(client); + }); + } + } + + static bool ReadHttpRequest(SocketFd fd, ParsedRequest* out) { + std::string buf; + char tmp[4096]; + size_t header_end = std::string::npos; + while (header_end == std::string::npos) { +#if defined(_WIN32) + int n = recv(fd, tmp, sizeof(tmp), 0); +#else + ssize_t n = recv(fd, tmp, sizeof(tmp), 0); +#endif + if (n <= 0) return false; + buf.append(tmp, static_cast(n)); + header_end = buf.find("\r\n\r\n"); + } + + std::string header_block = buf.substr(0, header_end); + std::string remainder = buf.substr(header_end + 4); + + size_t line_end = header_block.find("\r\n"); + std::string req_line = line_end == std::string::npos + ? header_block + : header_block.substr(0, line_end); + size_t sp1 = req_line.find(' '); + size_t sp2 = sp1 == std::string::npos ? std::string::npos + : req_line.find(' ', sp1 + 1); + if (sp1 == std::string::npos || sp2 == std::string::npos) { + return false; + } + out->method = req_line.substr(0, sp1); + out->target = req_line.substr(sp1 + 1, sp2 - (sp1 + 1)); + + size_t pos = + line_end == std::string::npos ? header_block.size() : line_end + 2; + while (pos < header_block.size()) { + size_t next = header_block.find("\r\n", pos); + std::string_view line = + next == std::string::npos + ? std::string_view(header_block).substr(pos) + : std::string_view(header_block).substr(pos, next - pos); + pos = next == std::string::npos ? header_block.size() : next + 2; + size_t colon = line.find(':'); + if (colon != std::string_view::npos && colon > 0) { + out->headers.emplace_back( + std::string(TrimAsciiWhitespace(line.substr(0, colon))), + std::string(TrimAsciiWhitespace(line.substr(colon + 1)))); + } + } + + std::string te = out->GetHeader("Transfer-Encoding"); + if (AsciiEqualsIgnoreCase(te, "chunked")) { + std::string raw = std::move(remainder); + auto ensure = [&](size_t need) -> bool { + while (raw.size() < need) { +#if defined(_WIN32) + int n = recv(fd, tmp, sizeof(tmp), 0); +#else + ssize_t n = recv(fd, tmp, sizeof(tmp), 0); +#endif + if (n <= 0) return false; + raw.append(tmp, static_cast(n)); + } + return true; + }; + while (true) { + size_t crlf = raw.find("\r\n"); + while (crlf == std::string::npos) { + if (!ensure(raw.size() + 1)) return false; + crlf = raw.find("\r\n"); + } + size_t chunk_len = static_cast( + std::strtoull(raw.substr(0, crlf).c_str(), nullptr, 16)); + raw.erase(0, crlf + 2); + if (chunk_len == 0) { + ensure(2); + break; + } + if (!ensure(chunk_len + 2)) return false; + out->body.append(raw.data(), chunk_len); + raw.erase(0, chunk_len + 2); + } + } else { + std::string cl = out->GetHeader("Content-Length"); + size_t content_len = + cl.empty() + ? 0 + : static_cast(std::strtoull(cl.c_str(), nullptr, 10)); + out->body = std::move(remainder); + while (out->body.size() < content_len) { +#if defined(_WIN32) + int n = recv(fd, tmp, sizeof(tmp), 0); +#else + ssize_t n = recv(fd, tmp, sizeof(tmp), 0); +#endif + if (n <= 0) return false; + out->body.append(tmp, static_cast(n)); + } + if (out->body.size() > content_len) { + out->body.resize(content_len); + } + } + return true; + } + + void HandleClient(SocketFd fd) { + 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_; +}; + +// Event-driven test helper that asserts exact completion events using blocking +// `HttpWaitNextEventInternal` calls (never polling in a sleep loop, T2). +class BlockingEventDemux { + public: + void DrainStale() { + buffered_.clear(); + while (HttpWaitNextEventInternal(0) != 0) { + } + } + + bool WaitFor(int64_t handle, HttpEventKind expected_kind, int timeout_ms) { + auto& q = buffered_[handle]; + for (auto it = q.begin(); it != q.end(); ++it) { + if (*it == expected_kind) { + q.erase(it); + return true; + } + } + + auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(timeout_ms); + while (true) { + auto now = std::chrono::steady_clock::now(); + if (now >= deadline) { + return false; + } + int32_t rem_ms = static_cast( + std::chrono::duration_cast(deadline - now) + .count()); + if (rem_ms <= 0) { + rem_ms = 1; + } + int64_t ev = HttpWaitNextEventInternal(rem_ms); + if (ev == 0) { + return false; + } + int64_t ev_handle = ev >> 8; + auto ev_kind = static_cast(ev & 0xFF); + if (ev_handle == handle && ev_kind == expected_kind) { + return true; + } + buffered_[ev_handle].push_back(ev_kind); + } + } + + private: + std::unordered_map> buffered_; +}; + +int32_t WaitHeaders(BlockingEventDemux* demux, int64_t handle, + int timeout_ms = 5000) { + int32_t status = HttpPollResponseHeadersInternal(handle); + if (status != 0) { + return status; + } + EXPECT_TRUE( + demux->WaitFor(handle, kHttpEventResponseHeadersReady, timeout_ms)) + << "Timed out waiting for kHttpEventResponseHeadersReady on handle " + << handle; + return HttpPollResponseHeadersInternal(handle); +} + +bool ReadAllBody(BlockingEventDemux* demux, int64_t handle, std::string* out, + int timeout_ms = 10000) { + auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(timeout_ms); + char buf[16384]; + while (true) { + int32_t n = HttpTryReadResponseBodyInternal(handle, buf, sizeof(buf)); + if (n > 0) { + out->append(buf, static_cast(n)); + continue; + } + if (n == 0) { + return true; + } + if (n == kHttpReadErrorOrCanceled) { + return false; + } + auto now = std::chrono::steady_clock::now(); + if (now >= deadline) { + return false; + } + int rem_ms = static_cast( + std::chrono::duration_cast(deadline - now) + .count()); + if (!demux->WaitFor(handle, kHttpEventResponseBodyAvailable, + (std::max)(rem_ms, 1))) { + ADD_FAILURE() << "Expected kHttpEventResponseBodyAvailable event"; + return false; + } + } +} + +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) { + 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; + } + 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; + } + } + HttpFinishRequestBodyInternal(handle); + return true; +} + +TEST(HttpTransportCurlTest, GetBasic200AndMultiValueHeaders) { + BlockingEventDemux demux; + demux.DrainStale(); + + LoopbackHttpServer server([](const ParsedRequest& req, SocketFd fd) { + EXPECT_EQ(req.method, "GET"); + EXPECT_EQ(req.target, "/hello"); + EXPECT_EQ(req.GetHeader("X-Client"), "firebase-cpp"); + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/plain\r\n" + "Set-Cookie: a=1\r\n" + "Set-Cookie: b=2\r\n" + "Content-Length: 5\r\n" + "Connection: close\r\n" + "\r\n" + "world"); + }); + + int64_t h = HttpCreateRequestInternal("GET", server.Url("/hello").c_str(), + "X-Client\tfirebase-cpp\n", "", + kNoRequestContent); + HttpStartRequestInternal(h); + ASSERT_EQ(WaitHeaders(&demux, h), 200); + + std::string raw_headers = HttpGetResponseHeadersInternal(h); + EXPECT_NE(raw_headers.find("Set-Cookie\ta=1\n"), std::string::npos); + EXPECT_NE(raw_headers.find("Set-Cookie\tb=2\n"), std::string::npos); + + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, h, &body)); + EXPECT_EQ(body, "world"); + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, ZeroLengthGetAndHeadStayGetAndHead) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::mutex mu; + std::string get_method; + std::string head_method; + LoopbackHttpServer server([&](const ParsedRequest& req, SocketFd fd) { + if (req.target == "/zero-get") { + { + std::lock_guard lock(mu); + get_method = req.method; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 2\r\n" + "Connection: close\r\n\r\nok"); + } else if (req.target == "/zero-head") { + { + std::lock_guard lock(mu); + head_method = req.method; + } + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: 1234\r\n" + "Connection: close\r\n\r\n"); + } + }); + + int64_t h1 = HttpCreateRequestInternal("GET", server.Url("/zero-get").c_str(), + "", "", 0); + HttpStartRequestInternal(h1); + ASSERT_EQ(WaitHeaders(&demux, h1), 200); + std::string b1; + ASSERT_TRUE(ReadAllBody(&demux, h1, &b1)); + EXPECT_EQ(b1, "ok"); + HttpDestroyRequestInternal(h1); + + int64_t h2 = HttpCreateRequestInternal( + "HEAD", server.Url("/zero-head").c_str(), "", "", 0); + HttpStartRequestInternal(h2); + ASSERT_EQ(WaitHeaders(&demux, h2), 200); + std::string b2; + ASSERT_TRUE(ReadAllBody(&demux, h2, &b2)); + EXPECT_TRUE(b2.empty()); + HttpDestroyRequestInternal(h2); + + std::lock_guard lock(mu); + EXPECT_EQ(get_method, "GET"); + EXPECT_EQ(head_method, "HEAD"); +} + +TEST(HttpTransportCurlTest, PostJsonAndError400And204NoContent) { + BlockingEventDemux demux; + demux.DrainStale(); + + LoopbackHttpServer server([](const ParsedRequest& req, SocketFd fd) { + if (req.target == "/callable") { + EXPECT_EQ(req.method, "POST"); + EXPECT_EQ(req.body, "{\"data\":{\"msg\":\"hi\"}}"); + std::string resp = "{\"result\":{\"echo\":\"hi\"}}"; + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: application/json\r\n" + "Content-Length: " + + std::to_string(resp.size()) + + "\r\nConnection: close\r\n\r\n" + resp); + } else if (req.target == "/err400") { + std::string resp = "{\"error\":{\"status\":\"INVALID_ARGUMENT\"}}"; + SendAll(fd, + "HTTP/1.1 400 Bad Request\r\n" + "Content-Type: application/json\r\n" + "Content-Length: " + + std::to_string(resp.size()) + + "\r\nConnection: close\r\n\r\n" + resp); + } else if (req.target == "/delete") { + EXPECT_EQ(req.method, "DELETE"); + SendAll(fd, + "HTTP/1.1 204 No Content\r\n" + "Connection: close\r\n\r\n"); + } + }); + + // 1. JSON POST + const std::string payload = "{\"data\":{\"msg\":\"hi\"}}"; + int64_t h1 = + HttpCreateRequestInternal("POST", server.Url("/callable").c_str(), + "Content-Type\tapplication/json\n", "", + static_cast(payload.size())); + HttpStartRequestInternal(h1); + ASSERT_TRUE(WriteAllBody(&demux, h1, + reinterpret_cast(payload.data()), + payload.size())); + ASSERT_EQ(WaitHeaders(&demux, h1), 200); + std::string body1; + ASSERT_TRUE(ReadAllBody(&demux, h1, &body1)); + EXPECT_EQ(body1, "{\"result\":{\"echo\":\"hi\"}}"); + HttpDestroyRequestInternal(h1); + + // 2. 400 error JSON body preserved + int64_t h2 = HttpCreateRequestInternal("POST", server.Url("/err400").c_str(), + "", "", 0); + HttpStartRequestInternal(h2); + ASSERT_EQ(WaitHeaders(&demux, h2), 400); + std::string body2; + ASSERT_TRUE(ReadAllBody(&demux, h2, &body2)); + EXPECT_EQ(body2, "{\"error\":{\"status\":\"INVALID_ARGUMENT\"}}"); + HttpDestroyRequestInternal(h2); + + // 3. 204 No Content + int64_t h3 = HttpCreateRequestInternal( + "DELETE", server.Url("/delete").c_str(), "", "", kNoRequestContent); + HttpStartRequestInternal(h3); + ASSERT_EQ(WaitHeaders(&demux, h3), 204); + std::string body3; + ASSERT_TRUE(ReadAllBody(&demux, h3, &body3)); + EXPECT_TRUE(body3.empty()); + HttpDestroyRequestInternal(h3); +} + +TEST(HttpTransportCurlTest, SseTrickleStreamingImmediateDelivery) { + BlockingEventDemux demux; + demux.DrainStale(); + + std::mutex gate_mu; + std::condition_variable gate_cv; + int client_acked_chunk = 0; + + LoopbackHttpServer server([&](const ParsedRequest& req, SocketFd fd) { + EXPECT_EQ(req.method, "POST"); + EXPECT_EQ(req.GetHeader("Accept"), "text/event-stream"); + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "Transfer-Encoding: chunked\r\n" + "Connection: close\r\n" + "\r\n"); + + auto send_chunk = [&](std::string_view sse) { + char hex[32]; + std::snprintf(hex, sizeof(hex), "%zx\r\n", sse.size()); + SendAll(fd, hex); + SendAll(fd, sse); + SendAll(fd, "\r\n"); + }; + + send_chunk("data: {\"seq\":1}\n\n"); + { + std::unique_lock lock(gate_mu); + ASSERT_TRUE(gate_cv.wait_for(lock, std::chrono::seconds(5), + [&]() { return client_acked_chunk >= 1; })); + } + + send_chunk("data: {\"seq\":2}\n\n"); + { + std::unique_lock lock(gate_mu); + ASSERT_TRUE(gate_cv.wait_for(lock, std::chrono::seconds(5), + [&]() { return client_acked_chunk >= 2; })); + } + + send_chunk("data: {\"seq\":3}\n\n"); + SendAll(fd, "0\r\n\r\n"); + }); + + const std::string req_body = "{\"prompt\":\"stream\"}"; + int64_t h = HttpCreateRequestInternal( + "POST", server.Url("/sse").c_str(), + "Accept\ttext/event-stream\nContent-Type\tapplication/json\n", "", + static_cast(req_body.size())); + HttpStartRequestInternal(h); + ASSERT_TRUE(WriteAllBody(&demux, h, + reinterpret_cast(req_body.data()), + req_body.size())); + ASSERT_EQ(WaitHeaders(&demux, h), 200); + + auto read_until = [&](std::string* accum, std::string_view needle) -> bool { + char buf[1024]; + while (accum->find(needle) == std::string::npos) { + int32_t n = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); + if (n > 0) { + accum->append(buf, static_cast(n)); + } else if (n == 0 || n == kHttpReadErrorOrCanceled) { + break; + } else { + if (!demux.WaitFor(h, kHttpEventResponseBodyAvailable, 5000)) { + return false; + } + } + } + return accum->find(needle) != std::string::npos; + }; + + std::string accum; + ASSERT_TRUE(read_until(&accum, "data: {\"seq\":1}\n\n")); + { + std::lock_guard lock(gate_mu); + client_acked_chunk = 1; + } + gate_cv.notify_all(); + + ASSERT_TRUE(read_until(&accum, "data: {\"seq\":2}\n\n")); + { + std::lock_guard lock(gate_mu); + client_acked_chunk = 2; + } + gate_cv.notify_all(); + + std::string rest; + ASSERT_TRUE(ReadAllBody(&demux, h, &rest)); + accum.append(rest); + EXPECT_NE(accum.find("data: {\"seq\":3}\n\n"), std::string::npos); + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, SseIdleCancelUnblocksPromptly) { + BlockingEventDemux demux; + demux.DrainStale(); + + // T1: Server explicitly waits for peer socket close (EOF/RST) on cancel. + std::mutex close_mu; + std::condition_variable close_cv; + bool server_observed_close = false; + + LoopbackHttpServer server([&](const ParsedRequest&, SocketFd fd) { + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + "12\r\ndata: {\"ok\":true}\n\r\n"); + bool closed = WaitForPeerClose(fd, 5000); + { + std::lock_guard lock(close_mu); + server_observed_close = closed; + } + close_cv.notify_all(); + }); + + int64_t h = HttpCreateRequestInternal("GET", server.Url("/hang").c_str(), + "Accept\ttext/event-stream\n", "", + kNoRequestContent); + HttpStartRequestInternal(h); + ASSERT_EQ(WaitHeaders(&demux, h), 200); + + // Read the first SSE chunk using blocking event waits (T2). + std::string got; + char buf[512]; + while (got.empty()) { + int32_t n = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); + if (n > 0) { + got.append(buf, static_cast(n)); + } else { + ASSERT_EQ(n, kHttpReadWouldBlock); + ASSERT_TRUE(demux.WaitFor(h, kHttpEventResponseBodyAvailable, 5000)); + } + } + EXPECT_EQ(got, "data: {\"ok\":true}\n"); + + // Arm a read while server is silent, then signal canceler via cv (T3: no + // sleep-based synchronization). + ASSERT_EQ(HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)), + kHttpReadWouldBlock); + std::mutex cancel_mu; + std::condition_variable cancel_cv; + bool armed = false; + std::thread canceler([&]() { + { + std::unique_lock lock(cancel_mu); + cancel_cv.wait(lock, [&]() { return armed; }); + } + HttpCancelRequestInternal(h); + }); + + auto t0 = std::chrono::steady_clock::now(); + { + std::lock_guard lock(cancel_mu); + armed = true; + } + cancel_cv.notify_one(); + + ASSERT_TRUE(demux.WaitFor(h, kHttpEventResponseBodyAvailable, 3000)); + int32_t rc = HttpTryReadResponseBodyInternal(h, buf, sizeof(buf)); + canceler.join(); + + auto elapsed_ms = std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0) + .count(); + EXPECT_EQ(rc, kHttpReadErrorOrCanceled); + EXPECT_EQ(HttpGetErrorClassInternal(h), kHttpErrorCanceled); + EXPECT_LT(elapsed_ms, 1000); + + // Assert the TCP socket actually closed from HttpCancelRequestInternal alone, + // BEFORE HttpDestroyRequestInternal is called (T1). + { + std::unique_lock lock(close_mu); + EXPECT_TRUE(close_cv.wait_for(lock, std::chrono::seconds(3), + [&]() { return server_observed_close; })) + << "Server did not observe TCP socket closure after cancel"; + } + + HttpDestroyRequestInternal(h); +} + +TEST(HttpTransportCurlTest, + 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; + 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_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"); + } + 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"); + } + 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"); + } + }); + + // 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"); + } + 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); + + // 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(&demux, h3), -1); + EXPECT_NE(HttpGetErrorInternal(h3).find("Maximum HTTP redirects"), + std::string::npos); + HttpDestroyRequestInternal(h3); + + // 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); +} + +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) + + 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(&demux, h_up, expected_upload.data(), expected_upload.size())); + ASSERT_EQ(WaitHeaders(&demux, h_up), 200); + std::string up_resp; + ASSERT_TRUE(ReadAllBody(&demux, h_up, &up_resp)); + EXPECT_EQ(up_resp, "ok"); + { + std::lock_guard lock(upload_mu); + ASSERT_EQ(server_received_upload.size(), expected_upload.size()); + EXPECT_EQ(std::memcmp(server_received_upload.data(), expected_upload.data(), + expected_upload.size()), + 0); + } + HttpDestroyRequestInternal(h_up); + + // 2. 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(&demux, h_dl), 200); + + 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(&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); +} + +TEST(HttpTransportCurlTest, ConcurrentMixedTransfers) { + BlockingEventDemux demux; + demux.DrainStale(); + + LoopbackHttpServer server([](const ParsedRequest& req, SocketFd fd) { + if (req.target.rfind("/echo/", 0) == 0) { + std::string payload(64 * 1024, req.target.back()); + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Length: " + + std::to_string(payload.size()) + + "\r\nConnection: close\r\n\r\n" + payload); + } else if (req.target.rfind("/sse/", 0) == 0) { + SendAll(fd, + "HTTP/1.1 200 OK\r\n" + "Content-Type: text/event-stream\r\n" + "Transfer-Encoding: chunked\r\n" + "Connection: close\r\n\r\n"); + for (int i = 0; i < 4; ++i) { + std::string evt = + "data: " + req.target + "#" + std::to_string(i) + "\n\n"; + char hex[32]; + std::snprintf(hex, sizeof(hex), "%zx\r\n", evt.size()); + SendAll(fd, hex); + SendAll(fd, evt); + SendAll(fd, "\r\n"); + } + SendAll(fd, "0\r\n\r\n"); + } + }); + + constexpr int kOps = 6; + std::vector handles; + handles.reserve(kOps); + for (int i = 0; i < 3; ++i) { + char tag = static_cast('A' + i); + std::string url = server.Url(std::string("/echo/") + tag); + int64_t h = HttpCreateRequestInternal("GET", url.c_str(), "", "", + kNoRequestContent); + HttpStartRequestInternal(h); + handles.push_back(h); + } + for (int i = 0; i < 3; ++i) { + std::string url = server.Url("/sse/" + std::to_string(i)); + int64_t h = HttpCreateRequestInternal("GET", url.c_str(), + "Accept\ttext/event-stream\n", "", + kNoRequestContent); + HttpStartRequestInternal(h); + handles.push_back(h); + } + + for (int i = 0; i < 3; ++i) { + ASSERT_EQ(WaitHeaders(&demux, handles[i]), 200); + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, handles[i], &body)); + EXPECT_EQ(body.size(), 64u * 1024u); + EXPECT_EQ(body.front(), static_cast('A' + i)); + EXPECT_EQ(body.back(), static_cast('A' + i)); + HttpDestroyRequestInternal(handles[i]); + } + for (int i = 3; i < 6; ++i) { + ASSERT_EQ(WaitHeaders(&demux, handles[i]), 200); + std::string body; + ASSERT_TRUE(ReadAllBody(&demux, handles[i], &body)); + std::string expected_last = + "data: /sse/" + std::to_string(i - 3) + "#3\n\n"; + EXPECT_NE(body.find(expected_last), std::string::npos); + HttpDestroyRequestInternal(handles[i]); + } +} + +TEST(HttpTransportCurlTest, EarlyServerResponseUnblocksLargeUpload) { + 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); + + 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); + } + 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(); + 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); + + 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}