/src/curl_fuzzer/proto_fuzzer/mqtt_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 packet-aware in-process MQTT peer. |
9 | | |
10 | | #include "proto_fuzzer/mqtt_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 | | // MQTT 3.1.1 control packet types, already shifted into the fixed header's |
28 | | // high nibble. The low nibble carries type-specific flags such as PUBLISH QoS. |
29 | | constexpr unsigned char kMqttConnect = 0x10; |
30 | | constexpr unsigned char kMqttPublish = 0x30; |
31 | | constexpr unsigned char kMqttPuback = 0x40; |
32 | | constexpr unsigned char kMqttSubscribe = 0x80; |
33 | | constexpr unsigned char kMqttSuback = 0x90; |
34 | | constexpr unsigned char kMqttPingreq = 0xc0; |
35 | | constexpr unsigned char kMqttPingresp = 0xd0; |
36 | | constexpr unsigned char kMqttDisconnect = 0xe0; |
37 | | constexpr std::size_t kMqttProbePublishBytes = 16 * 1024; |
38 | | constexpr std::size_t kOversizedMqttCredentialBytes = 0x10000; |
39 | | |
40 | 12.8k | unsigned char ByteAt(std::string_view bytes, std::size_t index) { return static_cast<unsigned char>(bytes[index]); } |
41 | | |
42 | | } // namespace |
43 | | |
44 | | /// Begin without a borrowed protobuf or open socketpair. RunLoop borrows a |
45 | | /// Scenario only for the synchronous DriveScenario call in which socket |
46 | | /// callbacks can run. |
47 | | /// @param mode Closed harness-owned probe shape to apply before the transfer. |
48 | | MqttMockServer::MqttMockServer(curl::fuzzer::proto::MqttProbeMode mode) |
49 | 4.21k | : mode_(mode), |
50 | 4.21k | scenario_(nullptr), |
51 | 4.21k | server_chunk_count_(0), |
52 | 4.21k | next_server_chunk_(0), |
53 | 4.21k | packet_count_(0), |
54 | 4.21k | connect_count_(0), |
55 | 4.21k | publish_count_(0), |
56 | 4.21k | subscribe_count_(0), |
57 | 4.21k | qos1_publish_count_(0), |
58 | 4.21k | active_pollset_probe_count_(0), |
59 | 4.21k | release_script_chunks_(false), |
60 | 4.21k | protocol_error_(false), |
61 | 4.21k | socket_opened_(false) {} |
62 | | |
63 | | /// Release the server-owned socketpair half after curl has returned its client |
64 | | /// descriptor. The out-of-line destructor keeps MockConnection's complete type |
65 | | /// local to this translation unit. |
66 | 4.21k | MqttMockServer::~MqttMockServer() = default; |
67 | | |
68 | | /// @return A prefix of complete client packets from the most recent drive. |
69 | 4.17k | const std::string& MqttMockServer::packet_transcript() const { return packet_transcript_; } |
70 | | |
71 | | /// @return A prefix of the first PUBLISH packet's topic. |
72 | 0 | const std::string& MqttMockServer::published_topic() const { return published_topic_; } |
73 | | |
74 | | /// @return A prefix of the first PUBLISH packet's application payload. |
75 | 4.17k | const std::string& MqttMockServer::published_payload() const { return published_payload_; } |
76 | | |
77 | | /// @return Number of complete client packets observed in the most recent drive. |
78 | 7.64k | std::size_t MqttMockServer::packet_count() const { return packet_count_; } |
79 | | |
80 | | /// @return Number of CONNECT packets observed. |
81 | 0 | std::size_t MqttMockServer::connect_count() const { return connect_count_; } |
82 | | |
83 | | /// @return Number of PUBLISH packets observed. |
84 | 4.17k | std::size_t MqttMockServer::publish_count() const { return publish_count_; } |
85 | | |
86 | | /// @return Number of SUBSCRIBE packets observed. |
87 | 4.17k | std::size_t MqttMockServer::subscribe_count() const { return subscribe_count_; } |
88 | | |
89 | | /// @return Number of PUBLISH packets that requested QoS 1. |
90 | 0 | std::size_t MqttMockServer::qos1_publish_count() const { return qos1_publish_count_; } |
91 | | |
92 | | /// Report how many requested zero-timeout multi-poll probes ran during the |
93 | | /// most recent drive. RunLoop increments this only after a successful perform |
94 | | /// turn while curl still owns an active transfer and the MQTT socket is open. |
95 | | /// @return Number of active, connected pollset probes in the previous drive. |
96 | 0 | std::size_t MqttMockServer::active_pollset_probe_count() const { return active_pollset_probe_count_; } |
97 | | |
98 | | /// Reset every borrowed pointer, parser cursor, and observable capture before |
99 | | /// borrowing the next Scenario. |
100 | | /// @param scenario Scenario whose Connection supplies the CONNACK and any |
101 | | /// server-initiated packet chunks. |
102 | 4.01k | void MqttMockServer::ResetForScenario(const curl::fuzzer::proto::Scenario& scenario) { |
103 | 4.01k | connection_.reset(); |
104 | 4.01k | scenario_ = &scenario; |
105 | 4.01k | server_chunk_count_ = std::min<std::size_t>(scenario_limits::kMaxResponseChunks, |
106 | 4.01k | static_cast<std::size_t>(scenario.connection().on_readable_size())); |
107 | 4.01k | next_server_chunk_ = 0; |
108 | 4.01k | packet_count_ = 0; |
109 | 4.01k | connect_count_ = 0; |
110 | 4.01k | publish_count_ = 0; |
111 | 4.01k | subscribe_count_ = 0; |
112 | 4.01k | qos1_publish_count_ = 0; |
113 | 4.01k | active_pollset_probe_count_ = 0; |
114 | 4.01k | pending_client_bytes_.clear(); |
115 | 4.01k | packet_transcript_.clear(); |
116 | 4.01k | published_topic_.clear(); |
117 | 4.01k | published_payload_.clear(); |
118 | 4.01k | release_script_chunks_ = false; |
119 | 4.01k | protocol_error_ = false; |
120 | 4.01k | socket_opened_ = false; |
121 | 4.01k | } |
122 | | |
123 | | /// Apply bounded transport knobs when creating the scripted socket. Target |
124 | | /// policies normally clear MQTT backpressure, but direct corpus replay must |
125 | | /// retain deterministic, well-defined behavior. |
126 | | /// @param connection Peer receiving the socket settings. |
127 | | /// @param script Connection script carrying optional backpressure values. |
128 | | void MqttMockServer::ApplyScriptBackpressure(MockConnection* connection, |
129 | 3.64k | const curl::fuzzer::proto::Connection& script) { |
130 | 3.64k | if (connection == nullptr) { |
131 | 0 | return; |
132 | 0 | } |
133 | | |
134 | 3.64k | const std::uint32_t int_max = static_cast<std::uint32_t>(std::numeric_limits<int>::max()); |
135 | 3.64k | const auto& backpressure = script.backpressure(); |
136 | 3.64k | const int receive_buffer = static_cast<int>(std::min(backpressure.recv_buf_bytes(), int_max)); |
137 | 3.64k | connection->ApplyBackpressure(receive_buffer, static_cast<std::size_t>(backpressure.drain_limit())); |
138 | 3.64k | } |
139 | | |
140 | | /// Create the default plaintext transport for the MQTT packet exchange. The |
141 | | /// MQTTS subclass overrides this factory while retaining the binary parser. |
142 | | /// @return A new socketpair-backed connection. |
143 | 507 | std::unique_ptr<MockConnection> MqttMockServer::CreateConnection() { return std::make_unique<MockConnection>(); } |
144 | | |
145 | | /// Append decoded application bytes to the pending parser buffer. The outer |
146 | | /// service loop drains this buffer after every transport call, so it remains |
147 | | /// bounded by the scenario's packet budget. |
148 | | /// @param data First decoded byte. |
149 | | /// @param size Number of bytes available at `data`. |
150 | 6.59k | void MqttMockServer::ObserveIncomingData(const unsigned char* data, std::size_t size) { |
151 | 6.59k | if (data == nullptr || size == 0) { |
152 | 0 | return; |
153 | 0 | } |
154 | 6.59k | pending_client_bytes_.append(reinterpret_cast<const char*>(data), size); |
155 | 6.59k | } |
156 | | |
157 | | /// Create the single MQTT socketpair and queue the scenario's first server |
158 | | /// bytes. curl sends CONNECT immediately, so a normal scenario preloads the |
159 | | /// CONNACK here; an empty or malformed greeting remains a reachable error path. |
160 | | /// @param purpose Socket role requested by curl. |
161 | | /// @param address Unused stream destination metadata required by the callback |
162 | | /// signature. |
163 | | /// @return Client descriptor for the MQTT channel, or CURL_SOCKET_BAD. |
164 | 3.64k | curl_socket_t MqttMockServer::HandleOpenSocket(curlsocktype purpose, struct curl_sockaddr* /*address*/) { |
165 | 3.64k | if (scenario_ == nullptr || purpose != CURLSOCKTYPE_IPCXN || socket_opened_) { |
166 | 0 | return CURL_SOCKET_BAD; |
167 | 0 | } |
168 | | |
169 | 3.64k | connection_ = CreateConnection(); |
170 | 3.64k | if (!connection_ || !connection_->ok()) { |
171 | 0 | connection_.reset(); |
172 | 0 | return CURL_SOCKET_BAD; |
173 | 0 | } |
174 | 3.64k | connection_->SetIncomingDataObserver(this); |
175 | | |
176 | 3.64k | ApplyScriptBackpressure(connection_.get(), scenario_->connection()); |
177 | 3.64k | const std::string& greeting = scenario_->connection().initial_response(); |
178 | 3.64k | if (!greeting.empty() && |
179 | 1.56k | !connection_->WriteAll(reinterpret_cast<const unsigned char*>(greeting.data()), greeting.size())) { |
180 | 2 | connection_.reset(); |
181 | 2 | return CURL_SOCKET_BAD; |
182 | 2 | } |
183 | | |
184 | 3.64k | socket_opened_ = true; |
185 | 3.64k | return connection_->take_client_fd(); |
186 | 3.64k | } |
187 | | |
188 | | /// Decode MQTT's base-128 remaining-length field. MQTT 3.1.1 permits at most |
189 | | /// four length bytes; a fifth continuation is a malformed fixed header rather |
190 | | /// than an invitation to wait for more input. |
191 | | /// @param bytes Fixed header and whatever length bytes have arrived. |
192 | | /// @param header_size Receives the fixed-header size when complete. |
193 | | /// @param remaining_length Receives the declared body size when complete. |
194 | | /// @return kComplete, kNeedMore, or kInvalid. |
195 | | MqttMockServer::ParseResult MqttMockServer::ParseRemainingLength(std::string_view bytes, std::size_t* header_size, |
196 | 4.98k | std::size_t* remaining_length) { |
197 | 4.98k | std::size_t value = 0; |
198 | 4.98k | std::size_t multiplier = 1; |
199 | 5.51k | for (std::size_t index = 1; index <= 4; ++index) { |
200 | 5.51k | if (bytes.size() <= index) { |
201 | 0 | return ParseResult::kNeedMore; |
202 | 0 | } |
203 | 5.51k | const unsigned char encoded = ByteAt(bytes, index); |
204 | 5.51k | value += static_cast<std::size_t>(encoded & 0x7fU) * multiplier; |
205 | 5.51k | if ((encoded & 0x80U) == 0) { |
206 | 4.98k | *header_size = index + 1; |
207 | 4.98k | *remaining_length = value; |
208 | 4.98k | return ParseResult::kComplete; |
209 | 4.98k | } |
210 | 532 | multiplier *= 128; |
211 | 532 | } |
212 | 0 | return ParseResult::kInvalid; |
213 | 4.98k | } |
214 | | |
215 | | /// Retain only a bounded prefix for assertions. Parsing and draining continue |
216 | | /// against the full transport bytes, so reaching the cap cannot change curl's |
217 | | /// behavior or manufacture socket backpressure. |
218 | | /// @param source Newly observed bytes. |
219 | | /// @param limit Maximum retained destination size. |
220 | | /// @param destination Capture buffer receiving the available prefix. |
221 | 5.30k | void MqttMockServer::CapturePrefix(std::string_view source, std::size_t limit, std::string* destination) { |
222 | 5.30k | if (destination == nullptr || destination->size() >= limit) { |
223 | 6 | return; |
224 | 6 | } |
225 | 5.29k | const std::size_t available = limit - destination->size(); |
226 | 5.29k | destination->append(source.data(), std::min(source.size(), available)); |
227 | 5.29k | } |
228 | | |
229 | | /// Keep failed peer writes local to the mock. Response cursors must still |
230 | | /// advance after curl closes early, otherwise a replacement socket could see a |
231 | | /// reply intended for an earlier packet. |
232 | | /// @param bytes Response bytes to queue. |
233 | | /// @return true when the complete fragment was queued. |
234 | 6.10k | bool MqttMockServer::WriteServerBytes(std::string_view bytes) { |
235 | 6.10k | return bytes.empty() || (connection_ != nullptr && |
236 | 6.10k | connection_->WriteAll(reinterpret_cast<const unsigned char*>(bytes.data()), bytes.size())); |
237 | 6.10k | } |
238 | | |
239 | | /// Interpret one complete client packet. Packet classification uses only the |
240 | | /// fixed header, so a malformed variable header cannot desynchronize the |
241 | | /// remaining-length parser that already found the next boundary. |
242 | | /// @param first_byte Fixed header byte carrying the type and flags. |
243 | | /// @param body Variable header plus payload, exactly `remaining_length` bytes. |
244 | 4.95k | void MqttMockServer::HandleClientPacket(unsigned char first_byte, std::string_view body) { |
245 | 4.95k | const unsigned char type = static_cast<unsigned char>(first_byte & 0xf0U); |
246 | 4.95k | switch (type) { |
247 | 3.58k | case kMqttConnect: |
248 | 3.58k | ++connect_count_; |
249 | 3.58k | return; |
250 | | |
251 | 172 | case kMqttPublish: { |
252 | 172 | ++publish_count_; |
253 | 172 | if (body.size() < 2) { |
254 | 0 | return; |
255 | 0 | } |
256 | 172 | const std::size_t topic_length = |
257 | 172 | (static_cast<std::size_t>(ByteAt(body, 0)) << 8U) | static_cast<std::size_t>(ByteAt(body, 1)); |
258 | 172 | std::size_t cursor = 2; |
259 | 172 | const std::size_t available = body.size() - cursor; |
260 | 172 | const std::size_t captured_topic = std::min(topic_length, available); |
261 | 172 | CapturePrefix(body.substr(cursor, captured_topic), scenario_limits::kMaxMetadataBytes, &published_topic_); |
262 | 172 | cursor += captured_topic; |
263 | 172 | if (captured_topic < topic_length) { |
264 | 0 | return; |
265 | 0 | } |
266 | | |
267 | 172 | const unsigned qos = (static_cast<unsigned>(first_byte) >> 1U) & 0x03U; |
268 | 172 | if (qos == 1U) { |
269 | 0 | if (body.size() - cursor < 2) { |
270 | 0 | return; |
271 | 0 | } |
272 | 0 | const unsigned char packet_id_high = ByteAt(body, cursor); |
273 | 0 | const unsigned char packet_id_low = ByteAt(body, cursor + 1); |
274 | 0 | cursor += 2; |
275 | | // PUBACK has no flags and a two-byte remaining length followed by the |
276 | | // packet identifier it acknowledges. Current curl always publishes at |
277 | | // QoS 0; this branch keeps the acknowledgement path correct if a |
278 | | // future revision makes QoS configurable. |
279 | 0 | const unsigned char puback[] = {kMqttPuback, 0x02, packet_id_high, packet_id_low}; |
280 | 0 | (void)WriteServerBytes(std::string_view(reinterpret_cast<const char*>(puback), sizeof(puback))); |
281 | 0 | ++qos1_publish_count_; |
282 | 0 | } |
283 | | |
284 | 172 | CapturePrefix(body.substr(cursor), kMaxCapturedPayloadBytes, &published_payload_); |
285 | 172 | return; |
286 | 172 | } |
287 | | |
288 | 1.02k | case kMqttSubscribe: { |
289 | 1.02k | ++subscribe_count_; |
290 | 1.02k | const unsigned char packet_id_high = body.empty() ? 0 : ByteAt(body, 0); |
291 | 1.02k | const unsigned char packet_id_low = body.size() < 2 ? 0 : ByteAt(body, 1); |
292 | | // SUBACK echoes the SUBSCRIBE packet id and reports success for the |
293 | | // single requested topic filter. curl's MQTT state machine compares both |
294 | | // identifier bytes and the return code before accepting the packet. |
295 | 1.02k | const unsigned char suback[] = {kMqttSuback, 0x03, packet_id_high, packet_id_low, 0x00}; |
296 | 1.02k | (void)WriteServerBytes(std::string_view(reinterpret_cast<const char*>(suback), sizeof(suback))); |
297 | | // Only the subscribe flow remains readable after its acknowledgement. |
298 | | // on_readable chunks carry server-initiated packets such as PUBLISH. |
299 | 1.02k | release_script_chunks_ = true; |
300 | 1.02k | return; |
301 | 172 | } |
302 | | |
303 | 0 | case kMqttPingreq: { |
304 | 0 | const unsigned char pingresp[] = {kMqttPingresp, 0x00}; |
305 | 0 | (void)WriteServerBytes(std::string_view(reinterpret_cast<const char*>(pingresp), sizeof(pingresp))); |
306 | 0 | return; |
307 | 172 | } |
308 | | |
309 | 172 | case kMqttDisconnect: |
310 | | // curl sends DISCONNECT after PUBLISH. No reply is defined, and the |
311 | | // cleanup half-close below still terminates the socket. |
312 | 172 | return; |
313 | | |
314 | 0 | default: |
315 | | // CONNACK/SUBACK/PUBACK and unknown types are server-to-client packets. |
316 | | // Recording them in the transcript is enough; inventing a reply would |
317 | | // only add bytes curl never reads in this direction. |
318 | 0 | return; |
319 | 4.95k | } |
320 | 4.95k | } |
321 | | |
322 | | /// Release one scenario-provided server chunk after SUBACK. Chunks are opaque |
323 | | /// bytes, not newline commands: each one is expected to be a complete MQTT |
324 | | /// packet (for example PUBLISH followed by DISCONNECT). An explicitly empty |
325 | | /// chunk half-closes the peer, retaining a scripted truncation/EOF path. |
326 | | /// @return true when a script slot was consumed. |
327 | 42.9k | bool MqttMockServer::ReleaseNextServerChunk() { |
328 | 42.9k | if (!release_script_chunks_ || scenario_ == nullptr || connection_ == nullptr || |
329 | 37.8k | next_server_chunk_ >= server_chunk_count_) { |
330 | 37.8k | return false; |
331 | 37.8k | } |
332 | | |
333 | 5.16k | const std::string& chunk = scenario_->connection().on_readable(static_cast<int>(next_server_chunk_++)); |
334 | 5.16k | if (chunk.empty()) { |
335 | 84 | connection_->ShutdownWrite(); |
336 | 84 | release_script_chunks_ = false; |
337 | 84 | return true; |
338 | 84 | } |
339 | | |
340 | 5.07k | (void)WriteServerBytes(chunk); |
341 | 5.07k | if (next_server_chunk_ >= server_chunk_count_) { |
342 | 526 | connection_->ShutdownWrite(); |
343 | 526 | } |
344 | 5.07k | return true; |
345 | 5.16k | } |
346 | | |
347 | | /// Advance the carrier without waiting, then process every complete packet |
348 | | /// already decoded into the pending buffer. A plaintext connection yields raw |
349 | | /// socket bytes; a TLS carrier completes its handshake and yields decrypted |
350 | | /// application bytes through ObserveIncomingData. A packet is delivered only |
351 | | /// after its fixed header and declared body have both arrived, so fragmentation |
352 | | /// cannot shift the parser. |
353 | | /// @return true when bytes, transport state, a packet, or a response cursor |
354 | | /// advanced. |
355 | 42.9k | bool MqttMockServer::ServiceClientConnection() { |
356 | 42.9k | if (connection_ == nullptr || protocol_error_) { |
357 | 1.41k | return false; |
358 | 1.41k | } |
359 | | |
360 | 41.5k | const std::size_t size_before_read = pending_client_bytes_.size(); |
361 | 41.5k | const std::size_t transport_progress = connection_->DrainIncoming(); |
362 | 41.5k | bool made_progress = pending_client_bytes_.size() != size_before_read || transport_progress != 0; |
363 | | |
364 | 41.5k | std::size_t consumed = 0; |
365 | 41.5k | int packets = 0; |
366 | 46.5k | while (consumed < pending_client_bytes_.size() && packets < kMaxPacketsPerService) { |
367 | 4.98k | const std::string_view available(pending_client_bytes_.data() + consumed, pending_client_bytes_.size() - consumed); |
368 | 4.98k | if (available.size() < 2) { |
369 | 0 | break; |
370 | 0 | } |
371 | | |
372 | 4.98k | std::size_t header_size = 0; |
373 | 4.98k | std::size_t remaining_length = 0; |
374 | 4.98k | const ParseResult parsed = ParseRemainingLength(available, &header_size, &remaining_length); |
375 | 4.98k | if (parsed == ParseResult::kNeedMore) { |
376 | 0 | break; |
377 | 0 | } |
378 | 4.98k | if (parsed == ParseResult::kInvalid || remaining_length > kMaxPacketBytes) { |
379 | 8 | protocol_error_ = true; |
380 | 8 | break; |
381 | 8 | } |
382 | | |
383 | 4.97k | const std::size_t packet_size = header_size + remaining_length; |
384 | 4.97k | if (available.size() < packet_size) { |
385 | 16 | break; |
386 | 16 | } |
387 | | |
388 | 4.95k | const std::string_view packet = available.substr(0, packet_size); |
389 | 4.95k | CapturePrefix(packet, kMaxCapturedPacketBytes, &packet_transcript_); |
390 | 4.95k | ++packet_count_; |
391 | 4.95k | HandleClientPacket(ByteAt(packet, 0), packet.substr(header_size)); |
392 | 4.95k | consumed += packet_size; |
393 | 4.95k | ++packets; |
394 | 4.95k | made_progress = true; |
395 | 4.95k | } |
396 | | |
397 | 41.5k | if (protocol_error_) { |
398 | 8 | pending_client_bytes_.clear(); |
399 | | // curl's malformed-packet paths are bounded, but closing the write half |
400 | | // immediately keeps a bogus remaining length from waiting on the idle |
401 | | // budget for an impossible body. |
402 | 8 | connection_->ShutdownWrite(); |
403 | 8 | release_script_chunks_ = false; |
404 | 41.5k | } else if (consumed != 0) { |
405 | 4.78k | pending_client_bytes_.erase(0, consumed); |
406 | 4.78k | } |
407 | 41.5k | return made_progress; |
408 | 42.9k | } |
409 | | |
410 | | /// Half-close the peer so curl observes a deterministic end of server packets |
411 | | /// after the transfer has stopped or the idle budget expired. |
412 | 4.01k | void MqttMockServer::FinishConnections() { |
413 | 4.01k | if (connection_ != nullptr) { |
414 | 3.64k | connection_->ShutdownWrite(); |
415 | 3.64k | } |
416 | 4.01k | } |
417 | | |
418 | | /// Install one fixed option shape after ordinary scenario options but before |
419 | | /// curl starts the transfer. The static strings outlive the easy handle; |
420 | | /// notably CURLOPT_POSTFIELDS borrows rather than copies its pointer. |
421 | | /// @param easy Handle receiving the harness-owned probe values. |
422 | 4.01k | void MqttMockServer::ApplyProbeOptions(CURL* easy) const { |
423 | 4.01k | if (easy == nullptr) { |
424 | 0 | return; |
425 | 0 | } |
426 | | |
427 | 4.01k | switch (mode_) { |
428 | 1 | case curl::fuzzer::proto::MQTT_PROBE_SEND_BACKPRESSURE: { |
429 | 1 | static const std::string publish_body(kMqttProbePublishBytes, 'p'); |
430 | 1 | (void)curl_easy_setopt(easy, CURLOPT_POSTFIELDSIZE_LARGE, static_cast<curl_off_t>(publish_body.size())); |
431 | 1 | (void)curl_easy_setopt(easy, CURLOPT_POSTFIELDS, publish_body.c_str()); |
432 | 1 | return; |
433 | 0 | } |
434 | | |
435 | 1 | case curl::fuzzer::proto::MQTT_PROBE_OVERSIZED_USERNAME: { |
436 | 1 | static const std::string username(kOversizedMqttCredentialBytes, 'u'); |
437 | 1 | (void)curl_easy_setopt(easy, CURLOPT_USERNAME, username.c_str()); |
438 | 1 | (void)curl_easy_setopt(easy, CURLOPT_PASSWORD, ""); |
439 | 1 | return; |
440 | 0 | } |
441 | | |
442 | 1 | case curl::fuzzer::proto::MQTT_PROBE_OVERSIZED_PASSWORD: { |
443 | 1 | static const std::string password(kOversizedMqttCredentialBytes, 'p'); |
444 | 1 | (void)curl_easy_setopt(easy, CURLOPT_USERNAME, ""); |
445 | 1 | (void)curl_easy_setopt(easy, CURLOPT_PASSWORD, password.c_str()); |
446 | 1 | return; |
447 | 0 | } |
448 | | |
449 | 4.01k | case curl::fuzzer::proto::MQTT_PROBE_DEFAULT: |
450 | 4.01k | default: |
451 | 4.01k | return; |
452 | 4.01k | } |
453 | 4.01k | } |
454 | | |
455 | | /// Alternate curl transitions with immediate peer service until the transfer |
456 | | /// completes or deterministic idle/operation caps win. No select(), poll(), or |
457 | | /// sleep is needed: the CONNACK is preloaded, synthesized acknowledgements are |
458 | | /// written from the same thread, and scripted server packets are released one |
459 | | /// per turn so curl consumes the preceding acknowledgement first. |
460 | | /// @param multi Multi handle containing `easy`. |
461 | | /// @param easy Easy handle already installed on this mock. |
462 | | /// @param scenario Connection script to borrow. |
463 | 4.01k | void MqttMockServer::RunLoop(CURLM* multi, CURL* easy, const curl::fuzzer::proto::Scenario& scenario) { |
464 | 4.01k | ApplyProbeOptions(easy); |
465 | 4.01k | ResetForScenario(scenario); |
466 | | |
467 | 4.01k | int still_running = 1; |
468 | 4.01k | int idle_iterations = 0; |
469 | 4.01k | int drive_iterations = 0; |
470 | 4.01k | CURLMcode result = CURLM_OK; |
471 | 42.9k | while (still_running && idle_iterations < kMaxIdleIterations && drive_iterations++ < kMaxDriveIterations) { |
472 | 38.9k | const int running_before = still_running; |
473 | 38.9k | result = curl_multi_perform(multi, &still_running); |
474 | 38.9k | if (result != CURLM_OK) { |
475 | 0 | break; |
476 | 0 | } |
477 | | |
478 | | // Pollset construction is opt-in coverage work. Waiting until the socket |
479 | | // callback has run and the transfer remains active keeps the default hot |
480 | | // loop syscall-free and asks curl for a live MQTT protocol pollset. |
481 | 38.9k | if (scenario.probe_multi_pollset() && still_running && socket_opened_) { |
482 | 1.66k | ProbeMultiPollset(multi); |
483 | 1.66k | ++active_pollset_probe_count_; |
484 | 1.66k | } |
485 | | |
486 | 38.9k | bool made_progress = still_running != running_before; |
487 | 38.9k | made_progress = ServiceClientConnection() || made_progress; |
488 | 38.9k | made_progress = ReleaseNextServerChunk() || made_progress; |
489 | 38.9k | if (made_progress) { |
490 | 14.0k | idle_iterations = 0; |
491 | 24.8k | } else { |
492 | 24.8k | ++idle_iterations; |
493 | 24.8k | } |
494 | 38.9k | } |
495 | | |
496 | | // The final perform may have emitted CONNECT/PUBLISH/DISCONNECT immediately |
497 | | // before marking the transfer done. Drain those bytes before cleanup. |
498 | 4.01k | (void)ServiceClientConnection(); |
499 | 4.01k | (void)ReleaseNextServerChunk(); |
500 | 4.01k | FinishConnections(); |
501 | 4.01k | scenario_ = nullptr; |
502 | 4.01k | } |
503 | | |
504 | | /// Retain protocol outcomes in coverage and introspector builds. |
505 | 4.17k | void MqttMockServer::ObserveState() { |
506 | 4.17k | #if defined(PROTO_FUZZER_OBSERVE_STATE) |
507 | 4.17k | MockServerBase::ObserveState(); |
508 | 4.17k | const volatile std::size_t mqtt_observation[] = {packet_transcript().size(), packet_count(), publish_count(), |
509 | 4.17k | subscribe_count(), published_payload().size()}; |
510 | 4.17k | (void)mqtt_observation; |
511 | 4.17k | #endif |
512 | 4.17k | } |
513 | | |
514 | | } // namespace proto_fuzzer |