Skip to content

Commit 1729aa8

Browse files
authored
Issue 2162 (#2163)
* Resolve #2162 * Update
1 parent aabd063 commit 1729aa8

File tree

4 files changed

+463
-2
lines changed

4 files changed

+463
-2
lines changed

example/Makefile

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ ZLIB_SUPPORT = -DCPPHTTPLIB_ZLIB_SUPPORT -lz
1818
BROTLI_DIR = $(PREFIX)/opt/brotli
1919
BROTLI_SUPPORT = -DCPPHTTPLIB_BROTLI_SUPPORT -I$(BROTLI_DIR)/include -L$(BROTLI_DIR)/lib -lbrotlicommon -lbrotlienc -lbrotlidec
2020

21-
all: server client hello simplecli simplesvr upload redirect ssesvr ssecli benchmark one_time_request server_and_client
21+
all: server client hello simplecli simplesvr upload redirect ssesvr ssecli benchmark one_time_request server_and_client accept_header
2222

2323
server : server.cc ../httplib.h Makefile
2424
$(CXX) -o server $(CXXFLAGS) server.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT) $(BROTLI_SUPPORT)
@@ -56,9 +56,12 @@ one_time_request : one_time_request.cc ../httplib.h Makefile
5656
server_and_client : server_and_client.cc ../httplib.h Makefile
5757
$(CXX) -o server_and_client $(CXXFLAGS) server_and_client.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT) $(BROTLI_SUPPORT)
5858

59+
accept_header : accept_header.cc ../httplib.h Makefile
60+
$(CXX) -o accept_header $(CXXFLAGS) accept_header.cc $(OPENSSL_SUPPORT) $(ZLIB_SUPPORT) $(BROTLI_SUPPORT)
61+
5962
pem:
6063
openssl genrsa 2048 > key.pem
6164
openssl req -new -key key.pem | openssl x509 -days 3650 -req -signkey key.pem > cert.pem
6265

6366
clean:
64-
rm server client hello simplecli simplesvr upload redirect ssesvr ssecli benchmark one_time_request server_and_client *.pem
67+
rm server client hello simplecli simplesvr upload redirect ssesvr ssecli benchmark one_time_request server_and_client accept_header *.pem

