#include "prx/libSceHttp/include/Http.hpp" #include "prx/libSceHttp/src/Cookies.hpp" #include "SceTypes.hpp" #include "prx/libc/include/General.hpp" #include "prx/libSceHttp/src/GuestAccess.hpp" #include "prx/libSceHttp/src/HttpErrors.hpp" #include "prx/libSceHttp/src/Options.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static_assert(sizeof(HttpCookieStats) == 32); static_assert(offsetof(HttpCookieStats, cookieCount) == 8); static_assert(offsetof(HttpCookieStats, peakUsedBytes) == 16); static_assert(offsetof(HttpCookieStats, peakCookieCount) == 24); static_assert(offsetof(HttpCookieStats, evictedCookieCount) == 28); namespace { using Clock = std::chrono::system_clock; constexpr std::uint32_t DefaultMaxSize = 4096; constexpr std::uint32_t DefaultMaxNumPerDomain = 50; constexpr std::uint32_t DefaultMaxNum = 3000; constexpr std::uint32_t DefaultTotalMaxSize = 81920; constexpr std::uint64_t StoredSizeSlack = 516; constexpr size_t EvictedAtOnce = 10; struct Cookie { std::string name; std::string value; std::string domainSpelling; std::string domain; std::string path; bool secure = false; std::optional expiry; std::uint64_t creation = 0; }; struct CookieJar { std::vector cookies; std::uint32_t maxNum = DefaultMaxNum; std::uint32_t maxNumPerDomain = DefaultMaxNumPerDomain; std::uint32_t maxSize = DefaultMaxSize; std::uint32_t totalMaxSize = DefaultTotalMaxSize; std::uint64_t peakSize = 0; std::uint32_t peakNum = 0; std::uint32_t removedNum = 0; }; struct RequestUrl { std::string host; std::string path; bool secure = false; }; std::mutex g_cookieMutex; std::unordered_map g_jars; std::uint64_t g_cookieClock = 0; char lower(char c) { return c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c; } std::string lowered(std::string_view text) { std::string result(text); for (char& c : result) c = lower(c); return result; } bool equalsIgnoreCase(std::string_view left, std::string_view right) { return left.size() == right.size() && std::equal(left.begin(), left.end(), right.begin(), [](char a, char b) { return lower(a) == lower(b); }); } std::string_view trimmed(std::string_view text) { while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) text.remove_prefix(1); while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) text.remove_suffix(1); return text; } int parseUrl(const char* url, RequestUrl& parsed) { size_t required = 0; if (const int result = sceHttpUriParse(nullptr, url, nullptr, &required, 0); result != 0) return result; std::vector pool(required); SceHttpUriElement element; if (const int result = sceHttpUriParse(&element, url, pool.data(), &required, pool.size()); result != 0) return result; if (element.hostname[0] == '\0') return ERROR_PARSE_HTTP_INVALID_VALUE; parsed.host = lowered(element.hostname); parsed.path = element.path; parsed.secure = equalsIgnoreCase(element.scheme, "https"); return 0; } bool domainMatches(std::string_view host, std::string_view domain) { if (host == domain) return true; return host.size() > domain.size() && host.ends_with(domain) && host[host.size() - domain.size() - 1] == '.'; } bool allowedDomain(std::string_view domain) { constexpr std::array generic = {"com", "org", "net", "edu", "gov", "mil", "int"}; const size_t dots = static_cast(std::count(domain.begin(), domain.end(), '.')); if (dots == 0 || domain.back() == '.') return false; const std::string_view topLevel = domain.substr(domain.rfind('.') + 1); return dots >= (std::find(generic.begin(), generic.end(), topLevel) != generic.end() ? 1u : 2u); } std::string defaultPath(std::string_view path) { if (path.empty() || path.front() != '/') return "/"; return std::string(path.substr(0, path.rfind('/') + 1)); } bool pathMatches(std::string_view requestPath, std::string_view cookiePath) { if (requestPath.empty() || requestPath.front() != '/') requestPath = "/"; return requestPath.starts_with(cookiePath); } bool isDateDelimiter(char c) { const auto u = static_cast(c); return u == 0x09 || (u >= 0x20 && u <= 0x2F) || (u >= 0x3B && u <= 0x40) || (u >= 0x5B && u <= 0x60) || (u >= 0x7B && u <= 0x7E); } bool leadingDigits(std::string_view token, size_t minimum, size_t maximum, int& value, size_t& used) { used = 0; value = 0; while (used < token.size() && used < maximum && token[used] >= '0' && token[used] <= '9') value = value * 10 + (token[used++] - '0'); return used >= minimum && (used == token.size() || token[used] < '0' || token[used] > '9'); } bool parseTime(std::string_view token, int& hour, int& minute, int& second) { int* fields[] = {&hour, &minute, &second}; for (size_t index = 0; index < 3; ++index) { size_t used = 0; if (!leadingDigits(token, 1, 2, *fields[index], used)) return false; token.remove_prefix(used); if (index < 2) { if (!token.starts_with(':')) return false; token.remove_prefix(1); } } return true; } Clock::time_point clampedTime(std::chrono::sys_seconds time) { if (time >= std::chrono::floor(Clock::time_point::max())) return Clock::time_point::max(); if (time <= std::chrono::ceil(Clock::time_point::min())) return Clock::time_point::min(); return std::chrono::time_point_cast(time); } std::optional parseCookieDate(std::string_view text) { constexpr std::string_view months[] = {"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}; bool foundTime = false; bool foundDay = false; bool foundMonth = false; bool foundYear = false; int hour = 0; int minute = 0; int second = 0; int day = 0; int month = 0; int year = 0; while (!text.empty()) { while (!text.empty() && isDateDelimiter(text.front())) text.remove_prefix(1); size_t length = 0; while (length < text.size() && !isDateDelimiter(text[length])) ++length; const std::string_view token = text.substr(0, length); text.remove_prefix(length); if (token.empty()) continue; size_t used = 0; int value = 0; if (!foundTime && parseTime(token, hour, minute, second)) { foundTime = true; } else if (!foundDay && leadingDigits(token, 1, 2, value, used)) { foundDay = true; day = value; } else if (!foundMonth && token.size() >= 3 && std::find(std::begin(months), std::end(months), lowered(token.substr(0, 3))) != std::end(months)) { foundMonth = true; month = static_cast(std::find(std::begin(months), std::end(months), lowered(token.substr(0, 3))) - std::begin(months)) + 1; } else if (!foundYear && leadingDigits(token, 2, 4, value, used)) { foundYear = true; year = value; } } if (year >= 70 && year <= 99) year += 1900; else if (year >= 0 && year <= 69) year += 2000; if (!foundTime || !foundDay || !foundMonth || !foundYear) return std::nullopt; if (day < 1 || day > 31 || year < 1601 || hour > 23 || minute > 59 || second > 59) return std::nullopt; const std::chrono::year_month_day date{std::chrono::year{year}, std::chrono::month{static_cast(month)}, std::chrono::day{static_cast(day)}}; if (!date.ok()) return std::nullopt; return clampedTime(std::chrono::sys_days{date} + std::chrono::hours{hour} + std::chrono::minutes{minute} + std::chrono::seconds{second}); } std::optional parseMaxAge(std::string_view text, Clock::time_point now) { if (text.empty()) return std::nullopt; const bool negative = text.front() == '-'; if (negative) text.remove_prefix(1); if (text.empty() || text.find_first_not_of("0123456789") != std::string_view::npos) return std::nullopt; if (negative) return Clock::time_point::min(); const std::int64_t remaining = std::chrono::duration_cast(Clock::time_point::max() - now).count() - 1; std::int64_t seconds = 0; for (const char c : text) { seconds = seconds * 10 + (c - '0'); if (seconds >= remaining) return Clock::time_point::max(); } if (seconds == 0) return Clock::time_point::min(); return now + std::chrono::seconds{seconds}; } bool expired(const Cookie& cookie, Clock::time_point now) { return cookie.expiry && *cookie.expiry <= now; } std::uint64_t cookieSize(const Cookie& cookie) { return cookie.name.size() + cookie.value.size(); } std::uint64_t storedSize(const Cookie& cookie) { return cookie.name.size() + cookie.value.size() + cookie.domain.size() + cookie.path.size() + 5; } std::uint64_t jarSize(const CookieJar& jar) { std::uint64_t size = 0; for (const Cookie& cookie : jar.cookies) size += storedSize(cookie); return size; } void evictOldest(CookieJar& jar, const std::string* domain, std::uint64_t newest) { auto oldest = jar.cookies.end(); for (auto it = jar.cookies.begin(); it != jar.cookies.end(); ++it) { if ((domain && it->domain != *domain) || it->creation == newest) continue; if (oldest == jar.cookies.end() || it->creation < oldest->creation) oldest = it; } if (oldest == jar.cookies.end()) return; jar.cookies.erase(oldest); ++jar.removedNum; } void evictBatch(CookieJar& jar, std::uint64_t newest) { for (size_t index = 0; index < EvictedAtOnce && jar.cookies.size() > 1; ++index) evictOldest(jar, nullptr, newest); } void enforceLimits(CookieJar& jar, const std::string& domain, std::uint64_t newest) { while (std::count_if(jar.cookies.begin(), jar.cookies.end(), [&](const Cookie& cookie) { return cookie.domain == domain; }) > jar.maxNumPerDomain) evictOldest(jar, &domain, 0); if (jar.cookies.size() > jar.maxNum) evictBatch(jar, newest); while (jar.cookies.size() > 1 && jarSize(jar) > jar.totalMaxSize) evictBatch(jar, newest); jar.peakSize = std::max(jar.peakSize, jarSize(jar)); jar.peakNum = std::max(jar.peakNum, static_cast(jar.cookies.size())); } int storeCookie(CookieJar& jar, const RequestUrl& url, std::string_view header, Clock::time_point now) { const size_t pairEnd = header.find(';'); const std::string_view pair = header.substr(0, pairEnd); const size_t equals = pair.find('='); Cookie cookie; if (equals == std::string_view::npos) { cookie.name = trimmed(pair); } else { cookie.name = trimmed(pair.substr(0, equals)); cookie.value = trimmed(pair.substr(equals + 1)); } if (cookie.name.empty() && cookie.value.empty()) return ERROR_INVALID_VALUE; std::optional expires; std::optional maxAge; std::optional domainSpelling; std::optional path; std::string_view attributes = pairEnd == std::string_view::npos ? std::string_view{} : header.substr(pairEnd + 1); while (!attributes.empty()) { const size_t end = attributes.find(';'); const std::string_view attribute = attributes.substr(0, end); attributes = end == std::string_view::npos ? std::string_view{} : attributes.substr(end + 1); const size_t split = attribute.find('='); const std::string_view name = trimmed(attribute.substr(0, split)); const std::string_view value = split == std::string_view::npos ? std::string_view{} : trimmed(attribute.substr(split + 1)); if (equalsIgnoreCase(name, "expires")) { if (const auto date = parseCookieDate(value)) expires = date; } else if (equalsIgnoreCase(name, "max-age")) { if (const auto age = parseMaxAge(value, now)) maxAge = age; } else if (equalsIgnoreCase(name, "domain")) { if (!value.empty()) domainSpelling = std::string(value); } else if (equalsIgnoreCase(name, "path")) { path = value.empty() || value.front() != '/' ? defaultPath(url.path) : std::string(value); } else if (equalsIgnoreCase(name, "secure")) { cookie.secure = true; } } cookie.expiry = maxAge ? maxAge : expires; if (domainSpelling) { const std::string_view spelling = *domainSpelling; cookie.domain = lowered(spelling.starts_with('.') ? spelling.substr(1) : spelling); if (!allowedDomain(cookie.domain)) return ERROR_INVALID_VALUE; if (!domainMatches(url.host, cookie.domain)) return ERROR_PARSE_HTTP_INVALID_VALUE; cookie.domainSpelling = *domainSpelling; } else { cookie.domain = url.host; cookie.domainSpelling = url.host; } cookie.path = path ? *path : defaultPath(url.path); if (cookieSize(cookie) > jar.maxSize || storedSize(cookie) > jar.maxSize + StoredSizeSlack) return ERROR_OUT_OF_SIZE; std::erase_if(jar.cookies, [&](const Cookie& stored) { return stored.name == cookie.name && stored.domainSpelling == cookie.domainSpelling && stored.path == cookie.path; }); if (expired(cookie, now)) return 0; cookie.creation = ++g_cookieClock; const std::uint64_t newest = cookie.creation; const std::string domain = cookie.domain; const auto last = std::find_if(jar.cookies.rbegin(), jar.cookies.rend(), [&](const Cookie& stored) { return stored.domain == domain; }); jar.cookies.insert(last == jar.cookies.rend() ? jar.cookies.end() : std::prev(last.base()), std::move(cookie)); enforceLimits(jar, domain, newest); return 0; } std::string headerItem(const Cookie& cookie) { if (cookie.name.empty()) return cookie.value; if (cookie.value.empty()) return cookie.name; return cookie.name + '=' + cookie.value; } CookieJar* findJar(int contextId) { return IsHttpContext(contextId) ? &g_jars[contextId] : nullptr; } int setLimit(int contextId, std::uint32_t value, void (*apply)(CookieJar&, std::uint32_t)) { std::lock_guard lock(g_cookieMutex); CookieJar* jar = findJar(contextId); if (!jar) return ERROR_INVALID_ID; jar->cookies.clear(); apply(*jar, value); return 0; } constexpr std::array CookieExportMagic{'A', 'P', 'S', '5', 'C', 'K', '1', 0}; void appendU32(std::vector& output, std::uint32_t value) { for (int shift = 0; shift < 32; shift += 8) output.push_back(static_cast(value >> shift)); } void appendU64(std::vector& output, std::uint64_t value) { for (int shift = 0; shift < 64; shift += 8) output.push_back(static_cast(value >> shift)); } void appendString(std::vector& output, const std::string& text) { appendU32(output, static_cast(text.size())); output.insert(output.end(), text.begin(), text.end()); } bool take(std::vector::const_iterator& cursor, std::vector::const_iterator end, void* destination, std::size_t bytes) { if (static_cast(end - cursor) < bytes) return false; std::memcpy(destination, &*cursor, bytes); cursor += bytes; return true; } bool takeU32(std::vector::const_iterator& cursor, std::vector::const_iterator end, std::uint32_t& value) { value = 0; for (int shift = 0; shift < 32; shift += 8) { std::uint8_t byte = 0; if (!take(cursor, end, &byte, 1)) return false; value |= static_cast(byte) << shift; } return true; } bool takeU64(std::vector::const_iterator& cursor, std::vector::const_iterator end, std::uint64_t& value) { value = 0; for (int shift = 0; shift < 64; shift += 8) { std::uint8_t byte = 0; if (!take(cursor, end, &byte, 1)) return false; value |= static_cast(byte) << shift; } return true; } bool takeString(std::vector::const_iterator& cursor, std::vector::const_iterator end, std::string& text) { std::uint32_t length = 0; if (!takeU32(cursor, end, length)) return false; if (static_cast(end - cursor) < length) return false; if (length == 0) { text.clear(); return true; } text.assign(reinterpret_cast(&*cursor), length); cursor += length; return true; } bool guestWrite(std::size_t* destination, std::size_t value) { return GuestCopyOut_nid_no_patch(destination, &value, sizeof(value)); } std::vector exportBlob(const CookieJar& jar) { std::vector output(CookieExportMagic.begin(), CookieExportMagic.end()); appendU32(output, static_cast(jar.cookies.size())); for (const Cookie& cookie : jar.cookies) { appendString(output, cookie.name); appendString(output, cookie.value); appendString(output, cookie.domainSpelling); appendString(output, cookie.domain); appendString(output, cookie.path); output.push_back(cookie.secure ? 1 : 0); output.push_back(cookie.expiry ? 1 : 0); const std::int64_t seconds = cookie.expiry ? std::chrono::duration_cast(cookie.expiry->time_since_epoch()).count() : 0; appendU64(output, static_cast(seconds)); appendU64(output, cookie.creation); } return output; } bool importBlob(const std::vector& input, std::vector& cookies) { auto cursor = input.begin(); const auto end = input.end(); if (static_cast(end - cursor) < CookieExportMagic.size()) return false; if (!std::equal(CookieExportMagic.begin(), CookieExportMagic.end(), cursor)) return false; cursor += CookieExportMagic.size(); std::uint32_t count = 0; if (!takeU32(cursor, end, count)) return false; if (count > static_cast(end - cursor) / 38) return false; cookies.clear(); cookies.reserve(count); for (std::uint32_t index = 0; index < count; ++index) { Cookie cookie; if (!takeString(cursor, end, cookie.name) || !takeString(cursor, end, cookie.value) || !takeString(cursor, end, cookie.domainSpelling) || !takeString(cursor, end, cookie.domain) || !takeString(cursor, end, cookie.path)) { return false; } std::uint8_t secure = 0; std::uint8_t hasExpiry = 0; std::uint64_t seconds = 0; if (!take(cursor, end, &secure, 1) || !take(cursor, end, &hasExpiry, 1) || secure > 1 || hasExpiry > 1 || !takeU64(cursor, end, seconds) || !takeU64(cursor, end, cookie.creation)) { return false; } cookie.secure = secure != 0; if (hasExpiry != 0) { const std::int64_t signedSeconds = seconds > static_cast(std::numeric_limits::max()) ? std::numeric_limits::max() : static_cast(seconds); cookie.expiry = clampedTime(std::chrono::sys_seconds{std::chrono::seconds{signedSeconds}}); } if (cookie.name.empty() && cookie.value.empty()) return false; if (cookie.domain.empty() || cookie.path.empty() || cookie.path.front() != '/') return false; cookies.push_back(std::move(cookie)); } return cursor == end; } } void ClearHttpCookieJar(int contextId) { std::lock_guard lock(g_cookieMutex); if (const auto jar = g_jars.find(contextId); jar != g_jars.end()) jar->second.cookies.clear(); } void RemoveHttpCookieJar(int contextId) { std::lock_guard lock(g_cookieMutex); g_jars.erase(contextId); } extern "C" { int APS5_VABI sceHttpAddCookie(int contextId, const char* url, const char* cookie, std::size_t size) { std::lock_guard lock(g_cookieMutex); CookieJar* jar = findJar(contextId); if (!jar) return ERROR_INVALID_ID; if (!url || !cookie) return ERROR_INVALID_VALUE; RequestUrl parsed; if (const int result = parseUrl(url, parsed); result != 0) return result; std::string header; if (!HttpGuest::CopyText(cookie, size, header)) return ERROR_INVALID_VALUE; return storeCookie(*jar, parsed, header, Clock::now()); } int APS5_VABI sceHttpGetCookie(int contextId, const char* url, char* cookie, std::size_t* required, std::size_t prepared) { std::lock_guard lock(g_cookieMutex); CookieJar* jar = findJar(contextId); if (!jar) return ERROR_INVALID_ID; if (!url) return ERROR_INVALID_VALUE; RequestUrl parsed; if (const int result = parseUrl(url, parsed); result != 0) return result; const auto now = Clock::now(); std::erase_if(jar->cookies, [&](const Cookie& stored) { return expired(stored, now); }); std::vector matches; for (const Cookie& stored : jar->cookies) { if (domainMatches(parsed.host, stored.domain) && pathMatches(parsed.path, stored.path) && (!stored.secure || parsed.secure)) matches.push_back(&stored); } if (matches.empty()) return ERROR_HTTP_NOT_FOUND; if (!cookie && !required) return ERROR_INVALID_VALUE; std::stable_sort(matches.begin(), matches.end(), [](const Cookie* left, const Cookie* right) { if (left->path.size() != right->path.size()) return left->path.size() > right->path.size(); return left->domain.size() > right->domain.size(); }); std::vector items; size_t length = 0; for (const Cookie* stored : matches) { items.push_back(headerItem(*stored)); length += (items.size() > 1 ? 2 : 0) + items.back().size(); } const size_t total = length + 3; if (!cookie) { if (!guestWrite(required, total)) return ERROR_INVALID_VALUE; return 0; } if (prepared < total) { std::string partial; for (const std::string& item : items) { const size_t next = partial.size() + (!partial.empty() ? 2 : 0) + item.size(); if (next + 1 > prepared) break; if (!partial.empty()) partial += "; "; partial += item; } if (prepared != 0) { partial.push_back('\0'); if (!GuestCopyOut_nid_no_patch(cookie, partial.data(), partial.size())) return ERROR_INVALID_VALUE; } return ERROR_OUT_OF_SIZE; } std::string joined; for (const std::string& item : items) { if (!joined.empty()) joined += "; "; joined += item; } joined.append("\0 \0", 3); if (!GuestCopyOut_nid_no_patch(cookie, joined.data(), joined.size())) return ERROR_INVALID_VALUE; if (required && !guestWrite(required, total)) return ERROR_INVALID_VALUE; return 0; } int APS5_VABI sceHttpSetCookieTotalMaxSize(int contextId, std::uint32_t size) { return setLimit(contextId, size, [](CookieJar& jar, std::uint32_t value) { jar.totalMaxSize = value; }); } int APS5_VABI sceHttpSetCookieMaxSize(int contextId, std::uint32_t size) { return setLimit(contextId, size, [](CookieJar& jar, std::uint32_t value) { jar.maxSize = value; }); } int APS5_VABI sceHttpSetCookieMaxNum(int contextId, std::uint32_t count) { return setLimit(contextId, count, [](CookieJar& jar, std::uint32_t value) { jar.maxNum = value; }); } int APS5_VABI sceHttpSetCookieMaxNumPerDomain(int contextId, std::uint32_t count) { return setLimit(contextId, count, [](CookieJar& jar, std::uint32_t value) { jar.maxNumPerDomain = value; }); } int APS5_VABI sceHttpGetCookieStats(int id, HttpCookieStats* stats) { std::lock_guard lock(g_cookieMutex); CookieJar* jar = findJar(id); if (!jar) return ERROR_INVALID_ID; if (!stats) return ERROR_INVALID_VALUE; std::erase_if(jar->cookies, [now = Clock::now()](const Cookie& stored) { return expired(stored, now); }); HttpCookieStats out{}; if (!GuestCopyIn_nid_no_patch(&out, stats, sizeof(out))) return ERROR_INVALID_VALUE; out.usedBytes = jarSize(*jar); out.cookieCount = static_cast(jar->cookies.size()); out.peakUsedBytes = jar->peakSize; out.peakCookieCount = jar->peakNum; out.evictedCookieCount = jar->removedNum; if (!GuestCopyOut_nid_no_patch(stats, &out, sizeof(out))) return ERROR_INVALID_VALUE; return 0; } extern "C++" { int ExportHttpCookies(int contextId, void* buffer, std::size_t size, std::size_t* requiredSize) { std::vector blob; { std::lock_guard lock(g_cookieMutex); CookieJar* jar = findJar(contextId); if (!jar) return ERROR_INVALID_ID; if (!requiredSize) return ERROR_INVALID_VALUE; std::erase_if(jar->cookies, [now = Clock::now()](const Cookie& stored) { return expired(stored, now); }); try { blob = exportBlob(*jar); } catch (const std::bad_alloc&) { return ERROR_OUT_OF_MEMORY; } } const std::size_t required = blob.size(); if (!guestWrite(requiredSize, required)) return ERROR_INVALID_VALUE; if (!buffer) return 0; if (size < required) return ERROR_OUT_OF_SIZE; const bool written = GuestCopyOut_nid_no_patch(buffer, blob.data(), required); return written ? 0 : ERROR_INVALID_VALUE; } int ImportHttpCookies(int contextId, const void* buffer, std::size_t size) { std::uint64_t maximumSize = 0; { std::lock_guard lock(g_cookieMutex); CookieJar* jar = findJar(contextId); if (!jar) return ERROR_INVALID_ID; maximumSize = CookieExportMagic.size() + static_cast(jar->maxNum) * 38 + jar->totalMaxSize; } if (!buffer || size < CookieExportMagic.size()) return ERROR_INVALID_VALUE; if (size > maximumSize) return ERROR_OUT_OF_SIZE; std::vector input; std::vector cookies; try { input.resize(size); } catch (const std::bad_alloc&) { return ERROR_OUT_OF_MEMORY; } const bool read = GuestCopyIn_nid_no_patch(input.data(), buffer, size); if (!read) return ERROR_INVALID_VALUE; try { if (!importBlob(input, cookies)) return ERROR_INVALID_VALUE; } catch (const std::bad_alloc&) { return ERROR_OUT_OF_MEMORY; } const auto now = Clock::now(); std::erase_if(cookies, [&](const Cookie& cookie) { return expired(cookie, now); }); std::lock_guard lock(g_cookieMutex); CookieJar* jar = findJar(contextId); if (!jar) return ERROR_INVALID_ID; std::uint64_t stored = 0; std::unordered_map perDomain; try { for (const Cookie& cookie : cookies) { if (cookieSize(cookie) > jar->maxSize || storedSize(cookie) > jar->maxSize + StoredSizeSlack) return ERROR_OUT_OF_SIZE; if (++perDomain[cookie.domain] > jar->maxNumPerDomain) return ERROR_OUT_OF_SIZE; stored += storedSize(cookie); } } catch (const std::bad_alloc&) { return ERROR_OUT_OF_MEMORY; } if (cookies.size() > jar->maxNum || stored > jar->totalMaxSize) return ERROR_OUT_OF_SIZE; for (Cookie& cookie : cookies) { if (cookie.creation == 0) cookie.creation = ++g_cookieClock; else g_cookieClock = std::max(g_cookieClock, cookie.creation); } jar->cookies = std::move(cookies); jar->removedNum = 0; jar->peakSize = jarSize(*jar); jar->peakNum = static_cast(jar->cookies.size()); return 0; } } }