/src/curl_fuzzer/proto_fuzzer/rtsp_mock_server.cc
Line | Count | Source |
1 | | /* |
2 | | * Copyright (C) Max Dymond, <cmeister2@gmail.com>, et al. |
3 | | * |
4 | | * SPDX-License-Identifier: curl |
5 | | */ |
6 | | |
7 | | /// @file |
8 | | /// @brief Implementation of the request-aligned in-process RTSP peer. |
9 | | |
10 | | #include "proto_fuzzer/rtsp_mock_server.h" |
11 | | |
12 | | #include <algorithm> |
13 | | #include <cstddef> |
14 | | #include <cstdint> |
15 | | #include <limits> |
16 | | #include <string> |
17 | | #include <string_view> |
18 | | #include <utility> |
19 | | |
20 | | #include "proto_fuzzer/curl_raii.h" |
21 | | |
22 | | namespace proto_fuzzer { |
23 | | |
24 | | namespace { |
25 | | |
26 | | constexpr long kSplitRtpReadBufferBytes = 1024; |
27 | | constexpr char kCrossOriginReuseUrl[] = "rtsp://rtsp-other.test/session-reuse"; |
28 | | |
29 | | /// Remove a command line's trailing CR/LF so header parsing does not treat the |
30 | | /// terminator as part of a value. |
31 | | /// @param line Complete newline-terminated line. |
32 | | /// @return The line without its line ending. |
33 | 99.4k | std::string_view TrimLineEnding(std::string_view line) { |
34 | 266k | while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) { |
35 | 167k | line.remove_suffix(1); |
36 | 167k | } |
37 | 99.4k | return line; |
38 | 99.4k | } |
39 | | |
40 | | /// Compare two ASCII tokens ignoring case. Header names are case-insensitive, |
41 | | /// and protocol bytes outside ASCII have no valid interpretation here. |
42 | | /// @param actual Observed token. |
43 | | /// @param expected Literal comparison token. |
44 | | /// @return true when both tokens contain the same case-folded ASCII bytes. |
45 | 13.7k | bool EqualsIgnoreCase(std::string_view actual, std::string_view expected) { |
46 | 13.7k | if (actual.size() != expected.size()) { |
47 | 0 | return false; |
48 | 0 | } |
49 | 88.7k | for (std::size_t index = 0; index < actual.size(); ++index) { |
50 | 76.1k | unsigned char left = static_cast<unsigned char>(actual[index]); |
51 | 76.1k | unsigned char right = static_cast<unsigned char>(expected[index]); |
52 | 76.1k | if (left >= 'a' && left <= 'z') { |
53 | 47.5k | left = static_cast<unsigned char>(left - 'a' + 'A'); |
54 | 47.5k | } |
55 | 76.1k | if (right >= 'a' && right <= 'z') { |
56 | 47.0k | right = static_cast<unsigned char>(right - 'a' + 'A'); |
57 | 47.0k | } |
58 | 76.1k | if (left != right) { |
59 | 1.18k | return false; |
60 | 1.18k | } |
61 | 76.1k | } |
62 | 12.5k | return true; |
63 | 13.7k | } |
64 | | |
65 | | /// Extract a header value from one complete header line. Only an exact |
66 | | /// case-insensitive field name followed by a colon matches, so a value that |
67 | | /// happens to contain the same text cannot be mistaken for the header. |
68 | | /// @param line Complete header line, including its line ending. |
69 | | /// @param name Case-insensitive field name without the colon. |
70 | | /// @param value Receives the trimmed value when the header matches. |
71 | | /// @return true when the field name matched. |
72 | 40.3k | bool HeaderValue(std::string_view line, std::string_view name, std::string_view* value) { |
73 | 40.3k | const std::string_view trimmed = TrimLineEnding(line); |
74 | 40.3k | if (trimmed.size() <= name.size() || trimmed[name.size()] != ':' || |
75 | 27.7k | !EqualsIgnoreCase(trimmed.substr(0, name.size()), name)) { |
76 | 27.7k | return false; |
77 | 27.7k | } |
78 | | |
79 | 12.5k | std::size_t begin = name.size() + 1; |
80 | 39.4k | while (begin < trimmed.size() && (trimmed[begin] == ' ' || trimmed[begin] == '\t')) { |
81 | 26.8k | ++begin; |
82 | 26.8k | } |
83 | 12.5k | std::string_view parsed = trimmed.substr(begin); |
84 | 18.9k | while (!parsed.empty() && (parsed.back() == ' ' || parsed.back() == '\t')) { |
85 | 6.31k | parsed.remove_suffix(1); |
86 | 6.31k | } |
87 | 12.5k | *value = parsed; |
88 | 12.5k | return true; |
89 | 40.3k | } |
90 | | |
91 | | /// Parse a non-negative decimal field without relying on locale-sensitive or |
92 | | /// throwing library conversions. Oversized values saturate, because the |
93 | | /// caller only needs a bounded amount of subsequent work. |
94 | | /// @param text Decimal digits with no sign or other characters. |
95 | | /// @param result Receives the parsed or saturated value. |
96 | | /// @return true when every byte was a decimal digit and the text was nonempty. |
97 | 12.5k | bool ParseDecimal(std::string_view text, std::uint64_t* result) { |
98 | 12.5k | if (text.empty()) { |
99 | 739 | return false; |
100 | 739 | } |
101 | 11.8k | std::uint64_t value = 0; |
102 | 31.2k | for (const char byte : text) { |
103 | 31.2k | if (byte < '0' || byte > '9') { |
104 | 1.95k | return false; |
105 | 1.95k | } |
106 | 29.2k | const std::uint64_t digit = static_cast<std::uint64_t>(byte - '0'); |
107 | 29.2k | if (value > (std::numeric_limits<std::uint64_t>::max() - digit) / 10U) { |
108 | 856 | value = std::numeric_limits<std::uint64_t>::max(); |
109 | 28.4k | } else { |
110 | 28.4k | value = value * 10U + digit; |
111 | 28.4k | } |
112 | 29.2k | } |
113 | 9.89k | *result = value; |
114 | 9.89k | return true; |
115 | 11.8k | } |
116 | | |
117 | | /// Recognize the empty line that terminates an RTSP request header block. |
118 | | /// @param line Complete line, including its line ending. |
119 | | /// @return true when the line contains no bytes before its line ending. |
120 | 42.0k | bool IsBlankLine(std::string_view line) { return TrimLineEnding(line).empty(); } |
121 | | |
122 | | /// Keep one response per transfer while the lifecycle probe repeats the easy |
123 | | /// handle. Ordinary RTSP scenarios interpret on_readable entries as replies |
124 | | /// to successive requests; the probe maps the first three entries onto its |
125 | | /// sequential transfers without exposing another URL or lifecycle count. |
126 | | curl::fuzzer::proto::Scenario SelectTransferResponse(const curl::fuzzer::proto::Scenario& scenario, |
127 | 3 | int response_index) { |
128 | 3 | curl::fuzzer::proto::Scenario selected = scenario; |
129 | 3 | auto* connection = selected.mutable_connection(); |
130 | 3 | std::string response; |
131 | 3 | const bool has_response = response_index >= 0 && response_index < scenario.connection().on_readable_size(); |
132 | 3 | if (has_response) { |
133 | 3 | response = scenario.connection().on_readable(response_index); |
134 | 3 | } |
135 | 3 | connection->clear_on_readable(); |
136 | 3 | if (has_response) { |
137 | 3 | connection->add_on_readable(std::move(response)); |
138 | 3 | } |
139 | 3 | return selected; |
140 | 3 | } |
141 | | |
142 | | } // namespace |
143 | | |
144 | | /// Begin without a borrowed protobuf or open socketpair. RunLoop borrows a |
145 | | /// Scenario only for the synchronous drive in which socket callbacks can run. |
146 | | RtspMockServer::RtspMockServer() |
147 | 7.85k | : in_request_(false), |
148 | 7.85k | in_headers_(false), |
149 | 7.85k | have_client_cseq_(false), |
150 | 7.85k | have_content_length_(false), |
151 | 7.85k | client_cseq_(0), |
152 | 7.85k | last_client_cseq_(0), |
153 | 7.85k | content_length_(0), |
154 | 7.85k | request_count_(0), |
155 | 7.85k | response_count_(0), |
156 | 7.85k | probe_mode_(curl::fuzzer::proto::RTSP_PROBE_DEFAULT), |
157 | 7.85k | client_write_failure_count_(0), |
158 | 7.85k | opened_transport_count_(0) {} |
159 | | |
160 | | /// Release the server-owned socketpair half after curl has returned its client |
161 | | /// descriptor. The out-of-line destructor keeps inherited transport ownership |
162 | | /// local to this translation unit. |
163 | 7.85k | RtspMockServer::~RtspMockServer() = default; |
164 | | |
165 | | /// Install only the callback and receive-buffer boundary required by the |
166 | | /// split-RTP probe. The callback otherwise consumes bytes exactly like the |
167 | | /// baseline sink, so enabling the closed mode changes behavior only for the |
168 | | /// single buffered '$' byte selected below. |
169 | | /// @param easy Borrowed easy handle whose callback and receive buffer may be |
170 | | /// configured. |
171 | | /// @param mode Closed RTSP probe selected by the normalized scenario. |
172 | 7.82k | void RtspMockServer::ConfigureClient(CURL* easy, curl::fuzzer::proto::RtspProbeMode mode) { |
173 | 7.82k | probe_mode_ = mode; |
174 | 7.82k | client_write_failure_count_ = 0; |
175 | 7.82k | opened_transport_count_ = 0; |
176 | 7.82k | if (easy == nullptr || mode != curl::fuzzer::proto::RTSP_PROBE_SPLIT_INVALID_RTP_WRITE_FAILURE) { |
177 | 7.82k | return; |
178 | 7.82k | } |
179 | 1 | (void)curl_easy_setopt(easy, CURLOPT_BUFFERSIZE, kSplitRtpReadBufferBytes); |
180 | 1 | (void)curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, &RtspMockServer::ProbeWriteCallback); |
181 | 1 | (void)curl_easy_setopt(easy, CURLOPT_WRITEDATA, this); |
182 | 1 | } |
183 | | |
184 | | /// Fail only curl's attempt to release a buffered one-byte '$' marker as |
185 | | /// ordinary response body data. Earlier padding and all other callback shapes |
186 | | /// are consumed normally, so the failure is tied to the invalid-channel state |
187 | | /// transition rather than to an allocation or callback ordinal. |
188 | 2 | std::size_t RtspMockServer::ProbeWriteCallback(char* contents, std::size_t size, std::size_t nmemb, void* userdata) { |
189 | 2 | auto* server = static_cast<RtspMockServer*>(userdata); |
190 | 2 | const std::size_t bytes = size * nmemb; |
191 | 2 | if (server != nullptr && server->client_write_failure_count_ == 0 && bytes == 1 && contents != nullptr && |
192 | 1 | contents[0] == '$') { |
193 | 1 | ++server->client_write_failure_count_; |
194 | 1 | return 0; |
195 | 1 | } |
196 | 1 | return bytes; |
197 | 2 | } |
198 | | |
199 | | /// Run three ordinary OPTIONS-style exchanges through one multi connection |
200 | | /// cache. The first response can teach curl a Session ID. Closing the peer's |
201 | | /// write half leaves that completed connection cached; the same-origin second |
202 | | /// add makes curl run RTSP's liveness check before opening a replacement |
203 | | /// transport. The fixed URL for the third transfer then exercises suppression |
204 | | /// of the learned Session header across origins without accepting an |
205 | | /// input-controlled destination. |
206 | | /// @param easy Borrowed easy handle repeated across all three transfers. |
207 | | /// @param scenario Normalized RTSP script supplying one response per transfer. |
208 | | /// @return First non-success result, otherwise the final cross-origin result. |
209 | 1 | CURLcode RtspMockServer::DriveCrossOriginReuseScenario(CURL* easy, const curl::fuzzer::proto::Scenario& scenario) { |
210 | 1 | if (easy == nullptr) { |
211 | 0 | return CURLE_FAILED_INIT; |
212 | 0 | } |
213 | 1 | CurlMultiPtr multi(curl_multi_init()); |
214 | 1 | if (!multi) { |
215 | 0 | return CURLE_FAILED_INIT; |
216 | 0 | } |
217 | | |
218 | 3 | const auto drive = [&](const curl::fuzzer::proto::Scenario& transfer) { |
219 | 3 | CURLcode result = CURLE_FAILED_INIT; |
220 | 3 | if (curl_multi_add_handle(multi.get(), easy) != CURLM_OK) { |
221 | 0 | return result; |
222 | 0 | } |
223 | 3 | PingpongMockServer::RunLoop(multi.get(), easy, transfer); |
224 | 3 | int messages_remaining = 0; |
225 | 3 | CURLMsg* message = nullptr; |
226 | 6 | while ((message = curl_multi_info_read(multi.get(), &messages_remaining)) != nullptr) { |
227 | 3 | if (message->msg == CURLMSG_DONE && message->easy_handle == easy) { |
228 | 3 | result = message->data.result; |
229 | 3 | } |
230 | 3 | } |
231 | 3 | (void)curl_multi_remove_handle(multi.get(), easy); |
232 | 3 | return result; |
233 | 3 | }; |
234 | | |
235 | 1 | const curl::fuzzer::proto::Scenario first = SelectTransferResponse(scenario, 0); |
236 | 1 | const curl::fuzzer::proto::Scenario second = SelectTransferResponse(scenario, 1); |
237 | 1 | const curl::fuzzer::proto::Scenario third = SelectTransferResponse(scenario, 2); |
238 | 1 | CURLcode result = drive(first); |
239 | 1 | if (result != CURLE_OK) { |
240 | 0 | return result; |
241 | 0 | } |
242 | 1 | result = drive(second); |
243 | 1 | if (result != CURLE_OK) { |
244 | 0 | return result; |
245 | 0 | } |
246 | 1 | (void)curl_easy_setopt(easy, CURLOPT_URL, kCrossOriginReuseUrl); |
247 | 1 | return drive(third); |
248 | 1 | } |
249 | | |
250 | | /// Expose how far the bounded request stream progressed. The parser counts a |
251 | | /// request only after its header block and any announced body were consumed. |
252 | | /// @return Complete requests observed in the most recent drive. |
253 | 7.82k | std::size_t RtspMockServer::request_count() const { return request_count_; } |
254 | | |
255 | | /// Expose how many scripted replies could be released before the bounded |
256 | | /// script ran out. |
257 | | /// @return Scripted replies written in the most recent drive. |
258 | 7.82k | std::size_t RtspMockServer::response_count() const { return response_count_; } |
259 | | |
260 | | /// Expose the last parsed client sequence number so tests can verify that one |
261 | | /// request advanced the exchange exactly once. |
262 | | /// @return Last request CSeq, or zero when no parseable CSeq was present. |
263 | 7.82k | std::uint32_t RtspMockServer::last_client_cseq() const { return last_client_cseq_; } |
264 | | |
265 | | /// @return Start line of the most recently completed request. |
266 | 7.82k | const std::string& RtspMockServer::last_request_line() const { return last_request_line_; } |
267 | | |
268 | | /// @return Method token of the most recently completed request. |
269 | 0 | const std::string& RtspMockServer::last_method() const { return last_method_; } |
270 | | |
271 | | /// @return Stream URI token of the most recently completed request. |
272 | 7.82k | const std::string& RtspMockServer::last_stream_uri() const { return last_stream_uri_; } |
273 | | |
274 | | /// @return Number of semantic one-byte '$' writes rejected in the latest |
275 | | /// drive. |
276 | 7.82k | std::size_t RtspMockServer::client_write_failure_count() const { return client_write_failure_count_; } |
277 | | |
278 | | /// @return Number of control transports opened since ConfigureClient(). |
279 | 7.82k | std::size_t RtspMockServer::opened_transport_count() const { return opened_transport_count_; } |
280 | | |
281 | | /// Count successfully handed-off transports without changing the shared |
282 | | /// request-aligned socket construction. The lifecycle test uses the |
283 | | /// same-origin retry opening to establish that curl discarded the cached |
284 | | /// half-closed connection before issuing its second request. |
285 | | /// @param purpose Socket role requested by curl. |
286 | | /// @param address Destination metadata passed through to the shared peer. |
287 | | /// @return Client descriptor for a successful control transport, or |
288 | | /// CURL_SOCKET_BAD. |
289 | 7.26k | curl_socket_t RtspMockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* address) { |
290 | 7.26k | const curl_socket_t socket = PingpongMockServer::HandleOpenSocket(purpose, address); |
291 | 7.26k | if (socket != CURL_SOCKET_BAD) { |
292 | 7.26k | ++opened_transport_count_; |
293 | 7.26k | } |
294 | 7.26k | return socket; |
295 | 7.26k | } |
296 | | |
297 | | /// Clear RTSP's per-request parse state before the next drive. The shared base |
298 | | /// has already reset the transport, reply cursor, transcript, upload capture, |
299 | | /// and body mode. |
300 | 7.74k | void RtspMockServer::ResetProtocolState() { |
301 | 7.74k | in_request_ = false; |
302 | 7.74k | in_headers_ = false; |
303 | 7.74k | have_client_cseq_ = false; |
304 | 7.74k | have_content_length_ = false; |
305 | 7.74k | client_cseq_ = 0; |
306 | 7.74k | last_client_cseq_ = 0; |
307 | 7.74k | content_length_ = 0; |
308 | 7.74k | request_count_ = 0; |
309 | 7.74k | response_count_ = 0; |
310 | 7.74k | client_write_failure_count_ = 0; |
311 | 7.74k | last_request_line_.clear(); |
312 | 7.74k | last_method_.clear(); |
313 | 7.74k | last_stream_uri_.clear(); |
314 | 7.74k | } |
315 | | |
316 | | /// Start a new request after the previous one completed. The request line is |
317 | | /// parsed for observability, while the reply itself stays scripted. |
318 | | /// @param line Complete request start line, including its line ending. |
319 | 17.0k | void RtspMockServer::BeginRequest(std::string_view line) { |
320 | 17.0k | const std::string_view trimmed = TrimLineEnding(line); |
321 | 17.0k | last_request_line_.assign(trimmed.data(), trimmed.size()); |
322 | 17.0k | const std::string_view method = FirstToken(trimmed); |
323 | 17.0k | const std::string_view stream_uri = SecondToken(trimmed); |
324 | 17.0k | last_method_.assign(method.data(), method.size()); |
325 | 17.0k | last_stream_uri_.assign(stream_uri.data(), stream_uri.size()); |
326 | | |
327 | 17.0k | in_request_ = true; |
328 | 17.0k | in_headers_ = true; |
329 | 17.0k | have_client_cseq_ = false; |
330 | 17.0k | have_content_length_ = false; |
331 | 17.0k | client_cseq_ = 0; |
332 | 17.0k | content_length_ = 0; |
333 | 17.0k | } |
334 | | |
335 | | /// Parse the two headers that change how the peer stays synchronized. Other |
336 | | /// headers remain part of the transcript and are otherwise opaque to the peer. |
337 | | /// @param line Complete header line, including its line ending. |
338 | 25.2k | void RtspMockServer::ParseHeader(std::string_view line) { |
339 | 25.2k | std::string_view value; |
340 | 25.2k | if (HeaderValue(line, "CSeq", &value)) { |
341 | 10.2k | std::uint64_t parsed = 0; |
342 | 10.2k | if (ParseDecimal(value, &parsed)) { |
343 | 8.62k | have_client_cseq_ = true; |
344 | 8.62k | client_cseq_ = |
345 | 8.62k | static_cast<std::uint32_t>(std::min<std::uint64_t>(parsed, std::numeric_limits<std::uint32_t>::max())); |
346 | 8.62k | } |
347 | 10.2k | return; |
348 | 10.2k | } |
349 | | |
350 | 15.0k | if (HeaderValue(line, "Content-Length", &value)) { |
351 | 2.38k | std::uint64_t parsed = 0; |
352 | 2.38k | if (ParseDecimal(value, &parsed)) { |
353 | 1.27k | have_content_length_ = true; |
354 | 1.27k | content_length_ = |
355 | 1.27k | static_cast<std::size_t>(std::min<std::uint64_t>(parsed, std::numeric_limits<std::size_t>::max())); |
356 | 1.27k | } |
357 | 2.38k | } |
358 | 15.0k | } |
359 | | |
360 | | /// Complete one request: advance the scripted reply cursor, record the parsed |
361 | | /// exchange, and return to start-line mode. An empty scripted reply still |
362 | | /// advances the cursor because it is a meaningful truncation mutation. |
363 | 16.5k | void RtspMockServer::FinishRequest() { |
364 | 16.5k | ++request_count_; |
365 | 16.5k | last_client_cseq_ = have_client_cseq_ ? client_cseq_ : 0; |
366 | 16.5k | bool wrote_response = false; |
367 | 16.5k | if (probe_mode_ == curl::fuzzer::proto::RTSP_PROBE_SPLIT_INVALID_RTP_WRITE_FAILURE) { |
368 | 1 | std::string response = "RTSP/1.0 200 OK\r\nCSeq: 1\r\nContent-Length: 4096\r\n\r\n"; |
369 | 1 | if (response.size() < static_cast<std::size_t>(kSplitRtpReadBufferBytes)) { |
370 | 1 | response.append(static_cast<std::size_t>(kSplitRtpReadBufferBytes) - response.size() - 1, 'x'); |
371 | 1 | response.push_back('$'); |
372 | 1 | response.push_back(static_cast<char>(0xff)); |
373 | 1 | wrote_response = WriteControlBytes(response); |
374 | 1 | } |
375 | 16.5k | } else { |
376 | 16.5k | wrote_response = WriteNextReply(); |
377 | 16.5k | } |
378 | 16.5k | if (wrote_response) { |
379 | 5.95k | ++response_count_; |
380 | 5.95k | } |
381 | | |
382 | 16.5k | in_request_ = false; |
383 | 16.5k | in_headers_ = false; |
384 | 16.5k | have_client_cseq_ = false; |
385 | 16.5k | have_content_length_ = false; |
386 | 16.5k | client_cseq_ = 0; |
387 | 16.5k | content_length_ = 0; |
388 | 16.5k | } |
389 | | |
390 | | /// Consume one complete request line or header line. The blank line that ends |
391 | | /// the header block is the reply trigger: an announced body first switches the |
392 | | /// shared parser into exact-length mode, whose completion calls |
393 | | /// HandleBodyComplete(). |
394 | | /// @param line Complete line sent by curl. |
395 | 59.1k | void RtspMockServer::HandleLine(std::string_view line) { |
396 | 59.1k | if (!in_request_) { |
397 | 17.0k | BeginRequest(line); |
398 | 17.0k | return; |
399 | 17.0k | } |
400 | | |
401 | 42.0k | if (IsBlankLine(line)) { |
402 | 16.8k | in_headers_ = false; |
403 | 16.8k | if (have_content_length_ && content_length_ != 0) { |
404 | 982 | BeginExactBody(content_length_); |
405 | 982 | return; |
406 | 982 | } |
407 | 15.8k | FinishRequest(); |
408 | 15.8k | return; |
409 | 16.8k | } |
410 | | |
411 | 25.2k | if (in_headers_) { |
412 | 25.2k | ParseHeader(line); |
413 | 25.2k | } |
414 | 25.2k | } |
415 | | |
416 | | /// Release the reply after an announced request body was drained exactly. |
417 | 715 | void RtspMockServer::HandleBodyComplete() { FinishRequest(); } |
418 | | |
419 | | /// Retain protocol outcomes in coverage and introspector builds. |
420 | 7.82k | void RtspMockServer::ObserveState() { |
421 | 7.82k | #if defined(PROTO_FUZZER_OBSERVE_STATE) |
422 | 7.82k | PingpongMockServer::ObserveState(); |
423 | 7.82k | const volatile std::size_t rtsp_observation[] = {request_count(), |
424 | 7.82k | response_count(), |
425 | 7.82k | last_client_cseq(), |
426 | 7.82k | control_transcript().size(), |
427 | 7.82k | last_request_line().size(), |
428 | 7.82k | last_stream_uri().size(), |
429 | 7.82k | client_write_failure_count(), |
430 | 7.82k | opened_transport_count()}; |
431 | 7.82k | (void)rtsp_observation; |
432 | 7.82k | #endif |
433 | 7.82k | } |
434 | | |
435 | | } // namespace proto_fuzzer |