CCF
Loading...
Searching...
No Matches
http_etag.h
Go to the documentation of this file.
1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the Apache 2.0 License.
3#pragma once
4
5#define FMT_HEADER_ONLY
6#include <exception>
7#include <regex>
8#include <set>
9#include <string>
10
11namespace ccf::http
12{
14 class MatcherError : public std::exception
15 {
16 private:
17 std::string msg;
18
19 public:
20 MatcherError(std::string msg_) : msg(std::move(msg_)) {}
21
22 [[nodiscard]] const char* what() const noexcept override
23 {
24 return msg.c_str();
25 }
26 };
27
31 class Matcher
32 {
33 private:
35 bool any_value = false;
37 std::set<std::string> if_etags;
38
39 public:
44 Matcher(const std::string& match_header)
45 {
46 if (match_header == "*")
47 {
48 any_value = true;
49 return;
50 }
51
52 std::regex etag_rx(R"(\"([^\"]+)\",?\s*)");
53 auto etags_begin =
54 std::sregex_iterator(match_header.begin(), match_header.end(), etag_rx);
55 auto etags_end = std::sregex_iterator();
56 ssize_t last_matched = 0;
57
58 for (std::sregex_iterator i = etags_begin; i != etags_end; ++i)
59 {
60 if (i->position() != last_matched)
61 {
62 throw MatcherError("Invalid If-Match header");
63 }
64 const std::smatch& match = *i;
65 if_etags.insert(match[1].str());
66 last_matched = match.position() + match.length();
67 }
68
69 ssize_t last_index_in_header = match_header.size();
70
71 if (last_matched != last_index_in_header || if_etags.empty())
72 {
73 throw MatcherError("Invalid If-Match header");
74 }
75 }
76
78 [[nodiscard]] bool matches(const std::string& etag) const
79 {
80 return any_value || if_etags.contains(etag);
81 }
82
84 [[nodiscard]] bool is_any() const
85 {
86 return any_value;
87 }
88 };
89}
Definition http_etag.h:15
MatcherError(std::string msg_)
Definition http_etag.h:20
const char * what() const noexcept override
Definition http_etag.h:22
Definition http_etag.h:32
bool matches(const std::string &etag) const
Check if a given ETag matches the If-Match/If-None-Match header.
Definition http_etag.h:78
Matcher(const std::string &match_header)
Definition http_etag.h:44
bool is_any() const
Check if the header will match any ETag (*)
Definition http_etag.h:84
Definition http_accept.h:13
STL namespace.