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/ldap_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 BER/ASN.1-aware in-process LDAP peer.
9
10
#include "proto_fuzzer/ldap_mock_server.h"
11
12
#include <algorithm>
13
#include <cstddef>
14
#include <cstdint>
15
#include <limits>
16
#include <memory>
17
#include <string>
18
#include <string_view>
19
20
#include "proto_fuzzer/mock_server.h"
21
#include "proto_fuzzer/scenario_limits.h"
22
23
namespace proto_fuzzer {
24
25
namespace {
26
27
// RFC 4511 protocol operation tags used by this peer.
28
constexpr unsigned char kSequenceTag = 0x30;
29
constexpr unsigned char kBooleanTag = 0x01;
30
constexpr unsigned char kIntegerTag = 0x02;
31
constexpr unsigned char kEnumeratedTag = 0x0a;
32
constexpr unsigned char kOctetStringTag = 0x04;
33
constexpr unsigned char kUnbindRequest = 0x42;
34
constexpr unsigned char kBindRequest = 0x60;
35
constexpr unsigned char kBindResponse = 0x61;
36
constexpr unsigned char kSearchRequest = 0x63;
37
constexpr unsigned char kSearchResultEntry = 0x64;
38
constexpr unsigned char kSearchResultDone = 0x65;
39
constexpr unsigned char kAbandonRequest = 0x50;
40
constexpr unsigned char kExtendedRequest = 0x77;
41
constexpr unsigned char kExtendedResponse = 0x78;
42
constexpr unsigned char kSetTag = 0x31;
43
constexpr unsigned char kPresentFilter = 0x87;
44
constexpr int kLdapSuccess = 0;
45
constexpr std::string_view kObjectClass = "objectclass";
46
constexpr std::string_view kSupportedSaslMechanisms = "supportedSASLMechanisms";
47
constexpr std::string_view kPlainMechanism = "PLAIN";
48
49
107k
unsigned char ByteAt(std::string_view bytes, std::size_t index) { return static_cast<unsigned char>(bytes[index]); }
50
51
}  // namespace
52
53
/// Begin without a borrowed protobuf or open socketpair. RunLoop borrows a
54
/// Scenario only for the synchronous DriveScenario call in which socket
55
/// callbacks can run.
56
LdapMockServer::LdapMockServer()
57
2.02k
    : scenario_(nullptr),
58
2.02k
      server_chunk_count_(0),
59
2.02k
      next_server_chunk_(0),
60
2.02k
      bind_request_count_(0),
61
2.02k
      search_request_count_(0),
62
2.02k
      mechanism_search_request_count_(0),
63
2.02k
      starttls_request_count_(0),
64
2.02k
      unbind_request_count_(0),
65
2.02k
      server_message_count_(0),
66
2.02k
      scripted_message_count_(0),
67
2.02k
      synthesized_done_count_(0),
68
2.02k
      scripted_bind_response_count_(0),
69
2.02k
      search_message_id_(0),
70
2.02k
      search_active_(false),
71
2.02k
      search_done_sent_(false),
72
2.02k
      scripted_bind_consumed_(false),
73
2.02k
      release_script_chunks_(false),
74
2.02k
      peer_closed_(false),
75
2.02k
      protocol_error_(false),
76
2.02k
      socket_opened_(false) {}
77
78
/// Release the server-owned socketpair half after curl has returned its client
79
/// descriptor. The out-of-line destructor keeps MockConnection's complete type
80
/// local to this translation unit.
81
2.02k
LdapMockServer::~LdapMockServer() = default;
82
83
/// @return A prefix of complete client LDAPMessages from the most recent drive.
84
2.00k
const std::string& LdapMockServer::packet_transcript() const { return packet_transcript_; }
85
86
/// Append one fragment after the transport has decoded it. Plaintext peers
87
/// report socket bytes directly; the LDAPS peer reports decrypted application
88
/// bytes, so the BER parser is independent of the carrier.
89
/// @param data First byte of the fragment.
90
/// @param size Number of bytes available at `data`.
91
5.96k
void LdapMockServer::ObserveIncomingData(const unsigned char* data, std::size_t size) {
92
5.96k
  if (data == nullptr || size == 0) {
93
0
    return;
94
0
  }
95
5.96k
  pending_client_bytes_.append(reinterpret_cast<const char*>(data), size);
96
5.96k
}
97
98
/// @return Number of bindRequest messages observed.
99
2.00k
std::size_t LdapMockServer::bind_request_count() const { return bind_request_count_; }
100
101
/// @return Number of searchRequest messages observed.
102
2.00k
std::size_t LdapMockServer::search_request_count() const { return search_request_count_; }
103
104
/// @return Number of root-DSE supportedSASLMechanisms searches observed.
105
0
std::size_t LdapMockServer::mechanism_search_request_count() const { return mechanism_search_request_count_; }
106
107
/// @return Number of StartTLS ExtendedRequest messages observed.
108
2.00k
std::size_t LdapMockServer::starttls_request_count() const { return starttls_request_count_; }
109
110
/// @return Number of unbindRequest messages observed.
111
0
std::size_t LdapMockServer::unbind_request_count() const { return unbind_request_count_; }
112
113
/// @return Number of server messages written in the most recent drive.
114
0
std::size_t LdapMockServer::server_message_count() const { return server_message_count_; }
115
116
/// @return Number of scripted search-result chunks forwarded.
117
2.00k
std::size_t LdapMockServer::scripted_message_count() const { return scripted_message_count_; }
118
119
/// @return Number of searchResDone messages generated by the peer.
120
2.00k
std::size_t LdapMockServer::synthesized_done_count() const { return synthesized_done_count_; }
121
122
/// @return Number of bind replies taken from initial_response.
123
0
std::size_t LdapMockServer::scripted_bind_response_count() const { return scripted_bind_response_count_; }
124
125
/// Decode one definite-length BER TLV. The decoder accepts a single short-form
126
/// length byte or long form with at most four length bytes; indefinite lengths
127
/// and lengths beyond the peer's message budget are protocol errors. A
128
/// truncated header or body reports kNeedMore so the caller can retain the
129
/// partial bytes for the next socket read.
130
/// @param bytes Buffer beginning at the TLV start.
131
/// @param offset Offset of the tag byte within `bytes`.
132
/// @param view Receives the decoded tag and bounded value extent.
133
/// @return kComplete, kNeedMore, or kInvalid.
134
47.5k
LdapMockServer::ParseResult LdapMockServer::ParseTlv(std::string_view bytes, std::size_t offset, TlvView* view) {
135
47.5k
  if (view == nullptr) {
136
0
    return ParseResult::kInvalid;
137
0
  }
138
47.5k
  if (offset >= bytes.size()) {
139
758
    return ParseResult::kNeedMore;
140
758
  }
141
142
46.7k
  const unsigned char tag = ByteAt(bytes, offset);
143
46.7k
  if (tag == 0) {
144
    // End-of-contents is only valid for indefinite lengths, which LDAP forbids
145
    // in the commands this peer accepts.
146
2.04k
    return ParseResult::kInvalid;
147
2.04k
  }
148
149
44.7k
  std::size_t cursor = offset + 1;
150
44.7k
  if (cursor >= bytes.size()) {
151
2.33k
    return ParseResult::kNeedMore;
152
2.33k
  }
153
154
42.3k
  const unsigned char length_byte = ByteAt(bytes, cursor++);
155
42.3k
  std::size_t length = 0;
156
42.3k
  if ((length_byte & 0x80U) == 0) {
157
39.6k
    length = static_cast<std::size_t>(length_byte);
158
39.6k
  } else {
159
2.76k
    const std::size_t length_bytes = static_cast<std::size_t>(length_byte & 0x7fU);
160
2.76k
    if (length_bytes == 0 || length_bytes > 4) {
161
590
      return ParseResult::kInvalid;
162
590
    }
163
2.17k
    if (bytes.size() - cursor < length_bytes) {
164
54
      return ParseResult::kNeedMore;
165
54
    }
166
6.97k
    for (std::size_t index = 0; index < length_bytes; ++index) {
167
4.86k
      length = (length << 8U) | static_cast<std::size_t>(ByteAt(bytes, cursor + index));
168
4.86k
    }
169
2.11k
    cursor += length_bytes;
170
2.11k
  }
171
172
41.7k
  if (length > kMaxClientMessageBytes) {
173
478
    return ParseResult::kInvalid;
174
478
  }
175
41.2k
  if (bytes.size() - cursor < length) {
176
817
    return ParseResult::kNeedMore;
177
817
  }
178
179
40.4k
  view->tag = tag;
180
40.4k
  view->value_offset = cursor;
181
40.4k
  view->value_length = length;
182
40.4k
  view->total_length = cursor - offset + length;
183
40.4k
  return ParseResult::kComplete;
184
41.2k
}
185
186
/// Recognize the exact root-DSE query emitted by oldap_perform_mechs. A plain
187
/// substring check would let a mutation-controlled data search for the same
188
/// attribute consume the peer-owned setup response, so every BER field that
189
/// distinguishes the fixed discovery request is checked fail closed. Routing
190
/// also requires the pre-bind state because a later data search can be byte
191
/// identical to this query.
192
/// @param value Value bytes of a searchRequest protocol operation.
193
/// @return true only for the supportedSASLMechanisms root-DSE query.
194
2.29k
bool LdapMockServer::IsSaslMechanismSearch(std::string_view value) {
195
2.29k
  std::size_t cursor = 0;
196
2.29k
  TlvView field;
197
11.0k
  const auto parse_field = [&value, &cursor](unsigned char tag, TlvView* parsed) {
198
11.0k
    if (ParseTlv(value, cursor, parsed) != ParseResult::kComplete || parsed->tag != tag) {
199
638
      return false;
200
638
    }
201
10.4k
    cursor = parsed->value_offset + parsed->value_length;
202
10.4k
    return true;
203
11.0k
  };
204
6.31k
  const auto is_zero = [&value](const TlvView& parsed) {
205
6.31k
    return parsed.value_length == 1 && ByteAt(value, parsed.value_offset) == 0;
206
6.31k
  };
207
208
2.29k
  if (!parse_field(kOctetStringTag, &field) || field.value_length != 0 || !parse_field(kEnumeratedTag, &field) ||
209
1.51k
      !is_zero(field) || !parse_field(kEnumeratedTag, &field) || !is_zero(field) || !parse_field(kIntegerTag, &field) ||
210
1.23k
      !is_zero(field) || !parse_field(kIntegerTag, &field) || !is_zero(field) || !parse_field(kBooleanTag, &field) ||
211
1.07k
      !is_zero(field) || !parse_field(kPresentFilter, &field) ||
212
983
      value.substr(field.value_offset, field.value_length) != kObjectClass || !parse_field(kSequenceTag, &field) ||
213
1.31k
      cursor != value.size()) {
214
1.31k
    return false;
215
1.31k
  }
216
217
983
  const std::size_t attributes_end = field.value_offset + field.value_length;
218
983
  TlvView attribute;
219
983
  if (ParseTlv(value, field.value_offset, &attribute) != ParseResult::kComplete || attribute.tag != kOctetStringTag ||
220
863
      attribute.value_offset + attribute.value_length != attributes_end) {
221
863
    return false;
222
863
  }
223
120
  return value.substr(attribute.value_offset, attribute.value_length) == kSupportedSaslMechanisms;
224
983
}
225
226
/// Decode an LDAPMessage envelope: SEQUENCE { messageID INTEGER, protocolOp }.
227
/// The peer needs the integer id and outer operation tag. Search bodies remain
228
/// opaque except for exact classification of OpenLDAP's fixed mechanism query,
229
/// so mutation-controlled data searches still reach OpenLDAP's BER parser.
230
/// @param bytes Buffer beginning at the message's first tag byte.
231
/// @param message Receives the decoded envelope fields.
232
/// @return kComplete, kNeedMore, or kInvalid.
233
10.8k
LdapMockServer::ParseResult LdapMockServer::ParseMessage(std::string_view bytes, MessageView* message) {
234
10.8k
  if (message == nullptr) {
235
0
    return ParseResult::kInvalid;
236
0
  }
237
238
10.8k
  TlvView outer;
239
10.8k
  ParseResult parsed = ParseTlv(bytes, 0, &outer);
240
10.8k
  if (parsed != ParseResult::kComplete) {
241
1.86k
    return parsed;
242
1.86k
  }
243
9.00k
  if (outer.tag != kSequenceTag || outer.value_length < 2) {
244
307
    return ParseResult::kInvalid;
245
307
  }
246
247
8.70k
  const std::size_t outer_end = outer.value_offset + outer.value_length;
248
8.70k
  TlvView integer;
249
8.70k
  parsed = ParseTlv(bytes, outer.value_offset, &integer);
250
8.70k
  if (parsed != ParseResult::kComplete) {
251
962
    return parsed;
252
962
  }
253
7.74k
  if (integer.tag != kIntegerTag || integer.value_length == 0 || integer.value_length > 4 ||
254
7.37k
      integer.value_offset + integer.value_length > outer_end) {
255
368
    return ParseResult::kInvalid;
256
368
  }
257
258
7.37k
  std::uint32_t message_id = 0;
259
15.0k
  for (std::size_t index = 0; index < integer.value_length; ++index) {
260
7.69k
    message_id = (message_id << 8U) | static_cast<std::uint32_t>(ByteAt(bytes, integer.value_offset + index));
261
7.69k
  }
262
263
7.37k
  const std::size_t operation_offset = integer.value_offset + integer.value_length;
264
7.37k
  if (operation_offset >= outer_end) {
265
1
    return ParseResult::kInvalid;
266
1
  }
267
7.37k
  TlvView operation;
268
7.37k
  parsed = ParseTlv(bytes, operation_offset, &operation);
269
7.37k
  if (parsed != ParseResult::kComplete) {
270
326
    return parsed;
271
326
  }
272
7.04k
  if (operation.value_offset + operation.value_length > outer_end) {
273
8
    return ParseResult::kInvalid;
274
8
  }
275
276
7.03k
  message->op_tag = operation.tag;
277
7.03k
  message->message_id = message_id;
278
7.03k
  message->total_length = outer.total_length;
279
7.03k
  message->sasl_mechanism_query = operation.tag == kSearchRequest &&
280
2.29k
                                  IsSaslMechanismSearch(bytes.substr(operation.value_offset, operation.value_length));
281
7.03k
  return ParseResult::kComplete;
282
7.04k
}
283
284
/// Append a definite BER length. LDAP fuzz inputs remain far below the
285
/// long-form boundary in ordinary traffic, but server chunks are
286
/// mutation-controlled, so the encoder handles the full 32-bit size_t range
287
/// with the shortest representation.
288
/// @param out Destination string.
289
/// @param length Number of value bytes that follow.
290
23.7k
void LdapMockServer::AppendBerLength(std::string* out, std::size_t length) {
291
23.7k
  if (out == nullptr) {
292
0
    return;
293
0
  }
294
23.7k
  if (length < 128) {
295
23.7k
    out->push_back(static_cast<char>(length));
296
23.7k
    return;
297
23.7k
  }
298
299
0
  unsigned char encoded[sizeof(std::size_t)];
300
0
  std::size_t count = 0;
301
0
  while (length != 0) {
302
0
    encoded[count++] = static_cast<unsigned char>(length & 0xffU);
303
0
    length >>= 8U;
304
0
  }
305
0
  out->push_back(static_cast<char>(0x80U | count));
306
0
  while (count != 0) {
307
0
    out->push_back(static_cast<char>(encoded[--count]));
308
0
  }
309
0
}
310
311
/// Append one TLV with a definite length.
312
/// @param out Destination string.
313
/// @param tag BER identifier octet.
314
/// @param value Value bytes.
315
23.7k
void LdapMockServer::AppendTlv(std::string* out, unsigned char tag, std::string_view value) {
316
23.7k
  if (out == nullptr) {
317
0
    return;
318
0
  }
319
23.7k
  out->push_back(static_cast<char>(tag));
320
23.7k
  AppendBerLength(out, value.size());
321
23.7k
  out->append(value.data(), value.size());
322
23.7k
}
323
324
/// Append a minimally encoded non-negative BER INTEGER.
325
/// @param out Destination string.
326
/// @param value Integer to encode.
327
5.02k
void LdapMockServer::AppendBerInteger(std::string* out, std::uint32_t value) {
328
5.02k
  unsigned char encoded[5];
329
5.02k
  std::size_t count = 0;
330
5.02k
  do {
331
5.02k
    encoded[count++] = static_cast<unsigned char>(value & 0xffU);
332
5.02k
    value >>= 8U;
333
5.02k
  } while (value != 0);
334
335
5.02k
  std::string bytes;
336
5.02k
  if ((encoded[count - 1] & 0x80U) != 0) {
337
0
    bytes.push_back('\0');
338
0
  }
339
10.0k
  while (count != 0) {
340
5.02k
    bytes.push_back(static_cast<char>(encoded[--count]));
341
5.02k
  }
342
5.02k
  AppendTlv(out, kIntegerTag, bytes);
343
5.02k
}
344
345
/// Encode a bindResponse or searchResDone carrying a single result code and
346
/// empty matchedDN/diagnosticMessage fields. The peer echoes the request's
347
/// message id so OpenLDAP associates the reply with curl's outstanding call.
348
/// @param message_id Request message id.
349
/// @param op_tag kBindResponse or kSearchResultDone.
350
/// @param result_code LDAP resultCode (0 is success).
351
/// @param out Receives the complete LDAPMessage.
352
void LdapMockServer::BuildResultMessage(std::uint32_t message_id, unsigned char op_tag, int result_code,
353
3.29k
                                        std::string* out) {
354
3.29k
  if (out == nullptr) {
355
0
    return;
356
0
  }
357
358
3.29k
  std::string result;
359
3.29k
  const int bounded_code = std::max(0, std::min(result_code, 255));
360
3.29k
  const char code_byte = static_cast<char>(bounded_code);
361
3.29k
  AppendTlv(&result, kEnumeratedTag, std::string_view(&code_byte, 1));
362
3.29k
  AppendTlv(&result, kOctetStringTag, std::string_view());
363
3.29k
  AppendTlv(&result, kOctetStringTag, std::string_view());
364
365
3.29k
  std::string content;
366
3.29k
  AppendBerInteger(&content, message_id);
367
3.29k
  AppendTlv(&content, op_tag, result);
368
369
3.29k
  out->clear();
370
3.29k
  AppendTlv(out, kSequenceTag, content);
371
3.29k
}
372
373
/// Encode a root-DSE searchResEntry advertising the one deterministic SASL
374
/// mechanism that the in-process peer can complete without external state.
375
/// @param message_id Mechanism-search request id to echo.
376
/// @param out Receives the complete LDAPMessage.
377
78
void LdapMockServer::BuildSaslMechanismsEntry(std::uint32_t message_id, std::string* out) {
378
78
  if (out == nullptr) {
379
0
    return;
380
0
  }
381
382
78
  std::string values;
383
78
  AppendTlv(&values, kOctetStringTag, kPlainMechanism);
384
385
78
  std::string attribute;
386
78
  AppendTlv(&attribute, kOctetStringTag, kSupportedSaslMechanisms);
387
78
  AppendTlv(&attribute, kSetTag, values);
388
389
78
  std::string attributes;
390
78
  AppendTlv(&attributes, kSequenceTag, attribute);
391
392
78
  std::string entry;
393
78
  AppendTlv(&entry, kOctetStringTag, std::string_view());
394
78
  AppendTlv(&entry, kSequenceTag, attributes);
395
396
78
  std::string content;
397
78
  AppendBerInteger(&content, message_id);
398
78
  AppendTlv(&content, kSearchResultEntry, entry);
399
400
78
  out->clear();
401
78
  AppendTlv(out, kSequenceTag, content);
402
78
}
403
404
/// Replace the messageID of a complete LDAPMessage. Scripted server bytes are
405
/// mutation-controlled and may not know OpenLDAP's per-connection counter, so
406
/// this keeps a valid seed meaningful without rewriting the operation body.
407
/// @param message Complete LDAPMessage bytes.
408
/// @param message_id New envelope integer.
409
/// @param out Receives the rewritten message.
410
/// @return true when the envelope parsed and was rewritten; false leaves `out`
411
///         unspecified and the caller should relay the original bytes.
412
5.69k
bool LdapMockServer::RewriteMessageId(std::string_view message, std::uint32_t message_id, std::string* out) {
413
5.69k
  if (out == nullptr) {
414
0
    return false;
415
0
  }
416
417
5.69k
  TlvView outer;
418
5.69k
  if (ParseTlv(message, 0, &outer) != ParseResult::kComplete || outer.tag != kSequenceTag ||
419
3.48k
      outer.total_length != message.size()) {
420
2.86k
    return false;
421
2.86k
  }
422
423
2.82k
  TlvView integer;
424
2.82k
  if (ParseTlv(message, outer.value_offset, &integer) != ParseResult::kComplete || integer.tag != kIntegerTag ||
425
1.65k
      integer.value_offset + integer.value_length > outer.value_offset + outer.value_length) {
426
1.17k
    return false;
427
1.17k
  }
428
429
1.65k
  std::string content;
430
1.65k
  AppendBerInteger(&content, message_id);
431
1.65k
  const std::size_t remainder_offset = integer.value_offset + integer.value_length;
432
1.65k
  const std::size_t outer_end = outer.value_offset + outer.value_length;
433
1.65k
  content.append(message.data() + remainder_offset, outer_end - remainder_offset);
434
435
1.65k
  out->clear();
436
1.65k
  AppendTlv(out, kSequenceTag, content);
437
1.65k
  return true;
438
2.82k
}
439
440
/// Extract only the protocol operation tag from a complete server message.
441
/// @param message Candidate LDAPMessage bytes.
442
/// @param op_tag Receives the operation tag.
443
/// @return true when the envelope parsed completely.
444
5.61k
bool LdapMockServer::MessageOpTag(std::string_view message, unsigned char* op_tag) {
445
5.61k
  if (op_tag == nullptr) {
446
0
    return false;
447
0
  }
448
5.61k
  MessageView decoded;
449
5.61k
  if (ParseMessage(message, &decoded) != ParseResult::kComplete || decoded.total_length != message.size()) {
450
4.06k
    return false;
451
4.06k
  }
452
1.54k
  *op_tag = decoded.op_tag;
453
1.54k
  return true;
454
5.61k
}
455
456
/// Reset every borrowed pointer, parser cursor, and observable capture before
457
/// borrowing the next Scenario.
458
/// @param scenario Scenario whose Connection supplies the bind reply and
459
///                 search-result messages.
460
1.99k
void LdapMockServer::ResetForScenario(const curl::fuzzer::proto::Scenario& scenario) {
461
1.99k
  connection_.reset();
462
1.99k
  scenario_ = &scenario;
463
1.99k
  server_chunk_count_ = std::min<std::size_t>(scenario_limits::kMaxResponseChunks,
464
1.99k
                                              static_cast<std::size_t>(scenario.connection().on_readable_size()));
465
1.99k
  next_server_chunk_ = 0;
466
1.99k
  bind_request_count_ = 0;
467
1.99k
  search_request_count_ = 0;
468
1.99k
  mechanism_search_request_count_ = 0;
469
1.99k
  starttls_request_count_ = 0;
470
1.99k
  unbind_request_count_ = 0;
471
1.99k
  server_message_count_ = 0;
472
1.99k
  scripted_message_count_ = 0;
473
1.99k
  synthesized_done_count_ = 0;
474
1.99k
  scripted_bind_response_count_ = 0;
475
1.99k
  pending_client_bytes_.clear();
476
1.99k
  packet_transcript_.clear();
477
1.99k
  search_message_id_ = 0;
478
1.99k
  search_active_ = false;
479
1.99k
  search_done_sent_ = false;
480
1.99k
  scripted_bind_consumed_ = false;
481
1.99k
  release_script_chunks_ = false;
482
1.99k
  peer_closed_ = false;
483
1.99k
  protocol_error_ = false;
484
1.99k
  socket_opened_ = false;
485
1.99k
}
486
487
/// Apply bounded transport knobs when creating the scripted socket. Target
488
/// policies normally clear LDAP backpressure, but direct corpus replay must
489
/// retain deterministic, well-defined behavior.
490
/// @param connection Peer receiving the socket settings.
491
/// @param script Connection script carrying optional backpressure values.
492
void LdapMockServer::ApplyScriptBackpressure(MockConnection* connection,
493
1.84k
                                             const curl::fuzzer::proto::Connection& script) {
494
1.84k
  if (connection == nullptr) {
495
0
    return;
496
0
  }
497
498
1.84k
  const std::uint32_t int_max = static_cast<std::uint32_t>(std::numeric_limits<int>::max());
499
1.84k
  const auto& backpressure = script.backpressure();
500
1.84k
  const int receive_buffer = static_cast<int>(std::min(backpressure.recv_buf_bytes(), int_max));
501
1.84k
  connection->ApplyBackpressure(receive_buffer, static_cast<std::size_t>(backpressure.drain_limit()));
502
1.84k
}
503
504
/// Create the default plaintext transport. The LDAPS subclass overrides this
505
/// factory, which keeps every BER handling path identical across carriers.
506
/// @return Newly allocated in-process socketpair peer.
507
751
std::unique_ptr<MockConnection> LdapMockServer::CreateConnection() { return std::make_unique<MockConnection>(); }
508
509
/// Create the single LDAP socketpair. The bind reply is deliberately not
510
/// queued here: LDAP is client-first, and releasing the scripted reply only
511
/// after the bindRequest lets the peer rewrite its messageID to OpenLDAP's
512
/// current counter.
513
/// @param purpose Socket role requested by curl.
514
/// @param address Unused stream destination metadata required by the callback
515
///                signature.
516
/// @return Client descriptor for the LDAP channel, or CURL_SOCKET_BAD.
517
1.84k
curl_socket_t LdapMockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* /*address*/) {
518
1.84k
  if (scenario_ == nullptr || purpose != CURLSOCKTYPE_IPCXN || socket_opened_) {
519
0
    return CURL_SOCKET_BAD;
520
0
  }
521
522
1.84k
  connection_ = CreateConnection();
523
1.84k
  if (!connection_ || !connection_->ok()) {
524
0
    connection_.reset();
525
0
    return CURL_SOCKET_BAD;
526
0
  }
527
1.84k
  connection_->SetIncomingDataObserver(this);
528
529
1.84k
  ApplyScriptBackpressure(connection_.get(), scenario_->connection());
530
1.84k
  socket_opened_ = true;
531
1.84k
  return connection_->take_client_fd();
532
1.84k
}
533
534
/// Retain only a bounded prefix for assertions. Parsing and draining continue
535
/// against the full transport bytes, so reaching the cap cannot change curl's
536
/// behavior or manufacture socket backpressure.
537
/// @param source Newly observed bytes.
538
/// @param limit Maximum retained destination size.
539
/// @param destination Capture buffer receiving the available prefix.
540
5.25k
void LdapMockServer::CapturePrefix(std::string_view source, std::size_t limit, std::string* destination) {
541
5.25k
  if (destination == nullptr || destination->size() >= limit) {
542
0
    return;
543
0
  }
544
5.25k
  const std::size_t available = limit - destination->size();
545
5.25k
  destination->append(source.data(), std::min(source.size(), available));
546
5.25k
}
547
548
/// Keep failed peer writes local to the mock. Response cursors must still
549
/// advance after curl closes early, otherwise a replacement socket could see a
550
/// reply intended for an earlier request.
551
/// @param bytes Response bytes to queue.
552
/// @return true when the complete fragment was queued.
553
9.06k
bool LdapMockServer::WriteServerBytes(std::string_view bytes) {
554
9.06k
  if (bytes.empty()) {
555
0
    return true;
556
0
  }
557
9.06k
  const bool written = connection_ != nullptr &&
558
9.06k
                       connection_->WriteAll(reinterpret_cast<const unsigned char*>(bytes.data()), bytes.size());
559
9.06k
  if (written) {
560
8.70k
    ++server_message_count_;
561
8.70k
  }
562
9.06k
  return written;
563
9.06k
}
564
565
/// Answer one bindRequest. A non-empty initial_response is the scenario's bind
566
/// reply and is renumbered to the request id; otherwise a success response is
567
/// synthesized. Reusing the script only once preserves OpenLDAP's protocol-v2
568
/// fallback path, which sends a second bind after a protocol-error reply.
569
/// @param message_id Client bind message id.
570
1.83k
void LdapMockServer::HandleBindRequest(std::uint32_t message_id) {
571
1.83k
  ++bind_request_count_;
572
573
1.83k
  std::string response;
574
1.83k
  if (!scripted_bind_consumed_ && scenario_ != nullptr && !scenario_->connection().initial_response().empty()) {
575
83
    const std::string& scripted = scenario_->connection().initial_response();
576
83
    if (!RewriteMessageId(scripted, message_id, &response)) {
577
55
      response = scripted;
578
55
    }
579
83
    scripted_bind_consumed_ = true;
580
83
    ++scripted_bind_response_count_;
581
1.74k
  } else {
582
1.74k
    BuildResultMessage(message_id, kBindResponse, kLdapSuccess, &response);
583
1.74k
  }
584
1.83k
  (void)WriteServerBytes(response);
585
1.83k
}
586
587
/// Begin (or restart) the search script. Result chunks are released one per
588
/// drive turn so curl consumes each LDAPMessage before the next arrives; the
589
/// terminal done follows once the cursor is exhausted.
590
/// @param message_id Client search message id.
591
1.52k
void LdapMockServer::HandleSearchRequest(std::uint32_t message_id) {
592
1.52k
  ++search_request_count_;
593
1.52k
  search_message_id_ = message_id;
594
1.52k
  search_active_ = true;
595
1.52k
  search_done_sent_ = false;
596
1.52k
  release_script_chunks_ = true;
597
1.52k
  next_server_chunk_ = 0;
598
1.52k
}
599
600
/// Answer OpenLDAP's root-DSE SASL discovery search before the ordinary bind
601
/// and URL-derived search. Keeping this response peer-owned prevents mutable
602
/// search-result scripts from being consumed by the setup query.
603
/// @param message_id Mechanism-search request id to echo.
604
78
void LdapMockServer::HandleMechanismSearchRequest(std::uint32_t message_id) {
605
78
  ++search_request_count_;
606
78
  ++mechanism_search_request_count_;
607
608
78
  std::string entry;
609
78
  BuildSaslMechanismsEntry(message_id, &entry);
610
78
  (void)WriteServerBytes(entry);
611
612
78
  std::string done;
613
78
  BuildResultMessage(message_id, kSearchResultDone, kLdapSuccess, &done);
614
78
  ++synthesized_done_count_;
615
78
  (void)WriteServerBytes(done);
616
78
}
617
618
/// Accept the RFC 4511 StartTLS ExtendedRequest. The successful correlated
619
/// response makes OpenLDAP return control to curl, which installs its TLS
620
/// connection filter on the existing confined socketpair. This plaintext peer
621
/// deliberately does not impersonate a TLS server after the upgrade: the
622
/// subsequent handshake observes a bounded EOF/error path while still
623
/// exercising the production filter transition.
624
/// @param message_id Client request identifier echoed in ExtendedResponse.
625
7
void LdapMockServer::HandleStartTlsRequest(std::uint32_t message_id) {
626
7
  ++starttls_request_count_;
627
7
  std::string response;
628
7
  BuildResultMessage(message_id, kExtendedResponse, kLdapSuccess, &response);
629
7
  (void)WriteServerBytes(response);
630
7
}
631
632
/// Route one complete client message. Unknown protocol operations are consumed
633
/// without a reply, matching LDAP's asymmetry: bind, search, and StartTLS
634
/// expect responses, while unbind/abandon are fire-and-forget.
635
/// @param message Decoded client envelope.
636
5.25k
void LdapMockServer::HandleClientMessage(const MessageView& message) {
637
5.25k
  switch (message.op_tag) {
638
1.83k
    case kBindRequest:
639
1.83k
      HandleBindRequest(message.message_id);
640
1.83k
      return;
641
642
1.60k
    case kSearchRequest:
643
1.60k
      if (message.sasl_mechanism_query && bind_request_count_ == 0 && mechanism_search_request_count_ == 0) {
644
78
        HandleMechanismSearchRequest(message.message_id);
645
1.52k
      } else {
646
1.52k
        HandleSearchRequest(message.message_id);
647
1.52k
      }
648
1.60k
      return;
649
650
7
    case kExtendedRequest:
651
7
      HandleStartTlsRequest(message.message_id);
652
7
      return;
653
654
1.40k
    case kUnbindRequest:
655
1.40k
      ++unbind_request_count_;
656
1.40k
      return;
657
658
414
    case kAbandonRequest:
659
414
      return;
660
661
0
    default:
662
0
      return;
663
5.25k
  }
664
5.25k
}
665
666
/// Release one scenario-provided search-result message. Chunks are opaque BER
667
/// LDAPMessages rather than command replies: each is forwarded with its
668
/// envelope messageID rewritten to the active search id. A scripted
669
/// searchResDone ends the search so no duplicate completion is synthesized; an
670
/// explicitly empty chunk half-closes the peer for a truncated-stream path.
671
/// @return true when a script slot was consumed.
672
16.3k
bool LdapMockServer::ReleaseNextServerChunk() {
673
16.3k
  if (!release_script_chunks_ || scenario_ == nullptr || connection_ == nullptr ||
674
10.7k
      next_server_chunk_ >= server_chunk_count_) {
675
10.7k
    return false;
676
10.7k
  }
677
678
5.64k
  const std::string& chunk = scenario_->connection().on_readable(static_cast<int>(next_server_chunk_));
679
5.64k
  ++next_server_chunk_;
680
681
5.64k
  if (chunk.empty()) {
682
34
    connection_->ShutdownWrite();
683
34
    peer_closed_ = true;
684
34
    release_script_chunks_ = false;
685
34
    return true;
686
34
  }
687
688
5.61k
  unsigned char op_tag = 0;
689
5.61k
  const bool has_op_tag = MessageOpTag(chunk, &op_tag);
690
5.61k
  std::string rewritten;
691
5.61k
  const bool renumbered = RewriteMessageId(chunk, search_message_id_, &rewritten);
692
5.61k
  const std::string_view bytes = renumbered ? std::string_view(rewritten) : std::string_view(chunk);
693
694
5.61k
  ++scripted_message_count_;
695
5.61k
  (void)WriteServerBytes(bytes);
696
5.61k
  if (has_op_tag && op_tag == kSearchResultDone) {
697
5
    search_done_sent_ = true;
698
5
    release_script_chunks_ = false;
699
5
  }
700
5.61k
  return true;
701
5.64k
}
702
703
/// Complete an outstanding search once its script cursor is exhausted. A
704
/// scripted done (or an explicit truncation) suppresses this synthesized
705
/// message, so the peer never invents completion after a deliberate error.
706
/// @return true when a searchResDone was written.
707
16.3k
bool LdapMockServer::FinishSearchIfReady() {
708
16.3k
  if (!search_active_ || search_done_sent_ || peer_closed_ || connection_ == nullptr) {
709
9.95k
    return false;
710
9.95k
  }
711
6.39k
  if (release_script_chunks_ && next_server_chunk_ < server_chunk_count_) {
712
4.93k
    return false;
713
4.93k
  }
714
715
1.46k
  std::string done;
716
1.46k
  BuildResultMessage(search_message_id_, kSearchResultDone, kLdapSuccess, &done);
717
1.46k
  ++synthesized_done_count_;
718
1.46k
  search_done_sent_ = true;
719
1.46k
  release_script_chunks_ = false;
720
1.46k
  return WriteServerBytes(done);
721
6.39k
}
722
723
/// Read without waiting and process every complete LDAPMessage currently
724
/// buffered. A message is delivered only after its outer TLV has fully
725
/// arrived, so fragmentation cannot shift the parser. DrainIncoming() also
726
/// advances a layered TLS carrier, and reports its handshake progress so the
727
/// outer loop does not mistake useful negotiation for an idle peer.
728
/// @return true when bytes, a message, or a transport state advanced.
729
16.3k
bool LdapMockServer::ServiceClientConnection() {
730
16.3k
  if (connection_ == nullptr || protocol_error_ || peer_closed_) {
731
447
    return false;
732
447
  }
733
734
15.9k
  const std::size_t size_before_read = pending_client_bytes_.size();
735
15.9k
  const std::size_t transport_progress = connection_->DrainIncoming();
736
15.9k
  bool made_progress = pending_client_bytes_.size() != size_before_read || transport_progress != 0;
737
738
15.9k
  std::size_t consumed = 0;
739
15.9k
  int messages = 0;
740
21.1k
  while (consumed < pending_client_bytes_.size() && messages < kMaxMessagesPerService) {
741
5.26k
    const std::string_view available(pending_client_bytes_.data() + consumed, pending_client_bytes_.size() - consumed);
742
5.26k
    MessageView message;
743
5.26k
    const ParseResult parsed = ParseMessage(available, &message);
744
5.26k
    if (parsed == ParseResult::kNeedMore) {
745
0
      break;
746
0
    }
747
5.26k
    if (parsed == ParseResult::kInvalid) {
748
8
      protocol_error_ = true;
749
8
      break;
750
8
    }
751
752
5.25k
    const std::string_view complete = available.substr(0, message.total_length);
753
5.25k
    CapturePrefix(complete, kMaxCapturedMessageBytes, &packet_transcript_);
754
5.25k
    HandleClientMessage(message);
755
5.25k
    consumed += message.total_length;
756
5.25k
    ++messages;
757
5.25k
    made_progress = true;
758
5.25k
  }
759
760
15.9k
  if (protocol_error_) {
761
8
    pending_client_bytes_.clear();
762
    // Close the write half immediately so a bogus length cannot wait on the
763
    // idle budget for an impossible body.
764
8
    connection_->ShutdownWrite();
765
8
    release_script_chunks_ = false;
766
15.8k
  } else if (consumed != 0) {
767
5.04k
    pending_client_bytes_.erase(0, consumed);
768
5.04k
  }
769
15.9k
  return made_progress;
770
16.3k
}
771
772
/// Half-close the peer so curl observes a deterministic end of server messages
773
/// after the transfer has stopped or the idle budget expired.
774
1.99k
void LdapMockServer::FinishConnections() {
775
1.99k
  if (connection_ != nullptr) {
776
1.84k
    connection_->ShutdownWrite();
777
1.84k
  }
778
1.99k
}
779
780
/// Alternate curl transitions with immediate peer service until the transfer
781
/// completes or deterministic idle/operation caps win. No select(), poll(), or
782
/// sleep is needed: OpenLDAP reads through a duplicate of the same in-process
783
/// socketpair endpoint that curl opened, so the peer can answer requests
784
/// synchronously from this thread.
785
/// @param multi Multi handle containing `easy`.
786
/// @param easy Easy handle already installed on this mock.
787
/// @param scenario Connection script to borrow.
788
1.99k
void LdapMockServer::RunLoop(CURLM* multi, CURL* easy, const curl::fuzzer::proto::Scenario& scenario) {
789
1.99k
  (void)easy;
790
1.99k
  ResetForScenario(scenario);
791
792
1.99k
  int still_running = 1;
793
1.99k
  int idle_iterations = 0;
794
1.99k
  int drive_iterations = 0;
795
1.99k
  CURLMcode result = CURLM_OK;
796
16.3k
  while (still_running && idle_iterations < kMaxIdleIterations && drive_iterations++ < kMaxDriveIterations) {
797
14.3k
    const int running_before = still_running;
798
14.3k
    result = curl_multi_perform(multi, &still_running);
799
14.3k
    if (result != CURLM_OK) {
800
0
      break;
801
0
    }
802
803
14.3k
    bool made_progress = still_running != running_before;
804
14.3k
    made_progress = ServiceClientConnection() || made_progress;
805
14.3k
    made_progress = ReleaseNextServerChunk() || made_progress;
806
14.3k
    made_progress = FinishSearchIfReady() || made_progress;
807
14.3k
    if (made_progress) {
808
12.9k
      idle_iterations = 0;
809
12.9k
    } else {
810
1.41k
      ++idle_iterations;
811
1.41k
    }
812
14.3k
  }
813
814
  // The final perform may have emitted a request immediately before marking
815
  // the transfer done. Drain those bytes before cleanup.
816
1.99k
  (void)ServiceClientConnection();
817
1.99k
  (void)ReleaseNextServerChunk();
818
1.99k
  (void)FinishSearchIfReady();
819
1.99k
  FinishConnections();
820
1.99k
  scenario_ = nullptr;
821
1.99k
}
822
823
/// Retain protocol outcomes in coverage and introspector builds.
824
2.00k
void LdapMockServer::ObserveState() {
825
2.00k
#if defined(PROTO_FUZZER_OBSERVE_STATE)
826
2.00k
  MockServerBase::ObserveState();
827
2.00k
  const volatile std::size_t ldap_observation[] = {packet_transcript().size(), bind_request_count(),
828
2.00k
                                                   search_request_count(),     scripted_message_count(),
829
2.00k
                                                   synthesized_done_count(),   starttls_request_count()};
830
2.00k
  (void)ldap_observation;
831
2.00k
#endif
832
2.00k
}
833
834
}  // namespace proto_fuzzer