From 5509091ab8e90bc12df4375b55dee06e7496feb0 Mon Sep 17 00:00:00 2001 From: Omar Mohamed Khallaf <51155980+omarmohamedkh@users.noreply.github.com> Date: Mon, 14 Aug 2023 04:41:34 +0300 Subject: [PATCH] Perform insensitive string compare of cookie SameSite attribute (#1706) Co-authored-by: Omar Mohamed --- lib/inc/drogon/Cookie.h | 44 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/lib/inc/drogon/Cookie.h b/lib/inc/drogon/Cookie.h index bc63039d..1cfe4641 100644 --- a/lib/inc/drogon/Cookie.h +++ b/lib/inc/drogon/Cookie.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -295,25 +296,60 @@ class DROGON_EXPORT Cookie return sameSite_; } + /** + * @brief Compare two strings ignoring the their cases + * + * @param str1 string to check its value + * @param str2 string to check against, written in lower case + * + * @note the function is optimized to check for cookie's samesite value + * where we check if the value equals to a specific value we already know in + * str2. so the function doesn't apply tolower to the second argument + * str2 as it's always in lower case. + * + * @return 0 if both strings are equall ignoring case, negative value if lhs + * is smaller than rhs and vice versa + */ + static int stricmp(const string_view str1, const string_view str2) + { + auto str1Len{str1.length()}; + auto str2Len{str2.length()}; + + if (str1Len != str2Len) + return str1Len - str2Len; + + for (size_t idx{0}; idx < str1Len; ++idx) + { + auto lowerChar{tolower(str1[idx])}; + + if (lowerChar != str2[idx]) + { + return lowerChar - str2[idx]; + } + } + + return 0; + } + /** * @brief Converts a string value to its associated enum class SameSite * value */ static SameSite convertString2SameSite(const string_view &sameSite) { - if (sameSite == "Lax") + if (stricmp(sameSite, "lax") == 0) { return Cookie::SameSite::kLax; } - else if (sameSite == "Strict") + else if (stricmp(sameSite, "strict") == 0) { return Cookie::SameSite::kStrict; } - else if (sameSite == "None") + else if (stricmp(sameSite, "none") == 0) { return Cookie::SameSite::kNone; } - else if (sameSite != "Null") + else if (stricmp(sameSite, "null") != 0) { LOG_WARN << "'" << sameSite