Coverage Report

Created: 2026-12-01 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/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
122k
std::string_view TrimLineEnding(std::string_view line) {
34
337k
  while (!line.empty() && (line.back() == '\n' || line.back() == '\r')) {
35
214k
    line.remove_suffix(1);
36
214k
  }
37
122k
  return line;
38
122k
}
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
17.6k
bool EqualsIgnoreCase(std::string_view actual, std::string_view expected) {
46
17.6k
  if (actual.size() != expected.size()) {
47
0
    return false;
48
0
  }
49
103k
  for (std::size_t index = 0; index < actual.size(); ++index) {
50
87.1k
    unsigned char left = static_cast<unsigned char>(actual[index]);
51
87.1k
    unsigned char right = static_cast<unsigned char>(expected[index]);
52
87.1k
    if (left >= 'a' && left <= 'z') {
53
51.0k
      left = static_cast<unsigned char>(left - 'a' + 'A');
54
51.0k
    }
55
87.1k
    if (right >= 'a' && right <= 'z') {
56
50.8k
      right = static_cast<unsigned char>(right - 'a' + 'A');
57
50.8k
    }
58
87.1k
    if (left != right) {
59
1.15k
      return false;
60
1.15k
    }
61
87.1k
  }
62
16.4k
  return true;
63
17.6k
}
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
51.1k
bool HeaderValue(std::string_view line, std::string_view name, std::string_view* value) {
73
51.1k
  const std::string_view trimmed = TrimLineEnding(line);
74
51.1k
  if (trimmed.size() <= name.size() || trimmed[name.size()] != ':' ||
75
34.6k
      !EqualsIgnoreCase(trimmed.substr(0, name.size()), name)) {
76
34.6k
    return false;
77
34.6k
  }
78
79
16.4k
  std::size_t begin = name.size() + 1;
80
32.4k
  while (begin < trimmed.size() && (trimmed[begin] == ' ' || trimmed[begin] == '\t')) {
81
15.9k
    ++begin;
82
15.9k
  }
83
16.4k
  std::string_view parsed = trimmed.substr(begin);
84
18.0k
  while (!parsed.empty() && (parsed.back() == ' ' || parsed.back() == '\t')) {
85
1.55k
    parsed.remove_suffix(1);
86
1.55k
  }
87
16.4k
  *value = parsed;
88
16.4k
  return true;
89
51.1k
}
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
16.4k
bool ParseDecimal(std::string_view text, std::uint64_t* result) {
98
16.4k
  if (text.empty()) {
99
831
    return false;
100
831
  }
101
15.6k
  std::uint64_t value = 0;
102
28.4k
  for (const char byte : text) {
103
28.4k
    if (byte < '0' || byte > '9') {
104
1.48k
      return false;
105
1.48k
    }
106
26.9k
    const std::uint64_t digit = static_cast<std::uint64_t>(byte - '0');
107
26.9k
    if (value > (std::numeric_limits<std::uint64_t>::max() - digit) / 10U) {
108
2.41k
      value = std::numeric_limits<std::uint64_t>::max();
109
24.5k
    } else {
110
24.5k
      value = value * 10U + digit;
111
24.5k
    }
112
26.9k
  }
113
14.1k
  *result = value;
114
14.1k
  return true;
115
15.6k
}
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
52.1k
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
4.11k
                                                     int response_index) {
128
4.11k
  curl::fuzzer::proto::Scenario selected = scenario;
129
4.11k
  auto* connection = selected.mutable_connection();
130
4.11k
  std::string response;
131
4.11k
  const bool has_response = response_index >= 0 && response_index < scenario.connection().on_readable_size();
132
4.11k
  if (has_response) {
133
2.32k
    response = scenario.connection().on_readable(response_index);
134
2.32k
  }
135
4.11k
  connection->clear_on_readable();
136
4.11k
  if (has_response) {
137
2.32k
    connection->add_on_readable(std::move(response));
138
2.32k
  }
139
4.11k
  return selected;
140
4.11k
}
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
9.07k
    : in_request_(false),
148
9.07k
      in_headers_(false),
149
9.07k
      have_client_cseq_(false),
150
9.07k
      have_content_length_(false),
151
9.07k
      client_cseq_(0),
152
9.07k
      last_client_cseq_(0),
153
9.07k
      content_length_(0),
154
9.07k
      request_count_(0),
155
9.07k
      response_count_(0),
156
9.07k
      probe_mode_(curl::fuzzer::proto::RTSP_PROBE_DEFAULT),
157
9.07k
      client_write_failure_count_(0),
158
9.07k
      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
