1
0

sse_parser_fuzzer.cc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #include <algorithm>
  2. #include <cstdint>
  3. #include <cstdlib>
  4. #include <string>
  5. #include <httplib.h>
  6. namespace {
  7. // Feeds the stream in chunks and records every handler call in order
  8. std::string parse_in_chunks(const std::string &stream, size_t chunk,
  9. size_t max_event_length) {
  10. std::string trace;
  11. httplib::detail::SSEParser parser(
  12. [&](const httplib::sse::SSEMessage &msg) {
  13. trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  14. },
  15. [&](const std::string &id) { trace += "id[" + id + "]"; },
  16. [&](int retry_ms) { trace += "retry[" + std::to_string(retry_ms) + "]"; },
  17. max_event_length);
  18. for (size_t off = 0; off < stream.size(); off += chunk) {
  19. if (!parser.parse(stream.data() + off,
  20. std::min(chunk, stream.size() - off))) {
  21. break;
  22. }
  23. }
  24. return trace;
  25. }
  26. } // namespace
  27. extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
  28. if (size < 2 || size > 65536) { return 0; }
  29. // First byte selects the chunk size, the rest is the event stream
  30. auto chunk = static_cast<size_t>(data[0]) + 1;
  31. std::string stream(reinterpret_cast<const char *>(data + 1), size - 1);
  32. // Without a length limit, chunking must not change what is reported
  33. auto whole = parse_in_chunks(stream, stream.size(), 0);
  34. auto chunked = parse_in_chunks(stream, chunk, 0);
  35. if (whole != chunked) { std::abort(); }
  36. // With a limit, only check that the parser stops cleanly
  37. parse_in_chunks(stream, chunk, 64);
  38. return 0;
  39. }