Compare commits
14
Commits
ba85c5f2e5
...
78c45d378c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78c45d378c | ||
|
|
d7057ebb00 | ||
|
|
6b188fbee5 | ||
|
|
cb845efe69 | ||
|
|
6e4e463a96 | ||
|
|
3e6e410fe8 | ||
|
|
5b6d4ea8ab | ||
|
|
bf6810b781 | ||
|
|
a033cc6718 | ||
|
|
94d4a30e88 | ||
|
|
28feaff3d7 | ||
|
|
14697e2af2 | ||
|
|
4082e82466 | ||
|
|
29c9a5b855 |
No files matched your search
@@ -9,3 +9,4 @@ build/
|
|||||||
.history/
|
.history/
|
||||||
testing/mstring_test
|
testing/mstring_test
|
||||||
testing/zstring_test
|
testing/zstring_test
|
||||||
|
testing/http_test
|
||||||
+155
-15
@@ -1,28 +1,168 @@
|
|||||||
#include "CGIFormData.h"
|
#include "CGIFormData.h"
|
||||||
#include "IMFHeader.h"
|
#include "CGIFormattedData.h"
|
||||||
#include "malloc.h"
|
#include "Exception.h"
|
||||||
|
|
||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
CGIFormData::CGIFormData(int fd, ZString contentType, int contentLength, ZString boundary)
|
CGIFormData::CGIFormData(StreamReader &reader, ZString contentType, int contentLength, ZString boundary)
|
||||||
: contentType(contentType) {
|
: Parser(reader), contentType(contentType), contentLength(contentLength), boundary(boundary) {
|
||||||
if(contentType == "application/x-www-form-urlencoded") {
|
if (contentType.startsWith("application/x-www-form-urlencoded"))
|
||||||
setSize(contentLength);
|
mode = URLENCODED;
|
||||||
read(fd, contentLength);
|
else if (contentType.startsWith("multipart/form-data"))
|
||||||
formdata = new CGIFormattedData(*this);
|
mode = MULTIPART;
|
||||||
} else if(contentType == "multipart/form-data") {
|
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) {
|
MString CGIFormData::operator[](ZString name) {
|
||||||
// if(contentType == "application/x-www-form-urlencoded")
|
MString key(name);
|
||||||
// return formdata[name];
|
if (key.find(ZString(":")) == -1) {
|
||||||
MString temp(name);
|
key << ":0";
|
||||||
return temp;
|
}
|
||||||
|
return data[key];
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+66
-10
@@ -1,27 +1,83 @@
|
|||||||
#ifndef __CGIFormData_h__
|
#ifndef __CGIFormData_h__
|
||||||
# define __IMFFormData_h__
|
# define __CGIFormData_h__
|
||||||
|
|
||||||
#include "MString.h"
|
#include "Parser.h"
|
||||||
#include "ZString.h"
|
#include "IMFHeader.h"
|
||||||
#include "CGIFormattedData.h"
|
#include "IMFBoundary.h"
|
||||||
|
#include <map>
|
||||||
|
|
||||||
namespace coreutils {
|
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:
|
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);
|
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:
|
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
|
#endif
|
||||||
|
|
||||||
|
|
||||||
+18
-12
@@ -6,25 +6,31 @@ namespace coreutils {
|
|||||||
CGIFormattedData::CGIFormattedData() {}
|
CGIFormattedData::CGIFormattedData() {}
|
||||||
|
|
||||||
CGIFormattedData::CGIFormattedData(ZString cgiData) {
|
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 != "") {
|
if(cgiData != "") {
|
||||||
cgiData.split("&");
|
cgiData.split(delimiter);
|
||||||
for(int ix = 0; ix < cgiData.getList().size(); ++ix) {
|
for(int ix = 0; ix < cgiData.getList().size(); ++ix) {
|
||||||
cgiData[ix].split("=");
|
ZString pair = cgiData[ix].trim();
|
||||||
data[cgiData[ix][0]] = cgiData[ix][1];
|
pair.split("=");
|
||||||
data[cgiData[ix][0]].fromCGI();
|
data[pair[0]] = pair[1];
|
||||||
|
data[pair[0]] = data[pair[0]].fromCGI();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ZString CGIFormattedData::operator=(ZString cgiData) {
|
ZString CGIFormattedData::operator=(ZString cgiData) {
|
||||||
if(cgiData != "") {
|
parse(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();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return cgiData;
|
return cgiData;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,11 +17,18 @@ namespace coreutils {
|
|||||||
public:
|
public:
|
||||||
CGIFormattedData();
|
CGIFormattedData();
|
||||||
CGIFormattedData(ZString cgiData);
|
CGIFormattedData(ZString cgiData);
|
||||||
|
CGIFormattedData(ZString cgiData, ZString delimiter);
|
||||||
|
|
||||||
ZString operator=(ZString cgiData);
|
ZString operator=(ZString cgiData);
|
||||||
|
void setDelimiter(ZString delimiter);
|
||||||
|
|
||||||
std::map<MString, MString> data;
|
std::map<MString, MString> data;
|
||||||
|
|
||||||
|
private:
|
||||||
|
void parse(ZString cgiData);
|
||||||
|
|
||||||
|
ZString delimiter = "&";
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-1
@@ -4,6 +4,7 @@
|
|||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
|
#include <source_location>
|
||||||
|
|
||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
@@ -15,7 +16,20 @@ namespace coreutils {
|
|||||||
class Exception {
|
class Exception {
|
||||||
|
|
||||||
public:
|
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 className;
|
||||||
std::string file;
|
std::string file;
|
||||||
|
|||||||
@@ -17,19 +17,34 @@ namespace coreutils {
|
|||||||
|
|
||||||
this->fileName = fileName;
|
this->fileName = fileName;
|
||||||
|
|
||||||
struct stat status;
|
|
||||||
stat(fileName.c_str(), &status);
|
|
||||||
|
|
||||||
buffer = NULL;
|
buffer = NULL;
|
||||||
|
|
||||||
setBufferSize(status.st_size);
|
|
||||||
|
|
||||||
fd = ::open(fileName.c_str(), mode, authority);
|
fd = ::open(fileName.c_str(), mode, authority);
|
||||||
if(fd < 0) {
|
if(fd < 0) {
|
||||||
std::stringstream temp;
|
std::stringstream temp;
|
||||||
temp << "Error opening file " << fileName << ".";
|
temp << "Error opening file " << fileName << ".";
|
||||||
throw Exception(temp.str(), __FILE__, __LINE__);
|
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() {
|
File::~File() {
|
||||||
|
|||||||
+127
@@ -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
@@ -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
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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
|
||||||
+36
-17
@@ -1,30 +1,49 @@
|
|||||||
#include "IMFBoundary.h"
|
#include "IMFBoundary.h"
|
||||||
#include "Exception.h"
|
#include "Exception.h"
|
||||||
#include <unistd.h>
|
|
||||||
|
|
||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
IMFBoundary(StreamReader &reader, ZString boundary) : boundary(boundary) {
|
IMFBoundary::IMFBoundary(StreamReader &reader, ZString boundary) : Parser(reader), boundary(boundary) {}
|
||||||
|
|
||||||
|
Parser::Status IMFBoundary::parse() {
|
||||||
|
MString &buffer = reader.getBuffer();
|
||||||
|
switch (state) {
|
||||||
|
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
int IMFBoundary::parse() {
|
case TAIL:
|
||||||
switch(state) {
|
// ZString::getLength() is already cursor-relative (bytes remaining
|
||||||
case PREFIX:
|
// from the cursor to the end) - do not subtract the cursor offset
|
||||||
if(buffer.remaining() > 3)
|
// again here.
|
||||||
if(reader.nextIf("\r\n--"))
|
if (buffer.getLength() < 2)
|
||||||
state = BOUNDARY;
|
return Status::INCOMPLETE;
|
||||||
case BOUNDARY:
|
if (buffer.ifNext(ZString("--"))) {
|
||||||
while(buffer.getTokenInclude(""));
|
last = true;
|
||||||
if(buffer.eod())
|
return Status::COMPLETE;
|
||||||
return 2;
|
}
|
||||||
else if(buffer.remaining() > 1)
|
if (buffer.ifNext(ZString("\r\n"))) {
|
||||||
if(buffer.ifNext("--"))
|
last = false;
|
||||||
state = LAST_BOUNDARY;
|
return Status::COMPLETE;
|
||||||
case LAST_BOUNDARY:
|
}
|
||||||
return 0;
|
throw coreutils::Exception("IMFBoundary: malformed boundary line - expected CRLF or trailing --.");
|
||||||
|
|
||||||
|
}
|
||||||
|
throw coreutils::Exception("IMFBoundary: unreachable state.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool IMFBoundary::isLast() {
|
||||||
|
return last;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+25
-2
@@ -1,20 +1,43 @@
|
|||||||
#ifndef __IMFBoundary_h__
|
#ifndef __IMFBoundary_h__
|
||||||
# define __IMFBoundary_h__
|
# define __IMFBoundary_h__
|
||||||
|
|
||||||
#include "StreamReader.h"
|
|
||||||
#include "Parser.h"
|
#include "Parser.h"
|
||||||
|
|
||||||
namespace coreutils {
|
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 {
|
class IMFBoundary : public Parser {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
IMFBoundary(StreamReader &reader, ZString boundary);
|
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:
|
private:
|
||||||
|
|
||||||
|
enum State { PREFIX, TAIL } state = PREFIX;
|
||||||
ZString boundary;
|
ZString boundary;
|
||||||
|
bool last = false;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+7
-1
@@ -5,7 +5,13 @@
|
|||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
IMFFormData::IMFFormData(int fd, ZString boundary) {
|
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);
|
IMFText text(fd, boundary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,5 +15,3 @@ namespace coreutils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
+68
-19
@@ -1,32 +1,81 @@
|
|||||||
#include "IMFHeader.h"
|
#include "IMFHeader.h"
|
||||||
#include "Exception.h"
|
#include "Exception.h"
|
||||||
#include "Log.h"
|
|
||||||
#include <unistd.h>
|
|
||||||
|
|
||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
IMFHeader::IMFHeader(int fd) {}
|
IMFHeader::IMFHeader(StreamReader &reader) : Parser(reader) {}
|
||||||
|
|
||||||
virtual int parse() {
|
Parser::Status IMFHeader::parse() {
|
||||||
switch(state) {
|
MString &buffer = reader.getBuffer();
|
||||||
case NAME:
|
|
||||||
|
switch (state) {
|
||||||
|
|
||||||
|
case NAME: {
|
||||||
|
if (buffer.eod())
|
||||||
|
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");
|
name << buffer.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-0123456789");
|
||||||
if(buffer.ifNext(":"))
|
if (buffer.eod())
|
||||||
state = FIELD;
|
return Status::INCOMPLETE;
|
||||||
else
|
if (!buffer.ifNext(ZString(":")))
|
||||||
return 2;
|
throw coreutils::Exception("IMFHeader: expected ':' in header name.");
|
||||||
case FIELD:
|
state = SKIP_SPACE;
|
||||||
field << buffer.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-;'\"0123456789");
|
return Status::DATA_AVAIL;
|
||||||
if(!buffer.ifNext("\r\n"))
|
|
||||||
if(buffer.eod())
|
|
||||||
return 2;
|
|
||||||
// Right here is where we should check if next line is an extension to the previous line.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
@@ -1,26 +1,48 @@
|
|||||||
#ifndef __IMFHeader_h__
|
#ifndef __IMFHeader_h__
|
||||||
# define __IMFHeader_h__
|
# define __IMFHeader_h__
|
||||||
|
|
||||||
# include "StreamReader.h"
|
|
||||||
# include "Parser.h"
|
# include "Parser.h"
|
||||||
# include "MString.h"
|
# include "MString.h"
|
||||||
# include "IMFHeaderField.h"
|
# include <map>
|
||||||
# include <vector>
|
|
||||||
|
|
||||||
namespace coreutils {
|
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 {
|
class IMFHeader : public Parser {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
IMFHeader(StreamReader &reader);
|
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:
|
private:
|
||||||
|
|
||||||
|
enum State { NAME, SKIP_SPACE, FIELD, FOLD_CHECK } state = NAME;
|
||||||
MString name;
|
MString name;
|
||||||
MString field;
|
MString field;
|
||||||
std::map<MString, MString> headers;
|
std::map<MString, MString> headers;
|
||||||
|
|
||||||
|
void commitField();
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,5 +7,6 @@
|
|||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
IMFMessage::IMFMessage(int fd) {}
|
IMFMessage::IMFMessage(int fd) {}
|
||||||
|
IMFMessage::~IMFMessage() {}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -4,7 +4,34 @@
|
|||||||
|
|
||||||
namespace coreutils {
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
+516
-100
@@ -1,5 +1,7 @@
|
|||||||
#include "JString.h"
|
#include "JString.h"
|
||||||
#include "Exception.h"
|
#include "Exception.h"
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
|
||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
@@ -10,140 +12,537 @@ namespace coreutils {
|
|||||||
return os;
|
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("{}") {}
|
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();
|
reset();
|
||||||
if(locate(path)) {
|
if (!locate(path))
|
||||||
push();
|
return JSONType::NOT_FOUND;
|
||||||
if(ifNext("\"")) {
|
return typeAtCursor();
|
||||||
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.");
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
// std::cout << "[" << unparsed() << "] >" << value << "<" << std::endl;
|
bool JString::exists(ZString path) {
|
||||||
MString key;
|
return getType(path) != JSONType::NOT_FOUND;
|
||||||
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::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) {
|
ZString JString::find(ZString path) {
|
||||||
reset();
|
reset();
|
||||||
if(locate(path)) {
|
return findRelative(path);
|
||||||
if(ifNext("\""))
|
|
||||||
return getTokenExclude("\"");
|
|
||||||
// TODO: Handle numbers that are not in double quotes.
|
|
||||||
|
|
||||||
else if(startsWith("["))
|
|
||||||
return getContainer();
|
|
||||||
|
|
||||||
else if(startsWith("{"))
|
|
||||||
return getContainer();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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();
|
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) {
|
bool JString::locate(ZString path) {
|
||||||
// std::cout << "path locate: " << path << std::endl;
|
|
||||||
path.getTokenExclude("[.");
|
path.getTokenExclude("[.");
|
||||||
notfirst = false;
|
notfirst = false;
|
||||||
if(ifNext("{")) {
|
if (ifNext("{")) {
|
||||||
while(startsWith("\"")) {
|
while (startsWith("\"")) {
|
||||||
notfirst = true;
|
notfirst = true;
|
||||||
ZString label;
|
ZString label;
|
||||||
ZString value;
|
if (ifNext("\"")) {
|
||||||
if(ifNext("\"")) {
|
|
||||||
label = getTokenExclude("\"");
|
label = getTokenExclude("\"");
|
||||||
ifNext("\"");
|
ifNext("\"");
|
||||||
} else
|
} else
|
||||||
throw coreutils::Exception("Labels must be contained in double quotes.");
|
throw coreutils::Exception("Labels must be contained in double quotes.");
|
||||||
if(ifNext(":")) {
|
if (ifNext(":")) {
|
||||||
// std::cout << "path: (" << path.parsed() << ") (" << label << ") " << (label == path.parsed()) << std::endl;
|
if (label == path.parsed()) {
|
||||||
if(label == path.parsed()) {
|
if (path.unparsed() == "") {
|
||||||
if(path.unparsed() == "") {
|
|
||||||
// std::cout << "found cursor: " << unparsed() << std::endl;
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if(path.ifNext("."))
|
if (path.ifNext("."))
|
||||||
return locate(path.unparsed());
|
return locate(path.unparsed());
|
||||||
if(path.ifNext("[")) {
|
if (path.ifNext("[")) {
|
||||||
|
bool found = true;
|
||||||
|
if (path.startsWithNumber()) {
|
||||||
|
// Numeric index: label[N]
|
||||||
int index = path.asInteger();
|
int index = path.asInteger();
|
||||||
if(!path.ifNext("]"))
|
if (!path.ifNext("]"))
|
||||||
throw coreutils::Exception("expecting ] after index value in array selector.");
|
throw coreutils::Exception("expecting ] after index value in array selector.");
|
||||||
if(ifNext("[")) {
|
if (!ifNext("["))
|
||||||
while(index > 0) {
|
throw coreutils::Exception("Path is expecting an array for selector value.");
|
||||||
getContainer();
|
while (index > 0) {
|
||||||
if(!ifNext(","))
|
skipValue();
|
||||||
|
if (!ifNext(","))
|
||||||
throw coreutils::Exception("expecting comma to seperate array elements.");
|
throw coreutils::Exception("expecting comma to seperate array elements.");
|
||||||
--index;
|
--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.");
|
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;
|
return false;
|
||||||
else if(path.ifNext("."))
|
if (path.eod())
|
||||||
|
return true;
|
||||||
|
if (path.ifNext("."))
|
||||||
return locate(path.unparsed());
|
return locate(path.unparsed());
|
||||||
throw coreutils::Exception("expecting '.' in path.");
|
throw coreutils::Exception("expecting '.' in path.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// std::cout << "+++" << unparsed() << std::endl;
|
skipValue();
|
||||||
if(startsWith("\"")) {
|
|
||||||
getContainer();
|
|
||||||
} else if(startsWith("[")) {
|
|
||||||
getContainer();
|
|
||||||
} else if(startsWith("{")) {
|
|
||||||
getContainer();
|
|
||||||
} else {
|
|
||||||
throw coreutils::Exception("Unrecognized data type.");
|
|
||||||
}
|
|
||||||
ifNext(",");
|
ifNext(",");
|
||||||
} else
|
} else
|
||||||
throw coreutils::Exception("Expected colon after label.");
|
throw coreutils::Exception("Expected colon after label.");
|
||||||
}
|
}
|
||||||
} else if(ifNext("[")) {
|
} else if (ifNext("[")) {
|
||||||
ZString label = path[0].getTokenExclude("[");
|
ZString label = path.getTokenExclude("[");
|
||||||
path.ifNext("[");
|
path.ifNext("[");
|
||||||
ZString key = path[0].getTokenExclude("=");
|
ZString key = path.getTokenExclude("=");
|
||||||
path.ifNext("=");
|
path.ifNext("=");
|
||||||
ZString value = path[0].getTokenExclude("]");
|
ZString value = path.getTokenExclude("]");
|
||||||
while(!ifNext("]")) {
|
while (!ifNext("]")) {
|
||||||
push();
|
push();
|
||||||
ZString check = find(key);
|
ZString check = findRelative(key);
|
||||||
pop();
|
pop();
|
||||||
if(check.equals(value)) {
|
if (check.equals(value)) {
|
||||||
return locate(label);
|
return locate(label);
|
||||||
} else {
|
} else {
|
||||||
getContainer();
|
skipValue();
|
||||||
ifNext(",");
|
ifNext(",");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// std::cout << "not found cursor: " << unparsed() << std::endl;
|
|
||||||
return false;
|
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) {
|
JString & JString::operator=(coreutils:: ZString value) {
|
||||||
setSize(value.getLength());
|
setSize(value.getLength());
|
||||||
memcpy(data, value.getData(), value.getLength());
|
memcpy(data, value.getData(), value.getLength());
|
||||||
@@ -153,17 +552,17 @@ namespace coreutils {
|
|||||||
|
|
||||||
void JString::removeWhitespace() {
|
void JString::removeWhitespace() {
|
||||||
reset();
|
reset();
|
||||||
while(!eod()) {
|
while (!eod()) {
|
||||||
if(*cursor == ' ')
|
if (*cursor == ' ')
|
||||||
remove(1);
|
remove(1);
|
||||||
else if(*cursor == '\r')
|
else if (*cursor == '\r')
|
||||||
remove(1);
|
remove(1);
|
||||||
else if(*cursor == '\t')
|
else if (*cursor == '\t')
|
||||||
remove(1);
|
remove(1);
|
||||||
else if(*cursor == '\n')
|
else if (*cursor == '\n')
|
||||||
remove(1);
|
remove(1);
|
||||||
else if(startsWith("\""))
|
else if (startsWith("\""))
|
||||||
getContainer();
|
skipString();
|
||||||
else
|
else
|
||||||
++cursor;
|
++cursor;
|
||||||
}
|
}
|
||||||
@@ -175,42 +574,59 @@ namespace coreutils {
|
|||||||
reset();
|
reset();
|
||||||
char ch;
|
char ch;
|
||||||
int index = 0;
|
int index = 0;
|
||||||
while(!eod()) {
|
while (!eod()) {
|
||||||
ch = nextChar();
|
ch = nextChar();
|
||||||
if(ch == '{') {
|
if (ch == '{') {
|
||||||
index += 3;
|
index += 3;
|
||||||
output << ch << '\n';
|
output << ch << '\n';
|
||||||
for(int ix = 0; ix < index; ++ix)
|
for (int ix = 0; ix < index; ++ix)
|
||||||
output << ' ';
|
output << ' ';
|
||||||
}
|
}
|
||||||
else if(ch == '[') {
|
else if (ch == '[') {
|
||||||
index += 3;
|
index += 3;
|
||||||
output << ch << '\n';
|
output << ch << '\n';
|
||||||
for(int ix = 0; ix < index; ++ix)
|
for (int ix = 0; ix < index; ++ix)
|
||||||
output << ' ';
|
output << ' ';
|
||||||
}
|
}
|
||||||
else if(ch == ':') {
|
else if (ch == ':') {
|
||||||
output << ": ";
|
output << ": ";
|
||||||
}
|
}
|
||||||
else if(ch == '}') {
|
else if (ch == '}') {
|
||||||
index -= 3;
|
index -= 3;
|
||||||
output << '\n';
|
output << '\n';
|
||||||
for(int ix = 0; ix < index; ++ix)
|
for (int ix = 0; ix < index; ++ix)
|
||||||
output << ' ';
|
output << ' ';
|
||||||
output << ch;
|
output << ch;
|
||||||
}
|
}
|
||||||
else if(ch == ']') {
|
else if (ch == ']') {
|
||||||
index -= 3;
|
index -= 3;
|
||||||
output << '\n';
|
output << '\n';
|
||||||
for(int ix = 0; ix < index; ++ix)
|
for (int ix = 0; ix < index; ++ix)
|
||||||
output << ' ';
|
output << ' ';
|
||||||
output << ch;
|
output << ch;
|
||||||
}
|
}
|
||||||
else if(ch == ',') {
|
else if (ch == ',') {
|
||||||
output << ch << '\n';
|
output << ch << '\n';
|
||||||
for(int ix = 0; ix < index; ++ix)
|
for (int ix = 0; ix < index; ++ix)
|
||||||
output << ' ';
|
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
|
else
|
||||||
output << ch;
|
output << ch;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ namespace coreutils {
|
|||||||
/// access the objects elements using a named path as the index to the items.
|
/// access the objects elements using a named path as the index to the items.
|
||||||
///
|
///
|
||||||
/// JString default constructor will create an empty JString object pointing
|
/// 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
|
/// Use a constructor or assignment operator to initialize a JString to an
|
||||||
/// initial JSON string.
|
/// initial JSON string.
|
||||||
@@ -23,10 +23,30 @@ namespace coreutils {
|
|||||||
/// object to initialize the JSON string. On destruction the file is saved back.
|
/// 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.
|
/// The [] operator can be used to access elements within the JSON string.
|
||||||
/// Use:
|
/// Assigning a value dispatches on the C++ type of the right-hand side, so the
|
||||||
/// jstring["key"] = "value";
|
/// resulting JSON is correctly typed rather than always being a quoted string:
|
||||||
/// std::cout << jstring["key"];
|
|
||||||
///
|
///
|
||||||
|
/// 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 {
|
class JString : virtual public MString {
|
||||||
|
|
||||||
@@ -36,10 +56,24 @@ namespace coreutils {
|
|||||||
|
|
||||||
void set(ZString &path, ZString &value);
|
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
|
/// 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
|
/// 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);
|
ZString find(ZString path);
|
||||||
@@ -48,6 +82,34 @@ namespace coreutils {
|
|||||||
bool notfirst;
|
bool notfirst;
|
||||||
ZString path;
|
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 {
|
class Proxy {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
@@ -55,6 +117,23 @@ namespace coreutils {
|
|||||||
|
|
||||||
friend std::ostream &operator<<(std::ostream &os, const Proxy &proxy);
|
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 () {
|
operator coreutils::ZString () {
|
||||||
return jstring.find(key);
|
return jstring.find(key);
|
||||||
}
|
}
|
||||||
@@ -64,15 +143,53 @@ namespace coreutils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
operator std::string () {
|
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) {
|
Proxy& operator=(coreutils::MString value) {
|
||||||
jstring.set(key, value);
|
jstring.setString(key, value.str());
|
||||||
jstring.changed(key, value);
|
jstring.changed(key, value);
|
||||||
return *this;
|
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:
|
private:
|
||||||
JString &jstring;
|
JString &jstring;
|
||||||
ZString key;
|
ZString key;
|
||||||
@@ -88,9 +205,38 @@ namespace coreutils {
|
|||||||
|
|
||||||
virtual void changed(ZString key, ZString value);
|
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();
|
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
@@ -1,18 +1,26 @@
|
|||||||
#include "LineParser.h"
|
#include "LineParser.h"
|
||||||
#include "Exception.h"
|
|
||||||
#include <unistd.h>
|
|
||||||
|
|
||||||
namespace coreutils {
|
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
@@ -1,17 +1,39 @@
|
|||||||
#ifndef __LineParser_h__
|
#ifndef __LineParser_h__
|
||||||
# define __LineParser_h__
|
# define __LineParser_h__
|
||||||
|
|
||||||
#include "StreamReader.h"
|
|
||||||
#include "Parser.h"
|
#include "Parser.h"
|
||||||
|
|
||||||
namespace coreutils {
|
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 {
|
class LineParser : public Parser {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
LineParser(StreamReader &reader);
|
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
@@ -48,13 +48,13 @@ namespace coreutils {
|
|||||||
|
|
||||||
MString::MString(const ZString &zstring) {
|
MString::MString(const ZString &zstring) {
|
||||||
setSize(zstring.getLength());
|
setSize(zstring.getLength());
|
||||||
memcpy(data, zstring.getData(), zstring.getLength());
|
memcpy(data, zstring.getCursor(), zstring.getLength());
|
||||||
cursor = data;
|
cursor = data;
|
||||||
}
|
}
|
||||||
|
|
||||||
MString::MString(ZString &zstring) {
|
MString::MString(ZString &zstring) {
|
||||||
setSize(zstring.getLength());
|
setSize(zstring.getLength());
|
||||||
memcpy(data, zstring.getData(), zstring.getLength());
|
memcpy(data, zstring.getCursor(), zstring.getLength());
|
||||||
cursor = data;
|
cursor = data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +66,7 @@ namespace coreutils {
|
|||||||
|
|
||||||
MString::MString(MString &mstring) {
|
MString::MString(MString &mstring) {
|
||||||
setSize(mstring.getLength());
|
setSize(mstring.getLength());
|
||||||
memcpy(data, mstring.getData(), mstring.getLength());
|
memcpy(data, mstring.getCursor(), mstring.getLength());
|
||||||
cursor = data;
|
cursor = data;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,16 +106,18 @@ namespace coreutils {
|
|||||||
|
|
||||||
MString &MString::operator=(coreutils::MString value) {
|
MString &MString::operator=(coreutils::MString value) {
|
||||||
setSize(value.getLength());
|
setSize(value.getLength());
|
||||||
memcpy(data, value.getData(), value.getLength());
|
memcpy(data, value.getCursor(), value.getLength());
|
||||||
length = value.getLength();
|
length = value.getLength();
|
||||||
|
cursor = data;
|
||||||
onChange();
|
onChange();
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
MString &MString::operator=(coreutils::ZString value) {
|
MString &MString::operator=(coreutils::ZString value) {
|
||||||
setSize(value.getLength());
|
setSize(value.getLength());
|
||||||
memcpy(data, value.getData(), value.getLength());
|
memcpy(data, value.getCursor(), value.getLength());
|
||||||
length = value.getLength();
|
length = value.getLength();
|
||||||
|
cursor = data;
|
||||||
onChange();
|
onChange();
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
@@ -124,6 +126,7 @@ namespace coreutils {
|
|||||||
setSize(value.length());
|
setSize(value.length());
|
||||||
memcpy(data, value.c_str(), value.length());
|
memcpy(data, value.c_str(), value.length());
|
||||||
length = value.length();
|
length = value.length();
|
||||||
|
cursor = data;
|
||||||
onChange();
|
onChange();
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
@@ -132,6 +135,7 @@ namespace coreutils {
|
|||||||
int len = strlen(value);
|
int len = strlen(value);
|
||||||
setSize(len);
|
setSize(len);
|
||||||
memcpy(data, value, len);
|
memcpy(data, value, len);
|
||||||
|
cursor = data;
|
||||||
onChange();
|
onChange();
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
@@ -140,6 +144,7 @@ namespace coreutils {
|
|||||||
int len = 1;
|
int len = 1;
|
||||||
setSize(1);
|
setSize(1);
|
||||||
*data = value;
|
*data = value;
|
||||||
|
cursor = data;
|
||||||
onChange();
|
onChange();
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
@@ -195,7 +200,7 @@ namespace coreutils {
|
|||||||
int temp = length;
|
int temp = length;
|
||||||
int len = length + zstring.getLength();
|
int len = length + zstring.getLength();
|
||||||
setSize(len);
|
setSize(len);
|
||||||
memcpy(data + temp, zstring.getData(), zstring.getLength());
|
memcpy(data + temp, zstring.getCursor(), zstring.getLength());
|
||||||
onChange();
|
onChange();
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
@@ -240,7 +245,7 @@ namespace coreutils {
|
|||||||
setSize(length + value.getLength());
|
setSize(length + value.getLength());
|
||||||
for (int ix = length; ix >= offset; ix--)
|
for (int ix = length; ix >= offset; ix--)
|
||||||
getData()[ix] = getData()[ix - value.getLength()];
|
getData()[ix] = getData()[ix - value.getLength()];
|
||||||
std::memcpy(data + offset, value.getData(), value.getLength());
|
std::memcpy(data + offset, value.getCursor(), value.getLength());
|
||||||
onChange();
|
onChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,15 +266,26 @@ namespace coreutils {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void MString::remove(int length) {
|
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);
|
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];
|
cursor[ix] = cursor[ix + length];
|
||||||
setSize(this->length - length);
|
setSize(this->length - length);
|
||||||
onChange();
|
onChange();
|
||||||
}
|
}
|
||||||
|
|
||||||
void MString::remove(int offset, int length) {
|
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];
|
getData()[ix] = getData()[ix + length];
|
||||||
setSize(this->length - length);
|
setSize(this->length - length);
|
||||||
onChange();
|
onChange();
|
||||||
@@ -285,7 +301,7 @@ namespace coreutils {
|
|||||||
MString &MString::write(ZString value) {
|
MString &MString::write(ZString value) {
|
||||||
int len = length;
|
int len = length;
|
||||||
setSize(length + value.getLength());
|
setSize(length + value.getLength());
|
||||||
memcpy(data + len, value.getData(), value.getLength());
|
memcpy(data + len, value.getCursor(), value.getLength());
|
||||||
onChange();
|
onChange();
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
@@ -390,7 +406,7 @@ namespace coreutils {
|
|||||||
ch1 <<= 4;
|
ch1 <<= 4;
|
||||||
ch1 &= 240;
|
ch1 &= 240;
|
||||||
if(eod())
|
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();
|
char ch2 = nextChar();
|
||||||
ch2 -= 48;
|
ch2 -= 48;
|
||||||
if(ch2 > 9)
|
if(ch2 > 9)
|
||||||
@@ -432,13 +448,57 @@ namespace coreutils {
|
|||||||
|
|
||||||
|
|
||||||
MString MString::toCGI() {
|
MString MString::toCGI() {
|
||||||
|
push();
|
||||||
|
reset();
|
||||||
MString target;
|
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;
|
return target;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
MString MString::fromCGI() {
|
MString MString::fromCGI() {
|
||||||
|
push();
|
||||||
|
reset();
|
||||||
MString target;
|
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;
|
return target;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+9
-7
@@ -1,19 +1,21 @@
|
|||||||
#include "Parser.h"
|
#include "Parser.h"
|
||||||
#include "StreamReader.h"
|
|
||||||
|
|
||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
Parser::Parser(int socket) : socket(socket) {}
|
Parser::Parser(StreamReader &reader) : reader(reader) {}
|
||||||
|
|
||||||
Parser::~Parser() {}
|
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);
|
bool Parser::checkParse(Parser &parser) {
|
||||||
|
return parser.doParse() == Status::COMPLETE;
|
||||||
Status Parser::parse() {
|
|
||||||
return Status::COMPLETE;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -1,30 +1,39 @@
|
|||||||
#ifndef __Parser_h__
|
#ifndef __Parser_h__
|
||||||
#define __Parser_h__
|
#define __Parser_h__
|
||||||
|
|
||||||
#include <fstream>
|
#include "StreamReader.h"
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace coreutils {
|
namespace coreutils {
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Use the StreamReader to read data from a socket and buffer it for use by
|
/// Parser is the base class for building a protocol/object parser that reads
|
||||||
/// various stream parsers such as IMFMessage. The reader maintains data
|
/// from a shared StreamReader's buffer. A subclass implements parse() as a
|
||||||
/// consistency regardless of the packet delivery for the stream.
|
/// 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:
|
public:
|
||||||
|
|
||||||
///
|
Parser(StreamReader &reader);
|
||||||
///
|
|
||||||
///
|
|
||||||
|
|
||||||
Parser(int socket);
|
|
||||||
|
|
||||||
///
|
|
||||||
///
|
|
||||||
///
|
|
||||||
|
|
||||||
enum class Status {
|
enum class Status {
|
||||||
COMPLETE,
|
COMPLETE,
|
||||||
@@ -32,38 +41,39 @@ namespace coreutils {
|
|||||||
DATA_AVAIL
|
DATA_AVAIL
|
||||||
};
|
};
|
||||||
|
|
||||||
///
|
|
||||||
///
|
|
||||||
///
|
|
||||||
|
|
||||||
virtual ~Parser();
|
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();
|
Status doParse();
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Inside of parse() you can call another parser object with the checkParse method to
|
/// Inside of parse() you can call another parser object with the
|
||||||
/// determine if the parsing should branch to the new passed parsing object.
|
/// 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
|
bool checkParse(Parser &parser);
|
||||||
|
|
||||||
///
|
|
||||||
///
|
|
||||||
///
|
|
||||||
|
|
||||||
virtual Status parse();
|
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
MString buffer;
|
|
||||||
|
|
||||||
private:
|
///
|
||||||
int socket;
|
/// parse() performs one resumable step of parsing against reader's
|
||||||
Parser *parser;
|
/// buffer. Must be implemented by every concrete Parser to build its
|
||||||
vector<Parser *> chain;
|
/// specific object.
|
||||||
|
///
|
||||||
|
|
||||||
|
virtual Status parse() = 0;
|
||||||
|
|
||||||
|
StreamReader &reader;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -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
@@ -70,11 +70,16 @@ namespace coreutils {
|
|||||||
free(cdata);
|
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 {
|
bool ZString::operator<(const ZString &valuex) const {
|
||||||
char *end1 = data + length;
|
char *end1 = data + length;
|
||||||
char *end2 = valuex.getData() + valuex.getLength();
|
char *end2 = valuex.data + valuex.length;
|
||||||
char *cursor1 = cursor;
|
char *cursor1 = cursor;
|
||||||
char *cursor2 = valuex.getCursor();
|
char *cursor2 = valuex.cursor;
|
||||||
while((cursor1 < end1) && (cursor2 < end2)) {
|
while((cursor1 < end1) && (cursor2 < end2)) {
|
||||||
if(*cursor1 < *cursor2)
|
if(*cursor1 < *cursor2)
|
||||||
return 1;
|
return 1;
|
||||||
@@ -90,18 +95,16 @@ namespace coreutils {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Fix the following comparison operators to handle the length problem appropriately.
|
|
||||||
|
|
||||||
bool ZString::operator<=(const ZString &valuex) const {
|
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 {
|
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 {
|
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) {
|
bool ZString::operator==(const ZString valuex) {
|
||||||
@@ -261,7 +264,12 @@ namespace coreutils {
|
|||||||
char *end = data + length;
|
char *end = data + length;
|
||||||
char *startChar = data + start;
|
char *startChar = data + start;
|
||||||
char *endChar = startChar + len;
|
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)
|
if(startChar < end)
|
||||||
return ZString(startChar, newlen);
|
return ZString(startChar, newlen);
|
||||||
return ZString();
|
return ZString();
|
||||||
@@ -600,9 +608,11 @@ namespace coreutils {
|
|||||||
|
|
||||||
bool ZString::trimCRLF() {
|
bool ZString::trimCRLF() {
|
||||||
int len = length;
|
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;
|
--length;
|
||||||
if (*(data + length - 1) == '\r')
|
if ((length > 0) && (*(data + length - 1) == '\r'))
|
||||||
--length;
|
--length;
|
||||||
if (cursor >= (data + length))
|
if (cursor >= (data + length))
|
||||||
cursor = data + length;
|
cursor = data + length;
|
||||||
|
|||||||
@@ -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++ -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 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++20 -o jfile_test jfile_test.cpp -I.. -L.. -lCoreUtils
|
||||||
|
g++ -g -std=c++23 -o http_test http_test.cpp -I.. -L.. -lCoreUtils
|
||||||
@@ -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
@@ -1,14 +1,73 @@
|
|||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include "../MString.h"
|
#include <cassert>
|
||||||
|
#include <cstring>
|
||||||
|
#include "../StreamReader.h"
|
||||||
#include "../LineParser.h"
|
#include "../LineParser.h"
|
||||||
|
#include "../IMFHeader.h"
|
||||||
|
#include "../IMFBoundary.h"
|
||||||
|
|
||||||
int main(int argc, char **argv) {
|
using namespace coreutils;
|
||||||
|
|
||||||
coreutils::LineParser line(0);
|
static int checks = 0;
|
||||||
Parse.Status status = line.doParse();
|
#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;
|
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;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user