Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2847ce5fa7 | ||
|
|
fd81bb877f | ||
|
|
cfdb3cbf57 | ||
|
|
3c6411c16e | ||
|
|
a18d1358b0 | ||
|
|
9fae14eb96 | ||
|
|
ec3e40b71a | ||
|
|
5f9a53aba2 | ||
|
|
fdcb2b43a9 | ||
|
|
08462ca996 | ||
|
|
867ace3cb3 | ||
|
|
b8f7793773 | ||
|
|
905fbafa5a | ||
|
|
9d965bfd1a | ||
|
|
46ef67b735 | ||
|
|
41fbf0b7d9 | ||
|
|
dcfe2a667c | ||
|
|
c1491b044b | ||
|
|
b0cadc3f08 | ||
|
|
54b6e522f9 | ||
|
|
7893746582 | ||
|
|
b276bdb6cc | ||
|
|
7f6ebb0ea8 | ||
|
|
8b2391b289 | ||
|
|
5c703f5620 | ||
|
|
97142ce9b4 | ||
|
|
9f3349b671 | ||
|
|
8483618012 | ||
|
|
a7dab09150 | ||
|
|
76ea89e79c | ||
|
|
bc3c50f045 | ||
|
|
942d2641ab | ||
|
|
fde94acad6 | ||
|
|
b143b821de | ||
|
|
80a939d1ef | ||
|
|
7b4a25f305 | ||
|
|
b1c275182a | ||
|
|
9bbb95cc57 | ||
|
|
3f273b0a95 | ||
|
|
634eb7a9a9 | ||
|
|
a32444acc2 | ||
|
|
6ac33601a0 | ||
|
|
aaed4cb4da | ||
|
|
f33c041ae5 | ||
|
|
a94fc5e8fb | ||
|
|
d52ca61250 | ||
|
|
fc849c44a4 | ||
|
|
6f2f3d7339 | ||
|
|
51133e0c76 | ||
|
|
2d9505cd33 | ||
|
|
d0f2551e89 | ||
|
|
e6ebb34366 | ||
|
|
3bd9ea124f | ||
|
|
ac0865d2da | ||
|
|
7e835e5073 | ||
|
|
8b38617b00 | ||
|
|
50a29a4238 | ||
|
|
db59e9e87c | ||
|
|
3f14b28435 | ||
|
|
a91d78f524 | ||
|
|
61216a2296 | ||
|
|
63916cc32a | ||
|
|
5e0523619d | ||
|
|
3314a410e0 | ||
|
|
c21f27f14d | ||
|
|
4e47d6aaf7 | ||
|
|
e6bee9b67b |
No files matched your search
@@ -1,4 +1,39 @@
|
||||
*.o
|
||||
*~
|
||||
jet-2.0
|
||||
docs/JetCore.aux
|
||||
docs/JetCore.dvi
|
||||
docs/JetCore.log
|
||||
docs/JetCore.toc
|
||||
|
||||
# jetc build byproducts (compiled JET-to-C++ output, binaries, .jtc/.a artifacts).
|
||||
# Generated .cpp files are always named "*.compiled.cpp" (see build-compiled.sh/
|
||||
# build-shared.sh) - deliberately not a blanket "*.cpp", which would also
|
||||
# swallow real source files added to jetc/ later (bit us once already: an
|
||||
# earlier blanket rule silently hid api_test.cpp from git status).
|
||||
jetc/jetc
|
||||
jetc/demo
|
||||
jetc/demo2
|
||||
jetc/demo3
|
||||
jetc/host_test
|
||||
jetc/api_test
|
||||
jetc/demo.cpp
|
||||
jetc/demo2.cpp
|
||||
jetc/demo4
|
||||
jetc/demo5
|
||||
jetc/demo6
|
||||
jetc/demo7
|
||||
jetc/*.compiled.cpp
|
||||
jetc/*.pic.o
|
||||
jetc/*.jtc
|
||||
jetc/libCoreUtils_pic.a
|
||||
|
||||
# These 3 pages' converted output bakes in a real barant.com DB password
|
||||
# (via BARANT_DB_PASSWORD at conversion time - see convert.py's MYSQL_PAGES
|
||||
# handling) so they never enter git history, unlike the rest of
|
||||
# jetc/barant-site/jet/, which is plain static content and safe to commit.
|
||||
jetc/barant-site/jet/vst.jet
|
||||
jetc/barant-site/jet/modular1.jet
|
||||
jetc/barant-site/jet/modular1_patches.jet
|
||||
jetc/**/*.jtc
|
||||
jetc/__pycache__/
|
||||
@@ -1,17 +1,24 @@
|
||||
#include "Global.h"
|
||||
#include "Exception.h"
|
||||
#include "__mysql.h"
|
||||
#include "__imap.h"
|
||||
#include <iostream>
|
||||
#include <stdlib.h>
|
||||
#include <cstdio>
|
||||
|
||||
namespace jet {
|
||||
|
||||
Global::Global(char **envp) : envp(envp) {
|
||||
|
||||
cookies.setDelimiter(";");
|
||||
}
|
||||
|
||||
Global::~Global() {
|
||||
|
||||
// JFile's destructor (via MFile::~MFile()->update()) is what actually
|
||||
// writes the session JSON back to disk - it has to run for session
|
||||
// persistence to happen at all, so sessionFile can't be left as a
|
||||
// leaked, never-deleted pointer the way cgiData currently is.
|
||||
if(sessionFile)
|
||||
delete sessionFile;
|
||||
}
|
||||
|
||||
void Global::dump() {
|
||||
@@ -25,7 +32,7 @@ namespace jet {
|
||||
|
||||
void Global::addSession(coreutils::MString sessionId, __mysql *mysql) {
|
||||
if(sessionExists(sessionId))
|
||||
coreutils::Exception("sessionid already exists.");
|
||||
throw coreutils::Exception("sessionid already exists.");
|
||||
sessions[sessionId] = mysql;
|
||||
}
|
||||
|
||||
@@ -39,6 +46,26 @@ namespace jet {
|
||||
return sessions[sessionId];
|
||||
}
|
||||
|
||||
bool Global::imapSessionExists(coreutils::MString sessionId) {
|
||||
return imapSessions.find(sessionId) != imapSessions.end();
|
||||
}
|
||||
|
||||
void Global::addImapSession(coreutils::MString sessionId, __imap *imap) {
|
||||
if(imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid already exists.");
|
||||
imapSessions[sessionId] = imap;
|
||||
}
|
||||
|
||||
void Global::removeImapSession(coreutils::MString sessionId) {
|
||||
imapSessions.erase(sessionId);
|
||||
}
|
||||
|
||||
__imap * Global::getImapSession(coreutils::MString sessionId) {
|
||||
if(imapSessions.find(sessionId) == imapSessions.end())
|
||||
throw coreutils::Exception("requested imap session is not available.");
|
||||
return imapSessions[sessionId];
|
||||
}
|
||||
|
||||
coreutils::ZString Global::getSessionVariable(coreutils::MString &splitName) {
|
||||
if(sessions.find(splitName[0]) == sessions.end())
|
||||
throw coreutils::Exception("requested session is not available in variable.");
|
||||
@@ -56,55 +83,4 @@ namespace jet {
|
||||
}
|
||||
}
|
||||
|
||||
void Global::setupFormData(coreutils::ZString &formdata) {
|
||||
coreutils::ZString boundary = formdata.goeol();
|
||||
while(!formdata.eod()) {
|
||||
if(formdata.ifNext("Content-Disposition: form-data;")) {
|
||||
formdata.skipWhitespace();
|
||||
if(formdata.ifNext("name=\"")) {
|
||||
coreutils::ZString name = formdata.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-");
|
||||
if(formdata.ifNext("\"")) {
|
||||
formdata.goeol();
|
||||
formdata.goeol();
|
||||
coreutils::ZString data = formdata.getTokenExclude("-"); // TODO: Fix this parsing. Need a string exclusion method to check for 'boundary'.
|
||||
data.trimCRLF();
|
||||
formdata.ifNext(boundary);
|
||||
int index = 0;
|
||||
coreutils::MString namex;
|
||||
do {
|
||||
namex = "";
|
||||
namex << name << ":" << index++;
|
||||
} while(cgiVariables.count(namex) != 0);
|
||||
cgiVariables[namex] = data;
|
||||
if(formdata.ifNext("--"))
|
||||
break;
|
||||
formdata.goeol();
|
||||
}
|
||||
else
|
||||
throw coreutils::Exception("expecting closing double quote on variable name in received CGI data.");
|
||||
} else
|
||||
throw coreutils::Exception("expecting name subfield in received CGI data.");
|
||||
} else
|
||||
throw coreutils::Exception("expecting Content-Disposition header in received CGI data.");
|
||||
}
|
||||
}
|
||||
|
||||
void Global::setupFormURLEncoded(coreutils::ZString &formdata) {
|
||||
while(!formdata.eod()) {
|
||||
coreutils::ZString name = formdata.getTokenInclude("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-");
|
||||
if(formdata.ifNext("=")) {
|
||||
coreutils::MString data = formdata.getTokenExclude("&");
|
||||
formdata.ifNext("&");
|
||||
int index = 0;
|
||||
coreutils::MString namex;
|
||||
do {
|
||||
namex = "";
|
||||
namex << name << ":" << index++;
|
||||
} while(cgiVariables.count(namex) != 0);
|
||||
cgiVariables[namex] = data.fromCGI();
|
||||
} else
|
||||
throw coreutils::Exception("expecting = after name in received CGI data.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,12 +3,17 @@
|
||||
|
||||
# include "MString.h"
|
||||
# include "CGIFormattedData.h"
|
||||
# include "CGIFormData.h"
|
||||
# include "StreamReader.h"
|
||||
# include "JFile.h"
|
||||
# include <map>
|
||||
|
||||
namespace jet {
|
||||
|
||||
class __mysql;
|
||||
|
||||
class __imap;
|
||||
class Tag;
|
||||
|
||||
class Global {
|
||||
|
||||
public:
|
||||
@@ -20,6 +25,10 @@ namespace jet {
|
||||
void addSession(coreutils::MString sessionId, __mysql *mysql);
|
||||
void removeSession(coreutils::MString sessionId);
|
||||
__mysql * getSession(coreutils::MString sessionId);
|
||||
bool imapSessionExists(coreutils::MString sessionId);
|
||||
void addImapSession(coreutils::MString sessionId, __imap *imap);
|
||||
void removeImapSession(coreutils::MString sessionId);
|
||||
__imap * getImapSession(coreutils::MString sessionId);
|
||||
coreutils::ZString getSessionVariable(coreutils::MString &splitName);
|
||||
void outputHeaders();
|
||||
void setupFormData(coreutils::ZString &formdata);
|
||||
@@ -27,15 +36,57 @@ namespace jet {
|
||||
char *errorCursor = NULL;
|
||||
|
||||
coreutils::CGIFormattedData cookies;
|
||||
|
||||
///
|
||||
/// cgiReader backs cgiData below - it must outlive it, since
|
||||
/// CGIFormData (a Parser) only holds a reference to it, not its own
|
||||
/// copy of the request body. Declared before cgiData so it's
|
||||
/// constructed first and destroyed last (member destruction order
|
||||
/// mirrors declaration order).
|
||||
///
|
||||
|
||||
coreutils::StreamReader cgiReader;
|
||||
coreutils::CGIFormData *cgiData = NULL;
|
||||
|
||||
///
|
||||
/// sessionFile backs $[@name] (read) and <set name="@name" .../>
|
||||
/// (write) - a JSON file at sessiondir/<sessionId>.json, loaded when
|
||||
/// opened and saved automatically when destroyed (JFile/MFile's own
|
||||
/// RAII behavior - see MFile.cpp). NULL unless cgi mode and the
|
||||
/// sessiondir keyword are both active for this request.
|
||||
///
|
||||
|
||||
coreutils::JFile *sessionFile = NULL;
|
||||
std::map<coreutils::MString, coreutils::MString> variables;
|
||||
std::map<coreutils::MString, coreutils::MString> cgiVariables;
|
||||
std::map<coreutils::MString, __mysql *> sessions;
|
||||
std::map<coreutils::MString, coreutils::MString> headers;
|
||||
std::map<coreutils::MString, coreutils::MString> tags;
|
||||
|
||||
// Populated once per compiled .jtc module's own entry function (see
|
||||
// jetc's TAGDEF codegen) - a top-level <tag name="X"> definition
|
||||
// that jetc could compile directly registers its own render
|
||||
// function here under its lowercase name, same key convention as
|
||||
// `tags` above. __dotag checks this first before falling back to
|
||||
// the text-based findTagDefinition()/processContainer() path (see
|
||||
// __dotag.cpp), avoiding a full re-parse of the definition's body
|
||||
// on every invocation. A miss here (a locally-scoped/nested tag
|
||||
// definition, or content that was never compiled at all) is always
|
||||
// safe - it just means the existing interpreted path runs exactly
|
||||
// as it always has; this is a pure additive fast path, never a
|
||||
// replacement for `tags`, which every TAGDEF still populates too.
|
||||
std::map<coreutils::MString, void(*)(Tag&, coreutils::MString&)> compiledTags;
|
||||
|
||||
char **envp;
|
||||
bool cgi = false;
|
||||
bool session = false;
|
||||
coreutils::MString sessionId;
|
||||
|
||||
// Deliberately the LAST member declared in Global - appended
|
||||
// here, after every pre-existing field, rather than inserted
|
||||
// earlier among them, so this addition does not shift the
|
||||
// memory offset of any field that existed before it. See
|
||||
// __imap.h for what registers here.
|
||||
std::map<coreutils::MString, __imap *> imapSessions;
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -6,29 +6,96 @@
|
||||
#include <time.h>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
#include <random>
|
||||
|
||||
namespace jet {
|
||||
|
||||
Operand::Operand(coreutils::ZString &in, Tag &tag) {
|
||||
Operand::Operand(coreutils::ZString &in, Tag &tag, bool stop) : in(in), tag(tag) {
|
||||
|
||||
doubleValue = 0;
|
||||
|
||||
|
||||
in.skipWhitespace();
|
||||
|
||||
|
||||
if(in.startsWith("$[") || in.startsWith("#[")) {
|
||||
string = tag.getVariable(in);
|
||||
doubleValue = string.asDouble();
|
||||
isNumber = string.eod();
|
||||
string.reset();
|
||||
if((string == "false") || (string == "true"))
|
||||
boolean = true;
|
||||
boolean = (string == "true");
|
||||
} else if(in.ifNext("(")) {
|
||||
Operand op(in, tag);
|
||||
string = op.string;
|
||||
doubleValue = op.doubleValue;
|
||||
isNumber = op.isNumber;
|
||||
// A parenthesized sub-expression's own comparison result was never
|
||||
// propagated to the wrapping Operand - only string/doubleValue/
|
||||
// isNumber were copied, leaving this Operand's own `boolean`
|
||||
// genuinely uninitialized (Operand.h declares it with no default
|
||||
// value). Confirmed via debug tracing: printed as garbage stack
|
||||
// bytes, which "and"/"or" then combined instead of the real
|
||||
// true/false result.
|
||||
boolean = op.boolean;
|
||||
if(!in.ifNext(")"))
|
||||
throw coreutils::Exception("expected ) in expression.");
|
||||
} else if(in.ifNextIgnoreCase("SUBSTRING_INDEX")) {
|
||||
// MySQL SUBSTRING_INDEX(str, delim, count): with a positive count,
|
||||
// returns everything before the count-th occurrence of delim
|
||||
// (counting from the left); with a negative count, everything
|
||||
// after the |count|-th occurrence (counting from the right). If
|
||||
// delim doesn't occur that many times, the whole string is
|
||||
// returned unchanged. Genuinely missing (like LOCATE was) - real
|
||||
// content (index2.cgi's own URI-parsing logic, ported as part of
|
||||
// the /var/www/barant jet-2.0 conversion) relies on it to peel a
|
||||
// path apart one segment at a time:
|
||||
// substring_index(substring_index('$[REQUEST_URI]','?',1),'/',2).
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for SUBSTRING_INDEX parameters.");
|
||||
Operand parm1(in, tag);
|
||||
if(!in.ifNext(","))
|
||||
throw coreutils::Exception("Expecting , in SUBSTRING_INDEX expression.");
|
||||
Operand parm2(in, tag);
|
||||
if(!in.ifNext(","))
|
||||
throw coreutils::Exception("Expecting , in SUBSTRING_INDEX expression.");
|
||||
Operand parm3(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
coreutils::MString haystack = parm1.string;
|
||||
haystack.reset();
|
||||
coreutils::MString delim = parm2.string;
|
||||
delim.reset();
|
||||
int count = parm3.string.asInteger();
|
||||
int delimLen = (int)delim.getLength();
|
||||
std::vector<int> positions;
|
||||
if(delimLen > 0) {
|
||||
int base = 0;
|
||||
while(true) {
|
||||
coreutils::MString scan = haystack.substring(base);
|
||||
scan.reset();
|
||||
int pos = scan.find(delim);
|
||||
if(pos == -1) break;
|
||||
positions.push_back(base + pos);
|
||||
base += pos + delimLen;
|
||||
}
|
||||
}
|
||||
if(count >= 0) {
|
||||
size_t n = (size_t)count;
|
||||
if(n == 0 || positions.size() < n) {
|
||||
string = haystack.substring(0);
|
||||
} else {
|
||||
string = haystack.substring(0, positions[n - 1]);
|
||||
}
|
||||
} else {
|
||||
size_t n = (size_t)(-count);
|
||||
if(positions.size() < n) {
|
||||
string = haystack.substring(0);
|
||||
} else {
|
||||
int idx = positions[positions.size() - n];
|
||||
string = haystack.substring(idx + delimLen);
|
||||
}
|
||||
}
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of SUBSTRING_INDEX expression.");
|
||||
} else if(in.ifNextIgnoreCase("SUBSTRING")) {
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for SUBSTRING parameters.");
|
||||
@@ -38,13 +105,78 @@ namespace jet {
|
||||
Operand parm2(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
string = parm1.string.substring(parm2.string.asInteger());
|
||||
} else if(!in.ifNext(","))
|
||||
} else {
|
||||
// Real, pre-existing bug fixed here: the 3-arg-only branch below
|
||||
// used to run unconditionally (missing braces around this
|
||||
// else-if), so even after the 2-arg form above already
|
||||
// succeeded, it fell through into trying to parse a third
|
||||
// argument from whatever was left (nothing, since the closing
|
||||
// ")" was already consumed) - always throwing "operand is not
|
||||
// valid." right after computing the correct 2-arg result.
|
||||
// Confirmed via real debug tracing showing an extra Operand
|
||||
// constructed on empty input immediately after a successful
|
||||
// 2-arg substring(str, start) call - the 2-arg form was
|
||||
// completely unusable before this fix.
|
||||
if(!in.ifNext(","))
|
||||
throw coreutils::Exception("Expecting , in SUBSTRING expression.");
|
||||
Operand parm3(in, tag);
|
||||
Operand parm3(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
string = parm1.string.substring(parm2.string.asInteger(), parm3.string.asInteger());
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of substring expression.");
|
||||
}
|
||||
} else if(in.ifNextIgnoreCase("LOCATE")) {
|
||||
// MySQL-style LOCATE(needle, haystack): 1-based position of the
|
||||
// first occurrence of needle within haystack, or 0 if not found -
|
||||
// a genuinely missing function (like <eval> was a genuinely
|
||||
// missing tag). Real 1.4 content depends on it for exactly this
|
||||
// "is #[name] present in the space-padded $[errfield] list"
|
||||
// pattern (barant.tag's own <field> definition:
|
||||
// locate(' #[name] ','$[errfield]') != 0), used throughout for
|
||||
// marking a field's input as erroring after a failed validation.
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for LOCATE parameters.");
|
||||
Operand parm1(in, tag);
|
||||
if(!in.ifNext(","))
|
||||
throw coreutils::Exception("Expecting , in LOCATE expression.");
|
||||
Operand parm2(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
string = parm1.string.substring(parm2.string.asInteger(), parm3.string.asInteger());
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of substring expression.");
|
||||
coreutils::MString haystack = parm2.string;
|
||||
haystack.reset();
|
||||
int pos = haystack.find(parm1.string);
|
||||
doubleValue = (pos == -1) ? 0 : (pos + 1);
|
||||
isNumber = true;
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
string.removeTrailingZeros();
|
||||
} else {
|
||||
// Optional 3rd start_pos argument (MySQL LOCATE(substr, str,
|
||||
// pos)): search begins at the given 1-based position instead of
|
||||
// the start of the string. Needed by index2.cgi's own real
|
||||
// URI-parsing logic (walking a path one '/' at a time), ported
|
||||
// as part of the /var/www/barant jet-2.0 conversion.
|
||||
if(!in.ifNext(","))
|
||||
throw coreutils::Exception("Expecting , in LOCATE expression.");
|
||||
Operand parm3(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
coreutils::MString haystack = parm2.string;
|
||||
haystack.reset();
|
||||
int totalLen = (int)haystack.getLength();
|
||||
int startPos = parm3.string.asInteger() - 1;
|
||||
if(startPos < 0) startPos = 0;
|
||||
if(startPos >= totalLen) {
|
||||
doubleValue = 0;
|
||||
} else {
|
||||
coreutils::MString sub = haystack.substring(startPos);
|
||||
sub.reset();
|
||||
int pos = sub.find(parm1.string);
|
||||
doubleValue = (pos == -1) ? 0 : (startPos + pos + 1);
|
||||
}
|
||||
isNumber = true;
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
string.removeTrailingZeros();
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of LOCATE expression.");
|
||||
}
|
||||
} else if(in.ifNextIgnoreCase("LEFT")) {
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for LEFT parameters.");
|
||||
@@ -64,6 +196,11 @@ namespace jet {
|
||||
Operand op(parm1.string, tag);
|
||||
string = op.string;
|
||||
isNumber = op.isNumber;
|
||||
if(isNumber) {
|
||||
doubleValue = op.doubleValue;
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
string.removeTrailingZeros();
|
||||
}
|
||||
boolean = op.boolean;
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of EXPR expression.");
|
||||
@@ -88,7 +225,37 @@ namespace jet {
|
||||
if(in.ifNext(")")) {
|
||||
string = parm1.string.trim();
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of TRIM expression.");
|
||||
throw coreutils::Exception("Expecting ) at end of TRIM expression.");
|
||||
} else if(in.ifNextIgnoreCase("LTRIM")) {
|
||||
// Leading blanks only - the same characters TRIM removes (space,
|
||||
// tab, newline).
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for LTRIM parameters.");
|
||||
Operand parm1(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
const char *data = parm1.string.getData();
|
||||
int len = parm1.string.getLength();
|
||||
int start = 0;
|
||||
while((start < len) && ((data[start] == ' ') || (data[start] == '\t') || (data[start] == '\n')))
|
||||
++start;
|
||||
string = parm1.string.substring(start, len - start);
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of LTRIM expression.");
|
||||
} else if(in.ifNextIgnoreCase("RTRIM")) {
|
||||
// Trailing blanks only. Counted by index rather than with
|
||||
// trimTrailingWhitespace(), which stops one character short and
|
||||
// would leave " " for an all-blank value.
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for RTRIM parameters.");
|
||||
Operand parm1(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
const char *data = parm1.string.getData();
|
||||
int len = parm1.string.getLength();
|
||||
while((len > 0) && ((data[len - 1] == ' ') || (data[len - 1] == '\t') || (data[len - 1] == '\n')))
|
||||
--len;
|
||||
string = parm1.string.substring(0, len);
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of RTRIM expression.");
|
||||
} else if(in.ifNextIgnoreCase("TOUPPER")) {
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for TOUPPER parameters.");
|
||||
@@ -106,9 +273,26 @@ namespace jet {
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of TOLOWER expression.");
|
||||
} else if(in.ifNextIgnoreCase("REVERSE")) {
|
||||
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for REVERSE parameters.");
|
||||
Operand parm1(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
std::string reversed = parm1.string.str();
|
||||
std::reverse(reversed.begin(), reversed.end());
|
||||
string = reversed;
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of REVERSE expression.");
|
||||
} else if(in.ifNextIgnoreCase("CONCAT")) {
|
||||
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for CONCAT parameters.");
|
||||
Operand parm1(in, tag);
|
||||
string = parm1.string;
|
||||
while(in.ifNext(",")) {
|
||||
Operand parm(in, tag);
|
||||
string << parm.string;
|
||||
}
|
||||
if(!in.ifNext(")"))
|
||||
throw coreutils::Exception("Expecting ) at end of CONCAT expression.");
|
||||
} else if(in.ifNextIgnoreCase("INTEGER")) {
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for INTEGER parameters.");
|
||||
@@ -146,9 +330,63 @@ namespace jet {
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of ABS expression.");
|
||||
} else if(in.ifNextIgnoreCase("MAX")) {
|
||||
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for MAX parameters.");
|
||||
Operand *parm = new Operand(in, tag);
|
||||
string = parm->string;
|
||||
doubleValue = parm->doubleValue;
|
||||
isNumber = parm->isNumber;
|
||||
delete parm;
|
||||
while(in.ifNext(",")) {
|
||||
parm = new Operand(in, tag);
|
||||
if(isNumber != parm->isNumber)
|
||||
throw coreutils::Exception("All parameters in MAX expression must be same type.");
|
||||
if(isNumber) {
|
||||
if(parm->doubleValue > doubleValue) {
|
||||
doubleValue = parm->doubleValue;
|
||||
string = parm->string;
|
||||
}
|
||||
} else {
|
||||
if(parm->string > string) {
|
||||
doubleValue = parm->doubleValue;
|
||||
string = parm->string;
|
||||
}
|
||||
}
|
||||
delete parm;
|
||||
}
|
||||
if(!in.ifNext(")")) {
|
||||
throw coreutils::Exception("Expecting ) at end of MAX expression.");
|
||||
}
|
||||
string.removeTrailingZeros();
|
||||
} else if(in.ifNextIgnoreCase("MIN")) {
|
||||
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for MIN parameters.");
|
||||
Operand *parm = new Operand(in, tag);
|
||||
string = parm->string;
|
||||
doubleValue = parm->doubleValue;
|
||||
isNumber = parm->isNumber;
|
||||
delete parm;
|
||||
while(in.ifNext(",")) {
|
||||
parm = new Operand(in, tag);
|
||||
if(isNumber != parm->isNumber)
|
||||
throw coreutils::Exception("All parameters in MIN expression must be same type.");
|
||||
if(isNumber) {
|
||||
if(parm->doubleValue < doubleValue) {
|
||||
doubleValue = parm->doubleValue;
|
||||
string = parm->string;
|
||||
}
|
||||
} else {
|
||||
if(parm->string < string) {
|
||||
doubleValue = parm->doubleValue;
|
||||
string = parm->string;
|
||||
}
|
||||
}
|
||||
delete parm;
|
||||
}
|
||||
if(!in.ifNext(")")) {
|
||||
throw coreutils::Exception("Expecting ) at end of MIN expression.");
|
||||
}
|
||||
string.removeTrailingZeros();
|
||||
} else if(in.ifNextIgnoreCase("POW")) {
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for POW parameters.");
|
||||
@@ -274,10 +512,31 @@ namespace jet {
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of TRUNC expression.");
|
||||
} else if(in.ifNextIgnoreCase("CEIL")) {
|
||||
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for CEIL parameters.");
|
||||
Operand parm1(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
doubleValue = ceil(parm1.doubleValue);
|
||||
isNumber = true;
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
string.removeTrailingZeros();
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of CEIL expression.");
|
||||
} else if(in.ifNextIgnoreCase("FLOOR")) {
|
||||
|
||||
} else if(in.ifNextIgnoreCase("UNIXTIME")) {
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for FLOOR parameters.");
|
||||
Operand parm1(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
doubleValue = floor(parm1.doubleValue);
|
||||
isNumber = true;
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
string.removeTrailingZeros();
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of FLOOR expression.");
|
||||
} else if(in.ifNextIgnoreCase("UNIXTIME") || in.ifNextIgnoreCase("UNIX_TIMESTAMP")) {
|
||||
// Real content (cart.page's own <set expr="unix_timestamp()">)
|
||||
// calls MySQL's real function name, not this codebase's own
|
||||
// "UNIXTIME" - same value, just accept both spellings.
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for UNIXTIME.");
|
||||
if(in.ifNext(")")) {
|
||||
@@ -287,7 +546,91 @@ namespace jet {
|
||||
int unixtime = seconds_since_epoch.count();
|
||||
string << unixtime;
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of UNIXTIME.");
|
||||
throw coreutils::Exception("Expecting ) at end of UNIXTIME.");
|
||||
}
|
||||
else if(in.ifNextIgnoreCase("NOW")) {
|
||||
// MySQL's now() - real content (SESSIONCTL.tag's own
|
||||
// createsession definition: <set name="_timestamp" expr="now()">,
|
||||
// embedded directly into a DATETIME column via a raw SQL literal:
|
||||
// timestamp='$[_timestamp]') expects a MySQL DATETIME-formatted
|
||||
// string ("YYYY-MM-DD HH:MM:SS"), not a Unix timestamp (that's
|
||||
// UNIX_TIMESTAMP, just above).
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for NOW.");
|
||||
if(in.ifNext(")")) {
|
||||
std::time_t t = std::time(nullptr);
|
||||
std::tm tmVal;
|
||||
gmtime_r(&t, &tmVal);
|
||||
char buf[32];
|
||||
std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tmVal);
|
||||
string = buf;
|
||||
isNumber = false;
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of NOW.");
|
||||
}
|
||||
else if(in.ifNextIgnoreCase("UUID")) {
|
||||
// MySQL's uuid() - real content (SESSIONCTL.tag's own
|
||||
// createsession definition: <set name="_uuid" expr="uuid()">)
|
||||
// uses this to mint a new session id, stored as sessions.uuid and
|
||||
// handed back to the browser as the _session_id cookie. A real
|
||||
// random (v4) UUID, not MySQL's actual v1 (time+MAC-derived)
|
||||
// algorithm - the schema only ever treats this as an opaque
|
||||
// unique string, nothing depends on v1's specific bit layout.
|
||||
// Seeded from std::random_device (real entropy), not RANDOM's
|
||||
// existing clock()-seeded rand_r() above - this value doubles as
|
||||
// a session token, so it needs to be unguessable, not just unique.
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for UUID.");
|
||||
if(in.ifNext(")")) {
|
||||
static thread_local std::mt19937_64 rng(std::random_device{}());
|
||||
std::uniform_int_distribution<int> hexDigit(0, 15);
|
||||
const char *hex = "0123456789abcdef";
|
||||
char buf[37];
|
||||
int p = 0;
|
||||
for(int i = 0; i < 36; i++) {
|
||||
if(i == 8 || i == 13 || i == 18 || i == 23) { buf[p++] = '-'; continue; }
|
||||
int v;
|
||||
if(i == 14) v = 4; // version 4
|
||||
else if(i == 19) v = 8 + hexDigit(rng) % 4; // variant 10xx
|
||||
else v = hexDigit(rng);
|
||||
buf[p++] = hex[v];
|
||||
}
|
||||
buf[p] = '\0';
|
||||
string = buf;
|
||||
isNumber = false;
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of UUID.");
|
||||
}
|
||||
else if(in.ifNextIgnoreCase("DATEDIFF")) {
|
||||
if(!in.ifNext("("))
|
||||
throw coreutils::Exception("Expecting ( for DATEDIFF.");
|
||||
Operand parm1(in, tag);
|
||||
if(!in.ifNext(","))
|
||||
throw coreutils::Exception("Expecting , in DATEDIFF expression.");
|
||||
Operand parm2(in, tag);
|
||||
if(in.ifNext(")")) {
|
||||
// Matches MySQL's DATEDIFF(expr1, expr2): expr1 - expr2 expressed
|
||||
// as a whole number of days, ignoring any time-of-day component.
|
||||
// Dates are parsed as YYYY-MM-DD (a leading date portion of a
|
||||
// longer "YYYY-MM-DD HH:MM:SS" value parses fine too, since
|
||||
// strptime only consumes what the format string asks for) and
|
||||
// interpreted as UTC via timegm() (not mktime(), which is
|
||||
// local-timezone-dependent) so the result doesn't shift with the
|
||||
// server's own timezone setting.
|
||||
struct tm tm1 = {};
|
||||
struct tm tm2 = {};
|
||||
if(!strptime(parm1.string.c_str(), "%Y-%m-%d", &tm1))
|
||||
throw coreutils::Exception("DATEDIFF: first argument is not a valid date (expected YYYY-MM-DD).");
|
||||
if(!strptime(parm2.string.c_str(), "%Y-%m-%d", &tm2))
|
||||
throw coreutils::Exception("DATEDIFF: second argument is not a valid date (expected YYYY-MM-DD).");
|
||||
time_t t1 = timegm(&tm1);
|
||||
time_t t2 = timegm(&tm2);
|
||||
doubleValue = difftime(t1, t2) / 86400.0;
|
||||
isNumber = true;
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
string.removeTrailingZeros();
|
||||
} else
|
||||
throw coreutils::Exception("Expecting ) at end of DATEDIFF expression.");
|
||||
} else if(in.ifNextIgnoreCase("true")) {
|
||||
boolean = true;
|
||||
string = "true";
|
||||
@@ -299,14 +642,33 @@ namespace jet {
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
isNumber = true;
|
||||
} else if(in.ifNext("'")) {
|
||||
string = in.getTokenExclude("'");
|
||||
coreutils::MString raw = in.getTokenExclude("'");
|
||||
in.ifNext("'");
|
||||
coreutils::MString resolved;
|
||||
raw.reset();
|
||||
while(!raw.eod()) {
|
||||
if(raw.startsWith("$[") || raw.startsWith("#["))
|
||||
resolved.write(tag.getVariable(raw));
|
||||
else {
|
||||
resolved.write(raw.charAt(0));
|
||||
raw.nextChar();
|
||||
}
|
||||
}
|
||||
string = resolved;
|
||||
isNumber = false;
|
||||
} else
|
||||
throw coreutils::Exception("operand is not valid.");
|
||||
|
||||
in.skipWhitespace();
|
||||
|
||||
if(!stop)
|
||||
parseOperator();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
int Operand::parseOperator() {
|
||||
|
||||
if(in.ifNext("!=") || in.ifNext("<>")) {
|
||||
Operand op(in, tag);
|
||||
if(isNumber && op.isNumber) {
|
||||
@@ -451,6 +813,8 @@ namespace jet {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if(in.ifNext("+")) {
|
||||
if(isNumber) {
|
||||
Operand op(in, tag);
|
||||
@@ -475,28 +839,42 @@ namespace jet {
|
||||
throw coreutils::Exception("operand is not a number.");
|
||||
} else if(in.ifNext("*")) {
|
||||
if(isNumber) {
|
||||
Operand op(in, tag);
|
||||
Operand op(in, tag, true);
|
||||
if(op.isNumber) {
|
||||
doubleValue *= op.doubleValue;
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
string.removeTrailingZeros();
|
||||
parseOperator();
|
||||
} else
|
||||
throw coreutils::Exception("operand is not a number.");
|
||||
} else
|
||||
throw coreutils::Exception("operand is not a number.");
|
||||
} else if(in.ifNext("/")) {
|
||||
if(isNumber) {
|
||||
Operand op(in, tag);
|
||||
Operand op(in, tag, true);
|
||||
if(op.isNumber) {
|
||||
doubleValue /= op.doubleValue;
|
||||
string = std::format("{:.12f}", doubleValue);
|
||||
string.removeTrailingZeros();
|
||||
parseOperator();
|
||||
} else
|
||||
throw coreutils::Exception("operand is not a number.");
|
||||
} else
|
||||
throw coreutils::Exception("operand is not a number.");
|
||||
} else
|
||||
return;
|
||||
}
|
||||
in.skipWhitespace();
|
||||
if(in.ifNextIgnoreCase("and")) {
|
||||
Operand op(in, tag);
|
||||
boolean = boolean && op.boolean;
|
||||
isNumber = false;
|
||||
string = boolean ? "true" : "false";
|
||||
} else if(in.ifNextIgnoreCase("or")) {
|
||||
Operand op(in, tag);
|
||||
boolean = boolean || op.boolean;
|
||||
isNumber = false;
|
||||
string = boolean ? "true" : "false";
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -10,8 +10,11 @@ namespace jet {
|
||||
class Operand {
|
||||
|
||||
public:
|
||||
Operand(coreutils::ZString &in, Tag &tag);
|
||||
Operand(coreutils::ZString &in, Tag &tag, bool stop = false);
|
||||
|
||||
coreutils::ZString ∈
|
||||
Tag &tag;
|
||||
|
||||
bool isNumber;
|
||||
|
||||
///
|
||||
@@ -23,6 +26,8 @@ namespace jet {
|
||||
coreutils::MString string = "";
|
||||
|
||||
double doubleValue;
|
||||
|
||||
int parseOperator();
|
||||
|
||||
|
||||
};
|
||||
|
||||
@@ -1,17 +1,28 @@
|
||||
#include "SessionId.h"
|
||||
#include <openssl/ssl.h>
|
||||
#include "Exception.h"
|
||||
#include <openssl/rand.h>
|
||||
|
||||
namespace jet {
|
||||
|
||||
// Previously SHA1("JETSESSION" + time(0)) - deterministic and
|
||||
// guessable from the wall-clock second alone (two sessions started in
|
||||
// the same second got the IDENTICAL id, and an attacker doesn't even
|
||||
// need a collision - the whole value is computable from a public,
|
||||
// narrow-range input). Confirmed via a real test: two separate
|
||||
// jet-2.0 runs with no cookie, back to back, produced the same
|
||||
// "fresh" session id. Replaced with 20 bytes straight from OpenSSL's
|
||||
// CSPRNG - RAND_bytes() is already available via libcrypto, which
|
||||
// every jet-2.0/jetc build already links against for other reasons.
|
||||
SessionId::SessionId() {
|
||||
unsigned char hashit[64];
|
||||
unsigned char hash[SHA_DIGEST_LENGTH];
|
||||
setSize(64);
|
||||
sprintf((char *)hashit, "JETSESSION%ld", time(0));
|
||||
SHA1(hashit, strlen((char *)hashit), hash);
|
||||
unsigned char randomBytes[20];
|
||||
if(RAND_bytes(randomBytes, sizeof(randomBytes)) != 1)
|
||||
throw coreutils::Exception("failed to generate a random session id.");
|
||||
setSize(40);
|
||||
sprintf(getData(), "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
|
||||
hash[0], hash[1], hash[2], hash[3], hash[4], hash[5], hash[6], hash[7], hash[8], hash[9],
|
||||
hash[10], hash[11], hash[12], hash[13], hash[14], hash[15], hash[16], hash[17], hash[18], hash[19]);
|
||||
randomBytes[0], randomBytes[1], randomBytes[2], randomBytes[3], randomBytes[4],
|
||||
randomBytes[5], randomBytes[6], randomBytes[7], randomBytes[8], randomBytes[9],
|
||||
randomBytes[10], randomBytes[11], randomBytes[12], randomBytes[13], randomBytes[14],
|
||||
randomBytes[15], randomBytes[16], randomBytes[17], randomBytes[18], randomBytes[19]);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
#include "SqlBind.h"
|
||||
#include "Exception.h"
|
||||
#include <cctype>
|
||||
|
||||
namespace jet {
|
||||
|
||||
namespace {
|
||||
|
||||
std::string lower(std::string s) {
|
||||
for(char &c : s) c = (char)std::tolower((unsigned char)c);
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string trim(const std::string &s) {
|
||||
size_t b = 0, e = s.size();
|
||||
while(b < e && std::isspace((unsigned char)s[b])) ++b;
|
||||
while(e > b && std::isspace((unsigned char)s[e - 1])) --e;
|
||||
return s.substr(b, e - b);
|
||||
}
|
||||
|
||||
std::string where(int position) {
|
||||
return "bind " + std::to_string(position) + ": ";
|
||||
}
|
||||
|
||||
bool allDigits(const std::string &s, size_t from, size_t to) {
|
||||
if(from >= to) return false;
|
||||
for(size_t i = from; i < to; ++i)
|
||||
if(!std::isdigit((unsigned char)s[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ^-?[0-9]{1,maxDigits}$
|
||||
bool isInteger(const std::string &s, size_t maxDigits) {
|
||||
size_t start = (!s.empty() && s[0] == '-') ? 1 : 0;
|
||||
size_t digits = s.size() - start;
|
||||
return digits >= 1 && digits <= maxDigits && allDigits(s, start, s.size());
|
||||
}
|
||||
|
||||
// ^-?[0-9]{1,30}(\.[0-9]{1,30})?$
|
||||
bool isDecimal(const std::string &s) {
|
||||
size_t dot = s.find('.');
|
||||
if(dot == std::string::npos) return isInteger(s, 30);
|
||||
std::string frac = s.substr(dot + 1);
|
||||
return isInteger(s.substr(0, dot), 30) && frac.size() >= 1 && frac.size() <= 30 && allDigits(frac, 0, frac.size());
|
||||
}
|
||||
|
||||
int num(const std::string &s, size_t at, size_t len) {
|
||||
return std::stoi(s.substr(at, len));
|
||||
}
|
||||
|
||||
// YYYY-MM-DD with a real month and day range.
|
||||
bool isDate(const std::string &s) {
|
||||
if(s.size() != 10 || s[4] != '-' || s[7] != '-') return false;
|
||||
if(!allDigits(s, 0, 4) || !allDigits(s, 5, 7) || !allDigits(s, 8, 10)) return false;
|
||||
int month = num(s, 5, 2), day = num(s, 8, 2);
|
||||
return month >= 1 && month <= 12 && day >= 1 && day <= 31;
|
||||
}
|
||||
|
||||
// YYYY-MM-DD HH:MM or YYYY-MM-DD HH:MM:SS
|
||||
bool isDateTime(const std::string &s) {
|
||||
if(s.size() != 16 && s.size() != 19) return false;
|
||||
if(!isDate(s.substr(0, 10)) || s[10] != ' ' || s[13] != ':') return false;
|
||||
if(!allDigits(s, 11, 13) || !allDigits(s, 14, 16)) return false;
|
||||
if(num(s, 11, 2) > 23 || num(s, 14, 2) > 59) return false;
|
||||
if(s.size() == 19) {
|
||||
if(s[16] != ':' || !allDigits(s, 17, 19) || num(s, 17, 2) > 59) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Walks query and calls onPlaceholder(index) for every '?' that is
|
||||
// outside '...', "...", `...`, -- / # line comments and /* */
|
||||
// comments. With NO_BACKSLASH_ESCAPES off, a backslash escapes the
|
||||
// next character inside '...' and "..."; with it on, it doesn't.
|
||||
// A doubled quote ('', "", ``) is an escaped quote in every mode.
|
||||
template<typename F>
|
||||
void scan(const std::string &q, bool noBackslashEscapes, F onPlaceholder) {
|
||||
size_t i = 0, n = q.size();
|
||||
while(i < n) {
|
||||
char c = q[i];
|
||||
if(c == '\'' || c == '"' || c == '`') {
|
||||
char quote = c;
|
||||
++i;
|
||||
while(i < n) {
|
||||
if(quote != '`' && !noBackslashEscapes && q[i] == '\\') { i += 2; continue; }
|
||||
if(q[i] == quote) {
|
||||
if(i + 1 < n && q[i + 1] == quote) { i += 2; continue; }
|
||||
++i;
|
||||
break;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if(c == '#' || (c == '-' && i + 1 < n && q[i + 1] == '-' &&
|
||||
(i + 2 >= n || (unsigned char)q[i + 2] <= ' '))) {
|
||||
while(i < n && q[i] != '\n') ++i;
|
||||
continue;
|
||||
}
|
||||
if(c == '/' && i + 1 < n && q[i + 1] == '*') {
|
||||
size_t end = q.find("*/", i + 2);
|
||||
i = (end == std::string::npos) ? n : end + 2;
|
||||
continue;
|
||||
}
|
||||
if(c == '?') onPlaceholder(i);
|
||||
++i;
|
||||
}
|
||||
}
|
||||
|
||||
// Lowercased words ([a-z0-9_@.$]) outside quotes and comments.
|
||||
std::vector<std::string> words(const std::string &q) {
|
||||
std::vector<std::string> out;
|
||||
std::string cur;
|
||||
size_t i = 0, n = q.size();
|
||||
auto flush = [&]() { if(!cur.empty()) { out.push_back(lower(cur)); cur.clear(); } };
|
||||
while(i < n) {
|
||||
char c = q[i];
|
||||
if(c == '\'' || c == '"' || c == '`') {
|
||||
flush();
|
||||
char quote = c;
|
||||
++i;
|
||||
while(i < n) {
|
||||
if(quote != '`' && q[i] == '\\') { i += 2; continue; }
|
||||
if(q[i] == quote) {
|
||||
if(i + 1 < n && q[i + 1] == quote) { i += 2; continue; }
|
||||
++i;
|
||||
break;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
out.push_back("'"); // a literal stands between words
|
||||
continue;
|
||||
}
|
||||
if(c == '#' || (c == '-' && i + 1 < n && q[i + 1] == '-' &&
|
||||
(i + 2 >= n || (unsigned char)q[i + 2] <= ' '))) {
|
||||
flush();
|
||||
while(i < n && q[i] != '\n') ++i;
|
||||
continue;
|
||||
}
|
||||
if(c == '/' && i + 1 < n && q[i + 1] == '*') {
|
||||
flush();
|
||||
size_t end = q.find("*/", i + 2);
|
||||
i = (end == std::string::npos) ? n : end + 2;
|
||||
continue;
|
||||
}
|
||||
if(std::isalnum((unsigned char)c) || c == '_' || c == '@' || c == '.' || c == '$')
|
||||
cur += c;
|
||||
else
|
||||
flush();
|
||||
++i;
|
||||
}
|
||||
flush();
|
||||
return out;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
BoundValue makeBoundValue(const std::string &value,
|
||||
const std::string &typeIn,
|
||||
const std::string &nullModeIn,
|
||||
bool hasAllow,
|
||||
const std::string &allow,
|
||||
int position) {
|
||||
std::string type = typeIn.empty() ? "string" : lower(trim(typeIn));
|
||||
std::string nullMode = lower(trim(nullModeIn));
|
||||
|
||||
if(nullMode != "" && nullMode != "empty")
|
||||
throw coreutils::Exception(where(position) + "null must be \"empty\".");
|
||||
if(hasAllow && type != "ident")
|
||||
throw coreutils::Exception(where(position) + "allow is only valid with type=\"ident\".");
|
||||
|
||||
BoundValue b;
|
||||
if(nullMode == "empty" && value.empty()) {
|
||||
b.kind = BoundValue::SQLNULL;
|
||||
return b;
|
||||
}
|
||||
|
||||
if(type == "string") {
|
||||
b.kind = BoundValue::QUOTED;
|
||||
b.text = value;
|
||||
} else if(type == "int") {
|
||||
if(!isInteger(value, 19))
|
||||
throw coreutils::Exception(where(position) + "value is not a valid int.");
|
||||
b.kind = BoundValue::BARE;
|
||||
b.text = value;
|
||||
} else if(type == "decimal") {
|
||||
if(!isDecimal(value))
|
||||
throw coreutils::Exception(where(position) + "value is not a valid decimal.");
|
||||
b.kind = BoundValue::BARE;
|
||||
b.text = value;
|
||||
} else if(type == "bool") {
|
||||
std::string v = lower(value);
|
||||
b.kind = BoundValue::BARE;
|
||||
if(v == "1" || v == "true" || v == "yes")
|
||||
b.text = "1";
|
||||
else if(v == "0" || v == "false" || v == "no")
|
||||
b.text = "0";
|
||||
else
|
||||
throw coreutils::Exception(where(position) + "value is not a valid bool.");
|
||||
} else if(type == "date") {
|
||||
if(!isDate(value))
|
||||
throw coreutils::Exception(where(position) + "value is not a valid date (YYYY-MM-DD).");
|
||||
b.kind = BoundValue::QUOTED;
|
||||
b.text = value;
|
||||
} else if(type == "datetime") {
|
||||
if(!isDateTime(value))
|
||||
throw coreutils::Exception(where(position) + "value is not a valid datetime (YYYY-MM-DD HH:MM[:SS]).");
|
||||
b.kind = BoundValue::QUOTED;
|
||||
b.text = value;
|
||||
} else if(type == "ident") {
|
||||
if(!hasAllow)
|
||||
throw coreutils::Exception(where(position) + "type=\"ident\" requires an allow list.");
|
||||
// Match case-insensitively, but emit the allow list's own spelling:
|
||||
// what reaches the query always comes from the page, never the request.
|
||||
std::string match;
|
||||
bool found = false;
|
||||
size_t start = 0;
|
||||
while(start <= allow.size()) {
|
||||
size_t comma = allow.find(',', start);
|
||||
if(comma == std::string::npos) comma = allow.size();
|
||||
std::string entry = trim(allow.substr(start, comma - start));
|
||||
if(!entry.empty() && lower(entry) == lower(value)) {
|
||||
match = entry;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
start = comma + 1;
|
||||
}
|
||||
if(!found)
|
||||
throw coreutils::Exception(where(position) + "value is not in the allow list.");
|
||||
b.kind = BoundValue::BARE;
|
||||
std::string m = lower(match);
|
||||
if(m == "asc" || m == "desc") {
|
||||
b.text = (m == "asc") ? "ASC" : "DESC";
|
||||
} else {
|
||||
b.text = "`";
|
||||
for(char c : match) {
|
||||
if(c == '`') b.text += '`';
|
||||
b.text += c;
|
||||
}
|
||||
b.text += "`";
|
||||
}
|
||||
} else
|
||||
throw coreutils::Exception(where(position) + "unknown type \"" + type + "\".");
|
||||
|
||||
return b;
|
||||
}
|
||||
|
||||
size_t countPlaceholders(const std::string &query, bool noBackslashEscapes) {
|
||||
size_t count = 0;
|
||||
scan(query, noBackslashEscapes, [&](size_t) { ++count; });
|
||||
return count;
|
||||
}
|
||||
|
||||
std::string bindPlaceholders(const std::string &query,
|
||||
const std::vector<BoundValue> &values,
|
||||
bool noBackslashEscapes,
|
||||
const std::function<std::string(const std::string &)> "eEscape) {
|
||||
std::vector<size_t> at;
|
||||
scan(query, noBackslashEscapes, [&](size_t i) { at.push_back(i); });
|
||||
if(at.size() != values.size())
|
||||
throw coreutils::Exception("sql: " + std::to_string(at.size()) + " placeholders but " +
|
||||
std::to_string(values.size()) + " bind values");
|
||||
std::string out;
|
||||
out.reserve(query.size() + 32 * values.size());
|
||||
size_t last = 0;
|
||||
for(size_t k = 0; k < at.size(); ++k) {
|
||||
out.append(query, last, at[k] - last);
|
||||
const BoundValue &v = values[k];
|
||||
if(v.kind == BoundValue::SQLNULL)
|
||||
out += "NULL";
|
||||
else if(v.kind == BoundValue::BARE)
|
||||
out += v.text;
|
||||
else {
|
||||
out += '\'';
|
||||
out += quoteEscape(v.text);
|
||||
out += '\'';
|
||||
}
|
||||
last = at[k] + 1;
|
||||
}
|
||||
out.append(query, last, std::string::npos);
|
||||
return out;
|
||||
}
|
||||
|
||||
bool isCharsetChange(const std::string &query) {
|
||||
std::vector<std::string> w = words(query);
|
||||
if(w.empty() || w[0] != "set")
|
||||
return false;
|
||||
for(size_t i = 1; i < w.size(); ++i) {
|
||||
const std::string &x = w[i];
|
||||
if(x == "names" || x == "charset")
|
||||
return true;
|
||||
if(x == "character" && i + 1 < w.size() && w[i + 1] == "set")
|
||||
return true;
|
||||
// character_set_client, @@character_set_client, @@session.character_set_client, ...
|
||||
for(const char *var : {"character_set_client", "character_set_connection", "collation_connection"}) {
|
||||
std::string v(var);
|
||||
if(x.size() >= v.size() && x.compare(x.size() - v.size(), v.size(), v) == 0)
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
#ifndef __SqlBind_h__
|
||||
#define __SqlBind_h__
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// Bound parameters for <sql> - see docs/design-sql-bound-parameters.md.
|
||||
//
|
||||
// Everything here is plain string logic with no MySQL or Tag dependency,
|
||||
// so it can be unit tested on its own (tests/sqlbind_test.cpp). __bind
|
||||
// builds BoundValues with makeBoundValue(); __sql substitutes them into
|
||||
// the rendered query with bindPlaceholders(), passing in the connection's
|
||||
// own escaping function.
|
||||
|
||||
namespace jet {
|
||||
|
||||
struct BoundValue {
|
||||
enum Kind {
|
||||
SQLNULL, // emitted as NULL
|
||||
BARE, // already validated (int/decimal/bool/ASC/DESC/`ident`) - emitted as is
|
||||
QUOTED // escaped with the connection's escaper and wrapped in '...'
|
||||
};
|
||||
Kind kind = QUOTED;
|
||||
std::string text;
|
||||
};
|
||||
|
||||
// Validates value against type and returns how it must be emitted.
|
||||
// position is the 1-based bind number, used only in error messages.
|
||||
// Error messages never contain the value itself (it may be a password).
|
||||
// type: string (default if empty), int, decimal, bool, date, datetime, ident
|
||||
// nullMode: "" (bind '' for an empty value) or "empty" (bind NULL)
|
||||
// allow: comma list of permitted identifiers - required for ident,
|
||||
// not allowed on any other type
|
||||
BoundValue makeBoundValue(const std::string &value,
|
||||
const std::string &type,
|
||||
const std::string &nullMode,
|
||||
bool hasAllow,
|
||||
const std::string &allow,
|
||||
int position);
|
||||
|
||||
// Number of '?' placeholders in query that are outside string literals,
|
||||
// backtick identifiers and comments.
|
||||
size_t countPlaceholders(const std::string &query, bool noBackslashEscapes);
|
||||
|
||||
// Replaces each placeholder (as counted above) with the matching bound
|
||||
// value, in order. Throws if the placeholder and value counts differ.
|
||||
// quoteEscape escapes the body of a single-quoted string literal (no
|
||||
// surrounding quotes) for the actual connection.
|
||||
std::string bindPlaceholders(const std::string &query,
|
||||
const std::vector<BoundValue> &values,
|
||||
bool noBackslashEscapes,
|
||||
const std::function<std::string(const std::string &)> "eEscape);
|
||||
|
||||
// True for a SET statement that changes the connection character set
|
||||
// (SET NAMES, SET CHARACTER SET, SET CHARSET, or an assignment to
|
||||
// character_set_client / character_set_connection / collation_connection).
|
||||
// Changing it after connect makes client-side escaping and server-side
|
||||
// parsing disagree, so <sql> refuses these.
|
||||
bool isCharsetChange(const std::string &query);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -9,7 +9,4 @@ file name and content length from variable. $[data(filename)] and
|
||||
$[data(length)] possibly.
|
||||
4)
|
||||
|
||||
BUG LIST
|
||||
|
||||
1) Fix the variable retriever to perform all variable translation
|
||||
before fetching value processing.
|
||||
@@ -34,6 +34,58 @@ namespace jet {
|
||||
Tag *parent;
|
||||
Tag *local;
|
||||
|
||||
// Public write counterpart to the public getVariable() read path -
|
||||
// needed by anything (e.g. compiled/codegen'd output) that assigns
|
||||
// variables without being a Tag subclass itself. See Tag.cpp for the
|
||||
// "@name" session-file routing this also handles.
|
||||
void assignVariable(coreutils::ZString variable, coreutils::MString value, coreutils::ZString scope);
|
||||
|
||||
// Falls back to the normal text-scanning interpreter (parseContainer)
|
||||
// for a raw source span - used by generated code to run any tag a
|
||||
// compiler doesn't have a codegen rule for yet, without duplicating
|
||||
// the 22 tag classes' logic.
|
||||
void interpretSpan(coreutils::ZString span, coreutils::MString &out);
|
||||
|
||||
// Custom <tag name="..."> scoping: a Tag defined directly inside
|
||||
// another custom tag's own invocation (i.e. inside a __dotag
|
||||
// instance's expansion, not just nested inside <if>/<for>/etc. that
|
||||
// happen to sit there) registers into that invocation's own
|
||||
// localTags instead of the single flat global.tags map, so it's
|
||||
// only visible for the rest of that invocation - not the whole
|
||||
// script. isCustomTagBoundary is true only on __dotag instances
|
||||
// (set in __dotag's own constructor body); every other tag leaves
|
||||
// it false and is transparently walked past when searching for an
|
||||
// enclosing scope, exactly like <if>/<for>/<while> already are for
|
||||
// parent-chain purposes elsewhere. Public (like variables/keywords/
|
||||
// name/etc. above) rather than protected - __tag.cpp needs to read
|
||||
// and write these through an arbitrary ancestor Tag* found by
|
||||
// walking parent, not just on its own `this`, and protected access
|
||||
// in C++ only extends to a derived class's own (sub)object, not to
|
||||
// another object reached through a base-class-typed pointer.
|
||||
bool isCustomTagBoundary = false;
|
||||
std::map<coreutils::MString, coreutils::MString> localTags;
|
||||
|
||||
// Walks from `this` up through `parent` looking for the nearest
|
||||
// isCustomTagBoundary ancestor whose localTags has `name`, falling
|
||||
// back to global.tags - used by both ifTagDefined() (is <name>
|
||||
// visible right here?) and __dotag's own constructor (fetch the
|
||||
// actual definition to expand).
|
||||
bool findTagDefinition(coreutils::MString name, coreutils::ZString &result);
|
||||
|
||||
// Renders the enclosing custom tag invocation's own nested content -
|
||||
// the <container> marker inside a <tag name="X"> definition body -
|
||||
// into `out`. Extracted, unchanged, from parseContainer's own
|
||||
// "container" dispatch branch (see Tag.cpp) so generated code for a
|
||||
// compiled tag-definition body (see jetc's TAGDEF handling) can call
|
||||
// this exact logic directly instead of going through the raw-text
|
||||
// scan to reach it - walks up from `local` to the nearest
|
||||
// isCustomTagBoundary ancestor not already being resolved (guards
|
||||
// the pass-through self-reference case, e.g. linkbutton's own
|
||||
// <EVAL><CONTAINER></EVAL>) and renders THAT scope's own ->container;
|
||||
// falls back to rendering container2 if no such ancestor exists,
|
||||
// exactly matching parseContainer's own fallback for the same case.
|
||||
void renderContainer(coreutils::MString &out, coreutils::ZString container2 = NULL);
|
||||
|
||||
protected:
|
||||
bool hasContainer = false;
|
||||
bool hasContainer2 = false;
|
||||
@@ -54,7 +106,7 @@ namespace jet {
|
||||
void renderVariableName(coreutils::ZString &variable, coreutils::MString &name, coreutils::MString &modifier);
|
||||
void storeVariable(coreutils::ZString variable, coreutils::MString value, coreutils::ZString scope);
|
||||
void storeVariable(coreutils::ZString variable);
|
||||
|
||||
|
||||
private:
|
||||
bool containerOnly = false;
|
||||
coreutils::ZString splitTagName;
|
||||
@@ -68,8 +120,31 @@ namespace jet {
|
||||
bool ifTagDefined(coreutils::ZString &in, coreutils::ZString &tag);
|
||||
bool ifEndTagName(coreutils::ZString &in);
|
||||
bool ifSplitTagName(coreutils::ZString &in);
|
||||
|
||||
// ifNested(in)'s own same-name-only check misses a DIFFERENTLY
|
||||
// named nested split-tag construct - e.g. an <if> nested inside an
|
||||
// <ifrow>'s own body (both use splitTagName "else"): ifNested(in)
|
||||
// only recognizes another nested <ifrow>, so an inner <if>'s own
|
||||
// <else>/</if> markers were being read as if they belonged to the
|
||||
// OUTER <ifrow>'s own boundary scan, corrupting both. This overload
|
||||
// set (ifNested/ifEndTagName parameterized by an explicit tag name,
|
||||
// plus scanContainerNamed) generalizes the exact same logic to any
|
||||
// of the built-in splitTagName="else" conditionals - if/while/
|
||||
// until/ifrow - so the outer tag's boundary scan correctly skips
|
||||
// PAST an inner one of any of these, regardless of name, before
|
||||
// resuming its own search. See Tag.cpp's own doc comment on the
|
||||
// shared splitTagNames list for the real story/repro.
|
||||
bool ifNested(coreutils::ZString &in, const char *tagName);
|
||||
bool ifEndTagName(coreutils::ZString &in, const char *tagName);
|
||||
void scanContainerNamed(coreutils::ZString &in, const char *tagName);
|
||||
|
||||
coreutils::MString processModifier(coreutils::MString &value, coreutils::MString &modifier);
|
||||
|
||||
public:
|
||||
// The split tag's own attributes (raw, unresolved) - e.g. <try>'s
|
||||
// <catch name="err">, so __trytag can bind the error to that name.
|
||||
// Last member on purpose: adding it changes no other member's offset.
|
||||
std::map<coreutils::MString, coreutils::MString> splitKeywords;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#include "__bind.h"
|
||||
#include "__sql.h"
|
||||
#include "Exception.h"
|
||||
#include "SqlBind.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
__bind::__bind(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
output = false;
|
||||
|
||||
// Nearest enclosing <sql>, through any <if>/<for>/etc. in between.
|
||||
__sql *sql = NULL;
|
||||
for(Tag *scope = parent; scope && !sql; scope = scope->parent)
|
||||
sql = dynamic_cast<__sql *>(scope);
|
||||
if(!sql)
|
||||
throw coreutils::Exception("bind must be inside sql.");
|
||||
if(!keywordDefined("value"))
|
||||
throw coreutils::Exception("bind must have a value.");
|
||||
|
||||
std::string value = resolveKeyword("value").str();
|
||||
std::string type = keywordDefined("type") ? resolveKeyword("type").str() : "";
|
||||
std::string nullMode = keywordDefined("null") ? resolveKeyword("null").str() : "";
|
||||
bool hasAllow = keywordDefined("allow");
|
||||
std::string allow = hasAllow ? resolveKeyword("allow").str() : "";
|
||||
|
||||
sql->addBind(makeBoundValue(value, type, nullMode, hasAllow, allow, (int)sql->bindCount() + 1));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef ____bind_h__
|
||||
#define ____bind_h__
|
||||
|
||||
#include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
// <bind value="..." [type="..."] [null="empty"] [allow="a,b"]> - supplies
|
||||
// the value for the next '?' placeholder of the enclosing <sql>. Always
|
||||
// void (no closing tag) and produces no output. See
|
||||
// docs/design-sql-bound-parameters.md.
|
||||
class __bind : public Tag {
|
||||
|
||||
public:
|
||||
__bind(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -7,68 +7,123 @@
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
|
||||
namespace jet {
|
||||
|
||||
|
||||
__call::__call(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
if(hasContainer && keywordDefined("input"))
|
||||
throw coreutils::Exception("call tag cannot have both input keyword and have a container.");
|
||||
throw coreutils::Exception("call tag cannot have both input keyword and have a container.");
|
||||
if(!keywordDefined("pgm"))
|
||||
throw coreutils::Exception("pgm keyword must be specified.");
|
||||
for(ix = 0; ix <= 50; ++ix)
|
||||
for(ix = 0; ix < 50; ++ix)
|
||||
argv[ix] = NULL;
|
||||
argv[0] = resolveKeyword("pgm").c_str(); // TODO: Need to peel off the program name only and pass as argv[0].
|
||||
for(ix = 1; ix <= 50; ++ix) {
|
||||
// Reserve up front - argStrings must never reallocate once a
|
||||
// c_str() pointer from one of its elements has been stored into
|
||||
// argv[] below, or that pointer dangles exactly like the bug this
|
||||
// replaces (see the .h's own comment). 50 arg slots + argv[0]'s
|
||||
// own program name.
|
||||
argStrings.reserve(51);
|
||||
argStrings.push_back(resolveKeyword("pgm")); // TODO: Need to peel off the program name only and pass as argv[0].
|
||||
argv[0] = argStrings.back().c_str();
|
||||
for(ix = 1; ix < 50; ++ix) {
|
||||
coreutils::MString arg("arg");
|
||||
arg << ix;
|
||||
if(keywordDefined(arg)) {
|
||||
argv[ix] = resolveKeyword(arg).c_str();
|
||||
if(keywordDefined(arg)) {
|
||||
argStrings.push_back(resolveKeyword(arg));
|
||||
argv[ix] = argStrings.back().c_str();
|
||||
} else
|
||||
break;
|
||||
}
|
||||
pipe(fdo);
|
||||
// pipe()/fork() both used to go unchecked here - on failure (most
|
||||
// realistically pipe() hitting the process's open-file-descriptor
|
||||
// limit, see below) fdo[] is left holding whatever garbage was
|
||||
// already on the stack/in this member array, and every use of it
|
||||
// after this point (close(), read(), and - for a failed fork() -
|
||||
// waitpid(-1, ...), which has the special POSIX meaning "wait for
|
||||
// ANY child" rather than "wait for none") operates on that garbage
|
||||
// or on an unrelated process instead of safely no-oping. That's a
|
||||
// real, confirmed mechanism for exactly the kind of sporadic
|
||||
// memory corruption this codebase has seen: closing/reading a
|
||||
// stale fd that coincidentally matches another subsystem's live
|
||||
// socket, or reaping a concurrent request's own child out from
|
||||
// under it.
|
||||
if(pipe(fdo) != 0)
|
||||
throw coreutils::Exception("call: pipe() failed - " + std::string(strerror(errno)), __FILE__, __LINE__, 500);
|
||||
pid = fork();
|
||||
if(pid < 0) {
|
||||
close(fdo[0]);
|
||||
close(fdo[1]);
|
||||
throw coreutils::Exception("call: fork() failed - " + std::string(strerror(errno)), __FILE__, __LINE__, 500);
|
||||
}
|
||||
if(pid == 0) {
|
||||
close(fdo[0]);
|
||||
dup2(fdo[1], 1);
|
||||
if(hasContainer) {
|
||||
pipe(fdi);
|
||||
if(fork() == 0) {
|
||||
close(fdi[0]);
|
||||
write(fdi[1], container.getData(), container.getLength());
|
||||
close(fdi[1]);
|
||||
exit(0);
|
||||
if(hasContainer) {
|
||||
if(pipe(fdi) == 0) {
|
||||
pid_t innerPid = fork();
|
||||
if(innerPid == 0) {
|
||||
close(fdi[0]);
|
||||
write(fdi[1], container.getData(), container.getLength());
|
||||
close(fdi[1]);
|
||||
_exit(0);
|
||||
} else if(innerPid > 0) {
|
||||
close(fdi[1]);
|
||||
dup2(fdi[0], 0);
|
||||
close(fdi[0]);
|
||||
} else {
|
||||
close(fdi[0]);
|
||||
close(fdi[1]);
|
||||
}
|
||||
}
|
||||
close(fdi[1]);
|
||||
dup2(fdi[0], 0);
|
||||
} else if(keywordDefined("input")) {
|
||||
coreutils::MString input(resolveKeyword("input"));
|
||||
pipe(fdi);
|
||||
if(fork() == 0) {
|
||||
close(fdi[0]);
|
||||
write(fdi[1], input.getData(), input.getLength());
|
||||
close(fdi[1]);
|
||||
exit(0);
|
||||
if(pipe(fdi) == 0) {
|
||||
pid_t innerPid = fork();
|
||||
if(innerPid == 0) {
|
||||
close(fdi[0]);
|
||||
write(fdi[1], input.getData(), input.getLength());
|
||||
close(fdi[1]);
|
||||
_exit(0);
|
||||
} else if(innerPid > 0) {
|
||||
close(fdi[1]);
|
||||
dup2(fdi[0], 0);
|
||||
close(fdi[0]);
|
||||
} else {
|
||||
close(fdi[0]);
|
||||
close(fdi[1]);
|
||||
}
|
||||
}
|
||||
close(fdi[1]);
|
||||
dup2(fdi[0], 0);
|
||||
}
|
||||
rc = execvpe(resolveKeyword("pgm").c_str(), argv, global.envp);
|
||||
rc = execvpe(argv[0], argv, global.envp);
|
||||
close(fdo[1]);
|
||||
exit(errno);
|
||||
_exit(errno);
|
||||
}
|
||||
close(fdo[1]);
|
||||
if(keywordDefined("name")) {
|
||||
coreutils::MString value;
|
||||
value.read(fdo[0]);
|
||||
storeVariable(resolveKeyword("name"), value, resolveKeyword("scope"));
|
||||
} else
|
||||
out.read(fdo[0]);
|
||||
} else
|
||||
out.read(fdo[0]);
|
||||
// fdo[0] (the read end, still open in this - the parent - process)
|
||||
// was never closed here before, leaking one file descriptor on
|
||||
// every single <call> invocation for the life of the process.
|
||||
// Harmless-looking for an occasional <call>, but <call> is used
|
||||
// throughout this codebase (jq/curl parsing, mailcreate, this
|
||||
// session's own per-line-item JS-escaping on the invoice editor,
|
||||
// which alone can issue a double-digit number of calls per page
|
||||
// load) - repeated, routine use was slowly accumulating leaked
|
||||
// fds for as long as this process stayed up, eventually hitting
|
||||
// the real open-files limit and turning into exactly the pipe()
|
||||
// failures (and the undefined behavior above) this fix addresses.
|
||||
close(fdo[0]);
|
||||
waitpid(pid, &status, 0);
|
||||
if(keywordDefined("error")) {
|
||||
if(keywordDefined("error")) {
|
||||
global.variables[resolveKeyword("error")] = (status >> 8 & 255);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -2,11 +2,12 @@
|
||||
#define ____call_h__
|
||||
|
||||
#include "Tag.h"
|
||||
#include <vector>
|
||||
|
||||
namespace jet {
|
||||
|
||||
|
||||
class __call : public Tag {
|
||||
|
||||
|
||||
public:
|
||||
__call(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
@@ -18,9 +19,24 @@ namespace jet {
|
||||
int fdo[2];
|
||||
int rc;
|
||||
char *argv[50];
|
||||
|
||||
|
||||
// Owns the actual character storage argv[] points into. Resolved
|
||||
// MStrings used to be created as unnamed temporaries with only
|
||||
// their .c_str() pointer kept (argv[ix] = resolveKeyword(arg)
|
||||
// .c_str()) - the temporary is destroyed at the end of that same
|
||||
// statement, so argv[ix] was a dangling pointer from that point
|
||||
// on, read only much later by execvpe() in the forked child.
|
||||
// Undefined behavior - confirmed via a real repro: two sequential
|
||||
// <call> tags (date, then cp using date's own captured output)
|
||||
// corrupted each other's arguments, producing a "cp" invocation
|
||||
// that actually ran /bin/date with garbage arguments instead.
|
||||
// Reserved to its final size up front (see the constructor) so no
|
||||
// push_back can reallocate and invalidate a c_str() pointer
|
||||
// already stored in argv[] earlier in the same construction.
|
||||
std::vector<coreutils::MString> argStrings;
|
||||
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -2,10 +2,65 @@
|
||||
#include "Exception.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
__dotag::__dotag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
coreutils::ZString container3 = global.tags[name];
|
||||
processContainer(container3, container);
|
||||
|
||||
__dotag::__dotag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this) {
|
||||
// Every invocation of a custom tag is itself a new scope boundary -
|
||||
// a <tag name="..."> encountered while expanding this invocation's
|
||||
// own template (below) registers into THIS instance's localTags,
|
||||
// not the global map, so it's only visible for the rest of this
|
||||
// expansion. See Tag.h's isCustomTagBoundary/localTags doc comment.
|
||||
//
|
||||
// local=this (bound above, in the base Tag constructor call rather
|
||||
// than forwarding the caller's own local) is what makes a custom
|
||||
// tag's own body see ITS OWN declared/passed attributes via
|
||||
// #[name] - matches the pattern __if/__while/__until already use
|
||||
// for the same reason. Without this, #[name] reads inside e.g.
|
||||
// SESSIONCTL.tag's <sessionctl>/<setpage>/<retain> bodies resolved
|
||||
// against whatever local scope happened to be active in the
|
||||
// caller instead of this invocation's own attributes, and always
|
||||
// fell through to the empty-string fallback.
|
||||
isCustomTagBoundary = true;
|
||||
|
||||
// The base Tag constructor already set hasContainer from whether
|
||||
// THIS INVOCATION was self-closing (<name /> vs <name>...</name>) -
|
||||
// that's the right question for capturing this invocation's own
|
||||
// nested content into `container` above, but the wrong one for
|
||||
// whether the tag's DEFINITION (container3 below) should render:
|
||||
// a self-closing invocation of a tag whose definition doesn't use
|
||||
// <container /> at all is completely normal and should still
|
||||
// render. Found this as a real, pre-existing bug while testing
|
||||
// this scoping feature - <name /> always silently rendered nothing
|
||||
// for ANY custom tag, only <name></name> worked, since
|
||||
// processContainer() gates on hasContainer. Force it true here:
|
||||
// by this point a valid definition is guaranteed to exist (dispatch
|
||||
// only constructs __dotag after ifTagDefined() already confirmed
|
||||
// it), so there's always something to render regardless of how
|
||||
// this invocation was written.
|
||||
hasContainer = true;
|
||||
|
||||
// Fast path: if jetc compiled this tag's definition directly (a
|
||||
// top-level <tag name="X"> - see JetCodegen's TAGDEF handling), a
|
||||
// render function was registered under its lowercase name (matching
|
||||
// __tag.cpp's own registration key convention) instead of - or
|
||||
// alongside - the raw text findTagDefinition()/processContainer()
|
||||
// below would otherwise have to re-parse on every single invocation.
|
||||
// A miss here (locally-scoped/nested definitions, or a tag that was
|
||||
// never part of a compiled module) falls straight through to that
|
||||
// exact same interpreted path, unchanged - see Global.h's own doc
|
||||
// comment on compiledTags.
|
||||
coreutils::MString nameLower = coreutils::MString(name).toLower();
|
||||
auto compiledIt = global.compiledTags.find(nameLower);
|
||||
if(compiledIt != global.compiledTags.end()) {
|
||||
// Same gate processContainer() below applies on the interpreted
|
||||
// path - keeps both paths behaviorally identical rather than
|
||||
// having the compiled fast path unconditionally render.
|
||||
if(hasContainer && evaluate)
|
||||
compiledIt->second(*this, out);
|
||||
} else {
|
||||
coreutils::ZString container3;
|
||||
if(!findTagDefinition(name, container3))
|
||||
throw coreutils::Exception("tag definition not found.");
|
||||
processContainer(container3, container);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "Exception.h"
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
|
||||
namespace jet {
|
||||
|
||||
@@ -13,8 +14,8 @@ namespace jet {
|
||||
|
||||
if(global.cgi) {
|
||||
outFile << "*** CGI VARIABLES ***" << std::endl;
|
||||
for (auto i = global.cgiVariables.begin(); i != global.cgiVariables.end(); i++)
|
||||
outFile << i->first << "=[" << i->second << "]" << std::endl;
|
||||
// for (auto i = global.cgiVariables.begin(); i != global.cgiVariables.end(); i++)
|
||||
// outFile << i->first << "=[" << i->second << "]" << std::endl;
|
||||
}
|
||||
|
||||
outFile << "*** GLOBAL VARIABLES ***" << std::endl;
|
||||
@@ -29,10 +30,41 @@ namespace jet {
|
||||
for (auto i = parent->keywords.begin(); i != parent->keywords.end(); i++)
|
||||
outFile << i->first << "=[" << i->second << "]" << std::endl;
|
||||
|
||||
outFile << "*** COOKIES ***" << std::endl;
|
||||
outFile << "*** COOKIES ***" << std::endl;
|
||||
for (auto i = global.cookies.data.begin(); i != global.cookies.data.end(); i++)
|
||||
outFile << i->first << "=[" << i->second << "]" << std::endl;
|
||||
|
||||
// Custom <tag name="..."> definitions now have real scoping - one
|
||||
// defined directly inside another custom tag's own invocation is
|
||||
// only visible for the rest of that invocation (see Tag.h's
|
||||
// isCustomTagBoundary/localTags doc comment). Render the actual
|
||||
// tree currently in effect at this point in the script: global at
|
||||
// the root, then each enclosing custom-tag invocation nested one
|
||||
// level deeper, outermost first - if there's no active local scope
|
||||
// (this <dump> isn't running inside any custom tag's expansion),
|
||||
// that's just the root with nothing nested under it.
|
||||
outFile << "*** DEFINED TAGS ***" << std::endl;
|
||||
outFile << "(global)" << std::endl;
|
||||
for (auto i = global.tags.begin(); i != global.tags.end(); i++)
|
||||
outFile << " " << i->first << std::endl;
|
||||
|
||||
std::vector<Tag *> scopeChain;
|
||||
for (Tag *scope = this; scope; scope = scope->parent)
|
||||
if (scope->isCustomTagBoundary)
|
||||
scopeChain.push_back(scope);
|
||||
|
||||
int depth = 1;
|
||||
for (auto it = scopeChain.rbegin(); it != scopeChain.rend(); ++it) {
|
||||
Tag *boundary = *it;
|
||||
coreutils::MString indent;
|
||||
for (int d = 0; d < depth; d++)
|
||||
indent << " ";
|
||||
outFile << indent << "(inside " << boundary->name << ")" << std::endl;
|
||||
for (auto i = boundary->localTags.begin(); i != boundary->localTags.end(); i++)
|
||||
outFile << indent << " " << i->first << std::endl;
|
||||
depth++;
|
||||
}
|
||||
|
||||
outFile.close();
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
#include "__eval.h"
|
||||
#include "Exception.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
// <eval> is not a jet-2.0 addition - it's a genuine jet-1.4 tag that was
|
||||
// simply never implemented in 2.0 at all (no class, no dispatch entry
|
||||
// anywhere). SESSIONCTL.tag's own <page> definition depends on it
|
||||
// throughout - capturing a tag's own invocation content into a named
|
||||
// variable (<eval name="_BODY"><container></eval>, often with
|
||||
// scope="parent" so a nested custom tag can write back into its
|
||||
// caller's scope: <eval name="AUTHOR" scope="parent">...), and also
|
||||
// using it bare (no name=) to render an <include>'d file's content
|
||||
// inline (<eval><include file="...page"></eval>). Without this tag,
|
||||
// all of that content was silently falling through as undefined-tag
|
||||
// literal text, which is why a real, unmodified SESSIONCTL.tag <page>
|
||||
// never produced its actual rendered body.
|
||||
//
|
||||
// <eval name="X" [scope="local|parent|global"]>content</eval> - same
|
||||
// capture semantics as <set name="X">content</set> (Tag::storeVariable
|
||||
// already implements exactly this: interpret the container, then store
|
||||
// the result - raw if the container itself specified eval="no", already
|
||||
// evaluated otherwise - into variable X at the requested scope,
|
||||
// defaulting to global like <set> does). Reused directly rather than
|
||||
// reimplemented, since it's the identical contract under a different
|
||||
// tag name.
|
||||
//
|
||||
// <eval>content</eval> (no name=) - content is interpreted and flows to
|
||||
// normal output, exactly like any ordinary container-having tag; no
|
||||
// special-casing needed since output/evaluate already default to true
|
||||
// on the base Tag class and the destructor's copyContainer(out,
|
||||
// parentOut) handles the rest once processContainer(container) below
|
||||
// has populated `out`.
|
||||
__eval::__eval(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
if(keywordDefined("name")) {
|
||||
storeVariable(resolveKeyword("name"));
|
||||
output = false;
|
||||
} else if(hasContainer) {
|
||||
processContainer(container);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#ifndef ____eval_h__
|
||||
#define ____eval_h__
|
||||
|
||||
#include "Tag.h"
|
||||
#include "ZString.h"
|
||||
#include "MString.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
class __eval : public Tag {
|
||||
|
||||
public:
|
||||
__eval(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
protected:
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -2,12 +2,12 @@
|
||||
#include "Exception.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
|
||||
__exclude::__exclude(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this) {
|
||||
if(!hasContainer)
|
||||
throw coreutils::Exception("exclude must have a container.");
|
||||
throw coreutils::Exception("exclude must have a container.");
|
||||
output = true;
|
||||
evaluate = false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -5,32 +5,54 @@
|
||||
namespace jet {
|
||||
|
||||
__for::__for(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this) {
|
||||
double counter = 0.0f;
|
||||
double counter = 0.0f;
|
||||
bool nameDefined = keywordDefined("name");
|
||||
if(keywordDefined("start")) {
|
||||
counter = resolveKeyword("start").asDouble();
|
||||
keywords["start"].reset();
|
||||
}
|
||||
if(!keywordDefined("end"))
|
||||
if(!keywordDefined("end"))
|
||||
throw coreutils::Exception("for tag requires end keyword.");
|
||||
if(!keywordDefined("step"))
|
||||
if(!keywordDefined("step"))
|
||||
throw coreutils::Exception("for tag requires step keyword.");
|
||||
|
||||
// Where to write the loop counter (which variables map, and under
|
||||
// what name) is a static property of this <for>'s own invocation -
|
||||
// "scope"/"name" have no sensible reason to change mid-loop, so
|
||||
// resolve and branch on them once instead of re-resolving both
|
||||
// (and re-checking scope with up to 3 comparisons) on every single
|
||||
// iteration. Loop bounds (end/step) are deliberately left
|
||||
// re-resolved per iteration exactly as before - real content could
|
||||
// plausibly rely on a bound that changes as a side effect of the
|
||||
// loop body itself, and there's no clear evidence either way, so
|
||||
// that part stays conservative/unchanged.
|
||||
coreutils::MString counterVarName;
|
||||
enum { SCOPE_GLOBAL, SCOPE_LOCAL, SCOPE_PARENT } counterScope = SCOPE_GLOBAL;
|
||||
if(nameDefined) {
|
||||
counterVarName = resolveKeyword("name");
|
||||
if(keywordDefined("scope")) {
|
||||
coreutils::MString scopeVal = resolveKeyword("scope");
|
||||
if(scopeVal == "global") counterScope = SCOPE_GLOBAL;
|
||||
else if(scopeVal == "local") counterScope = SCOPE_LOCAL;
|
||||
else if(scopeVal == "parent") counterScope = SCOPE_PARENT;
|
||||
else throw coreutils::Exception("scope value is not valid.");
|
||||
}
|
||||
}
|
||||
|
||||
for(double ix = counter; ix <= resolveKeyword("end").asDouble(); ix += resolveKeyword("step").asDouble()) {
|
||||
resolveKeyword("end").reset();
|
||||
resolveKeyword("step").reset();
|
||||
resolveKeyword("step").reset();
|
||||
if(nameDefined) {
|
||||
if(!keywordDefined("scope") || (resolveKeyword("scope") == "global"))
|
||||
global.variables[resolveKeyword("name")] = ix;
|
||||
else if(resolveKeyword("scope") == "local")
|
||||
this->local->variables[resolveKeyword("name")] = ix;
|
||||
else if(resolveKeyword("scope") == "parent")
|
||||
parent->local->variables[resolveKeyword("name")] = ix;
|
||||
if(counterScope == SCOPE_GLOBAL)
|
||||
global.variables[counterVarName] = ix;
|
||||
else if(counterScope == SCOPE_LOCAL)
|
||||
this->local->variables[counterVarName] = ix;
|
||||
else
|
||||
throw coreutils::Exception("scope value is not valid.");
|
||||
}
|
||||
parent->local->variables[counterVarName] = ix;
|
||||
}
|
||||
processContainer(container);
|
||||
container.reset();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -16,7 +16,7 @@ namespace jet {
|
||||
throw coreutils::Exception("type expected if value1 and value2 specified.");
|
||||
} else
|
||||
throw coreutils::Exception("value2 required if value1 specified.");
|
||||
coreutils::MString type = resolveKeyword("type");
|
||||
coreutils::MString type = resolveKeyword("type").toLower();
|
||||
if((type != "eq") &&
|
||||
(type != "ne") &&
|
||||
(type != "lt") &&
|
||||
|
||||
@@ -6,17 +6,37 @@
|
||||
#include <unistd.h>
|
||||
|
||||
namespace jet {
|
||||
|
||||
|
||||
__ifrow::__ifrow(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this, "else") {
|
||||
output = false;
|
||||
// NOT setting output=false here (an earlier version of this file
|
||||
// did) - that flag gates Tag::~Tag()'s own copyContainer(out,
|
||||
// parentOut) call, the mechanism that propagates whatever
|
||||
// processContainer() below actually wrote up to this tag's own
|
||||
// caller. <ifrow>'s entire purpose is to conditionally DISPLAY one
|
||||
// of its two branches (exactly like <if>/<while>/<until>, none of
|
||||
// which ever touch `output`) - unlike the tags that legitimately
|
||||
// do set it (<set>/<sql>/<cookie>/<header>/<write>/<tag>/
|
||||
// <comment>/<stream>, none of which have any visible content of
|
||||
// their own to emit), so setting it here silently discarded
|
||||
// EVERY <ifrow>'s rendered content, true branch or false, on every
|
||||
// single use. Confirmed live via gdb-style tracing: hasRow(),
|
||||
// the resolved session pointer, and container's own text were all
|
||||
// exactly correct at the point processContainer(container) ran -
|
||||
// the content just never reached parentOut because the destructor
|
||||
// skipped the copy. Never caught before because no real content
|
||||
// this session exercised an <ifrow> with real row data AND had
|
||||
// its rendered output actually inspected (account.page's own
|
||||
// <ifrow sessionid="projman"> usage always redirected before
|
||||
// reaching it, for lack of a login session).
|
||||
if(!hasContainer)
|
||||
throw coreutils::Exception("ifrow tag must have a container.");
|
||||
if(!global.sessionExists(keywords[resolveKeyword("sessionid")]))
|
||||
throw coreutils::Exception("ifrow tag must have a container.");
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if(!global.sessionExists(sessionId))
|
||||
throw coreutils::Exception("sessionid does not exist.");
|
||||
if(global.getSession(keywords[resolveKeyword("sessionid")])->hasRow())
|
||||
if(global.getSession(sessionId)->hasRow())
|
||||
processContainer(container);
|
||||
else
|
||||
processContainer(container2);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
#ifndef ____imap_h__
|
||||
# define ____imap_h__
|
||||
|
||||
# include "Tag.h"
|
||||
# include "ZString.h"
|
||||
# include "MString.h"
|
||||
# include <cstdint>
|
||||
# include <openssl/ssl.h>
|
||||
# include <string>
|
||||
# include <vector>
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imap config="./email.cfg" user="..." password="..." sessionid="">
|
||||
///
|
||||
/// Connects to the IMAP host named in the JSON file `config` (keys:
|
||||
/// host, port, caCertificate - see email.cfg), TLS-handshakes
|
||||
/// (implicit TLS, matching IMAP's standard port 993 - no STARTTLS
|
||||
/// negotiation), and LOGINs with user/password. Throws
|
||||
/// coreutils::Exception (with errorNumber set to a real HTTP status -
|
||||
/// 401 for a bad login, 502 for a connection/protocol failure) on any
|
||||
/// failure, exactly like __mysql throws on a failed
|
||||
/// mysql_real_connect() - see ApiSession.cpp's exception->HTTP-status
|
||||
/// mapping, which both this tag and __mysql rely on identically.
|
||||
///
|
||||
/// Registers itself into Global::imapSessions under sessionid (a
|
||||
/// SEPARATE map from __mysql's Global::sessions - the two backends
|
||||
/// aren't interchangeable and Global::sessions is concretely typed
|
||||
/// __mysql*, not something a second backend could share without
|
||||
/// widening every existing __mysql-only call site), the same way
|
||||
/// __mysql registers into Global::sessions - later __imap* -family
|
||||
/// tags (__imaplist, __imapmessage, __imapflag, __imapdelete) look
|
||||
/// the live connection up by sessionid, mirroring how <sql> finds its
|
||||
/// <database> by sessionid.
|
||||
///
|
||||
/// Connection pooling: a thread_local pool keyed by sessionid+user,
|
||||
/// reused across requests on the same APIServer worker thread (an
|
||||
/// IMAP TCP+TLS+LOGIN round trip is too expensive to redo on every
|
||||
/// AJAX call the webmail UI makes) - directly mirrors __mysql.cpp's
|
||||
/// own thread_local connectionPool, including using a cheap
|
||||
/// keepalive probe (NOOP, IMAP's equivalent of mysql_ping()) to
|
||||
/// detect and discard a connection the server itself already dropped
|
||||
/// rather than handing a dead socket to the first real command.
|
||||
///
|
||||
|
||||
class __imap : public Tag {
|
||||
|
||||
public:
|
||||
__imap(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
~__imap();
|
||||
|
||||
// Each returns a complete, ready-to-emit JSON value (object or
|
||||
// array) - the __imap*-family wrapper tags (__imaplist.cpp etc.)
|
||||
// just write whatever this returns straight into their own `out`,
|
||||
// the same one-call-does-everything shape __sql's query() call
|
||||
// has relative to <sql>.
|
||||
/// offset counts back from the newest message (0 = the newest
|
||||
/// page); the returned JSON is {"total":N,"messages":[...]}.
|
||||
coreutils::MString listMessages(const std::string &folder, int limit, int offset);
|
||||
coreutils::MString searchMessages(const std::string &folder, const std::string &query);
|
||||
coreutils::MString fetchMessage(const std::string &folder, uint32_t uid);
|
||||
coreutils::MString setFlag(const std::string &folder, uint32_t uid, const std::string &flag, bool add);
|
||||
coreutils::MString deleteMessage(const std::string &folder, uint32_t uid);
|
||||
coreutils::MString moveMessage(const std::string &folder, uint32_t uid, const std::string &destFolder);
|
||||
// Permanently empties an entire folder - every message, not one at
|
||||
// a time. "1:*" is IMAP's standard UID-range syntax for "every UID
|
||||
// in the selected mailbox" (well-defined and a no-op, not an error,
|
||||
// on an already-empty folder - verified directly against
|
||||
// BARANTMail rather than assumed from the RFC), so this is a
|
||||
// single mark-all-deleted STORE plus one EXPUNGE, not a loop over
|
||||
// deleteMessage() - the whole point is one IMAP round trip instead
|
||||
// of one per message.
|
||||
coreutils::MString emptyFolder(const std::string &folder);
|
||||
coreutils::MString folderCounts();
|
||||
|
||||
coreutils::MString sessionId;
|
||||
|
||||
private:
|
||||
SSL_CTX *ctx = nullptr;
|
||||
SSL *ssl = nullptr;
|
||||
int fd = -1;
|
||||
int tagCounter = 0;
|
||||
std::string recvBuffer;
|
||||
size_t recvPos = 0;
|
||||
std::string selectedFolder;
|
||||
|
||||
std::string nextTag();
|
||||
void sendLine(const std::string &line);
|
||||
char readByte();
|
||||
// Reads one IMAP response line, INCLUDING any literal {n} content
|
||||
// that line announces (rejoined into the same returned string,
|
||||
// separated by "\r\n" markers) - see the .cpp for the full
|
||||
// rationale; this is a pragmatic, purpose-built reader for the
|
||||
// specific, known response shapes this client's own requests
|
||||
// provoke from BARANTMail (whose own FETCH implementation - built
|
||||
// earlier this same session - always uses literals for content,
|
||||
// never quoted strings), not a fully general IMAP parser.
|
||||
std::string readResponseLine();
|
||||
// Reads response lines until the tagged completion line for `tag`
|
||||
// (built earlier via nextTag()) appears; returns every line
|
||||
// (untagged and the final tagged one) collected along the way.
|
||||
// Throws if the tagged line's status isn't OK.
|
||||
std::vector<std::string> readUntilTagged(const std::string &tag);
|
||||
|
||||
bool selectFolderIfNeeded(const std::string &folder);
|
||||
static std::string jsonEscape(const std::string &s);
|
||||
static uint32_t findUidField(const std::string &fetchLine);
|
||||
static std::vector<std::string> findFlagsField(const std::string &fetchLine);
|
||||
static long findSizeField(const std::string &fetchLine);
|
||||
// Extracts the literal content immediately following a
|
||||
// "BODY[...]" (or "BODY[...]<n>") marker in an already-
|
||||
// literal-rejoined response line - see readResponseLine()'s own
|
||||
// doc comment for the "\r\n"-separated rejoining this depends on.
|
||||
static std::string findBodyLiteral(const std::string &fetchLine);
|
||||
// Shared by listMessages() and searchMessages() - see its own
|
||||
// doc comment in the .cpp.
|
||||
static std::vector<std::string> parseSummaryLines(const std::vector<std::string> &lines);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,163 @@
|
||||
#include "__imapaccounts.h"
|
||||
#include "Base64.h"
|
||||
#include "Exception.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
namespace jet {
|
||||
|
||||
std::string __imapaccounts::jsonEscape(const std::string &s) {
|
||||
std::string out;
|
||||
out.reserve(s.size() + 8);
|
||||
for (unsigned char c : s) {
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\r': continue;
|
||||
case '\t': out += "\\t"; break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
char buf[8];
|
||||
snprintf(buf, sizeof(buf), "\\u%04x", c);
|
||||
out += buf;
|
||||
} else {
|
||||
out += (char)c;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::string trimWhitespace(const std::string &s) {
|
||||
size_t start = s.find_first_not_of(" \t\r\n");
|
||||
if (start == std::string::npos)
|
||||
return std::string();
|
||||
size_t end = s.find_last_not_of(" \t\r\n");
|
||||
return s.substr(start, end - start + 1);
|
||||
}
|
||||
|
||||
std::vector<__imapaccounts::Account> __imapaccounts::decodeList(const std::string &encodedRaw) {
|
||||
std::vector<Account> entries;
|
||||
coreutils::Base64 base64;
|
||||
// The list value round-trips through <eval>/<set> template
|
||||
// captures, which include whatever whitespace/newlines surround
|
||||
// the tag call in the .jet source - trimming here (rather than
|
||||
// insisting every template call site stays whitespace-free) is
|
||||
// the robust fix, since a base64 decoder that stops at the first
|
||||
// invalid character would otherwise silently truncate to nothing
|
||||
// when a stray leading newline precedes real, valid content.
|
||||
std::string encoded = trimWhitespace(encodedRaw);
|
||||
size_t pos = 0;
|
||||
while (pos < encoded.size()) {
|
||||
size_t semi = encoded.find(';', pos);
|
||||
std::string entry = (semi == std::string::npos) ? encoded.substr(pos) : encoded.substr(pos, semi - pos);
|
||||
pos = (semi == std::string::npos) ? encoded.size() : semi + 1;
|
||||
entry = trimWhitespace(entry);
|
||||
if (entry.empty())
|
||||
continue;
|
||||
size_t colon1 = entry.find(':');
|
||||
if (colon1 == std::string::npos)
|
||||
continue;
|
||||
size_t colon2 = entry.find(':', colon1 + 1);
|
||||
if (colon2 == std::string::npos)
|
||||
continue;
|
||||
std::string hostB64 = trimWhitespace(entry.substr(0, colon1));
|
||||
std::string userB64 = trimWhitespace(entry.substr(colon1 + 1, colon2 - colon1 - 1));
|
||||
std::string passB64 = trimWhitespace(entry.substr(colon2 + 1));
|
||||
Account account;
|
||||
account.host = base64.decode(hostB64).str();
|
||||
account.user = base64.decode(userB64).str();
|
||||
account.password = base64.decode(passB64).str();
|
||||
entries.push_back(account);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
std::string __imapaccounts::encodeList(const std::vector<Account> &entries) {
|
||||
coreutils::Base64 base64;
|
||||
std::string result;
|
||||
for (size_t i = 0; i < entries.size(); i++) {
|
||||
if (i > 0)
|
||||
result += ";";
|
||||
std::string host = entries[i].host;
|
||||
std::string user = entries[i].user;
|
||||
std::string password = entries[i].password;
|
||||
result += base64.encode(host).str();
|
||||
result += ":";
|
||||
result += base64.encode(user).str();
|
||||
result += ":";
|
||||
result += base64.encode(password).str();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
__imapaccounts::__imapaccounts(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
std::string action = trimWhitespace(resolveKeyword("action").str());
|
||||
std::string listStr = resolveKeyword("list").str();
|
||||
auto entries = decodeList(listStr);
|
||||
|
||||
if (action == "add") {
|
||||
std::string host = trimWhitespace(resolveKeyword("host").str());
|
||||
std::string user = trimWhitespace(resolveKeyword("user").str());
|
||||
std::string password = trimWhitespace(resolveKeyword("password").str());
|
||||
for (size_t i = 0; i < entries.size(); i++) {
|
||||
if (entries[i].user == user) {
|
||||
entries.erase(entries.begin() + (long)i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Account account;
|
||||
account.host = host;
|
||||
account.user = user;
|
||||
account.password = password;
|
||||
entries.push_back(account);
|
||||
out = coreutils::MString(encodeList(entries));
|
||||
} else if (action == "remove") {
|
||||
std::string user = trimWhitespace(resolveKeyword("user").str());
|
||||
for (size_t i = 0; i < entries.size(); i++) {
|
||||
if (entries[i].user == user) {
|
||||
entries.erase(entries.begin() + (long)i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
out = coreutils::MString(encodeList(entries));
|
||||
} else if (action == "getpassword") {
|
||||
std::string user = trimWhitespace(resolveKeyword("user").str());
|
||||
std::string password;
|
||||
for (size_t i = 0; i < entries.size(); i++) {
|
||||
if (entries[i].user == user) {
|
||||
password = entries[i].password;
|
||||
break;
|
||||
}
|
||||
}
|
||||
out = coreutils::MString(password);
|
||||
} else if (action == "gethost") {
|
||||
std::string user = trimWhitespace(resolveKeyword("user").str());
|
||||
std::string host;
|
||||
for (size_t i = 0; i < entries.size(); i++) {
|
||||
if (entries[i].user == user) {
|
||||
host = entries[i].host;
|
||||
break;
|
||||
}
|
||||
}
|
||||
out = coreutils::MString(host);
|
||||
} else if (action == "firstuser") {
|
||||
out = coreutils::MString(entries.empty() ? std::string() : entries[0].user);
|
||||
} else if (action == "list") {
|
||||
std::string active = resolveKeyword("active").str();
|
||||
std::string json = "{\"accounts\":[";
|
||||
for (size_t i = 0; i < entries.size(); i++) {
|
||||
if (i > 0)
|
||||
json += ",";
|
||||
json += "\"" + jsonEscape(entries[i].user) + "\"";
|
||||
}
|
||||
json += "],\"active\":\"" + jsonEscape(active) + "\"}";
|
||||
out = coreutils::MString(json);
|
||||
} else {
|
||||
throw coreutils::Exception("imapaccounts: unknown action \"" + action + "\"", __FILE__, __LINE__, 500);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#ifndef ____imapaccounts_h__
|
||||
# define ____imapaccounts_h__
|
||||
|
||||
# include "Tag.h"
|
||||
# include "ZString.h"
|
||||
# include "MString.h"
|
||||
# include <string>
|
||||
# include <utility>
|
||||
# include <vector>
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imapaccounts action="add|remove|getpassword|gethost|firstuser|list"
|
||||
/// list="$[@_imap_accounts]" host="..." user="..." password="...">
|
||||
///
|
||||
/// Pure list-transform tag (no session-variable access of its own,
|
||||
/// no IMAP connection) that manages the multi-account list webmail
|
||||
/// keeps in the single session variable "_imap_accounts" - the .jet
|
||||
/// route wraps each call in <eval name="_imap_accounts"> itself and
|
||||
/// <set>s it back, the same separation-of-concerns every other
|
||||
/// session variable in this codebase already uses (this tag never
|
||||
/// touches Global's session-variable map directly).
|
||||
///
|
||||
/// The list's own on-the-wire encoding (semicolon-separated
|
||||
/// "base64(host):base64(user):base64(password)" entries) is private
|
||||
/// to this tag - callers only ever pass the whole `list` value back
|
||||
/// in verbatim and use the returned value the same way, so the
|
||||
/// choice of delimiter can't collide with any real username or
|
||||
/// password character. Each account can live on its own IMAP server
|
||||
/// (see the <imap>/<imaplist>/etc. tags' own optional host/port
|
||||
/// keywords), not just the one fixed host in email.cfg.
|
||||
///
|
||||
/// action="add": upserts host/user/password (removing any existing
|
||||
/// entry for the same user first, so reconnecting with a changed
|
||||
/// password or server updates it) - returns the updated encoded list.
|
||||
/// action="remove": drops the entry for user, if present - returns
|
||||
/// the updated encoded list.
|
||||
/// action="getpassword": returns the stored password for user, or
|
||||
/// an empty string if not present.
|
||||
/// action="gethost": returns the stored host for user, or an empty
|
||||
/// string if not present.
|
||||
/// action="firstuser": returns the first entry's username, or an
|
||||
/// empty string if the list is empty.
|
||||
/// action="list": returns JSON ({"accounts":[...],"active":"..."})
|
||||
/// - the one client-facing action; "active" echoes the `active`
|
||||
/// keyword (typically $[@_imap_user]) back verbatim so the sidebar
|
||||
/// can highlight the current one, and never includes any password or
|
||||
/// host (unchanged shape from before per-account hosts existed -
|
||||
/// nothing client-side needs the host to switch between already-
|
||||
/// connected accounts).
|
||||
///
|
||||
class __imapaccounts : public Tag {
|
||||
|
||||
struct Account {
|
||||
std::string host, user, password;
|
||||
};
|
||||
|
||||
public:
|
||||
__imapaccounts(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
private:
|
||||
static std::vector<Account> decodeList(const std::string &encoded);
|
||||
static std::string encodeList(const std::vector<Account> &entries);
|
||||
static std::string jsonEscape(const std::string &s);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,25 @@
|
||||
#include "__imapdelete.h"
|
||||
#include "Exception.h"
|
||||
#include "__imap.h"
|
||||
#include <cstdlib>
|
||||
|
||||
namespace jet {
|
||||
|
||||
__imapdelete::__imapdelete(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if (!global.imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid does not exist.", __FILE__, __LINE__, 502);
|
||||
|
||||
std::string folder = resolveKeyword("folder").str();
|
||||
if (folder.empty())
|
||||
folder = "INBOX";
|
||||
|
||||
if (!keywordDefined("uid"))
|
||||
throw coreutils::Exception("imapdelete tag must have uid defined.", __FILE__, __LINE__, 400);
|
||||
uint32_t uid = (uint32_t)strtoul(resolveKeyword("uid").str().c_str(), nullptr, 10);
|
||||
|
||||
out = global.getImapSession(sessionId)->deleteMessage(folder, uid);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#ifndef ____imapdelete_h__
|
||||
# define ____imapdelete_h__
|
||||
|
||||
# include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imapdelete sessionid="" folder="INBOX" uid="123">
|
||||
///
|
||||
/// Self-closing tag - marks \Deleted and EXPUNGEs one message,
|
||||
/// writes {"ok":true|false} into `out`. See __imaplist.h's doc
|
||||
/// comment for how `out` reaches the real response body.
|
||||
///
|
||||
|
||||
class __imapdelete : public Tag {
|
||||
|
||||
public:
|
||||
__imapdelete(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,26 @@
|
||||
#include "__imapemptyfolder.h"
|
||||
#include "Exception.h"
|
||||
#include "__imap.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
__imapemptyfolder::__imapemptyfolder(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if (!global.imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid does not exist.", __FILE__, __LINE__, 502);
|
||||
|
||||
// Unlike __imapdelete (one message - low blast radius even on a
|
||||
// wrong default), this permanently destroys an entire folder's
|
||||
// contents - no silent "defaults to INBOX" here. A missing/blank
|
||||
// folder attribute is refused outright rather than risked.
|
||||
if (!keywordDefined("folder"))
|
||||
throw coreutils::Exception("imapemptyfolder tag must have folder defined.", __FILE__, __LINE__, 400);
|
||||
std::string folder = resolveKeyword("folder").str();
|
||||
if (folder.empty())
|
||||
throw coreutils::Exception("imapemptyfolder tag must have folder defined.", __FILE__, __LINE__, 400);
|
||||
|
||||
out = global.getImapSession(sessionId)->emptyFolder(folder);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#ifndef ____imapemptyfolder_h__
|
||||
# define ____imapemptyfolder_h__
|
||||
|
||||
# include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imapemptyfolder sessionid="" folder="Trash">
|
||||
///
|
||||
/// Self-closing tag - permanently deletes every message in the given
|
||||
/// folder (mark-all-\Deleted + one EXPUNGE, not a per-message loop),
|
||||
/// writes {"ok":true|false} into `out`. See __imaplist.h's doc
|
||||
/// comment for how `out` reaches the real response body.
|
||||
///
|
||||
|
||||
class __imapemptyfolder : public Tag {
|
||||
|
||||
public:
|
||||
__imapemptyfolder(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,32 @@
|
||||
#include "__imapflag.h"
|
||||
#include "Exception.h"
|
||||
#include "__imap.h"
|
||||
#include <cstdlib>
|
||||
|
||||
namespace jet {
|
||||
|
||||
__imapflag::__imapflag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if (!global.imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid does not exist.", __FILE__, __LINE__, 502);
|
||||
|
||||
std::string folder = resolveKeyword("folder").str();
|
||||
if (folder.empty())
|
||||
folder = "INBOX";
|
||||
|
||||
if (!keywordDefined("uid"))
|
||||
throw coreutils::Exception("imapflag tag must have uid defined.", __FILE__, __LINE__, 400);
|
||||
uint32_t uid = (uint32_t)strtoul(resolveKeyword("uid").str().c_str(), nullptr, 10);
|
||||
|
||||
if (!keywordDefined("flag"))
|
||||
throw coreutils::Exception("imapflag tag must have flag defined.", __FILE__, __LINE__, 400);
|
||||
std::string flag = resolveKeyword("flag").str();
|
||||
|
||||
std::string setStr = resolveKeyword("set").str();
|
||||
bool add = setStr.empty() || setStr == "yes" || setStr == "true";
|
||||
|
||||
out = global.getImapSession(sessionId)->setFlag(folder, uid, flag, add);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#ifndef ____imapflag_h__
|
||||
# define ____imapflag_h__
|
||||
|
||||
# include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imapflag sessionid="" folder="INBOX" uid="123" flag="\Seen" set="yes">
|
||||
///
|
||||
/// Self-closing tag - STOREs (adds, or removes when set="no") a
|
||||
/// single IMAP flag on one message, writes {"ok":true|false} into
|
||||
/// `out`. See __imaplist.h's doc comment for how `out` reaches the
|
||||
/// real response body.
|
||||
///
|
||||
|
||||
class __imapflag : public Tag {
|
||||
|
||||
public:
|
||||
__imapflag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,16 @@
|
||||
#include "__imapfolders.h"
|
||||
#include "Exception.h"
|
||||
#include "__imap.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
__imapfolders::__imapfolders(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if (!global.imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid does not exist.", __FILE__, __LINE__, 502);
|
||||
|
||||
out = global.getImapSession(sessionId)->folderCounts();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef ____imapfolders_h__
|
||||
# define ____imapfolders_h__
|
||||
|
||||
# include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imapfolders sessionid="">
|
||||
///
|
||||
/// Self-closing tag - writes {"Inbox":{"messages":n,"unseen":n},
|
||||
/// "Spam":{...},"Trash":{...}} into `out` (see
|
||||
/// __imap::folderCounts()'s own doc comment for why it's this fixed
|
||||
/// 3-folder set specifically). See __imaplist.h's doc comment for
|
||||
/// how `out` reaches the real response body.
|
||||
///
|
||||
|
||||
class __imapfolders : public Tag {
|
||||
|
||||
public:
|
||||
__imapfolders(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "__imaplist.h"
|
||||
#include "Exception.h"
|
||||
#include "__imap.h"
|
||||
#include <cstdlib>
|
||||
|
||||
namespace jet {
|
||||
|
||||
__imaplist::__imaplist(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if (!global.imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid does not exist.", __FILE__, __LINE__, 502);
|
||||
|
||||
std::string folder = resolveKeyword("folder").str();
|
||||
if (folder.empty())
|
||||
folder = "INBOX";
|
||||
|
||||
std::string limitStr = resolveKeyword("limit").str();
|
||||
int limit = limitStr.empty() ? 50 : atoi(limitStr.c_str());
|
||||
if (limit <= 0)
|
||||
limit = 50;
|
||||
|
||||
std::string offsetStr = resolveKeyword("offset").str();
|
||||
int offset = offsetStr.empty() ? 0 : atoi(offsetStr.c_str());
|
||||
if (offset < 0)
|
||||
offset = 0;
|
||||
|
||||
out = global.getImapSession(sessionId)->listMessages(folder, limit, offset);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef ____imaplist_h__
|
||||
# define ____imaplist_h__
|
||||
|
||||
# include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imaplist sessionid="" folder="INBOX" limit="50">
|
||||
///
|
||||
/// Self-closing tag (no container) - writes a JSON array of message
|
||||
/// summaries for `folder`, newest first, straight into `out`, the
|
||||
/// same way any other self-closing value tag with default
|
||||
/// output=true/evaluate=true does: Tag::~Tag() copies `out` into the
|
||||
/// caller's parentOut verbatim (Tag::copyContainer() is a raw byte
|
||||
/// copy, no re-evaluation - see Tag.cpp - so literal "$"/"["/"<" in
|
||||
/// real email subjects pass through unmolested; __imap::jsonEscape()
|
||||
/// already handled quote/backslash/control-char JSON-escaping).
|
||||
///
|
||||
|
||||
class __imaplist : public Tag {
|
||||
|
||||
public:
|
||||
__imaplist(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,25 @@
|
||||
#include "__imapmessage.h"
|
||||
#include "Exception.h"
|
||||
#include "__imap.h"
|
||||
#include <cstdlib>
|
||||
|
||||
namespace jet {
|
||||
|
||||
__imapmessage::__imapmessage(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if (!global.imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid does not exist.", __FILE__, __LINE__, 502);
|
||||
|
||||
std::string folder = resolveKeyword("folder").str();
|
||||
if (folder.empty())
|
||||
folder = "INBOX";
|
||||
|
||||
if (!keywordDefined("uid"))
|
||||
throw coreutils::Exception("imapmessage tag must have uid defined.", __FILE__, __LINE__, 400);
|
||||
uint32_t uid = (uint32_t)strtoul(resolveKeyword("uid").str().c_str(), nullptr, 10);
|
||||
|
||||
out = global.getImapSession(sessionId)->fetchMessage(folder, uid);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#ifndef ____imapmessage_h__
|
||||
# define ____imapmessage_h__
|
||||
|
||||
# include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imapmessage sessionid="" folder="INBOX" uid="123">
|
||||
///
|
||||
/// Self-closing tag - writes a single JSON message object (headers +
|
||||
/// text body) into `out`. See __imaplist.h's doc comment for how
|
||||
/// `out` reaches the real response body.
|
||||
///
|
||||
|
||||
class __imapmessage : public Tag {
|
||||
|
||||
public:
|
||||
__imapmessage(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,29 @@
|
||||
#include "__imapmove.h"
|
||||
#include "Exception.h"
|
||||
#include "__imap.h"
|
||||
#include <cstdlib>
|
||||
|
||||
namespace jet {
|
||||
|
||||
__imapmove::__imapmove(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if (!global.imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid does not exist.", __FILE__, __LINE__, 502);
|
||||
|
||||
std::string folder = resolveKeyword("folder").str();
|
||||
if (folder.empty())
|
||||
folder = "INBOX";
|
||||
|
||||
if (!keywordDefined("uid"))
|
||||
throw coreutils::Exception("imapmove tag must have uid defined.", __FILE__, __LINE__, 400);
|
||||
uint32_t uid = (uint32_t)strtoul(resolveKeyword("uid").str().c_str(), nullptr, 10);
|
||||
|
||||
if (!keywordDefined("destfolder"))
|
||||
throw coreutils::Exception("imapmove tag must have destfolder defined.", __FILE__, __LINE__, 400);
|
||||
std::string destFolder = resolveKeyword("destfolder").str();
|
||||
|
||||
out = global.getImapSession(sessionId)->moveMessage(folder, uid, destFolder);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef ____imapmove_h__
|
||||
# define ____imapmove_h__
|
||||
|
||||
# include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imapmove sessionid="" folder="INBOX" uid="123" destfolder="Trash">
|
||||
///
|
||||
/// Self-closing tag - moves one message into destfolder (COPY there,
|
||||
/// then \Deleted + EXPUNGE from the original folder, the standard
|
||||
/// pre-RFC6851 two-step "move" every IMAP client used before the
|
||||
/// MOVE extension existed - see __imap::moveMessage()'s own doc
|
||||
/// comment for why this server doesn't just speak that extension
|
||||
/// directly). Writes {"ok":true|false} into `out`, same convention
|
||||
/// as __imapdelete/__imapflag.
|
||||
///
|
||||
|
||||
class __imapmove : public Tag {
|
||||
|
||||
public:
|
||||
__imapmove(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,22 @@
|
||||
#include "__imapsearch.h"
|
||||
#include "Exception.h"
|
||||
#include "__imap.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
__imapsearch::__imapsearch(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if (!global.imapSessionExists(sessionId))
|
||||
throw coreutils::Exception("imap sessionid does not exist.", __FILE__, __LINE__, 502);
|
||||
|
||||
std::string folder = resolveKeyword("folder").str();
|
||||
if (folder.empty())
|
||||
folder = "INBOX";
|
||||
|
||||
std::string query = resolveKeyword("query").str();
|
||||
|
||||
out = global.getImapSession(sessionId)->searchMessages(folder, query);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef ____imapsearch_h__
|
||||
# define ____imapsearch_h__
|
||||
|
||||
# include "Tag.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <imapsearch sessionid="" folder="INBOX" query="text">
|
||||
///
|
||||
/// Self-closing tag - writes a JSON array of message summaries
|
||||
/// (same shape as <imaplist>) for every message in `folder` whose
|
||||
/// From, Subject, or body matches `query` (see
|
||||
/// __imap::searchMessages()'s own doc comment), newest first,
|
||||
/// straight into `out`.
|
||||
///
|
||||
|
||||
class __imapsearch : public Tag {
|
||||
|
||||
public:
|
||||
__imapsearch(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,35 +1,104 @@
|
||||
#include "__include.h"
|
||||
#include "Exception.h"
|
||||
#include "File.h"
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <sys/stat.h>
|
||||
|
||||
namespace jet {
|
||||
|
||||
|
||||
namespace {
|
||||
struct CachedInclude {
|
||||
std::string content;
|
||||
time_t mtime;
|
||||
};
|
||||
// Persistent, per-worker-thread cache of <include> file contents,
|
||||
// keyed by resolved filename. Real content depends on this
|
||||
// constantly through custom tag bodies that jetc's own compile-
|
||||
// time <include>-inlining doesn't reach (only the top-level .jet
|
||||
// source's own includes get compiled in) - mainpagetemplate.temp
|
||||
// alone pulls in login.menu/menu.bar/opensource.menu/cart.menu/
|
||||
// sessionvar.menu, all previously re-read from disk on every
|
||||
// single request even though the files are 100% static between
|
||||
// edits. Invalidated via mtime comparison (a stat() call, cheap
|
||||
// relative to a full read()) so a live edit still takes effect on
|
||||
// the very next request - matching the workflow already relied on
|
||||
// all session of editing .tag/.temp/.menu content directly and
|
||||
// seeing it live without a rebuild.
|
||||
thread_local std::unordered_map<std::string, CachedInclude> includeCache;
|
||||
}
|
||||
|
||||
__include::__include(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
if(!keywordDefined("file"))
|
||||
throw coreutils::Exception("file keyword must be specified.");
|
||||
if(hasContainer)
|
||||
throw coreutils::Exception("include tag should not have a container.");
|
||||
hasContainer = true;
|
||||
coreutils::File file(resolveKeyword("file"));
|
||||
file.read();
|
||||
container = file.asZString();
|
||||
try {
|
||||
coreutils::MString includeFileName = resolveKeyword("file");
|
||||
std::string fileNameKey = includeFileName.str();
|
||||
|
||||
struct stat st;
|
||||
bool haveStat = (stat(fileNameKey.c_str(), &st) == 0);
|
||||
|
||||
auto cached = includeCache.find(fileNameKey);
|
||||
if(cached != includeCache.end() && haveStat && cached->second.mtime == st.st_mtime) {
|
||||
container = coreutils::ZString(cached->second.content.data(), cached->second.content.length());
|
||||
} else {
|
||||
coreutils::File file(includeFileName);
|
||||
file.read();
|
||||
if(haveStat) {
|
||||
CachedInclude &entry = includeCache[fileNameKey];
|
||||
entry.content = file.asString();
|
||||
entry.mtime = st.st_mtime;
|
||||
container = coreutils::ZString(entry.content.data(), entry.content.length());
|
||||
} else {
|
||||
// Couldn't stat the file (unusual - e.g. a race with deletion) -
|
||||
// don't cache something we can't validate the freshness of,
|
||||
// just render this one read directly, matching the pre-cache
|
||||
// behavior exactly for this edge case.
|
||||
container = file.asZString();
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
processContainer(container);
|
||||
}
|
||||
catch(coreutils::Exception e) {
|
||||
container.setCursor(global.errorCursor);
|
||||
container.moveBackToLineStart();
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
std::cout << "Error in included script '" << variables["file"] << "' at line " << container.getLineNumberAtCursor() << std::endl;
|
||||
std::cout << "Error text: " << e.text << std::endl;
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
std::cout << container.parsed() << std::endl;
|
||||
std::cout << "******** Error caught: " << e.text << std::endl;
|
||||
std::cout << container.unparsed() << std::endl;
|
||||
// global.errorCursor is whatever cursor was active in whichever
|
||||
// ZString buffer was being parsed at the moment the ORIGINAL
|
||||
// exception was thrown - not necessarily this include's own
|
||||
// `container` buffer at all (e.g. a keyword-resolution error
|
||||
// happening while interpreting a completely different .temp
|
||||
// file's own text). setCursor() on a pointer outside container's
|
||||
// own [data, data+length] range throws "Cursor out of range on
|
||||
// setCursor." - and since that happens INSIDE this diagnostic-
|
||||
// only "show a nice line number" block, it was replacing the
|
||||
// real error (e.text) with that unrelated cursor-range message
|
||||
// before it ever reached the caller, making every real error
|
||||
// from inside an <include> impossible to see. This is purely
|
||||
// diagnostic output - if it can't compute a line number, fall
|
||||
// back to printing the real error text without one rather than
|
||||
// losing it entirely.
|
||||
try {
|
||||
container.setCursor(global.errorCursor);
|
||||
container.moveBackToLineStart();
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
std::cout << "Error in included script '" << variables["file"] << "' at line " << container.getLineNumberAtCursor() << std::endl;
|
||||
std::cout << "Error text: " << e.text << std::endl;
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
std::cout << container.parsed() << std::endl;
|
||||
std::cout << "******** Error caught: " << e.text << std::endl;
|
||||
std::cout << container.unparsed() << std::endl;
|
||||
} catch(coreutils::Exception &) {
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
std::cout << "Error in included script '" << variables["file"] << "' (line number unavailable - error originated outside this include's own content)" << std::endl;
|
||||
std::cout << "Error text: " << e.text << std::endl;
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
}
|
||||
global.errorCursor = in.getCursor();
|
||||
throw coreutils::Exception("error in included file.");
|
||||
throw coreutils::Exception(e.text);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -2,46 +2,107 @@
|
||||
#include "Exception.h"
|
||||
#include "Global.h"
|
||||
#include "SessionId.h"
|
||||
#include <stdlib.h>
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace jet {
|
||||
|
||||
__jet::__jet(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this) {
|
||||
char *cookies;
|
||||
if(keywordDefined("cgi") && (resolveKeyword("cgi") == "true")) {
|
||||
if(keywordDefined("cgi") && (resolveKeyword("cgi") == "yes")) {
|
||||
global.cgi = true;
|
||||
|
||||
if(keywordDefined("sessiondir")) {
|
||||
global.session = true;
|
||||
global.cookies = getenv("HTTP_COOKIE");
|
||||
|
||||
// if request_has_cookie then
|
||||
// pull sessionfile from sessiondir.
|
||||
coreutils::MString sessionIdValue;
|
||||
if(global.cookies.data["session"] != NULL) {
|
||||
sessionIdValue = global.cookies.data["session"];
|
||||
// if last activity time is expired then ignore.
|
||||
// follow sessiontimeoutredirecturl.
|
||||
// else
|
||||
SessionId sessionId;
|
||||
global.headers["Set-Cookie"] << "session=" << sessionId;
|
||||
if(keywordDefined("sessiontimeout")) {
|
||||
time_t timeout = time(0) + keywords["sessiontimeout"].asInteger();
|
||||
} else {
|
||||
SessionId sessionId;
|
||||
// A 160-bit CSPRNG value colliding with an existing session file
|
||||
// is astronomically unlikely, but cheap to guard against outright
|
||||
// rather than trust the probability - regenerate on an actual
|
||||
// collision instead of ever reusing another session's file.
|
||||
int sessionIdAttempts = 0;
|
||||
while(true) {
|
||||
coreutils::MString candidatePath;
|
||||
candidatePath << resolveKeyword("sessiondir") << "/" << sessionId << ".json";
|
||||
if(access(candidatePath.c_str(), F_OK) != 0)
|
||||
break;
|
||||
if(++sessionIdAttempts >= 5)
|
||||
throw coreutils::Exception("could not generate a unique session id after multiple attempts.");
|
||||
sessionId = SessionId();
|
||||
}
|
||||
global.headers["Set-Cookie"] << "session=" << sessionId;
|
||||
global.cookies.data["session"] = sessionId;
|
||||
sessionIdValue = sessionId;
|
||||
if(keywordDefined("sessiontimeout")) {
|
||||
time_t timeout = time(0) + keywords["sessiontimeout"].asInteger();
|
||||
}
|
||||
// also save last activity time in session file.
|
||||
}
|
||||
|
||||
// also save last activity time in session file.
|
||||
|
||||
|
||||
// JFile's own RAII behavior (see CoreUtils MFile.cpp) loads
|
||||
// whatever JSON is already at this path, or starts empty if the
|
||||
// file doesn't exist yet (a brand-new session), and writes any
|
||||
// changes back automatically when destroyed - no explicit save
|
||||
// call needed anywhere.
|
||||
coreutils::MString sessionFilePath;
|
||||
sessionFilePath << resolveKeyword("sessiondir");
|
||||
sessionFilePath << "/";
|
||||
sessionFilePath << sessionIdValue;
|
||||
sessionFilePath << ".json";
|
||||
global.sessionFile = new coreutils::JFile(sessionFilePath);
|
||||
}
|
||||
|
||||
|
||||
coreutils::ZString requestMethod(getenv("REQUEST_METHOD"));
|
||||
if(requestMethod == "POST") {
|
||||
coreutils::ZString contentLength(getenv("CONTENT_LENGTH"));
|
||||
coreutils::ZString contentType(getenv("CONTENT_TYPE"));
|
||||
|
||||
if(contentType == "multipart/form-data")
|
||||
coreutils::IMFMultipart postdata(0, "");
|
||||
|
||||
// else if(contentType == "application/x-www-form-urlencoded")
|
||||
// global.setupFormURLEncoded(postdata);
|
||||
}
|
||||
coreutils::ZString boundary;
|
||||
int boundaryPos = contentType.find("boundary=");
|
||||
if(boundaryPos != -1) {
|
||||
boundary = contentType.substring(boundaryPos + 9);
|
||||
}
|
||||
// find() leaves contentType's own cursor at the match position -
|
||||
// reset it before handing contentType to CGIFormData, whose
|
||||
// startsWith("multipart/form-data")/startsWith("application/...")
|
||||
// checks are cursor-relative and would otherwise silently miss,
|
||||
// falling through to an unrecognized content type that never
|
||||
// parses anything.
|
||||
contentType.reset();
|
||||
|
||||
int bodyLength = contentLength.asInteger();
|
||||
global.cgiData = new coreutils::CGIFormData(global.cgiReader, contentType, bodyLength, boundary);
|
||||
|
||||
// Feed the request body off stdin in chunks and drive the parser
|
||||
// resumably (the same feed()/doParse() pattern as a socket-fed
|
||||
// StreamReader) rather than blocking to read it all before parsing
|
||||
// starts - keeps memory bounded for large multipart uploads and
|
||||
// exercises the real Parser::Status::INCOMPLETE resumption path.
|
||||
char cgiReadBuf[4096];
|
||||
int cgiBytesRead = 0;
|
||||
coreutils::Parser::Status cgiStatus = coreutils::Parser::Status::INCOMPLETE;
|
||||
while(cgiBytesRead < bodyLength && cgiStatus != coreutils::Parser::Status::COMPLETE) {
|
||||
int want = bodyLength - cgiBytesRead;
|
||||
if(want > (int)sizeof(cgiReadBuf))
|
||||
want = sizeof(cgiReadBuf);
|
||||
int got = ::read(0, cgiReadBuf, want);
|
||||
if(got <= 0)
|
||||
throw coreutils::Exception("CGI request body ended before Content-Length was reached.");
|
||||
cgiBytesRead += got;
|
||||
coreutils::ZString chunk(cgiReadBuf, got);
|
||||
global.cgiReader.feed(chunk);
|
||||
cgiStatus = global.cgiData->doParse();
|
||||
}
|
||||
if(cgiStatus != coreutils::Parser::Status::COMPLETE)
|
||||
throw coreutils::Exception("CGI request body did not parse to completion.");
|
||||
}
|
||||
}
|
||||
processContainer(container, NULL, true);
|
||||
}
|
||||
|
||||
@@ -3,8 +3,7 @@
|
||||
|
||||
#include "Tag.h"
|
||||
#include "ZString.h"
|
||||
#include "IMFRequest.h"
|
||||
#include "IMFMessage.h"
|
||||
//#include "IMFMessage.h"
|
||||
#include <sstream>
|
||||
|
||||
namespace jet {
|
||||
|
||||
@@ -1,33 +1,149 @@
|
||||
#include "__mysql.h"
|
||||
#include "Exception.h"
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace jet {
|
||||
|
||||
namespace {
|
||||
struct PooledConnection {
|
||||
MYSQL *handle;
|
||||
std::string host, user, database;
|
||||
};
|
||||
// Persistent, per-worker-thread connection cache - reused across
|
||||
// requests instead of a fresh mysql_real_connect() every time.
|
||||
// Safe with no locking: the apiserver's EPoll worker pool is a
|
||||
// fixed set of OS threads for the process's whole life (see
|
||||
// MysqlThreadScope's own doc comment - mysql_thread_init() runs
|
||||
// once per worker thread at thread start), so a thread_local
|
||||
// instance here means a given MYSQL* handle is only ever touched
|
||||
// by the one thread that created it, never concurrently accessed.
|
||||
// Keyed by sessionid, which is how this codebase's own <database>/
|
||||
// <sql>/<ifrow> tags already address a specific connection
|
||||
// (Global::sessions is keyed the same way) - the cached host/user/
|
||||
// database are kept alongside purely as a defensive check that a
|
||||
// reused entry really matches what THIS invocation asked for,
|
||||
// not a real expectation that sessionid is ever reused across
|
||||
// genuinely different backing databases in practice.
|
||||
thread_local std::unordered_map<std::string, PooledConnection> connectionPool;
|
||||
}
|
||||
|
||||
__mysql::__mysql(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this) {
|
||||
|
||||
if(!keywordDefined("host"))
|
||||
throw coreutils::Exception("host must be specified for mysql tag.");
|
||||
if(!keywordDefined("database"))
|
||||
// jet-1.4's <database> spells the same attribute "name" instead of
|
||||
// "database" (e.g. SESSIONCTL.tag's own <sessionctl> definition) -
|
||||
// accept either rather than requiring that real content to change.
|
||||
coreutils::ZString databaseKeyword = keywordDefined("database") ? "database" : "name";
|
||||
if(!keywordDefined(databaseKeyword))
|
||||
throw coreutils::Exception("database must be specified for mysql tag.");
|
||||
if(!keywordDefined("user"))
|
||||
throw coreutils::Exception("user must be specified for mysql tag.");
|
||||
if(!keywordDefined("password"))
|
||||
throw coreutils::Exception("password must be specified for mysql tag.");
|
||||
|
||||
sessionId = keywords[resolveKeyword("sessionid")];
|
||||
|
||||
// Same double-indirection bug as the host/user/password/database
|
||||
// fix above - resolveKeyword("sessionid") already returns the
|
||||
// resolved VALUE (e.g. "_SESSIONCTL"), so wrapping it in keywords[...]
|
||||
// used that value as a map KEY instead, auto-vivifying an empty
|
||||
// string (no attribute is ever literally named "_SESSIONCTL").
|
||||
// sessionId was therefore always empty regardless of what
|
||||
// sessionid= actually specified - confirmed live via gdb: two
|
||||
// real <mysql>/<database> tags with genuinely different sessionid
|
||||
// values ("" and "_SESSIONCTL") both registered under "", the
|
||||
// second colliding with "sessionid already exists.".
|
||||
sessionId = resolveKeyword("sessionid");
|
||||
|
||||
// mysql_real_connect() returns NULL on failure but does NOT itself
|
||||
// free the handle mysql_init() allocated - the caller is still
|
||||
// expected to mysql_close() that original handle to avoid leaking
|
||||
// it (MySQL C API docs). The previous code overwrote `mysql` with
|
||||
// the connect() return value directly, so on failure the only
|
||||
// pointer to the real handle was lost before ever being freed - a
|
||||
// real leak on every failed connection attempt (this member's
|
||||
// eventual value, NULL, is what a normal ~__mysql() would try to
|
||||
// mysql_close() anyway, which is a safe no-op, but that never even
|
||||
// runs here since the constructor throws below - see the
|
||||
// addSession() comment for why that matters more).
|
||||
// resolveKeyword() already returns the fully-resolved VALUE - the
|
||||
// previous keywords[resolveKeyword("host")] wrapped that resolved
|
||||
// VALUE ("localhost") back into a keywords[] lookup, i.e. used it
|
||||
// as a MAP KEY instead of the value itself. Since no attribute is
|
||||
// ever literally named "localhost"/the real username/etc.,
|
||||
// std::map::operator[] silently auto-vivified an empty MString for
|
||||
// every one of the four parameters - mysql_real_connect() was
|
||||
// therefore always called with host/user/password/database all
|
||||
// empty, regardless of what the tag actually specified. Confirmed
|
||||
// live: MySQL's own error ("Access denied for user 'barant'@'localhost'
|
||||
// (using password: NO)") showed the password was genuinely empty,
|
||||
// not merely wrong.
|
||||
coreutils::MString hostVal = resolveKeyword("host");
|
||||
coreutils::MString userVal = resolveKeyword("user");
|
||||
coreutils::MString passwordVal = resolveKeyword("password");
|
||||
coreutils::MString databaseVal = resolveKeyword(databaseKeyword);
|
||||
|
||||
// Reuse a live connection this same worker thread already holds
|
||||
// for this sessionid, rather than paying mysql_real_connect()'s
|
||||
// full handshake cost on every single request. mysql_ping() is
|
||||
// what makes this safe - it's a genuine round trip to the server,
|
||||
// so a connection MySQL itself already dropped (its own
|
||||
// wait_timeout, or an admin-initiated restart like this project
|
||||
// already lived through once) is detected and discarded here
|
||||
// rather than handed to processContainer() to fail on later.
|
||||
std::string poolKey = sessionId.str();
|
||||
auto pooled = connectionPool.find(poolKey);
|
||||
if(pooled != connectionPool.end() &&
|
||||
pooled->second.host == hostVal.str() &&
|
||||
pooled->second.user == userVal.str() &&
|
||||
pooled->second.database == databaseVal.str()) {
|
||||
if(mysql_ping(pooled->second.handle) == 0) {
|
||||
mysql = pooled->second.handle;
|
||||
} else {
|
||||
mysql_close(pooled->second.handle);
|
||||
connectionPool.erase(pooled);
|
||||
}
|
||||
}
|
||||
|
||||
if(!mysql) {
|
||||
MYSQL *handle = mysql_init(NULL);
|
||||
// Pin the connection character set so <bind>'s client-side
|
||||
// escaping and the server's parsing always agree (<sql> refuses
|
||||
// SET NAMES and friends for the same reason).
|
||||
mysql_options(handle, MYSQL_SET_CHARSET_NAME, "utf8mb4");
|
||||
mysql = mysql_real_connect(handle,
|
||||
hostVal.c_str(),
|
||||
userVal.c_str(),
|
||||
passwordVal.c_str(),
|
||||
databaseVal.c_str(), 0, NULL, 0);
|
||||
|
||||
if(!mysql) {
|
||||
std::string err = mysql_error(handle);
|
||||
mysql_close(handle);
|
||||
throw coreutils::Exception("database connection failed: " + err);
|
||||
}
|
||||
|
||||
connectionPool[poolKey] = PooledConnection{mysql, hostVal.str(), userVal.str(), databaseVal.str()};
|
||||
}
|
||||
|
||||
// Registered only once the connection is confirmed live - a real,
|
||||
// reproducible crash (heap corruption - "free(): invalid pointer"
|
||||
// seen live, then two independent server-hang repros) traced back
|
||||
// to this: addSession() used to run BEFORE the connect attempt, so
|
||||
// a FAILED connection (which throws, right above) left a dangling
|
||||
// `this` pointer registered under sessionId in Global's session
|
||||
// map forever - ~__mysql() (which would normally call
|
||||
// removeSession()) never runs for a constructor that itself threw,
|
||||
// per ordinary C++ rules (only already-completed base-class
|
||||
// subobjects get destroyed during exception unwinding, not the
|
||||
// derived object whose constructor is still executing). The very
|
||||
// next <mysql> tag construction using the same sessionId (e.g. two
|
||||
// product pages with an empty sessionid="" back to back, both
|
||||
// failing the same way) then collided with that stale entry.
|
||||
// Confirmed via a real, deterministic two-request repro before this
|
||||
// fix, and confirmed gone after it.
|
||||
global.addSession(sessionId, this);
|
||||
|
||||
mysql = mysql_init(NULL);
|
||||
mysql = mysql_real_connect(mysql,
|
||||
keywords[resolveKeyword("host")].c_str(),
|
||||
keywords[resolveKeyword("user")].c_str(),
|
||||
keywords[resolveKeyword("password")].c_str(),
|
||||
keywords[resolveKeyword("database")].c_str(), 0, NULL, 0);
|
||||
|
||||
if(!mysql)
|
||||
throw coreutils::Exception("database and host parameters are not valid.");
|
||||
|
||||
processContainer(container);
|
||||
|
||||
@@ -36,19 +152,78 @@ namespace jet {
|
||||
__mysql::~__mysql() {
|
||||
global.removeSession(sessionId);
|
||||
mysql_free_result(result);
|
||||
mysql_close(mysql);
|
||||
// mysql itself is deliberately NOT closed here anymore - see the
|
||||
// connectionPool doc comment above the constructor. It's owned by
|
||||
// this worker thread's persistent pool now and gets reused by
|
||||
// whatever request this thread handles next, instead of being
|
||||
// torn down and fully reconnected from scratch every time.
|
||||
}
|
||||
|
||||
void __mysql::query(coreutils::MString query) {
|
||||
int rc = mysql_real_query(mysql, query.getData(), query.getLength());
|
||||
// rc was captured but never checked - a genuinely failed query
|
||||
// (syntax error, constraint violation, etc.) fell straight into
|
||||
// the result==NULL branch below, which is ALSO the normal path
|
||||
// for a successful non-SELECT statement (INSERT/UPDATE/DELETE
|
||||
// have no result set to store either). That made every SQL error
|
||||
// in the whole codebase silently indistinguishable from "ran fine,
|
||||
// no rows" - <try>/<catch> around a failing <sql> never caught
|
||||
// anything, since no exception was ever thrown in the first place.
|
||||
// Only rc (mysql_real_query's own success/failure signal) can
|
||||
// actually tell the two cases apart; result's nullness can't.
|
||||
if(rc != 0)
|
||||
throw coreutils::Exception(std::string("mysql query failed: ") + mysql_error(mysql));
|
||||
result = mysql_store_result(mysql);
|
||||
if(result) {
|
||||
row = mysql_fetch_row(result);
|
||||
fieldLength = mysql_fetch_lengths(result);
|
||||
qFields = mysql_num_fields(result);
|
||||
// Built once per query, not once per column LOOKUP - see the
|
||||
// matching comment on getColumnValue() and on fieldIndex's own
|
||||
// declaration in __mysql.h. mysql_fetch_fields() returns the
|
||||
// whole field array in one call (mysql_fetch_field_direct()
|
||||
// looping ix=0..qFields-1, as getColumnValue() used to do on
|
||||
// every single named access, does the exact same work over and
|
||||
// over for a result set whose schema never changes after this
|
||||
// point).
|
||||
fieldIndex.clear();
|
||||
MYSQL_FIELD *fields = mysql_fetch_fields(result);
|
||||
for(unsigned int ix = 0; ix < qFields; ++ix)
|
||||
fieldIndex[std::string(fields[ix].name)] = (int)ix;
|
||||
} else {
|
||||
// A failed/errored query (real content builds one from an unset
|
||||
// $[...] parameter, e.g. "where tasks.id=" with no value - genuine
|
||||
// MySQL syntax error) previously left row/qFields holding whatever
|
||||
// a PRIOR successful query on this same session object had set,
|
||||
// since only the success branch above ever touched them. A later
|
||||
// getColumnValue() call then looped 0..qFields (stale, nonzero)
|
||||
// calling mysql_fetch_field_direct() against this NULL `result` -
|
||||
// segfaulting (confirmed via gdb: SIGSEGV in
|
||||
// mysql_fetch_field_direct, called from getColumnValue) instead of
|
||||
// reaching the "column does not exist in session result." the
|
||||
// caller already throws/catches for a genuinely missing column.
|
||||
// Resetting both here makes a failed query present as "no row, no
|
||||
// columns" - clean and consistent regardless of what ran before it
|
||||
// on this session.
|
||||
row = NULL;
|
||||
qFields = 0;
|
||||
fieldIndex.clear();
|
||||
}
|
||||
}
|
||||
|
||||
std::string __mysql::escapeString(const std::string &value) {
|
||||
std::string to(value.size() * 2 + 1, '\0');
|
||||
unsigned long len = mysql_real_escape_string_quote(mysql, to.data(), value.data(), value.size(), '\'');
|
||||
if(len == (unsigned long)-1)
|
||||
throw coreutils::Exception("sql: bind value could not be escaped.");
|
||||
to.resize(len);
|
||||
return to;
|
||||
}
|
||||
|
||||
bool __mysql::noBackslashEscapes() {
|
||||
return (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES) != 0;
|
||||
}
|
||||
|
||||
void __mysql::nextRow() {
|
||||
row = mysql_fetch_row(result);
|
||||
fieldLength = mysql_fetch_lengths(result);
|
||||
@@ -63,25 +238,51 @@ namespace jet {
|
||||
if(column == "?#") {
|
||||
nbrOfColumns = (int)qFields;
|
||||
return nbrOfColumns;
|
||||
} else if(column.ifNext("#")) {
|
||||
} else if(column.ifNext("#") || column.ifNext("?")) {
|
||||
// "#N"/"?N" (column name at 1-based position N) are the same
|
||||
// jet-1.4 syntax under two different prefixes - real, unmodified
|
||||
// 1.4 content uses both (barant.tag's own <showtable> definition
|
||||
// writes $[?$[index]], never $[#$[index]]) - confirmed via a real
|
||||
// repro: admin.page's own Users/Products tables rendered every
|
||||
// column header and cell completely blank, since "?N" fell all
|
||||
// the way through to the ordinary column-VALUE lookup below
|
||||
// (nothing named "?3" exists in the row) and read as empty rather
|
||||
// than as "the name of column 3", per the jet-1.4-fallback #2
|
||||
// empty-string-on-missing-column behavior elsewhere in this
|
||||
// codebase (see Tag.cpp).
|
||||
if(column.eod()) {
|
||||
nbrOfRows = (int)mysql_num_rows(result);
|
||||
return nbrOfRows;
|
||||
} else {
|
||||
std::cout << "[" << column.unparsed() << "]" << std::endl;
|
||||
int index = column.asInteger();
|
||||
std::cout << "integer: " << index << std::endl;
|
||||
field = mysql_fetch_field_direct(result, index - 1);
|
||||
return coreutils::ZString(field->name);
|
||||
return coreutils::ZString(field->name);
|
||||
}
|
||||
}
|
||||
|
||||
for(int ix = 0; ix < qFields; ++ix) {
|
||||
field = mysql_fetch_field_direct(result, ix);
|
||||
if(column.equals((char *)field->name)) {
|
||||
return coreutils::ZString(row[ix], fieldLength[ix]);
|
||||
}
|
||||
}
|
||||
|
||||
// A query that ran successfully but matched zero rows (a real,
|
||||
// valid query - e.g. cart.page's own aggregate/JOIN query against
|
||||
// an empty cart session - not a failed one, see query()'s own
|
||||
// row=NULL/qFields=0 reset above for that separate case) leaves
|
||||
// qFields correctly reflecting the real schema but `row` NULL.
|
||||
// The loop below finds a genuine matching column name and then
|
||||
// dereferences row[ix] - segfaulting (confirmed via gdb: SIGSEGV
|
||||
// right here) instead of reaching a catchable error. Reusing the
|
||||
// same "column does not exist" exception the loop's own fallthrough
|
||||
// already throws - no current row means no column value is
|
||||
// obtainable either way, and callers already expect and catch
|
||||
// this exact exception.
|
||||
if(!row)
|
||||
throw coreutils::Exception("column does not exist in session result.");
|
||||
|
||||
// O(1) against the map query() already built for this result set,
|
||||
// instead of re-deriving field metadata (mysql_fetch_field_direct,
|
||||
// a real MySQL C API call) and string-comparing column names one
|
||||
// by one on every single named access - see fieldIndex's own doc
|
||||
// comment in __mysql.h for the full story.
|
||||
auto it = fieldIndex.find(column.str());
|
||||
if(it != fieldIndex.end())
|
||||
return coreutils::ZString(row[it->second], fieldLength[it->second]);
|
||||
throw coreutils::Exception("column does not exist in session result.");
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
#include "ZString.h"
|
||||
#include "MString.h"
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <mysql/mysql.h>
|
||||
|
||||
namespace jet {
|
||||
@@ -19,15 +21,38 @@ namespace jet {
|
||||
void nextRow();
|
||||
bool hasRow();
|
||||
coreutils::ZString getColumnValue(coreutils::ZString column);
|
||||
|
||||
// Body of a single-quoted SQL string literal for this connection
|
||||
// (mysql_real_escape_string_quote: uses the connection's character
|
||||
// set and honours NO_BACKSLASH_ESCAPES). Used by <bind>.
|
||||
std::string escapeString(const std::string &value);
|
||||
// True while the session's sql_mode includes NO_BACKSLASH_ESCAPES.
|
||||
bool noBackslashEscapes();
|
||||
|
||||
private:
|
||||
MYSQL *mysql;
|
||||
MYSQL_RES *result;
|
||||
MYSQL_ROW row;
|
||||
unsigned long *fieldLength;
|
||||
unsigned int qFields;
|
||||
// Explicitly initialized - result/row/fieldLength were otherwise
|
||||
// left as garbage stack values until query() first ran. A
|
||||
// <mysql>...</mysql> block that connects successfully but never
|
||||
// runs a <sql> query inside it (e.g. just a connectivity check)
|
||||
// would previously reach ~__mysql()'s mysql_free_result(result)
|
||||
// with an uninitialized pointer - real undefined behavior, found
|
||||
// while root-causing a live crash in a related part of this same
|
||||
// class's constructor.
|
||||
MYSQL *mysql = NULL;
|
||||
MYSQL_RES *result = NULL;
|
||||
MYSQL_ROW row = NULL;
|
||||
unsigned long *fieldLength = NULL;
|
||||
unsigned int qFields = 0;
|
||||
coreutils::MString sessionId;
|
||||
|
||||
// Column-name -> row[] index, built once per query() call (see its
|
||||
// own comment) instead of getColumnValue() re-deriving it via a
|
||||
// fresh mysql_fetch_field_direct() linear scan on every single
|
||||
// named lookup - a template reading N columns off one row used to
|
||||
// pay that scan N times over, even though the schema is fixed for
|
||||
// the lifetime of one result set.
|
||||
std::unordered_map<std::string, int> fieldIndex;
|
||||
|
||||
coreutils::MString nbrOfRows = "0";
|
||||
coreutils::MString nbrOfColumns = "0";
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
#include "__smtpsend.h"
|
||||
#include "Exception.h"
|
||||
#include "JFile.h"
|
||||
#include "Base64.h"
|
||||
|
||||
#include <sys/socket.h>
|
||||
#include <sys/types.h>
|
||||
#include <netdb.h>
|
||||
#include <unistd.h>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <iomanip>
|
||||
#include <sstream>
|
||||
|
||||
namespace jet {
|
||||
|
||||
void __smtpsend::sendLine(const std::string &line) {
|
||||
std::string data = line + "\r\n";
|
||||
size_t sent = 0;
|
||||
while (sent < data.size()) {
|
||||
int n = SSL_write(ssl, data.data() + sent, (int)(data.size() - sent));
|
||||
if (n <= 0)
|
||||
throw coreutils::Exception("smtpsend: write failed", __FILE__, __LINE__, 502);
|
||||
sent += (size_t)n;
|
||||
}
|
||||
}
|
||||
|
||||
char __smtpsend::readByte() {
|
||||
if (recvPos >= recvBuffer.size()) {
|
||||
char buf[4096];
|
||||
int n = SSL_read(ssl, buf, sizeof(buf));
|
||||
if (n <= 0)
|
||||
throw coreutils::Exception("smtpsend: read failed", __FILE__, __LINE__, 502);
|
||||
recvBuffer.assign(buf, buf + n);
|
||||
recvPos = 0;
|
||||
}
|
||||
return recvBuffer[recvPos++];
|
||||
}
|
||||
|
||||
std::string __smtpsend::readLine() {
|
||||
std::string line;
|
||||
char c;
|
||||
for (;;) {
|
||||
c = readByte();
|
||||
if (c == '\n')
|
||||
break;
|
||||
if (c != '\r')
|
||||
line += c;
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
int __smtpsend::readReply(int expectedCode) {
|
||||
int code = 0;
|
||||
std::string line;
|
||||
for (;;) {
|
||||
line = readLine();
|
||||
if (line.size() < 4)
|
||||
throw coreutils::Exception("smtpsend: malformed reply: " + line, __FILE__, __LINE__, 502);
|
||||
code = atoi(line.substr(0, 3).c_str());
|
||||
if (line[3] == ' ')
|
||||
break;
|
||||
// else line[3] == '-': a continuation line, same code - keep reading.
|
||||
}
|
||||
if (code / 100 != expectedCode / 100)
|
||||
throw coreutils::Exception("smtpsend: unexpected reply " + std::to_string(code) + ": " + line, __FILE__, __LINE__, 502);
|
||||
return code;
|
||||
}
|
||||
|
||||
void __smtpsend::closeConnection() {
|
||||
if (ssl) { SSL_shutdown(ssl); SSL_free(ssl); ssl = nullptr; }
|
||||
if (fd >= 0) { ::close(fd); fd = -1; }
|
||||
if (ctx) { SSL_CTX_free(ctx); ctx = nullptr; }
|
||||
}
|
||||
|
||||
std::string __smtpsend::base64Encode(const std::string &s) {
|
||||
coreutils::Base64 base64;
|
||||
std::string copy = s;
|
||||
coreutils::ZString z(copy);
|
||||
return base64.encode(z).str();
|
||||
}
|
||||
|
||||
std::string __smtpsend::rfc2822Date() {
|
||||
time_t now = time(nullptr);
|
||||
struct tm tmResult{};
|
||||
gmtime_r(&now, &tmResult);
|
||||
char buf[64];
|
||||
strftime(buf, sizeof(buf), "%a, %d %b %Y %H:%M:%S +0000", &tmResult);
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
// RFC 5322 3.6.4: Message-ID "SHOULD be present" - in practice
|
||||
// several real receivers (confirmed live: Gmail) now hard-reject
|
||||
// anything missing one ("550 5.7.1 Messages missing a valid
|
||||
// Message-ID header are not accepted") rather than just marking it
|
||||
// down, so this isn't optional in practice. Domain part is the
|
||||
// sender's own domain (everything after '@' in `from`), matching
|
||||
// RFC 5322's own recommendation that it be a name under the
|
||||
// generating system's control - falls back to the literal `from`
|
||||
// string in the (should-never-happen) case it has no '@' at all.
|
||||
std::string __smtpsend::generateMessageId(const std::string &from) {
|
||||
size_t at = from.find('@');
|
||||
std::string domainPart = (at == std::string::npos) ? from : from.substr(at + 1);
|
||||
struct timespec ts;
|
||||
clock_gettime(CLOCK_REALTIME, &ts);
|
||||
std::ostringstream idStream;
|
||||
idStream << ts.tv_sec << "." << std::setfill('0') << std::setw(9) << ts.tv_nsec
|
||||
<< "." << rand() << "@" << domainPart;
|
||||
return idStream.str();
|
||||
}
|
||||
|
||||
std::string __smtpsend::buildMessage(const std::string &from, const std::string &to,
|
||||
const std::string &subject, const std::string &html) {
|
||||
std::string msg;
|
||||
msg += "Date: " + rfc2822Date() + "\r\n";
|
||||
msg += "Message-ID: <" + generateMessageId(from) + ">\r\n";
|
||||
msg += "From: " + from + "\r\n";
|
||||
msg += "To: " + to + "\r\n";
|
||||
msg += "Subject: " + subject + "\r\n";
|
||||
msg += "MIME-Version: 1.0\r\n";
|
||||
msg += "Content-Type: text/html; charset=UTF-8\r\n";
|
||||
msg += "Content-Transfer-Encoding: 8bit\r\n";
|
||||
msg += "\r\n";
|
||||
// SMTP DATA's dot-stuffing rule: any body line starting with '.'
|
||||
// needs a second '.' prepended, or the server treats it as the
|
||||
// end-of-data marker prematurely and truncates the message.
|
||||
std::string stuffed;
|
||||
stuffed.reserve(html.size());
|
||||
bool atLineStart = true;
|
||||
for (size_t i = 0; i < html.size(); i++) {
|
||||
char c = html[i];
|
||||
if (atLineStart && c == '.')
|
||||
stuffed += '.';
|
||||
stuffed += c;
|
||||
atLineStart = (c == '\n');
|
||||
}
|
||||
msg += stuffed;
|
||||
return msg;
|
||||
}
|
||||
|
||||
__smtpsend::__smtpsend(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
std::string user = resolveKeyword("user").str();
|
||||
std::string password = resolveKeyword("password").str();
|
||||
std::string to = resolveKeyword("to").str();
|
||||
std::string subject = resolveKeyword("subject").str();
|
||||
std::string html = resolveKeyword("html").str();
|
||||
coreutils::MString configPath = resolveKeyword("config");
|
||||
|
||||
if (user.empty() || password.empty())
|
||||
throw coreutils::Exception("smtpsend: user/password must be specified.", __FILE__, __LINE__, 401);
|
||||
if (to.empty())
|
||||
throw coreutils::Exception("smtpsend: to address must be specified.", __FILE__, __LINE__, 400);
|
||||
|
||||
coreutils::JFile config(configPath);
|
||||
std::string host = config.getString("host");
|
||||
long port = (long)config.getNumber("smtpPort");
|
||||
if (port <= 0)
|
||||
port = 465;
|
||||
|
||||
struct addrinfo hints {};
|
||||
hints.ai_family = AF_UNSPEC;
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
struct addrinfo *result = nullptr;
|
||||
std::string portStr = std::to_string(port);
|
||||
if (getaddrinfo(host.c_str(), portStr.c_str(), &hints, &result) != 0 || !result)
|
||||
throw coreutils::Exception("smtpsend: could not resolve " + host, __FILE__, __LINE__, 502);
|
||||
|
||||
int newFd = -1;
|
||||
for (struct addrinfo *rp = result; rp != nullptr; rp = rp->ai_next) {
|
||||
newFd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
|
||||
if (newFd < 0)
|
||||
continue;
|
||||
if (::connect(newFd, rp->ai_addr, rp->ai_addrlen) == 0)
|
||||
break;
|
||||
::close(newFd);
|
||||
newFd = -1;
|
||||
}
|
||||
freeaddrinfo(result);
|
||||
if (newFd < 0)
|
||||
throw coreutils::Exception("smtpsend: could not connect to " + host, __FILE__, __LINE__, 502);
|
||||
|
||||
struct timeval timeout { 30, 0 };
|
||||
setsockopt(newFd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
|
||||
setsockopt(newFd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
|
||||
|
||||
SSL_CTX *newCtx = SSL_CTX_new(SSLv23_client_method());
|
||||
if (!newCtx) {
|
||||
::close(newFd);
|
||||
throw coreutils::Exception("smtpsend: SSL_CTX_new failed", __FILE__, __LINE__, 502);
|
||||
}
|
||||
SSL *newSsl = SSL_new(newCtx);
|
||||
SSL_set_fd(newSsl, newFd);
|
||||
if (SSL_connect(newSsl) != 1) {
|
||||
SSL_free(newSsl);
|
||||
SSL_CTX_free(newCtx);
|
||||
::close(newFd);
|
||||
throw coreutils::Exception("smtpsend: TLS handshake failed", __FILE__, __LINE__, 502);
|
||||
}
|
||||
|
||||
ctx = newCtx;
|
||||
ssl = newSsl;
|
||||
fd = newFd;
|
||||
|
||||
try {
|
||||
readReply(220);
|
||||
|
||||
sendLine("EHLO " + host);
|
||||
readReply(250);
|
||||
|
||||
sendLine("AUTH LOGIN");
|
||||
readReply(334);
|
||||
sendLine(base64Encode(user));
|
||||
readReply(334);
|
||||
sendLine(base64Encode(password));
|
||||
readReply(235);
|
||||
|
||||
sendLine("MAIL FROM:<" + user + ">");
|
||||
readReply(250);
|
||||
sendLine("RCPT TO:<" + to + ">");
|
||||
readReply(250);
|
||||
sendLine("DATA");
|
||||
readReply(354);
|
||||
|
||||
std::string message = buildMessage(user, to, subject, html);
|
||||
sendLine(message);
|
||||
sendLine(".");
|
||||
readReply(250);
|
||||
|
||||
sendLine("QUIT");
|
||||
readReply(221);
|
||||
} catch (...) {
|
||||
closeConnection();
|
||||
throw;
|
||||
}
|
||||
|
||||
closeConnection();
|
||||
|
||||
out = coreutils::MString(std::string("{\"ok\":true}"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
#ifndef ____smtpsend_h__
|
||||
# define ____smtpsend_h__
|
||||
|
||||
# include "Tag.h"
|
||||
# include "ZString.h"
|
||||
# include "MString.h"
|
||||
# include <openssl/ssl.h>
|
||||
# include <string>
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <smtpsend config="./email.cfg" user="..." password="..."
|
||||
/// to="..." subject="..." html="...">
|
||||
///
|
||||
/// One-shot authenticated SMTP submission to BARANTMAIL's own
|
||||
/// implicit-TLS submission port (config key "smtpPort" - matches
|
||||
/// barantmail.cfg's smtpTLS.port, :465, the same implicit-TLS style
|
||||
/// as IMAP's :993 - no STARTTLS negotiation). Connects, TLS-
|
||||
/// handshakes, AUTH LOGIN with the SAME mailbox credentials already
|
||||
/// used by <imap> (so the message goes out authenticated as the
|
||||
/// actual connected mailbox, not the site's own transactional-mail
|
||||
/// identity - see barant.tag's separate <email> tag for that), then
|
||||
/// MAIL FROM/RCPT TO/DATAs a freshly-built RFC 5322 message
|
||||
/// (Date/From/To/Subject/MIME headers, HTML body), then QUITs. The
|
||||
/// authenticated user IS the From address - SMTP submission
|
||||
/// requires MAIL FROM to match the authenticated identity anyway, so
|
||||
/// there's no separate "from" keyword.
|
||||
///
|
||||
/// No connection pooling, unlike __imap - composing mail is rare
|
||||
/// enough that a fresh connect/auth/send/close per message is fine.
|
||||
///
|
||||
/// Throws coreutils::Exception (401 for a bad login, 502 for any
|
||||
/// other connect/protocol/rejected-recipient failure) on any
|
||||
/// failure - same convention as __imap.
|
||||
///
|
||||
class __smtpsend : public Tag {
|
||||
|
||||
public:
|
||||
__smtpsend(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
private:
|
||||
SSL_CTX *ctx = nullptr;
|
||||
SSL *ssl = nullptr;
|
||||
int fd = -1;
|
||||
std::string recvBuffer;
|
||||
size_t recvPos = 0;
|
||||
|
||||
void sendLine(const std::string &line);
|
||||
char readByte();
|
||||
std::string readLine();
|
||||
// Reads one (possibly multi-line, "250-text"/"250 text"
|
||||
// continuation-marked) SMTP reply and returns its 3-digit code;
|
||||
// throws if the code's first digit doesn't match expectedCode's.
|
||||
int readReply(int expectedCode);
|
||||
|
||||
void closeConnection();
|
||||
|
||||
static std::string base64Encode(const std::string &s);
|
||||
static std::string rfc2822Date();
|
||||
static std::string generateMessageId(const std::string &from);
|
||||
// Builds the full RFC 5322 message (headers + dot-stuffed body)
|
||||
// handed to SMTP's DATA command.
|
||||
static std::string buildMessage(const std::string &from, const std::string &to,
|
||||
const std::string &subject, const std::string &html);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -8,15 +8,39 @@
|
||||
#include <sys/wait.h>
|
||||
|
||||
namespace jet {
|
||||
|
||||
|
||||
__sql::__sql(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
output = false;
|
||||
if(!hasContainer)
|
||||
throw coreutils::Exception("sql tag must have a container.");
|
||||
if(!global.sessionExists(keywords["sessionid"]))
|
||||
throw coreutils::Exception("sql tag must have a container.");
|
||||
// resolveKeyword("sessionid") already returns the resolved VALUE
|
||||
// (e.g. "projman") - the query call below used to wrap that value
|
||||
// back into keywords[...] as if it were a MAP KEY, auto-vivifying
|
||||
// an empty string and silently running every <sql sessionid="X">
|
||||
// query (X != "") against the DEFAULT session instead of the one
|
||||
// actually named - same double-indirection bug already fixed in
|
||||
// __mysql.cpp's own constructor (see its own comment on this).
|
||||
// Resolved once into a local so both the existence check and the
|
||||
// query call agree on the real, resolved session id.
|
||||
coreutils::MString sessionId = resolveKeyword("sessionid");
|
||||
if(!global.sessionExists(sessionId))
|
||||
throw coreutils::Exception("sessionid does not exist.");
|
||||
processContainer(container);
|
||||
global.getSession(keywords[resolveKeyword("sessionid")])->query(out);
|
||||
__mysql *session = global.getSession(sessionId);
|
||||
// No <bind> inside: the query runs exactly as rendered, with no '?'
|
||||
// replacement at all, so existing queries containing a literal '?'
|
||||
// are unaffected. See docs/design-sql-bound-parameters.md.
|
||||
if(binds.empty()) {
|
||||
if(isCharsetChange(out.str()))
|
||||
throw coreutils::Exception("sql: changing the connection character set is not allowed.");
|
||||
session->query(out);
|
||||
return;
|
||||
}
|
||||
std::string bound = bindPlaceholders(out.str(), binds, session->noBackslashEscapes(),
|
||||
[session](const std::string &s) { return session->escapeString(s); });
|
||||
if(isCharsetChange(bound))
|
||||
throw coreutils::Exception("sql: changing the connection character set is not allowed.");
|
||||
session->query(coreutils::MString(bound));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -2,16 +2,25 @@
|
||||
#define ____sql_h__
|
||||
|
||||
#include "Tag.h"
|
||||
#include "SqlBind.h"
|
||||
#include <vector>
|
||||
|
||||
namespace jet {
|
||||
|
||||
|
||||
class __sql : public Tag {
|
||||
|
||||
|
||||
public:
|
||||
__sql(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
|
||||
// Called by each <bind> inside this <sql> while its body renders.
|
||||
void addBind(BoundValue value) { binds.push_back(std::move(value)); }
|
||||
size_t bindCount() const { return binds.size(); }
|
||||
|
||||
private:
|
||||
std::vector<BoundValue> binds;
|
||||
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -2,15 +2,46 @@
|
||||
#include "Exception.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
__tag::__tag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, this, this) {
|
||||
|
||||
__tag::__tag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
evaluate = false;
|
||||
output = false;
|
||||
if(!keywordDefined("name"))
|
||||
throw coreutils::Exception("tag must have a name.");
|
||||
if(!hasContainer)
|
||||
throw coreutils::Exception("tag requires a container to process.");
|
||||
global.tags[keywords["name"]] = container;
|
||||
|
||||
// A <tag> defined directly inside another custom tag's own
|
||||
// invocation (a __dotag instance's expansion) is scoped to that
|
||||
// invocation - only visible for the rest of it, not the whole
|
||||
// script. Control-flow tags like <if>/<for> that happen to sit in
|
||||
// between are transparent (walked past, not boundaries themselves).
|
||||
// Reaching parent==NULL (true top level) falls back to the original
|
||||
// single flat global.tags map, unchanged from before. This relies
|
||||
// on `parent` here actually being the real enclosing tag - the base
|
||||
// Tag(...) call above used to pass (this, this) instead of the
|
||||
// parent/local this constructor actually received, which would have
|
||||
// made this walk loop on itself forever; fixed as part of adding
|
||||
// this scoping (parent/local weren't needed anywhere else in this
|
||||
// class - <tag>'s own container is never evaluated at definition
|
||||
// time, evaluate=false above, so nothing depended on the old
|
||||
// self-referential values).
|
||||
Tag *scope = parent;
|
||||
while(scope && !scope->isCustomTagBoundary)
|
||||
scope = scope->parent;
|
||||
// Custom tag NAMES are matched case-insensitively at invocation
|
||||
// (findTagDefinition normalizes its own lookup key the same way),
|
||||
// matching the precedent already set for built-in tag names
|
||||
// (ifTagName) and attribute names - real 1.4 content declares and
|
||||
// invokes a custom tag in different case at different sites (e.g.
|
||||
// SESSIONCTL.tag's own <TAG NAME='TEMPLATE'> definition vs
|
||||
// mainpagetemplate.temp's <template>...</template> invocation of
|
||||
// it). Registering under the lowercase key here is what makes that
|
||||
// match.
|
||||
coreutils::MString tagName = coreutils::MString(keywords["name"]).toLower();
|
||||
if(scope)
|
||||
scope->localTags[tagName] = container;
|
||||
else
|
||||
global.tags[tagName] = container;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
#include "__trytag.h"
|
||||
#include "Exception.h"
|
||||
#include <exception>
|
||||
|
||||
namespace jet {
|
||||
|
||||
__trytag::__trytag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local)
|
||||
: Tag(in, parentOut, global, parent, this, "catch") {
|
||||
|
||||
coreutils::MString errorText;
|
||||
bool failed = false;
|
||||
|
||||
try {
|
||||
processContainer(container);
|
||||
} catch(coreutils::Exception &e) {
|
||||
errorText = e.text;
|
||||
failed = true;
|
||||
} catch(std::exception &e) {
|
||||
errorText = e.what();
|
||||
failed = true;
|
||||
} catch(...) {
|
||||
errorText = "unknown error";
|
||||
failed = true;
|
||||
}
|
||||
|
||||
if(failed) {
|
||||
// Discard whatever the failed attempt had already written before
|
||||
// it threw - out is this tag's own accumulating output buffer
|
||||
// (processContainer(container) above wrote into it directly), so
|
||||
// without this a caught mid-render failure would leave partial
|
||||
// try-block output mixed in ahead of the catch block's own.
|
||||
out = "";
|
||||
// <try name="err"> or <catch name="err"> (the usual form).
|
||||
if(keywordDefined("name"))
|
||||
storeVariable(resolveKeyword("name"), errorText,
|
||||
keywordDefined("scope") ? resolveKeyword("scope") : "global");
|
||||
else if(splitKeywords.count("name"))
|
||||
storeVariable(splitKeywords["name"], errorText,
|
||||
splitKeywords.count("scope") ? coreutils::ZString(splitKeywords["scope"]) : coreutils::ZString("global"));
|
||||
if(hasContainer2)
|
||||
processContainer(container2);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
#ifndef ____trytag_h__
|
||||
#define ____trytag_h__
|
||||
|
||||
#include "Tag.h"
|
||||
#include "ZString.h"
|
||||
#include "MString.h"
|
||||
|
||||
namespace jet {
|
||||
|
||||
///
|
||||
/// <try>...container...<catch>...container2...</catch></try>
|
||||
///
|
||||
/// Runs its own container the same as any other tag; if that raises an
|
||||
/// error that would otherwise propagate up and halt the whole script -
|
||||
/// a coreutils::Exception (what every other tag actually throws), any
|
||||
/// other std::exception (e.g. the std::filesystem::filesystem_error
|
||||
/// <whiledir> can raise), or anything else - the <catch> container (if
|
||||
/// present) runs instead, with any partial output the failed attempt
|
||||
/// had already written discarded first so the result is cleanly either
|
||||
/// the try's output or the catch's, never a mix of both.
|
||||
///
|
||||
/// Optional keywords, both meaningful only on catch: name (a variable
|
||||
/// to receive the caught error's message text) and scope (global by
|
||||
/// default, or local/parent - same convention as <for>'s own name/scope
|
||||
/// pair).
|
||||
///
|
||||
/// Named __trytag rather than __try: <ios> transitively defines a
|
||||
/// preprocessor macro "#define __try try" (an SEH-compatibility shim
|
||||
/// pulled in on this toolchain) that silently rewrites the identifier
|
||||
/// __try to the literal keyword try wherever it appears, breaking
|
||||
/// compilation - confirmed via `g++ -E -dM` before picking this name,
|
||||
/// not guessed. The JET tag name itself is still plain <try> - this
|
||||
/// only affects the internal C++ class name, matched by ifTagName(in,
|
||||
/// "try") in Tag.cpp regardless of what the class is called.
|
||||
///
|
||||
|
||||
class __trytag : public Tag {
|
||||
|
||||
public:
|
||||
__trytag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -21,7 +21,7 @@ namespace jet {
|
||||
if(!keywordDefined("type"))
|
||||
throw coreutils::Exception("type expected if value1 and value2 specified.");
|
||||
|
||||
int rc = keywords[resolveKeyword("value1")].compare(keywords[resolveKeyword("value2")]);
|
||||
int rc = resolveKeyword("value1").compare(resolveKeyword("value2"));
|
||||
if(((keywords[resolveKeyword("type")] == "eq") && (rc == 0)) ||
|
||||
((keywords[resolveKeyword("type")] == "ne") && (rc != 0)) ||
|
||||
((keywords[resolveKeyword("type")] == "lt") && (rc == -1)) ||
|
||||
@@ -50,7 +50,7 @@ namespace jet {
|
||||
booleanResult = Operand(keywords["expr"], *this).boolean;
|
||||
} else {
|
||||
booleanResult = false;
|
||||
int rc = keywords[resolveKeyword("value1")].compare(keywords[resolveKeyword("value2")]);
|
||||
int rc = resolveKeyword("value1").compare(resolveKeyword("value2"));
|
||||
if(((keywords[resolveKeyword("type")] == "eq") && (rc == 0)) ||
|
||||
((keywords[resolveKeyword("type")] == "ne") && (rc != 0)) ||
|
||||
((keywords[resolveKeyword("type")] == "lt") && (rc == -1)) ||
|
||||
|
||||
@@ -21,7 +21,7 @@ namespace jet {
|
||||
if(!keywordDefined("type"))
|
||||
throw coreutils::Exception("type expected if value1 and value2 specified.");
|
||||
|
||||
int rc = keywords[resolveKeyword("value1")].compare(keywords[resolveKeyword("value2")]);
|
||||
int rc = resolveKeyword("value1").compare(resolveKeyword("value2"));
|
||||
if(((keywords[resolveKeyword("type")] == "eq") && (rc == 0)) ||
|
||||
((keywords[resolveKeyword("type")] == "ne") && (rc != 0)) ||
|
||||
((keywords[resolveKeyword("type")] == "lt") && (rc == -1)) ||
|
||||
@@ -50,7 +50,7 @@ namespace jet {
|
||||
booleanResult = Operand(keywords["expr"], *this).boolean;
|
||||
} else {
|
||||
booleanResult = false;
|
||||
int rc = keywords[resolveKeyword("value1")].compare(keywords[resolveKeyword("value2")]);
|
||||
int rc = resolveKeyword("value1").compare(resolveKeyword("value2"));
|
||||
if(((keywords[resolveKeyword("type")] == "eq") && (rc == 0)) ||
|
||||
((keywords[resolveKeyword("type")] == "ne") && (rc != 0)) ||
|
||||
((keywords[resolveKeyword("type")] == "lt") && (rc == -1)) ||
|
||||
|
||||
@@ -9,36 +9,101 @@
|
||||
namespace jet {
|
||||
|
||||
__whiledir::__whiledir(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, this) {
|
||||
if(!keywordDefined("path"))
|
||||
// Real 1.4 content (barantmusic.page/davidarant.page's own
|
||||
// bae1996.section) writes <whiledir dir="..." name="filename">,
|
||||
// not <whiledir path="..." filename="...">. Accept "dir" as an
|
||||
// alias for "path" and "name" as an alias for "filename" so that
|
||||
// content runs unmodified, matching the same "accept either"
|
||||
// precedent already used for <database name=>/<mysql database=>.
|
||||
// Resolved once into real local VALUES (not a dynamically-chosen
|
||||
// keyword NAME threaded through repeated keywordDefined()/
|
||||
// resolveKeyword() calls) - an earlier version of this fix passed
|
||||
// a ZString holding just the chosen attribute name around and hit
|
||||
// real, unexplained corruption (a whiledir on a real, correctly
|
||||
// specified directory resolved to a garbage nonsense path instead).
|
||||
// This form fixed it in isolation (a standalone whiledir_test.jet
|
||||
// against this exact directory/attributes works perfectly) but the
|
||||
// SAME garbage path still recurs when this exact content
|
||||
// (bae1996.section) is reached through real content's actual deep
|
||||
// <eval>/<dotag>/<include> nesting (40+ stack frames by that
|
||||
// point) - genuinely not yet root-caused; flagged in project
|
||||
// memory as still open. The try/catch below at least converts
|
||||
// whatever throws there into the same graceful, catchable error
|
||||
// page every other tag failure already gets, instead of a raw
|
||||
// std::exception unwinding past everything and dropping the
|
||||
// connection with no HTTP response at all.
|
||||
coreutils::MString dirPath;
|
||||
if(keywordDefined("path"))
|
||||
dirPath = resolveKeyword("path");
|
||||
else if(keywordDefined("dir"))
|
||||
dirPath = resolveKeyword("dir");
|
||||
else
|
||||
throw coreutils::Exception("whiledir tag must specify a path.");
|
||||
if(keywordDefined("sort") && (resolveKeyword("sort") == "true")) {
|
||||
std::vector<std::filesystem::directory_entry> entries;
|
||||
for(auto const &entry : std::filesystem::directory_iterator(resolveKeyword("path").str()))
|
||||
entries.push_back(entry);
|
||||
std::sort(entries.begin(), entries.end(), [](const auto &a, const auto &b) { return a.path() < b.path(); });
|
||||
for(const auto &entry : entries) {
|
||||
if(keywordDefined("fullpath"))
|
||||
global.variables[resolveKeyword("fullpath")] = entry.path();
|
||||
if(keywordDefined("filename"))
|
||||
global.variables[resolveKeyword("filename")] = entry.path().filename();
|
||||
if(keywordDefined("filenamenoextension"))
|
||||
global.variables[resolveKeyword("filenamenoextension")] = entry.path().stem();
|
||||
processContainer(container);
|
||||
container.reset();
|
||||
}
|
||||
} else {
|
||||
for(auto const &entry : std::filesystem::directory_iterator(variables[resolveKeyword("path")].str())) {
|
||||
if(keywordDefined("fullpath"))
|
||||
global.variables[resolveKeyword("fullpath")] = entry.path();
|
||||
if(keywordDefined("filename"))
|
||||
global.variables[resolveKeyword("filename")] = entry.path().filename();
|
||||
if(keywordDefined("filenamenoextension"))
|
||||
global.variables[resolveKeyword("filenamenoextension")] = entry.path().stem();
|
||||
processContainer(container);
|
||||
container.reset();
|
||||
}
|
||||
|
||||
// Every one of these attributes - which output variable name to
|
||||
// assign into for a given field, and whether that field was even
|
||||
// requested - is a static property of this <whiledir> invocation,
|
||||
// fixed at construction, never changing across its own loop. The
|
||||
// per-iteration body used to call keywordDefined()+resolveKeyword()
|
||||
// (2 map lookups each) for fullpath/filename/filenamenoextension
|
||||
// on every single directory entry - resolved once here instead,
|
||||
// same reasoning as __whilerow.cpp's session-pointer hoist.
|
||||
coreutils::MString filenameVarName;
|
||||
bool haveFilenameVar = false;
|
||||
if(keywordDefined("filename")) {
|
||||
filenameVarName = resolveKeyword("filename");
|
||||
haveFilenameVar = true;
|
||||
} else if(keywordDefined("name")) {
|
||||
filenameVarName = resolveKeyword("name");
|
||||
haveFilenameVar = true;
|
||||
}
|
||||
|
||||
|
||||
coreutils::MString fullpathVarName;
|
||||
bool haveFullpathVar = keywordDefined("fullpath");
|
||||
if(haveFullpathVar)
|
||||
fullpathVarName = resolveKeyword("fullpath");
|
||||
|
||||
coreutils::MString noExtVarName;
|
||||
bool haveNoExtVar = keywordDefined("filenamenoextension");
|
||||
if(haveNoExtVar)
|
||||
noExtVarName = resolveKeyword("filenamenoextension");
|
||||
|
||||
bool sorted = keywordDefined("sort") && (resolveKeyword("sort") == "true");
|
||||
|
||||
try {
|
||||
if(sorted) {
|
||||
std::vector<std::filesystem::directory_entry> entries;
|
||||
for(auto const &entry : std::filesystem::directory_iterator(dirPath.str()))
|
||||
entries.push_back(entry);
|
||||
std::sort(entries.begin(), entries.end(), [](const auto &a, const auto &b) { return a.path() < b.path(); });
|
||||
for(const auto &entry : entries) {
|
||||
if(haveFullpathVar)
|
||||
global.variables[fullpathVarName] = entry.path();
|
||||
if(haveFilenameVar)
|
||||
global.variables[filenameVarName] = entry.path().filename();
|
||||
if(haveNoExtVar)
|
||||
global.variables[noExtVarName] = entry.path().stem();
|
||||
processContainer(container);
|
||||
container.reset();
|
||||
}
|
||||
} else {
|
||||
for(auto const &entry : std::filesystem::directory_iterator(dirPath.str())) {
|
||||
if(haveFullpathVar)
|
||||
global.variables[fullpathVarName] = entry.path();
|
||||
if(haveFilenameVar)
|
||||
global.variables[filenameVarName] = entry.path().filename();
|
||||
if(haveNoExtVar)
|
||||
global.variables[noExtVarName] = entry.path().stem();
|
||||
processContainer(container);
|
||||
container.reset();
|
||||
}
|
||||
}
|
||||
} catch(std::exception &e) {
|
||||
coreutils::MString msg("whiledir failed: ");
|
||||
msg << e.what();
|
||||
throw coreutils::Exception(msg.str());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -6,16 +6,35 @@
|
||||
namespace jet {
|
||||
|
||||
__whilerow::__whilerow(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
|
||||
|
||||
int count = keywords["count"].asInteger();
|
||||
|
||||
while ((count != 0) && global.getSession(keywords["sessionid"])->hasRow()) {
|
||||
|
||||
// A bare <whilerow> (no count= attribute at all - the overwhelming
|
||||
// majority of real usage: modular1_patches.page, account.page,
|
||||
// task.page, project.page, editinvoice.page, musicianhome.page,
|
||||
// invoice.method, modular1_1_preset_admin.page) used to default
|
||||
// count to 0 - keywords["count"] auto-vivifies an empty string for
|
||||
// a missing attribute, and "".asInteger() is 0 - which made the
|
||||
// loop's own (count != 0) condition false on the very first check,
|
||||
// before hasRow() was ever even consulted. Every one of those
|
||||
// pages' row-based content silently rendered nothing, for every
|
||||
// request, this entire session - never caught because nothing
|
||||
// that exercised a bare <whilerow> with real row data also had its
|
||||
// actual rendered output inspected until now. count= is meant as
|
||||
// an OPTIONAL cap ("show at most N rows"); absent, it must mean
|
||||
// unlimited, not zero - -1 as a sentinel keeps working with the
|
||||
// existing (count != 0) loop test forever (decrementing through
|
||||
// negative numbers never hits 0), letting hasRow() alone decide
|
||||
// when the loop ends, exactly as bare usage always intended.
|
||||
int count = keywordDefined("count") ? keywords["count"].asInteger() : -1;
|
||||
|
||||
__mysql *session = global.getSession(resolveKeyword("sessionid"));
|
||||
|
||||
while((count != 0) && session->hasRow()) {
|
||||
processContainer(container);
|
||||
container.reset();
|
||||
global.getSession(keywords["sessionid"])->nextRow();
|
||||
session->nextRow();
|
||||
--count;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -24,19 +24,49 @@ namespace jet {
|
||||
throw coreutils::Exception("write tag must have a value, expr or a container.");
|
||||
if(!keywordDefined("mode"))
|
||||
throw coreutils::Exception("write tag must have a mode keyword.");
|
||||
if(keywords[resolveKeyword("mode")] == "append")
|
||||
// resolveKeyword("mode") already returns the resolved VALUE (e.g.
|
||||
// "overwrite") - re-indexing keywords[...] with that value treats
|
||||
// it as if it were a MAP KEY instead (auto-vivifying an empty
|
||||
// string, since no keyword is literally named "overwrite"/
|
||||
// "append"), so this comparison was false for every real input
|
||||
// and <write> threw "mode keyword must be..." unconditionally.
|
||||
// Same double-indirection bug already fixed elsewhere in this
|
||||
// codebase (__mysql.cpp's own constructor, __sql.cpp's sessionid
|
||||
// handling) - confirmed via a real repro building the jet-2.0
|
||||
// htmleditor port's file-based storage.
|
||||
coreutils::MString modeValue = resolveKeyword("mode");
|
||||
if(modeValue == "append")
|
||||
mode = O_APPEND;
|
||||
else if(keywords[resolveKeyword("mode")] == "overwrite")
|
||||
else if(modeValue == "overwrite")
|
||||
mode = O_TRUNC;
|
||||
else
|
||||
throw coreutils::Exception("mode keyword must be 'overwrite' or 'append'.");
|
||||
int fd = open(keywords[resolveKeyword("file")].c_str(), mode, 0644); // TODO: Need to add O_CREAT and AUTH flags.
|
||||
// mode alone (O_APPEND or O_TRUNC) has no access-mode bits at
|
||||
// all - open()'s access mode defaults to O_RDONLY (0) unless
|
||||
// O_WRONLY/O_RDWR is explicitly OR'd in, so the write() call below
|
||||
// was failing on every real invocation (EBADF - can't write a
|
||||
// read-only fd), and without O_CREAT this could never create a
|
||||
// NEW file either, only (theoretically) write an existing one.
|
||||
// Confirmed via a real repro: <write file="..." mode="overwrite">
|
||||
// silently produced a 0-byte or missing file every time.
|
||||
// Same double-indirection bug as "mode" above.
|
||||
int fd = open(resolveKeyword("file").c_str(), mode | O_WRONLY | O_CREAT, 0644); // TODO: Need to add AUTH flags.
|
||||
if(hasContainer && !evaluate)
|
||||
len = write(fd, container.getData(), container.getLength());
|
||||
else if(hasContainer && evaluate)
|
||||
len = write(fd, out.getData(), out.getLength());
|
||||
else if(!hasContainer && keywordDefined("value"))
|
||||
len = write(fd, variables[resolveKeyword("value")].getData(), keywords[resolveKeyword("value")].getLength());
|
||||
else if(!hasContainer && keywordDefined("value")) {
|
||||
// Same double-indirection bug as "mode"/"file" above:
|
||||
// variables[resolveKeyword("value")] used the resolved VALUE
|
||||
// itself as a lookup key into global.variables (a DIFFERENT map
|
||||
// entirely), not the literal value to write - looking up a
|
||||
// variable literally named e.g. "hello world" auto-vivifies an
|
||||
// empty entry, so this wrote 0 bytes for every real invocation.
|
||||
// Confirmed via a real repro: <write value="hello world"
|
||||
// mode="overwrite"> produced a genuinely empty file.
|
||||
coreutils::MString writeValue = resolveKeyword("value");
|
||||
len = write(fd, writeValue.getData(), writeValue.getLength());
|
||||
}
|
||||
else if(!hasContainer && keywordDefined("expr"))
|
||||
len = write(fd, keywords["expr"].getData(), keywords["expr"].getLength());
|
||||
close(fd);
|
||||
|
||||
@@ -18,7 +18,7 @@ done
|
||||
|
||||
wait
|
||||
echo -n "Building executable jet-2.0..."
|
||||
g++ -g -o jet-2.0 $list -std=c++23 -L../CoreUtils -lCoreUtils -lmysqlclient -lcrypto
|
||||
g++ -g -o jet-2.0 $list -std=c++23 -L../CoreUtils -lCoreUtils -lmysqlclient -lssl -lcrypto
|
||||
if [ $? = '0' ]
|
||||
then
|
||||
echo "OK"
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
\relax
|
||||
\@writefile{toc}{\contentsline {chapter}{\numberline {1}Introduction}{5}{}\protected@file@percent }
|
||||
\@writefile{lof}{\addvspace {10\p@ }}
|
||||
\@writefile{lot}{\addvspace {10\p@ }}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {1.1}Use Cases}{5}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {1.1.1}World Wide Web Site}{5}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {1.1.2}API Handling}{5}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {1.1.3}Asterisk Dial Plan Generator Tool}{5}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {chapter}{\numberline {2}Tags and Attributes}{7}{}\protected@file@percent }
|
||||
\@writefile{lof}{\addvspace {10\p@ }}
|
||||
\@writefile{lot}{\addvspace {10\p@ }}
|
||||
\@writefile{toc}{\contentsline {chapter}{\numberline {3}User Defined Tags and Tag Libraries}{9}{}\protected@file@percent }
|
||||
\@writefile{lof}{\addvspace {10\p@ }}
|
||||
\@writefile{lot}{\addvspace {10\p@ }}
|
||||
\@writefile{toc}{\contentsline {chapter}{\numberline {4}Variables and Variable Types}{11}{}\protected@file@percent }
|
||||
\@writefile{lof}{\addvspace {10\p@ }}
|
||||
\@writefile{lot}{\addvspace {10\p@ }}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {4.1}Global Variables}{11}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {4.2}Local Variables}{12}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {4.3}Keyword Variables}{12}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {4.4}Environment Variables}{12}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {4.5}CGI Variables}{12}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {chapter}{\numberline {5}Expressions}{13}{}\protected@file@percent }
|
||||
\@writefile{lof}{\addvspace {10\p@ }}
|
||||
\@writefile{lot}{\addvspace {10\p@ }}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {5.1}Operators}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.1.1}Arithmetic Operators}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.1.2}Boolean Operators}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {5.2}Function Reference}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {5.3}Date Functions}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.3.1}unixtime}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {5.4}Math Functions}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.1}abs}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.2}acos}{13}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.3}asin}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.4}atan}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.5}cos}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.6}max}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.7}min}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.8}pow}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.9}random}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.4.10}sin}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {5.5}String Functions}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.1}concat}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.2}integer}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.3}left}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.4}reverse}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.5}right}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.6}round}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.7}substring}{14}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.8}tolower}{15}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.9}toupper}{15}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.10}trim}{15}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {subsection}{\numberline {5.5.11}expr}{15}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {chapter}{\numberline {6}Common Gateway Interface Features}{17}{}\protected@file@percent }
|
||||
\@writefile{lof}{\addvspace {10\p@ }}
|
||||
\@writefile{lot}{\addvspace {10\p@ }}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {6.1}Session Control}{17}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {chapter}{\numberline {7}Tag Reference}{19}{}\protected@file@percent }
|
||||
\@writefile{lof}{\addvspace {10\p@ }}
|
||||
\@writefile{lot}{\addvspace {10\p@ }}
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.1}call}{19}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.2}comment}{19}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.3}cookie}{20}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.4}dump}{20}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.5}exclude}{20}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.6}expr}{20}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.7}for}{20}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.8}header}{20}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.9}if/else}{20}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.10}ifrow/else}{21}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.11}include}{21}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.12}jet}{21}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.13}mysql}{21}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.14}read}{21}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.15}set}{22}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.16}sql}{22}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.17}stream}{22}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.18}system}{22}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.19}tag}{22}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.20}until}{23}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.21}while}{23}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.22}whiledir}{23}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.23}whilerow}{23}{}\protected@file@percent }
|
||||
\@writefile{toc}{\contentsline {section}{\numberline {7.24}write}{23}{}\protected@file@percent }
|
||||
\gdef \@abspage@last{23}
|
||||
@@ -1,126 +0,0 @@
|
||||
This is pdfTeX, Version 3.141592653-2.6-1.40.25 (TeX Live 2023/Debian) (preloaded format=pdflatex 2024.11.17) 11 NOV 2025 10:01
|
||||
entering extended mode
|
||||
restricted \write18 enabled.
|
||||
%&-line parsing enabled.
|
||||
**JetCore.tex
|
||||
(./JetCore.tex
|
||||
LaTeX2e <2023-11-01> patch level 1
|
||||
L3 programming layer <2024-01-22>
|
||||
(/usr/share/texlive/texmf-dist/tex/latex/base/book.cls
|
||||
Document Class: book 2023/05/17 v1.4n Standard LaTeX document class
|
||||
(/usr/share/texlive/texmf-dist/tex/latex/base/bk10.clo
|
||||
File: bk10.clo 2023/05/17 v1.4n Standard LaTeX file (size option)
|
||||
)
|
||||
\c@part=\count187
|
||||
\c@chapter=\count188
|
||||
\c@section=\count189
|
||||
\c@subsection=\count190
|
||||
\c@subsubsection=\count191
|
||||
\c@paragraph=\count192
|
||||
\c@subparagraph=\count193
|
||||
\c@figure=\count194
|
||||
\c@table=\count195
|
||||
\abovecaptionskip=\skip48
|
||||
\belowcaptionskip=\skip49
|
||||
\bibindent=\dimen140
|
||||
)
|
||||
(/usr/share/texlive/texmf-dist/tex/latex/l3backend/l3backend-pdftex.def
|
||||
File: l3backend-pdftex.def 2024-01-04 L3 backend support: PDF output (pdfTeX)
|
||||
\l__color_backend_stack_int=\count196
|
||||
\l__pdf_internal_box=\box51
|
||||
)
|
||||
(./JetCore.aux)
|
||||
\openout1 = `JetCore.aux'.
|
||||
|
||||
LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 7.
|
||||
LaTeX Font Info: ... okay on input line 7.
|
||||
LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 7.
|
||||
LaTeX Font Info: ... okay on input line 7.
|
||||
LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 7.
|
||||
LaTeX Font Info: ... okay on input line 7.
|
||||
LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 7.
|
||||
LaTeX Font Info: ... okay on input line 7.
|
||||
LaTeX Font Info: Checking defaults for TS1/cmr/m/n on input line 7.
|
||||
LaTeX Font Info: ... okay on input line 7.
|
||||
LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 7.
|
||||
LaTeX Font Info: ... okay on input line 7.
|
||||
LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 7.
|
||||
LaTeX Font Info: ... okay on input line 7.
|
||||
LaTeX Font Info: External font `cmex10' loaded for size
|
||||
(Font) <12> on input line 9.
|
||||
LaTeX Font Info: External font `cmex10' loaded for size
|
||||
(Font) <8> on input line 9.
|
||||
LaTeX Font Info: External font `cmex10' loaded for size
|
||||
(Font) <6> on input line 9.
|
||||
[1
|
||||
|
||||
|
||||
{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}] [2
|
||||
|
||||
]
|
||||
(./JetCore.toc
|
||||
LaTeX Font Info: External font `cmex10' loaded for size
|
||||
(Font) <7> on input line 2.
|
||||
LaTeX Font Info: External font `cmex10' loaded for size
|
||||
(Font) <5> on input line 2.
|
||||
[3])
|
||||
\tf@toc=\write3
|
||||
\openout3 = `JetCore.toc'.
|
||||
|
||||
[4]
|
||||
Chapter 1.
|
||||
[5
|
||||
|
||||
] [6
|
||||
|
||||
]
|
||||
Chapter 2.
|
||||
[7] [8
|
||||
|
||||
]
|
||||
Chapter 3.
|
||||
[9] [10
|
||||
|
||||
]
|
||||
Chapter 4.
|
||||
[11{/usr/share/texmf/fonts/enc/dvips/cm-super/cm-super-ts1.enc}] [12]
|
||||
Chapter 5.
|
||||
[13
|
||||
|
||||
] [14] [15] [16
|
||||
|
||||
]
|
||||
Chapter 6.
|
||||
[17] [18]
|
||||
Chapter 7.
|
||||
[19
|
||||
|
||||
] [20] [21] [22] [23] (./JetCore.aux)
|
||||
***********
|
||||
LaTeX2e <2023-11-01> patch level 1
|
||||
L3 programming layer <2024-01-22>
|
||||
***********
|
||||
)
|
||||
Here is how much of TeX's memory you used:
|
||||
508 strings out of 474222
|
||||
9280 string characters out of 5748732
|
||||
1936975 words of memory out of 5000000
|
||||
22826 multiletter control sequences out of 15000+600000
|
||||
564392 words of font info for 57 fonts, out of 8000000 for 9000
|
||||
1141 hyphenation exceptions out of 8191
|
||||
35i,6n,50p,280b,189s stack positions out of 10000i,1000n,20000p,200000b,200000s
|
||||
</usr/share/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmbx10.pfb></us
|
||||
r/share/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmbx12.pfb></usr/shar
|
||||
e/texlive/texmf-dist/fonts/type1/public/amsfonts/cm/cmr10.pfb></usr/share/texli
|
||||
ve/texmf-dist/fonts/type1/public/amsfonts/cm/cmr12.pfb></usr/share/texlive/texm
|
||||
f-dist/fonts/type1/public/amsfonts/cm/cmr17.pfb></usr/share/texlive/texmf-dist/
|
||||
fonts/type1/public/amsfonts/cm/cmsl10.pfb></usr/share/texlive/texmf-dist/fonts/
|
||||
type1/public/amsfonts/cm/cmtt10.pfb></usr/share/texmf/fonts/type1/public/cm-sup
|
||||
er/sfrm1000.pfb>
|
||||
Output written on JetCore.pdf (23 pages, 138298 bytes).
|
||||
PDF statistics:
|
||||
119 PDF objects out of 1000 (max. 8388607)
|
||||
77 compressed objects within 1 object stream
|
||||
0 named destinations out of 1000 (max. 500000)
|
||||
1 words of extra memory for PDF output out of 10000 (max. 10000000)
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
\documentclass{book}
|
||||
\usepackage{fontspec}
|
||||
\setmainfont{Roboto}
|
||||
|
||||
\title{JET Extension Tags}
|
||||
\author{Bradford Matthew Arant Sr.}
|
||||
@@ -93,9 +95,12 @@ specifying the scope of global.
|
||||
\item Keyword - within a tag's container we may access the keyword
|
||||
values specified on the containing tag.
|
||||
|
||||
\item Environment -
|
||||
\item Session - values stored in the session file with the set tag and
|
||||
a scope of session. They persist across requests from the same browser.
|
||||
|
||||
\item CGI Variables -
|
||||
\item Environment -
|
||||
|
||||
\item CGI Variables -
|
||||
|
||||
\end{itemize}
|
||||
|
||||
@@ -118,6 +123,32 @@ the container where they are defined. Some containers may not be
|
||||
capable of storing local variables (i.e. set tag) and are inheriting
|
||||
the local scope from their parent tag.
|
||||
|
||||
\section{Session Variables}
|
||||
|
||||
Session variables are stored in the session file for the current
|
||||
session and remain available to later requests from the same browser.
|
||||
Session control must be enabled (see Session Control).
|
||||
|
||||
A session variable is written with the set tag and a scope of
|
||||
session:
|
||||
|
||||
\begin{verbatim}
|
||||
<set name="_login_id" value="$[login_id]" scope="session">
|
||||
\end{verbatim}
|
||||
|
||||
The name can be any variable name. It does not need an @ prefix.
|
||||
Session variables are read with the \$[@name] syntax, for example
|
||||
\$[@\_login\_id].
|
||||
|
||||
Setting a session variable does not also set a global variable of
|
||||
the same name. When the same request needs to read the value as
|
||||
\$[name], set it with both scopes:
|
||||
|
||||
\begin{verbatim}
|
||||
<set name="_login_id" value="$[login_id]">
|
||||
<set name="_login_id" value="$[login_id]" scope="session">
|
||||
\end{verbatim}
|
||||
|
||||
\section{Keyword Variables}
|
||||
|
||||
Keyword variables are set when they are specified on a containing tag.
|
||||
@@ -166,15 +197,19 @@ operators, as follows:
|
||||
|
||||
\section{Date Functions}
|
||||
|
||||
\subsection{datediff}
|
||||
|
||||
\subsection{unixtime}
|
||||
|
||||
\section{Math Functions}
|
||||
|
||||
\subsection{abs}
|
||||
|
||||
Returns the absolute value of the given parameter.
|
||||
|
||||
\subsection{acos}
|
||||
|
||||
Returns to arc-cosine of the given parameter.
|
||||
Returns to arc cosine of the given parameter.
|
||||
|
||||
\subsection{asin}
|
||||
|
||||
@@ -182,10 +217,20 @@ Returns to arc-cosine of the given parameter.
|
||||
|
||||
\subsection{cos}
|
||||
|
||||
\subsection{floor}
|
||||
|
||||
\subsection{ceil}
|
||||
|
||||
\subsection{max}
|
||||
|
||||
Returns the greatest value item from a list of comma seperated values in a
|
||||
list.
|
||||
|
||||
\subsection{min}
|
||||
|
||||
Returns the least value item from a list of comma seperated values in
|
||||
a list.
|
||||
|
||||
\subsection{pow}
|
||||
|
||||
\subsection{random}
|
||||
@@ -196,11 +241,15 @@ Use the random function to return a random number between 0 and 1.
|
||||
|
||||
\section{String Functions}
|
||||
|
||||
String functions are provided to accelerate the building and parsing of strings passed into the expression. Numbers can be treated as a string or a number depending on the function called and the data state of the values being manipulated.
|
||||
String functions are provided to accelerate the building and parsing of
|
||||
strings passed into the expression. Numbers can be treated as a string or
|
||||
a number depending on the function called and the data state of the values
|
||||
being manipulated.
|
||||
|
||||
\subsection{concat}
|
||||
|
||||
The concat tag is used to assemble a string by concatenating one or more values to formulate the resulting string.
|
||||
The concat function is used to assemble a string by concatenating one or
|
||||
more values to formulate the resulting string.
|
||||
|
||||
|
||||
|
||||
@@ -208,6 +257,21 @@ The concat tag is used to assemble a string by concatenating one or more values
|
||||
|
||||
\subsection{left}
|
||||
|
||||
Use the left function to return the number of characters specified in
|
||||
the second parameter from the parameter passed as the first parameter.
|
||||
|
||||
If the number of characters to return is greater than the length of
|
||||
the first parameter then the entire parameter is returned.
|
||||
|
||||
\subsection{ltrim}
|
||||
|
||||
Use the ltrim function to remove the leading blanks (spaces, tabs and
|
||||
newlines) from a value. Trailing blanks are kept.
|
||||
|
||||
\begin{verbatim}
|
||||
ltrim(' abc ') returns 'abc '
|
||||
\end{verbatim}
|
||||
|
||||
\subsection{reverse}
|
||||
|
||||
\subsection{right}
|
||||
@@ -215,7 +279,16 @@ The concat tag is used to assemble a string by concatenating one or more values
|
||||
\subsection{round}
|
||||
|
||||
Use the round function to round a numeric value to the specified
|
||||
number of digits after the decimal point.
|
||||
number of digits after the decimal point.
|
||||
|
||||
\subsection{rtrim}
|
||||
|
||||
Use the rtrim function to remove the trailing blanks (spaces, tabs and
|
||||
newlines) from a value. Leading blanks are kept.
|
||||
|
||||
\begin{verbatim}
|
||||
rtrim(' abc ') returns ' abc'
|
||||
\end{verbatim}
|
||||
|
||||
\subsection{substring}
|
||||
|
||||
@@ -228,6 +301,13 @@ the value as a string.
|
||||
|
||||
\subsection{trim}
|
||||
|
||||
Use the trim function to remove the blanks (spaces, tabs and newlines)
|
||||
from both ends of a value. See also ltrim and rtrim.
|
||||
|
||||
\begin{verbatim}
|
||||
trim(' abc ') returns 'abc'
|
||||
\end{verbatim}
|
||||
|
||||
\subsection{expr}
|
||||
|
||||
Use the expr function to parse the string contents contained in the expr string.
|
||||
@@ -273,8 +353,16 @@ into the directory named after the token. Captured session data will
|
||||
become available to future requests coming into the server and made
|
||||
available through the variable formats for the session.
|
||||
|
||||
The <set> tag will also have an additional scope value that can be
|
||||
used to store the value in the session. This is scope="session".
|
||||
Under APIServer, session control is enabled for a site by its
|
||||
sessionDir setting in the server configuration instead of the <jet>
|
||||
tag.
|
||||
|
||||
Use the <set> tag with scope="session" to store a value in the
|
||||
session, and \$[@name] to read it back (see Session Variables).
|
||||
|
||||
The session tags in SESSIONCTL.tag are deprecated for session
|
||||
management. Its setenv tag has been removed, and the startsession and
|
||||
endsession tags are no longer provided. Use scope="session" instead.
|
||||
|
||||
|
||||
|
||||
@@ -289,6 +377,82 @@ variable parsing. This sequence is |> this is not parsed or resolved
|
||||
and is different from the <exclude /> tag as exclude may be further
|
||||
parsed if output is again evaluated.
|
||||
|
||||
\section{bind}
|
||||
|
||||
Use the bind tag inside an sql tag to supply the value for a ?
|
||||
placeholder in the statement. Each bind fills the next ? in order. The
|
||||
value is escaped or checked before it reaches the server, so whatever
|
||||
it contains can never change the meaning of the statement. Use bind for
|
||||
every value that comes from a request, a cookie or a session instead of
|
||||
writing \$[name] into the statement text.
|
||||
|
||||
The bind tag has no closing tag and produces no output. It must be
|
||||
inside an sql tag, although it may be inside other tags (if, for and so
|
||||
on) within that sql tag.
|
||||
|
||||
\begin{verbatim}
|
||||
<sql>select id, name from users where email=? and status=?
|
||||
<bind value="$[email]">
|
||||
<bind value="ACTIVE">
|
||||
</sql>
|
||||
\end{verbatim}
|
||||
|
||||
The attributes are:
|
||||
|
||||
value - the value to bind. Required. Any expression or variable
|
||||
reference may be used here.
|
||||
|
||||
type - how the value is checked and sent. The values are:
|
||||
|
||||
\begin{itemize}
|
||||
\item string - the default. Quoted and escaped.
|
||||
\item int - a whole number of up to 19 digits, optionally negative.
|
||||
Sent without quotes.
|
||||
\item decimal - a number with an optional fraction, for example
|
||||
-12.50. Sent without quotes.
|
||||
\item bool - 1, true, yes, 0, false or no (any case). Sent as 1 or 0.
|
||||
\item date - YYYY-MM-DD.
|
||||
\item datetime - YYYY-MM-DD HH:MM or YYYY-MM-DD HH:MM:SS.
|
||||
\item ident - a column or table name, or a sort direction, for the
|
||||
places SQL cannot take a value (ORDER BY and so on). Requires the allow
|
||||
attribute. Names are sent in backticks; ASC and DESC are sent as they
|
||||
are.
|
||||
\end{itemize}
|
||||
|
||||
null - set to empty to send SQL NULL when the value is empty. Without
|
||||
it an empty value is sent as an empty string (and is an error for int,
|
||||
decimal, bool, date and datetime).
|
||||
|
||||
allow - for type="ident" only. A comma separated list of the values
|
||||
that are permitted. Any other value is an error.
|
||||
|
||||
\begin{verbatim}
|
||||
<sql>select * from products order by ? ?
|
||||
<bind value="$[sort]" type="ident" allow="name,price,created">
|
||||
<bind value="$[dir]" type="ident" allow="ASC,DESC">
|
||||
</sql>
|
||||
\end{verbatim}
|
||||
|
||||
A ? inside a quoted string, a backtick name or a comment in the
|
||||
statement is not a placeholder. An sql tag that contains no bind tags
|
||||
is run exactly as written, so a ? in it is left alone.
|
||||
|
||||
These are errors, and can be caught with try/catch: a value that does
|
||||
not fit its type, an ident that is not in the allow list, a bind
|
||||
outside an sql tag, a bind with no value, an unknown type, and a
|
||||
statement whose number of ? placeholders differs from its number of
|
||||
bind tags. The error text never contains the bound value itself.
|
||||
|
||||
To find the sql tags that still write values into the statement text,
|
||||
run the jet compiler's lint over a site:
|
||||
|
||||
\begin{verbatim}
|
||||
jetc --lint-sql /path/to/site
|
||||
\end{verbatim}
|
||||
|
||||
It prints the file and line of each one, with the variables it uses.
|
||||
Add \texttt{-{}-strict} to include values from the rows of an earlier query.
|
||||
|
||||
\section{call}
|
||||
|
||||
Use the call tag to evoke an executable file from a jet script.
|
||||
@@ -462,7 +626,16 @@ value
|
||||
|
||||
container
|
||||
|
||||
scope
|
||||
scope - where the variable is stored. The values are:
|
||||
|
||||
\begin{itemize}
|
||||
\item global - the default. Available to all logic for the rest of the
|
||||
request.
|
||||
\item local - available only within the container where it is set.
|
||||
\item parent - stored in the scope of the enclosing tag.
|
||||
\item session - stored in the session file and kept across requests.
|
||||
Requires session control. See Session Variables.
|
||||
\end{itemize}
|
||||
|
||||
\section{sql}
|
||||
|
||||
@@ -473,6 +646,21 @@ As long as sql statements are executed within the same mysql
|
||||
containing tag then the same mysql session is used for each sql
|
||||
statement.
|
||||
|
||||
Values that come from a request, a cookie or a session should be
|
||||
passed with bind tags and ? placeholders rather than written into the
|
||||
statement text. See the bind tag.
|
||||
|
||||
\begin{verbatim}
|
||||
<sql>delete from cart_item where session_uuid=? and sku=?
|
||||
<bind value="$[_session_id]">
|
||||
<bind value="$[sku]">
|
||||
</sql>
|
||||
\end{verbatim}
|
||||
|
||||
A statement that changes the connection character set (SET NAMES, SET
|
||||
CHARACTER SET and similar) is refused. The connection always uses
|
||||
utf8mb4.
|
||||
|
||||
The attributes are:
|
||||
|
||||
sessionid
|
||||
@@ -542,4 +730,4 @@ a container to process for each row retrieved by the sql statement.
|
||||
|
||||
Use the write tag to write data to the local file system.
|
||||
|
||||
\end{document}
|
||||
\end{document}
|
||||
@@ -1,70 +0,0 @@
|
||||
\contentsline {chapter}{\numberline {1}Introduction}{5}{}%
|
||||
\contentsline {section}{\numberline {1.1}Use Cases}{5}{}%
|
||||
\contentsline {subsection}{\numberline {1.1.1}World Wide Web Site}{5}{}%
|
||||
\contentsline {subsection}{\numberline {1.1.2}API Handling}{5}{}%
|
||||
\contentsline {subsection}{\numberline {1.1.3}Asterisk Dial Plan Generator Tool}{5}{}%
|
||||
\contentsline {chapter}{\numberline {2}Tags and Attributes}{7}{}%
|
||||
\contentsline {chapter}{\numberline {3}User Defined Tags and Tag Libraries}{9}{}%
|
||||
\contentsline {chapter}{\numberline {4}Variables and Variable Types}{11}{}%
|
||||
\contentsline {section}{\numberline {4.1}Global Variables}{11}{}%
|
||||
\contentsline {section}{\numberline {4.2}Local Variables}{12}{}%
|
||||
\contentsline {section}{\numberline {4.3}Keyword Variables}{12}{}%
|
||||
\contentsline {section}{\numberline {4.4}Environment Variables}{12}{}%
|
||||
\contentsline {section}{\numberline {4.5}CGI Variables}{12}{}%
|
||||
\contentsline {chapter}{\numberline {5}Expressions}{13}{}%
|
||||
\contentsline {section}{\numberline {5.1}Operators}{13}{}%
|
||||
\contentsline {subsection}{\numberline {5.1.1}Arithmetic Operators}{13}{}%
|
||||
\contentsline {subsection}{\numberline {5.1.2}Boolean Operators}{13}{}%
|
||||
\contentsline {section}{\numberline {5.2}Function Reference}{13}{}%
|
||||
\contentsline {section}{\numberline {5.3}Date Functions}{13}{}%
|
||||
\contentsline {subsection}{\numberline {5.3.1}unixtime}{13}{}%
|
||||
\contentsline {section}{\numberline {5.4}Math Functions}{13}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.1}abs}{13}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.2}acos}{13}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.3}asin}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.4}atan}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.5}cos}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.6}max}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.7}min}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.8}pow}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.9}random}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.4.10}sin}{14}{}%
|
||||
\contentsline {section}{\numberline {5.5}String Functions}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.1}concat}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.2}integer}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.3}left}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.4}reverse}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.5}right}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.6}round}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.7}substring}{14}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.8}tolower}{15}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.9}toupper}{15}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.10}trim}{15}{}%
|
||||
\contentsline {subsection}{\numberline {5.5.11}expr}{15}{}%
|
||||
\contentsline {chapter}{\numberline {6}Common Gateway Interface Features}{17}{}%
|
||||
\contentsline {section}{\numberline {6.1}Session Control}{17}{}%
|
||||
\contentsline {chapter}{\numberline {7}Tag Reference}{19}{}%
|
||||
\contentsline {section}{\numberline {7.1}call}{19}{}%
|
||||
\contentsline {section}{\numberline {7.2}comment}{19}{}%
|
||||
\contentsline {section}{\numberline {7.3}cookie}{20}{}%
|
||||
\contentsline {section}{\numberline {7.4}dump}{20}{}%
|
||||
\contentsline {section}{\numberline {7.5}exclude}{20}{}%
|
||||
\contentsline {section}{\numberline {7.6}expr}{20}{}%
|
||||
\contentsline {section}{\numberline {7.7}for}{20}{}%
|
||||
\contentsline {section}{\numberline {7.8}header}{20}{}%
|
||||
\contentsline {section}{\numberline {7.9}if/else}{20}{}%
|
||||
\contentsline {section}{\numberline {7.10}ifrow/else}{21}{}%
|
||||
\contentsline {section}{\numberline {7.11}include}{21}{}%
|
||||
\contentsline {section}{\numberline {7.12}jet}{21}{}%
|
||||
\contentsline {section}{\numberline {7.13}mysql}{21}{}%
|
||||
\contentsline {section}{\numberline {7.14}read}{21}{}%
|
||||
\contentsline {section}{\numberline {7.15}set}{22}{}%
|
||||
\contentsline {section}{\numberline {7.16}sql}{22}{}%
|
||||
\contentsline {section}{\numberline {7.17}stream}{22}{}%
|
||||
\contentsline {section}{\numberline {7.18}system}{22}{}%
|
||||
\contentsline {section}{\numberline {7.19}tag}{22}{}%
|
||||
\contentsline {section}{\numberline {7.20}until}{23}{}%
|
||||
\contentsline {section}{\numberline {7.21}while}{23}{}%
|
||||
\contentsline {section}{\numberline {7.22}whiledir}{23}{}%
|
||||
\contentsline {section}{\numberline {7.23}whilerow}{23}{}%
|
||||
\contentsline {section}{\numberline {7.24}write}{23}{}%
|
||||
@@ -0,0 +1,238 @@
|
||||
# Design: bound parameters for `<sql>`
|
||||
|
||||
**Status:** phases 1 and 2 implemented (2026-11-20) · **Author:** Brad Arant (drafted with Claude) · **Date:** 2026-10-23
|
||||
**Applies to:** JetCore (`__sql`, `__mysql`, `Tag.cpp` tag dispatch, `jetc` parser/codegen)
|
||||
|
||||
## 1. The problem
|
||||
|
||||
`<sql>` builds its query by rendering its body as text, then sending the finished
|
||||
string to MySQL:
|
||||
|
||||
```cpp
|
||||
// __sql.cpp today
|
||||
processContainer(container); // every $[...] substituted as plain text
|
||||
global.getSession(sessionId)->query(out); // mysql_real_query(the whole string)
|
||||
```
|
||||
|
||||
So a request value lands *inside the SQL text*:
|
||||
|
||||
```html
|
||||
<sql>select id from users where email='$[email]' and secret='$[password]'</sql>
|
||||
```
|
||||
|
||||
With `email = x' or '1'='1' -- ` that becomes a different query. There is no
|
||||
escaping function in Jet, so this is the only way to write a query, and it's
|
||||
unsafe everywhere a value comes from a request. Numeric positions are worse:
|
||||
`where id=$[id]` has no quotes, so even escaping wouldn't help (`id = 1 or 1=1`).
|
||||
|
||||
Measured on 2026-10-23 (`<sql>` blocks whose body contains a request/session
|
||||
value other than `$[.column]`, `$[_login_id]` or `$[_session_id]`):
|
||||
|
||||
| Site | `<sql>` blocks | with values pasted in | files |
|
||||
|---|---:|---:|---:|
|
||||
| barant.com | 152 | 117 | 64 |
|
||||
| ClockPlanet | 94 | 83 | 35 |
|
||||
|
||||
Roughly 80% of all queries. Login, signup, cart, checkout and admin pages are
|
||||
all in that set.
|
||||
|
||||
## 2. Goals
|
||||
|
||||
1. A way to pass values to `<sql>` that **can never change the query's meaning**,
|
||||
whatever they contain.
|
||||
2. **No change to how results are read** - `<ifrow>`, `<whilerow>`, `$[.column]`,
|
||||
`$[?N]`, `$[#]` keep working exactly as today.
|
||||
3. Easy, mechanical migration of existing pages; old pages keep running until migrated.
|
||||
4. A path to *enforcing* it, so new unsafe queries can't be written by accident.
|
||||
|
||||
Non-goals: an ORM, query builders, or changing `<database>`/`<mysql>` connection handling.
|
||||
|
||||
## 3. Proposed syntax
|
||||
|
||||
Placeholders are `?` in the query; values come from `<bind>` tags inside the
|
||||
`<sql>`, in order:
|
||||
|
||||
```html
|
||||
<sql>
|
||||
select id, name from users where email=? and status=?
|
||||
<bind value="$[email]">
|
||||
<bind value="ACTIVE">
|
||||
</sql>
|
||||
```
|
||||
|
||||
`<bind>` attributes:
|
||||
|
||||
| attribute | meaning |
|
||||
|---|---|
|
||||
| `value` | the value (any Jet expression - `$[...]` is fine here, that's the point) |
|
||||
| `type` | `string` (default), `int`, `decimal`, `bool`, `date`, `datetime`, `ident` |
|
||||
| `null` | `empty` = bind SQL `NULL` when the value is empty (default: bind `''`) |
|
||||
| `allow` | for `type="ident"` only: comma list of permitted identifiers |
|
||||
|
||||
Type behaviour (a value that doesn't fit throws a catchable Jet exception -
|
||||
`<try>`/`<catch>` works, see §6):
|
||||
|
||||
- `string` - quoted and escaped (§4).
|
||||
- `int` - must match `^-?[0-9]{1,19}$`; emitted bare. This fixes the unquoted
|
||||
`where id=$[id]` case.
|
||||
- `decimal` - must match `^-?[0-9]{1,30}(\.[0-9]{1,30})?$`; emitted bare.
|
||||
- `bool` - `1/0/true/false/yes/no` → `1`/`0`.
|
||||
- `date` / `datetime` - must parse as `YYYY-MM-DD` / `YYYY-MM-DD HH:MM[:SS]`; quoted.
|
||||
- `ident` - for the things SQL can't parameterise (column in `ORDER BY`, a sort
|
||||
direction, a table name). The value must be in `allow` or it throws; emitted
|
||||
backtick-quoted (`ASC`/`DESC` emitted bare). Example:
|
||||
|
||||
```html
|
||||
<sql>select * from products order by ? ?
|
||||
<bind value="$[sort]" type="ident" allow="name,price,created">
|
||||
<bind value="$[dir]" type="ident" allow="ASC,DESC">
|
||||
</sql>
|
||||
```
|
||||
|
||||
Why `<bind>` and not `<param>`: `param` is an HTML element (inside `<object>`),
|
||||
and `jetc`'s void-tag list treats it as HTML. A Jet-only name avoids any ambiguity.
|
||||
|
||||
Why positional `?` and not named (`:email`): `?` is what MySQL and every SQL
|
||||
library uses, it needs no new attribute-name syntax in the parser, and the
|
||||
`<bind>` lines sit right under the query so the order is easy to read. Named
|
||||
binds can be added later without breaking this (§9).
|
||||
|
||||
## 4. How it works
|
||||
|
||||
### Emulated binding (recommended for phase 1)
|
||||
|
||||
`__sql` collects the `<bind>` values while its body renders, then replaces each
|
||||
`?` that is **outside** a string literal, backtick identifier or comment with the
|
||||
bound value, rendered safely - and only then calls `query()` as today.
|
||||
|
||||
- Strings are escaped with `mysql_real_escape_string_quote(mysql, to, from, len, '\'')`
|
||||
and wrapped in single quotes. This uses the *connection's* character set and
|
||||
respects `NO_BACKSLASH_ESCAPES`, which plain `mysql_real_escape_string` doesn't.
|
||||
- The connection's character set is pinned at connect time
|
||||
(`mysql_options(MYSQL_SET_CHARSET_NAME, "utf8mb4")` in `__mysql`), so escaping
|
||||
and server parsing always agree. `<sql>` refuses a `SET NAMES`/`SET CHARACTER SET`
|
||||
statement (the classic way to make escaping and parsing disagree).
|
||||
- Number of `?` must equal number of `<bind>`s, otherwise throw
|
||||
`"sql: 3 placeholders but 2 bind values"`.
|
||||
|
||||
This is the same approach PHP's PDO uses by default. Its big advantage here:
|
||||
**the result path doesn't change at all** - `query()` still runs
|
||||
`mysql_real_query` and `mysql_store_result`, so `MYSQL_ROW`, `getColumnValue()`,
|
||||
`<ifrow>`, `<whilerow>` and the column-index map are untouched.
|
||||
|
||||
### Why not real server-side prepared statements (yet)
|
||||
|
||||
`mysql_stmt_*` returns rows through typed bind buffers, not `MYSQL_ROW`, so
|
||||
`getColumnValue()`, `$[?N]`, `$[#]` and the field-index map would all need a
|
||||
second implementation, and some statements (multi-statements, some DDL) can't be
|
||||
prepared. That's a bigger change for no extra safety over correct emulation.
|
||||
It stays open as a later option (§9), behind the same `<bind>` syntax, so pages
|
||||
written now won't need touching again.
|
||||
|
||||
### Code shape
|
||||
|
||||
- **New** `__bind.h/.cpp`: on construction, find the nearest enclosing `__sql`
|
||||
(walk `parent` with `dynamic_cast<__sql*>`; throw `"bind must be inside sql"`
|
||||
if none), resolve `value`/`type`/`null`/`allow`, validate per type, and call
|
||||
`sql->addBind(...)`. Produces no output.
|
||||
- **`__sql`**: a `std::vector<BoundValue>` member and `addBind()`. After
|
||||
`processContainer(container)`, run `bindPlaceholders(out)` - a small scanner
|
||||
that tracks `'...'` (with `''` and `\'`), `"..."`, `` `...` ``, `-- `, `#` and
|
||||
`/* */` so `?` inside them is left alone - then `query(result)`.
|
||||
- **`__mysql`**: `escapeString(const MString&)` wrapper around
|
||||
`mysql_real_escape_string_quote`; pin `utf8mb4` at connect.
|
||||
- **`Tag.cpp`**: add `ifTagName(in, "bind")` next to `sql` (line ~494).
|
||||
- **`jetc` `JetParser.cpp`**: add `"bind"` to the Jet void-tag list (it has no
|
||||
closing tag); **`JetCodegen.cpp`**: emit `__bind` like the other tags.
|
||||
|
||||
Estimated size: ~200 lines plus tests.
|
||||
|
||||
## 5. Existing pages: nothing breaks
|
||||
|
||||
A `<sql>` with no `<bind>` runs exactly as today - no `?` replacement at all,
|
||||
so existing queries containing a literal `?` are unaffected. Migration is
|
||||
page by page:
|
||||
|
||||
```html
|
||||
<!-- before -->
|
||||
<sql>select * from users where email="$[email]" and status="CONFIRM"</sql>
|
||||
<!-- after -->
|
||||
<sql>select * from users where email=? and status="CONFIRM"
|
||||
<bind value="$[email]">
|
||||
</sql>
|
||||
|
||||
<!-- before: unquoted number, injectable even with escaping -->
|
||||
<sql>delete from cart_item where session_uuid='$[_session_id]' and sku='$[sku]'</sql>
|
||||
<!-- after -->
|
||||
<sql>delete from cart_item where session_uuid=? and sku=?
|
||||
<bind value="$[_session_id]">
|
||||
<bind value="$[sku]">
|
||||
</sql>
|
||||
```
|
||||
|
||||
## 6. Errors
|
||||
|
||||
- Bad `<bind>` value (wrong type, ident not allowed), placeholder/bind count
|
||||
mismatch, `<bind>` outside `<sql>`: throw `coreutils::Exception` with a clear
|
||||
message, caught by `<try>`/`<catch>` like the MySQL errors fixed on 2026-09-13.
|
||||
- The exception text never includes the bound value itself (it may be a password).
|
||||
|
||||
## 7. Enforcement
|
||||
|
||||
Once pages are migrated, make the unsafe form an error instead of a habit:
|
||||
|
||||
1. **`jetc --lint-sql`** - lists every `<sql>` whose body contains `$[...]`
|
||||
other than `$[.column]` (row values from an outer query), with file:line.
|
||||
This is the migration worklist (§8) and a CI check.
|
||||
|
||||
As implemented (`jetc/JetLint.cpp`): `jetc --lint-sql [--strict] <file|dir>...`
|
||||
scans every file under the given paths. It reports `$[...]` and local
|
||||
`#[...]` references, with the kind of each (`global`, `cgi`, `session`,
|
||||
`env`, `keyword`, `local`). Row values (`$[.col]`, `$[session.col]`,
|
||||
`$[?N]`, `$[#]`, `$[?#]`) are not reported unless `--strict` is given.
|
||||
References in the attributes of `<bind>`, `<if>`, `<else>`, `<ifrow>`,
|
||||
`<while>`, `<whilerow>`, `<until>`, `<for>` and `<set>` are not reported,
|
||||
since those never become statement text; nor is anything inside
|
||||
`<comment>` or `|> <|`. A custom tag defined as `<sql ...><container></sql>`
|
||||
(barant.com's `<showtable>`) takes its statement from the caller's content,
|
||||
so each use of it is checked like an `<sql>`. Exit status: 0 nothing found,
|
||||
1 findings, 2 a path could not be read. Tests: `tests/runlinttests.sh`.
|
||||
2. **Per-site strict mode** - an APIServer site setting
|
||||
`"sqlInterpolation": "warn" | "error"`. In `error` mode `<sql>` refuses to run
|
||||
if its body substituted any `$[...]` except `$[.column]`; `warn` logs it.
|
||||
Default `warn` for existing sites, `error` for new ones.
|
||||
3. **Escape hatch** - `<sql raw="yes">` for the rare trusted dynamic SQL
|
||||
(generated by the site itself, never from input), so it's visible in review
|
||||
and greppable.
|
||||
|
||||
## 8. Migration plan
|
||||
|
||||
| Phase | What | Notes |
|
||||
|---|---|---|
|
||||
| 1 | Implement `<bind>`, escaping, utf8mb4 pinning, tests | JetCore only; no page changes. Done 2026-11-20 |
|
||||
| 2 | `jetc --lint-sql`; run on both sites | produces the worklist (≈200 queries). Done 2026-11-20 on the local copies: see [sql-lint-worklist.md](sql-lint-worklist.md) |
|
||||
| 3 | Convert the high-risk pages first | login/signup/password reset, cart/checkout/payment (`pp.jet`), admin procs, ClockPlanet `mobile_api.jet` and auth |
|
||||
| 4 | Convert the rest; turn on `warn` | logs show anything missed |
|
||||
| 5 | Switch both sites to `error` | unsafe queries can no longer ship |
|
||||
|
||||
Phase 3 is the one that matters most for security and is a few days' work;
|
||||
each conversion is mechanical and testable page by page.
|
||||
|
||||
## 9. Later
|
||||
|
||||
- Named binds: `where email=:email` + `<bind name="email" value="...">`.
|
||||
- Real prepared statements (`mysql_stmt_*`) behind the same `<bind>` syntax.
|
||||
- The companion fix for output: HTML-escape `$[...]` by default with an explicit
|
||||
raw form - the same "safe unless you say otherwise" rule for the other half of
|
||||
the injection problem (cross-site scripting).
|
||||
|
||||
## 10. Tests
|
||||
|
||||
- Every type: valid values bind correctly; invalid values throw.
|
||||
- Injection strings (`' or '1'='1`, `\'`, multibyte sequences such as `0xbf27`,
|
||||
`--`, `;`, NUL bytes) are stored and read back byte-for-byte unchanged.
|
||||
- `?` inside `'...'`, `"..."`, `` `...` ``, `--`, `#` and `/* */` is never replaced.
|
||||
- Placeholder/bind count mismatch throws; `<bind>` outside `<sql>` throws.
|
||||
- A `<sql>` with no binds produces exactly the same query text as before.
|
||||
- `<ifrow>`/`<whilerow>`/`$[.col]`/`$[?N]`/`$[#]` behave identically on bound queries.
|
||||
- `NO_BACKSLASH_ESCAPES` on and off.
|
||||
@@ -24,3 +24,24 @@ mktextfm Bookman
|
||||
mktextfm Bookman
|
||||
mktextfm Bookman
|
||||
mktextfm Bookman
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia/BI
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia/B
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia/I
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia
|
||||
mktextfm Georgia
|
||||
mktextfm PadaukBook
|
||||
mktextfm PadaukBook
|
||||
mktextfm PadaukBook
|
||||
mktextfm Gerramond
|
||||
mktextfm URWBookman
|
||||
mktextfm Bookman
|
||||
@@ -0,0 +1,166 @@
|
||||
# `<sql>` migration worklist
|
||||
|
||||
Output of `jetc --lint-sql` (phase 2 of [design-sql-bound-parameters.md](design-sql-bound-parameters.md)),
|
||||
generated 2026-11-20 from the copies of the two sites in `~/Development`.
|
||||
Each line is a `<sql>` (or a use of a custom tag that wraps one, such as
|
||||
barant.com's `<showtable>`) whose statement pastes in a variable instead of
|
||||
using `<bind>`. The kind in brackets is where the value comes from: `global`
|
||||
includes request parameters, `cgi` is a POST body field, `session` is
|
||||
`$[@name]`, `local` is `#[name]`.
|
||||
|
||||
These local copies are not the whole of either live site. ClockPlanet in
|
||||
particular has only billing and a few site pages here (no `mobile_api.jet`), so
|
||||
rerun the lint on the live site trees for the full list:
|
||||
|
||||
```
|
||||
jetc --lint-sql /path/to/site
|
||||
```
|
||||
|
||||
Phase 3 starts with login/signup/password reset, cart/checkout/payment and
|
||||
admin procs (see the design doc §8).
|
||||
|
||||
## barant.com (`JetCore/jetc/barant-site`)
|
||||
|
||||
```
|
||||
./src/SIPPHONE.tag:178: <sql> pastes $[_login_id] (global)
|
||||
./src/account-info.subpage:3: <sql> pastes $[_login_id] (global)
|
||||
./src/account-info.subpage:14: <sql> pastes $[_login_id] (global)
|
||||
./src/account-info.subpage:28: <sql> pastes $[_login_id] (global)
|
||||
./src/account-info.subpage:54: <sql> pastes $[_login_id] (global)
|
||||
./src/account-invoices.subpage:3: <sql> pastes $[@_invoice_id] (session)
|
||||
./src/account-invoices.subpage:14: <showtable> (wraps sql) pastes $[_login_id] (global)
|
||||
./src/accountconfirm.page:14: <sql> pastes $[uuid] (global)
|
||||
./src/accountconfirm.page:15: <sql> pastes $[uuid] (global)
|
||||
./src/accountconfirm.page:16: <sql> pastes $[id] (global)
|
||||
./src/add_track.page:10: <sql> pastes $[collection_id] (global)
|
||||
./src/add_track.proc:5: <sql> pastes $[login_id] (global), $[collection_id] (global), $[name] (global), $[artist] (global), $[description] (global), $[price] (global), $[filedata_binary] (global)
|
||||
./src/addtasknote.page:12: <sql> pastes $[_task_id] (global)
|
||||
./src/addtasknote.proc:3: <sql> pastes $[_task_id] (global), $[_login_id] (global), $[noteb] (global), $[task_status_id] (global)
|
||||
./src/addtocart.proc:1: <sql> pastes $[_session_id] (global), $[sku] (global)
|
||||
./src/addtocart.proc:4: <sql> pastes $[_session_id] (global), $[sku] (global), $[qty] (global)
|
||||
./src/admin-mailaccounts.subpage:19: <sql> pastes $[@_login_id] (session)
|
||||
./src/barant.tag:70: <sql> pastes #[table] (local), #[where] (local), #[sortfield] (local)
|
||||
./src/cart.menu:2: <sql> pastes $[_session_id] (global)
|
||||
./src/cart.page:17: <sql> pastes $[_session_id] (global)
|
||||
./src/cart.page:34: <sql> pastes $[_session_id] (global)
|
||||
./src/cart.page:67: <sql> pastes $[_session_id] (global)
|
||||
./src/changeprojecticon.proc:3: <sql> pastes $[datax] (global)
|
||||
./src/changeprojecticon.proc:9: <sql> pastes $[image_id] (global), $[_project_id] (global)
|
||||
./src/checkout.page:65: <sql> pastes $[_session_id] (global)
|
||||
./src/checkout.page:75: <sql> pastes $[_session_id] (global)
|
||||
./src/copy_invoice.jet:14: <sql> pastes $[source_invoice_id] (global)
|
||||
./src/copy_invoice.jet:19: <sql> pastes $[new_invoice_id] (global), $[source_invoice_id] (global)
|
||||
./src/create_invoice.jet:14: <sql> pastes $[user_id] (global)
|
||||
./src/createaccount.proc:17: <sql> pastes $[email:0] (global)
|
||||
./src/createaccount.proc:28: <sql> pastes $[name] (global), $[company_name] (global), $[email] (global), $[password] (global)
|
||||
./src/createaccount.proc:46: <sql> pastes $[id] (global), $[link] (global)
|
||||
./src/createproject.proc:2: <sql> pastes $[_login_id] (global), $[text] (global), $[description] (global)
|
||||
./src/createreleasetarget.proc:4: <sql> pastes $[_project_id] (global), $[release] (global), $[descriptionx] (global)
|
||||
./src/createrequest.proc:4: <sql> pastes $[_project_id] (global), $[_login_id] (global), $[priority] (global), $[release_id] (global), $[textx] (global), $[descriptionx] (global)
|
||||
./src/createtask.proc:5: <sql> pastes $[_request_id] (global), $[_login_id] (global), $[textx] (global), $[descriptionx] (global)
|
||||
./src/deleterequest.proc:3: <sql> pastes $[_request_id] (global)
|
||||
./src/documents.jet:2: <sql> pastes $[id] (global), $[@_login_id] (session)
|
||||
./src/documents_api.jet:17: <sql> pastes $[@_login_id] (session), $[name] (global)
|
||||
./src/documents_api.jet:29: <sql> pastes $[id] (global), $[@_login_id] (session)
|
||||
./src/documents_api.jet:31: <sql> pastes $[id] (global), $[@_login_id] (session)
|
||||
./src/documents_api.jet:43: <sql> pastes $[@_login_id] (session)
|
||||
./src/documents_delete.proc:4: <sql> pastes $[delete_id] (global), $[@_login_id] (session)
|
||||
./src/documents_delete.proc:6: <sql> pastes $[delete_id] (global), $[@_login_id] (session)
|
||||
./src/documents_upload.proc:4: <sql> pastes $[@_login_id] (session), $[name] (global)
|
||||
./src/editinvoice.page:180: <sql> pastes $[@_invoice_id] (session)
|
||||
./src/editinvoice.page:234: <sql> pastes $[@_invoice_id] (session)
|
||||
./src/editproduct.page:8: <sql> pastes $[_product_sku] (global)
|
||||
./src/editrequest.page:7: <sql> pastes $[_request_id] (global)
|
||||
./src/edittask.page:12: <sql> pastes $[_task_id] (global)
|
||||
./src/invoice.method:1: <sql> pastes $[@_invoice_id] (session)
|
||||
./src/invoice.method:28: <sql> pastes $[@_invoice_id] (session)
|
||||
./src/invoice.method:51: <sql> pastes $[@_invoice_id] (session)
|
||||
./src/invoices.menu:2: <sql> pastes $[_user_id] (global)
|
||||
./src/login.method:1: <sql> pastes $[login_email] (global), $[login_password] (global)
|
||||
./src/login.method:16: <sql> pastes $[login_id] (global)
|
||||
./src/login.method:17: <sql> pastes $[login_id] (global)
|
||||
./src/mailaccounts.jet:25: <sql> pastes $[@_login_id] (session), $[mail_email] (global), $[mail_host] (global), $[mail_password] (global)
|
||||
./src/mailaccounts.jet:38: <sql> pastes $[account_id] (global), $[@_login_id] (session)
|
||||
./src/make_invoice.method:5: <sql> pastes $[_session_id] (global)
|
||||
./src/make_invoice.method:47: <sql> pastes $[_login_id] (global), $[total] (global)
|
||||
./src/make_invoice.method:62: <sql> pastes $[invoice_id] (global), $[total] (global), $[card_brand] (global), $[last_4_digits] (global), $[exp_month] (global), $[exp_year] (global), $[payment_id] (global), $[tranonce] (global)
|
||||
./src/make_invoice.method:74: <sql> pastes $[_session_id] (global)
|
||||
./src/make_invoice.method:81: <sql> pastes $[invoice_id] (global)
|
||||
./src/make_invoice.method:96: <sql> pastes $[license] (global)
|
||||
./src/make_invoice.method:97: <sql> pastes $[_login_id] (global), $[invoice_id] (global), $[license] (global), $[key] (global)
|
||||
./src/make_invoice.method:110: <sql> pastes $[_session_id] (global)
|
||||
./src/memberhometemplate.temp:25: <sql> pastes $[login_id] (global)
|
||||
./src/menu.bar:18: <sql> pastes $[_session_id] (global)
|
||||
./src/musicianhome.page:13: <sql> pastes $[login_id] (global)
|
||||
./src/musicianhome.page:35: <sql> pastes $[login_id] (global)
|
||||
./src/myprojects.page:15: <showtable> (wraps sql) pastes $[_login_id] (global)
|
||||
./src/myworklist.page:10: <showtable> (wraps sql) pastes $[_login_id] (global)
|
||||
./src/newcollection.proc:11: <sql> pastes $[login_id] (global), $[name] (global), $[artist] (global), $[description] (global), $[price] (global)
|
||||
./src/payinvoice.page:7: <sql> pastes $[_invoice_id] (global)
|
||||
./src/phones.section:1: <sql> pastes $[@_login_id] (session)
|
||||
./src/phones.section:9: <showtable> (wraps sql) pastes $[@_login_id] (session)
|
||||
./src/processorder.proc:4: <sql> pastes $[_login_id] (global)
|
||||
./src/processorder.proc:7: <sql> pastes $[_session_id] (global)
|
||||
./src/processorder.proc:12: <sql> pastes $[invoice_id] (global)
|
||||
./src/processorder.proc:27: <sql> pastes $[license] (global)
|
||||
./src/processorder.proc:28: <sql> pastes $[_login_id] (global), $[invoice_id] (global), $[license] (global), $[key] (global)
|
||||
./src/processorder.proc:41: <sql> pastes $[_session_id] (global)
|
||||
./src/project.page:16: <sql> pastes $[_project_id] (global)
|
||||
./src/project.page:37: <showtable> (wraps sql) pastes $[_project_id] (global)
|
||||
./src/project.tag:3: <sql> pastes $[_project_id] (global)
|
||||
./src/projects.menu:1: <sql> pastes $[_login_id] (global)
|
||||
./src/projman.bar:15: <sql> pastes $[_session_id] (global)
|
||||
./src/registermusician.proc:2: <sql> pastes $[login_id] (global)
|
||||
./src/removecartitem.proc:1: <sql> pastes $[_session_id] (global), $[sku] (global)
|
||||
./src/removefromcart.proc:1: <sql> pastes $[_session_id] (global)
|
||||
./src/request.page:12: <sql> pastes $[_request_id] (global)
|
||||
./src/request.page:43: <showtable> (wraps sql) pastes $[_request_id] (global)
|
||||
./src/selectproject.proc:2: <sql> pastes $[project_id] (global)
|
||||
./src/selecttask.proc:2: <sql> pastes $[task_id] (global)
|
||||
./src/send_invoice_email.method:5: <sql> pastes $[_send_invoice_id] (global)
|
||||
./src/task.page:12: <sql> pastes $[_request_id] (global)
|
||||
./src/task.page:35: <sql> pastes $[_task_id] (global)
|
||||
./src/taskassignresource.page:15: <sql> pastes $[_task_id] (global)
|
||||
./src/taskassignresource.proc:5: <sql> pastes $[_task_id] (global), $[user_id] (global), $[estimate_hours] (global)
|
||||
./src/update_invoice.proc:3: <sql> pastes $[@_invoice_id] (session)
|
||||
./src/update_invoice.proc:5: <sql> pastes $[@_invoice_id] (session), $[sku$[ix]] (global), $[quantity$[ix]] (global), $[description$[ix]] (global), $[textarea$[ix]] (global), $[price$[ix]] (global), $[total$[ix]] (global), $[tax_amount$[ix]] (global), $[type$[ix]] (global)
|
||||
./src/update_invoice.proc:8: <sql> pastes $[invoice_total] (global), $[user_id] (global), $[@_invoice_id] (session)
|
||||
./src/update_product.proc:2: <sql> pastes $[type] (global), $[description] (global), $[text] (global), $[price] (global), $[image] (global), $[_product_sku] (global)
|
||||
./src/updatecartqty.proc:2: <sql> pastes $[_session_id] (global), $[sku] (global)
|
||||
./src/updatecartqty.proc:4: <sql> pastes $[qty] (global), $[_session_id] (global), $[sku] (global)
|
||||
./src/updaterequest.proc:6: <sql> pastes $[textx] (global), $[descriptionx] (global), $[priority] (global), $[owner_id] (global), $[release_id] (global), $[_request_id] (global)
|
||||
./src/upload_modular1_1_preset.proc:5: <sql> pastes $[title] (global), $[textx] (global), $[preset_datax] (global), $[audio_samplex] (global)
|
||||
lint-sql: 108 of 139 <sql> blocks (and uses of tags that wrap <sql>) paste values into the statement, in 64 of 76 files (global 174, local 3, session 22)
|
||||
```
|
||||
|
||||
## ClockPlanet (`~/Development/ClockPlanet`)
|
||||
|
||||
```
|
||||
./billing/account.page:9: <sql> pastes $[_acct_bid] (global)
|
||||
./billing/account.page:46: <sql> pastes $[_acct_bid] (global), $[_acct_req] (global)
|
||||
./billing/account.page:157: <sql> pastes $[_acct_bid] (global)
|
||||
./billing/account.page:159: <sql> pastes $[_acct_bid] (global)
|
||||
./billing/billing_api.jet:28: <sql> pastes $[_mail_key] (global)
|
||||
./billing/billing_api.jet:50: <sql> pastes $[_mail_key] (global)
|
||||
./billing/billing_api.jet:53: <sql> pastes $[_notice_business] (global)
|
||||
./billing/dobilling_pay.proc:16: <sql> pastes $[_bp_bid] (global)
|
||||
./billing/dobilling_settings.proc:7: <sql> pastes $[_bs_bid] (global), $[_bs_low] (global), $[_bs_rep] (global)
|
||||
./billing/dobilling_settings.proc:14: <sql> pastes $[_bs_low] (global), $[_bs_rep] (global), $[_bs_bid] (global)
|
||||
./billing/doemployee_add.proc:6: <sql> pastes $[@_login_business_id] (session), $[name] (global), $[role] (global), $[phone] (global), $[mode] (global), $[invitecode] (global)
|
||||
./billing/invoice.method:1: <sql> pastes $[_cp_invoice_id] (global)
|
||||
./billing/invoice.method:33: <sql> pastes $[_cp_invoice_id] (global)
|
||||
./billing/invoice.method:52: <sql> pastes $[_cp_invoice_id] (global)
|
||||
./billing/send_invoice_email.method:3: <sql> pastes $[_send_invoice_id] (global)
|
||||
./site-live/billing-current.txt:10: <sql> pastes $[_acct_bid] (global)
|
||||
./site-live/billing-current.txt:49: <sql> pastes $[_acct_bid] (global), $[_acct_req] (global)
|
||||
./site-live/billing-current.txt:114: <sql> pastes $[_acct_bid] (global)
|
||||
./site-live/billing-current.txt:116: <sql> pastes $[_acct_bid] (global)
|
||||
./site-live/billing-current.txt:252: <sql> pastes $[_mail_key] (global)
|
||||
./site-live/billing-current.txt:272: <sql> pastes $[_mail_key] (global)
|
||||
./site-live/billing-current.txt:275: <sql> pastes $[_notice_business] (global)
|
||||
./site-live/billing-current.txt:313: <sql> pastes $[@_login_business_id] (session), $[name] (global), $[role] (global), $[phone] (global), $[mode] (global), $[invitecode] (global)
|
||||
./site-live/sites.page:12: <sql> pastes $[@_login_business_id] (session)
|
||||
./site-live/sites.page:32: <sql> pastes $[@_login_business_id] (session)
|
||||
./site-live/sites.page:36: <sql> pastes $[@_login_business_id] (session)
|
||||
lint-sql: 26 of 28 <sql> blocks paste values into the statement, in 9 of 10 files (global 37, session 5)
|
||||
```
|
||||
@@ -23,16 +23,37 @@ int main(int argc, char **argv, char **envp) {
|
||||
std::cout << out;
|
||||
}
|
||||
catch(coreutils::Exception e) {
|
||||
data.setCursor(global.errorCursor);
|
||||
data.moveBackToLineStart();
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
std::cout << "Error in jet script '" << argv[1] << "' at line " << data.getLineNumberAtCursor() << std::endl;
|
||||
std::cout << "Error text: " << e.text << std::endl;
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
std::cout << data.parsed() << std::endl;
|
||||
std::cout << "******** Error caught: " << e.text << std::endl;
|
||||
std::cout << data.unparsed() << std::endl;
|
||||
// global.errorCursor is updated by every Tag's own construction, so
|
||||
// it can point into a completely different buffer than `data` (the
|
||||
// top-level script) - most commonly, a custom tag's own expanded
|
||||
// template body (container3 in __dotag.cpp) when the error actually
|
||||
// happened while that was being processed, not the top-level script
|
||||
// directly. ZString::setCursor() correctly rejects a cursor that
|
||||
// isn't within its own buffer, but that rejection is itself a throw
|
||||
// - uncaught here, a SECOND exception escaping while this catch
|
||||
// block is still handling the first one calls std::terminate()
|
||||
// immediately, crashing the whole process instead of reporting a
|
||||
// normal error. Confirmed via a real crash + gdb backtrace while
|
||||
// testing an error thrown from inside a custom tag's own body.
|
||||
// Degrade gracefully instead: the error text above is already the
|
||||
// important part; the precise source-line context is a bonus only
|
||||
// available when the cursor genuinely belongs to this buffer.
|
||||
try {
|
||||
data.setCursor(global.errorCursor);
|
||||
data.moveBackToLineStart();
|
||||
std::cout << "Error in jet script '" << argv[1] << "' at line " << data.getLineNumberAtCursor() << std::endl;
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
std::cout << data.parsed() << std::endl;
|
||||
std::cout << "******** Error caught: " << e.text << std::endl;
|
||||
std::cout << data.unparsed() << std::endl;
|
||||
} catch(coreutils::Exception) {
|
||||
std::cout << "(error originated inside a custom tag's own expansion - "
|
||||
<< "no precise source-line context available for it)" << std::endl;
|
||||
std::cout << "-----------------------------" << std::endl;
|
||||
}
|
||||
global.dump();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
#ifndef __JetAST_h__
|
||||
#define __JetAST_h__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
namespace jetc {
|
||||
|
||||
enum class NodeKind {
|
||||
TEXT, VAR, SET, IF, FOR, WHILE, FALLBACK, TAGDEF, CONTAINER_SLOT
|
||||
};
|
||||
|
||||
enum class CondMode { VALUES, EXPR };
|
||||
|
||||
struct Node;
|
||||
using NodePtr = std::shared_ptr<Node>;
|
||||
|
||||
struct Cond {
|
||||
CondMode mode = CondMode::EXPR;
|
||||
std::string value1, value2, type; // VALUES mode
|
||||
std::string expr; // EXPR mode
|
||||
};
|
||||
|
||||
struct Node {
|
||||
NodeKind kind;
|
||||
|
||||
// TEXT
|
||||
std::string text;
|
||||
|
||||
// VAR - raw source slice, e.g. "$[@greeting]" or "#[foo]"
|
||||
std::string varText;
|
||||
|
||||
// SET
|
||||
std::string setName;
|
||||
bool setHasValue = false;
|
||||
std::string setValue;
|
||||
bool setHasExpr = false;
|
||||
std::string setExpr;
|
||||
std::string setScope; // "" = default/global
|
||||
|
||||
// IF
|
||||
Cond cond;
|
||||
std::vector<NodePtr> thenBody;
|
||||
std::vector<NodePtr> elseBody;
|
||||
bool hasElse = false;
|
||||
|
||||
// FOR
|
||||
bool forHasStart = false;
|
||||
std::string forStart;
|
||||
std::string forEnd;
|
||||
std::string forStep;
|
||||
bool forHasName = false;
|
||||
std::string forName;
|
||||
std::string forScope;
|
||||
std::vector<NodePtr> body; // also used by WHILE
|
||||
|
||||
// TAGDEF - a top-level <tag name="X">...</tag> custom-tag definition
|
||||
// (only recognized at the file's true top level - see Parser::topLevel;
|
||||
// one nested inside another tag's own definition body stays FALLBACK,
|
||||
// unchanged). tagDefName is already lowercased, matching __tag.cpp's
|
||||
// own registration key. tagDefBody is the compiled definition body
|
||||
// (may itself contain CONTAINER_SLOT nodes for <container> markers,
|
||||
// and FALLBACK leaves for anything still unsupported). rawSpan
|
||||
// (shared with FALLBACK, below) still holds the exact original source
|
||||
// text - codegen still emits the same raw interpretSpan-based
|
||||
// registration into global.tags alongside the new compiled fast path,
|
||||
// so anything that reaches this tag some other way keeps working
|
||||
// exactly as it does today.
|
||||
std::string tagDefName;
|
||||
std::vector<NodePtr> tagDefBody;
|
||||
|
||||
// CONTAINER_SLOT - a <container> marker (see Tag::renderContainer) -
|
||||
// a pure leaf, no extra fields.
|
||||
|
||||
// FALLBACK - exact original source text of one unsupported tag
|
||||
std::string rawSpan;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,314 @@
|
||||
#include "JetCodegen.h"
|
||||
#include <stdexcept>
|
||||
|
||||
namespace jetc {
|
||||
|
||||
std::string Codegen::ind(int indent) {
|
||||
return std::string(indent * 3, ' ');
|
||||
}
|
||||
|
||||
std::string Codegen::cstr(const std::string &raw) {
|
||||
std::string r;
|
||||
r.reserve(raw.size() + 8);
|
||||
r += '"';
|
||||
for (unsigned char c : raw) {
|
||||
switch (c) {
|
||||
case '\\': r += "\\\\"; break;
|
||||
case '"': r += "\\\""; break;
|
||||
case '\n': r += "\\n"; break;
|
||||
case '\r': r += "\\r"; break;
|
||||
case '\t': r += "\\t"; break;
|
||||
default:
|
||||
if (c < 0x20) {
|
||||
char buf[8];
|
||||
snprintf(buf, sizeof(buf), "\\x%02x\" \"", c);
|
||||
r += buf;
|
||||
} else {
|
||||
r += (char)c;
|
||||
}
|
||||
}
|
||||
}
|
||||
r += '"';
|
||||
return r;
|
||||
}
|
||||
|
||||
std::string Codegen::zstr(const std::string &raw) {
|
||||
// A plain C string literal stops at its first NUL, so text holding
|
||||
// one (raw bytes in a page) has to carry its length explicitly.
|
||||
if (raw.find('\0') == std::string::npos) return cstr(raw);
|
||||
return "coreutils::ZString(" + cstr(raw) + ", " + std::to_string(raw.size()) + ")";
|
||||
}
|
||||
|
||||
const char *Codegen::staticTypeOp(const std::string &type, const char *rc) {
|
||||
// type is known at compile time (a literal attribute value, not a
|
||||
// runtime expression) so the comparison operator is picked once here
|
||||
// instead of being re-checked against six string constants on every
|
||||
// request the way Tag::__if/__while do it at runtime.
|
||||
static thread_local std::string expr;
|
||||
if (type == "eq") expr = std::string(rc) + " == 0";
|
||||
else if (type == "ne") expr = std::string(rc) + " != 0";
|
||||
else if (type == "lt") expr = std::string(rc) + " == -1";
|
||||
else if (type == "le") expr = std::string(rc) + " != 1";
|
||||
else if (type == "gt") expr = std::string(rc) + " == 1";
|
||||
else if (type == "ge") expr = std::string(rc) + " != -1";
|
||||
else throw std::runtime_error("jetc: type=\"" + type + "\" is not one of eq/ne/lt/le/gt/ge "
|
||||
"(and jetc only supports a literal type= value - use expr= for a dynamic comparison).");
|
||||
return expr.c_str();
|
||||
}
|
||||
|
||||
void Codegen::emitBody(const std::vector<NodePtr> &nodes, int indent, std::ostringstream &target) {
|
||||
for (auto &n : nodes) emitNode(n, indent, target);
|
||||
}
|
||||
|
||||
void Codegen::emitNode(const NodePtr &n, int indent, std::ostringstream &target) {
|
||||
std::string I = ind(indent);
|
||||
switch (n->kind) {
|
||||
|
||||
case NodeKind::TEXT: {
|
||||
if (n->text.empty()) break;
|
||||
target << I << "out << " << zstr(n->text) << ";\n";
|
||||
break;
|
||||
}
|
||||
|
||||
case NodeKind::VAR: {
|
||||
target << I << "{ coreutils::ZString v(" << cstr(n->varText) << "); out << scope.getVariable(v, true); }\n";
|
||||
break;
|
||||
}
|
||||
|
||||
case NodeKind::SET: {
|
||||
std::string k = id("set_");
|
||||
target << I << "{\n";
|
||||
target << I << " scope.keywords[\"" << k << "name\"] = " << cstr(n->setName) << ";\n";
|
||||
target << I << " scope.keywords[\"" << k << "scope\"] = " << cstr(n->setScope) << ";\n";
|
||||
target << I << " coreutils::MString val;\n";
|
||||
if (n->setHasExpr) {
|
||||
target << I << " scope.keywords[\"" << k << "expr\"] = " << cstr(n->setExpr) << ";\n";
|
||||
target << I << " val = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).string;\n";
|
||||
} else {
|
||||
target << I << " scope.keywords[\"" << k << "value\"] = " << cstr(n->setHasValue ? n->setValue : std::string()) << ";\n";
|
||||
target << I << " val = scope.resolveKeyword(\"" << k << "value\");\n";
|
||||
}
|
||||
target << I << " scope.assignVariable(scope.resolveKeyword(\"" << k << "name\"), val, scope.resolveKeyword(\"" << k << "scope\"));\n";
|
||||
target << I << "}\n";
|
||||
break;
|
||||
}
|
||||
|
||||
case NodeKind::IF: {
|
||||
std::string k = id("if_");
|
||||
target << I << "{\n";
|
||||
target << I << " bool cond;\n";
|
||||
if (n->cond.mode == CondMode::EXPR) {
|
||||
target << I << " scope.keywords[\"" << k << "expr\"] = " << cstr(n->cond.expr) << ";\n";
|
||||
target << I << " cond = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).boolean;\n";
|
||||
} else {
|
||||
target << I << " scope.keywords[\"" << k << "value1\"] = " << cstr(n->cond.value1) << ";\n";
|
||||
target << I << " scope.keywords[\"" << k << "value2\"] = " << cstr(n->cond.value2) << ";\n";
|
||||
target << I << " int rc = scope.resolveKeyword(\"" << k << "value1\").compare(scope.resolveKeyword(\"" << k << "value2\"));\n";
|
||||
target << I << " cond = (" << staticTypeOp(n->cond.type, "rc") << ");\n";
|
||||
}
|
||||
target << I << " if (cond) {\n";
|
||||
emitBody(n->thenBody, indent + 2, target);
|
||||
if (n->hasElse) {
|
||||
target << I << " } else {\n";
|
||||
emitBody(n->elseBody, indent + 2, target);
|
||||
}
|
||||
target << I << " }\n";
|
||||
target << I << "}\n";
|
||||
break;
|
||||
}
|
||||
|
||||
case NodeKind::FOR: {
|
||||
std::string k = id("for_");
|
||||
target << I << "{\n";
|
||||
target << I << " scope.keywords[\"" << k << "start\"] = " << cstr(n->forHasStart ? n->forStart : std::string("0")) << ";\n";
|
||||
target << I << " scope.keywords[\"" << k << "end\"] = " << cstr(n->forEnd) << ";\n";
|
||||
target << I << " scope.keywords[\"" << k << "step\"] = " << cstr(n->forStep) << ";\n";
|
||||
target << I << " double ix = scope.resolveKeyword(\"" << k << "start\").asDouble();\n";
|
||||
if (n->forHasName) {
|
||||
target << I << " scope.keywords[\"" << k << "name\"] = " << cstr(n->forName) << ";\n";
|
||||
target << I << " scope.keywords[\"" << k << "scope\"] = " << cstr(n->forScope) << ";\n";
|
||||
}
|
||||
target << I << " for (; ix <= scope.resolveKeyword(\"" << k << "end\").asDouble(); ix += scope.resolveKeyword(\"" << k << "step\").asDouble()) {\n";
|
||||
if (n->forHasName) {
|
||||
target << I << " coreutils::MString nameSel = scope.resolveKeyword(\"" << k << "name\");\n";
|
||||
target << I << " coreutils::MString scopeSel = scope.resolveKeyword(\"" << k << "scope\");\n";
|
||||
target << I << " if ((scopeSel == \"\") || (scopeSel == \"global\")) global.variables[nameSel] = ix;\n";
|
||||
target << I << " else if (scopeSel == \"local\") scope.local->variables[nameSel] = ix;\n";
|
||||
target << I << " else if (scopeSel == \"parent\") scope.parent->local->variables[nameSel] = ix;\n";
|
||||
target << I << " else throw coreutils::Exception(\"scope value is not valid.\");\n";
|
||||
}
|
||||
emitBody(n->body, indent + 2, target);
|
||||
target << I << " }\n";
|
||||
target << I << "}\n";
|
||||
break;
|
||||
}
|
||||
|
||||
case NodeKind::WHILE: {
|
||||
std::string k = id("while_");
|
||||
target << I << "{\n";
|
||||
target << I << " bool cond;\n";
|
||||
if (n->cond.mode == CondMode::EXPR) {
|
||||
target << I << " scope.keywords[\"" << k << "expr\"] = " << cstr(n->cond.expr) << ";\n";
|
||||
target << I << " coreutils::MString exprSaved = scope.keywords[\"" << k << "expr\"];\n";
|
||||
target << I << " cond = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).boolean;\n";
|
||||
target << I << " while (cond) {\n";
|
||||
emitBody(n->body, indent + 2, target);
|
||||
target << I << " scope.keywords[\"" << k << "expr\"].reset();\n";
|
||||
target << I << " scope.keywords[\"" << k << "expr\"] = exprSaved;\n";
|
||||
target << I << " cond = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).boolean;\n";
|
||||
target << I << " }\n";
|
||||
} else {
|
||||
target << I << " scope.keywords[\"" << k << "value1\"] = " << cstr(n->cond.value1) << ";\n";
|
||||
target << I << " scope.keywords[\"" << k << "value2\"] = " << cstr(n->cond.value2) << ";\n";
|
||||
target << I << " int rc = scope.resolveKeyword(\"" << k << "value1\").compare(scope.resolveKeyword(\"" << k << "value2\"));\n";
|
||||
target << I << " cond = (" << staticTypeOp(n->cond.type, "rc") << ");\n";
|
||||
target << I << " while (cond) {\n";
|
||||
emitBody(n->body, indent + 2, target);
|
||||
target << I << " int rc2 = scope.resolveKeyword(\"" << k << "value1\").compare(scope.resolveKeyword(\"" << k << "value2\"));\n";
|
||||
target << I << " cond = (" << staticTypeOp(n->cond.type, "rc2") << ");\n";
|
||||
target << I << " }\n";
|
||||
}
|
||||
target << I << "}\n";
|
||||
break;
|
||||
}
|
||||
|
||||
case NodeKind::FALLBACK: {
|
||||
target << I << "{ coreutils::ZString span(" << zstr(n->rawSpan) << "); scope.interpretSpan(span, out); }\n";
|
||||
break;
|
||||
}
|
||||
|
||||
case NodeKind::CONTAINER_SLOT: {
|
||||
// Reuses the interpreter's own <container> scope-walking logic
|
||||
// verbatim (see Tag::renderContainer) rather than re-deriving
|
||||
// it - this is exactly what the runtime's own <container>
|
||||
// dispatch does when it's reached via interpretSpan, just
|
||||
// without the text-scanning step to get there.
|
||||
target << I << "scope.renderContainer(out);\n";
|
||||
break;
|
||||
}
|
||||
|
||||
case NodeKind::TAGDEF: {
|
||||
// Codegen can still fail for a node that parsed successfully -
|
||||
// e.g. an <if>/<while> whose type= isn't one of eq/ne/lt/le/gt/ge
|
||||
// (staticTypeOp's own check - real legacy content occasionally
|
||||
// has one of these sitting in a branch that's never actually
|
||||
// reached at runtime either, so there's nothing to "correctly"
|
||||
// compile). Parsing this definition's body already succeeded
|
||||
// (see parseTagDef's own try/catch for that stage) or this node
|
||||
// wouldn't exist as TAGDEF at all - so mirror that same
|
||||
// graceful-degradation approach here for the emit stage: try
|
||||
// building the compiled function into a throwaway stream first,
|
||||
// and only splice it into tagDefFuncs (and register the
|
||||
// compiledTags fast path) if that fully succeeds. A failure
|
||||
// here just means this one definition stays interpreted,
|
||||
// unchanged - zero risk to the rest of the file.
|
||||
std::string funcName = "jetc_tagdef_" + id("");
|
||||
std::ostringstream trial;
|
||||
bool compiledOk = true;
|
||||
try {
|
||||
trial << "static void " << funcName << "(jet::Tag &scope, coreutils::MString &out) {\n";
|
||||
emitBody(n->tagDefBody, 1, trial);
|
||||
trial << "}\n\n";
|
||||
} catch (const std::exception &) {
|
||||
compiledOk = false;
|
||||
}
|
||||
|
||||
// Emitted in place, at this TAGDEF's original position in
|
||||
// program flow - matches exactly what FALLBACK would have
|
||||
// emitted for this same <tag name="X">...</tag> span, so
|
||||
// global.tags["x"] still gets populated as before (needed as a
|
||||
// correctness fallback: any invocation this compiler doesn't
|
||||
// itself recognize - e.g. reached through content this pass
|
||||
// never compiled - still resolves it exactly as it always has).
|
||||
target << I << "{ coreutils::ZString span(" << zstr(n->rawSpan) << "); scope.interpretSpan(span, out); }\n";
|
||||
if (compiledOk) {
|
||||
// The registration into compiledTags right after is the only
|
||||
// new behavior beyond the raw registration above - a pure
|
||||
// additive fast path __dotag checks first (see __dotag.cpp);
|
||||
// a miss there falls through to the now-unchanged interpreted
|
||||
// path, which is exactly what happens when compiledOk is
|
||||
// false here too.
|
||||
tagDefFuncs << trial.str();
|
||||
target << I << "global.compiledTags[coreutils::MString(" << cstr(n->tagDefName) << ")] = &" << funcName << ";\n";
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::string Codegen::generate(const std::vector<NodePtr> &top, const std::string &sourceFileComment,
|
||||
bool sharedMode, const std::string &entrySymbol,
|
||||
const std::vector<ApiRoute> &apiRoutes, const std::string &apiSymbol) {
|
||||
out.str("");
|
||||
out.clear();
|
||||
tagDefFuncs.str("");
|
||||
tagDefFuncs.clear();
|
||||
|
||||
out << "// " << sourceFileComment << "\n";
|
||||
out << "// Generated by jetc - DO NOT EDIT BY HAND.\n";
|
||||
out << "#include \"Global.h\"\n";
|
||||
out << "#include \"Tag.h\"\n";
|
||||
out << "#include \"Operand.h\"\n";
|
||||
out << "#include \"ZString.h\"\n";
|
||||
out << "#include \"MString.h\"\n";
|
||||
out << "#include \"Exception.h\"\n";
|
||||
out << "#include <iostream>\n\n";
|
||||
|
||||
// The entry function's own text is built into a separate stream so
|
||||
// tagDefFuncs - populated as a SIDE EFFECT of the emitBody() call
|
||||
// below, since TAGDEF nodes append to it as they're encountered -
|
||||
// can be spliced in ahead of it. A compiled tag-definition function
|
||||
// never needs to be forward-declared for anything defined before it
|
||||
// in program order (nothing upstream calls it directly - see
|
||||
// __dotag.cpp's runtime lookup instead), so this ordering is purely
|
||||
// for readability, not a correctness requirement.
|
||||
std::ostringstream body;
|
||||
|
||||
if (sharedMode) {
|
||||
if (!apiRoutes.empty()) {
|
||||
// A plain C struct, not any CoreUtils/JetCore type - this is the
|
||||
// one piece of the plugin ABI a host loader needs to know about
|
||||
// independent of the rest of this same-ABI C++ boundary.
|
||||
body << "struct JetApiRoute { const char *method; const char *path; };\n";
|
||||
body << "extern \"C\" const JetApiRoute *" << apiSymbol << "(int *count) {\n";
|
||||
body << " static const JetApiRoute routes[] = {\n";
|
||||
for (auto &r : apiRoutes)
|
||||
body << " { " << cstr(r.method) << ", " << cstr(r.path) << " },\n";
|
||||
body << " };\n";
|
||||
body << " *count = " << apiRoutes.size() << ";\n";
|
||||
body << " return routes;\n";
|
||||
body << "}\n\n";
|
||||
}
|
||||
body << "extern \"C\" void " << entrySymbol << "(jet::Global &global, coreutils::MString &out) {\n";
|
||||
body << " coreutils::ZString jetc_empty(\"\");\n";
|
||||
body << " coreutils::MString jetc_scopeOut;\n";
|
||||
body << " jet::Tag scope(jetc_empty, jetc_scopeOut, global, NULL, NULL);\n";
|
||||
emitBody(top, 1, body);
|
||||
body << "}\n";
|
||||
return out.str() + tagDefFuncs.str() + body.str();
|
||||
}
|
||||
|
||||
body << "static void jetc_render(jet::Global &global, coreutils::MString &out) {\n";
|
||||
body << " coreutils::ZString jetc_empty(\"\");\n";
|
||||
body << " coreutils::MString jetc_scopeOut;\n";
|
||||
body << " jet::Tag scope(jetc_empty, jetc_scopeOut, global, NULL, NULL);\n";
|
||||
emitBody(top, 1, body);
|
||||
body << "}\n\n";
|
||||
body << "int main(int argc, char **argv, char **envp) {\n";
|
||||
body << " jet::Global global(envp);\n";
|
||||
body << " coreutils::MString out;\n";
|
||||
body << " try {\n";
|
||||
body << " jetc_render(global, out);\n";
|
||||
body << " global.outputHeaders();\n";
|
||||
body << " std::cout << out;\n";
|
||||
body << " } catch(coreutils::Exception e) {\n";
|
||||
body << " std::cout << out;\n";
|
||||
body << " std::cout << \"\\n----- Error: \" << e.text << std::endl;\n";
|
||||
body << " return 1;\n";
|
||||
body << " }\n";
|
||||
body << " return 0;\n";
|
||||
body << "}\n";
|
||||
return out.str() + tagDefFuncs.str() + body.str();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
#ifndef __JetCodegen_h__
|
||||
#define __JetCodegen_h__
|
||||
|
||||
#include "JetAST.h"
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace jetc {
|
||||
|
||||
// One `#api METHOD /path` directive from the top of the source template
|
||||
// (see jetc.cpp) - a compile-time-known route this template wants to
|
||||
// serve once loaded as a .jtc. Purely descriptive data handed to Codegen;
|
||||
// jetc itself never interprets the method/path beyond storing them.
|
||||
struct ApiRoute {
|
||||
std::string method;
|
||||
std::string path;
|
||||
};
|
||||
|
||||
// Emits a standalone .cpp translation unit that renders a compiled JET
|
||||
// template. The static tag/text structure becomes real C++ control flow;
|
||||
// anything genuinely dynamic (variable values, expr/value comparisons,
|
||||
// loop bounds) still calls into the existing JetCore/CoreUtils runtime
|
||||
// (Tag::getVariable/resolveKeyword/assignVariable, jet::Operand) exactly
|
||||
// as the interpreter does - compiling doesn't try to eliminate that, only
|
||||
// the repeated re-parsing of the template's own structure.
|
||||
class Codegen {
|
||||
public:
|
||||
// sharedMode == false (default): emits a static jetc_render() plus a
|
||||
// main() that runs it once, catches coreutils::Exception, and writes
|
||||
// the result to stdout - the existing CGI-style standalone program.
|
||||
// apiRoutes/apiSymbol are ignored in this mode (there's no host to
|
||||
// dlsym them).
|
||||
//
|
||||
// sharedMode == true: emits no main() at all. Instead the render
|
||||
// logic is exported as `extern "C" void <entrySymbol>(jet::Global
|
||||
// &global, coreutils::MString &out)`, meant to be built into a .jtc
|
||||
// (see build-shared.sh) and dlsym()'d by a long-running host server -
|
||||
// one call renders one request into the caller-owned `out`, using
|
||||
// whatever Global the host passes in (its lifecycle, cgi/session
|
||||
// setup etc. is entirely the host's business, not this module's).
|
||||
// extern "C" only affects name mangling here, not the parameter
|
||||
// types - both sides are compiled from the same CoreUtils/JetCore
|
||||
// headers with the same toolchain, so passing C++ class types (and
|
||||
// letting coreutils::Exception propagate to the caller) across the
|
||||
// dlopen() boundary is safe; this is a same-ABI plugin boundary, not
|
||||
// a foreign C ABI one. entrySymbol should be unique per compiled
|
||||
// template (see jetc.cpp) so multiple .jtc's can coexist even if a
|
||||
// host ever dlopen()s them RTLD_GLOBAL instead of keeping separate
|
||||
// handles.
|
||||
//
|
||||
// If apiRoutes is non-empty, sharedMode also emits a second exported
|
||||
// function `extern "C" const JetApiRoute *<apiSymbol>(int *count)`
|
||||
// returning a static array describing every `#api` directive the
|
||||
// source declared - a host's directory watcher/loader dlsym()'s this
|
||||
// (by the same filename-derived naming convention as entrySymbol) to
|
||||
// learn what to register, without any separate manifest file that
|
||||
// could drift out of sync with the render function it describes.
|
||||
std::string generate(const std::vector<NodePtr> &top, const std::string &sourceFileComment,
|
||||
bool sharedMode = false, const std::string &entrySymbol = "jetc_render",
|
||||
const std::vector<ApiRoute> &apiRoutes = {}, const std::string &apiSymbol = "jetc_api");
|
||||
|
||||
private:
|
||||
std::ostringstream out;
|
||||
|
||||
// Free functions generated for compiled <tag name="X"> definitions
|
||||
// (see the TAGDEF case in emitNode) accumulate here, in the order
|
||||
// encountered, and are spliced into the final output ahead of the
|
||||
// entry function (see generate()) - C++ doesn't care about
|
||||
// definition order within one translation unit as long as nothing
|
||||
// outside of it needs a forward declaration, but keeping them
|
||||
// grouped together ahead of the entry point makes the generated
|
||||
// file easier to read/debug than interleaving them positionally.
|
||||
std::ostringstream tagDefFuncs;
|
||||
|
||||
size_t nextId = 0;
|
||||
std::string id(const std::string &prefix) { return prefix + std::to_string(nextId++) + "_"; }
|
||||
|
||||
// target is the stream this node's statements are written to - `out`
|
||||
// for everything at the top level or nested inside ordinary control
|
||||
// flow (IF/FOR/WHILE bodies stay in the same stream as their
|
||||
// enclosing scope), but a TAGDEF's own body is rendered into a
|
||||
// fresh stream to become a separate generated function (see
|
||||
// emitNode's TAGDEF case) rather than being inlined in place.
|
||||
void emitBody(const std::vector<NodePtr> &nodes, int indent, std::ostringstream &target);
|
||||
void emitNode(const NodePtr &n, int indent, std::ostringstream &target);
|
||||
static std::string ind(int indent);
|
||||
static std::string cstr(const std::string &raw); // C++ string-literal escape
|
||||
static std::string zstr(const std::string &raw); // same, as a sized ZString if it holds a NUL
|
||||
static const char *staticTypeOp(const std::string &type, const char *rcVar);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,322 @@
|
||||
#include "JetLint.h"
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
|
||||
// See JetLint.h. This is a plain text scan of the page source rather than a
|
||||
// use of jetc's Parser: the parser keeps no line numbers, compiles some
|
||||
// content into fallback spans, and stops at the first error, while a lint
|
||||
// run over a whole site has to report every <sql> in every file.
|
||||
|
||||
namespace jetc {
|
||||
|
||||
namespace {
|
||||
|
||||
bool startsWithNoCase(const std::string &s, size_t pos, const char *word) {
|
||||
for (size_t i = 0; word[i]; ++i)
|
||||
if (pos + i >= s.size() || std::tolower((unsigned char)s[pos + i]) != word[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isTagEndChar(char c) {
|
||||
return c == '>' || c == '/' || std::isspace((unsigned char)c);
|
||||
}
|
||||
|
||||
// "<name" at pos, followed by whitespace, '>' or '/'.
|
||||
bool isOpenTag(const std::string &s, size_t pos, const std::string &name) {
|
||||
if (s[pos] != '<' || !startsWithNoCase(s, pos + 1, name.c_str())) return false;
|
||||
size_t after = pos + 1 + name.size();
|
||||
return after < s.size() && isTagEndChar(s[after]);
|
||||
}
|
||||
|
||||
// "</name" + optional whitespace + ">" at pos. Returns the position
|
||||
// after the '>', or npos.
|
||||
size_t closeTagEnd(const std::string &s, size_t pos, const std::string &name) {
|
||||
if (s.compare(pos, 2, "</") != 0 || !startsWithNoCase(s, pos + 2, name.c_str())) return std::string::npos;
|
||||
size_t i = pos + 2 + name.size();
|
||||
while (i < s.size() && std::isspace((unsigned char)s[i])) ++i;
|
||||
return (i < s.size() && s[i] == '>') ? i + 1 : std::string::npos;
|
||||
}
|
||||
|
||||
// pos is at '<'. Returns the position of the '>' ending the opening
|
||||
// tag, skipping quoted attribute values, or npos.
|
||||
size_t openTagEnd(const std::string &s, size_t pos) {
|
||||
char quote = 0;
|
||||
for (size_t i = pos + 1; i < s.size(); ++i) {
|
||||
char c = s[i];
|
||||
if (quote) { if (c == quote) quote = 0; }
|
||||
else if (c == '"' || c == '\'') quote = c;
|
||||
else if (c == '>') return i;
|
||||
}
|
||||
return std::string::npos;
|
||||
}
|
||||
|
||||
// pos is at "$[" or "#[". Returns the position after the matching
|
||||
// ']' (nested references included), or npos.
|
||||
size_t refEnd(const std::string &s, size_t pos) {
|
||||
int depth = 0;
|
||||
for (size_t i = pos; i < s.size(); ++i) {
|
||||
if ((s[i] == '$' || s[i] == '#') && i + 1 < s.size() && s[i + 1] == '[') { ++depth; ++i; }
|
||||
else if (s[i] == ']' && --depth == 0) return i + 1;
|
||||
}
|
||||
return std::string::npos;
|
||||
}
|
||||
|
||||
// What a reference reads from, from its type designator (see
|
||||
// Tag::getVariable). "row" is a column of an earlier query.
|
||||
std::string refKind(const std::string &ref) {
|
||||
if (ref[0] == '#') return "local";
|
||||
char d = ref.size() > 2 ? ref[2] : 0;
|
||||
switch (d) {
|
||||
case ':': return "cgi";
|
||||
case '@': return "session";
|
||||
case '&': return "env";
|
||||
case '%': return "keyword";
|
||||
case '!': return "global";
|
||||
case '.': case '?': case '#': return "row";
|
||||
}
|
||||
// $[session.column] - a dot outside any nested reference.
|
||||
int depth = 0;
|
||||
for (size_t i = 2; i + 1 < ref.size(); ++i) {
|
||||
if (ref[i] == '[') ++depth;
|
||||
else if (ref[i] == ']') --depth;
|
||||
else if (ref[i] == '.' && depth == 0) return "row";
|
||||
}
|
||||
return "global";
|
||||
}
|
||||
|
||||
int lineAt(const std::string &s, size_t pos) {
|
||||
return 1 + (int)std::count(s.begin(), s.begin() + pos, '\n');
|
||||
}
|
||||
|
||||
// Tags inside a <sql> whose attributes never become statement text:
|
||||
// <bind> passes its value safely, and the rest only decide what the
|
||||
// body renders.
|
||||
const char *const attributeOnlyTags[] = {
|
||||
"bind", "if", "else", "ifrow", "while", "whilerow", "until", "for", "set",
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
void lintSqlText(const std::string &file, const std::string &s, bool strict,
|
||||
const std::vector<std::string> &wrappers,
|
||||
std::vector<LintFinding> &findings, LintStats &stats) {
|
||||
std::vector<std::string> names{"sql"};
|
||||
names.insert(names.end(), wrappers.begin(), wrappers.end());
|
||||
bool counted = false;
|
||||
size_t pos = 0;
|
||||
while ((pos = s.find('<', pos)) != std::string::npos) {
|
||||
std::string name;
|
||||
for (const auto &n : names)
|
||||
if (isOpenTag(s, pos, n)) { name = n; break; }
|
||||
if (name.empty()) { ++pos; continue; }
|
||||
if (!counted) { ++stats.files; counted = true; }
|
||||
++stats.sqlBlocks;
|
||||
size_t tagStart = pos;
|
||||
size_t gt = openTagEnd(s, pos);
|
||||
if (gt == std::string::npos) break;
|
||||
pos = gt + 1;
|
||||
if (s[gt - 1] == '/') continue; // <sql ... /> has no statement
|
||||
|
||||
LintFinding finding{file, lineAt(s, tagStart), name, {}};
|
||||
int depth = 1;
|
||||
size_t i = pos;
|
||||
while (i < s.size()) {
|
||||
size_t end;
|
||||
if (s[i] == '<') {
|
||||
if ((end = closeTagEnd(s, i, name)) != std::string::npos) {
|
||||
i = end;
|
||||
if (--depth == 0) break;
|
||||
continue;
|
||||
}
|
||||
if (isOpenTag(s, i, name)) {
|
||||
// A nested block of the same tag is its own block; it is
|
||||
// reported when the outer scan reaches it.
|
||||
++depth;
|
||||
size_t e = openTagEnd(s, i);
|
||||
i = (e == std::string::npos) ? s.size() : e + 1;
|
||||
continue;
|
||||
}
|
||||
if (isOpenTag(s, i, "comment")) {
|
||||
size_t c = s.find("</comment>", i);
|
||||
i = (c == std::string::npos) ? s.size() : c + 10;
|
||||
continue;
|
||||
}
|
||||
bool skipped = false;
|
||||
for (const char *tag : attributeOnlyTags)
|
||||
if (isOpenTag(s, i, tag)) {
|
||||
size_t e = openTagEnd(s, i);
|
||||
i = (e == std::string::npos) ? s.size() : e + 1;
|
||||
skipped = true;
|
||||
break;
|
||||
}
|
||||
if (skipped) continue;
|
||||
} else if (s.compare(i, 2, "|>") == 0) {
|
||||
// |> ... <| is never parsed, so nothing in it is a reference.
|
||||
size_t c = s.find("<|", i + 2);
|
||||
i = (c == std::string::npos) ? s.size() : c + 2;
|
||||
continue;
|
||||
} else if ((s[i] == '$' || s[i] == '#') && i + 1 < s.size() && s[i + 1] == '[') {
|
||||
end = refEnd(s, i);
|
||||
if (end == std::string::npos) end = s.size();
|
||||
LintRef ref{s.substr(i, end - i), ""};
|
||||
ref.kind = refKind(ref.text);
|
||||
i = end;
|
||||
if (ref.kind == "row" && !strict) continue;
|
||||
bool seen = false;
|
||||
for (auto &r : finding.refs) seen = seen || r.text == ref.text;
|
||||
if (!seen) finding.refs.push_back(ref);
|
||||
continue;
|
||||
}
|
||||
++i;
|
||||
}
|
||||
if (!finding.refs.empty()) {
|
||||
++stats.flaggedBlocks;
|
||||
findings.push_back(finding);
|
||||
}
|
||||
// Carry on from the end of this <sql>'s opening tag, not its body,
|
||||
// so a nested <sql> is still counted and checked.
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
bool fileMentions(const std::string &text, const std::vector<std::string> &names) {
|
||||
for (size_t p = 0; (p = text.find('<', p)) != std::string::npos; ++p)
|
||||
for (const auto &n : names)
|
||||
if (isOpenTag(text, p, n)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
bool readFile(const std::string &path, std::string &text) {
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
if (!in) return false;
|
||||
std::ostringstream ss;
|
||||
ss << in.rdbuf();
|
||||
text = ss.str();
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void findSqlWrappers(const std::string &s, std::vector<std::string> &wrappers) {
|
||||
for (size_t pos = 0; (pos = s.find('<', pos)) != std::string::npos; ++pos) {
|
||||
if (!isOpenTag(s, pos, "tag")) continue;
|
||||
size_t gt = openTagEnd(s, pos);
|
||||
if (gt == std::string::npos) return;
|
||||
std::string open = s.substr(pos, gt - pos);
|
||||
// name="X" (or name='X')
|
||||
std::string lower = open;
|
||||
for (auto &c : lower) c = (char)std::tolower((unsigned char)c);
|
||||
size_t n = lower.find("name=");
|
||||
if (n == std::string::npos || n + 5 >= open.size()) continue;
|
||||
char q = open[n + 5];
|
||||
if (q != '"' && q != '\'') continue;
|
||||
size_t e = open.find(q, n + 6);
|
||||
if (e == std::string::npos) continue;
|
||||
std::string name = open.substr(n + 6, e - n - 6);
|
||||
// Tag names match without regard to case (isOpenTag lowercases).
|
||||
for (auto &c : name) c = (char)std::tolower((unsigned char)c);
|
||||
size_t close = std::string::npos;
|
||||
for (size_t c = gt; (c = s.find("</", c)) != std::string::npos; ++c)
|
||||
if (closeTagEnd(s, c, "tag") != std::string::npos) { close = c; break; }
|
||||
std::string body = s.substr(gt + 1, (close == std::string::npos ? s.size() : close) - gt - 1);
|
||||
// An <sql> in the definition whose statement is the caller's content.
|
||||
for (size_t p = 0; (p = body.find('<', p)) != std::string::npos; ++p) {
|
||||
if (!isOpenTag(body, p, "sql")) continue;
|
||||
size_t bgt = openTagEnd(body, p);
|
||||
if (bgt == std::string::npos) break;
|
||||
size_t end = std::string::npos;
|
||||
for (size_t c = bgt; (c = body.find("</", c)) != std::string::npos; ++c)
|
||||
if (closeTagEnd(body, c, "sql") != std::string::npos) { end = c; break; }
|
||||
std::string stmt = body.substr(bgt + 1, (end == std::string::npos ? body.size() : end) - bgt - 1);
|
||||
bool hasContainer = false;
|
||||
for (size_t c = 0; (c = stmt.find('<', c)) != std::string::npos; ++c)
|
||||
hasContainer = hasContainer || isOpenTag(stmt, c, "container");
|
||||
if (hasContainer && !name.empty() &&
|
||||
std::find(wrappers.begin(), wrappers.end(), name) == wrappers.end()) {
|
||||
wrappers.push_back(name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int lintSql(const std::vector<std::string> &paths, bool strict, std::ostream &out, std::ostream &err) {
|
||||
namespace fs = std::filesystem;
|
||||
std::vector<std::string> files;
|
||||
bool error = false;
|
||||
for (const auto &p : paths) {
|
||||
std::error_code ec;
|
||||
if (fs::is_directory(p, ec)) {
|
||||
std::vector<std::string> found;
|
||||
for (auto it = fs::recursive_directory_iterator(p, fs::directory_options::skip_permission_denied, ec);
|
||||
it != fs::recursive_directory_iterator(); it.increment(ec)) {
|
||||
if (ec) break;
|
||||
std::string name = it->path().filename().string();
|
||||
if (it->is_directory(ec) && !name.empty() && name[0] == '.') { it.disable_recursion_pending(); continue; }
|
||||
if (it->is_regular_file(ec)) found.push_back(it->path().string());
|
||||
}
|
||||
std::sort(found.begin(), found.end());
|
||||
files.insert(files.end(), found.begin(), found.end());
|
||||
} else if (fs::is_regular_file(p, ec)) {
|
||||
files.push_back(p);
|
||||
} else {
|
||||
err << "jetc: cannot open " << p << std::endl;
|
||||
error = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Two passes: a custom tag defined anywhere in the scanned files as
|
||||
// <sql ...><container></sql> takes its statement from the caller's
|
||||
// content, so each use of it is checked like an <sql>.
|
||||
std::vector<std::string> texts(files.size());
|
||||
std::vector<bool> readOk(files.size(), false);
|
||||
std::vector<std::string> wrappers;
|
||||
for (size_t i = 0; i < files.size(); ++i) {
|
||||
if (!readFile(files[i], texts[i])) { err << "jetc: cannot read " << files[i] << std::endl; error = true; continue; }
|
||||
readOk[i] = true;
|
||||
findSqlWrappers(texts[i], wrappers);
|
||||
}
|
||||
std::vector<std::string> names{"sql"};
|
||||
names.insert(names.end(), wrappers.begin(), wrappers.end());
|
||||
|
||||
std::vector<LintFinding> findings;
|
||||
LintStats stats;
|
||||
for (size_t i = 0; i < files.size(); ++i) {
|
||||
if (!readOk[i] || !fileMentions(texts[i], names)) continue;
|
||||
lintSqlText(files[i], texts[i], strict, wrappers, findings, stats);
|
||||
}
|
||||
|
||||
std::map<std::string, int> byKind;
|
||||
std::map<std::string, bool> flaggedFiles;
|
||||
for (const auto &f : findings) {
|
||||
flaggedFiles[f.file] = true;
|
||||
out << f.file << ":" << f.line << ": <" << f.tag << ">"
|
||||
<< (f.tag == "sql" ? "" : " (wraps sql)") << " pastes ";
|
||||
for (size_t i = 0; i < f.refs.size(); ++i) {
|
||||
out << (i ? ", " : "") << f.refs[i].text << " (" << f.refs[i].kind << ")";
|
||||
++byKind[f.refs[i].kind];
|
||||
}
|
||||
out << "\n";
|
||||
}
|
||||
out << "lint-sql: " << stats.flaggedBlocks << " of " << stats.sqlBlocks
|
||||
<< " <sql> blocks" << (wrappers.empty() ? "" : " (and uses of tags that wrap <sql>)")
|
||||
<< " paste values into the statement, in " << flaggedFiles.size()
|
||||
<< " of " << stats.files << " files";
|
||||
if (!byKind.empty()) {
|
||||
out << " (";
|
||||
bool first = true;
|
||||
for (auto &[kind, n] : byKind) { out << (first ? "" : ", ") << kind << " " << n; first = false; }
|
||||
out << ")";
|
||||
}
|
||||
out << std::endl;
|
||||
|
||||
if (error) return 2;
|
||||
return findings.empty() ? 0 : 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#ifndef __JetLint_h__
|
||||
#define __JetLint_h__
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <ostream>
|
||||
|
||||
// jetc --lint-sql: phase 2 of docs/design-sql-bound-parameters.md.
|
||||
//
|
||||
// Lists every <sql> whose body pastes a variable into the statement text
|
||||
// ($[...] or #[...]) instead of passing it with <bind>. These are the
|
||||
// queries to migrate. A value from a row of an earlier query
|
||||
// ($[.column], $[session.column], $[?N], $[#]) is not reported, as the
|
||||
// design doc specifies, unless strict is set.
|
||||
|
||||
namespace jetc {
|
||||
|
||||
struct LintRef {
|
||||
std::string text; // the reference as written, e.g. "$[:email]"
|
||||
std::string kind; // cgi, global, local, session, env, keyword, row, ...
|
||||
};
|
||||
|
||||
struct LintFinding {
|
||||
std::string file;
|
||||
int line; // line of the <sql tag
|
||||
std::string tag; // "sql", or a custom tag that wraps <sql><container></sql>
|
||||
std::vector<LintRef> refs;
|
||||
};
|
||||
|
||||
struct LintStats {
|
||||
int files = 0; // files that contain at least one <sql>
|
||||
int sqlBlocks = 0;
|
||||
int flaggedBlocks = 0;
|
||||
};
|
||||
|
||||
// Scans one file's text. Appends to findings and stats.
|
||||
// wrappers: custom tag names whose uses count as <sql> (see
|
||||
// findSqlWrappers).
|
||||
void lintSqlText(const std::string &file, const std::string &text, bool strict,
|
||||
const std::vector<std::string> &wrappers,
|
||||
std::vector<LintFinding> &findings, LintStats &stats);
|
||||
|
||||
// Adds to wrappers each custom tag defined in text (<tag name="X">)
|
||||
// whose definition runs the caller's content as its statement:
|
||||
// <sql ...><container></sql>.
|
||||
void findSqlWrappers(const std::string &text, std::vector<std::string> &wrappers);
|
||||
|
||||
// Scans files and directories (recursively; every regular file,
|
||||
// whatever its extension). Tag definitions are collected from all of
|
||||
// them first, so a wrapper defined in one file is found in all.
|
||||
// Prints one line per finding and a summary. Returns 0 when nothing is found, 1 when something is,
|
||||
// 2 on an error (unreadable path).
|
||||
int lintSql(const std::vector<std::string> &paths, bool strict, std::ostream &out, std::ostream &err);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,622 @@
|
||||
#include "JetParser.h"
|
||||
#include <cctype>
|
||||
#include <stdexcept>
|
||||
#include <set>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <cstdio>
|
||||
|
||||
namespace jetc {
|
||||
|
||||
bool Parser::starts(const std::string &lit) const {
|
||||
return s.compare(pos, lit.size(), lit) == 0;
|
||||
}
|
||||
|
||||
bool Parser::isNameChar(char c) {
|
||||
return std::isalnum((unsigned char)c) || c == '-' || c == '_';
|
||||
}
|
||||
|
||||
void Parser::skipWs() {
|
||||
while (!eof() && std::isspace((unsigned char)s[pos])) pos++;
|
||||
}
|
||||
|
||||
std::string Parser::readName() {
|
||||
size_t start = pos;
|
||||
while (!eof() && isNameChar(s[pos])) pos++;
|
||||
return s.substr(start, pos - start);
|
||||
}
|
||||
|
||||
std::string Parser::peekTagName(size_t at) const {
|
||||
size_t p = at + 1;
|
||||
size_t start = p;
|
||||
while (p < s.size() && isNameChar(s[p])) p++;
|
||||
return s.substr(start, p - start);
|
||||
}
|
||||
|
||||
namespace {
|
||||
// jet-1.4 (the language this parser also has to accept, alongside
|
||||
// real 2.0 source) was fully case-insensitive on tag names - the
|
||||
// production source mixes case freely, even within one tag's own
|
||||
// body (e.g. <SET ...> and <set ...> side by side). Tag names are
|
||||
// matched case-insensitively throughout this parser for that
|
||||
// reason; nothing else (attribute values, text content) is
|
||||
// affected by this helper.
|
||||
bool ciEquals(const char *a, size_t alen, const std::string &b) {
|
||||
if (alen != b.size()) return false;
|
||||
for (size_t i = 0; i < alen; i++)
|
||||
if (std::tolower((unsigned char)a[i]) != std::tolower((unsigned char)b[i]))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool Parser::matchTagOpen(const std::string &name, size_t at) const {
|
||||
if (s.compare(at, 1, "<") != 0) return false;
|
||||
size_t p = at + 1;
|
||||
size_t nstart = p;
|
||||
while (p < s.size() && isNameChar(s[p])) p++;
|
||||
if (!ciEquals(s.data() + nstart, p - nstart, name)) return false;
|
||||
if (p >= s.size()) return false;
|
||||
char c = s[p];
|
||||
return c == ' ' || c == '>' || c == '/';
|
||||
}
|
||||
|
||||
bool Parser::matchTagClose(const std::string &name, size_t at) const {
|
||||
if (s.compare(at, 2, "</") != 0) return false;
|
||||
size_t p = at + 2;
|
||||
size_t nstart = p;
|
||||
while (p < s.size() && isNameChar(s[p])) p++;
|
||||
if (!ciEquals(s.data() + nstart, p - nstart, name)) return false;
|
||||
return p < s.size() && s[p] == '>';
|
||||
}
|
||||
|
||||
namespace {
|
||||
// jet-1.4's real parser knew which tags never take a body (its own
|
||||
// "void element" list) - kept here, ahead of skipOpenTag/
|
||||
// skipEmbeddedTag/parseFallback, since all of them need it.
|
||||
bool isVoidTag(const std::string &name) {
|
||||
static const std::set<std::string> voidTags = {
|
||||
// jet's own built-ins that never take a body. exclude is
|
||||
// NOT here - __exclude.cpp's own constructor requires a
|
||||
// real body (throws "exclude must have a container"
|
||||
// otherwise), it was previously miscategorized as void.
|
||||
"set", "include", "cookie", "header", "read", "write",
|
||||
"call", "system", "dump",
|
||||
// <bind> (see __bind.cpp) supplies one <sql> placeholder value
|
||||
// and never has a closing tag - without this a bare
|
||||
// <bind value="..."> outside a <sql> span would scan forward
|
||||
// for a "</bind>" that doesn't exist.
|
||||
"bind",
|
||||
// <container> (see parseContainerSlot/Tag::renderContainer) -
|
||||
// real content always writes it as a bare marker with no
|
||||
// separate closing tag, even when it carries its own
|
||||
// attributes (e.g. SESSIONCTL.tag's own
|
||||
// <CONTAINER EVAL="NO">) - without this it was previously only
|
||||
// reachable via the generic FALLBACK path (scanBody would
|
||||
// incorrectly scan forward for a "</container>" that never
|
||||
// exists, consuming unrelated following content).
|
||||
"container",
|
||||
// standard HTML5 void elements - real 1.4-era content (e.g.
|
||||
// SESSIONCTL.tag) writes these the classic HTML way too,
|
||||
// bare '>' and never a closing tag.
|
||||
"br", "img", "input", "hr", "meta", "link", "area", "base",
|
||||
"col", "embed", "source", "track", "wbr",
|
||||
// <else> is a marker inside an <if>/<while>/<until> body
|
||||
// (scanBody's own lookForElse handles it at the top level) -
|
||||
// it never has its own close tag, so when it shows up
|
||||
// embedded (inside a quoted attribute or another tag's
|
||||
// attribute region, same as <if> does in <linkbutton>) it
|
||||
// needs the same void treatment.
|
||||
"else"
|
||||
};
|
||||
std::string lower = name;
|
||||
for (char &c : lower) c = (char)std::tolower((unsigned char)c);
|
||||
return voidTags.count(lower) != 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Real 1.4 content nests real jet tags in two places a plain
|
||||
// quote/angle-bracket scanner can't handle on its own:
|
||||
// 1. Inside a quoted attribute value - SESSIONCTL.tag's <linkbutton>
|
||||
// has HREF="javascript: <IF VALUE1="..." VALUE2="" TYPE=NE> ...
|
||||
// </IF> ... " - the outer string and the embedded tag's own
|
||||
// attributes reuse the same quote character with no escaping.
|
||||
// 2. Inside another tag's OWN opening-tag attribute region, before
|
||||
// its closing '>' - linkbutton's <A ...> has a conditional
|
||||
// <if value1="#[CLASS]" value2="" type="ne">CLASS="#[CLASS]"</if>
|
||||
// sitting between its other attributes and its own '>' - the
|
||||
// literal '>' that ends the embedded <if ...>'s OWN opening tag
|
||||
// would otherwise be mistaken for <A>'s closing '>'.
|
||||
// skipEmbeddedTag() skips one such nested tag as a whole unit -
|
||||
// its own attributes (recursing through skipOpenTag, so an embedded
|
||||
// tag's embedded tag works too) and, if it isn't a void tag and wasn't
|
||||
// self-closed, its real body up through its own matching close tag
|
||||
// (via the same matchTagOpen/matchTagClose depth-tracking scanBody
|
||||
// uses at the top level). skipOpenTag's own attribute scan and
|
||||
// skipQuotedValue both call this for anything that looks like a
|
||||
// nested tag, instead of treating it as ordinary content.
|
||||
void Parser::skipEmbeddedTag(size_t &p) {
|
||||
size_t nameStart = p + 1;
|
||||
size_t nameEnd = nameStart;
|
||||
while (nameEnd < s.size() && isNameChar(s[nameEnd])) nameEnd++;
|
||||
std::string tagName = s.substr(nameStart, nameEnd - nameStart);
|
||||
bool selfClosing = skipOpenTag(p);
|
||||
if (!selfClosing && !isVoidTag(tagName)) {
|
||||
auto span = scanBody(p, tagName, false);
|
||||
p = span.first + 3 + tagName.size();
|
||||
}
|
||||
}
|
||||
|
||||
void Parser::skipQuotedValue(size_t &p) {
|
||||
p++; // opening '"'
|
||||
while (p < s.size()) {
|
||||
if (s[p] == '"') { p++; return; }
|
||||
if (s[p] == '\\' && p + 1 < s.size()) { p += 2; continue; }
|
||||
if (s[p] == '<' && p + 1 < s.size() && isNameChar(s[p + 1])) {
|
||||
skipEmbeddedTag(p);
|
||||
continue;
|
||||
}
|
||||
if (s[p] == '<' && s.compare(p, 2, "</") == 0) {
|
||||
p += 2;
|
||||
while (p < s.size() && isNameChar(s[p])) p++;
|
||||
if (p < s.size() && s[p] == '>') p++;
|
||||
continue;
|
||||
}
|
||||
p++;
|
||||
}
|
||||
}
|
||||
|
||||
// Advances p from '<' of "<comment" (any case - matchTagOpen already
|
||||
// confirmed the match before this is called) past the whole
|
||||
// <comment>...</comment> construct, including any nested <comment>
|
||||
// tags, counted the same case-insensitive way everything else in this
|
||||
// file matches tag names. Deliberately does NOT call skipOpenTag/
|
||||
// skipQuotedValue/skipEmbeddedTag or any other quote- or tag-aware
|
||||
// scanning on the body text - a comment containing an explanatory '"'
|
||||
// or '\"' (about the code itself, say) previously fell through to
|
||||
// parseFallback()'s generic path, which DOES apply those rules while
|
||||
// hunting for this same closing tag, and silently mislocated it
|
||||
// exactly like the already-documented JS-comment-corrupts-jetc bug
|
||||
// class, just triggered from inside a <comment> instead of a //
|
||||
// comment. This only ever advances past '<'/'>' boundaries it
|
||||
// recognizes as comment open/close - nothing inside can affect it.
|
||||
void Parser::skipCommentTag(size_t &p) {
|
||||
p += 8; // "<comment" (8 chars regardless of case)
|
||||
bool selfClosing = false;
|
||||
while (p < s.size() && s[p] != '>') {
|
||||
if (s[p] == '/' && p + 1 < s.size() && s[p + 1] == '>') selfClosing = true;
|
||||
p++;
|
||||
}
|
||||
if (p < s.size()) p++; // past '>'
|
||||
if (selfClosing) return;
|
||||
int depth = 1;
|
||||
while (p < s.size()) {
|
||||
if (matchTagOpen("comment", p)) {
|
||||
depth++;
|
||||
p++;
|
||||
continue;
|
||||
}
|
||||
if (matchTagClose("comment", p)) {
|
||||
p += 2; // "</"
|
||||
while (p < s.size() && isNameChar(s[p])) p++;
|
||||
if (p < s.size() && s[p] == '>') p++;
|
||||
depth--;
|
||||
if (depth == 0) return;
|
||||
continue;
|
||||
}
|
||||
p++;
|
||||
}
|
||||
}
|
||||
|
||||
bool Parser::skipOpenTag(size_t &p) {
|
||||
p++; // '<'
|
||||
while (p < s.size() && isNameChar(s[p])) p++;
|
||||
while (p < s.size()) {
|
||||
if (s[p] == '"') {
|
||||
skipQuotedValue(p);
|
||||
continue;
|
||||
}
|
||||
if (s.compare(p, 2, "/>") == 0) { p += 2; return true; }
|
||||
if (s[p] == '>') { p += 1; return false; }
|
||||
if (s[p] == '<' && p + 1 < s.size() && isNameChar(s[p + 1])) {
|
||||
skipEmbeddedTag(p);
|
||||
continue;
|
||||
}
|
||||
p++;
|
||||
}
|
||||
throw std::runtime_error("jetc: unterminated tag near end of input");
|
||||
}
|
||||
|
||||
std::map<std::string, std::string> Parser::parseAttrs(bool &hasContainer) {
|
||||
std::map<std::string, std::string> attrs;
|
||||
while (true) {
|
||||
skipWs();
|
||||
if (eof()) throw std::runtime_error("jetc: unterminated tag near end of input");
|
||||
if (starts("/>")) { pos += 2; hasContainer = false; break; }
|
||||
if (starts(">")) { pos += 1; hasContainer = true; break; }
|
||||
std::string aname = readName();
|
||||
if (aname.empty()) throw std::runtime_error("jetc: malformed attribute near offset " + std::to_string(pos));
|
||||
if (starts("=")) {
|
||||
pos += 1;
|
||||
std::string val;
|
||||
if (!eof() && s[pos] == '"') {
|
||||
pos++;
|
||||
while (!eof() && s[pos] != '"') {
|
||||
if (s[pos] == '\\' && pos + 1 < s.size()) { val += s[pos]; val += s[pos + 1]; pos += 2; continue; }
|
||||
val += s[pos++];
|
||||
}
|
||||
if (!eof()) pos++; // closing quote
|
||||
} else if (!eof() && s[pos] == '\'') {
|
||||
// Single-quoted value - real 1.4 content writes both
|
||||
// (SESSIONCTL.tag's own name='tmp_#[name]' alongside
|
||||
// ordinary name="..." elsewhere in the same file).
|
||||
pos++;
|
||||
while (!eof() && s[pos] != '\'') {
|
||||
if (s[pos] == '\\' && pos + 1 < s.size()) { val += s[pos]; val += s[pos + 1]; pos += 2; continue; }
|
||||
val += s[pos++];
|
||||
}
|
||||
if (!eof()) pos++; // closing quote
|
||||
} else {
|
||||
// Unquoted bareword value - real 1.4 content writes this
|
||||
// too (type=eq, format=tobrowser, TYPE=NE throughout
|
||||
// SESSIONCTL.tag) - the runtime interpreter's own
|
||||
// attribute scanning already tolerates it; jetc's own
|
||||
// parser previously didn't, since nothing had ever
|
||||
// recursively parsed a tag definition's own body deeply
|
||||
// enough to reach one before (see parseTagDef). Runs to
|
||||
// the next whitespace or the tag's own closing '>'/'/>' .
|
||||
while (!eof() && !std::isspace((unsigned char)s[pos]) && s[pos] != '>' &&
|
||||
!(s[pos] == '/' && pos + 1 < s.size() && s[pos + 1] == '>')) {
|
||||
val += s[pos++];
|
||||
}
|
||||
}
|
||||
attrs[aname] = val;
|
||||
}
|
||||
}
|
||||
return attrs;
|
||||
}
|
||||
|
||||
std::pair<size_t, size_t> Parser::scanBody(size_t bodyStart, const std::string &tagName, bool lookForElse) {
|
||||
size_t p = bodyStart;
|
||||
int depth = 1;
|
||||
size_t elsePos = std::string::npos;
|
||||
while (p < s.size()) {
|
||||
if (matchTagClose(tagName, p)) {
|
||||
depth--;
|
||||
if (depth == 0) return {p, elsePos};
|
||||
p += 3 + tagName.size();
|
||||
continue;
|
||||
}
|
||||
if (lookForElse && depth == 1 && elsePos == std::string::npos && s.compare(p, 6, "<else>") == 0) {
|
||||
elsePos = p;
|
||||
p += 6;
|
||||
continue;
|
||||
}
|
||||
if (matchTagOpen(tagName, p)) {
|
||||
bool selfClosing = skipOpenTag(p);
|
||||
if (!selfClosing) depth++;
|
||||
continue;
|
||||
}
|
||||
if (s[p] == '<') {
|
||||
if (s.compare(p, 2, "</") == 0) {
|
||||
size_t q = p + 2;
|
||||
while (q < s.size() && isNameChar(s[q])) q++;
|
||||
if (q < s.size() && s[q] == '>') q++;
|
||||
p = q;
|
||||
} else {
|
||||
skipOpenTag(p);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
p++;
|
||||
}
|
||||
throw std::runtime_error("jetc: unterminated <" + tagName + "> - no matching close tag found");
|
||||
}
|
||||
|
||||
std::vector<NodePtr> Parser::parseSub(size_t start, size_t end) {
|
||||
// Always topLevel=false - an <if>/<for>/<while> body is never the
|
||||
// file's true top level, regardless of what topLevel this Parser
|
||||
// itself was constructed with (see parseTagDef/isVoidTag's doc
|
||||
// comments - a <tag name="X"> found here stays FALLBACK, unchanged).
|
||||
Parser sub(s.substr(start, end - start), baseDir, includeDepth, false);
|
||||
return sub.parseNodes();
|
||||
}
|
||||
|
||||
std::vector<NodePtr> Parser::parseInclude() {
|
||||
pos += 8; // "<include"
|
||||
bool hasContainer;
|
||||
// <include> is always void, the same way <set> is (see parseSet) -
|
||||
// real content writes it bare (<include file="X">, no explicit
|
||||
// '/>'), which parseAttrs reports as hasContainer=true since it
|
||||
// can't tell that apart from a real container tag on syntax alone.
|
||||
auto attrs = parseAttrs(hasContainer);
|
||||
(void)hasContainer;
|
||||
auto it = attrs.find("file");
|
||||
if (it == attrs.end())
|
||||
throw std::runtime_error("jetc: <include> must have a file attribute.");
|
||||
if (includeDepth > 32)
|
||||
throw std::runtime_error("jetc: <include> depth exceeded (possible include cycle) resolving " + it->second);
|
||||
std::string fullPath = baseDir.empty() ? it->second : baseDir + "/" + it->second;
|
||||
std::ifstream in(fullPath);
|
||||
if (!in)
|
||||
throw std::runtime_error("jetc: <include> cannot open " + fullPath);
|
||||
std::ostringstream ss;
|
||||
ss << in.rdbuf();
|
||||
// Inherits the includer's own topLevel - an <include> spliced in at
|
||||
// the file's true top level reads as if its content were written
|
||||
// inline there (see this method's own doc comment), so a <tag
|
||||
// name="X"> defined in the included file is just as eligible for
|
||||
// compilation as one written directly in the includer.
|
||||
Parser sub(ss.str(), baseDir, includeDepth + 1, topLevel);
|
||||
return sub.parseNodes();
|
||||
}
|
||||
|
||||
NodePtr Parser::parseVar() {
|
||||
size_t start = pos;
|
||||
pos += 2; // "$[" or "#["
|
||||
int depth = 1;
|
||||
while (!eof() && depth > 0) {
|
||||
if (starts("$[") || starts("#[")) { depth++; pos += 2; continue; }
|
||||
if (s[pos] == ']') { depth--; pos++; continue; }
|
||||
pos++;
|
||||
}
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::VAR;
|
||||
n->varText = s.substr(start, pos - start);
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr Parser::parseSet() {
|
||||
pos += 4; // "<set"
|
||||
bool hasContainer;
|
||||
auto attrs = parseAttrs(hasContainer);
|
||||
// jet-1.4's <set name=... value=... expr=...> is always a plain
|
||||
// attribute-based assignment - it never had a container/body form.
|
||||
// Real 1.4 content (config.cfg, SESSIONCTL.tag, throughout) writes
|
||||
// it with a bare closing '>' and no explicit </set>, which is
|
||||
// syntactically indistinguishable from a (speculative, and per the
|
||||
// comment this replaced, never actually implemented) 2.0
|
||||
// container-form <set>...</set>. Since the container form was never
|
||||
// real to begin with, <set> is always treated as self-closing here,
|
||||
// matching 1.4's actual, exclusive behavior rather than guessing.
|
||||
(void)hasContainer;
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::SET;
|
||||
n->setName = attrs.count("name") ? attrs["name"] : "";
|
||||
if (attrs.count("value")) { n->setHasValue = true; n->setValue = attrs["value"]; }
|
||||
if (attrs.count("expr")) { n->setHasExpr = true; n->setExpr = attrs["expr"]; }
|
||||
n->setScope = attrs.count("scope") ? attrs["scope"] : "";
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr Parser::parseIf() {
|
||||
pos += 3; // "<if"
|
||||
bool hasContainer;
|
||||
auto attrs = parseAttrs(hasContainer);
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::IF;
|
||||
if (attrs.count("expr")) {
|
||||
n->cond.mode = CondMode::EXPR;
|
||||
n->cond.expr = attrs["expr"];
|
||||
} else {
|
||||
n->cond.mode = CondMode::VALUES;
|
||||
n->cond.value1 = attrs.count("value1") ? attrs["value1"] : "";
|
||||
n->cond.value2 = attrs.count("value2") ? attrs["value2"] : "";
|
||||
n->cond.type = attrs.count("type") ? attrs["type"] : "";
|
||||
}
|
||||
if (hasContainer) {
|
||||
auto span = scanBody(pos, "if", true);
|
||||
size_t closePos = span.first, elsePos = span.second;
|
||||
size_t thenEnd = (elsePos != std::string::npos) ? elsePos : closePos;
|
||||
n->thenBody = parseSub(pos, thenEnd);
|
||||
if (elsePos != std::string::npos) {
|
||||
n->hasElse = true;
|
||||
n->elseBody = parseSub(elsePos + 6, closePos);
|
||||
}
|
||||
pos = closePos + 3 + 2; // "</if>"
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr Parser::parseFor() {
|
||||
pos += 4; // "<for"
|
||||
bool hasContainer;
|
||||
auto attrs = parseAttrs(hasContainer);
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::FOR;
|
||||
if (attrs.count("start")) { n->forHasStart = true; n->forStart = attrs["start"]; }
|
||||
n->forEnd = attrs.count("end") ? attrs["end"] : "0";
|
||||
n->forStep = attrs.count("step") ? attrs["step"] : "1";
|
||||
if (attrs.count("name")) { n->forHasName = true; n->forName = attrs["name"]; }
|
||||
n->forScope = attrs.count("scope") ? attrs["scope"] : "";
|
||||
if (hasContainer) {
|
||||
auto span = scanBody(pos, "for", false);
|
||||
n->body = parseSub(pos, span.first);
|
||||
pos = span.first + 3 + 3; // "</for>"
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr Parser::parseWhile() {
|
||||
pos += 6; // "<while"
|
||||
bool hasContainer;
|
||||
auto attrs = parseAttrs(hasContainer);
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::WHILE;
|
||||
if (attrs.count("expr")) {
|
||||
n->cond.mode = CondMode::EXPR;
|
||||
n->cond.expr = attrs["expr"];
|
||||
} else {
|
||||
n->cond.mode = CondMode::VALUES;
|
||||
n->cond.value1 = attrs.count("value1") ? attrs["value1"] : "";
|
||||
n->cond.value2 = attrs.count("value2") ? attrs["value2"] : "";
|
||||
n->cond.type = attrs.count("type") ? attrs["type"] : "";
|
||||
}
|
||||
if (hasContainer) {
|
||||
auto span = scanBody(pos, "while", false);
|
||||
n->body = parseSub(pos, span.first);
|
||||
pos = span.first + 3 + 5; // "</while>"
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr Parser::parseFallback() {
|
||||
size_t origStart = pos;
|
||||
std::string tagName = peekTagName(pos);
|
||||
size_t p = pos;
|
||||
bool selfClosing = skipOpenTag(p);
|
||||
if (!selfClosing && !isVoidTag(tagName)) {
|
||||
auto span = scanBody(p, tagName, false);
|
||||
p = span.first + 3 + tagName.size();
|
||||
}
|
||||
pos = p;
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::FALLBACK;
|
||||
n->rawSpan = s.substr(origStart, pos - origStart);
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr Parser::parseTagDef() {
|
||||
size_t origStart = pos;
|
||||
pos += 4; // "<tag"
|
||||
bool hasContainer;
|
||||
auto attrs = parseAttrs(hasContainer);
|
||||
std::string name = attrs.count("name") ? attrs["name"] : "";
|
||||
// A dynamic name ($[...]/#[...]) or a body-less definition can't be
|
||||
// (and, per __tag.cpp, isn't even valid as) a compiled definition -
|
||||
// fall back to the exact same FALLBACK behavior as before rather
|
||||
// than failing to compile. Real content always uses a literal name.
|
||||
bool dynamicName = name.find("$[") != std::string::npos || name.find("#[") != std::string::npos;
|
||||
if (!hasContainer || name.empty() || dynamicName) {
|
||||
if (hasContainer) {
|
||||
auto span = scanBody(pos, "tag", false);
|
||||
pos = span.first + 3 + 3; // "</tag>"
|
||||
}
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::FALLBACK;
|
||||
n->rawSpan = s.substr(origStart, pos - origStart);
|
||||
return n;
|
||||
}
|
||||
std::string lowerName = name;
|
||||
for (char &c : lowerName) c = (char)std::tolower((unsigned char)c);
|
||||
|
||||
auto span = scanBody(pos, "tag", false);
|
||||
size_t closePos = span.first;
|
||||
size_t afterClose = closePos + 3 + 3; // "</tag>"
|
||||
|
||||
// Best-effort: this compiler's own modeled grammar is a real subset
|
||||
// of what the runtime interpreter tolerates (jet-1.4 content is
|
||||
// lenient in ways this parser doesn't fully cover yet - e.g. a
|
||||
// completely unrecognized bare tag like SESSIONCTL.tag's own
|
||||
// <setcookie ...>, which the interpreter just echoes as literal
|
||||
// text rather than treating as a real tag needing a close - see
|
||||
// Tag.cpp's own final dispatch fallback). Rather than teach every
|
||||
// such case to this parser up front, fall all the way back to the
|
||||
// exact same FALLBACK behavior a pre-TAGDEF compiler would have
|
||||
// produced for this whole span whenever the body can't be parsed -
|
||||
// this tag definition simply isn't compiled (stays fully
|
||||
// interpreted, unchanged), with zero risk to anything else in the
|
||||
// file. pos is never mutated by the failed parseSub call itself
|
||||
// (it operates on its own copied substring), so no explicit
|
||||
// rewind is needed before falling through.
|
||||
std::vector<NodePtr> body;
|
||||
bool bodyOk = true;
|
||||
try {
|
||||
body = parseSub(pos, closePos);
|
||||
} catch (const std::exception &) {
|
||||
bodyOk = false;
|
||||
}
|
||||
if (!bodyOk) {
|
||||
pos = afterClose;
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::FALLBACK;
|
||||
n->rawSpan = s.substr(origStart, pos - origStart);
|
||||
return n;
|
||||
}
|
||||
pos = afterClose;
|
||||
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::TAGDEF;
|
||||
n->tagDefName = lowerName;
|
||||
n->tagDefBody = body;
|
||||
// Exact original source text - codegen still emits the same
|
||||
// interpretSpan-based raw registration into global.tags alongside
|
||||
// the new compiled fast path (see JetCodegen's TAGDEF case), so
|
||||
// anything that reaches this tag some other way (a nested/locally-
|
||||
// scoped definition shadowing it, or interpreted content elsewhere)
|
||||
// keeps working exactly as it does today.
|
||||
n->rawSpan = s.substr(origStart, pos - origStart);
|
||||
return n;
|
||||
}
|
||||
|
||||
NodePtr Parser::parseContainerSlot() {
|
||||
pos += 10; // "<container"
|
||||
bool hasContainer;
|
||||
auto attrs = parseAttrs(hasContainer);
|
||||
// Attributes on <container> (eval=/name=/scope=, as real content
|
||||
// sometimes writes) are not consulted by the interpreter's own
|
||||
// <container> dispatch branch either (see Tag::renderContainer) -
|
||||
// matching that exactly rather than inventing new behavior here.
|
||||
(void)attrs;
|
||||
(void)hasContainer;
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::CONTAINER_SLOT;
|
||||
return n;
|
||||
}
|
||||
|
||||
std::vector<NodePtr> Parser::parseNodes() {
|
||||
std::vector<NodePtr> nodes;
|
||||
std::string textBuf;
|
||||
auto flush = [&]() {
|
||||
if (!textBuf.empty()) {
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::TEXT;
|
||||
n->text = textBuf;
|
||||
nodes.push_back(n);
|
||||
textBuf.clear();
|
||||
}
|
||||
};
|
||||
while (!eof()) {
|
||||
if (starts("|>")) {
|
||||
flush();
|
||||
pos += 2;
|
||||
std::string buf;
|
||||
while (!eof() && !starts("<|")) buf += s[pos++];
|
||||
if (!eof()) pos += 2;
|
||||
auto n = std::make_shared<Node>();
|
||||
n->kind = NodeKind::TEXT;
|
||||
n->text = buf;
|
||||
nodes.push_back(n);
|
||||
continue;
|
||||
}
|
||||
if (s[pos] == '<') {
|
||||
if (matchTagOpen("set", pos)) { flush(); nodes.push_back(parseSet()); continue; }
|
||||
if (matchTagOpen("if", pos)) { flush(); nodes.push_back(parseIf()); continue; }
|
||||
if (matchTagOpen("for", pos)) { flush(); nodes.push_back(parseFor()); continue; }
|
||||
if (matchTagOpen("while", pos)) { flush(); nodes.push_back(parseWhile()); continue; }
|
||||
if (matchTagOpen("include", pos)) {
|
||||
flush();
|
||||
auto included = parseInclude();
|
||||
nodes.insert(nodes.end(), included.begin(), included.end());
|
||||
continue;
|
||||
}
|
||||
if (matchTagOpen("container", pos)) { flush(); nodes.push_back(parseContainerSlot()); continue; }
|
||||
if (matchTagOpen("comment", pos)) { flush(); skipCommentTag(pos); continue; }
|
||||
if (topLevel && matchTagOpen("tag", pos)) { flush(); nodes.push_back(parseTagDef()); continue; }
|
||||
flush();
|
||||
nodes.push_back(parseFallback());
|
||||
continue;
|
||||
}
|
||||
if (starts("$[") || starts("#[")) {
|
||||
flush();
|
||||
nodes.push_back(parseVar());
|
||||
continue;
|
||||
}
|
||||
textBuf += s[pos++];
|
||||
}
|
||||
flush();
|
||||
return nodes;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
#ifndef __JetParser_h__
|
||||
#define __JetParser_h__
|
||||
|
||||
#include "JetAST.h"
|
||||
#include <string>
|
||||
#include <map>
|
||||
#include <utility>
|
||||
|
||||
namespace jetc {
|
||||
|
||||
// Standalone parser for a subset of the JET template grammar. Mirrors the
|
||||
// character-level grammar implemented by JetCore's Tag::parseContainer /
|
||||
// Tag::Tag (attribute scanning, same-tag-name nesting depth, the <if>
|
||||
// <else> split) closely enough for well-formed templates, but is a fresh
|
||||
// implementation - it does not reuse JetCore's Tag classes, since those
|
||||
// fuse parsing and execution together (a real parse/execute split there
|
||||
// is a separate, larger refactor). Anything outside the modeled subset
|
||||
// (set/if/for/while/$[...]/literal text) is captured as an exact raw
|
||||
// source span and left for the existing interpreter (Tag::interpretSpan)
|
||||
// to run at compiled-program runtime, so unsupported constructs degrade
|
||||
// gracefully instead of failing to compile.
|
||||
class Parser {
|
||||
public:
|
||||
// topLevel is false for any nested sub-parse (an <if>/<for>/<while>
|
||||
// body, via parseSub) and true for the file's own top-level flow and
|
||||
// for anything spliced in from an <include> (which inherits the
|
||||
// includer's own topLevel, since it's meant to read as if written
|
||||
// inline at that point - see parseInclude). Only used to decide
|
||||
// whether a <tag name="X"> definition is eligible for compilation
|
||||
// (see parseTagDef) - one found at topLevel==false (nested inside
|
||||
// another construct) stays FALLBACK, unchanged, matching __tag.cpp's
|
||||
// own locally-scoped-registration semantics that only a true
|
||||
// top-level definition is guaranteed to always be registered by the
|
||||
// time any invocation could reach it.
|
||||
explicit Parser(const std::string &src, std::string baseDir = "", int includeDepth = 0, bool topLevel = true)
|
||||
: s(src), pos(0), baseDir(baseDir), includeDepth(includeDepth), topLevel(topLevel) {}
|
||||
|
||||
std::vector<NodePtr> parseNodes();
|
||||
|
||||
private:
|
||||
std::string s;
|
||||
size_t pos;
|
||||
size_t nextId = 0;
|
||||
std::string baseDir;
|
||||
int includeDepth;
|
||||
bool topLevel;
|
||||
|
||||
bool eof() const { return pos >= s.size(); }
|
||||
bool starts(const std::string &lit) const;
|
||||
static bool isNameChar(char c);
|
||||
void skipWs();
|
||||
std::string readName();
|
||||
std::string peekTagName(size_t at) const;
|
||||
|
||||
bool matchTagOpen(const std::string &name, size_t at) const;
|
||||
bool matchTagClose(const std::string &name, size_t at) const;
|
||||
|
||||
// p points at '<' of some tag's opening; advances p past its '>' or
|
||||
// "/>", skipping quoted attribute values. Returns true if self-closing.
|
||||
bool skipOpenTag(size_t &p);
|
||||
void skipQuotedValue(size_t &p);
|
||||
void skipEmbeddedTag(size_t &p);
|
||||
|
||||
// <comment>...</comment> must be fully inert regardless of what's
|
||||
// inside it - unlike the generic parseFallback/scanBody path this
|
||||
// tag used to fall through to (which applies the same quote/
|
||||
// backslash-escape and nested-tag scanning real Jet syntax needs),
|
||||
// this tracks only same-tag-name nesting depth via matchTagOpen/
|
||||
// matchTagClose and otherwise ignores every character. See its own
|
||||
// definition for the quote-corruption bug this specifically closes.
|
||||
void skipCommentTag(size_t &p);
|
||||
|
||||
std::map<std::string, std::string> parseAttrs(bool &hasContainer);
|
||||
|
||||
// Scans forward from bodyStart (just after the opening tag's '>') for
|
||||
// tagName's matching close, tracking same-tag-name nesting depth and
|
||||
// (if lookForElse) a depth==1 "<else>" split point.
|
||||
// Returns {closePos, elsePos} (elsePos == npos if not found/not sought).
|
||||
std::pair<size_t, size_t> scanBody(size_t bodyStart, const std::string &tagName, bool lookForElse);
|
||||
|
||||
std::vector<NodePtr> parseSub(size_t start, size_t end);
|
||||
|
||||
// <include file="..."> is spliced in at compile time - read the
|
||||
// referenced file (resolved relative to baseDir) and parse ITS
|
||||
// content as if it had been written inline here, so everything in
|
||||
// it (custom <tag> definitions included) goes through this real
|
||||
// compiler, not the separate runtime interpreter (which has its own,
|
||||
// independently-buggy nested-tag handling). Returns the parsed nodes
|
||||
// to be spliced into the caller's own node list.
|
||||
std::vector<NodePtr> parseInclude();
|
||||
|
||||
NodePtr parseVar();
|
||||
NodePtr parseSet();
|
||||
NodePtr parseIf();
|
||||
NodePtr parseFor();
|
||||
NodePtr parseWhile();
|
||||
NodePtr parseFallback();
|
||||
|
||||
// <tag name="X">...</tag> at true top level (see topLevel above) -
|
||||
// compiles the definition body with a nested (topLevel=false) parse
|
||||
// instead of falling back to raw text, so jetc can generate a real
|
||||
// render function for it (see JetCodegen). Falls back to an ordinary
|
||||
// FALLBACK node (same as today) if the definition has no container
|
||||
// or no literal name= - degrades gracefully rather than failing to
|
||||
// compile.
|
||||
NodePtr parseTagDef();
|
||||
|
||||
// <container> (any case/attributes/closing style, always void - see
|
||||
// isVoidTag) - a leaf node; the actual rendering logic lives in
|
||||
// Tag::renderContainer, called from generated code exactly as the
|
||||
// interpreter's own <container> dispatch calls it today.
|
||||
NodePtr parseContainerSlot();
|
||||
|
||||
std::string newId(const std::string &prefix) { return prefix + std::to_string(nextId++) + "_"; }
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,39 @@
|
||||
// Minimal dlsym() check for the jetc_api_<name> route-metadata export added
|
||||
// alongside jetc_render_<name> in --shared mode (see JetCodegen.cpp). Proves
|
||||
// a host can discover a compiled module's declared routes purely from the
|
||||
// .jtc itself, with no separate manifest file - the actual point of putting
|
||||
// routing metadata in an exported symbol instead of a sidecar file.
|
||||
#include <dlfcn.h>
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
|
||||
struct JetApiRoute { const char *method; const char *path; };
|
||||
typedef const JetApiRoute *(*ApiFn)(int *count);
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc < 3) {
|
||||
std::cerr << "usage: api_test <module.jtc> <api-symbol>" << std::endl;
|
||||
return 1;
|
||||
}
|
||||
void *handle = dlopen(argv[1], RTLD_NOW);
|
||||
if (!handle) {
|
||||
std::cerr << "dlopen failed: " << dlerror() << std::endl;
|
||||
return 1;
|
||||
}
|
||||
dlerror();
|
||||
ApiFn api = (ApiFn)dlsym(handle, argv[2]);
|
||||
const char *err = dlerror();
|
||||
if (err) {
|
||||
std::cerr << "dlsym failed: " << err << std::endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int count = -1;
|
||||
const JetApiRoute *routes = api(&count);
|
||||
std::cout << count << " route(s):" << std::endl;
|
||||
for (int i = 0; i < count; ++i)
|
||||
std::cout << " " << routes[i].method << " " << routes[i].path << std::endl;
|
||||
|
||||
dlclose(handle);
|
||||
return 0;
|
||||
}
|
||||
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 48 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 510 KiB |
@@ -0,0 +1,26 @@
|
||||
|
||||
.controlframe {background: #16161c;
|
||||
border: 1px solid rgba(197, 164, 90, 0.28);
|
||||
border-radius: 3px;
|
||||
padding: 5px 5px 15px 10px;
|
||||
}
|
||||
|
||||
.vm {position: relative;
|
||||
height: 55px;
|
||||
}
|
||||
|
||||
.vmname {position: absolute;
|
||||
left: 0px; top: 0px;
|
||||
height: 55px;
|
||||
}
|
||||
|
||||
.vmcover {position: absolute;
|
||||
left: 15px;
|
||||
top: 30px;
|
||||
font: 12px 'Dot Matrix';
|
||||
background: #101014;
|
||||
color: #e3c47e;
|
||||
border: 1px solid rgba(197, 164, 90, 0.4);
|
||||
border-radius: 5px;
|
||||
padding: 2px 10px 2px 10px;
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
(function() {
|
||||
var dropzone = document.getElementById('documents-dropzone');
|
||||
var fileInput = document.getElementById('documents-file-input');
|
||||
var listBody = document.getElementById('documents-list-body');
|
||||
if (!dropzone || !listBody)
|
||||
return;
|
||||
|
||||
function escapeHtml(s) {
|
||||
var div = document.createElement('div');
|
||||
div.textContent = s == null ? '' : String(s);
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function post(path, params) {
|
||||
return fetch(path, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams(params || {}).toString()
|
||||
}).then(function(r) { return r.json(); });
|
||||
}
|
||||
|
||||
function loadList() {
|
||||
post('/documents/api/list', {}).then(function(res) {
|
||||
if (!res.ok || !res.documents.length) {
|
||||
listBody.innerHTML = '<div id="documents-empty">No documents yet - upload your first one above.</div>';
|
||||
return;
|
||||
}
|
||||
var html = '<table id="documents-list"><tr><th>Name</th><th>Uploaded</th><th></th><th></th></tr>';
|
||||
for (var i = 0; i < res.documents.length; i++) {
|
||||
var doc = res.documents[i];
|
||||
html += '<tr>' +
|
||||
'<td>' + escapeHtml(doc.name) + '</td>' +
|
||||
'<td>' + escapeHtml(doc.created) + '</td>' +
|
||||
'<td><span class="documents-action" data-action="download" data-id="' + doc.id + '" data-name="' + escapeHtml(doc.name) + '">Download</span></td>' +
|
||||
'<td><span class="documents-action" data-action="delete" data-id="' + doc.id + '">Delete</span></td>' +
|
||||
'</tr>';
|
||||
}
|
||||
html += '</table>';
|
||||
listBody.innerHTML = html;
|
||||
|
||||
var actions = listBody.querySelectorAll('.documents-action');
|
||||
for (var j = 0; j < actions.length; j++) {
|
||||
actions[j].addEventListener('click', function() {
|
||||
var id = this.getAttribute('data-id');
|
||||
if (this.getAttribute('data-action') === 'download') {
|
||||
window.fileManagerDownload && window.fileManagerDownload(id, this.getAttribute('data-name'));
|
||||
} else {
|
||||
post('/documents/api/delete', { id: id }).then(function(res) {
|
||||
if (res.ok)
|
||||
loadList();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}).catch(function() {
|
||||
listBody.innerHTML = '<div id="documents-empty">Could not load your documents.</div>';
|
||||
});
|
||||
}
|
||||
|
||||
function uploadFiles(files) {
|
||||
if (!files || !files.length)
|
||||
return;
|
||||
if (window.fileManagerUpload)
|
||||
window.fileManagerUpload(files);
|
||||
}
|
||||
|
||||
dropzone.addEventListener('click', function() {
|
||||
fileInput.click();
|
||||
});
|
||||
fileInput.addEventListener('change', function() {
|
||||
uploadFiles(fileInput.files);
|
||||
fileInput.value = '';
|
||||
});
|
||||
dropzone.addEventListener('dragover', function(e) {
|
||||
e.preventDefault();
|
||||
dropzone.classList.add('documents-dropzone-active');
|
||||
});
|
||||
dropzone.addEventListener('dragleave', function() {
|
||||
dropzone.classList.remove('documents-dropzone-active');
|
||||
});
|
||||
dropzone.addEventListener('drop', function(e) {
|
||||
e.preventDefault();
|
||||
dropzone.classList.remove('documents-dropzone-active');
|
||||
uploadFiles(e.dataTransfer.files);
|
||||
});
|
||||
|
||||
// The site-wide file manager (documents.js, loaded once via
|
||||
// mainpagetemplate.jet) dispatches this after a successful upload -
|
||||
// listening here (rather than only refreshing right after our own
|
||||
// uploadFiles() calls) also picks up uploads that were still running
|
||||
// when this page was navigated to via spa.js.
|
||||
document.addEventListener('documents:changed', loadList);
|
||||
|
||||
loadList();
|
||||
})();
|
||||
@@ -0,0 +1,178 @@
|
||||
// Site-wide file transfer manager - loaded once via mainpagetemplate.jet
|
||||
// (see its own script tag, outside #content) so the floating panel and
|
||||
// any in-progress transfer survive spa.js's own #content-only swaps
|
||||
// when navigating to a different page mid-upload/download.
|
||||
(function() {
|
||||
var panel = document.getElementById('filemgr-panel');
|
||||
if (!panel)
|
||||
return;
|
||||
|
||||
var toggle = document.getElementById('filemgr-toggle');
|
||||
var badge = document.getElementById('filemgr-badge');
|
||||
var list = document.getElementById('filemgr-list');
|
||||
var clearBtn = document.getElementById('filemgr-clear');
|
||||
|
||||
var transfers = {};
|
||||
var nextId = 1;
|
||||
|
||||
function escapeHtml(s) {
|
||||
var div = document.createElement('div');
|
||||
div.textContent = s == null ? '' : String(s);
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function updateBadge() {
|
||||
var activeCount = 0;
|
||||
for (var k in transfers) {
|
||||
if (transfers[k].status === 'active')
|
||||
activeCount++;
|
||||
}
|
||||
badge.textContent = activeCount > 0 ? String(activeCount) : '';
|
||||
}
|
||||
|
||||
function removeEmptyPlaceholder() {
|
||||
var empty = document.getElementById('filemgr-empty');
|
||||
if (empty)
|
||||
empty.remove();
|
||||
}
|
||||
|
||||
function showEmptyPlaceholderIfNeeded() {
|
||||
if (Object.keys(transfers).length === 0 && !document.getElementById('filemgr-empty'))
|
||||
list.innerHTML = '<div id="filemgr-empty">No transfers yet.</div>';
|
||||
}
|
||||
|
||||
var UPLOAD_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V6M5 12l7-7 7 7"/></svg>';
|
||||
var DOWNLOAD_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v13M5 12l7 7 7-7"/></svg>';
|
||||
|
||||
function addTransfer(name, direction) {
|
||||
var id = 'xfer' + (nextId++);
|
||||
removeEmptyPlaceholder();
|
||||
|
||||
var el = document.createElement('div');
|
||||
el.className = 'filemgr-item';
|
||||
el.innerHTML =
|
||||
'<div class="filemgr-item-row">' +
|
||||
'<span class="filemgr-item-icon">' + (direction === 'upload' ? UPLOAD_ICON : DOWNLOAD_ICON) + '</span>' +
|
||||
'<span class="filemgr-item-name">' + escapeHtml(name) + '</span>' +
|
||||
'<span class="filemgr-item-status">0%</span>' +
|
||||
'</div>' +
|
||||
'<div class="filemgr-progress-track"><div class="filemgr-progress-fill"></div></div>';
|
||||
list.insertBefore(el, list.firstChild);
|
||||
|
||||
transfers[id] = { el: el, status: 'active' };
|
||||
panel.classList.add('filemgr-expanded');
|
||||
updateBadge();
|
||||
return id;
|
||||
}
|
||||
|
||||
function updateProgress(id, percent) {
|
||||
var t = transfers[id];
|
||||
if (!t)
|
||||
return;
|
||||
t.el.querySelector('.filemgr-progress-fill').style.width = percent + '%';
|
||||
t.el.querySelector('.filemgr-item-status').textContent = percent + '%';
|
||||
}
|
||||
|
||||
function markDone(id, statusText) {
|
||||
var t = transfers[id];
|
||||
if (!t)
|
||||
return;
|
||||
t.status = 'done';
|
||||
t.el.classList.add('filemgr-done');
|
||||
t.el.querySelector('.filemgr-progress-fill').style.width = '100%';
|
||||
t.el.querySelector('.filemgr-item-status').textContent = statusText || 'Done';
|
||||
updateBadge();
|
||||
}
|
||||
|
||||
function markFailed(id, statusText) {
|
||||
var t = transfers[id];
|
||||
if (!t)
|
||||
return;
|
||||
t.status = 'failed';
|
||||
t.el.classList.add('filemgr-failed');
|
||||
t.el.querySelector('.filemgr-item-status').textContent = statusText || 'Failed';
|
||||
updateBadge();
|
||||
}
|
||||
|
||||
// Uploads a FileList/array of File objects, each as its own
|
||||
// concurrent XHR request - the browser's own HTTP connection pooling
|
||||
// runs several at once, tracked here as separate panel entries with
|
||||
// independent progress via xhr.upload's own progress event (fetch()
|
||||
// has no equivalent for the request/upload side, only the response).
|
||||
window.fileManagerUpload = function(files) {
|
||||
for (var i = 0; i < files.length; i++) {
|
||||
(function(file) {
|
||||
var id = addTransfer(file.name, 'upload');
|
||||
var xhr = new XMLHttpRequest();
|
||||
transfers[id].xhr = xhr;
|
||||
xhr.open('POST', '/documents/api/upload');
|
||||
xhr.upload.addEventListener('progress', function(e) {
|
||||
if (e.lengthComputable)
|
||||
updateProgress(id, Math.round((e.loaded / e.total) * 100));
|
||||
});
|
||||
xhr.addEventListener('load', function() {
|
||||
var res = null;
|
||||
try { res = JSON.parse(xhr.responseText); } catch (e) {}
|
||||
if (xhr.status === 200 && res && res.ok) {
|
||||
markDone(id);
|
||||
document.dispatchEvent(new CustomEvent('documents:changed'));
|
||||
} else {
|
||||
markFailed(id, (res && res.error) || 'Failed');
|
||||
}
|
||||
});
|
||||
xhr.addEventListener('error', function() { markFailed(id); });
|
||||
var fd = new FormData();
|
||||
fd.append('name', file.name);
|
||||
fd.append('filedata', file);
|
||||
xhr.send(fd);
|
||||
})(files[i]);
|
||||
}
|
||||
};
|
||||
|
||||
// Downloads a document by id via XHR (responseType 'blob') instead
|
||||
// of a plain <a href> so it gets real tracked progress in the same
|
||||
// panel as uploads, then hands the fetched bytes to the browser's
|
||||
// normal save flow via a Blob URL + synthetic <a download> click.
|
||||
window.fileManagerDownload = function(id, name) {
|
||||
var xferId = addTransfer(name, 'download');
|
||||
var xhr = new XMLHttpRequest();
|
||||
transfers[xferId].xhr = xhr;
|
||||
xhr.open('GET', '/documents/download?id=' + encodeURIComponent(id));
|
||||
xhr.responseType = 'blob';
|
||||
xhr.addEventListener('progress', function(e) {
|
||||
if (e.lengthComputable)
|
||||
updateProgress(xferId, Math.round((e.loaded / e.total) * 100));
|
||||
});
|
||||
xhr.addEventListener('load', function() {
|
||||
if (xhr.status !== 200) {
|
||||
markFailed(xferId);
|
||||
return;
|
||||
}
|
||||
var blobUrl = URL.createObjectURL(xhr.response);
|
||||
var a = document.createElement('a');
|
||||
a.href = blobUrl;
|
||||
a.download = name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
setTimeout(function() { URL.revokeObjectURL(blobUrl); }, 30000);
|
||||
markDone(xferId);
|
||||
});
|
||||
xhr.addEventListener('error', function() { markFailed(xferId); });
|
||||
xhr.send();
|
||||
};
|
||||
|
||||
toggle.addEventListener('click', function() {
|
||||
panel.classList.toggle('filemgr-expanded');
|
||||
});
|
||||
|
||||
clearBtn.addEventListener('click', function() {
|
||||
for (var k in transfers) {
|
||||
if (transfers[k].status !== 'active') {
|
||||
transfers[k].el.remove();
|
||||
delete transfers[k];
|
||||
}
|
||||
}
|
||||
showEmptyPlaceholderIfNeeded();
|
||||
});
|
||||
})();
|
||||
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,881 @@
|
||||
(function() {
|
||||
var app = document.getElementById('email-app');
|
||||
if (!app) return;
|
||||
|
||||
// Small inline-SVG icon set for the toolbar/action buttons below -
|
||||
// stroke="currentColor" so each one just inherits its <button>'s own
|
||||
// text color (the site's gold theme, see .icon-btn in email.page's
|
||||
// own <style> block), no separate image assets or color variants to
|
||||
// keep in sync with the theme.
|
||||
var ICONS = {
|
||||
search:
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<circle cx="11" cy="11" r="7"/>' +
|
||||
'<path d="M21 21l-4.35-4.35"/>' +
|
||||
'</svg>',
|
||||
compose:
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M4 6h13a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z"/>' +
|
||||
'<path d="M2.5 7.5 12 14l9.5-6.5"/>' +
|
||||
'<path d="M18.5 3.5v5M16 6h5"/>' +
|
||||
'</svg>',
|
||||
refresh:
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M20 11a8 8 0 0 0-14.6-4.4M4 4v5h5"/>' +
|
||||
'<path d="M4 13a8 8 0 0 0 14.6 4.4M20 20v-5h-5"/>' +
|
||||
'</svg>',
|
||||
flag:
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M5 3v18"/>' +
|
||||
'<path d="M5 4h12l-3 4.5L17 13H5"/>' +
|
||||
'</svg>',
|
||||
trash:
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M4 7h16"/>' +
|
||||
'<path d="M9 7V4h6v3"/>' +
|
||||
'<path d="M6 7l1 13a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-13"/>' +
|
||||
'<path d="M10 11v6M14 11v6"/>' +
|
||||
'</svg>',
|
||||
pagePrev:
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M15 18l-6-6 6-6"/>' +
|
||||
'</svg>',
|
||||
pageNext:
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M9 18l6-6-6-6"/>' +
|
||||
'</svg>',
|
||||
emptyFolder:
|
||||
'<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">' +
|
||||
'<path d="M4 7h16"/>' +
|
||||
'<path d="M9 7V4h6v3"/>' +
|
||||
'<path d="M6 7l1 13a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-13"/>' +
|
||||
'<path d="M9.5 12.5l5 5M14.5 12.5l-5 5"/>' +
|
||||
'</svg>'
|
||||
};
|
||||
|
||||
// Matches the exact, case-sensitive names the mailbox itself reports
|
||||
// via IMAP LIST (confirmed live: "Inbox", "Spam", "Trash" - only
|
||||
// INBOX is specially case-insensitive per RFC 3501, the other two
|
||||
// are not, so this has to be exact) - see email.menu's own folder
|
||||
// links, which pass these same three names to emailSelectFolder().
|
||||
var currentFolder = 'Inbox';
|
||||
var currentUid = null;
|
||||
// null = showing the normal folder listing; a non-empty string =
|
||||
// showing search results instead (see performSearch()/clearSearch()
|
||||
// and loadMessageList()'s own branch on this).
|
||||
var currentSearchQuery = null;
|
||||
// How many newest-first messages /email/list has already skipped -
|
||||
// 0 is the newest page. Must match LIST_LIMIT server-side (email.jet
|
||||
// defaults "limit" to 50 too) so a page is exactly one "limit"
|
||||
// worth of messages. Reset to 0 everywhere currentFolder/currentUid
|
||||
// already get reset (folder switch, search, account switch) - a
|
||||
// stale offset from one folder/account applied to another would
|
||||
// silently skip or duplicate messages.
|
||||
var currentOffset = 0;
|
||||
var LIST_LIMIT = 50;
|
||||
// Total message count the server reported for the CURRENT page's
|
||||
// folder/query, used only to enable/disable the Next button -
|
||||
// updated every time updateListCount() runs.
|
||||
var currentTotal = 0;
|
||||
// The array last handed to renderMessageList() - kept so openMessage()
|
||||
// can flip a single message's .seen flag locally and recompute the
|
||||
// toolbar's unread/total count without a round trip.
|
||||
var currentMessages = [];
|
||||
|
||||
// email.menu (the site's own left-side #panelmenu, a static include
|
||||
// living outside #email-app/#content entirely - see mainpagetemplate
|
||||
// .jet's own panelmenu wiring) renders its folder links against this
|
||||
// global rather than anything scoped to this closure, since it has
|
||||
// no other way to reach into a same-page IMAP client without a full
|
||||
// page navigation (which the rest of this client deliberately avoids
|
||||
// for every other interaction too - see the module doc comment on
|
||||
// post() below... [see loadMessageList/openMessage]). Guarded with
|
||||
// `window.emailSelectFolder &&` at each call site in email.menu so a
|
||||
// click before email.js has loaded (or before a mailbox is even
|
||||
// connected) is a harmless no-op instead of a broken link.
|
||||
window.emailSelectFolder = function(folder) {
|
||||
if (!document.getElementById('email-client') || (folder === currentFolder && !currentSearchQuery))
|
||||
return;
|
||||
currentFolder = folder;
|
||||
currentUid = null;
|
||||
currentOffset = 0;
|
||||
// A folder click always means "show me this folder, plain" - drops
|
||||
// out of search mode even if the folder didn't actually change,
|
||||
// which is exactly how a user would expect to back out of a
|
||||
// search result view.
|
||||
currentSearchQuery = null;
|
||||
var searchInput = document.getElementById('email-search-input');
|
||||
if (searchInput) searchInput.value = '';
|
||||
syncActiveFolder();
|
||||
var pane = document.getElementById('email-reading-pane');
|
||||
if (pane) pane.innerHTML = '<div id="email-empty-state">Select a message to read it.</div>';
|
||||
loadMessageList();
|
||||
};
|
||||
|
||||
function syncActiveFolder() {
|
||||
var links = document.querySelectorAll('.email-folder-link');
|
||||
for (var i = 0; i < links.length; i++)
|
||||
links[i].classList.toggle('email-folder-selected', links[i].getAttribute('data-folder') === currentFolder);
|
||||
// Only Spam/Trash ever offer this - emptying Inbox (or any future
|
||||
// folder) as a single destructive click isn't something any real
|
||||
// mail client exposes, and the server enforces the exact same
|
||||
// Spam/Trash-only allowlist independently (see email.jet) - this is
|
||||
// just keeping the button from ever being visible somewhere it
|
||||
// would 400 anyway, not the actual safety boundary.
|
||||
var emptyBtn = document.getElementById('email-empty-folder-btn');
|
||||
if (emptyBtn)
|
||||
emptyBtn.hidden = (currentFolder !== 'Spam' && currentFolder !== 'Trash');
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
var div = document.createElement('div');
|
||||
div.textContent = s == null ? '' : String(s);
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function post(path, params) {
|
||||
return fetch(path, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams(params || {}).toString()
|
||||
}).then(function(r) { return r.json(); });
|
||||
}
|
||||
|
||||
// Matches spa.js's own delay() exactly - a separate closure here
|
||||
// since this file has no dependency on spa.js at all, not worth
|
||||
// sharing just for this.
|
||||
function delay(ms) {
|
||||
return new Promise(function(resolve) { setTimeout(resolve, ms); });
|
||||
}
|
||||
|
||||
function showConnectForm(errorText) {
|
||||
app.innerHTML =
|
||||
'<div id="email-connect-form">' +
|
||||
'<h3>Connect to Mailbox</h3>' +
|
||||
'<input type="text" id="email-user-input" placeholder="you@barant.com" autocomplete="username">' +
|
||||
'<input type="password" id="email-password-input" placeholder="Password" autocomplete="current-password">' +
|
||||
'<button type="button" id="email-connect-btn">Connect</button>' +
|
||||
'<div id="email-connect-error">' + (errorText ? escapeHtml(errorText) : '') + '</div>' +
|
||||
'</div>';
|
||||
wireConnectForm();
|
||||
}
|
||||
|
||||
function showClientView(userEmail) {
|
||||
app.innerHTML =
|
||||
'<div id="email-client">' +
|
||||
'<div id="email-toolbar">' +
|
||||
'<span id="email-connected-as">' + escapeHtml(userEmail) + '</span>' +
|
||||
'<span id="email-list-count"></span>' +
|
||||
'<span id="email-pagination"></span>' +
|
||||
'<span id="email-toolbar-actions">' +
|
||||
'<span id="email-search-box">' +
|
||||
'<input type="text" id="email-search-input" placeholder="Search mail…">' +
|
||||
'<button type="button" id="email-search-btn" class="icon-btn" title="Search">' + ICONS.search + '</button>' +
|
||||
'</span>' +
|
||||
'<button type="button" id="email-compose-btn" class="icon-btn" title="New Mail">' + ICONS.compose + '</button>' +
|
||||
'<button type="button" id="email-empty-folder-btn" class="icon-btn" title="Permanently empty this folder" hidden>' + ICONS.emptyFolder + '</button>' +
|
||||
'<button type="button" id="email-refresh-btn" class="icon-btn" title="Refresh">' + ICONS.refresh + '</button>' +
|
||||
'</span>' +
|
||||
'</div>' +
|
||||
'<div id="email-layout">' +
|
||||
'<div id="email-list"></div>' +
|
||||
'<div id="email-reading-pane"><div id="email-empty-state">Select a message to read it.</div></div>' +
|
||||
'</div>' +
|
||||
'</div>';
|
||||
wireClientView();
|
||||
wireAddAccountForm();
|
||||
syncActiveFolder();
|
||||
loadMessageList();
|
||||
loadAccounts();
|
||||
}
|
||||
|
||||
function wireConnectForm() {
|
||||
var btn = document.getElementById('email-connect-btn');
|
||||
var userInput = document.getElementById('email-user-input');
|
||||
var passInput = document.getElementById('email-password-input');
|
||||
var errorDiv = document.getElementById('email-connect-error');
|
||||
|
||||
function submit() {
|
||||
errorDiv.textContent = '';
|
||||
btn.disabled = true;
|
||||
post('/email/connect', { user: userInput.value, password: passInput.value })
|
||||
.then(function(res) {
|
||||
btn.disabled = false;
|
||||
if (res.ok) {
|
||||
showClientView(userInput.value);
|
||||
} else {
|
||||
errorDiv.textContent = res.error || 'Could not connect.';
|
||||
}
|
||||
})
|
||||
.catch(function() {
|
||||
btn.disabled = false;
|
||||
errorDiv.textContent = 'Connection request failed.';
|
||||
});
|
||||
}
|
||||
|
||||
btn.addEventListener('click', submit);
|
||||
passInput.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter') submit();
|
||||
});
|
||||
}
|
||||
|
||||
function wireClientView() {
|
||||
// Navigates via a synthetic <a> click rather than
|
||||
// window.location.href so spa.js's own document-level click
|
||||
// listener intercepts it and does its normal fade transition,
|
||||
// exactly as if a real link had been clicked.
|
||||
document.getElementById('email-compose-btn').addEventListener('click', function() {
|
||||
var a = document.createElement('a');
|
||||
a.href = '/admin/newemail';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
});
|
||||
document.getElementById('email-refresh-btn').addEventListener('click', function() {
|
||||
loadMessageList();
|
||||
});
|
||||
document.getElementById('email-empty-folder-btn').addEventListener('click', emptyCurrentFolder);
|
||||
|
||||
// Matches sender, subject, or body content in whatever folder is
|
||||
// currently open (see __imap.cpp's searchMessages()) - an empty
|
||||
// query is treated as "leave search mode" rather than sent to the
|
||||
// server as a real search, since an empty needle would otherwise
|
||||
// just match everything anyway (see __IMAP_SEARCH.cpp's own
|
||||
// containsCI()) - clearer to just fall back to the plain listing.
|
||||
function runSearch() {
|
||||
var input = document.getElementById('email-search-input');
|
||||
var query = input.value.trim();
|
||||
currentSearchQuery = query === '' ? null : query;
|
||||
currentUid = null;
|
||||
currentOffset = 0;
|
||||
document.getElementById('email-reading-pane').innerHTML =
|
||||
'<div id="email-empty-state">Select a message to read it.</div>';
|
||||
loadMessageList();
|
||||
}
|
||||
document.getElementById('email-search-btn').addEventListener('click', runSearch);
|
||||
document.getElementById('email-search-input').addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter')
|
||||
runSearch();
|
||||
});
|
||||
}
|
||||
|
||||
function updateListCount(messages) {
|
||||
var countEl = document.getElementById('email-list-count');
|
||||
if (!countEl)
|
||||
return;
|
||||
if (!messages.length) {
|
||||
countEl.textContent = '';
|
||||
return;
|
||||
}
|
||||
var unread = 0;
|
||||
for (var i = 0; i < messages.length; i++) {
|
||||
if (!messages[i].seen)
|
||||
unread++;
|
||||
}
|
||||
countEl.textContent = '(' + unread + '/' + messages.length + ')';
|
||||
}
|
||||
|
||||
// total === null means "not paginated" (search results, or nothing
|
||||
// loaded yet) - hides the whole control rather than showing a
|
||||
// meaningless "1-0 of null". Otherwise renders the current page's
|
||||
// 1-based range and enables Prev/Next based on currentOffset/total,
|
||||
// matching how far a click on either button would actually move.
|
||||
function updatePaginationControls(total) {
|
||||
var el = document.getElementById('email-pagination');
|
||||
if (!el)
|
||||
return;
|
||||
currentTotal = total || 0;
|
||||
if (total === null || total === 0) {
|
||||
el.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
var rangeStart = total === 0 ? 0 : currentOffset + 1;
|
||||
var rangeEnd = Math.min(currentOffset + LIST_LIMIT, total);
|
||||
var atStart = currentOffset <= 0;
|
||||
var atEnd = currentOffset + LIST_LIMIT >= total;
|
||||
el.innerHTML =
|
||||
'<button type="button" id="email-page-prev" class="icon-btn"' + (atStart ? ' disabled' : '') + ' title="Newer messages">' + ICONS.pagePrev + '</button>' +
|
||||
'<span id="email-page-range">' + rangeStart + '–' + rangeEnd + ' of ' + total + '</span>' +
|
||||
'<button type="button" id="email-page-next" class="icon-btn"' + (atEnd ? ' disabled' : '') + ' title="Older messages">' + ICONS.pageNext + '</button>';
|
||||
var prevBtn = document.getElementById('email-page-prev');
|
||||
var nextBtn = document.getElementById('email-page-next');
|
||||
if (prevBtn) prevBtn.addEventListener('click', function() {
|
||||
if (currentOffset <= 0)
|
||||
return;
|
||||
currentOffset = Math.max(0, currentOffset - LIST_LIMIT);
|
||||
currentUid = null;
|
||||
loadMessageList();
|
||||
});
|
||||
if (nextBtn) nextBtn.addEventListener('click', function() {
|
||||
if (currentOffset + LIST_LIMIT >= currentTotal)
|
||||
return;
|
||||
currentOffset += LIST_LIMIT;
|
||||
currentUid = null;
|
||||
loadMessageList();
|
||||
});
|
||||
}
|
||||
|
||||
function renderMessageList(messages, total) {
|
||||
var list = document.getElementById('email-list');
|
||||
currentMessages = messages;
|
||||
updateListCount(messages);
|
||||
updatePaginationControls(total === undefined ? null : total);
|
||||
if (!messages.length) {
|
||||
list.innerHTML = '<div id="email-empty-state">No messages.</div>';
|
||||
return;
|
||||
}
|
||||
var html = '';
|
||||
for (var i = 0; i < messages.length; i++) {
|
||||
var m = messages[i];
|
||||
html += '<div class="email-row' + (m.seen ? '' : ' unread') +
|
||||
(m.uid === currentUid ? ' selected' : '') + '" data-uid="' + m.uid + '">' +
|
||||
'<div class="email-row-info">' +
|
||||
'<div class="email-from">' + escapeHtml(m.from) + '</div>' +
|
||||
'<div class="email-subject">' + escapeHtml(m.subject || '(no subject)') + '</div>' +
|
||||
'<div class="email-date">' + escapeHtml(m.date) + '</div>' +
|
||||
'</div>' +
|
||||
'<button type="button" class="icon-btn email-row-trash-btn" data-uid="' + m.uid + '" title="Move to Trash">' + ICONS.trash + '</button>' +
|
||||
'</div>';
|
||||
}
|
||||
list.innerHTML = html;
|
||||
|
||||
var rows = list.querySelectorAll('.email-row');
|
||||
for (var j = 0; j < rows.length; j++) {
|
||||
rows[j].addEventListener('click', function() {
|
||||
openMessage(parseInt(this.getAttribute('data-uid'), 10));
|
||||
});
|
||||
}
|
||||
// Each row's own trash button - stopPropagation so it doesn't also
|
||||
// trigger the row's own click-to-open handler just above.
|
||||
var trashBtns = list.querySelectorAll('.email-row-trash-btn');
|
||||
for (var k = 0; k < trashBtns.length; k++) {
|
||||
trashBtns[k].addEventListener('click', function(e) {
|
||||
e.stopPropagation();
|
||||
trashMessage(parseInt(this.getAttribute('data-uid'), 10));
|
||||
});
|
||||
}
|
||||
|
||||
// Whatever caused this particular render (initial connect, a
|
||||
// folder switch, the refresh button with nothing open) left
|
||||
// currentUid null - open the top message rather than leave the
|
||||
// reading pane sitting empty. trashMessage() deliberately sets
|
||||
// currentUid to the row it's already decided to select BEFORE
|
||||
// reloading the list (see its own comment), specifically so this
|
||||
// check sees a real, already-correct uid and stays out of the way
|
||||
// instead of racing it to open something different.
|
||||
if (currentUid === null)
|
||||
openMessage(messages[0].uid);
|
||||
}
|
||||
|
||||
// Moves a message into the Trash folder (server-side: COPY there,
|
||||
// then \Deleted+EXPUNGE from the original folder - see __imap.cpp's
|
||||
// moveMessage()) rather than permanently removing it, the same
|
||||
// "delete means trash it" convention the reading pane's own Delete
|
||||
// button (a real, permanent expunge) deliberately does NOT follow -
|
||||
// that one stays as-is; this is a separate, softer action reachable
|
||||
// straight from the list.
|
||||
// Total time the .email-row-removing CSS animation takes to finish
|
||||
// (see email.page's own <style> block) - the opacity fade runs with
|
||||
// no delay for FADE_MS, then the height/padding/margin/border
|
||||
// collapse (what actually slides the rows below it up) runs for
|
||||
// COLLAPSE_MS starting COLLAPSE_DELAY_MS in. Kept here as the single
|
||||
// source of truth for how long trashMessage() waits before swapping
|
||||
// in the server's real, post-trash list - duplicated as literal
|
||||
// numbers in the CSS transition properties themselves, since CSS has
|
||||
// no way to reference a JS constant, so keep those two in sync by
|
||||
// hand if either ever changes.
|
||||
var REMOVE_FADE_MS = 200;
|
||||
var REMOVE_COLLAPSE_DELAY_MS = 200;
|
||||
var REMOVE_COLLAPSE_MS = 220;
|
||||
|
||||
// Plays the dissolve-then-collapse removal animation on one row in
|
||||
// place, resolving once it's fully finished (safe to call with a
|
||||
// null row - resolves immediately, for when the trashed uid's row
|
||||
// isn't actually in the currently-rendered list for some reason).
|
||||
function animateRowRemoval(row) {
|
||||
if (!row)
|
||||
return Promise.resolve();
|
||||
var height = row.getBoundingClientRect().height;
|
||||
row.style.height = height + 'px';
|
||||
// Forces the browser to register the explicit pixel height above
|
||||
// as a real, already-applied style before the next line changes
|
||||
// it again - without this the two height changes collapse into a
|
||||
// single layout pass and no transition plays at all.
|
||||
row.offsetHeight;
|
||||
row.classList.add('email-row-removing');
|
||||
return new Promise(function(resolve) {
|
||||
setTimeout(resolve, REMOVE_FADE_MS + REMOVE_COLLAPSE_DELAY_MS + REMOVE_COLLAPSE_MS);
|
||||
});
|
||||
}
|
||||
|
||||
// Only the trashed row itself animates - every other row just stays
|
||||
// exactly where it is and shifts up as an ordinary side effect of
|
||||
// the trashed row's own height collapsing to 0 (real document-flow
|
||||
// reflow, not a separate animation applied to them). The list is
|
||||
// still reloaded from the server afterward (flags/counts could have
|
||||
// changed for reasons unrelated to this one trash action), but with
|
||||
// loadMessageList(true) - skipping ITS OWN whole-list fade, since by
|
||||
// the time it swaps in fresh markup the trashed row has already
|
||||
// visually shrunk to nothing and every other row is already sitting
|
||||
// in its final position; fading the whole list on top of that would
|
||||
// just be a second, redundant flash.
|
||||
function trashMessage(uid) {
|
||||
var rows = document.querySelectorAll('.email-row');
|
||||
var index = -1;
|
||||
var trashedRow = null;
|
||||
for (var i = 0; i < rows.length; i++) {
|
||||
if (parseInt(rows[i].getAttribute('data-uid'), 10) === uid) {
|
||||
index = i;
|
||||
trashedRow = rows[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
var nextUid = null;
|
||||
if (index !== -1) {
|
||||
if (index + 1 < rows.length)
|
||||
nextUid = parseInt(rows[index + 1].getAttribute('data-uid'), 10);
|
||||
else if (index - 1 >= 0)
|
||||
nextUid = parseInt(rows[index - 1].getAttribute('data-uid'), 10);
|
||||
}
|
||||
|
||||
Promise.all([
|
||||
animateRowRemoval(trashedRow),
|
||||
post('/email/trash', { folder: currentFolder, uid: uid })
|
||||
]).then(function() {
|
||||
// Set BEFORE the reload, not after - renderMessageList()'s own
|
||||
// auto-select-first-when-nothing's-selected check runs partway
|
||||
// through loadMessageList(true) below, and needs to already see
|
||||
// the real target here (or genuinely null, if the list is about
|
||||
// to be empty) rather than a stale null that would make it pick
|
||||
// the top row instead and race this function's own openMessage()
|
||||
// call just below.
|
||||
if (currentUid === uid)
|
||||
currentUid = nextUid;
|
||||
loadMessageList(true).then(function() {
|
||||
if (nextUid !== null)
|
||||
openMessage(nextUid);
|
||||
else
|
||||
document.getElementById('email-reading-pane').innerHTML =
|
||||
'<div id="email-empty-state">Select a message to read it.</div>';
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Permanently deletes every message in the CURRENT folder (only ever
|
||||
// reachable while viewing Spam or Trash - see syncActiveFolder()'s own
|
||||
// button-visibility gate, and email.jet's independent server-side
|
||||
// allowlist, which is the real enforcement). Unlike trashMessage()
|
||||
// there's no undo, no "move somewhere" - a real, human-readable confirm()
|
||||
// is the whole safety net here, matching how Gmail/Outlook both gate
|
||||
// "Empty Trash now" behind exactly one extra click and nothing fancier.
|
||||
function emptyCurrentFolder() {
|
||||
if (currentFolder !== 'Spam' && currentFolder !== 'Trash')
|
||||
return;
|
||||
if (!window.confirm('Permanently delete every message in ' + currentFolder + '? This cannot be undone.'))
|
||||
return;
|
||||
var btn = document.getElementById('email-empty-folder-btn');
|
||||
if (btn) btn.disabled = true;
|
||||
post('/email/emptyfolder', { folder: currentFolder })
|
||||
.then(function(res) {
|
||||
if (btn) btn.disabled = false;
|
||||
if (!res.ok) {
|
||||
window.alert(res.error || 'Could not empty the folder.');
|
||||
return;
|
||||
}
|
||||
currentUid = null;
|
||||
document.getElementById('email-reading-pane').innerHTML =
|
||||
'<div id="email-empty-state">Select a message to read it.</div>';
|
||||
loadMessageList();
|
||||
})
|
||||
.catch(function() {
|
||||
if (btn) btn.disabled = false;
|
||||
window.alert('Empty-folder request failed.');
|
||||
});
|
||||
}
|
||||
|
||||
// Same fade-out/fetch-concurrently/fade-in shape as openMessage() and
|
||||
// spa.js's own navigate() - every list refresh (folder switch,
|
||||
// refresh button) gets the same smooth transition instead of a flash
|
||||
// of "Loading..." text followed by an abrupt content swap. Pass
|
||||
// skipFade=true to skip that whole-list transition and just quietly
|
||||
// re-render in place - used only right after trashMessage()'s own
|
||||
// per-row removal animation has already provided the visual
|
||||
// transition, so this reload doesn't also blink the entire list.
|
||||
function loadMessageList(skipFade) {
|
||||
var list = document.getElementById('email-list');
|
||||
if (!list)
|
||||
return Promise.resolve();
|
||||
if (!skipFade)
|
||||
list.classList.add('email-fading');
|
||||
// Search results use the identical JSON shape as a normal list
|
||||
// (see __imap.cpp's shared parseSummaryLines()), so this is the
|
||||
// only place that needs to know search mode even exists -
|
||||
// renderMessageList() below has no idea which one produced what
|
||||
// it's rendering. Search isn't paginated (offset/limit only apply
|
||||
// to the plain listing) - a search result set is returned in full.
|
||||
var request = currentSearchQuery
|
||||
? post('/email/search', { folder: currentFolder, query: currentSearchQuery })
|
||||
: post('/email/list', { folder: currentFolder, offset: currentOffset, limit: LIST_LIMIT });
|
||||
return Promise.all([
|
||||
request,
|
||||
skipFade ? true : delay(180)
|
||||
])
|
||||
.then(function(results) {
|
||||
var res = results[0];
|
||||
if (!res.ok && res.error)
|
||||
list.innerHTML = '<div id="email-empty-state">' + escapeHtml(res.error) + '</div>';
|
||||
else if (currentSearchQuery)
|
||||
renderMessageList(Array.isArray(res) ? res : [], null);
|
||||
else
|
||||
renderMessageList(Array.isArray(res.messages) ? res.messages : [], res.total || 0);
|
||||
// Every place that reloads the list (connect, folder switch,
|
||||
// refresh, post-trash) is a place the unseen counts next to
|
||||
// each folder name could plausibly have changed too - one
|
||||
// hook here covers all of them rather than needing a separate
|
||||
// call at each individual call site.
|
||||
loadFolderCounts();
|
||||
if (!skipFade)
|
||||
list.classList.remove('email-fading');
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.error('loadMessageList failed:', err);
|
||||
list.innerHTML = '<div id="email-empty-state">Could not load messages' +
|
||||
(err && err.message ? ': ' + escapeHtml(err.message) : '.') + '</div>';
|
||||
if (!skipFade)
|
||||
list.classList.remove('email-fading');
|
||||
});
|
||||
}
|
||||
|
||||
// Populates the unread-count badge next to each folder name in
|
||||
// email.menu's own static markup (a real DOM lookup by
|
||||
// data-folder-count, not anything rendered by this file - email.menu
|
||||
// is a separate include living in #panelmenu, outside #content
|
||||
// entirely). Uses IMAP STATUS server-side (see __imap.cpp's
|
||||
// folderCounts()), not a real FETCH, so this is cheap enough to call
|
||||
// on every list reload without it being a heavy extra round trip.
|
||||
// Silently does nothing on error - a stale/missing count badge is a
|
||||
// cosmetic problem, not worth surfacing as a user-visible failure.
|
||||
function loadFolderCounts() {
|
||||
post('/email/folders', {}).then(function(res) {
|
||||
if (res.error) {
|
||||
console.error('loadFolderCounts server error:', res.error);
|
||||
return;
|
||||
}
|
||||
var folders = ['Inbox', 'Spam', 'Trash'];
|
||||
for (var i = 0; i < folders.length; i++) {
|
||||
var f = folders[i];
|
||||
var span = document.querySelector('.email-folder-count[data-folder-count="' + f + '"]');
|
||||
if (span && res[f])
|
||||
span.textContent = res[f].messages > 0 ? (res[f].unseen + '/' + res[f].messages) : '';
|
||||
}
|
||||
}).catch(function(err) {
|
||||
console.error('loadFolderCounts failed:', err);
|
||||
});
|
||||
}
|
||||
|
||||
function loadAccounts() {
|
||||
post('/email/accounts', {}).then(function(res) {
|
||||
var list = document.getElementById('email-account-list');
|
||||
if (!list || !res.accounts)
|
||||
return;
|
||||
var html = '';
|
||||
for (var i = 0; i < res.accounts.length; i++) {
|
||||
var user = res.accounts[i];
|
||||
html += '<a href="javascript:void(0);" class="email-account-link' +
|
||||
(user === res.active ? ' email-account-selected' : '') + '" data-user="' +
|
||||
escapeHtml(user) + '">' + escapeHtml(user) + '</a>';
|
||||
}
|
||||
list.innerHTML = html;
|
||||
var links = list.querySelectorAll('.email-account-link');
|
||||
for (var j = 0; j < links.length; j++) {
|
||||
links[j].addEventListener('click', function() {
|
||||
var user = this.getAttribute('data-user');
|
||||
if (!this.classList.contains('email-account-selected'))
|
||||
switchAccount(user);
|
||||
});
|
||||
}
|
||||
}).catch(function() {});
|
||||
}
|
||||
|
||||
// Shared by switchAccount() and the add-account form's own success
|
||||
// path (which is already connected/active server-side by the time
|
||||
// /email/connect returns ok - no reason to also round-trip through
|
||||
// switchaccount right after) - resets the view to a fresh Inbox for
|
||||
// whichever account just became active, same as a brand new connect.
|
||||
function resetViewForActiveAccount(user) {
|
||||
currentFolder = 'Inbox';
|
||||
currentUid = null;
|
||||
currentOffset = 0;
|
||||
currentSearchQuery = null;
|
||||
var searchInput = document.getElementById('email-search-input');
|
||||
if (searchInput) searchInput.value = '';
|
||||
var connectedAs = document.getElementById('email-connected-as');
|
||||
if (connectedAs) connectedAs.textContent = user;
|
||||
syncActiveFolder();
|
||||
var pane = document.getElementById('email-reading-pane');
|
||||
if (pane) pane.innerHTML = '<div id="email-empty-state">Select a message to read it.</div>';
|
||||
loadMessageList();
|
||||
loadAccounts();
|
||||
}
|
||||
|
||||
function switchAccount(user) {
|
||||
post('/email/switchaccount', { user: user }).then(function(res) {
|
||||
if (res.ok)
|
||||
resetViewForActiveAccount(user);
|
||||
}).catch(function() {});
|
||||
}
|
||||
|
||||
window.emailShowAddAccount = function() {
|
||||
var form = document.getElementById('email-add-account-form');
|
||||
var link = document.getElementById('email-add-account-link');
|
||||
if (!form)
|
||||
return;
|
||||
form.style.display = 'flex';
|
||||
if (link) link.style.display = 'none';
|
||||
var userInput = document.getElementById('email-add-account-user');
|
||||
if (userInput) userInput.focus();
|
||||
};
|
||||
|
||||
function wireAddAccountForm() {
|
||||
var btn = document.getElementById('email-add-account-btn');
|
||||
var userInput = document.getElementById('email-add-account-user');
|
||||
var passInput = document.getElementById('email-add-account-password');
|
||||
var errorDiv = document.getElementById('email-add-account-error');
|
||||
if (!btn)
|
||||
return;
|
||||
|
||||
function submit() {
|
||||
errorDiv.textContent = '';
|
||||
btn.disabled = true;
|
||||
post('/email/connect', { user: userInput.value, password: passInput.value })
|
||||
.then(function(res) {
|
||||
btn.disabled = false;
|
||||
if (!res.ok) {
|
||||
errorDiv.textContent = res.error || 'Could not connect.';
|
||||
return;
|
||||
}
|
||||
var newUser = userInput.value;
|
||||
userInput.value = '';
|
||||
passInput.value = '';
|
||||
document.getElementById('email-add-account-form').style.display = 'none';
|
||||
document.getElementById('email-add-account-link').style.display = 'block';
|
||||
resetViewForActiveAccount(newUser);
|
||||
})
|
||||
.catch(function() {
|
||||
btn.disabled = false;
|
||||
errorDiv.textContent = 'Connection request failed.';
|
||||
});
|
||||
}
|
||||
|
||||
btn.addEventListener('click', submit);
|
||||
passInput.addEventListener('keydown', function(e) {
|
||||
if (e.key === 'Enter') submit();
|
||||
});
|
||||
}
|
||||
|
||||
function renderMessage(msg) {
|
||||
var pane = document.getElementById('email-reading-pane');
|
||||
pane.innerHTML =
|
||||
'<div class="email-header">' +
|
||||
'<div><b>From:</b> ' + escapeHtml(msg.from) + '</div>' +
|
||||
'<div><b>To:</b> ' + escapeHtml(msg.to) + '</div>' +
|
||||
'<div><b>Subject:</b> ' + escapeHtml(msg.subject || '(no subject)') + '</div>' +
|
||||
'<div><b>Date:</b> ' + escapeHtml(msg.date) + '</div>' +
|
||||
'</div>' +
|
||||
'<div class="email-body-container"></div>' +
|
||||
'<div class="email-actions">' +
|
||||
'<button type="button" id="email-flag-btn" class="icon-btn' + (msg.flagged ? ' icon-btn-active' : '') +
|
||||
'" title="' + (msg.flagged ? 'Unflag' : 'Flag') + '">' + ICONS.flag + '</button>' +
|
||||
'<button type="button" id="email-delete-btn" class="icon-btn" title="Delete">' + ICONS.trash + '</button>' +
|
||||
'</div>';
|
||||
|
||||
// HTML-formatted mail renders in a sandboxed iframe, never via
|
||||
// innerHTML into this page directly - the body content is whatever
|
||||
// a third party sent, and this page runs as the logged-in user
|
||||
// with real session cookies. `allow-same-origin` alone (no
|
||||
// `allow-scripts`, no `allow-forms`, no `allow-popups`, no
|
||||
// `allow-top-navigation`) still blocks every dangerous thing
|
||||
// untrusted HTML could do - scripts simply do not run without
|
||||
// allow-scripts, full stop, regardless of same-origin access - it
|
||||
// ONLY additionally lets THIS PAGE read the iframe's own rendered
|
||||
// content height back out (contentDocument), which the very first,
|
||||
// fully-opaque `sandbox=""` version couldn't do at all. That's
|
||||
// needed to size the iframe to its actual content below, rather
|
||||
// than a fixed height with its own internal scrollbar sitting
|
||||
// inside the reading pane's own scrollbar - two nested scrollbars
|
||||
// for one piece of content, confusing regardless of how tall the
|
||||
// fixed box happened to be. Building it via createElement + the
|
||||
// .srcdoc PROPERTY (not a string-concatenated HTML attribute)
|
||||
// sidesteps any need to hand-escape the content for attribute-
|
||||
// safety - the DOM API does that correctly on its own. Plain-text
|
||||
// mail keeps using .textContent, same reasoning.
|
||||
var bodyContainer = pane.querySelector('.email-body-container');
|
||||
if (msg.isHtml) {
|
||||
var frame = document.createElement('iframe');
|
||||
frame.className = 'email-body-frame';
|
||||
frame.setAttribute('sandbox', 'allow-same-origin');
|
||||
frame.setAttribute('scrolling', 'no');
|
||||
frame.addEventListener('load', function() {
|
||||
try {
|
||||
var doc = frame.contentDocument;
|
||||
if (doc && doc.documentElement)
|
||||
frame.style.height = Math.max(doc.documentElement.scrollHeight, doc.body.scrollHeight) + 'px';
|
||||
} catch (e) {
|
||||
// Left at its CSS fallback height - still shows the content,
|
||||
// just with its own scrollbar if that fallback runs short.
|
||||
}
|
||||
});
|
||||
frame.srcdoc = msg.body;
|
||||
bodyContainer.appendChild(frame);
|
||||
} else {
|
||||
var textDiv = document.createElement('div');
|
||||
textDiv.className = 'email-body';
|
||||
textDiv.textContent = msg.body;
|
||||
bodyContainer.appendChild(textDiv);
|
||||
}
|
||||
|
||||
document.getElementById('email-flag-btn').addEventListener('click', function() {
|
||||
post('/email/flag', {
|
||||
folder: currentFolder,
|
||||
uid: msg.uid,
|
||||
flag: '\\Flagged',
|
||||
set: msg.flagged ? 'no' : 'yes'
|
||||
}).then(function() {
|
||||
loadMessageList();
|
||||
openMessage(msg.uid);
|
||||
});
|
||||
});
|
||||
|
||||
document.getElementById('email-delete-btn').addEventListener('click', function() {
|
||||
if (!window.confirm('Delete this message?')) return;
|
||||
post('/email/delete', { folder: currentFolder, uid: msg.uid }).then(function() {
|
||||
currentUid = null;
|
||||
document.getElementById('email-reading-pane').innerHTML =
|
||||
'<div id="email-empty-state">Select a message to read it.</div>';
|
||||
loadMessageList();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Opening a message is the reading pane's own concern - it fetches
|
||||
// and renders itself via /email/message and nothing else. It used to
|
||||
// also call loadMessageList() afterward (re-fetching and
|
||||
// re-rendering the ENTIRE list, every single time a message was
|
||||
// opened) just to pick up the \Seen flag the server already set as a
|
||||
// side effect of fetching the body - that's a locally-known update
|
||||
// (we know which uid was just opened), applied straight to the
|
||||
// already-rendered row below instead of paying for a second full
|
||||
// round trip and list re-render on every click.
|
||||
function openMessage(uid) {
|
||||
currentUid = uid;
|
||||
var pane = document.getElementById('email-reading-pane');
|
||||
var rows = document.querySelectorAll('.email-row');
|
||||
var wasUnread = false;
|
||||
for (var i = 0; i < rows.length; i++) {
|
||||
var isTarget = parseInt(rows[i].getAttribute('data-uid'), 10) === uid;
|
||||
rows[i].classList.toggle('selected', isTarget);
|
||||
if (isTarget) {
|
||||
wasUnread = rows[i].classList.contains('unread');
|
||||
// Marked read the instant it's selected, not after the fetch
|
||||
// resolves - fetchMessage() marks it \Seen server-side anyway
|
||||
// (BODY[] rather than BODY.PEEK[]), so there's nothing
|
||||
// optimistic about this beyond removing the visual lag.
|
||||
rows[i].classList.remove('unread');
|
||||
}
|
||||
}
|
||||
if (wasUnread) {
|
||||
for (var k = 0; k < currentMessages.length; k++) {
|
||||
if (currentMessages[k].uid === uid)
|
||||
currentMessages[k].seen = true;
|
||||
}
|
||||
updateListCount(currentMessages);
|
||||
loadFolderCounts();
|
||||
}
|
||||
|
||||
// Same fade-out/fetch-concurrently/fade-in shape as spa.js's own
|
||||
// navigate() - a minimum-duration fade (via delay()) runs alongside
|
||||
// the fetch rather than after it, so a fast response still shows
|
||||
// the full transition instead of a flash, and a slow one doesn't
|
||||
// wait any longer than the fetch itself already takes.
|
||||
pane.classList.add('email-fading');
|
||||
Promise.all([
|
||||
post('/email/message', { folder: currentFolder, uid: uid }),
|
||||
delay(180)
|
||||
])
|
||||
.then(function(results) {
|
||||
var res = results[0];
|
||||
if (!res.ok && res.error) {
|
||||
pane.innerHTML = '<div id="email-empty-state">' + escapeHtml(res.error) + '</div>';
|
||||
} else {
|
||||
renderMessage(res);
|
||||
}
|
||||
pane.classList.remove('email-fading');
|
||||
})
|
||||
.catch(function(err) {
|
||||
console.error('openMessage failed:', err);
|
||||
pane.innerHTML = '<div id="email-empty-state">Could not load message' +
|
||||
(err && err.message ? ': ' + escapeHtml(err.message) : '.') + '</div>';
|
||||
pane.classList.remove('email-fading');
|
||||
});
|
||||
}
|
||||
|
||||
// Up/Down moves through the message list and opens whatever it
|
||||
// lands on - registered once, unconditionally, at load time (same
|
||||
// always-on-but-internally-guarded shape as spa.js's own document-
|
||||
// level click listener) rather than added/removed each time the
|
||||
// client view is (re)shown, so reconnecting never stacks up
|
||||
// duplicate handlers. Bails out immediately whenever the client
|
||||
// view isn't actually showing (the connect form has no .email-row
|
||||
// elements at all) or the keystroke is really meant for a form
|
||||
// field (a future compose/search input, say) rather than list
|
||||
// navigation.
|
||||
document.addEventListener('keydown', function(e) {
|
||||
var active = document.activeElement;
|
||||
if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA'))
|
||||
return;
|
||||
|
||||
// Delete trashes whichever message is currently open, the same
|
||||
// action (and the same dissolve-and-slide-up animation) as
|
||||
// clicking that row's own trash button - see trashMessage().
|
||||
if (e.key === 'Delete') {
|
||||
if (!document.getElementById('email-client') || currentUid === null)
|
||||
return;
|
||||
e.preventDefault();
|
||||
trashMessage(currentUid);
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp')
|
||||
return;
|
||||
var rows = document.querySelectorAll('.email-row');
|
||||
if (!rows.length)
|
||||
return;
|
||||
e.preventDefault();
|
||||
|
||||
var index = -1;
|
||||
for (var i = 0; i < rows.length; i++) {
|
||||
if (parseInt(rows[i].getAttribute('data-uid'), 10) === currentUid) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (e.key === 'ArrowDown')
|
||||
index = (index === -1) ? 0 : Math.min(index + 1, rows.length - 1);
|
||||
else
|
||||
index = (index === -1) ? 0 : Math.max(index - 1, 0);
|
||||
|
||||
rows[index].scrollIntoView({ block: 'nearest' });
|
||||
openMessage(parseInt(rows[index].getAttribute('data-uid'), 10));
|
||||
});
|
||||
|
||||
if (document.getElementById('email-connect-form')) {
|
||||
wireConnectForm();
|
||||
} else if (document.getElementById('email-client')) {
|
||||
wireClientView();
|
||||
wireAddAccountForm();
|
||||
syncActiveFolder();
|
||||
loadMessageList();
|
||||
loadAccounts();
|
||||
}
|
||||
})();
|
||||
|
After Width: | Height: | Size: 132 KiB |