Compare commits

..
14 Commits
Author SHA1 Message Date
Brad Arant 78c45d378c Fix File stat-before-open crash risk, JSON string-quoting bug, and MString buffer overflow
- File: stat() only after a successful open() (previously ran first with
  its result ignored, feeding a missing file's garbage st_size into a
  realloc - could crash the whole APIServer on a request for a
  nonexistent static asset)
- JString::setString(): always quote+escape the value instead of going
  through set()'s literal-value guess, which misclassified any string
  starting with digits (e.g. a UUID) as a bare numeric literal and wrote
  it unquoted, corrupting later edits to the same JSON document
- MString::remove() (both overloads): fixed an off-by-one that read one
  byte past the buffer on a completely full string (found via ASan under
  concurrent load)
- CGIFormData: added fields() so callers can iterate every parsed field
  without knowing names in advance (used to merge POST body into
  jet::Global::variables the same way query-string params already are)
2026-09-03 05:14:24 +00:00
Brad Arant d7057ebb00 Fix JFile to normalize whitespace when loading JSON from disk
JString::operator=(ZString) already stripped whitespace between JSON
structural tokens before parsing, but JFile constructed via MFile file-
loading bypassed that path entirely, so any pretty-printed/hand-edited
JSON file silently failed every locate()/exists()/get*() call. Widen
removeWhitespace() to protected and call it from JFile constructor.
2026-08-25 19:14:14 -07:00
Brad ArantandClaude Sonnet 5 6b188fbee5 Restore execute bit on testing/compile (lost via UNC-path edit)
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 10:42:48 -07:00
Brad ArantandClaude Sonnet 5 cb845efe69 Add HTTPRequest/HTTPResponse: real HTTP parsing on the Parser/StreamReader stack
Stage 2 of the APIServer plan. This codebase has only ever sat behind a
CGI gateway - IMFRequest/IMFResponse/IMFMessage predate the
StreamReader/Parser rebuild and are stubs (IMFResponse's header-emission
calls addHeader()/output(), neither of which exist on the class;
IMFRequest is a fragile non-resumable 3-token line split). Nothing in
this repo has ever actually parsed a raw HTTP request off a socket.

HTTPRequest : public Parser fills that gap the same way every other
Parser here is built: REQUEST_LINE -> HEADERS -> BODY -> DONE, chaining
LineParser (request line) and IMFHeader (headers, reused as-is - HTTP
header syntax is IMF-derived, nothing email-specific in IMFHeader
itself) via checkParse() over one shared StreamReader, exactly the
pattern CGIFormData already established for chaining IMFHeader/
IMFBoundary. The BODY state dispatches on Content-Type as CGIFormData
itself does for CGI bodies - application/x-www-form-urlencoded and
multipart/form-data delegate directly to CGIFormData (reused, not
reimplemented), anything else is captured as a raw body (e.g. JSON).
Query string is split off the path before anything else sees it.
getHeader() does a case-insensitive lookup (HTTP header names are
case-insensitive per RFC 7230, unlike IMFHeader's own std::map, which
compares byte-for-byte) since a route handler constantly needs this and
getting it wrong would be a silent framing bug, not a cosmetic one.

The boundary-extraction code mirrors __jet.cpp's own fix exactly (same
cursor-mutation trap: ZString::find() leaves the searched string's
cursor at the match, and CGIFormData's constructor copy-constructs its
own contentType member from whatever's passed in, inheriting that same
moved cursor unless reset() first - would otherwise silently miss its
own startsWith() dispatch checks).

HTTPResponse is a small, new, output-only builder (status line + a real
headers container + body, Content-Length auto-computed unless set
explicitly) - deliberately not patched from IMFResponse, which has
nothing safe to extend.