example/accept_header.cc

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
#include "httplib.h"
2+
#include <iostream>
3+
4+
int main() {
5+
using namespace httplib;
6+
7+
// Example usage of parse_accept_header function
8+
std::cout << "=== Accept Header Parser Example ===" << std::endl;
9+
10+
// Example 1: Simple Accept header
11+
std::string accept1 = "text/html,application/json,text/plain";
12+
std::vector<std::string> result1;
13+
if (detail::parse_accept_header(accept1, result1)) {
14+
std::cout << "\nExample 1: " << accept1 << std::endl;
15+
std::cout << "Parsed order:" << std::endl;
16+
for (size_t i = 0; i < result1.size(); ++i) {
17+
std::cout << " " << (i + 1) << ". " << result1[i] << std::endl;
18+
}
19+
} else {
20+
std::cout << "\nExample 1: Failed to parse Accept header" << std::endl;
21+
}
22+
23+
// Example 2: Accept header with quality values
24+
std::string accept2 = "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8";
25+
std::vector<std::string> result2;
26+
if (detail::parse_accept_header(accept2, result2)) {
27+
std::cout << "\nExample 2: " << accept2 << std::endl;
28+
std::cout << "Parsed order (sorted by priority):" << std::endl;
29+
for (size_t i = 0; i < result2.size(); ++i) {
30+
std::cout << " " << (i + 1) << ". " << result2[i] << std::endl;
31+
}
32+
} else {
33+
std::cout << "\nExample 2: Failed to parse Accept header" << std::endl;
34+
}
35+
36+
// Example 3: Browser-like Accept header
37+
std::string accept3 = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
38+
std::vector<std::string> result3;
39+
if (detail::parse_accept_header(accept3, result3)) {
40+
std::cout << "\nExample 3: " << accept3 << std::endl;
41+
std::cout << "Parsed order:" << std::endl;
42+
for (size_t i = 0; i < result3.size(); ++i) {
43+
std::cout << " " << (i + 1) << ". " << result3[i] << std::endl;
44+
}
45+
} else {
46+
std::cout << "\nExample 3: Failed to parse Accept header" << std::endl;
47+
}
48+
49+
// Example 4: Invalid Accept header examples
50+
std::cout << "\n=== Invalid Accept Header Examples ===" << std::endl;
51+
52+
std::vector<std::string> invalid_examples = {
53+
"text/html;q=1.5,application/json", // q > 1.0
54+
"text/html;q=-0.1,application/json", // q < 0.0
55+
"text/html;q=invalid,application/json", // invalid q value
56+
"invalidtype,application/json", // invalid media type
57+
",application/json" // empty entry
58+
};
59+
60+
for (const auto& invalid_accept : invalid_examples) {
61+
std::vector<std::string> temp_result;
62+
std::cout << "\nTesting invalid: " << invalid_accept << std::endl;
63+
if (detail::parse_accept_header(invalid_accept, temp_result)) {
64+
std::cout << " Unexpectedly succeeded!" << std::endl;
65+
} else {
66+
std::cout << " Correctly rejected as invalid" << std::endl;
67+
}
68+
}
69+
70+
// Example 4: Server usage example
71+
std::cout << "\n=== Server Usage Example ===" << std::endl;
72+
Server svr;
73+
74+
svr.Get("/api/data", [](const Request& req, Response& res) {
75+
// Get Accept header
76+
auto accept_header = req.get_header_value("Accept");
77+
if (accept_header.empty()) {
78+
accept_header = "*/*"; // Default if no Accept header
79+
}
80+
81+
// Parse accept header to get preferred content types
82+
std::vector<std::string> preferred_types;
83+
if (!detail::parse_accept_header(accept_header, preferred_types)) {
84+
// Invalid Accept header
85+
res.status = 400; // Bad Request
86+
res.set_content("Invalid Accept header", "text/plain");
87+
return;
88+
}
89+
90+
std::cout << "Client Accept header: " << accept_header << std::endl;
91+
std::cout << "Preferred types in order:" << std::endl;
92+
for (size_t i = 0; i < preferred_types.size(); ++i) {
93+
std::cout << " " << (i + 1) << ". " << preferred_types[i] << std::endl;
94+
}
95+
96+
// Choose response format based on client preference
97+
std::string response_content;
98+
std::string content_type;
99+
100+
for (const auto& type : preferred_types) {
101+
if (type == "application/json" || type == "application/*" || type == "*/*") {
102+
response_content = "{\"message\": \"Hello, World!\", \"data\": [1, 2, 3]}";
103+
content_type = "application/json";
104+
break;
105+
} else if (type == "text/html" || type == "text/*") {
106+
response_content = "<html><body><h1>Hello, World!</h1><p>Data: 1, 2, 3</p></body></html>";
107+
content_type = "text/html";
108+
break;
109+
} else if (type == "text/plain") {
110+
response_content = "Hello, World!\nData: 1, 2, 3";
111+
content_type = "text/plain";
112+
break;
113+
}
114+
}
115+
116+
if (response_content.empty()) {
117+
// No supported content type found
118+
res.status = 406; // Not Acceptable
119+
res.set_content("No acceptable content type found", "text/plain");
120+
return;
121+
}
122+
123+
res.set_content(response_content, content_type);
124+
std::cout << "Responding with: " << content_type << std::endl;
125+
});
126+
127+
std::cout << "Server configured. You can test it with:" << std::endl;
128+
std::cout << " curl -H \"Accept: application/json\" http://localhost:8080/api/data" << std::endl;
129+
std::cout << " curl -H \"Accept: text/html\" http://localhost:8080/api/data" << std::endl;
130+
std::cout << " curl -H \"Accept: text/plain\" http://localhost:8080/api/data" << std::endl;
131+
std::cout << " curl -H \"Accept: text/html;q=0.9,application/json;q=1.0\" http://localhost:8080/api/data" << std::endl;
132+
133+
return 0;
134+
}

httplib.h

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,7 @@ struct Request {
670670
std::function<bool()> is_connection_closed = []() { return true; };
671671

672672
// for client
673+
std::vector<std::string> accept_content_types;
673674
ResponseHandler response_handler;
674675
ContentReceiverWithProgress content_receiver;
675676
Progress progress;
@@ -2491,6 +2492,9 @@ bool parse_multipart_boundary(const std::string &content_type,
24912492

24922493
bool parse_range_header(const std::string &s, Ranges &ranges);
24932494

2495+
bool parse_accept_header(const std::string &s,
2496+
std::vector<std::string> &content_types);
2497+
24942498
int close_socket(socket_t sock);
24952499

24962500
ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags);
@@ -5026,6 +5030,123 @@ inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
50265030
} catch (...) { return false; }
50275031
#endif
50285032

