Coverage Report

Created: 2026-12-01 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/fuzz_h2_conn.cpp
Line
Count
Source
1
// Copyright 2026 Google LLC
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//      http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
//
15
////////////////////////////////////////////////////////////////////////////////
16
//
17
// End-to-end fuzzer for the HTTP/2 server implementation (src/mhd2/h2/*).
18
//
19
// Threat model: a remote, unauthenticated client opens a cleartext TCP
20
// connection and speaks HTTP/2 with "prior knowledge" (RFC 9113 3.3), which
21
// MHD2 enables by default.  Every byte after the connection preface is
22
// attacker controlled: frame headers, SETTINGS, HEADERS/CONTINUATION carrying
23
// HPACK blocks, DATA, WINDOW_UPDATE, RST_STREAM, PING, GOAWAY, PRIORITY,
24
// unknown frames, padding, stream-id/state-machine abuse, etc.
25
//
26
// The harness writes the fixed 24-byte client preface followed by the fuzz
27
// input into a client connection accepted by a real MHD daemon
28
// (see the driver below), and drives the daemon until the input has been
29
// consumed and the connection is closed.  The fixed preface lets the fuzzer
30
// spend its mutations on the frame layer instead of rediscovering the magic.
31
// The application callback reads headers/cookies/arguments and handles
32
// uploads and POST forms, so the HTTP/2 request item storage (h2_req_*), the
33
// reply path (h2_reply_funcs.c with the HPACK encoder) and stream processing
34
// are all exercised.  (Authentication and MHD_request_get_info_*() are
35
// skipped for HTTP/2, see g_fuzz_skip_h1_only_request_apis.)
36
37
#include <errno.h>
38
#include <fcntl.h>
39
#include <poll.h>
40
#include <signal.h>
41
#include <stdarg.h>
42
#include <stddef.h>
43
#include <stdint.h>
44
#include <string.h>
45
#include <sys/socket.h>
46
#include <sys/types.h>
47
#include <netinet/in.h>
48
#include <netinet/tcp.h>
49
#include <arpa/inet.h>
50
#include <unistd.h>
51
52
#include <map>
53
#include <string>
54
#include <vector>
55
56
#include "microhttpd2.h"
57
58
// Realm/credentials known to the fuzz application (also in the dictionary).
59
0
#define FUZZ_REALM "fuzzrealm"
60
0
#define FUZZ_USER "fuzzuser"
61
0
#define FUZZ_PASS "fuzzpass"
62
63
namespace {
64
65
// When true, the fuzz application does not call request APIs that are
66
// currently implemented for HTTP/1.x requests only (MHD_request_get_info_*(),
67
// Basic/Digest auth getters and checks).  Upstream bug: for HTTP/2 requests
68
// these functions treat the MHD_Request as embedded in struct MHD_Connection
69
// (mhd_CNTNR_PTR(request, struct MHD_Connection, rq)) while it actually lives
70
// in struct mhd_H2Stream, resulting in heap out-of-bounds accesses on every
71
// HTTP/2 request.  Set it to false once upstream has fixed the issue.
72
bool g_fuzz_skip_h1_only_request_apis = true;
73
74
// A TCP client connection to the fuzz daemon.
75
class FuzzClient {
76
 public:
77
  explicit FuzzClient(struct MHD_Daemon *d);
78
  ~FuzzClient();
79
2
  bool ok() const { return fd_ >= 0; }
80
81
  // Write @a data to the server (as much as fits), driving the daemon so it
82
  // keeps draining its receive side; all server output is appended to
83
  // response().
84
  void Send(const uint8_t *data, size_t size);
85
  // Run the daemon event loop a few rounds, collecting output.
86
  void Pump(unsigned rounds);
87
  // Close client side and run the daemon until the connection is gone.
88
  void Close();
89
90
0
  const std::string &response() const { return resp_; }
91
0
  void ClearResponse() { resp_.clear(); }
92
93
 private:
94
  void Drain();
95
  struct MHD_Daemon *d_;
96
  int fd_;
97
  std::string resp_;
98
};
99
100
// ---- End-to-end driver
101
//
102
// A single MHD daemon is started in MHD_WM_EXTERNAL_EVENT_LOOP_CB_LEVEL mode,
103
// listening on 127.0.0.1 (kernel-assigned port).  Each fuzz iteration
104
// connects a new TCP client, lets MHD accept() it and writes the attacker
105
// bytes into the client end; the client is closed with an RST.  The daemon is
106
// driven by a tiny zero-timeout poll() loop feeding MHD_daemon_event_update()
107
// and MHD_daemon_process_reg_events(), so everything runs single-threaded and
108
// deterministically: socket recv -> HTTP/1.x or HTTP/2 layer -> request
109
// parsing -> application callback -> reply -> socket send.
110
//
111
// NOTE: the same driver is duplicated in fuzz_h2_conn.cpp and
112
// fuzz_http1_auth.cpp; keep the two copies in sync.
113
114
struct MHD_Daemon *g_daemon = nullptr;
115
bool g_daemon_tried = false;
116
struct sockaddr_in g_listen_addr;
117
118
volatile uint8_t g_sink;  // Prevents the compiler from dropping reads.
119
120
0
void TouchBytes(const char *p, size_t len) {
121
0
  uint8_t acc = 0;
122
0
  if (p == nullptr)
123
0
    return;
124
0
  for (size_t i = 0; i < len; ++i)
125
0
    acc ^= static_cast<uint8_t>(p[i]);
126
0
  g_sink = acc;
127
0
}
128
129
0
void SilentLog(void *, enum MHD_StatusCode, const char *, va_list) {}
130
131
// ---- Minimal level-triggered external event loop
132
// (MHD_WM_EXTERNAL_EVENT_LOOP_CB_LEVEL), driven with zero-timeout poll().
133
134
struct WatchedFd {
135
  enum MHD_FdState watch_for;
136
  struct MHD_EventUpdateContext *ecb;
137
};
138
std::map<MHD_Socket, WatchedFd> g_watched;
139
int g_app_cntx_marker;  // Address used as the non-NULL application context.
140
141
void *SocketRegCb(void *, MHD_Socket fd, enum MHD_FdState watch_for,
142
10
                  void *, struct MHD_EventUpdateContext *ecb) {
143
10
  if (MHD_FD_STATE_NONE == watch_for) {
144
2
    g_watched.erase(fd);
145
2
    return nullptr;
146
2
  }
147
8
  g_watched[fd] = WatchedFd{watch_for, ecb};
148
8
  return &g_app_cntx_marker;
149
10
}
150
151
28
void RunEventLoopOnce(struct MHD_Daemon *d) {
152
28
  std::vector<struct pollfd> pfds;
153
28
  std::vector<WatchedFd> regs;
154
28
  pfds.reserve(g_watched.size());
155
28
  regs.reserve(g_watched.size());
156
82
  for (const auto &it : g_watched) {
157
82
    struct pollfd p;
158
82
    p.fd = it.first;
159
82
    p.events = 0;
160
82
    if (MHD_FD_STATE_IS_SET_RECV(it.second.watch_for))
161
82
      p.events |= POLLIN;
162
82
    if (MHD_FD_STATE_IS_SET_SEND(it.second.watch_for))
163
2
      p.events |= POLLOUT;
164
82
    p.revents = 0;
165
82
    pfds.push_back(p);
166
82
    regs.push_back(it.second);
167
82
  }
168
28
  if (!pfds.empty())
169
28
    (void)poll(pfds.data(), pfds.size(), 0);
170
110
  for (size_t i = 0; i < pfds.size(); ++i) {
171
82
    unsigned int st = MHD_FD_STATE_NONE;
172
    // A peer hang-up is reported as "readable" so that recv() returns 0.
173
82
    if (pfds[i].revents & (POLLIN | POLLHUP))
174
8
      st |= MHD_FD_STATE_RECV;
175
82
    if (pfds[i].revents & POLLOUT)
176
2
      st |= MHD_FD_STATE_SEND;
177
82
    if (pfds[i].revents & (POLLERR | POLLNVAL))
178
2
      st |= MHD_FD_STATE_EXCEPT;
179
82
    MHD_daemon_event_update(d, regs[i].ecb, static_cast<enum MHD_FdState>(st));
180
82
  }
181
28
  (void)MHD_daemon_process_reg_events(d, nullptr);
182
28
}
183
184
0
bool PathStartsWith(const struct MHD_String *path, const char *prefix) {
185
0
  const size_t plen = strlen(prefix);
186
0
  return path->len >= plen && 0 == memcmp(path->cstr, prefix, plen);
187
0
}
188
189
// ---- Request inspection: what a typical application reads from a request.
190
191
enum MHD_Bool ValueIter(void *, enum MHD_ValueKind,
192
0
                        const struct MHD_NameAndValue *nv) {
193
0
  TouchBytes(nv->name.cstr, nv->name.len);
194
0
  TouchBytes(nv->value.cstr, nv->value.len);
195
0
  return MHD_YES;
196
0
}
197
198
0
void InspectRequest(struct MHD_Request *request) {
199
0
  struct MHD_StringNullable v;
200
0
  (void)MHD_request_get_values_cb(
201
0
      request,
202
0
      static_cast<enum MHD_ValueKind>(MHD_VK_HEADER | MHD_VK_COOKIE |
203
0
                                      MHD_VK_URI_QUERY_PARAM),
204
0
      &ValueIter, nullptr);
205
0
  if (MHD_YES == MHD_request_get_value(request, MHD_VK_HEADER,
206
0
                                       MHD_HTTP_HEADER_HOST, &v))
207
0
    TouchBytes(v.cstr, v.len);
208
0
  if (MHD_YES == MHD_request_get_value(request, MHD_VK_HEADER,
209
0
                                       MHD_HTTP_HEADER_CONTENT_TYPE, &v))
210
0
    TouchBytes(v.cstr, v.len);
211
0
  if (MHD_YES == MHD_request_get_value(request, MHD_VK_COOKIE, "session", &v))
212
0
    TouchBytes(v.cstr, v.len);
213
0
  if (MHD_YES ==
214
0
      MHD_request_get_value(request, MHD_VK_URI_QUERY_PARAM, "q", &v))
215
0
    TouchBytes(v.cstr, v.len);
216
217
0
  if (g_fuzz_skip_h1_only_request_apis)
218
0
    return;
219
220
0
  union MHD_RequestInfoDynamicData dyn;
221
0
  static const enum MHD_RequestInfoDynamicType kDyn[] = {
222
0
      MHD_REQUEST_INFO_DYNAMIC_HTTP_METHOD_STRING,
223
0
      MHD_REQUEST_INFO_DYNAMIC_URI,
224
0
      MHD_REQUEST_INFO_DYNAMIC_NUMBER_URI_PARAMS,
225
0
      MHD_REQUEST_INFO_DYNAMIC_NUMBER_COOKIES,
226
0
      MHD_REQUEST_INFO_DYNAMIC_HEADER_SIZE,
227
0
      MHD_REQUEST_INFO_DYNAMIC_UPLOAD_PRESENT,
228
0
      MHD_REQUEST_INFO_DYNAMIC_UPLOAD_CHUNKED,
229
0
      MHD_REQUEST_INFO_DYNAMIC_UPLOAD_SIZE_TOTAL,
230
0
  };
231
0
  for (enum MHD_RequestInfoDynamicType t : kDyn)
232
0
    (void)MHD_request_get_info_dynamic(request, t, &dyn);
233
234
0
  union MHD_RequestInfoFixedData fix;
235
0
  (void)MHD_request_get_info_fixed(request, MHD_REQUEST_INFO_FIXED_HTTP_VER,
236
0
                                   &fix);
237
0
}
238
239
// ---- Responses
240
241
const struct MHD_Action *RespondText(struct MHD_Request *request,
242
                                     enum MHD_HTTP_StatusCode sc,
243
0
                                     const char *text) {
244
0
  struct MHD_Response *r =
245
0
      MHD_response_from_buffer_static(sc, strlen(text), text);
246
0
  if (r == nullptr)
247
0
    return MHD_action_abort_request(request);
248
0
  (void)MHD_response_add_header(r, MHD_HTTP_HEADER_CONTENT_TYPE,
249
0
                                "text/plain");
250
0
  (void)MHD_response_add_header(r, "X-Fuzz", "1");
251
0
  return MHD_action_from_response(request, r);
252
0
}
253
254
0
const struct MHD_UploadAction *UploadRespond(struct MHD_Request *request) {
255
0
  static const char kOk[] = "upload ok";
256
0
  struct MHD_Response *r = MHD_response_from_buffer_static(
257
0
      MHD_HTTP_STATUS_OK, sizeof(kOk) - 1, kOk);
258
0
  if (r == nullptr)
259
0
    return MHD_upload_action_abort_request(request);
260
0
  return MHD_upload_action_from_response(request, r);
261
0
}
262
263
const struct MHD_UploadAction *UploadFull(void *, struct MHD_Request *request,
264
0
                                          size_t size, void *data) {
265
0
  TouchBytes(static_cast<const char *>(data), size);
266
0
  return UploadRespond(request);
267
0
}
268
269
const struct MHD_UploadAction *UploadInc(void *, struct MHD_Request *request,
270
0
                                         size_t size, void *data) {
271
0
  if (size != 0) {
272
0
    TouchBytes(static_cast<const char *>(data), size);
273
0
    return MHD_upload_action_continue(request);
274
0
  }
275
0
  return UploadRespond(request);
276
0
}
277
278
const struct MHD_UploadAction *PostReader(
279
    struct MHD_Request *request, void *, const struct MHD_String *name,
280
    const struct MHD_StringNullable *filename,
281
    const struct MHD_StringNullable *content_type,
282
    const struct MHD_StringNullable *encoding, size_t size, const void *data,
283
0
    uint_fast64_t, enum MHD_Bool) {
284
0
  TouchBytes(name->cstr, name->len);
285
0
  TouchBytes(filename->cstr, filename->len);
286
0
  TouchBytes(content_type->cstr, content_type->len);
287
0
  TouchBytes(encoding->cstr, encoding->len);
288
0
  TouchBytes(static_cast<const char *>(data), size);
289
0
  return MHD_upload_action_continue(request);
290
0
}
291
292
const struct MHD_UploadAction *PostDone(struct MHD_Request *request, void *,
293
0
                                        enum MHD_PostParseResult) {
294
0
  return UploadRespond(request);
295
0
}
296
297
// Digest / Basic authentication, as done by a typical protected resource.
298
0
const struct MHD_Action *HandleAuth(struct MHD_Request *request) {
299
0
  union MHD_RequestInfoDynamicData dyn;
300
301
0
  if (MHD_SC_OK ==
302
0
      MHD_request_get_info_dynamic(
303
0
          request, MHD_REQUEST_INFO_DYNAMIC_AUTH_BASIC_CREDS, &dyn)) {
304
0
    const struct MHD_AuthBasicCreds *bc = dyn.v_auth_basic_creds;
305
0
    TouchBytes(bc->username.cstr, bc->username.len);
306
0
    TouchBytes(bc->password.cstr, bc->password.len);
307
0
    if (bc->username.len == strlen(FUZZ_USER) &&
308
0
        0 == memcmp(bc->username.cstr, FUZZ_USER, bc->username.len) &&
309
0
        bc->password.cstr != nullptr &&
310
0
        bc->password.len == strlen(FUZZ_PASS) &&
311
0
        0 == memcmp(bc->password.cstr, FUZZ_PASS, bc->password.len))
312
0
      return RespondText(request, MHD_HTTP_STATUS_OK, "basic ok");
313
0
  }
314
315
0
  bool stale = false;
316
0
  if (MHD_SC_OK ==
317
0
      MHD_request_get_info_dynamic(
318
0
          request, MHD_REQUEST_INFO_DYNAMIC_AUTH_DIGEST_INFO, &dyn)) {
319
0
    const struct MHD_AuthDigestInfo *di = dyn.v_auth_digest_info;
320
0
    TouchBytes(di->username.cstr, di->username.len);
321
0
    TouchBytes(di->realm.cstr, di->realm.len);
322
0
    TouchBytes(di->opaque.cstr, di->opaque.len);
323
0
    TouchBytes(di->userhash_hex.cstr, di->userhash_hex.len);
324
0
    TouchBytes(reinterpret_cast<const char *>(di->userhash_bin),
325
0
               di->userhash_bin_size);
326
327
0
    enum MHD_DigestAuthResult res = MHD_digest_auth_check(
328
0
        request, FUZZ_REALM, FUZZ_USER, FUZZ_PASS, 0,
329
0
        MHD_DIGEST_AUTH_MULT_QOP_ANY_NON_INT, MHD_DIGEST_AUTH_MULT_ALGO_ANY);
330
0
    if (MHD_DAUTH_OK == res)
331
0
      return RespondText(request, MHD_HTTP_STATUS_OK, "digest ok");
332
0
    stale = (MHD_DAUTH_NONCE_STALE == res);
333
334
    // Same check through the pre-computed "userdigest" API (SHA-256).
335
0
    uint8_t ud[MHD_SHA256_DIGEST_SIZE];
336
0
    if (MHD_SC_OK == MHD_digest_auth_calc_userdigest(
337
0
                         MHD_DIGEST_AUTH_ALGO_SHA256, FUZZ_USER, FUZZ_REALM,
338
0
                         FUZZ_PASS, sizeof(ud), ud)) {
339
0
      if (MHD_DAUTH_OK ==
340
0
          MHD_digest_auth_check_digest(
341
0
              request, FUZZ_REALM, FUZZ_USER, sizeof(ud), ud, 0,
342
0
              MHD_DIGEST_AUTH_MULT_QOP_AUTH_ANY,
343
0
              MHD_DIGEST_AUTH_MULT_ALGO_SHA256_ANY))
344
0
        return RespondText(request, MHD_HTTP_STATUS_OK, "digest ok");
345
0
    }
346
0
  }
347
348
0
  static const char kDenied[] = "denied";
349
0
  struct MHD_Response *r = MHD_response_from_buffer_static(
350
0
      MHD_HTTP_STATUS_UNAUTHORIZED, sizeof(kDenied) - 1, kDenied);
351
0
  if (r == nullptr)
352
0
    return MHD_action_abort_request(request);
353
0
  (void)MHD_response_add_auth_basic_challenge(r, FUZZ_REALM, MHD_YES);
354
0
  return MHD_action_digest_auth_challenge(
355
0
      request, FUZZ_REALM, "fuzzopaque", "/", stale ? MHD_YES : MHD_NO,
356
0
      MHD_DIGEST_AUTH_MULT_QOP_AUTH, MHD_DIGEST_AUTH_MULT_ALGO_ANY_NON_SESSION,
357
0
      MHD_YES, MHD_YES, r, MHD_NO);
358
0
}
359
360
// The application.  Behaviour is selected by the (attacker supplied) path,
361
// as real applications route on the path.
362
const struct MHD_Action *RequestCb(void *, struct MHD_Request *request,
363
                                   const struct MHD_String *path,
364
                                   enum MHD_HTTP_Method method,
365
0
                                   uint_fast64_t) {
366
0
  InspectRequest(request);
367
368
0
  if (method == MHD_HTTP_METHOD_POST || method == MHD_HTTP_METHOD_PUT) {
369
0
    if (PathStartsWith(path, "/form"))
370
0
      return MHD_action_parse_post(request, 512, 256,
371
0
                                   MHD_HTTP_POST_ENCODING_OTHER, &PostReader,
372
0
                                   nullptr, &PostDone, nullptr);
373
0
    if (PathStartsWith(path, "/inc"))
374
0
      return MHD_action_process_upload(request, 0, nullptr, nullptr,
375
0
                                       &UploadInc, nullptr);
376
0
    return MHD_action_process_upload(request, 1024, &UploadFull, nullptr,
377
0
                                     &UploadInc, nullptr);
378
0
  }
379
0
  if (PathStartsWith(path, "/auth") && !g_fuzz_skip_h1_only_request_apis)
380
0
    return HandleAuth(request);
381
0
  return RespondText(request, MHD_HTTP_STATUS_OK, "hello");
382
0
}
383
384
2
struct MHD_Daemon *fuzz_get_daemon() {
385
2
  if (g_daemon_tried)
386
1
    return g_daemon;
387
1
  g_daemon_tried = true;
388
389
1
  signal(SIGPIPE, SIG_IGN);
390
391
  // Listen on 127.0.0.1 with a kernel-assigned port (unique per fuzzing
392
  // process, so parallel jobs do not collide).  The socket is created here
393
  // and handed to MHD; MHD accept()s the client connections itself.
394
  // (MHD_daemon_add_connection() cannot be used: externally added sockets
395
  // are rejected with MHD_SC_FEATURE_DISABLED by the current library.)
396
1
  int lfd = socket(AF_INET, SOCK_STREAM, 0);
397
1
  if (lfd < 0)
398
0
    return nullptr;
399
1
  memset(&g_listen_addr, 0, sizeof(g_listen_addr));
400
1
  g_listen_addr.sin_family = AF_INET;
401
1
  g_listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
402
1
  g_listen_addr.sin_port = 0;
403
1
  socklen_t alen = sizeof(g_listen_addr);
404
1
  if (0 != bind(lfd, reinterpret_cast<struct sockaddr *>(&g_listen_addr),
405
1
                sizeof(g_listen_addr)) ||
406
1
      0 != listen(lfd, 64) ||
407
1
      0 != getsockname(lfd, reinterpret_cast<struct sockaddr *>(&g_listen_addr),
408
1
                       &alen)) {
409
0
    close(lfd);
410
0
    return nullptr;
411
0
  }
412
413
1
  struct MHD_Daemon *d = MHD_daemon_create(&RequestCb, nullptr);
414
1
  if (d == nullptr) {
415
0
    close(lfd);
416
0
    return nullptr;
417
0
  }
418
419
  // Fixed entropy: nonces are derived deterministically from it.
420
1
  static uint8_t entropy[32];
421
33
  for (size_t i = 0; i < sizeof(entropy); ++i)
422
32
    entropy[i] = static_cast<uint8_t>(0x5A ^ (i * 31));
423
424
1
  if (MHD_SC_OK !=
425
1
          MHD_DAEMON_SET_OPTIONS(
426
1
              d,
427
1
              MHD_D_OPTION_WM_EXTERNAL_EVENT_LOOP_CB_LEVEL(&SocketRegCb,
428
1
                                                           nullptr),
429
1
              MHD_D_OPTION_LISTEN_SOCKET(lfd),
430
1
              MHD_D_OPTION_LOG_CALLBACK(&SilentLog, nullptr),
431
1
              MHD_D_OPTION_RANDOM_ENTROPY(sizeof(entropy), entropy),
432
1
              MHD_D_OPTION_SUPPRESS_DATE_HEADER(MHD_YES),
433
1
              MHD_D_OPTION_AUTH_DIGEST_NONCE_TIMEOUT(3600),
434
1
              MHD_D_OPTION_CONN_MEMORY_LIMIT(32 * 1024)) ||
435
1
      MHD_SC_OK != MHD_daemon_start(d)) {
436
0
    MHD_daemon_destroy(d);
437
0
    return nullptr;
438
0
  }
439
1
  g_daemon = d;
440
1
  return g_daemon;
441
1
}
442
443
2
FuzzClient::FuzzClient(struct MHD_Daemon *d) : d_(d), fd_(-1) {
444
2
  int fd = socket(AF_INET, SOCK_STREAM, 0);
445
2
  if (fd < 0)
446
0
    return;
447
  // Loopback connect() completes immediately (the kernel finishes the
448
  // handshake; MHD accept()s from the backlog below).
449
2
  if (0 != connect(fd, reinterpret_cast<struct sockaddr *>(&g_listen_addr),
450
2
                   sizeof(g_listen_addr))) {
451
0
    close(fd);
452
0
    return;
453
0
  }
454
2
  int one = 1;
455
2
  (void)setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one));