v1 limitations, flagged not fixed (matching the standard already set by
other Parser subclasses here for known-but-out-of-scope gaps): chunked
Transfer-Encoding isn't supported, and repeated header names last-wins
(inherited from IMFHeader's own std::map).

Verified live via testing/http_test.cpp (34 assertions, new - now wired
into testing/compile): byte-at-a-time GET with a query string and
case-insensitive header lookup; a GET with no query string; a POST with
an urlencoded body deliberately split mid-body (not just mid-header)
across two feed() calls, confirming the CGIFormData delegation resumes
correctly; a raw JSON POST body; testing/http_request.data (a real
fixture, previously unused - normalized from its stored LF line endings
to real CRLF, since HTTP requires CRLF and IMFHeader enforces that
strictly) fed byte-at-a-time; and HTTPResponse::serialize() both with an
auto-computed and an explicitly-set Content-Length (no duplicate
header). Also reran the full existing testing/compile suite
(zstring/mstring/jstring/mfile/jfile) against the rebuilt libCoreUtils.a
to confirm no regression from the two new files.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 10:42:34 -07:00
Brad ArantandClaude Sonnet 5 6e4e463a96 Fix MString assignment operators leaving cursor at its old (stale) offset
operator=(MString)/operator=(ZString)/operator=(std::string)/operator=(const
char*)/operator=(char) all replaced the buffer's content via setSize()+
memcpy() but never reset cursor back to the start - setSize() preserves
the *offset* the cursor was already at (correct for its own use, growing
a buffer while keeping a read position stable), so a full content
replacement left the cursor sitting at whatever offset it had into the
*previous* content, not the new content. operator=(double)/operator=(int)
already did `cursor = data;` after the same setSize()+memcpy() pattern,
confirming this was the intended behavior everywhere - just missing from
the other five overloads.

This is invisible to JetCore's interpreter, which never reassigns an
already-read-from MString (each tag is a freshly parsed C++ object every
time its container is scanned, so a keyword's MString is never both read
and then reassigned on the same instance). It surfaced in a prototype JET
compiler (JetCore/jetc) built this session, which intentionally reuses
one persistent keyword slot across loop iterations instead of
reconstructing everything from text every pass - exactly the case this
bug needed. A <while expr="..."> loop reusing a slot for its condition
worked for two iterations (matching a decoy pattern: the second
assignment happened to land the stale cursor at the exact end of the
new, same-length content) and threw "operand is not valid" on the third,
since a keyword reassigned inside the loop body left the cursor already
at eod() from the read.

Verified via jstring_test/mstring_test/zstring_test/parser_test (no
regressions), JetCore's tests/posttest.sh and the two-process JSON
session persistence test (no regressions), and the jetc prototype's two
demo templates - both now produce byte-identical output to jet-2.0's
interpreter, including a <while> loop that mutates and rereads the same
keyword slot every iteration.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:18:17 -07:00
Brad ArantandClaude Sonnet 5 3e6e410fe8 Fix JFile empty-document seed and MString's ZString-source pointer/length mismatch
JFile.cpp: JFile and MFile both "virtual public MString" a single shared
base, so a virtual base is initialized only by the *most derived* class's
constructor. JFile's own constructor never mentions MString, so
JString's own "{}" default initializer never ran - a JFile backed by a
new or nonexistent file started as a raw empty string instead of a valid
empty JSON object. Every subsequent locate()/set() call then silently
misbehaved (no leading "{" for ifNext("{") to match, so writes landed at
offset 0 with no braces or separators - fields ended up prepended in
reverse order, concatenated with no delimiters at all). Fixed by seeding
"{}" via append (matching MFile's own load pattern) whenever the loaded
content is empty.

MString.cpp: several ZString-source copy paths (the ZString/MString copy
constructors, both assignment operators, operator<<(ZString), insert(),
write()) called zstring.getData() (the object's absolute start) paired
with zstring.getLength() (which is documented/implemented as "remaining
bytes from cursor to end", i.e. length - (cursor - data)). Pairing an
absolute start with a cursor-relative length silently corrupts any
cursor-advanced source: the copy starts from the wrong (too-early)
position but is truncated by exactly the amount the cursor had already
advanced, keeping unwanted leading bytes while dropping trailing ones.
Found via the CGIFormData-style resumability testing pattern used
elsewhere this session, triggered by JetCore's new "@name" session
variable feature stripping a sigil prefix via ifNext() before streaming
the remainder into an MString. Fixed by pairing zstring.getCursor()
(cursor-relative start) with zstring.getLength() consistently everywhere
this pattern appeared.

Verified via the existing jstring_test/mstring_test/zstring_test/
parser_test suites (all pass, no output changes) plus a new isolated
JFile round-trip test proving persistence across two separate process
instances sharing one file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 18:44:59 -07:00
Brad ArantandClaude Sonnet 5 5b6d4ea8ab Fix ambiguous MString << JString::Proxy overload resolution
JString::Proxy offers several implicit conversion operators (ZString,
MString, std::string, double, bool) so a single $[...]-style access can
be used wherever any of those types is expected. That flexibility made
"MString << Proxy" genuinely ambiguous: operator ZString() and
operator MString() (via its own implicit upcast to ZString) both satisfy
MString::operator<<(ZString), and operator double()/operator bool() both
satisfy MString::operator<<(int) via a standard numeric conversion, so
the compiler had no basis to prefer one conversion path over another.

Fixed the same way Proxy already solves this exact problem for
std::cout << proxy - a dedicated friend operator<<(MString&, const
Proxy&) that needs no conversion at all, so it's always the preferred
candidate. Verified by actually running testing/jstring_test.cpp (not
just compiling it) - the line that used to fail to compile now correctly
prints "this is a test: this is a comment".

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 15:11:56 -07:00
Brad ArantandClaude Sonnet 5 bf6810b781 Rebuild CGIFormData on Parser/StreamReader, fix a 2-byte-lookahead bug
CGIFormData now inherits Parser instead of MString and parses a CGI
request body (urlencoded or multipart/form-data) resumably against the
shared StreamReader, exposing the result via operator[] - matching every
other Parser in this redesign. multipart/form-data reuses IMFBoundary and
IMFHeader via checkParse() (chained through the same StreamReader) for
each part's boundary line and header block; urlencoded bodies wait for
the full Content-Length before delegating to the existing
CGIFormattedData parser. File-upload parts (Content-Disposition with a
filename= parameter) are recognized and skipped, matching this
codebase's convention that uploads get a separate mechanism.

Values are stored under an indexed "name:N" key (N = 0-based occurrence
count for that name), matching the :N-suffix convention JetCore's
Tag::getVariable already applies to its $[:name] CGI variable syntax
(defaulting to :0) - this also naturally supports repeated field names
(checkboxes, multi-select). operator[] applies the same :0 default so a
bare name still works when called directly, not just through that
convention layer.

Two real resumability bugs found and fixed via a byte-at-a-time test
(feeding one byte per StreamReader::feed() call, the harshest possible
fragmentation):
- CGIFormData's opening boundary marker ("--boundary", no leading CRLF
  per RFC 2046 for the first boundary) crammed "find+consume the marker"
  and "disambiguate -- vs CRLF" into one state; when the disambiguation
  needed more data, INCOMPLETE was returned without recording that the
  marker was already consumed, so retrying re-searched for it past where
  it had already been consumed, silently skipping content forever. Split
  into two states (INIT / OPENING_TAIL), the same fix already applied
  once to IMFBoundary's PREFIX/TAIL split.
- IMFHeader's FIELD state checked eod() (a 1-byte availability check)
  immediately before an ifNext("\r\n") call that needs 2 bytes - a lone
  trailing \r with no \n yet available was wrongly treated as malformed
  instead of "wait for more data". Fixed to check getLength() < 2.

Verified via a dedicated test (64 assertions total across this and the
earlier Parser/StreamReader test) covering urlencoded, multipart with a
skipped file upload, and the byte-at-a-time stress case - plus a real
end-to-end run through jet-2.0 with a simulated CGI multipart POST
request (see the matching JetCore commit).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 15:07:09 -07:00
Brad ArantandClaude Sonnet 5 a033cc6718 Add StreamReader and rebuild Parser/LineParser/IMFHeader/IMFBoundary on it
Introduces StreamReader to accumulate socket data delivered in arbitrary
chunks into one buffer, so a Parser can build an object (a line, a header
block, a MIME boundary) that spans any number of packets without losing
its place. Parser is redesigned around this: no longer inherits MString
(was redundant with its own buffer member), takes a StreamReader&, and
drives a resumable COMPLETE/INCOMPLETE/DATA_AVAIL state-machine protocol
via doParse(). LineParser, IMFHeader, and IMFBoundary are rewritten as
real, working resumable parsers against the shared buffer instead of the
previous non-compiling stubs (mismatched constructors/return types, a
syntax error, checkParse() never implemented).

IMFFormData is left as the stub it already was, just restored to
compiling against the new IMFHeader signature - fully wiring it up needs
IMFMultipart/IMFText migrated to StreamReader too, out of scope here.

Verified with real runtime tests (not just compilation) covering data
split mid-line, mid-CRLF, mid-header-fold, and mid-boundary-marker across
separate feed() calls, plus StreamReader::compact(). Along the way fixed
a header-value bug (space after ':' wasn't skipped) and a double
cursor-offset subtraction bug in two places caused by forgetting that
ZString::getLength() is already cursor-relative, not the raw buffer size.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 14:25:58 -07:00
Brad ArantandClaude Sonnet 5 94d4a30e88 Fix CGI form/cookie data handling and CGI URL encode/decode
- CGIFormData: fix broken setSize()+read() double-length bug that
  corrupted every parsed body with a leading run of garbage bytes
  (setSize(contentLength) pre-set length before read()/write()
  appended on top of it); switch content-type checks from exact
  equality to startsWith() since a real multipart Content-Type
  always carries a boundary= parameter; implement the previously
  empty multipart/form-data branch (ordinary fields only, file
  uploads deferred to a separate upload mechanism per TODO.txt);
  restore operator[] real lookup logic (was hardcoded to echo the
  key back); default-initialize formdata to NULL; fix mismatched
  include guard (leftover from an IMFFormData.h copy-paste); drop
  the unused IMFHeader.h include that pulled in a broken,
  unrelated StreamReader.h dependency.
- CGIFormattedData: parameterize the split delimiter (was hardcoded
  to &, which silently broke cookie parsing since HTTP_COOKIE uses
  ; not &) and trim whitespace on each split token.
- MString::toCGI()/fromCGI(): were unimplemented stubs (always
  returned an empty string); implemented proper CGI percent-encode
  / percent-decode + space plus-encoding, and fixed the one caller
  that discarded fromCGIs return value instead of using it.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-22 21:37:10 -07:00
Brad Arant 28feaff3d7 Rewrite JString for real JSON compliance
The previous implementation was a narrow path-accessor, not a JSON parser:
numbers/booleans/null were unhandled entirely (self-acknowledged by a
// TODO: Handle numbers... comment), string escape sequences were never
encoded or decoded, updating an existing non-string-valued key threw a
hard-coded Fix me exception, and skipping past an uninteresting key threw
Unrecognized data type for anything but string/array/object. Full
analysis given to the user before this rewrite; nothing here was guessed.

Added:
- JSONType enum + getType()/exists()/isNull() for type introspection.
- Typed read access: getString() (escape-decoded), getNumber(), getInt(),
  getBool() - each validates the value at the path is actually that type.
- Typed write access: setString() (escapes automatically), setNumber(),
  setInt(), setBool(), setNull() - and Proxy operator= overloads for
  double/int/long/bool so  produces a real JSON number, not
  a quoted string the way the old single MString-typed operator= did.
- jsonEscape()/jsonUnescape(): full escape codec including \uXXXX and
  UTF-16 surrogate pairs (astral characters, e.g. emoji) decoded to
  correct UTF-8.
- skipValue()/skipString()/skipContainer()/skipNumber() and their
  capture (span-returning) counterparts: escape-aware structural
  skipping, so a string value containing a literal { } [ ] , or : can
  no longer desync object/array nesting depth - this affected both
  locate()s internal key-skipping and find()s array/object extraction
  (the latter still relied on the base ZString::getContainer(), which
  has this exact bug and was not touched - see the ZString commit in
  this same session - so a JString-specific escape-aware capture was
  added instead of depending on it for this purpose).
- set() rewritten to use skipValue() to correctly locate and replace an
  EXISTING values full span regardless of its current type, instead of
  only handling the case where the existing value was already a quoted
  string.

Bugs found and fixed along the way, surfaced by writing real tests
against realistic JSON rather than just getting it to compile:
- The array-index-then-further-path case (e.g. b[2].c) always returned
  true immediately after reaching the index, so any path segment past
  the index was silently ignored - dead code after an unconditional
  return/throw meant the intended continuation logic could never run.
- The array selector syntax (label[key=value]) was only reachable as a
  top-level special case, never as part of a normal nested path (e.g.
  items[id=x].val) - unified both under the same bracket handling.
- Once reachable, the selector-match subkey check (find(key) on each
  array element) always searched from the document root, not the
  current array element, because find() unconditionally calls reset().
  Split into public find() (resets) and internal findRelative() (does
  not), and pointed both selector-matching call sites at the latter.
- path[0].getTokenExclude(...) in the array-selector path parser
  indexed into a list vector that split() never populated - undefined
  behavior. Removed the erroneous [0].

Verified via a dedicated test program (not included in this commit)
covering: string escape round-trip, numbers, booleans, null, exists(),
\uXXXX including a real surrogate pair decoded to correct 4-byte UTF-8,
nested dotted+bracketed navigation, a string value containing every
structural JSON character, replacing an existing key with a different
type, multi-key documents, pretty() not corrupting structural characters
inside a string, and the array selector syntax on both a matching first
and second element - 30/30 assertions pass. Full CoreUtils compile pass
unchanged apart from JString.cpp itself now succeeding (14/20 clean, same
7 pre-existing StreamReader.h-blocked failures as always, nothing new
broken).
2026-08-22 20:53:54 -07:00
Brad Arant 14697e2af2 Fix three real bugs found during a full ZString review
operator< computed end2 as valuex.getData() + valuex.getLength() - mixing
an absolute pointer (getData(), the buffer start) with a cursor-relative
length (getLength(), remaining-from-cursor). For any ZString with a
non-zero cursor offset this produces an end pointer short of the true
buffer end by exactly the amount already consumed, truncating the
comparison early. Fixed to use valuex.data + valuex.length (the true
end), matching how end1 was already computed for *this. operator<=,
>=, and > were separately broken (flagged by the codes own TODO
comment) - they compared via strncmp from data (ignoring cursor
entirely), inconsistent with operator< and with each other. Replaced
all three with derivations from the now-correct operator< (a <= b is
!(b < a), etc.) - guarantees trichotomy by construction instead of
three independently-written comparison loops.

substring(start, len): when the requested length overran the buffer,
computed newlen as endChar - end (the overrun amount) instead of
end - startChar (the actual remaining valid length) - backwards, and
stored into a char (max 127), silently wrapping for longer strings.
Fixed the formula and widened to size_t.

trimCRLF(): read *(data + length - 1) unconditionally, including when
length is already 0 - one byte before the buffer on an empty string.
Guarded both checks on length > 0.

Verified: full local compile (identical result to before - 13/20 clean,
same pre-existing StreamReader.h-blocked failures, nothing new broken);
a dedicated runtime test exercising all three fixes plus a trichotomy
check across multiple cursor offsets - all 13 assertions pass. Test
file not included in this commit.
2026-08-22 20:11:13 -07:00
Brad Arant 4082e82466 Fix Exception default file/line always reporting Exception.h itself
__FILE__/__LINE__ are preprocessor macros - as default argument values
in the header they expand once, at the header declaration site, not at
each call site. Every throw relying on the defaults (all but File.cpp,
which passed them explicitly) reported Exception.h itself instead of
the real error location.

Switched the defaults to std::source_location::current(), which the
C++20 standard specifically defines to evaluate at the call site when
used as a default argument - unlike macros. Kept the same 4-parameter
signature so every existing call site, including ones that pass
__FILE__/__LINE__ explicitly, is unaffected.

Verified two ways: full-repo compile pass (identical result to before,
13/20 clean, same pre-existing StreamReader.h-blocked failures, nothing
new broken); a real runtime test - a throw relying on defaults from a
known line correctly reported that exact file/line via the caught
exceptions .file/.line members. Test file not included in this commit.
2026-08-22 19:52:44 -07:00
Brad Arant 29c9a5b855 Fix MString::fromHex() silently swallowing the odd-length-input error
The Exception on the odd-length-input path was constructed but never
thrown (missing throw keyword) - the temporary was destroyed with no
effect, so execution fell through to an out-of-bounds nextChar() read
past the exhausted buffer instead of raising an error. Added the
missing throw.

Verified via full local compile: MString.cpp builds clean standalone;
a full-repo pass shows only the pre-existing, already-known
StreamReader.h-missing failures (7 files, unrelated to this change),
confirmed via each error log individually.
2026-08-22 19:52:35 -07:00
35 changed files with 1973 additions and 243 deletions

No files matched your search

+1
View File
@@ -9,3 +9,4 @@ build/
.history/
testing/mstring_test
testing/zstring_test
testing/http_test
+155 -15
View File
@@ -1,28 +1,168 @@
#include "CGIFormData.h"
#include "IMFHeader.h"
#include "malloc.h"
#include "CGIFormattedData.h"
#include "Exception.h"
namespace coreutils {
CGIFormData::CGIFormData(int fd, ZString contentType, int contentLength, ZString boundary)
: contentType(contentType) {
if(contentType == "application/x-www-form-urlencoded") {
setSize(contentLength);
read(fd, contentLength);
formdata = new CGIFormattedData(*this);
} else if(contentType == "multipart/form-data") {
CGIFormData::CGIFormData(StreamReader &reader, ZString contentType, int contentLength, ZString boundary)
: Parser(reader), contentType(contentType), contentLength(contentLength), boundary(boundary) {
if (contentType.startsWith("application/x-www-form-urlencoded"))
mode = URLENCODED;
else if (contentType.startsWith("multipart/form-data"))
mode = MULTIPART;
else
mode = UNKNOWN;
}
CGIFormData::~CGIFormData() {
delete headerParser;
delete boundaryParser;
}
void CGIFormData::extractPartName(IMFHeader &header) {
auto &fields = header.getHeaders();
MString disposition = fields[MString("Content-Disposition")];
ZString dz(disposition.getData(), disposition.getLength());
currentSkip = (dz.find(ZString("filename=\"")) != -1);
int namePos = dz.find(ZString("name=\""));
if (namePos != -1) {
ZString afterName = dz.substring(namePos + 6);
int nameEnd = afterName.find(ZString("\""));
if (nameEnd != -1)
currentName = MString(afterName.substring(0, nameEnd));
}
}
Parser::Status CGIFormData::parse() {
MString &buffer = reader.getBuffer();
if (mode == UNKNOWN) {
state = DONE;
return Status::COMPLETE;
}
switch (state) {
case INIT:
if (mode == URLENCODED) {
state = URLENCODED_BODY;
return Status::DATA_AVAIL;
}
// MULTIPART: the very first boundary line has no leading CRLF
// (RFC 2046) - handled here directly rather than via IMFBoundary,
// which always expects the CRLF that terminates a PRECEDING part.
// Split into two states (find+consume the marker, then separately
// disambiguate -- vs CRLF) so that if the marker is consumed but
// there isn't yet enough data to tell -- from CRLF, retrying does
// not re-search for (and skip past) a marker that is already
// behind the cursor - the exact bug class already fixed once in
// IMFBoundary's PREFIX/TAIL split.
{
MString marker;
marker << "--";
marker << boundary;
int pos = buffer.find(marker);
if (pos < 0)
return Status::INCOMPLETE;
if (!buffer.ifNext(marker))
throw coreutils::Exception("CGIFormData: opening boundary vanished between find and ifNext.");
state = OPENING_TAIL;
return Status::DATA_AVAIL;
}
case OPENING_TAIL:
if (buffer.getLength() < 2)
return Status::INCOMPLETE;
if (buffer.ifNext(ZString("--"))) {
state = DONE;
return Status::COMPLETE;
}
if (!buffer.ifNext(ZString("\r\n")))
throw coreutils::Exception("CGIFormData: malformed opening boundary line.");
state = PART_HEADERS;
return Status::DATA_AVAIL;
case URLENCODED_BODY:
if ((int)buffer.getLength() < contentLength)
return Status::INCOMPLETE;
{
ZString body(buffer.getCursor(), contentLength);
buffer.setCursor(buffer.getCursor() + contentLength);
CGIFormattedData parsed(body);
for (auto &pair : parsed.data)
storeValue(pair.first, pair.second);
}
state = DONE;
return Status::COMPLETE;
case PART_HEADERS:
if (!headerParser)
headerParser = new IMFHeader(reader);
if (!checkParse(*headerParser))
return Status::INCOMPLETE;
extractPartName(*headerParser);
delete headerParser;
headerParser = NULL;
state = PART_BODY;
return Status::DATA_AVAIL;
case PART_BODY: {
MString marker;
marker << "\r\n--";
marker << boundary;
char *bodyStart = buffer.getCursor();
int pos = buffer.find(marker);
if (pos < 0)
return Status::INCOMPLETE;
char *bodyEnd = buffer.getCursor();
if (!currentSkip && currentName.getLength() > 0)
storeValue(currentName, MString(ZString(bodyStart, bodyEnd - bodyStart)));
currentName = MString();
currentSkip = false;
state = PART_BOUNDARY;
return Status::DATA_AVAIL;
}
case PART_BOUNDARY:
if (!boundaryParser)
boundaryParser = new IMFBoundary(reader, boundary);
if (!checkParse(*boundaryParser))
return Status::INCOMPLETE;
{
bool last = boundaryParser->isLast();
delete boundaryParser;
boundaryParser = NULL;
if (last) {
state = DONE;
return Status::COMPLETE;
}
state = PART_HEADERS;
return Status::DATA_AVAIL;
}
case DONE:
return Status::COMPLETE;
}
throw coreutils::Exception("CGIFormData: unreachable state.");
}
void CGIFormData::storeValue(MString name, MString value) {
int index = nameCounts[name]++;
MString key = name;
key << ":";
key << MString(std::to_string(index));
data[key] = value;
}
MString CGIFormData::operator[](ZString name) {
// if(contentType == "application/x-www-form-urlencoded")
// return formdata[name];
MString temp(name);
return temp;
MString key(name);
if (key.find(ZString(":")) == -1) {
key << ":0";
}
return data[key];
}
}
+66 -10
View File
@@ -1,27 +1,83 @@
#ifndef __CGIFormData_h__
# define __IMFFormData_h__
# define __CGIFormData_h__
#include "MString.h"
#include "ZString.h"
#include "CGIFormattedData.h"
#include "Parser.h"
#include "IMFHeader.h"
#include "IMFBoundary.h"
#include <map>
namespace coreutils {
class CGIFormData : public MString {
///
/// CGIFormData parses a CGI request body (application/x-www-form-urlencoded
/// or multipart/form-data) from the shared StreamReader and exposes the
/// resulting name/value pairs via operator[] - the object a caller (e.g.
/// JetCore's Tag::getVariable, for its $[:name] CGI variable syntax) holds
/// onto and indexes by variable name once doParse() reports COMPLETE.
///
/// Resumable like every other Parser here: for multipart/form-data, each
/// part's boundary line and header block are parsed via IMFBoundary/
/// IMFHeader (chained through checkParse(), sharing this same
/// StreamReader), so a part - or even its boundary marker - can straddle
/// any number of feed() calls without losing state. File-upload parts
/// (Content-Disposition with a filename= parameter) are recognized and
/// skipped - matching this codebase's existing convention that uploads
/// get a separate mechanism, not buffered through here.
///
class CGIFormData : public Parser {
public:
CGIFormData(int fd, ZString contentType, int contentLength, ZString boundary);
CGIFormData(StreamReader &reader, ZString contentType, int contentLength, ZString boundary);
virtual ~CGIFormData();
MString operator[](ZString name);
// Every parsed field, keyed as "name:N" (see storeValue's own doc
// comment below) - lets a caller (ApiSession::handleComplete, to
// merge POST body fields into jet::Global::variables the same way
// path params/query string already are - see its own doc comment)
// iterate every field without knowing its name in advance, which
// operator[] alone doesn't support.
const std::map<MString, MString> &fields() const { return data; }
protected:
Status parse() override;
private:
CGIFormattedData *formdata;
MString contentType;
enum Mode { URLENCODED, MULTIPART, UNKNOWN } mode;
enum State { INIT, OPENING_TAIL, PART_HEADERS, PART_BODY, PART_BOUNDARY, URLENCODED_BODY, DONE } state = INIT;
ZString contentType;
int contentLength;
ZString boundary;
std::map<MString, MString> data;
IMFHeader *headerParser = NULL;
IMFBoundary *boundaryParser = NULL;
MString currentName;
bool currentSkip = false;
std::map<MString, int> nameCounts;
void extractPartName(IMFHeader &header);
///
/// Stores value under "name:N", where N is how many values have
/// already been stored under this same base name (0 for the first,
/// 1 for the second, etc.) - matches the indexed key format
/// JetCore's Tag::getVariable's $[:name] syntax looks up by
/// (defaulting to :0 when the caller doesn't specify an index),
/// supporting repeated field names (checkboxes, multi-select) the
/// same way.
///
void storeValue(MString name, MString value);
};
}
#endif
+18 -12
View File
@@ -6,25 +6,31 @@ namespace coreutils {
CGIFormattedData::CGIFormattedData() {}
CGIFormattedData::CGIFormattedData(ZString cgiData) {
parse(cgiData);
}
CGIFormattedData::CGIFormattedData(ZString cgiData, ZString delimiter) : delimiter(delimiter) {
parse(cgiData);
}
void CGIFormattedData::setDelimiter(ZString delimiter) {
this->delimiter = delimiter;
}
void CGIFormattedData::parse(ZString cgiData) {
if(cgiData != "") {
cgiData.split("&");
cgiData.split(delimiter);
for(int ix = 0; ix < cgiData.getList().size(); ++ix) {
cgiData[ix].split("=");
data[cgiData[ix][0]] = cgiData[ix][1];
data[cgiData[ix][0]].fromCGI();
ZString pair = cgiData[ix].trim();
pair.split("=");
data[pair[0]] = pair[1];
data[pair[0]] = data[pair[0]].fromCGI();
}
}
}
ZString CGIFormattedData::operator=(ZString cgiData) {
if(cgiData != "") {
cgiData.split("&");
for(int ix = 0; ix < cgiData.getList().size(); ++ix) {
cgiData[ix].split("=");
data[cgiData[ix][0]] = cgiData[ix][1];
data[cgiData[ix][0]].fromCGI();
}
}
parse(cgiData);
return cgiData;
}
}
+7
View File
@@ -17,11 +17,18 @@ namespace coreutils {
public:
CGIFormattedData();
CGIFormattedData(ZString cgiData);
CGIFormattedData(ZString cgiData, ZString delimiter);
ZString operator=(ZString cgiData);
void setDelimiter(ZString delimiter);
std::map<MString, MString> data;
private:
void parse(ZString cgiData);
ZString delimiter = "&";
};
}
+15 -1
View File
@@ -4,6 +4,7 @@
#include <string.h>
#include <string>
#include <errno.h>
#include <source_location>
namespace coreutils {
@@ -15,7 +16,20 @@ namespace coreutils {
class Exception {
public:
Exception(std::string text, std::string file = __FILE__, int line = __LINE__, int errorNumber = errno);
///
/// file/line default to the caller's actual location. std::source_location::current()
/// is specifically defined by the standard to evaluate at the call site when used as a
/// default argument - unlike __FILE__/__LINE__ (preprocessor macros, which were used
/// here previously and always expanded to this header's own declaration line instead
/// of the real throw site, since macro expansion happens before the compiler even sees
/// "default argument" as a concept). Explicit callers (e.g. throw Exception(msg,
/// __FILE__, __LINE__)) are unaffected - the signature is unchanged.
///
Exception(std::string text,
std::string file = std::source_location::current().file_name(),
int line = std::source_location::current().line(),
int errorNumber = errno);
std::string className;
std::string file;
+20 -5
View File
@@ -17,19 +17,34 @@ namespace coreutils {
this->fileName = fileName;
struct stat status;
stat(fileName.c_str(), &status);
buffer = NULL;
setBufferSize(status.st_size);
fd = ::open(fileName.c_str(), mode, authority);
if(fd < 0) {
std::stringstream temp;
temp << "Error opening file " << fileName << ".";
throw Exception(temp.str(), __FILE__, __LINE__);
}
// stat() only after a successful open(), and only used to size the
// read buffer - previously this ran BEFORE the open()/fd check with
// its return value ignored, so a missing file left the stat struct fully
// uninitialized and fed that garbage st_size straight into
// setBufferSize()'s realloc(), before the open-failure path ever
// got a chance to throw its clean Exception. Found while adding a
// static-asset route (GET /assets/{filename}) that legitimately
// hits this path on every request for a nonexistent file - a
// garbage-sized realloc there could abort/crash the whole
// long-running APIServer process (shared with every other live
// route) instead of cleanly 500ing just that one request.
struct stat status;
if (fstat(fd, &status) != 0) {
std::stringstream temp;
temp << "Error statting file " << fileName << ".";
throw Exception(temp.str(), __FILE__, __LINE__);
}
setBufferSize(status.st_size);
}
File::~File() {
+127
View File
@@ -0,0 +1,127 @@
#include "HTTPRequest.h"
#include "Exception.h"
#include <strings.h>
namespace coreutils {
HTTPRequest::HTTPRequest(StreamReader &reader) : Parser(reader) {}
HTTPRequest::~HTTPRequest() {
delete lineParser;
delete headerParser;
delete formParser;
}
Parser::Status HTTPRequest::parse() {
MString &buffer = reader.getBuffer();
switch (state) {
case REQUEST_LINE: {
if (!lineParser)
lineParser = new LineParser(reader);
if (!checkParse(*lineParser))
return Status::INCOMPLETE;
{
ZString line = lineParser->getLine();
ZString sp(" ");
std::vector<ZString> &parts = line.split(sp);
if (parts.size() != 3)
throw coreutils::Exception("HTTPRequest: malformed request line "
"(expected \"METHOD /path HTTP/1.1\").");
method = MString(parts[0]);
path = MString(parts[1]);
version = MString(parts[2]);
}
delete lineParser;
lineParser = NULL;
{
// Split the query string off before anything else sees `path` -
// a route table (see the APIServer plan) should never have to
// deal with a trailing "?a=1&b=2" itself.
int qpos = path.find(ZString("?"));
if (qpos != -1) {
queryString = MString(path.substring(qpos + 1));
path = MString(path.substring(0, qpos));
}
}
state = HEADERS;
return Status::DATA_AVAIL;
}
case HEADERS:
if (!headerParser)
headerParser = new IMFHeader(reader);
if (!checkParse(*headerParser))
return Status::INCOMPLETE;
headers = headerParser->getHeaders();
delete headerParser;
headerParser = NULL;
state = BODY;
return Status::DATA_AVAIL;
case BODY: {
MString contentLengthHeader = getHeader("Content-Length");
if (contentLengthHeader.getLength() == 0) {
if (getHeader("Transfer-Encoding").getLength() > 0)
throw coreutils::Exception("HTTPRequest: chunked Transfer-Encoding "
"is not supported (Content-Length only).");
state = DONE;
return Status::COMPLETE;
}
int contentLength = contentLengthHeader.asInteger();
MString contentType = getHeader("Content-Type");
if (contentType.startsWith("application/x-www-form-urlencoded") ||
contentType.startsWith("multipart/form-data")) {
if (!formParser) {
// Mirrors __jet.cpp's identical CGI-path fix: find() leaves
// contentType's own cursor at the match, and CGIFormData's
// constructor copy-constructs its own contentType member
// from whatever we pass, inheriting that same moved cursor
// - its startsWith() dispatch checks are cursor-relative
// and would silently miss (falling through to UNKNOWN)
// without the reset().
int boundaryPos = contentType.find(ZString("boundary="));
if (boundaryPos != -1)
boundary = MString(contentType.substring(boundaryPos + 9));
contentType.reset();
formParser = new CGIFormData(reader, contentType, contentLength, boundary);
}
if (!checkParse(*formParser))
return Status::INCOMPLETE;
state = DONE;
return Status::COMPLETE;
}
if ((int)buffer.getLength() < contentLength)
return Status::INCOMPLETE;
body = MString(ZString(buffer.getCursor(), contentLength));
buffer.setCursor(buffer.getCursor() + contentLength);
state = DONE;
return Status::COMPLETE;
}
case DONE:
return Status::COMPLETE;
}
throw coreutils::Exception("HTTPRequest: unreachable state.");
}
MString HTTPRequest::getMethod() { return method; }
MString HTTPRequest::getPath() { return path; }
MString HTTPRequest::getQueryString() { return queryString; }
MString HTTPRequest::getVersion() { return version; }
MString HTTPRequest::getBody() { return body; }
std::map<MString, MString> &HTTPRequest::getHeaders() { return headers; }
CGIFormData *HTTPRequest::getFormData() { return formParser; }
MString HTTPRequest::getHeader(const char *name) {
for (auto &pair : headers) {
MString key = pair.first;
if (strcasecmp(key.c_str(), name) == 0)
return pair.second;
}
return MString();
}
}
+109
View File
@@ -0,0 +1,109 @@
#ifndef __HTTPRequest_h__
#define __HTTPRequest_h__
#include "Parser.h"
#include "LineParser.h"
#include "IMFHeader.h"
#include "CGIFormData.h"
#include "MString.h"
#include <map>
namespace coreutils {
///
/// HTTPRequest parses a full HTTP/1.1 request - request line, headers,
/// and (for a Content-Length body) either a raw body or, for
/// application/x-www-form-urlencoded / multipart/form-data, a parsed
/// CGIFormData - off a shared StreamReader. Resumable across any number
/// of StreamReader::feed() calls, exactly like every other Parser in
/// this subsystem: built by chaining LineParser (request line) and
/// IMFHeader (headers) via checkParse(), the same way CGIFormData itself
/// chains IMFHeader/IMFBoundary over one shared StreamReader.
///
/// This codebase predates ever parsing raw HTTP off a socket (it has
/// only ever sat behind a CGI gateway) - IMFRequest/IMFResponse/
/// IMFMessage are stubs from before this Parser/StreamReader subsystem
/// existed and are not built on here.
///
/// v1 limitations, deliberately not addressed (flagged, not fixed -
/// matching the standard already set by other Parser subclasses here for
/// known-but-out-of-scope gaps):
/// - chunked Transfer-Encoding is not supported, only Content-Length.
/// - repeated header names (e.g. multiple Cookie: lines) last-wins -
/// the same limitation IMFHeader's std::map already has, inherited
/// here since HEADERS delegates to IMFHeader directly.
///
class HTTPRequest : public Parser {
public:
HTTPRequest(StreamReader &reader);
virtual ~HTTPRequest();
///
/// Valid once doParse() has returned Status::COMPLETE.
///
MString getMethod();
MString getPath();
MString getQueryString();
MString getVersion();
///
/// Case-insensitive header lookup (HTTP header names are
/// case-insensitive per RFC 7230, unlike IMFHeader's underlying
/// std::map, which compares byte-for-byte) - returns an empty
/// MString if the header wasn't present. Valid once the HEADERS
/// state has completed (i.e. from BODY parsing onward).
///
MString getHeader(const char *name);
///
/// Every header as parsed, keyed exactly as received (not
/// case-normalized) - prefer getHeader() for lookups.
///
std::map<MString, MString> &getHeaders();
///
/// Valid once doParse() reports COMPLETE. Populated only when the
/// request had a body that was neither application/
/// x-www-form-urlencoded nor multipart/form-data (e.g. a raw JSON
/// body) - empty otherwise, including when there was no body at all.
///
MString getBody();
///
/// Valid once doParse() reports COMPLETE, when the body's
/// Content-Type was application/x-www-form-urlencoded or
/// multipart/form-data - NULL otherwise (including no body at all).
/// Owned by this HTTPRequest - do not delete.
///
CGIFormData *getFormData();
protected:
Status parse() override;
private:
enum State { REQUEST_LINE, HEADERS, BODY, DONE } state = REQUEST_LINE;
MString method, path, queryString, version;
std::map<MString, MString> headers;
MString body;
MString boundary;
LineParser *lineParser = NULL;
IMFHeader *headerParser = NULL;
CGIFormData *formParser = NULL;
};
}
#endif
+53
View File
@@ -0,0 +1,53 @@
#include "HTTPResponse.h"
#include <strings.h>
namespace coreutils {
HTTPResponse::HTTPResponse() {
statusText = "OK";
}
void HTTPResponse::setStatus(int code, ZString text) {
statusCode = code;
statusText = text;
}
void HTTPResponse::setHeader(ZString name, ZString value) {
headers[MString(name)] = MString(value);
}
void HTTPResponse::setBody(ZString bodyIn) {
body = bodyIn;
}
MString HTTPResponse::serialize() {
bool hasContentLength = false;
for (auto &pair : headers) {
MString key = pair.first;
if (strcasecmp(key.c_str(), "Content-Length") == 0)
hasContentLength = true;
}
MString out;
out << "HTTP/1.1 ";
out << MString(std::to_string(statusCode));
out << " ";
out << statusText;
out << "\r\n";
for (auto &pair : headers) {
out << pair.first;
out << ": ";
out << pair.second;
out << "\r\n";
}
if (!hasContentLength) {
out << "Content-Length: ";
out << MString(std::to_string(body.getLength()));
out << "\r\n";
}
out << "\r\n";
out << body;
return out;
}
}
+51
View File
@@ -0,0 +1,51 @@
#ifndef __HTTPResponse_h__
#define __HTTPResponse_h__
#include "MString.h"
#include <map>
namespace coreutils {
///
/// HTTPResponse builds a raw HTTP/1.1 response (status line + headers +
/// body) ready to write to a socket. Output-only, not a Parser - there's
/// nothing to resume here, the whole thing is built and serialized in
/// one pass once a handler has finished producing its body.
///
/// Deliberately new rather than built on/patched from IMFResponse -
/// IMFResponse's own header-emission code is dead (calls addHeader()/
/// output(), neither of which exist on that class) and it never grew a
/// real headers container, so there's nothing there safe to extend.
///
class HTTPResponse {
public:
HTTPResponse();
void setStatus(int code, ZString text);
void setHeader(ZString name, ZString value);
void setBody(ZString body);
///
/// Serializes the full response - status line, headers (an explicit
/// Content-Length header is respected as-is; otherwise one is
/// computed from the body automatically), the blank line, and the
/// body - ready to write to a socket.
///
MString serialize();
private:
int statusCode = 200;
MString statusText;
std::map<MString, MString> headers;
MString body;
};
}
#endif
+39 -20
View File
@@ -1,30 +1,49 @@
#include "IMFBoundary.h"
#include "Exception.h"
#include <unistd.h>
namespace coreutils {
IMFBoundary(StreamReader &reader, ZString boundary) : boundary(boundary) {
IMFBoundary::IMFBoundary(StreamReader &reader, ZString boundary) : Parser(reader), boundary(boundary) {}
}
int IMFBoundary::parse() {
Parser::Status IMFBoundary::parse() {
MString &buffer = reader.getBuffer();
switch (state) {
case PREFIX:
if(buffer.remaining() > 3)
if(reader.nextIf("\r\n--"))
state = BOUNDARY;
case BOUNDARY:
while(buffer.getTokenInclude(""));
if(buffer.eod())
return 2;
else if(buffer.remaining() > 1)
if(buffer.ifNext("--"))
state = LAST_BOUNDARY;
case LAST_BOUNDARY:
return 0;
}
case PREFIX: {
MString marker;
marker << "\r\n--";
marker << boundary;
int pos = buffer.find(marker);
if (pos < 0)
return Status::INCOMPLETE;
if (!buffer.ifNext(marker))
throw coreutils::Exception("IMFBoundary: boundary marker vanished between find and ifNext.");
state = TAIL;
return Status::DATA_AVAIL;
}
case TAIL:
// ZString::getLength() is already cursor-relative (bytes remaining
// from the cursor to the end) - do not subtract the cursor offset
// again here.
if (buffer.getLength() < 2)
return Status::INCOMPLETE;
if (buffer.ifNext(ZString("--"))) {
last = true;
return Status::COMPLETE;
}
if (buffer.ifNext(ZString("\r\n"))) {
last = false;
return Status::COMPLETE;
}
throw coreutils::Exception("IMFBoundary: malformed boundary line - expected CRLF or trailing --.");
}
throw coreutils::Exception("IMFBoundary: unreachable state.");
}
bool IMFBoundary::isLast() {
return last;
}
}
+25 -2
View File
@@ -1,20 +1,43 @@
#ifndef __IMFBoundary_h__
# define __IMFBoundary_h__
#include "StreamReader.h"
#include "Parser.h"
namespace coreutils {
///
/// IMFBoundary detects a MIME multipart boundary line in the shared
/// StreamReader - either an ordinary boundary ("\r\n--" + boundary +
/// "\r\n", meaning another part follows) or the closing boundary
/// ("\r\n--" + boundary + "--", meaning this was the last part).
/// Resumable: if the boundary text has been seen but there isn't yet
/// enough buffered data to tell an ordinary boundary from the closing
/// one, parse() reports INCOMPLETE without committing the cursor past
/// the ambiguous point.
///
class IMFBoundary : public Parser {
public:
IMFBoundary(StreamReader &reader, ZString boundary);
virtual int parse();
///
/// Valid once doParse() has returned Status::COMPLETE - true if this
/// was the closing boundary (no further parts follow).
///
bool isLast();
protected:
Status parse() override;
private:
enum State { PREFIX, TAIL } state = PREFIX;
ZString boundary;
bool last = false;
};
+7 -1
View File
@@ -5,7 +5,13 @@
namespace coreutils {
IMFFormData::IMFFormData(int fd, ZString boundary) {
IMFHeader header(fd);
// TODO: IMFHeader now reads through a StreamReader (see the Parser/
// StreamReader redesign) instead of a raw fd. This constructor - and
// IMFMultipart, which still constructs IMFFormData from a bare fd -
// needs migrating to StreamReader together before header parsing can
// be wired back in here. Out of scope for that redesign pass; this
// class was already an unfinished stub (constructed objects were
// discarded, nothing was stored) before this change.
IMFText text(fd, boundary);
}
-2
View File
@@ -15,5 +15,3 @@ namespace coreutils {
}
#endif
+67 -18
View File
@@ -1,32 +1,81 @@
#include "IMFHeader.h"
#include "Exception.h"
#include "Log.h"
#include <unistd.h>
namespace coreutils {
IMFHeader::IMFHeader(int fd) {}
IMFHeader::IMFHeader(StreamReader &reader) : Parser(reader) {}
Parser::Status IMFHeader::parse() {
MString &buffer = reader.getBuffer();
virtual int parse() {
switch (state) {
case NAME:
name << buffer.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-0123456789");
if(buffer.ifNext(":"))
state = FIELD;
else
return 2;
case FIELD:
field << buffer.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-;'\"0123456789");
if(!buffer.ifNext("\r\n"))
case NAME: {
if (buffer.eod())
return 2;
// Right here is where we should check if next line is an extension to the previous line.
return Status::INCOMPLETE;
if (buffer.getChar() == '\r') {
// ZString::getLength() is already cursor-relative.
if (buffer.getLength() < 2)
return Status::INCOMPLETE;
if (!buffer.ifNext(ZString("\r\n")))
throw coreutils::Exception("IMFHeader: expected CRLF at end of header block.");
return Status::COMPLETE;
}
name << buffer.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-0123456789");
if (buffer.eod())
return Status::INCOMPLETE;
if (!buffer.ifNext(ZString(":")))
throw coreutils::Exception("IMFHeader: expected ':' in header name.");
state = SKIP_SPACE;
return Status::DATA_AVAIL;
}
case SKIP_SPACE:
while (!buffer.eod() && buffer.getChar() == ' ')
buffer.nextChar();
if (buffer.eod())
return Status::INCOMPLETE;
state = FIELD;
return Status::DATA_AVAIL;
case FIELD:
field << buffer.getTokenExclude("\r\n");
// Need 2 bytes buffered to reliably test for "\r\n" - eod() (a
// 1-byte check) would wrongly treat a lone trailing \r as
// malformed instead of "wait for the \n". Same bug class already
// fixed once in IMFBoundary's TAIL state.
if (buffer.getLength() < 2)
return Status::INCOMPLETE;
if (!buffer.ifNext(ZString("\r\n")))
throw coreutils::Exception("IMFHeader: expected CRLF at end of header field.");
state = FOLD_CHECK;
return Status::DATA_AVAIL;
case FOLD_CHECK:
if (buffer.eod())
return Status::INCOMPLETE;
if (buffer.getChar() == ' ' || buffer.getChar() == '\t') {
buffer.nextChar();
field << " ";
state = SKIP_SPACE;
return Status::DATA_AVAIL;
}
commitField();
state = NAME;
return Status::DATA_AVAIL;
}
throw coreutils::Exception("IMFHeader: unreachable state.");
}
void IMFHeader::commitField() {
headers[name] = field;
name = MString();
field = MString();
}
std::map<MString, MString> &IMFHeader::getHeaders() {
return headers;
}
}
+26 -4
View File
@@ -1,26 +1,48 @@
#ifndef __IMFHeader_h__
# define __IMFHeader_h__
# include "StreamReader.h"
# include "Parser.h"
# include "MString.h"
# include "IMFHeaderField.h"
# include <vector>
# include <map>
namespace coreutils {
///
/// IMFHeader parses a full block of IMF/MIME-style headers (RFC 5322
/// "name: value" pairs, one per line, with folded continuation lines -
/// any line starting with a space or tab is appended to the previous
/// field's value) from the shared StreamReader, stopping at the blank
/// line that terminates the header block. Resumable across any number of
/// StreamReader::feed() calls - partially-read names/values accumulate
/// in the name/field members rather than being discarded between calls.
///
class IMFHeader : public Parser {
public:
IMFHeader(StreamReader &reader);
virtual int parse();
///
/// Valid once doParse() has returned Status::COMPLETE - every header
/// field parsed, keyed by field name.
///
std::map<MString, MString> &getHeaders();
protected:
Status parse() override;
private:
enum State { NAME, SKIP_SPACE, FIELD, FOLD_CHECK } state = NAME;
MString name;
MString field;
std::map<MString, MString> headers;
void commitField();
};
}
+1
View File
@@ -7,5 +7,6 @@
namespace coreutils {
IMFMessage::IMFMessage(int fd) {}
IMFMessage::~IMFMessage() {}
}
+28 -1
View File
@@ -4,7 +4,34 @@
namespace coreutils {
JFile::JFile(ZString filename) : MFile(filename) {}
// MFile and JString share a single virtual MString base (the diamond:
// both "MFile : virtual public MString" and "JString : virtual public
// MString"), and a virtual base is initialized only by the *most
// derived* class's constructor - so JString's own "{}" default
// initializer never runs here. Left alone, a JFile backed by a new or
// empty file starts as a raw empty string instead of a valid empty JSON
// object, and every subsequent locate()/set() call silently misbehaves
// (no leading "{" for ifNext("{") to match, so writes end up inserted
// at offset 0 with no braces or separators at all). Detect that case
// here and seed valid JSON explicitly.
JFile::JFile(ZString filename) : MFile(filename) {
if(getLength() == 0) {
*this << "{}";
} else {
// MFile's own file-loading reads the raw bytes straight into the
// shared MString buffer - it never goes through JString::operator=,
// which is the only other place this class normally strips
// whitespace before parsing (removeWhitespace()). Without this, a
// JFile backed by a hand-written or pretty-printed JSON file (any
// whitespace between tokens - indentation, newlines, spaces after
// ':'/',') fails every locate()/exists()/get*() call, since
// JString's parser expects compact JSON with no whitespace at all
// between structural tokens. In-memory JSON built via operator=
// never hit this because it already goes through the same
// normalization - loading from disk just missed it.
removeWhitespace();
}
}
}
+484 -68
View File
@@ -1,5 +1,7 @@
#include "JString.h"
#include "Exception.h"
#include <cstdio>
#include <cstdlib>
namespace coreutils {
@@ -10,140 +12,537 @@ namespace coreutils {
return os;
}
MString &operator<<(MString &ms, const JString::Proxy &proxy) {
ZString tempkey = proxy.key;
ZString temp = proxy.jstring.find(tempkey);
ms << temp;
return ms;
}
JString::JString() : MString("{}") {}
void JString::set(ZString &path, ZString &value) {
// ---------------------------------------------------------------------
// Structural helpers - escape/type aware skipping so JSON-significant
// characters (", {, }, [, ]) appearing inside string literals never
// desync the parse position.
// ---------------------------------------------------------------------
JSONType JString::typeAtCursor() {
if (startsWith("\""))
return JSONType::STRING;
if (startsWith("{"))
return JSONType::OBJECT;
if (startsWith("["))
return JSONType::ARRAY;
if (startsWith("true") || startsWith("false"))
return JSONType::BOOLEAN;
if (startsWith("null"))
return JSONType::JNULL;
if (startsWithNumber())
return JSONType::NUMBER;
return JSONType::NOT_FOUND;
}
// Captures the raw (still-escaped) content between a pair of quotes, cursor
// must be positioned on the opening quote. Leaves the cursor just past the
// closing quote. Correctly treats \" and \\ as escaped, not structural, so
// a string containing an escaped quote is captured in full rather than
// truncated early.
ZString JString::captureString() {
if (!ifNext("\""))
throw coreutils::Exception("Expected '\"' at start of JSON string.");
char *start = getCursor();
while (!eod()) {
char ch = getChar();
if (ch == '\\') {
nextChar();
if (!eod())
nextChar();
continue;
}
if (ch == '"') {
ZString result(start, getCursor() - start);
nextChar();
return result;
}
nextChar();
}
throw coreutils::Exception("Unterminated JSON string.");
}
void JString::skipString() {
captureString();
}
ZString JString::captureContainer() {
char *start = getCursor();
skipContainer();
return ZString(start, getCursor() - start);
}
void JString::skipContainer() {
char open = getChar();
char close = (open == '{') ? '}' : ']';
int depth = 0;
do {
if (eod())
throw coreutils::Exception("Unterminated JSON object/array.");
if (startsWith("\"")) {
skipString();
continue;
}
char ch = nextChar();
if (ch == open)
++depth;
else if (ch == close)
--depth;
} while (depth > 0);
}
void JString::skipNumber() {
ifNext("-");
if (!((getChar() >= '0') && (getChar() <= '9')))
throw coreutils::Exception("Invalid JSON number.");
while (!eod() && (getChar() >= '0') && (getChar() <= '9'))
nextChar();
if (!eod() && (getChar() == '.')) {
nextChar();
while (!eod() && (getChar() >= '0') && (getChar() <= '9'))
nextChar();
}
if (!eod() && ((getChar() == 'e') || (getChar() == 'E'))) {
nextChar();
if (!eod() && ((getChar() == '+') || (getChar() == '-')))
nextChar();
while (!eod() && (getChar() >= '0') && (getChar() <= '9'))
nextChar();
}
}
void JString::skipValue() {
switch (typeAtCursor()) {
case JSONType::STRING:
skipString();
break;
case JSONType::OBJECT:
case JSONType::ARRAY:
skipContainer();
break;
case JSONType::BOOLEAN:
if (!ifNext("true") && !ifNext("false"))
throw coreutils::Exception("Invalid JSON boolean.");
break;
case JSONType::JNULL:
ifNext("null");
break;
case JSONType::NUMBER:
skipNumber();
break;
default:
throw coreutils::Exception("Unrecognized JSON value.");
}
}
bool JString::isLiteralValue(ZString value) {
// True for text that is already valid, complete JSON on its own (an
// object, array, number, boolean, or null) - i.e. text that should be
// inserted as-is rather than quoted and escaped as a JSON string.
if (value.startsWith("{") || value.startsWith("["))
return true;
if (value.equals("true") || value.equals("false") || value.equals("null"))
return true;
if (value.startsWithNumber())
return true;
return false;
}
// ---------------------------------------------------------------------
// JSON string escape / unescape
// ---------------------------------------------------------------------
std::string JString::jsonEscape(ZString value) {
std::string result;
ZString v = value;
v.reset();
while (!v.eod()) {
char ch = v.nextChar();
switch (ch) {
case '"': result += "\\\""; break;
case '\\': result += "\\\\"; break;
case '\b': result += "\\b"; break;
case '\f': result += "\\f"; break;
case '\n': result += "\\n"; break;
case '\r': result += "\\r"; break;
case '\t': result += "\\t"; break;
default:
if ((unsigned char)ch < 0x20) {
char buf[8];
snprintf(buf, sizeof(buf), "\\u%04x", (unsigned char)ch);
result += buf;
} else {
result += ch;
}
}
}
return result;
}
static void appendUTF8(std::string &out, unsigned int codepoint) {
if (codepoint <= 0x7F) {
out += (char)codepoint;
} else if (codepoint <= 0x7FF) {
out += (char)(0xC0 | (codepoint >> 6));
out += (char)(0x80 | (codepoint & 0x3F));
} else if (codepoint <= 0xFFFF) {
out += (char)(0xE0 | (codepoint >> 12));
out += (char)(0x80 | ((codepoint >> 6) & 0x3F));
out += (char)(0x80 | (codepoint & 0x3F));
} else {
out += (char)(0xF0 | (codepoint >> 18));
out += (char)(0x80 | ((codepoint >> 12) & 0x3F));
out += (char)(0x80 | ((codepoint >> 6) & 0x3F));
out += (char)(0x80 | (codepoint & 0x3F));
}
}
static unsigned int readHex4(ZString &v) {
if (v.getLength() < 4)
throw coreutils::Exception("Truncated \\u escape in JSON string.");
unsigned int value = 0;
for (int ix = 0; ix < 4; ++ix) {
char ch = v.nextChar();
value <<= 4;
if ((ch >= '0') && (ch <= '9')) value |= (ch - '0');
else if ((ch >= 'a') && (ch <= 'f')) value |= (ch - 'a' + 10);
else if ((ch >= 'A') && (ch <= 'F')) value |= (ch - 'A' + 10);
else throw coreutils::Exception("Invalid hex digit in \\u escape.");
}
return value;
}
std::string JString::jsonUnescape(ZString raw) {
std::string result;
ZString v = raw;
v.reset();
while (!v.eod()) {
char ch = v.nextChar();
if ((ch != '\\') || v.eod()) {
result += ch;
continue;
}
char esc = v.nextChar();
switch (esc) {
case '"': result += '"'; break;
case '\\': result += '\\'; break;
case '/': result += '/'; break;
case 'b': result += '\b'; break;
case 'f': result += '\f'; break;
case 'n': result += '\n'; break;
case 'r': result += '\r'; break;
case 't': result += '\t'; break;
case 'u': {
unsigned int codepoint = readHex4(v);
// High surrogate? consume the paired low surrogate and combine.
if ((codepoint >= 0xD800) && (codepoint <= 0xDBFF) &&
(v.getLength() >= 6) && (v.getChar() == '\\')) {
char *mark = v.getCursor();
v.nextChar();
if (v.getChar() == 'u') {
v.nextChar();
unsigned int low = readHex4(v);
if ((low >= 0xDC00) && (low <= 0xDFFF)) {
codepoint = 0x10000 + ((codepoint - 0xD800) << 10) + (low - 0xDC00);
} else {
v.setCursor(mark); // not a valid low surrogate, back out
}
} else {
v.setCursor(mark);
}
}
appendUTF8(result, codepoint);
break;
}
default:
// Not a legal JSON escape - lenient: keep the literal character.
result += esc;
}
}
return result;
}
// ---------------------------------------------------------------------
// Typed read access
// ---------------------------------------------------------------------
JSONType JString::getType(ZString path) {
reset();
if(locate(path)) {
push();
if(ifNext("\"")) {
ZString old = getTokenExclude("\"");
pop();
remove(offset(), old.getLength() + 2);
MString key;
if(value.startsWith("["))
key << value;
else if(value.startsWith("{"))
key << value;
else
key << "\"" << value << "\"";
insert(key, offset());
} else {
pop();
throw coreutils::Exception("Fix me to accept integer type.");
if (!locate(path))
return JSONType::NOT_FOUND;
return typeAtCursor();
}
} else {
// std::cout << "[" << unparsed() << "] >" << value << "<" << std::endl;
MString key;
if(notfirst)
key << ",";
// TODO: The value added must be parsed down to remove all whitespace.
if(value.startsWith("["))
key << "\"" << path << "\":" << value;
else if(value.startsWith("{"))
key << "\"" << path << "\":" << value;
else
key << "\"" << path << "\":" << "\"" << value << "\"";
insert(key, offset());
bool JString::exists(ZString path) {
return getType(path) != JSONType::NOT_FOUND;
}
bool JString::isNull(ZString path) {
return getType(path) == JSONType::JNULL;
}
std::string JString::getString(ZString path) {
reset();
if (!locate(path))
throw coreutils::Exception("Path not found.");
if (typeAtCursor() != JSONType::STRING)
throw coreutils::Exception("Value at path is not a JSON string.");
return jsonUnescape(captureString());
}
double JString::getNumber(ZString path) {
reset();
if (!locate(path))
throw coreutils::Exception("Path not found.");
if (typeAtCursor() != JSONType::NUMBER)
throw coreutils::Exception("Value at path is not a JSON number.");
char *start = getCursor();
skipNumber();
return atof(std::string(start, getCursor() - start).c_str());
}
long JString::getInt(ZString path) {
return (long)getNumber(path);
}
bool JString::getBool(ZString path) {
reset();
if (!locate(path))
throw coreutils::Exception("Path not found.");
if (ifNext("true"))
return true;
if (ifNext("false"))
return false;
throw coreutils::Exception("Value at path is not a JSON boolean.");
}
// ---------------------------------------------------------------------
// find() - kept for callers that want the raw (still-escaped for strings)
// span rather than a fully typed/decoded value.
// ---------------------------------------------------------------------
ZString JString::find(ZString path) {
reset();
if(locate(path)) {
if(ifNext("\""))
return getTokenExclude("\"");
// TODO: Handle numbers that are not in double quotes.
else if(startsWith("["))
return getContainer();
else if(startsWith("{"))
return getContainer();
return findRelative(path);
}
// Same as find(), but searches from the cursor's current position rather than
// resetting to the start of the whole document first. Needed by the array
// selector logic in locate() below, which must check a subkey *within the
// array element currently under the cursor* - calling find() there (which
// always resets to the document root) would search the wrong object entirely.
ZString JString::findRelative(ZString path) {
if (!locate(path))
return ZString();
switch (typeAtCursor()) {
case JSONType::STRING:
return captureString();
case JSONType::ARRAY:
case JSONType::OBJECT:
return captureContainer();
default: {
char *start = getCursor();
skipValue();
return ZString(start, getCursor() - start);
}
}
}
// ---------------------------------------------------------------------
// locate() - path navigation. Structurally unchanged except that skipping
// past a key's value (when it isn't the one being searched for) now goes
// through skipValue() so every JSON type is handled, not just
// string/array/object, and strings are skipped escape-aware.
// ---------------------------------------------------------------------
bool JString::locate(ZString path) {
// std::cout << "path locate: " << path << std::endl;
path.getTokenExclude("[.");
notfirst = false;
if (ifNext("{")) {
while (startsWith("\"")) {
notfirst = true;
ZString label;
ZString value;
if (ifNext("\"")) {
label = getTokenExclude("\"");
ifNext("\"");
} else
throw coreutils::Exception("Labels must be contained in double quotes.");
if (ifNext(":")) {
// std::cout << "path: (" << path.parsed() << ") (" << label << ") " << (label == path.parsed()) << std::endl;
if (label == path.parsed()) {
if (path.unparsed() == "") {
// std::cout << "found cursor: " << unparsed() << std::endl;
return true;
}
if (path.ifNext("."))
return locate(path.unparsed());
if (path.ifNext("[")) {
bool found = true;
if (path.startsWithNumber()) {
// Numeric index: label[N]
int index = path.asInteger();
if (!path.ifNext("]"))
throw coreutils::Exception("expecting ] after index value in array selector.");
if(ifNext("[")) {
if (!ifNext("["))
throw coreutils::Exception("Path is expecting an array for selector value.");
while (index > 0) {
getContainer();
skipValue();
if (!ifNext(","))
throw coreutils::Exception("expecting comma to seperate array elements.");
--index;
}
return true;
} else
} else {
// Selector: label[key=value] - find the array element whose subkey
// matches the given value.
ZString key = path.getTokenExclude("=");
if (!path.ifNext("="))
throw coreutils::Exception("expecting '=' in array selector.");
ZString value = path.getTokenExclude("]");
if (!path.ifNext("]"))
throw coreutils::Exception("expecting ']' after array selector value.");
if (!ifNext("["))
throw coreutils::Exception("Path is expecting an array for selector value.");
if(path.eod())
found = false;
while (!ifNext("]")) {
push();
ZString check = findRelative(key);
pop();
if (check.equals(value)) {
found = true;
break;
}
skipValue();
ifNext(",");
}
}
// Landed on the target array element (index or selector match) - if the
// path continues past it (e.g. "b[2].c" or "items[id=x].val"), descend
// into it; otherwise this element itself is the target. Previously the
// numeric-index case always returned true immediately after reaching the
// index, so any further path segment was silently ignored, and the
// selector case was never reachable from a nested path at all - both
// now share this same continuation logic.
if (!found)
return false;
else if(path.ifNext("."))
if (path.eod())
return true;
if (path.ifNext("."))
return locate(path.unparsed());
throw coreutils::Exception("expecting '.' in path.");
}
}
// std::cout << "+++" << unparsed() << std::endl;
if(startsWith("\"")) {
getContainer();
} else if(startsWith("[")) {
getContainer();
} else if(startsWith("{")) {
getContainer();
} else {
throw coreutils::Exception("Unrecognized data type.");
}
skipValue();
ifNext(",");
} else
throw coreutils::Exception("Expected colon after label.");
}
} else if (ifNext("[")) {
ZString label = path[0].getTokenExclude("[");
ZString label = path.getTokenExclude("[");
path.ifNext("[");
ZString key = path[0].getTokenExclude("=");
ZString key = path.getTokenExclude("=");
path.ifNext("=");
ZString value = path[0].getTokenExclude("]");
ZString value = path.getTokenExclude("]");
while (!ifNext("]")) {
push();
ZString check = find(key);
ZString check = findRelative(key);
pop();
if (check.equals(value)) {
return locate(label);
} else {
getContainer();
skipValue();
ifNext(",");
}
}
}
// std::cout << "not found cursor: " << unparsed() << std::endl;
return false;
}
// ---------------------------------------------------------------------
// Writing values
// ---------------------------------------------------------------------
void JString::set(ZString &path, ZString &value) {
reset();
MString formatted;
if (isLiteralValue(value))
formatted << value;
else
formatted << "\"" << jsonEscape(value).c_str() << "\"";
setFormatted(path, formatted);
}
void JString::setFormatted(ZString path, MString formatted) {
reset();
if (locate(path)) {
int startOffset = offset();
skipValue();
int len = offset() - startOffset;
remove(startOffset, len);
insert(formatted, startOffset);
} else {
MString key;
if (notfirst)
key << ",";
key << "\"" << path << "\":" << formatted;
insert(key, offset());
}
}
void JString::setString(ZString path, std::string value) {
// Deliberately NOT routed through set() (which calls isLiteralValue()
// to guess whether the raw text should be quoted) - setString() is
// explicitly, unambiguously a string setter, so the value must
// ALWAYS be quoted+escaped regardless of what it looks like.
// isLiteralValue() classifies anything ZString::startsWithNumber()
// accepts as a bare numeric literal - true for "42", but ALSO true
// for a string that merely STARTS with digits, like a UUID
// ("00146df8-e42c-11e7-9c78-525400b869dc"). Going through set()
// wrote that UUID completely unquoted; skipValue() then only
// recognizes the JSON-number PREFIX ("00146") as the value's real
// span when locating it for a later update, so the next setString()
// call spliced its own new key/value pair in right after "00146",
// leaving "df8-e42c-...-869dc" as orphaned text outside the object
// entirely - malformed JSON, confirmed via a real corrupted session
// file (jet-2.0's own native $[@name] session variables, backed by
// this class - see Global.h). Every other setString() caller
// sitewide was silently exposed to the same risk for any string
// value that happens to start with a digit.
MString v(value);
MString formatted;
formatted << "\"" << jsonEscape(v).c_str() << "\"";
setFormatted(path, formatted);
}
void JString::setNumber(ZString path, double value) {
char buf[64];
snprintf(buf, sizeof(buf), "%g", value);
MString v(buf);
set(path, v);
}
void JString::setInt(ZString path, long value) {
char buf[32];
snprintf(buf, sizeof(buf), "%ld", value);
MString v(buf);
set(path, v);
}
void JString::setBool(ZString path, bool value) {
MString v(value ? "true" : "false");
set(path, v);
}
void JString::setNull(ZString path) {
MString v("null");
set(path, v);
}
JString & JString::operator=(coreutils:: ZString value) {
setSize(value.getLength());
memcpy(data, value.getData(), value.getLength());
@@ -163,7 +562,7 @@ namespace coreutils {
else if (*cursor == '\n')
remove(1);
else if (startsWith("\""))
getContainer();
skipString();
else
++cursor;
}
@@ -211,6 +610,23 @@ namespace coreutils {
for (int ix = 0; ix < index; ++ix)
output << ' ';
}
else if (ch == '"') {
output << ch;
// Stream the rest of the string literal through untouched, including
// escapes, without the pretty-printer's structural-character logic
// firing on a { } [ ] , or : that happens to appear inside it.
while (!eod()) {
char sch = nextChar();
output << sch;
if (sch == '\\') {
if (!eod())
output << nextChar();
continue;
}
if (sch == '"')
break;
}
}
else
output << ch;
}
+154 -8
View File
@@ -14,7 +14,7 @@ namespace coreutils {
/// access the objects elements using a named path as the index to the items.
///
/// JString default constructor will create an empty JString object pointing
/// to an empty string.
/// to an empty object ("{}").
///
/// Use a constructor or assignment operator to initialize a JString to an
/// initial JSON string.
@@ -23,10 +23,30 @@ namespace coreutils {
/// object to initialize the JSON string. On destruction the file is saved back.
///
/// The [] operator can be used to access elements within the JSON string.
/// Use:
/// jstring["key"] = "value";
/// std::cout << jstring["key"];
/// Assigning a value dispatches on the C++ type of the right-hand side, so the
/// resulting JSON is correctly typed rather than always being a quoted string:
///
/// jstring["name"] = "value"; // JSON string, escaped correctly
/// jstring["count"] = 42; // JSON number (integer)
/// jstring["price"] = 19.95; // JSON number
/// jstring["active"] = true; // JSON boolean
/// jstring["notes"].setNull(); // JSON null
///
/// std::cout << jstring["name"];
///
/// Typed read access is available directly on the path (no need to go through
/// operator[] first):
///
/// std::string name = jstring.getString("name");
/// double price = jstring.getNumber("price");
/// bool active = jstring.getBool("active");
/// bool missing = !jstring.exists("notfound");
/// JSONType t = jstring.getType("count"); // JSONType::NUMBER
///
enum class JSONType {
STRING, NUMBER, BOOLEAN, JNULL, ARRAY, OBJECT, NOT_FOUND
};
class JString : virtual public MString {
@@ -36,10 +56,24 @@ namespace coreutils {
void set(ZString &path, ZString &value);
///
/// Inserts/replaces path with already-formatted, valid JSON text
/// (a quoted+escaped string, or a bare number/bool/null literal) -
/// the locate()/skipValue()/insert() mechanics set() and setString()
/// both share, factored out so setString() can force string quoting
/// unconditionally instead of going through set()'s own
/// isLiteralValue() guess (see setString()'s own comment in the
/// .cpp for why that guess is wrong for a string setter).
///
void setFormatted(ZString path, MString formatted);
///
/// Use the find method to look through an object for member specified by
/// the key in parameter 1. The cursor must be pointing to the { character
/// that begins the object's list.
/// that begins the object's list. Returns the raw (still-escaped, for
/// strings) span of the value - use getString()/getNumber()/getBool()/
/// isNull() for decoded, typed access instead.
///
ZString find(ZString path);
@@ -48,6 +82,34 @@ namespace coreutils {
bool notfirst;
ZString path;
///
/// Type-aware access. All of these call locate() internally, so path uses
/// the same dotted/bracketed syntax as find()/set() (e.g. "a.b[2].c").
///
JSONType getType(ZString path);
bool exists(ZString path);
bool isNull(ZString path);
std::string getString(ZString path); ///< Escape-decoded string content.
double getNumber(ZString path);
long getInt(ZString path);
bool getBool(ZString path);
void setString(ZString path, std::string value); ///< Escapes value automatically.
void setNumber(ZString path, double value);
void setInt(ZString path, long value);
void setBool(ZString path, bool value);
void setNull(ZString path);
///
/// JSON string escape/unescape helpers (exposed as static utilities since
/// they operate on plain text, not on this object's own JSON document).
///
static std::string jsonEscape(ZString value);
static std::string jsonUnescape(ZString raw);
class Proxy {
public:
@@ -55,6 +117,23 @@ namespace coreutils {
friend std::ostream &operator<<(std::ostream &os, const Proxy &proxy);
///
/// Proxy offers several implicit conversion operators below (to
/// ZString, MString, std::string, double, bool) so a single $[...]-
/// style access can be used wherever any of those types is expected.
/// That flexibility makes "MString << Proxy" genuinely ambiguous on
/// its own - operator ZString() and operator MString() (via its own
/// implicit upcast to ZString) both satisfy MString::operator<<(ZString),
/// and operator double()/operator bool() both satisfy
/// MString::operator<<(int) via a standard numeric conversion - so
/// the compiler has no way to prefer one path over another. This
/// exact-match overload (mirroring the ostream one above, which
/// solves the same problem for std::cout << proxy) resolves it by
/// giving MString a candidate that needs no conversion at all.
///
friend MString &operator<<(MString &ms, const Proxy &proxy);
operator coreutils::ZString () {
return jstring.find(key);
}
@@ -64,15 +143,53 @@ namespace coreutils {
}
operator std::string () {
return jstring.find(key).str();
return jstring.getString(key);
}
operator double () {
return jstring.getNumber(key);
}
operator bool () {
return jstring.getBool(key);
}
Proxy& operator=(coreutils::MString value) {
jstring.set(key, value);
jstring.setString(key, value.str());
jstring.changed(key, value);
return *this;
}
Proxy& operator=(const char *value) {
jstring.setString(key, std::string(value));
jstring.changed(key, ZString(value));
return *this;
}
Proxy& operator=(double value) {
jstring.setNumber(key, value);
return *this;
}
Proxy& operator=(int value) {
jstring.setInt(key, value);
return *this;
}
Proxy& operator=(long value) {
jstring.setInt(key, value);
return *this;
}
Proxy& operator=(bool value) {
jstring.setBool(key, value);
return *this;
}
void setNull() {
jstring.setNull(key);
}
private:
JString &jstring;
ZString key;
@@ -88,9 +205,38 @@ namespace coreutils {
virtual void changed(ZString key, ZString value);
private:
protected:
///
/// Strips whitespace between JSON structural tokens (indentation,
/// newlines, spaces after ':'/',') - the parser expects compact JSON
/// internally. operator=(ZString) already calls this for in-memory
/// assignment; JFile's constructor also calls it after loading a
/// file's raw bytes, which otherwise bypasses this entirely (see
/// JFile.cpp). Protected rather than private specifically so JFile
/// can reach it.
///
void removeWhitespace();
private:
///
/// Structural helpers used internally by locate()/set() to correctly skip
/// past a value of any JSON type without being confused by JSON-structural
/// characters (quotes, braces, brackets) appearing inside string literals.
///
ZString findRelative(ZString path);
JSONType typeAtCursor();
void skipValue();
void skipString();
void skipContainer();
void skipNumber();
ZString captureString();
ZString captureContainer();
bool isLiteralValue(ZString value);
};
}
+16 -8
View File
@@ -1,18 +1,26 @@
#include "LineParser.h"
#include "Exception.h"
#include <unistd.h>
namespace coreutils {
LineParser::LineParser(StreamReader &reader) {
LineParser::LineParser(StreamReader &reader) : Parser(reader) {}
Parser::Status LineParser::parse() {
MString &buffer = reader.getBuffer();
char *lineStart = buffer.getCursor();
ZString term("\n");
int pos = buffer.find(term);
if (pos < 0)
return Status::INCOMPLETE;
char *lineEnd = buffer.getCursor();
if (lineEnd > lineStart && *(lineEnd - 1) == '\r')
--lineEnd;
line = ZString(lineStart, lineEnd - lineStart);
buffer.setCursor(buffer.getCursor() + 1);
return Status::COMPLETE;
}
int LineParser::parse() {
ZString LineParser::getLine() {
return line;
}
}
+24 -2
View File
@@ -1,17 +1,39 @@
#ifndef __LineParser_h__
# define __LineParser_h__
#include "StreamReader.h"
#include "Parser.h"
namespace coreutils {
///
/// LineParser builds one line of text at a time from the shared
/// StreamReader - terminated by LF or CRLF, either accepted, the
/// terminator itself is not included in getLine(). Resumable: if no
/// terminator has arrived yet, parse() reports INCOMPLETE and leaves the
/// cursor exactly where it started, so the same unconsumed bytes are
/// re-scanned (along with whatever new data arrived) on the next call.
///
class LineParser : public Parser {
public:
LineParser(StreamReader &reader);
int parse() override;
///
/// Valid once doParse() has returned Status::COMPLETE - the line that
/// was parsed, with its terminator stripped.
///
ZString getLine();
protected:
Status parse() override;
private:
ZString line;
};
+71 -11
View File
@@ -48,13 +48,13 @@ namespace coreutils {
MString::MString(const ZString &zstring) {
setSize(zstring.getLength());
memcpy(data, zstring.getData(), zstring.getLength());
memcpy(data, zstring.getCursor(), zstring.getLength());
cursor = data;
}
MString::MString(ZString &zstring) {
setSize(zstring.getLength());
memcpy(data, zstring.getData(), zstring.getLength());
memcpy(data, zstring.getCursor(), zstring.getLength());
cursor = data;
}
@@ -66,7 +66,7 @@ namespace coreutils {
MString::MString(MString &mstring) {
setSize(mstring.getLength());
memcpy(data, mstring.getData(), mstring.getLength());
memcpy(data, mstring.getCursor(), mstring.getLength());
cursor = data;
}
@@ -106,16 +106,18 @@ namespace coreutils {
MString &MString::operator=(coreutils::MString value) {
setSize(value.getLength());
memcpy(data, value.getData(), value.getLength());
memcpy(data, value.getCursor(), value.getLength());
length = value.getLength();
cursor = data;
onChange();
return *this;
}
MString &MString::operator=(coreutils::ZString value) {
setSize(value.getLength());
memcpy(data, value.getData(), value.getLength());
memcpy(data, value.getCursor(), value.getLength());
length = value.getLength();
cursor = data;
onChange();
return *this;
}
@@ -124,6 +126,7 @@ namespace coreutils {
setSize(value.length());
memcpy(data, value.c_str(), value.length());
length = value.length();
cursor = data;
onChange();
return *this;
}
@@ -132,6 +135,7 @@ namespace coreutils {
int len = strlen(value);
setSize(len);
memcpy(data, value, len);
cursor = data;
onChange();
return *this;
}
@@ -140,6 +144,7 @@ namespace coreutils {
int len = 1;
setSize(1);
*data = value;
cursor = data;
onChange();
return *this;
}
@@ -195,7 +200,7 @@ namespace coreutils {
int temp = length;
int len = length + zstring.getLength();
setSize(len);
memcpy(data + temp, zstring.getData(), zstring.getLength());
memcpy(data + temp, zstring.getCursor(), zstring.getLength());
onChange();
return *this;
}
@@ -240,7 +245,7 @@ namespace coreutils {
setSize(length + value.getLength());
for (int ix = length; ix >= offset; ix--)
getData()[ix] = getData()[ix - value.getLength()];
std::memcpy(data + offset, value.getData(), value.getLength());
std::memcpy(data + offset, value.getCursor(), value.getLength());
onChange();
}
@@ -261,15 +266,26 @@ namespace coreutils {
}
void MString::remove(int length) {
// Shifts the tail (everything after the removed range) down to close
// the gap. The loop must stop once ix + length reaches the end of the
// valid data - reading cursor[ix + length] past that point is a
// heap-buffer-overflow (confirmed via AddressSanitizer under
// concurrent APIServer load: a completely full MString hit exactly
// this on the final iteration, reading 1 byte past the allocation).
// The old condition `ix < len` let the loop run `length` iterations
// too far.
int len = (data + this->length - cursor);
for (int ix = 0; ix < len; ix++)
for (int ix = 0; ix < len - length; ix++)
cursor[ix] = cursor[ix + length];
setSize(this->length - length);
onChange();
}
void MString::remove(int offset, int length) {
for (int ix = offset; ix < this->length; ix++)
// Same off-by-one as the single-argument overload above - the loop
// must stop once ix + length reaches this->length, not run all the
// way to this->length itself.
for (int ix = offset; ix < this->length - length; ix++)
getData()[ix] = getData()[ix + length];
setSize(this->length - length);
onChange();
@@ -285,7 +301,7 @@ namespace coreutils {
MString &MString::write(ZString value) {
int len = length;
setSize(length + value.getLength());
memcpy(data + len, value.getData(), value.getLength());
memcpy(data + len, value.getCursor(), value.getLength());
onChange();
return *this;
}
@@ -390,7 +406,7 @@ namespace coreutils {
ch1 <<= 4;
ch1 &= 240;
if(eod())
coreutils::Exception("conversion from hex requires even number of characters.");
throw coreutils::Exception("conversion from hex requires even number of characters.");
char ch2 = nextChar();
ch2 -= 48;
if(ch2 > 9)
@@ -432,13 +448,57 @@ namespace coreutils {
MString MString::toCGI() {
push();
reset();
MString target;
while(!eod()) {
char ch = nextChar();
if(ch == ' ') {
target.write('+');
} else if(isalnum((unsigned char)ch) || ch == '-' || ch == '_' || ch == '.' || ch == '~') {
target.write(ch);
} else {
target.write('%');
target.write(hexChar((ch >> 4) & 15));
target.write(hexChar(ch & 15));
}
}
pop();
return target;
}
MString MString::fromCGI() {
push();
reset();
MString target;
while(!eod()) {
char ch = nextChar();
if(ch == '+') {
target.write(' ');
} else if(ch == '%' && !eod()) {
char ch1 = nextChar();
ch1 -= 48;
if(ch1 > 9)
ch1 -= 7;
ch1 <<= 4;
ch1 &= 240;
if(!eod()) {
char ch2 = nextChar();
ch2 -= 48;
if(ch2 > 9)
ch2 -= 7;
ch2 &= 15;
ch1 |= ch2;
target.write(ch1);
} else {
target.write(ch1);
}
} else {
target.write(ch);
}
}
pop();
return target;
}
+9 -7
View File
@@ -1,19 +1,21 @@
#include "Parser.h"
#include "StreamReader.h"
namespace coreutils {
Parser::Parser(int socket) : socket(socket) {}
Parser::Parser(StreamReader &reader) : reader(reader) {}
Parser::~Parser() {}
Status Parser::doParse() {
Parser::Status Parser::doParse() {
Status status;
do {
status = parse();
} while (status == Status::DATA_AVAIL);
return status;
}
bool Parser::checkParse(Parser &parser);
Status Parser::parse() {
return Status::COMPLETE;
bool Parser::checkParse(Parser &parser) {
return parser.doParse() == Status::COMPLETE;
}
}
+44 -34
View File
@@ -1,30 +1,39 @@
#ifndef __Parser_h__
#define __Parser_h__
#include <fstream>
#include <vector>
#include "StreamReader.h"
namespace coreutils {
///
/// Use the StreamReader to read data from a socket and buffer it for use by
/// various stream parsers such as IMFMessage. The reader maintains data
/// consistency regardless of the packet delivery for the stream.
/// Parser is the base class for building a protocol/object parser that reads
/// from a shared StreamReader's buffer. A subclass implements parse() as a
/// resumable state machine (typically a switch on an internal state member)
/// that consumes as much of the buffer as it currently can and reports how
/// the parse should proceed via Status:
///
/// - COMPLETE: the object this Parser builds is fully parsed and ready.
/// - INCOMPLETE: not enough data is currently buffered to make more
/// progress; the caller should wait for more data
/// (StreamReader::feed()) before calling doParse() again.
/// The subclass's state member must reflect exactly where
/// parsing should resume - and must NOT have consumed any
/// cursor position it can't yet commit to (see individual
/// Parser subclasses for how they guarantee this).
/// - DATA_AVAIL: this call made progress and there is more buffered data
/// this Parser can still work through right now, without
/// waiting for new data to arrive.
///
/// Call doParse() (not parse() directly) to drive a Parser - it loops on
/// DATA_AVAIL automatically and returns once the result is COMPLETE or
/// INCOMPLETE.
///
class Parser : public MString {
class Parser {
public:
///
///
///
Parser(int socket);
///
///
///
Parser(StreamReader &reader);
enum class Status {
COMPLETE,
@@ -32,38 +41,39 @@ namespace coreutils {
DATA_AVAIL
};
///
///
///
virtual ~Parser();
///
/// doParse is the entry and re-entry point method to continue the parsing process.
/// doParse is the entry and re-entry point method to continue the
/// parsing process. Safe to call repeatedly (e.g. once per
/// StreamReader::feed()) - each call resumes exactly where the
/// previous one left off.
///
Status doParse();
///
/// Inside of parse() you can call another parser object with the checkParse method to
/// determine if the parsing should branch to the new passed parsing object.
/// Inside of parse() you can call another parser object with the
/// checkParse method to attempt parsing with a candidate sub-parser
/// sharing the same StreamReader. Returns true only once that
/// sub-parser fully completes - retain the same sub-parser instance
/// across re-entries into your own parse() (e.g. as a member) so it
/// can resume, rather than constructing a new one on every call.
///
bool checkParse(Parser &parser); <--- can be called in parse to see if the parsing should branch
///
///
///
virtual Status parse();
bool checkParse(Parser &parser);
protected:
MString buffer;
private:
int socket;
Parser *parser;
vector<Parser *> chain;
///
/// parse() performs one resumable step of parsing against reader's
/// buffer. Must be implemented by every concrete Parser to build its
/// specific object.
///
virtual Status parse() = 0;
StreamReader &reader;
};
+27
View File
@@ -0,0 +1,27 @@
#include "StreamReader.h"
namespace coreutils {
StreamReader::StreamReader() {}
void StreamReader::feed(ZString &data) {
buffer.write(data);
}
MString &StreamReader::getBuffer() {
return buffer;
}
void StreamReader::compact() {
int parsedLength = buffer.getCursor() - buffer.getData();
if (parsedLength > 0) {
buffer.remove(0, parsedLength);
buffer.setCursor(buffer.getData());
}
}
bool StreamReader::hasUnparsedData() {
return !buffer.eod();
}
}
+66
View File
@@ -0,0 +1,66 @@
#ifndef __StreamReader_h__
#define __StreamReader_h__
#include "MString.h"
namespace coreutils {
///
/// StreamReader accumulates data delivered in arbitrary-sized chunks (e.g. from
/// core::Socket::onDataReceived) into one continuous, growable buffer, and exposes
/// it to a chain of Parser objects so they can build higher-level protocol objects
/// (a header, a line, a MIME part, etc.) without needing to worry about where one
/// network packet ended and the next began - a "complete" unit may span any number
/// of feed() calls.
///
/// Parsers consume data through the ZString-style cursor on getBuffer(). Once a
/// Parser has fully consumed a unit (advanced the cursor past it), call compact()
/// to drop the already-parsed prefix so the buffer doesn't grow unboundedly for the
/// life of a long-running connection.
///
class StreamReader {
public:
StreamReader();
///
/// Append newly-arrived data to the end of the buffer. Does not affect the
/// cursor - existing parse position is preserved across a feed().
///
void feed(ZString &data);
///
/// The accumulated buffer Parsers read from and advance the cursor over.
///
MString &getBuffer();
///
/// Drop the already-parsed prefix (everything before the cursor) and reset
/// the cursor to the new start of the buffer. Call this once a Parser has
/// completed a unit and before waiting for more data, so the buffer only
/// ever grows by the amount of not-yet-parsed data.
///
void compact();
///
/// True if there is unparsed data currently sitting in the buffer that a
/// Parser hasn't consumed yet (i.e. more progress may be possible without
/// waiting for the next feed()).
///
bool hasUnparsedData();
private:
MString buffer;
};
}
#endif
+20 -10
View File
@@ -70,11 +70,16 @@ namespace coreutils {
free(cdata);
}
// All four relational operators compare from each side's current cursor position to its
// own true buffer end (data+length), not from data alone - this class is a cursor/view
// over a buffer (see parsed()/unparsed()), so "less than" means "the remaining, unparsed
// content compares less than", consistently across <, <=, >=, and >.
bool ZString::operator<(const ZString &valuex) const {
char *end1 = data + length;
char *end2 = valuex.getData() + valuex.getLength();
char *end2 = valuex.data + valuex.length;
char *cursor1 = cursor;
char *cursor2 = valuex.getCursor();
char *cursor2 = valuex.cursor;
while((cursor1 < end1) && (cursor2 < end2)) {
if(*cursor1 < *cursor2)
return 1;
@@ -90,18 +95,16 @@ namespace coreutils {
return 0;
}
// TODO: Fix the following comparison operators to handle the length problem appropriately.
bool ZString::operator<=(const ZString &valuex) const {
return (strncmp(data, valuex.data, valuex.length <= length ? valuex.length : length) <= 0);
return !(valuex < *this);
}
bool ZString::operator>=(const ZString &valuex) const {
return (strncmp(data, valuex.data, valuex.length <= length ? valuex.length : length) >= 0);
return !(*this < valuex);
}
bool ZString::operator>(const ZString &valuex) const {
return (strncmp(data, valuex.data, valuex.length <= length ? valuex.length : length) > 0);
return (valuex < *this);
}
bool ZString::operator==(const ZString valuex) {
@@ -261,7 +264,12 @@ namespace coreutils {
char *end = data + length;
char *startChar = data + start;
char *endChar = startChar + len;
char newlen = endChar > end ? endChar - end: len;
// Clamp to the remaining valid length (end - startChar) when the requested
// length would overrun the buffer - previously computed endChar - end (the
// overrun amount itself) instead, handing back a length far past what's
// actually there. size_t also fixes a latent overflow for strings > 127
// bytes that the old `char newlen` would have silently wrapped.
size_t newlen = endChar > end ? (size_t)(end - startChar) : (size_t)len;
if(startChar < end)
return ZString(startChar, newlen);
return ZString();
@@ -600,9 +608,11 @@ namespace coreutils {
bool ZString::trimCRLF() {
int len = length;
if (*(data + length - 1) == '\n')
// Guard both checks against an empty string - previously read *(data - 1)
// (one byte before the buffer) when length was already 0.
if ((length > 0) && (*(data + length - 1) == '\n'))
--length;
if (*(data + length - 1) == '\r')
if ((length > 0) && (*(data + length - 1) == '\r'))
--length;
if (cursor >= (data + length))
cursor = data + length;
+1
View File
@@ -4,3 +4,4 @@ g++ -g -std=c++20 -o mstring_test mstring_test.cpp -I.. -L.. -lCoreUtils -lb64
g++ -o jstring_test jstring_test.cpp -I.. -L.. -lCoreUtils
g++ -g -std=c++20 -o mfile_test mfile_test.cpp -I.. -L.. -lCoreUtils
g++ -g -std=c++20 -o jfile_test jfile_test.cpp -I.. -L.. -lCoreUtils
g++ -g -std=c++23 -o http_test http_test.cpp -I.. -L.. -lCoreUtils
+179
View File
@@ -0,0 +1,179 @@
#include <iostream>
#include <cassert>
#include <cstring>
#include <fstream>
#include <sstream>
#include "../StreamReader.h"
#include "../HTTPRequest.h"
#include "../HTTPResponse.h"
using namespace coreutils;
static int checks = 0;
#define CHECK(cond) do { checks++; if(!(cond)) { std::cerr << "FAIL line " << __LINE__ << ": " #cond << std::endl; return 1; } } while(0)
// Feeds a StreamReader one byte at a time and drives a Parser's doParse()
// after every single byte - the harshest fragmentation test used elsewhere
// in this subsystem (see CGIFormData's byte-at-a-time stress test) - to
// prove HTTPRequest is genuinely resumable across arbitrary split points,
// not just "works when handed the whole request at once".
static Parser::Status feedByteAtATime(StreamReader &reader, Parser &parser, const std::string &data) {
Parser::Status status = Parser::Status::INCOMPLETE;
for (size_t i = 0; i < data.size() && status != Parser::Status::COMPLETE; ++i) {
ZString chunk((char *)data.data() + i, 1);
reader.feed(chunk);
status = parser.doParse();
}
return status;
}
int test_get_request_byte_at_a_time() {
StreamReader reader;
HTTPRequest req(reader);
std::string raw =
"GET /hello?x=1&y=two HTTP/1.1\r\n"
"Host: example.com\r\n"
"cookie: session=abc123\r\n"
"\r\n";
CHECK(feedByteAtATime(reader, req, raw) == Parser::Status::COMPLETE);
CHECK(req.getMethod() == "GET");
CHECK(req.getPath() == "/hello");
CHECK(req.getQueryString() == "x=1&y=two");
CHECK(req.getVersion() == "HTTP/1.1");
CHECK(req.getHeader("Host") == "example.com");
// Case-insensitive lookup: header arrived lowercase ("cookie:"), looked
// up with the canonical HTTP capitalization ("Cookie") - real clients
// and servers disagree on casing constantly, this must not care.
CHECK(req.getHeader("Cookie") == "session=abc123");
CHECK(req.getBody().getLength() == 0);
CHECK(req.getFormData() == NULL);
return 0;
}
int test_get_request_no_query_string() {
StreamReader reader;
HTTPRequest req(reader);
std::string raw = "GET /plain HTTP/1.1\r\nHost: h\r\n\r\n";
CHECK(feedByteAtATime(reader, req, raw) == Parser::Status::COMPLETE);
CHECK(req.getPath() == "/plain");
CHECK(req.getQueryString().getLength() == 0);
return 0;
}
int test_post_urlencoded_body_split_across_feeds() {
StreamReader reader;
HTTPRequest req(reader);
std::string raw =
"POST /submit HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Type: application/x-www-form-urlencoded\r\n"
"Content-Length: 14\r\n"
"\r\n"
"name=A%20B&x=1";
// Split mid-body, not just mid-header - the whole point of building this
// on the same StreamReader/checkParse() chain CGIFormData already uses.
size_t splitAt = raw.size() - 5;
ZString part1((char *)raw.data(), splitAt);
reader.feed(part1);
CHECK(req.doParse() == Parser::Status::INCOMPLETE);
ZString part2((char *)raw.data() + splitAt, raw.size() - splitAt);
reader.feed(part2);
CHECK(req.doParse() == Parser::Status::COMPLETE);
CHECK(req.getMethod() == "POST");
CHECK(req.getFormData() != NULL);
MString name = (*req.getFormData())["name"];
CHECK(name == "A B");
MString x = (*req.getFormData())["x"];
CHECK(x == "1");
CHECK(req.getBody().getLength() == 0); // consumed by the form parser, not the raw-body path
return 0;
}
int test_post_raw_json_body() {
StreamReader reader;
HTTPRequest req(reader);
std::string body = "{\"a\":1}";
std::string raw =
"POST /api HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Type: application/json\r\n"
"Content-Length: " + std::to_string(body.size()) + "\r\n"
"\r\n" + body;
CHECK(feedByteAtATime(reader, req, raw) == Parser::Status::COMPLETE);
CHECK(req.getFormData() == NULL);
CHECK(req.getBody() == body.c_str());
return 0;
}
int test_real_fixture_file() {
// testing/http_request.data is a real captured request, but stored with
// plain LF line endings (a text-editing convenience, confirmed via
// `file`/`xxd` - not a literal wire capture); real HTTP requires CRLF
// per RFC 7230, and IMFHeader (which HTTPRequest's HEADERS state reuses
// as-is) enforces that strictly. Normalize LF -> CRLF before feeding,
// same as any real client would actually send it.
std::ifstream in("http_request.data");
CHECK((bool)in);
std::stringstream ss;
ss << in.rdbuf();
std::string raw = ss.str();
std::string crlf;
crlf.reserve(raw.size() + 16);
for (char c : raw) {
if (c == '\n') crlf += '\r';
crlf += c;
}
StreamReader reader;
HTTPRequest req(reader);
CHECK(feedByteAtATime(reader, req, crlf) == Parser::Status::COMPLETE);
CHECK(req.getMethod() == "GET");
CHECK(req.getPath() == "/");
CHECK(req.getHeader("Host") == "localhost:8080");
CHECK(req.getHeader("Cookie") == "_ga=GA1.1.1017526412.1628195401");
return 0;
}
int test_http_response_serialize() {
HTTPResponse resp;
resp.setStatus(200, "OK");
resp.setHeader("Content-Type", "text/plain");
resp.setBody("hello");
MString out = resp.serialize();
std::string s(out.getData(), out.getLength());
CHECK(s.find("HTTP/1.1 200 OK\r\n") == 0);
CHECK(s.find("Content-Type: text/plain\r\n") != std::string::npos);
CHECK(s.find("Content-Length: 5\r\n") != std::string::npos);
CHECK(s.find("\r\n\r\nhello") != std::string::npos);
return 0;
}
int test_http_response_explicit_content_length_respected() {
HTTPResponse resp;
resp.setStatus(404, "Not Found");
resp.setHeader("Content-Length", "0");
resp.setBody("");
MString out = resp.serialize();
std::string s(out.getData(), out.getLength());
CHECK(s.find("HTTP/1.1 404 Not Found\r\n") == 0);
int firstCL = s.find("Content-Length:");
int lastCL = s.rfind("Content-Length:");
CHECK(firstCL == lastCL); // no duplicate Content-Length header
return 0;
}
int main() {
int rc = 0;
rc |= test_get_request_byte_at_a_time();
rc |= test_get_request_no_query_string();
rc |= test_post_urlencoded_body_split_across_feeds();
rc |= test_post_raw_json_body();
rc |= test_real_fixture_file();
rc |= test_http_response_serialize();
rc |= test_http_response_explicit_content_length_respected();
if (rc == 0)
std::cout << "ALL " << checks << " CHECKS PASSED" << std::endl;
else
std::cout << "SOME CHECKS FAILED (see above)" << std::endl;
return rc;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+63 -4
View File
@@ -1,14 +1,73 @@
#include <iostream>
#include "../MString.h"
#include <cassert>
#include <cstring>
#include "../StreamReader.h"
#include "../LineParser.h"
#include "../IMFHeader.h"
#include "../IMFBoundary.h"
int main(int argc, char **argv) {
using namespace coreutils;
coreutils::LineParser line(0);
Parse.Status status = line.doParse();
static int checks = 0;
#define CHECK(cond) do { checks++; if(!(cond)) { std::cerr << "FAIL line " << __LINE__ << ": " #cond << std::endl; return 1; } } while(0)
void feedStr(StreamReader &r, const char *s) {
ZString z((char *)s, strlen(s));
r.feed(z);
}
// The whole point of StreamReader/Parser: a "line" (or header, or boundary)
// can arrive split across any number of socket packets, and parsing must
// resume cleanly from wherever it left off once more data shows up.
int test_lineparser_split_across_feeds() {
StreamReader reader;
feedStr(reader, "partial li");
LineParser lp(reader);
CHECK(lp.doParse() == Parser::Status::INCOMPLETE);
feedStr(reader, "ne\r\n");
CHECK(lp.doParse() == Parser::Status::COMPLETE);
ZString line = lp.getLine();
CHECK(line.getLength() == 12);
CHECK(strncmp(line.getData(), "partial line", 12) == 0);
return 0;
}
int test_imfheader_folding_and_split_feeds() {
StreamReader reader;
IMFHeader header(reader);
feedStr(reader, "Subject: line one\r\n ");
CHECK(header.doParse() == Parser::Status::INCOMPLETE);
feedStr(reader, "line two\r\n\r\n");
CHECK(header.doParse() == Parser::Status::COMPLETE);
auto &fields = header.getHeaders();
CHECK(fields.size() == 1);
MString subj = fields[MString("Subject")];
CHECK(subj.getLength() == 17);
CHECK(strncmp(subj.getData(), "line one line two", subj.getLength()) == 0);
return 0;
}
int test_imfboundary_split_across_feeds() {
ZString b((char *)"XYZ", 3);
StreamReader reader;
IMFBoundary bound(reader, b);
feedStr(reader, "\r\n--X");
CHECK(bound.doParse() == Parser::Status::INCOMPLETE);
feedStr(reader, "YZ--");
CHECK(bound.doParse() == Parser::Status::COMPLETE);
CHECK(bound.isLast() == true);
return 0;
}
int main() {
int rc = 0;
rc |= test_lineparser_split_across_feeds();
rc |= test_imfheader_folding_and_split_feeds();
rc |= test_imfboundary_split_across_feeds();
if (rc == 0)
std::cout << "ALL " << checks << " CHECKS PASSED" << std::endl;
else
std::cout << "SOME CHECKS FAILED (see above)" << std::endl;
return rc;
}