/src/curl_fuzzer/proto_fuzzer/pingpong_mock_server.h
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 PingpongMockServer — shared line-oriented command/response transport |
9 | | /// for the mail-style protocol peers. |
10 | | |
11 | | #ifndef PROTO_FUZZER_PINGPONG_MOCK_SERVER_H_ |
12 | | #define PROTO_FUZZER_PINGPONG_MOCK_SERVER_H_ |
13 | | |
14 | | #include <curl/curl.h> |
15 | | |
16 | | #include <cstddef> |
17 | | #include <memory> |
18 | | #include <string> |
19 | | #include <string_view> |
20 | | |
21 | | #include "curl_fuzzer.pb.h" |
22 | | #include "proto_fuzzer/incoming_data_observer.h" |
23 | | #include "proto_fuzzer/mock_server_base.h" |
24 | | #include "proto_fuzzer/scenario_limits.h" |
25 | | |
26 | | namespace proto_fuzzer { |
27 | | |
28 | | class MockConnection; |
29 | | |
30 | | /// @class proto_fuzzer::PingpongMockServer |
31 | | /// @brief Drives one control socketpair that speaks a line-oriented |
32 | | /// command/response protocol. |
33 | | /// |
34 | | /// The base owns the transport lifecycle, the bounded perform loop, line |
35 | | /// buffering, the reply cursor, and the test-facing transcript. A concrete |
36 | | /// peer supplies HandleLine() and may switch the parser into body mode after a |
37 | | /// command that uploads data (SMTP DATA, IMAP APPEND). Replies are emitted |
38 | | /// exactly as scripted; a peer that needs protocol-specific rewriting, such as |
39 | | /// IMAP tag insertion, does so inside HandleLine(). |
40 | | /// |
41 | | /// Scenario.connection is a command-aligned script: initial_response is the |
42 | | /// server greeting and each on_readable entry answers the next command in |
43 | | /// order. Subclasses replace the transport through CreateConnection(); the |
44 | | /// implicit-TLS SMTPS peer uses that hook without touching the parser. |
45 | | class PingpongMockServer : public MockServerBase, public IncomingDataObserver { |
46 | | public: |
47 | | ~PingpongMockServer() override; |
48 | | |
49 | | PingpongMockServer(const PingpongMockServer&) = delete; |
50 | | PingpongMockServer& operator=(const PingpongMockServer&) = delete; |
51 | | |
52 | | // Bounded record of complete command lines sent by curl. |
53 | | const std::string& control_transcript() const; |
54 | | |
55 | | // Bounded record of the body most recently drained by a body phase. Peers |
56 | | // without an upload direction keep this empty. |
57 | | const std::string& uploaded_data() const; |
58 | | |
59 | | // Number of opt-in multi-poll probes issued while the most recent transfer |
60 | | // was active and its control socket had been handed to curl. |
61 | | std::size_t active_pollset_probe_count() const; |
62 | | |
63 | | // Number of opt-in probes where curl requested writable readiness while |
64 | | // the peer held an incomplete control command. A positive count exposes a |
65 | | // pending protocol send rather than a transient writable state. |
66 | | std::size_t writable_pollset_probe_count() const; |
67 | | |
68 | | protected: |
69 | | explicit PingpongMockServer(MultiDrivePolicy drive_policy = MultiDrivePolicy::kPerform); |
70 | | |
71 | | // Create the transport that carries the exchange. Overridden by TLS peers. |
72 | | virtual std::unique_ptr<MockConnection> CreateConnection(); |
73 | | |
74 | | /// Answer one complete, newline-terminated command line. |
75 | | /// @param line Complete command line, including its line ending. |
76 | | virtual void HandleLine(std::string_view line) = 0; |
77 | | |
78 | | // Body phase control. Only valid while HandleLine() is running; the parser |
79 | | // consumes the body before processing further command lines. |
80 | | |
81 | | // Consume bytes through the first occurrence of `terminator`, capturing the |
82 | | // body and the terminator itself. Used by SMTP's "\r\n.\r\n" end-of-body. |
83 | | void BeginMarkerBody(std::string_view terminator); |
84 | | |
85 | | // Consume exactly `length` bytes, capturing them, followed by a CRLF line |
86 | | // terminator that is not captured. Used by IMAP's {N} literal uploads. |
87 | | void BeginLiteralBody(std::size_t length); |
88 | | |
89 | | // Consume exactly `length` bytes, capturing them, with no trailing |
90 | | // terminator. Used by protocols such as RTSP whose announced entity body is |
91 | | // followed immediately by the next request or by the peer's close. |
92 | | void BeginExactBody(std::size_t length); |
93 | | |
94 | | // Drain all subsequent carrier bytes without command parsing or capture. |
95 | | // Plaintext upgrade peers use this after accepting STARTTLS because the |
96 | | // following TLS handshake is intentionally opaque to the line parser. |
97 | | void BeginOpaqueDrain(); |
98 | | |
99 | | /// Called after a body phase reached its terminator and the parser returned |
100 | | /// to command mode. The default does nothing. |
101 | 1.31k | virtual void HandleBodyComplete() {} |
102 | | |
103 | | /// Queue protocol-specific teardown liveness bytes before the control socket |
104 | | /// is half-closed. |
105 | 9.67k | virtual void QueueShutdownReply() {} |
106 | | |
107 | | /// Reset protocol-specific parser state for a new drive. The transport, |
108 | | /// cursors, transcript, upload capture, and body phase are already reset. |
109 | 4.01k | virtual void ResetProtocolState() {} |
110 | | |
111 | | curl_socket_t HandleOpenSocket(curlsocktype purpose = CURLSOCKTYPE_IPCXN, |
112 | | struct curl_sockaddr* address = nullptr) override; |
113 | | |
114 | | void RunLoop(CURLM* multi, CURL* easy, const curl::fuzzer::proto::Scenario& scenario) override; |
115 | | |
116 | | void HandleDetachedMulti(CurlMultiPtr multi) override; |
117 | | |
118 | | void ObserveIncomingData(const unsigned char* data, std::size_t size) override; |
119 | | |
120 | | /// Borrowed scenario for the synchronous drive, or nullptr outside RunLoop(). |
121 | | /// @return The Scenario borrowed by the active drive, or nullptr. |
122 | 207k | const curl::fuzzer::proto::Scenario* scenario() const { return scenario_; } |
123 | | |
124 | | // Return the next command-aligned reply, or nullptr once the bounded script |
125 | | // is exhausted. Empty entries still advance the cursor. |
126 | | const std::string* NextControlReply(); |
127 | | |
128 | | // Queue one reply fragment, returning false only when the transport write |
129 | | // failed. An empty fragment is a successful no-op. |
130 | | bool WriteControlBytes(std::string_view bytes); |
131 | | |
132 | | // Write the next scripted reply. Returns false when none remains. |
133 | | bool WriteNextReply(); |
134 | | |
135 | | // Half-close the peer's write side after a protocol-level transport |
136 | | // upgrade response. The existing socket remains readable so the bounded |
137 | | // driver can drain client handshake bytes without parsing them as commands. |
138 | | void ShutdownControlWrite(); |
139 | | |
140 | | // First and second whitespace-delimited tokens of a command line, without |
141 | | // interpreting any protocol-specific arguments. |
142 | | static std::string_view FirstToken(std::string_view line); |
143 | | static std::string_view SecondToken(std::string_view line); |
144 | | |
145 | | // Compare an ASCII protocol token to an uppercase literal, ignoring case. |
146 | | static bool TokenEquals(std::string_view token, std::string_view expected_uppercase); |
147 | | |
148 | | private: |
149 | | /// Parser mode after the most recent command. |
150 | | enum class BodyMode { |
151 | | kCommand, ///< Splitting newline-terminated command lines. |
152 | | kMarker, ///< Scanning for an opaque end-of-body marker. |
153 | | kLiteral, ///< Draining an announced number of bytes, then CRLF. |
154 | | kExact, ///< Draining exactly an announced number of bytes. |
155 | | kOpaque, ///< Discarding carrier bytes after a transport upgrade. |
156 | | }; |
157 | | |
158 | | // Observability must not grow with a future curl loop; these caps exceed the |
159 | | // normalized upload and command budgets without affecting draining. |
160 | | static constexpr std::size_t kMaxCapturedControlBytes = 64 * 1024; |
161 | | static constexpr std::size_t kMaxCapturedUploadBytes = 2 * scenario_limits::kMaxUploadBytes; |
162 | | |
163 | | void ResetForScenario(const curl::fuzzer::proto::Scenario& scenario); |
164 | | |
165 | | static void ApplyScriptBackpressure(MockConnection* connection, const curl::fuzzer::proto::Connection& script); |
166 | | |
167 | | bool ServiceControlConnection(); |
168 | | |
169 | | void FinishConnections(); |
170 | | |
171 | | // Retain a bounded prefix for assertions without affecting parser progress. |
172 | | static void CapturePrefix(std::string_view source, std::size_t limit, std::string* destination); |
173 | | |
174 | | /// Borrowed only while RunLoop is active, including every socket callback. |
175 | | const curl::fuzzer::proto::Scenario* scenario_; |
176 | | /// Runtime-visible prefix of on_readable response fragments. |
177 | | std::size_t control_reply_count_; |
178 | | /// Cursor advanced once per command, plus any pre-queued body completion. |
179 | | std::size_t next_control_reply_; |
180 | | /// Partial command or body bytes retained until the next read. |
181 | | std::string pending_control_bytes_; |
182 | | /// Bounded test-facing record of complete commands sent by curl. |
183 | | std::string control_transcript_; |
184 | | /// Bounded test-facing prefix of the body drained in the last body phase. |
185 | | std::string uploaded_data_; |
186 | | /// Opt-in probes made only while the transfer and control socket were live. |
187 | | std::size_t active_pollset_probe_count_; |
188 | | /// Writable probes observed while one control command remained incomplete. |
189 | | std::size_t writable_pollset_probe_count_; |
190 | | /// Opaque terminator for BodyMode::kMarker. |
191 | | std::string body_marker_; |
192 | | /// Literal bytes still to drain for BodyMode::kLiteral. |
193 | | std::size_t body_length_remaining_; |
194 | | /// Remaining bytes of the CRLF sent after a literal body. |
195 | | std::size_t body_terminator_remaining_; |
196 | | /// Current parser phase. |
197 | | BodyMode body_mode_; |
198 | | /// Client endpoint handed to curl, retained only as an opaque fd identity. |
199 | | curl_socket_t control_socket_; |
200 | | /// Prevent a second control socket from displacing the live first one. |
201 | | bool control_opened_; |
202 | | }; |
203 | | |
204 | | } // namespace proto_fuzzer |
205 | | |
206 | | #endif // PROTO_FUZZER_PINGPONG_MOCK_SERVER_H_ |