456
2
  int fl = fcntl(fd, F_GETFL);
457
2
  fcntl(fd, F_SETFL, fl | O_NONBLOCK);
458
2
  fd_ = fd;
459
  // Let MHD accept() the new connection.
460
2
  for (unsigned i = 0; i < 16; ++i) {
461
2
    RunEventLoopOnce(d_);
462
2
    union MHD_DaemonInfoDynamicData info;
463
2
    if (MHD_SC_OK == MHD_daemon_get_info_dynamic(
464
2
                         d_, MHD_DAEMON_INFO_DYNAMIC_HAS_CONNECTIONS, &info) &&
465
2
        MHD_YES == info.v_has_connections_bool)
466
2
      break;
467
2
  }
468
2
}
469
470
2
FuzzClient::~FuzzClient() { Close(); }
471
472
24
void FuzzClient::Drain() {
473
24
  if (fd_ < 0)
474
0
    return;
475
24
  char buf[4096];
476
26
  for (;;) {
477
26
    ssize_t n = recv(fd_, buf, sizeof(buf), 0);
478
26
    if (n <= 0)
479
24
      break;
480
    // Bound memory use: only the beginning of the output is of interest.
481
2
    if (resp_.size() < 65536)
482
2
      resp_.append(buf, static_cast<size_t>(n));
483
2
  }
484
24
}
485
486
10
void FuzzClient::Pump(unsigned rounds) {
487
34
  for (unsigned i = 0; i < rounds; ++i) {
488
24
    RunEventLoopOnce(d_);
489
24
    Drain();
490
24
  }
491
10
}
492
493
4
void FuzzClient::Send(const uint8_t *data, size_t size) {
494
4
  if (fd_ < 0)
495
0
    return;
496
4
  size_t off = 0;
497
4
  unsigned stalls = 0;
498
8
  while (off < size && stalls < 64) {
499
4
    ssize_t n = send(fd_, data + off, size - off, MSG_NOSIGNAL);
500
4
    if (n > 0) {
501
4
      off += static_cast<size_t>(n);
502
4
      stalls = 0;
503
4
    } else if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK &&
504
0
               errno != EINTR) {
505
0
      break;  // Server closed the connection.
506
0
    } else {
507
0
      ++stalls;
508
0
    }
509
4
    Pump(1);
510
4
  }