9.07k
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
9.04k
void RtspMockServer::ConfigureClient(CURL* easy, curl::fuzzer::proto::RtspProbeMode mode) {
173
9.04k
  probe_mode_ = mode;
174
9.04k
  client_write_failure_count_ = 0;
175
9.04k
  opened_transport_count_ = 0;
176
9.04k
  if (easy == nullptr || mode != curl::fuzzer::proto::RTSP_PROBE_SPLIT_INVALID_RTP_WRITE_FAILURE) {
177
8.96k
    return;
178
8.96k
  }
179
82
  (void)curl_easy_setopt(easy, CURLOPT_BUFFERSIZE, kSplitRtpReadBufferBytes);
180
82
  (void)curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, &RtspMockServer::ProbeWriteCallback);
181
82
  (void)curl_easy_setopt(easy, CURLOPT_WRITEDATA, this);
182
82
}
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
123
std::size_t RtspMockServer::ProbeWriteCallback(char* contents, std::size_t size, std::size_t nmemb, void* userdata) {
189
123
  auto* server = static_cast<RtspMockServer*>(userdata);
190
123
  const std::size_t bytes = size * nmemb;
191
123
  if (server != nullptr && server->client_write_failure_count_ == 0 && bytes == 1 && contents != nullptr &&
192
60
      contents[0] == '$') {
193
60
    ++server->client_write_failure_count_;
194
60
    return 0;
195
60
  }
196
63
  return bytes;
197
123
}
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.37k
CURLcode RtspMockServer::DriveCrossOriginReuseScenario(CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
210
1.37k
  if (easy == nullptr) {
211
0
    return CURLE_FAILED_INIT;
212
0
  }
213
1.37k
  CurlMultiPtr multi(curl_multi_init());
214
1.37k
  if (!multi) {
215
2
    return CURLE_FAILED_INIT;
216
2
  }
217
218
2.97k
  const auto drive = [&](const curl::fuzzer::proto::Scenario& transfer) {
219
2.97k
    CURLcode result = CURLE_FAILED_INIT;
220
2.97k
    if (curl_multi_add_handle(multi.get(), easy) != CURLM_OK) {
221
0
      return result;
222
0
    }
223
2.97k
    PingpongMockServer::RunLoop(multi.get(), easy, transfer);
224
2.97k
    int messages_remaining = 0;
225
2.97k
    CURLMsg* message = nullptr;
226
5.23k
    while ((message = curl_multi_info_read(multi.get(), &messages_remaining)) != nullptr) {
227
2.25k
      if (message->msg == CURLMSG_DONE && message->easy_handle == easy) {
228
2.25k
        result = message->data.result;
229
2.25k
      }
230
2.25k
    }
231
2.97k
    (void)curl_multi_remove_handle(multi.get(), easy);
232
2.97k
    return result;
233
2.97k
  };
234
235
1.37k
  const curl::fuzzer::proto::Scenario first = SelectTransferResponse(scenario, 0);
236
1.37k
  const curl::fuzzer::proto::Scenario second = SelectTransferResponse(scenario, 1);
237
1.37k
  const curl::fuzzer::proto::Scenario third = SelectTransferResponse(scenario, 2);
238
1.37k
  CURLcode result = drive(first);
239
1.37k
  if (result != CURLE_OK) {
240
172
    return result;
241
172
  }
242
1.20k
  result = drive(second);
243
1.20k
  if (result != CURLE_OK) {
244
800
    return result;
245
800
  }
246
400
  (void)curl_easy_setopt(easy, CURLOPT_URL, kCrossOriginReuseUrl);
247
400
  return drive(third);
248
1.20k
}
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
9.04k
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
9.04k
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
9.04k
std::uint32_t RtspMockServer::last_client_cseq() const { return last_client_cseq_; }
264
265
/// @return Start line of the most recently completed request.
266
9.04k
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
9.04k
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
9.04k
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
9.04k
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
9.88k
curl_socket_t RtspMockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* address) {
290
9.88k
  const curl_socket_t socket = PingpongMockServer::HandleOpenSocket(purpose, address);
291
9.88k
  if (socket != CURL_SOCKET_BAD) {
292
9.88k
    ++opened_transport_count_;
293
9.88k
  }
294
9.88k
  return socket;
295
9.88k
}
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
10.5k
void RtspMockServer::ResetProtocolState() {
301
10.5k
  in_request_ = false;
302
10.5k
  in_headers_ = false;
303
10.5k
  have_client_cseq_ = false;
304
10.5k
  have_content_length_ = false;
305
10.5k
  client_cseq_ = 0;
306
10.5k
  last_client_cseq_ = 0;
307
10.5k
  content_length_ = 0;
308
10.5k
  request_count_ = 0;
309
10.5k
  response_count_ = 0;
310
10.5k
  client_write_failure_count_ = 0;
311
10.5k
  last_request_line_.clear();
312
10.5k
  last_method_.clear();
313
10.5k
  last_stream_uri_.clear();
314
10.5k
}
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
19.5k
void RtspMockServer::BeginRequest(std::string_view line) {
320
19.5k
  const std::string_view trimmed = TrimLineEnding(line);
321
19.5k
  last_request_line_.assign(trimmed.data(), trimmed.size());
322
19.5k
  const std::string_view method = FirstToken(trimmed);
323
19.5k
  const std::string_view stream_uri = SecondToken(trimmed);
324
19.5k
  last_method_.assign(method.data(), method.size());
325
19.5k
  last_stream_uri_.assign(stream_uri.data(), stream_uri.size());
326
327
19.5k
  in_request_ = true;
328
19.5k
  in_headers_ = true;
329
19.5k
  have_client_cseq_ = false;
330
19.5k
  have_content_length_ = false;
331
19.5k
  client_cseq_ = 0;
332
19.5k
  content_length_ = 0;
333
19.5k
}
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
32.8k
void RtspMockServer::ParseHeader(std::string_view line) {
339
32.8k
  std::string_view value;
340
32.8k
  if (HeaderValue(line, "CSeq", &value)) {
341
14.4k
    std::uint64_t parsed = 0;
342
14.4k
    if (ParseDecimal(value, &parsed)) {
343
12.9k
      have_client_cseq_ = true;
344
12.9k
      client_cseq_ =
345
12.9k
          static_cast<std::uint32_t>(std::min<std::uint64_t>(parsed, std::numeric_limits<std::uint32_t>::max()));
346
12.9k
    }
347
14.4k
    return;
348
14.4k
  }
349
350
18.3k
  if (HeaderValue(line, "Content-Length", &value)) {
351
1.97k
    std::uint64_t parsed = 0;
352
1.97k
    if (ParseDecimal(value, &parsed)) {
353
1.19k
      have_content_length_ = true;
354
1.19k
      content_length_ =
355
1.19k
          static_cast<std::size_t>(std::min<std::uint64_t>(parsed, std::numeric_limits<std::size_t>::max()));
356
1.19k
    }
357
1.97k
  }
358
18.3k
}
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
19.0k
void RtspMockServer::FinishRequest() {
364
19.0k
  ++request_count_;
365
19.0k
  last_client_cseq_ = have_client_cseq_ ? client_cseq_ : 0;
366
19.0k
  bool wrote_response = false;
367
19.0k
  if (probe_mode_ == curl::fuzzer::proto::RTSP_PROBE_SPLIT_INVALID_RTP_WRITE_FAILURE) {
368
451
    std::string response = "RTSP/1.0 200 OK\r\nCSeq: 1\r\nContent-Length: 4096\r\n\r\n";
369
451
    if (response.size() < static_cast<std::size_t>(kSplitRtpReadBufferBytes)) {
370
451
      response.append(static_cast<std::size_t>(kSplitRtpReadBufferBytes) - response.size() - 1, 'x');
371
451
      response.push_back('$');
372
451
      response.push_back(static_cast<char>(0xff));
373
451
      wrote_response = WriteControlBytes(response);
374
451
    }
375
18.6k
  } else {
376
18.6k
    wrote_response = WriteNextReply();
377
18.6k
  }
378
19.0k
  if (wrote_response) {
379
8.78k
    ++response_count_;
380
8.78k
  }
381
382
19.0k
  in_request_ = false;
383
19.0k
  in_headers_ = false;
384
19.0k
  have_client_cseq_ = false;
385
19.0k
  have_content_length_ = false;
386
19.0k
  client_cseq_ = 0;
387
19.0k
  content_length_ = 0;
388
19.0k
}
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
71.7k
void RtspMockServer::HandleLine(std::string_view line) {
396
71.7k
  if (!in_request_) {
397
19.5k
    BeginRequest(line);
398
19.5k
    return;
399
19.5k
  }
400
401
52.1k
  if (IsBlankLine(line)) {
402
19.3k
    in_headers_ = false;
403
19.3k
    if (have_content_length_ && content_length_ != 0) {
404
876
      BeginExactBody(content_length_);
405
876
      return;
406
876
    }
407
18.4k
    FinishRequest();
408
18.4k
    return;
409
19.3k
  }
410
411
32.8k
  if (in_headers_) {
412
32.8k
    ParseHeader(line);
413
32.8k
  }
414
32.8k
}
415
416
/// Release the reply after an announced request body was drained exactly.
417
603
void RtspMockServer::HandleBodyComplete() { FinishRequest(); }
418
419
/// Retain protocol outcomes in coverage and introspector builds.
420
9.04k
void RtspMockServer::ObserveState() {
421
9.04k
#if defined(PROTO_FUZZER_OBSERVE_STATE)
422
9.04k
  PingpongMockServer::ObserveState();
423
9.04k
  const volatile std::size_t rtsp_observation[] = {request_count(),
424
9.04k
                                                   response_count(),
425
9.04k
                                                   last_client_cseq(),
426
9.04k
                                                   control_transcript().size(),
427
9.04k
                                                   last_request_line().size(),
428
9.04k
                                                   last_stream_uri().size(),
429
9.04k
                                                   client_write_failure_count(),
430
9.04k
                                                   opened_transport_count()};
431
9.04k
  (void)rtsp_observation;
432
9.04k
#endif
433
9.04k
}
434
435
}  // namespace proto_fuzzer