5033+
inline bool parse_accept_header(const std::string &s,
5034+
std::vector<std::string> &content_types) {
5035+
content_types.clear();
5036+
5037+
// Empty string is considered valid (no preference)
5038+
if (s.empty()) { return true; }
5039+
5040+
// Check for invalid patterns: leading/trailing commas or consecutive commas
5041+
if (s.front() == ',' || s.back() == ',' ||
5042+
s.find(",,") != std::string::npos) {
5043+
return false;
5044+
}
5045+
5046+
struct AcceptEntry {
5047+
std::string media_type;
5048+
double quality;
5049+
int order; // Original order in header
5050+
};
5051+
5052+
std::vector<AcceptEntry> entries;
5053+
int order = 0;
5054+
bool has_invalid_entry = false;
5055+
5056+
// Split by comma and parse each entry
5057+
split(s.data(), s.data() + s.size(), ',', [&](const char *b, const char *e) {
5058+
std::string entry(b, e);
5059+
entry = trim_copy(entry);
5060+
5061+
if (entry.empty()) {
5062+
has_invalid_entry = true;
5063+
return;
5064+
}
5065+
5066+
AcceptEntry accept_entry;
5067+
accept_entry.quality = 1.0; // Default quality
5068+
accept_entry.order = order++;
5069+
5070+
// Find q= parameter
5071+
auto q_pos = entry.find(";q=");
5072+
if (q_pos == std::string::npos) { q_pos = entry.find("; q="); }
5073+
5074+
if (q_pos != std::string::npos) {
5075+
// Extract media type (before q parameter)
5076+
accept_entry.media_type = trim_copy(entry.substr(0, q_pos));
5077+
5078+
// Extract quality value
5079+
auto q_start = entry.find('=', q_pos) + 1;
5080+
auto q_end = entry.find(';', q_start);
5081+
if (q_end == std::string::npos) { q_end = entry.length(); }
5082+
5083+
std::string quality_str =
5084+
trim_copy(entry.substr(q_start, q_end - q_start));
5085+
if (quality_str.empty()) {
5086+
has_invalid_entry = true;
5087+
return;
5088+
}
5089+
5090+
try {
5091+
accept_entry.quality = std::stod(quality_str);
5092+
// Check if quality is in valid range [0.0, 1.0]
5093+
if (accept_entry.quality < 0.0 || accept_entry.quality > 1.0) {
5094+
has_invalid_entry = true;
5095+
return;
5096+
}
5097+
} catch (...) {
5098+
has_invalid_entry = true;
5099+
return;
5100+
}
5101+
} else {
5102+
// No quality parameter, use entire entry as media type
5103+
accept_entry.media_type = entry;
5104+
}
5105+
5106+
// Remove additional parameters from media type
5107+
auto param_pos = accept_entry.media_type.find(';');
5108+
if (param_pos != std::string::npos) {
5109+
accept_entry.media_type =
5110+
trim_copy(accept_entry.media_type.substr(0, param_pos));
5111+
}
5112+
5113+
// Basic validation of media type format
5114+
if (accept_entry.media_type.empty()) {
5115+
has_invalid_entry = true;
5116+
return;
5117+
}
5118+
5119+
// Check for basic media type format (should contain '/' or be '*')
5120+
if (accept_entry.media_type != "*" &&
5121+
accept_entry.media_type.find('/') == std::string::npos) {
5122+
has_invalid_entry = true;
5123+
return;
5124+
}
5125+
5126+
entries.push_back(accept_entry);
5127+
});
5128+
5129+
// Return false if any invalid entry was found
5130+
if (has_invalid_entry) { return false; }
5131+
5132+
// Sort by quality (descending), then by original order (ascending)
5133+
std::sort(entries.begin(), entries.end(),
5134+
[](const AcceptEntry &a, const AcceptEntry &b) {
5135+
if (a.quality != b.quality) {
5136+
return a.quality > b.quality; // Higher quality first
5137+
}
5138+
return a.order < b.order; // Earlier order first for same quality
5139+
});
5140+
5141+
// Extract sorted media types
5142+
content_types.reserve(entries.size());
5143+
for (const auto &entry : entries) {
5144+
content_types.push_back(entry.media_type);
5145+
}
5146+
5147+
return true;
5148+
}
5149+
50295150
class MultipartFormDataParser {
50305151
public:
50315152
MultipartFormDataParser() = default;
@@ -7446,6 +7567,14 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
74467567
req.set_header("LOCAL_ADDR", req.local_addr);
74477568
req.set_header("LOCAL_PORT", std::to_string(req.local_port));
74487569

7570+
if (req.has_header("Accept")) {
7571+
const auto &accept_header = req.get_header_value("Accept");
7572+
if (!detail::parse_accept_header(accept_header, req.accept_content_types)) {
7573+
res.status = StatusCode::BadRequest_400;
7574+
return write_response(strm, close_connection, req, res);
7575+
}
7576+
}
7577+
74497578
if (req.has_header("Range")) {
74507579
const auto &range_header_value = req.get_header_value("Range");
74517580
if (!detail::parse_range_header(range_header_value, req.ranges)) {

0 commit comments

Comments
 (0)