511
4
  Pump(4);
512
4
}
513
514
4
void FuzzClient::Close() {
515
4
  if (fd_ < 0)
516
2
    return;
517
2
  Pump(2);
518
  // Abortive close (RST).  Besides avoiding TIME_WAIT port exhaustion, this
519
  // is required for HTTP/2: MHD currently ignores a plain peer EOF on HTTP/2
520
  // connections (upstream bug), while a reset is
521
  // reported as a hard socket error and the connection is cleaned up.
522
2
  struct linger lg;
523
2
  lg.l_onoff = 1;
524
2
  lg.l_linger = 0;
525
2
  (void)setsockopt(fd_, SOL_SOCKET, SO_LINGER, &lg, sizeof(lg));
526
2
  close(fd_);
527
2
  fd_ = -1;
528
  // Let MHD notice the EOF and clean the connection up, so that no state is
529
  // carried over to the next fuzz iteration.
530
2
  for (unsigned i = 0; i < 64; ++i) {
531
2
    RunEventLoopOnce(d_);
532
2
    union MHD_DaemonInfoDynamicData info;
533
2
    if (MHD_SC_OK == MHD_daemon_get_info_dynamic(
534
2
                         d_, MHD_DAEMON_INFO_DYNAMIC_HAS_CONNECTIONS, &info) &&
535
2
        MHD_NO == info.v_has_connections_bool)
536
2
      break;
537
2
  }
538
2
}
539
540
}  // namespace
541
542
static const uint8_t kPreface[] = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
543
544
2
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
545
2
  struct MHD_Daemon *d = fuzz_get_daemon();
546
2
  if (d == nullptr)
547
0
    return 0;
548
549
2
  FuzzClient client(d);
550
2
  if (!client.ok())
551
0
    return 0;
552
2
  client.Send(kPreface, sizeof(kPreface) - 1);
553
2
  if (size != 0)
554
2
    client.Send(data, size);
555
2
  client.Close();
556
2
  return 0;
557
2
}