Compare commits

..
19 Commits
Author SHA1 Message Date
brad ArantandClaude Opus 5.5 2847ce5fa7 Add jetc --lint-sql to find <sql> that pastes values (phase 2)
Implements phase 2 of docs/design-sql-bound-parameters.md. jetc --lint-sql
[--strict] <file|dir>... lists each <sql> whose statement contains a $[...]
or #[...] reference instead of a <bind>, with file:line and where each value
comes from. Row values ($[.col], $[session.col], $[?N], $[#]) are only
reported with --strict. References in <bind>, <if>, <set> and the other
attribute-only tags, <comment> and |> <| are skipped. A custom tag defined
as <sql><container></sql> (barant.com's <showtable>) is checked at each use.
Exit status is 0 for none found, 1 for findings, 2 for an unreadable path.

- jetc/JetLint.*: the scanner; jetc.cpp: the option
- build scripts and runbindtests.sh: link JetLint.cpp
- tests/runlinttests.sh and tests/lintsql/: fixtures and expected output
- docs: worklist for the local copies of both sites, design doc status,
  manual note on the lint

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:29:28 -08:00
brad ArantandClaude Opus 5.5 fd81bb877f Document <bind> and bound parameters in the user manual
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:22:50 -08:00
brad ArantandClaude Opus 5.5 cfdb3cbf57 Avoid a trigraph warning in the SqlBind unit test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 20:22:03 -08:00
brad ArantandClaude Opus 5.5 3c6411c16e Error on unterminated tags instead of looping forever
The Tag constructor's attribute loop made no progress at end of data, so
a tag that never closed - such as <set value="a\"> with its closing quote
escaped - hung jet-2.0. Throw "unterminated <name> tag." at end of data,
and "unterminated value for X in <name>." when an attribute value's
closing quote is missing.

Needs CoreUtils with the getTokenExclude fix for <set value="a\\">.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:57:51 -08:00
brad ArantandClaude Opus 5.5 a18d1358b0 Add <bind> bound parameters for <sql> (phase 1)
Implements phase 1 of docs/design-sql-bound-parameters.md: <bind> supplies
the value for the next ? placeholder of the enclosing <sql>, with typed
validation (int, decimal, date, datetime, bool, ident with allow list),
null="empty", and refusal to change the connection character set.

- SqlBind.*: MySQL-free placeholder scanning and binding logic
- __bind.*, __sql, __mysql: runtime wiring
- Tag.cpp, jetc/JetParser.cpp: bind is a void tag in both
- jetc/JetCodegen: emit sized ZString literals for text holding a NUL,
  which previously truncated the compiled page
- tests: unit tests, end-to-end test against MySQL (interpreted and
  jetc-compiled), and the generator for the binary test page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:55:23 -08:00
brad Arant 9fae14eb96 Merge branch 'fix-missing-libssl-link' 2026-11-20 19:37:33 -08:00
Brad ArantandClaude Opus 5.5 ec3e40b71a Add ltrim and rtrim expression functions
ltrim(x) removes leading blanks and rtrim(x) removes trailing blanks,
using the same characters trim removes (space, tab, newline). rtrim
counts by index so an all-blank value becomes empty. The manual now
documents trim, ltrim and rtrim with examples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 15:07:33 +00:00
Brad ArantandClaude Opus 5.5 5f9a53aba2 Fix nested tags hiding a marker right after their close
Tag::ifNested(in) returned false after skipping a nested same-name tag
(or, for if/while/until/ifrow, a nested one of the others), so both
callers also nextChar()ed and skipped the first character after it.
A marker right after the nested close was never seen: </if></if> lost
the outer end and swallowed the rest of the content, </if><else> lost
the else, and </try><catch> lost the outer catch, so an error raised
inside an inner catch block vanished silently. Return true instead.

Tested with the jet CLI (old vs new on 15 cases) and a test server on
port 8443: all 87 pages on both sites render the same apart from blank
lines, and nested try/catch tests pass on the live site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 02:18:39 +00:00
Brad ArantandClaude Opus 5.5 fdcb2b43a9 Keep <catch> attributes so <catch name="err"> stores the error
The split-tag scanner skipped the attributes on <catch ...>, so
<catch name="err"> never stored the error text and every caught error
read as "". Keep them in Tag::splitKeywords, and have <try> use the
catch tag's name and scope when the try tag itself has no name.

Tested live on barant.com: <catch name> and <try name> both store the
error, including scope="session" and single-quoted attributes; the
catch block still runs; no error leaves the name unset; nested tries
catch body errors at the right level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 01:51:04 +00:00
Brad ArantandClaude Opus 5.5 08462ca996 Add scope="session" to <set>; replace setenv with it
<set name="x" value="..." scope="session"> now writes x to the session
file (any name, no @ prefix); values are still read with $[@x].
storeVariable passes the scope through instead of repeating the
global/local/parent checks for each value source.

Convert every <setenv> use on barant-site and qualityiron-site to a
plain <set> plus a scope="session" <set>, which keeps same-request
$[name] reads working, and remove setenv from both SESSIONCTL.tag
copies (sessionctl is deprecated for session management).

Document session variables and the set tag scopes in the Jet manual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 01:46:36 +00:00
Brad ArantandClaude Sonnet 5 867ace3cb3 Give jetc a dedicated, fully inert <comment> handler at compile time
<comment> had no special-case in jetc's compiler at all - it fell
through to parseFallback(), the generic unknown-tag path, which hunts
for a tag's own closing tag via scanBody()/skipQuotedValue(), the same
quote-aware, backslash-escape-interpreting scanning real Jet attribute
syntax needs. A comment containing an explanatory " sequence (a JSON
example in prose, say) or a literal <else>/<if>-looking word - both
already confirmed, separately, to corrupt jetc when they turn up
inside a JS // comment - hit the exact same corruption here too, just
triggered from inside a <comment> block instead.

Added skipCommentTag(), which only tracks same-tag-name nesting depth
via the existing case-insensitive matchTagOpen/matchTagClose and
otherwise ignores every character - no quote tracking, no other-tag
recognition, nothing a comment's own body could ever trip over. Wired
into parseNodes() alongside the other recognized top-level tags;
unlike those, it pushes no node at all; the comment contributes
nothing to the compiled output, matching the runtime interpreters own
__comment behavior but now safe at compile time too.

Verified directly: a scratch .jet with five <comment> blocks (plain,
a bare quote, a backslash-quote JSON example, literal <else>/<if>
text, and nested comments with their own quotes) all compiled clean
and left zero trace in the generated code, with the <if> immediately
following them compiling correctly too - confirming nothing after a
tricky comment gets corrupted either.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-10 16:49:53 +00:00
Brad ArantandClaude Sonnet 5 b8f7793773 Add global music player, invoicing/payment system, account subpages, mail account admin, and the qualityiron.vegas Jet 2.0 port
Jet interpreter (Tag.cpp, __call.cpp, __imap*.cpp/h, __smtpsend.cpp/h,
__imapemptyfolder.cpp/h - new): assorted parser/tag fixes found across
this work - a stray literal-tag-in-comment and backslash-quote parser
corruption class, a dangling-pointer fix, a __call.cpp fd leak, IMAP
folder-management tags, multi-account/per-host IMAP support, and a
smtpsend Message-ID fix.

barant.com site (jetc/barant-site/):
- A site-wide persistent music player (header band, playlist/queue,
  stereo FFT EQ, session-persisted state) fed by new library/
  ianslibrary/music song-list subpages.
- /account split into info/phones/invoices subpages; a full invoicing
  and Square payment system (create/edit/copy/pay/email invoice);
  admin invoice management and mail-account management subpages.
- /services split into overview/hosting/siptrunking/documents
  subpages, retiring the old standalone pages.
- SIPPHONE.tag: a Jet 2.0 WebRTC softphone tag.
- main.css/spa.js/email.js: the SPA loading indicator, the music
  player band styling, and assorted fixes accumulated alongside this
  work.

qualityiron-site/: the qualityiron.vegas job/contractor/customer/
document management app, ported from its original Jet 1.4 codebase to
Jet 2.0 as barant.coms APIServers second multi-tenant site.

wcwc/wcwc.jet: the WCWC site Jet source (wcwc.jtc build output not
included).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 17:42:01 +00:00
Brad ArantandClaude Sonnet 5 905fbafa5a Fix <sql> silent-failure bug; split /vst into overview + subpage; misc site fixes
- __mysql.cpp: <sql> never checked mysql_real_query's own return code,
  so a genuine query failure was indistinguishable from "ran fine, zero
  rows" - <try>/<catch> around a failing <sql> never actually caught
  anything anywhere. Now throws on a real failure.
- spa.js: dynamically re-injected scripts now run in true sequential
  order (wait for each external script's load event before running the
  next), fixing checkout's Square card field never building on the
  first client-side navigation to /checkout (only after a refresh) -
  async=false alone only orders multiple external scripts relative to
  each other, it doesn't delay a plain inline sibling.
- /vst split into a real overview + /vst/modular1 subpage with a left
  menu, reusing opensource.page's existing subpage-tier pattern
  (opensource.menu/main.css's submenuitem-active highlighting, and
  several other subpage-tier retirements, were already finished earlier
  this session but never committed - included here too).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-13 15:14:25 +00:00
brad ArantandClaude Sonnet 5 9d965bfd1a Fix jet-2.0 link failure: add missing -lssl
The __imap tag (added for the /email webmail client) calls real
SSL_CTX_*/SSL_connect() functions, which live in libssl - not libcrypto
(a separate, lower-level library providing only crypto primitives).
compile only ever linked -lcrypto, so a build from a completely fresh
checkout fails at the final link step:

  __imap.o: undefined reference to symbol 'SSL_CTX_free@@OPENSSL_3.0.0'

Reproduced building fresh on a brand-new server (nothing else installed
yet) rather than an incremental rebuild against an already-linked
jet-2.0, which is presumably why this went unnoticed - barant.com's own
production jet-2.0 was likely last linked before __imap needed real SSL
session functions, or was patched by hand at the time without this fix
landing in the committed script.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-08 21:32:48 -07:00
Brad Arant 46ef67b735 Bump email.js cache-buster for pagination change 2026-09-07 04:20:53 +00:00
Brad Arant 41fbf0b7d9 Add pagination to the email list (was hardcoded to newest 50, no way to see older mail)
listMessages() only ever fetched everything then kept the newest
limit (default 50) messages, with no offset parameter and no way for
the client to know how many messages existed beyond what it was
shown - older mail was completely unreachable through the webmail UI.

__imap::listMessages() now takes an offset (counted back from the
newest message) and returns {"total":N,"messages":[...]} instead of
a bare array, so the client can page backward/forward and know when
it has reached either end. __imaplist tag and /email/list both pass
offset through; /email/search is unchanged (search results are not
paginated). email.js tracks currentOffset (reset alongside
currentFolder/currentUid at every existing reset site), and renders
Prev/Next controls next to the unread count showing the current
1-based range and total.
2026-09-07 04:20:42 +00:00
Brad Arant dcfe2a667c Restyle htmleditor.page to match site theme, remove email disconnect button
htmleditor.page previously used hardcoded blue/gray Windows-95-era
inline styles (#678, #abc, #808080, #def) totally disconnected from
the site current dark/gold Bond theme (main.css --bond-* variables) -
this is what showed up as "the old page with the blue stylesheet"
when opening a file to edit. Restyled the window chrome, toolbar,
title bar, and buttons to use the same custom properties/.button
class the rest of the site uses; left the #mainpage content-preview
canvas white since it renders the actual page being edited.

email.js: removed the Disconnect button/handler and its unused icon
from the email toolbar per request. Bumped its cache-buster in
admin-email.subpage.
2026-09-07 04:09:12 +00:00
Brad Arant c1491b044b Add IMAP webmail tag, admin/opensource subpage tiers, store/cart, htmleditor, uploads
New __imap*/__smtpsend/__eval Jet tags give templates real IMAP
(list/message/flag/delete/move/search/folders/accounts) and SMTP-send
capability, backing the new /email webmail client (email.jet/
email.menu, assets/images/email.js + newemail.js) and its
mainpagetemplate.jet-based page shell. Most of this tag family's
source was already being built into the live site (Tag.cpp already
registered __imap/__imaplist/__imapmessage/__imapflag/__imapdelete/
__eval) but had never actually been committed; this also registers
and commits the remaining five (__imapmove/__imapfolders/
__imapsearch/__smtpsend/__imapaccounts).

admin.page/admin.menu gain a real subpage tier (admin-email,
admin-newemail, admin-invoices, admin-products, admin-users) replacing
several previously top-level pages, mirrored by a similar
opensource.page subpage tier (opensource-overview/asm1802/barantmail/
jet/serverframework/synthmax) - old top-level pages retired via git
rename (asm1802.page, jet.page, serverframework.page,
admin_invoices.page); barantmail.page is dropped outright, folded into
opensource-barantmail.subpage.

New storefront (store.page, store-createstore.subpage,
barantstore.page) and cart flow (cart.jet, updatecartqty.proc,
removecartitem.proc, editproduct.page/selectproduct.proc/
update_product.proc for inventory maintenance against the barant
database).

New document upload/download manager (documents.jet, documents_api.jet,
documents_upload.proc, documents_delete.proc,
assets/images/documents.js + documents-page.js) with a persistent
floating panel, and a rich-text page editor (htmleditor.jet/.page,
createhtmleditor.proc, savehtmleditor.proc, assets/images/htmleditor.js
+ its icon/logo assets).

SESSIONCTL.tag: login now redirects back to the originally-requested
page instead of always landing on /account ($[start:0] vs $[start]
variable-name mismatch).

main.css/menu.bar/invoices.menu/jet_overview.section/login.menu:
styling and navigation updates for the above; new site assets (fonts,
images, audio) referenced by them.

jetc/build-assets.sh, list_jet_files.sh, lowercase_jet.py,
strip_fragments.py: small dev tooling used while building the above.
2026-09-06 04:14:00 +00:00
Brad Arant b0cadc3f08 Multi-day accumulated fixes: tag dispatch, session/pooling correctness, SPA rollout, jetc compiler
JetCore engine (Tag.cpp/.h, Global.cpp/.h, __*.cpp tag classes):
- Numerous __mysql.cpp connection-pooling correctness fixes (stale
  result sets, double-indirection sessionid bugs, field caching,
  pool keying) and a session-registration-before-connection-confirmed
  ordering fix (dangling pointer on a failed connect)
- Tag.cpp: large body of fixes to the tag-dispatch/container-scanning
  logic (bare-name fallback, database aliasing, single-quote handling,
  @-prefix session variable resolution, TAGDEF caching, nested split-tag
  scanning for if/while/until/ifrow so an inner one doesn't corrupt an
  outer one's own boundary scan) plus the process-first rendering
  order fix (a <process> now runs before <checksession>/page
  resolution, fixing a real "blank page after successful login" bug)
- Global.h/.cpp: added imapSessions (parallel to the existing __mysql*
  session map) for the new <imap> tag family
- __whiledir.cpp/__include.cpp: caching and directory-name-aliasing
  fixes
- __call.cpp/.h: fixed a dangling-pointer bug
- __write.cpp: fixed an O_WRONLY-only open that couldn't create a new
  file
- __ifrow.cpp/__sql.cpp: fixed the same sessionid double-indirection
  bug __mysql.cpp had (resolveKeyword's result was being used as a map
  key lookup instead of the resolved value itself)

jetc compiler (jetc/JetParser.cpp/.h, JetCodegen.cpp/.h, JetAST.h,
jetc.cpp, build-shared.sh, build-compiled.sh):
- Parser fixes: inline <include>, nested-quote handling, void-tag
  recognition
- Codegen fixes and expanded AST support
- build-shared.sh: atomic rename into place for a freshly-built .jtc
  (a live server dlopen()ing the same path mid-rebuild was corrupting
  its own already-mapped view of the old file) and a staleness check
  so a cached JetCore .o doesn't silently keep serving yesterday's
  fixes forever
- Added -lssl to both build scripts' link lines (needed once the new
  <imap> tag's client-side TLS code existed - previously nothing in
  this codebase used OpenSSL's SSL/TLS client API, only libcrypto)

Site content (jetc/barant-site/): SPA (fetch-and-swap navigation)
rollout across essentially every .page/.jet/.section/.tag/.proc/.method
file - dynamic-content fixes, fragment-mode stripping, native
$[@name] session variables replacing older mechanisms, and this
session's own checkout.page redesign, login start-param redirect fix,
and per-page side-menu (menu.bar/$[PAGE].menu) refresh support.
Completed the earlier main.css/control.css move from assets/ to
assets/images/ (git still showed the old paths as tracked-but-deleted
until now).

Deliberately left out of this commit: dozens of .pre-<description>-
<date> manual backup files (this session's and earlier ones' own
before/after snapshots, not meant for permanent history), compiled
.jtc build outputs, ad hoc test binaries and scripts under jetc/
(login_asan, wcwc_test, optest2_bin, etc.), and jetc/__pycache__/ -
none of these are meant to be tracked; a .gitignore covering them
would be worth adding separately.
2026-09-03 05:20:48 +00:00
678 changed files with 27956 additions and 3560 deletions

No files matched your search

+2
View File
@@ -35,3 +35,5 @@ jetc/libCoreUtils_pic.a
jetc/barant-site/jet/vst.jet
jetc/barant-site/jet/modular1.jet
jetc/barant-site/jet/modular1_patches.jet
jetc/**/*.jtc
jetc/__pycache__/
+22
View File
@@ -1,8 +1,10 @@
#include "Global.h"
#include "Exception.h"
#include "__mysql.h"
#include "__imap.h"
#include <iostream>
#include <stdlib.h>
#include <cstdio>
namespace jet {
@@ -44,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.");
+29 -1
View File
@@ -11,7 +11,9 @@
namespace jet {
class __mysql;
class __imap;
class Tag;
class Global {
public:
@@ -23,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);
@@ -55,10 +61,32 @@ namespace jet {
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;
};
+232 -4
View File
@@ -6,6 +6,8 @@
#include <time.h>
#include <chrono>
#include <cmath>
#include <vector>
#include <random>
namespace jet {
@@ -27,8 +29,73 @@ namespace jet {
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.");
@@ -58,6 +125,58 @@ namespace jet {
} 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(")")) {
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.");
@@ -106,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.");
@@ -384,7 +533,10 @@ namespace jet {
string.removeTrailingZeros();
} else
throw coreutils::Exception("Expecting ) at end of FLOOR expression.");
} else if(in.ifNextIgnoreCase("UNIXTIME")) {
} 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(")")) {
@@ -396,6 +548,59 @@ namespace jet {
} else
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.");
@@ -437,8 +642,19 @@ 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.");
@@ -645,7 +861,19 @@ namespace jet {
throw coreutils::Exception("operand is not a number.");
} else
throw coreutils::Exception("operand is not a number.");
}
}
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;
}
+305
View File
@@ -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 &)> &quoteEscape) {
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;
}
}
+64
View File
@@ -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 &)> &quoteEscape);
// 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
+848 -100
View File
File diff suppressed because it is too large. Load diff
+37
View File
@@ -72,6 +72,20 @@ namespace jet {
// 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;
@@ -106,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;
};
}
+29
View File
@@ -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));
}
}
+21
View File
@@ -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
+87 -32
View File
@@ -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);
}
}
}
}
+20 -4
View File
@@ -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
+35 -6
View File
@@ -3,12 +3,22 @@
namespace jet {
__dotag::__dotag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
__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
@@ -28,10 +38,29 @@ namespace jet {
// this invocation was written.
hasContainer = true;
coreutils::ZString container3;
if(!findTagDefinition(name, container3))
throw coreutils::Exception("tag definition not found.");
processContainer(container3, container);
// 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);
}
}
}
+43
View File
@@ -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);
}
}
}
+21
View File
@@ -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
+3 -3
View File
@@ -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;
}
}
+36 -14
View File
@@ -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();
}
}
}
}
+1 -1
View File
@@ -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") &&
+26 -6
View File
@@ -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);
}
}
+1133
View File
File diff suppressed because it is too large. Load diff
+123
View File
@@ -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
+163
View File
@@ -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);
}
}
}
+70
View File
@@ -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
+25
View File
@@ -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);
}
}
+25
View File
@@ -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
+26
View File
@@ -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);
}
}
+26
View File
@@ -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
+32
View File
@@ -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);
}
}
+26
View File
@@ -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
+16
View File
@@ -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();
}
}
+27
View File
@@ -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
+31
View File
@@ -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);
}
}
+30
View File
@@ -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
+25
View File
@@ -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);
}
}
+25
View File
@@ -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
+29
View File
@@ -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);
}
}
+29
View File
@@ -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
+22
View File
@@ -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);
}
}
+27
View File
@@ -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
+85 -16
View File
@@ -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);
}
}
}
+226 -25
View File
@@ -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.");
}
+30 -5
View File
@@ -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";
+243
View File
@@ -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}"));
}
}
+70
View File
@@ -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
+29 -5
View File
@@ -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));
}
}
+13 -4
View File
@@ -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
+13 -4
View File
@@ -2,7 +2,7 @@
#include "Exception.h"
namespace jet {
__tag::__tag(coreutils::ZString &in, coreutils::MString &parentOut, Global &global, Tag *parent, Tag *local) : Tag(in, parentOut, global, parent, local) {
evaluate = false;
output = false;
@@ -29,10 +29,19 @@ namespace jet {
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[keywords["name"]] = container;
scope->localTags[tagName] = container;
else
global.tags[keywords["name"]] = container;
global.tags[tagName] = container;
}
}
+4
View File
@@ -30,9 +30,13 @@ namespace jet {
// 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);
}
+2 -2
View File
@@ -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)) ||
+2 -2
View File
@@ -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)) ||
+94 -29
View File
@@ -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());
}
}
}
+26 -7
View File
@@ -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;
}
}
}
+35 -5
View File
@@ -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);
+1 -1
View File
@@ -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"
BIN
View File
Binary file not shown.
+168 -6
View File
@@ -95,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}
@@ -120,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.
@@ -234,6 +263,15 @@ 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}
@@ -241,7 +279,16 @@ the first parameter then the entire parameter is returned.
\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}
@@ -254,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.
@@ -299,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.
@@ -315,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.
@@ -488,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}
@@ -499,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
+238
View File
@@ -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.
+166
View File
@@ -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)
```
+19 -1
View File
@@ -8,7 +8,7 @@
namespace jetc {
enum class NodeKind {
TEXT, VAR, SET, IF, FOR, WHILE, FALLBACK
TEXT, VAR, SET, IF, FOR, WHILE, FALLBACK, TAGDEF, CONTAINER_SLOT
};
enum class CondMode { VALUES, EXPR };
@@ -55,6 +55,24 @@ namespace jetc {
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;
};
+181 -104
View File
@@ -32,6 +32,13 @@ namespace jetc {
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
@@ -49,124 +56,181 @@ namespace jetc {
return expr.c_str();
}
void Codegen::emitBody(const std::vector<NodePtr> &nodes, int indent) {
for (auto &n : nodes) emitNode(n, indent);
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) {
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;
out << I << "out << " << cstr(n->text) << ";\n";
target << I << "out << " << zstr(n->text) << ";\n";
break;
}
case NodeKind::VAR: {
out << I << "{ coreutils::ZString v(" << cstr(n->varText) << "); out << scope.getVariable(v, true); }\n";
target << I << "{ coreutils::ZString v(" << cstr(n->varText) << "); out << scope.getVariable(v, true); }\n";
break;
}
case NodeKind::SET: {
std::string k = id("set_");
out << I << "{\n";
out << I << " scope.keywords[\"" << k << "name\"] = " << cstr(n->setName) << ";\n";
out << I << " scope.keywords[\"" << k << "scope\"] = " << cstr(n->setScope) << ";\n";
out << I << " coreutils::MString val;\n";
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) {
out << I << " scope.keywords[\"" << k << "expr\"] = " << cstr(n->setExpr) << ";\n";
out << I << " val = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).string;\n";
target << I << " scope.keywords[\"" << k << "expr\"] = " << cstr(n->setExpr) << ";\n";
target << I << " val = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).string;\n";
} else {
out << I << " scope.keywords[\"" << k << "value\"] = " << cstr(n->setHasValue ? n->setValue : std::string()) << ";\n";
out << I << " val = scope.resolveKeyword(\"" << k << "value\");\n";
target << I << " scope.keywords[\"" << k << "value\"] = " << cstr(n->setHasValue ? n->setValue : std::string()) << ";\n";
target << I << " val = scope.resolveKeyword(\"" << k << "value\");\n";
}
out << I << " scope.assignVariable(scope.resolveKeyword(\"" << k << "name\"), val, scope.resolveKeyword(\"" << k << "scope\"));\n";
out << I << "}\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_");
out << I << "{\n";
out << I << " bool cond;\n";
target << I << "{\n";
target << I << " bool cond;\n";
if (n->cond.mode == CondMode::EXPR) {
out << I << " scope.keywords[\"" << k << "expr\"] = " << cstr(n->cond.expr) << ";\n";
out << I << " cond = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).boolean;\n";
target << I << " scope.keywords[\"" << k << "expr\"] = " << cstr(n->cond.expr) << ";\n";
target << I << " cond = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).boolean;\n";
} else {
out << I << " scope.keywords[\"" << k << "value1\"] = " << cstr(n->cond.value1) << ";\n";
out << I << " scope.keywords[\"" << k << "value2\"] = " << cstr(n->cond.value2) << ";\n";
out << I << " int rc = scope.resolveKeyword(\"" << k << "value1\").compare(scope.resolveKeyword(\"" << k << "value2\"));\n";
out << I << " cond = (" << staticTypeOp(n->cond.type, "rc") << ");\n";
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";
}
out << I << " if (cond) {\n";
emitBody(n->thenBody, indent + 2);
target << I << " if (cond) {\n";
emitBody(n->thenBody, indent + 2, target);
if (n->hasElse) {
out << I << " } else {\n";
emitBody(n->elseBody, indent + 2);
target << I << " } else {\n";
emitBody(n->elseBody, indent + 2, target);
}
out << I << " }\n";
out << I << "}\n";
target << I << " }\n";
target << I << "}\n";
break;
}
case NodeKind::FOR: {
std::string k = id("for_");
out << I << "{\n";
out << I << " scope.keywords[\"" << k << "start\"] = " << cstr(n->forHasStart ? n->forStart : std::string("0")) << ";\n";
out << I << " scope.keywords[\"" << k << "end\"] = " << cstr(n->forEnd) << ";\n";
out << I << " scope.keywords[\"" << k << "step\"] = " << cstr(n->forStep) << ";\n";
out << I << " double ix = scope.resolveKeyword(\"" << k << "start\").asDouble();\n";
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) {
out << I << " scope.keywords[\"" << k << "name\"] = " << cstr(n->forName) << ";\n";
out << I << " scope.keywords[\"" << k << "scope\"] = " << cstr(n->forScope) << ";\n";
target << I << " scope.keywords[\"" << k << "name\"] = " << cstr(n->forName) << ";\n";
target << I << " scope.keywords[\"" << k << "scope\"] = " << cstr(n->forScope) << ";\n";
}
out << I << " for (; ix <= scope.resolveKeyword(\"" << k << "end\").asDouble(); ix += scope.resolveKeyword(\"" << k << "step\").asDouble()) {\n";
target << I << " for (; ix <= scope.resolveKeyword(\"" << k << "end\").asDouble(); ix += scope.resolveKeyword(\"" << k << "step\").asDouble()) {\n";
if (n->forHasName) {
out << I << " coreutils::MString nameSel = scope.resolveKeyword(\"" << k << "name\");\n";
out << I << " coreutils::MString scopeSel = scope.resolveKeyword(\"" << k << "scope\");\n";
out << I << " if ((scopeSel == \"\") || (scopeSel == \"global\")) global.variables[nameSel] = ix;\n";
out << I << " else if (scopeSel == \"local\") scope.local->variables[nameSel] = ix;\n";
out << I << " else if (scopeSel == \"parent\") scope.parent->local->variables[nameSel] = ix;\n";
out << I << " else throw coreutils::Exception(\"scope value is not valid.\");\n";
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);
out << I << " }\n";
out << I << "}\n";
emitBody(n->body, indent + 2, target);
target << I << " }\n";
target << I << "}\n";
break;
}
case NodeKind::WHILE: {
std::string k = id("while_");
out << I << "{\n";
out << I << " bool cond;\n";
target << I << "{\n";
target << I << " bool cond;\n";
if (n->cond.mode == CondMode::EXPR) {
out << I << " scope.keywords[\"" << k << "expr\"] = " << cstr(n->cond.expr) << ";\n";
out << I << " coreutils::MString exprSaved = scope.keywords[\"" << k << "expr\"];\n";
out << I << " cond = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).boolean;\n";
out << I << " while (cond) {\n";
emitBody(n->body, indent + 2);
out << I << " scope.keywords[\"" << k << "expr\"].reset();\n";
out << I << " scope.keywords[\"" << k << "expr\"] = exprSaved;\n";
out << I << " cond = jet::Operand(scope.keywords[\"" << k << "expr\"], scope).boolean;\n";
out << I << " }\n";
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 {
out << I << " scope.keywords[\"" << k << "value1\"] = " << cstr(n->cond.value1) << ";\n";
out << I << " scope.keywords[\"" << k << "value2\"] = " << cstr(n->cond.value2) << ";\n";
out << I << " int rc = scope.resolveKeyword(\"" << k << "value1\").compare(scope.resolveKeyword(\"" << k << "value2\"));\n";
out << I << " cond = (" << staticTypeOp(n->cond.type, "rc") << ");\n";
out << I << " while (cond) {\n";
emitBody(n->body, indent + 2);
out << I << " int rc2 = scope.resolveKeyword(\"" << k << "value1\").compare(scope.resolveKeyword(\"" << k << "value2\"));\n";
out << I << " cond = (" << staticTypeOp(n->cond.type, "rc2") << ");\n";
out << I << " }\n";
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";
}
out << I << "}\n";
target << I << "}\n";
break;
}
case NodeKind::FALLBACK: {
out << I << "{ coreutils::ZString span(" << cstr(n->rawSpan) << "); scope.interpretSpan(span, out); }\n";
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;
}
}
@@ -177,6 +241,9 @@ namespace jetc {
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";
@@ -187,51 +254,61 @@ namespace jetc {
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.
out << "struct JetApiRoute { const char *method; const char *path; };\n";
out << "extern \"C\" const JetApiRoute *" << apiSymbol << "(int *count) {\n";
out << " static const JetApiRoute routes[] = {\n";
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)
out << " { " << cstr(r.method) << ", " << cstr(r.path) << " },\n";
out << " };\n";
out << " *count = " << apiRoutes.size() << ";\n";
out << " return routes;\n";
out << "}\n\n";
body << " { " << cstr(r.method) << ", " << cstr(r.path) << " },\n";
body << " };\n";
body << " *count = " << apiRoutes.size() << ";\n";
body << " return routes;\n";
body << "}\n\n";
}
out << "extern \"C\" void " << entrySymbol << "(jet::Global &global, coreutils::MString &out) {\n";
out << " coreutils::ZString jetc_empty(\"\");\n";
out << " coreutils::MString jetc_scopeOut;\n";
out << " jet::Tag scope(jetc_empty, jetc_scopeOut, global, NULL, NULL);\n";
emitBody(top, 1);
out << "}\n";
return out.str();
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();
}
out << "static void jetc_render(jet::Global &global, coreutils::MString &out) {\n";
out << " coreutils::ZString jetc_empty(\"\");\n";
out << " coreutils::MString jetc_scopeOut;\n";
out << " jet::Tag scope(jetc_empty, jetc_scopeOut, global, NULL, NULL);\n";
emitBody(top, 1);
out << "}\n\n";
out << "int main(int argc, char **argv, char **envp) {\n";
out << " jet::Global global(envp);\n";
out << " coreutils::MString out;\n";
out << " try {\n";
out << " jetc_render(global, out);\n";
out << " global.outputHeaders();\n";
out << " std::cout << out;\n";
out << " } catch(coreutils::Exception e) {\n";
out << " std::cout << out;\n";
out << " std::cout << \"\\n----- Error: \" << e.text << std::endl;\n";
out << " return 1;\n";
out << " }\n";
out << " return 0;\n";
out << "}\n";
return out.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();
}
}
+20 -2
View File
@@ -62,13 +62,31 @@ namespace jetc {
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++) + "_"; }
void emitBody(const std::vector<NodePtr> &nodes, int indent);
void emitNode(const NodePtr &n, int indent);
// 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);
};
+322
View File
@@ -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;
}
}
+57
View File
@@ -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
+347 -30
View File
@@ -1,6 +1,11 @@
#include "JetParser.h"
#include <cctype>
#include <stdexcept>
#include <set>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <cstdio>
namespace jetc {
@@ -29,37 +34,195 @@ namespace jetc {
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 (s.compare(nstart, p - nstart, name) != 0) return false;
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 {
std::string closer = "</" + name + ">";
return s.compare(at, closer.size(), closer) == 0;
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] == '>';
}
bool Parser::skipOpenTag(size_t &p) const {
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] == '"') {
p++;
while (p < s.size() && s[p] != '"') {
if (s[p] == '\\' && p + 1 < s.size()) p++;
p++;
}
if (p < s.size()) 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");
@@ -74,14 +237,40 @@ namespace jetc {
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 += 2;
if (starts("=")) {
pos += 1;
std::string val;
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() && 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++];
}
}
if (!eof()) pos++; // closing quote
attrs[aname] = val;
}
}
@@ -126,7 +315,40 @@ namespace jetc {
}
std::vector<NodePtr> Parser::parseSub(size_t start, size_t end) {
Parser sub(s.substr(start, end - start));
// 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();
}
@@ -146,21 +368,19 @@ namespace jetc {
}
NodePtr Parser::parseSet() {
size_t origStart = pos;
pos += 4; // "<set"
bool hasContainer;
auto attrs = parseAttrs(hasContainer);
if (hasContainer) {
// Container-form <set> (value comes from rendering nested content)
// isn't modeled by this prototype - fall back to full interpretation
// of the whole tag instead of failing to compile.
auto span = scanBody(pos, "set", false);
pos = span.first + 3 + 3; // "</set>"
auto n = std::make_shared<Node>();
n->kind = NodeKind::FALLBACK;
n->rawSpan = s.substr(origStart, pos - origStart);
return n;
}
// 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"] : "";
@@ -246,7 +466,7 @@ namespace jetc {
std::string tagName = peekTagName(pos);
size_t p = pos;
bool selfClosing = skipOpenTag(p);
if (!selfClosing) {
if (!selfClosing && !isVoidTag(tagName)) {
auto span = scanBody(p, tagName, false);
p = span.first + 3 + tagName.size();
}
@@ -257,6 +477,94 @@ namespace jetc {
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;
@@ -287,6 +595,15 @@ namespace jetc {
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;
+52 -2
View File
@@ -21,7 +21,19 @@ namespace jetc {
// gracefully instead of failing to compile.
class Parser {
public:
explicit Parser(const std::string &src) : s(src), pos(0) {}
// 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();
@@ -29,6 +41,9 @@ namespace jetc {
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;
@@ -42,7 +57,18 @@ namespace jetc {
// 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) const;
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);
@@ -54,6 +80,15 @@ namespace jetc {
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();
@@ -61,6 +96,21 @@ namespace jetc {
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++) + "_"; }
};
-24
View File
@@ -1,24 +0,0 @@
.controlframe {background: #888;
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: #bbb;
color: white;
border: 1pt solid white;
border-radius: 5px;
padding: 2px 10px 2px 10px;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 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();
})();
+178
View File
@@ -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();
});
})();
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

+881
View File
@@ -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&hellip;">' +
'<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();
}
})();
Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

@@ -0,0 +1,678 @@
function b64encode(str) {
return btoa(unescape(encodeURIComponent(str)));
}
function submitNewLetter(form) {
var name = document.getElementById('filename_display').value;
if (!/^[A-Za-z0-9_-]+$/.test(name)) {
alert('File name may only contain letters, numbers, underscores and hyphens.');
return false;
}
form.filename.value = name;
return true;
}
var mainpage;
var control;
var result;
var mousedownx;
var mousedowny;
var dragHint = "move";
var data;
var showGrid = false;
var snapToGrid = false;
var gridSize = 10;
var selected;
var firstSelected;
var itemparameters;
var grid;
var context;
var draggingHTML;
var window_dragging = false;
const undo = [];
var undoIndex = 0;
var lastRedo;
var mode = 'MOUSEUP';
var textobj;
var lastdragover;
var pendingDragover;
var dropIndicator;
var sequence = 0;
function showDropIndicator(target) {
if(!dropIndicator) {
dropIndicator = document.createElement('div');
dropIndicator.style.position = 'fixed';
dropIndicator.style.height = '4px';
dropIndicator.style.background = '#0088ff';
dropIndicator.style.zIndex = '99999';
dropIndicator.style.pointerEvents = 'none';
document.body.appendChild(dropIndicator);
}
let rect = target.getBoundingClientRect();
dropIndicator.style.left = rect.left + 'px';
dropIndicator.style.width = rect.width + 'px';
dropIndicator.style.top = (rect.top - 2) + 'px';
dropIndicator.style.display = 'block';
}
function hideDropIndicator() {
if(dropIndicator) {
dropIndicator.style.display = 'none';
}
}
function saveUndo() {
undo[undoIndex++] = mainpage.innerHTML;
}
function do_undo() {
if(undoIndex > 0) {
mainpage.innerHTML = undo[--undoIndex];
}
return true;
}
function do_redo() {
return true;
}
function init() {
mainpage = document.getElementById("mainpage");
data = document.getElementById("data");
itemparameters = document.getElementById("itemparameters");
var gridsize = document.getElementById("gridsize");
gridsize.value = gridSize;
grid = document.getElementById("grid");
context = grid.getContext("2d");
drawGrid();
buildToolbar();
document.designMode = 'off';
}
function getLayerMap(element) {
var map = '';
if(element.id != 'mainpage') {
var curelem = element;
while(curelem.id != 'mainpage') {
map = '&lt;' + curelem.nodeName + '&gt;' + map;
curelem = curelem.parentNode;
}
}
document.getElementById('map').innerHTML = map;
}
function jetEscape(text) {
return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function buildToolbar() {
let tbitems = [
{
"label": "&lt;div>",
"html": "<div id=\"newitem\" contenteditable=\"false\" style=\"width: 300px; height: 200px; background-color: #789;\"></div>"
},
{
"label": "&lt;input>",
"html": "<input id=\"newitem\" type=\"text\">"
},
{
"label": "&lt;button>",
"html": "<button id=\"newitem\" type=\"button\">Label</button>"
},
{
"label": "&lt;password>",
"html": "<input id=\"newitem\" type=\"password\">"
},
{
"label": "&lt;checkbox>",
"html": "<input id=\"newitem\" type=\"checkbox\">"
},
{
"label": "&lt;label>",
"html": "<label style=\"color: #000f;\" id=\"newitem\">Label text</label>"
},
{
"label": "&lt;p>",
"html": "<p style=\"color: #000f;\" id=\"newitem\">Type Here</p>"
},
{
"label": "&lt;hr>",
"html": "<hr id=\"newitem\">"
},
{
"label": "Jet: " + "$" + "[var]",
"html": "<code id=\"newitem\" contenteditable=\"true\" style=\"display:inline-block; background:#eef; border:1px dashed #99c; padding:4px; font-family:monospace; white-space:pre;\">" + jetEscape("$" + "[varname]") + "</code>"
},
{
"label": "Jet: &lt;set&gt;",
"html": "<code id=\"newitem\" contenteditable=\"true\" style=\"display:inline-block; background:#eef; border:1px dashed #99c; padding:4px; font-family:monospace; white-space:pre;\">" + jetEscape("<set name=\"varname\" value=\"\">") + "</code>"
},
{
"label": "Jet: &lt;if&gt;",
"html": "<code id=\"newitem\" contenteditable=\"true\" style=\"display:inline-block; background:#eef; border:1px dashed #99c; padding:4px; font-family:monospace; white-space:pre-wrap;\">" + jetEscape("<if value1=\"" + "$" + "[varname]\" value2=\"\" type=\"eq\">\ncontent\n</if>") + "</code>"
}
];
tbitems.forEach(doit);
function doit(currentValue, index) {
let index2 = index + 1;
let toolbar = document.getElementById('toolbar');
var itemHTML = '<button type="button" id="button' + index2;
itemHTML += '" style="width: 100%; height: 40px; border: 2px solid green;"';
itemHTML += '>' + currentValue.label + '</button>';
toolbar.insertAdjacentHTML("beforeend", itemHTML);
let id = 'button' + index2;
let button = document.getElementById(id);
button.html = currentValue.html;
button.addEventListener("mousedown",
(e) => {
e.preventDefault();
saveUndo();
draggingHTML = currentValue.html;
mainpage.insertAdjacentHTML('beforeend', draggingHTML);
let newEl = mainpage.lastElementChild;
newEl.style.position = 'absolute';
newEl.style.zIndex = '10000';
newEl.style.left = '0px';
newEl.style.top = '0px';
startNewItemDrag(newEl);
}
, false);
}
}
function startNewItemDrag(el) {
let rect = mainpage.getBoundingClientRect();
function ndMove(e) {
el.style.left = (e.clientX - rect.left - el.offsetWidth / 2) + 'px';
el.style.top = (e.clientY - rect.top - el.offsetHeight / 2) + 'px';
}
function ndUp(e) {
document.removeEventListener('mousemove', ndMove);
document.removeEventListener('mouseup', ndUp);
draggingHTML = null;
if((typeof selected !== 'undefined') && selected) {
selected.style.outline = '';
}
selected = el;
selected.style.outline = '2px solid #0088ff';
getLayerMap(selected);
displayParameters();
mode = "MOUSEUP";
}
document.addEventListener('mousemove', ndMove);
document.addEventListener('mouseup', ndUp);
}
function window_mousedown(win, e) {
mousedownx = e.offsetX;
mousedowny = e.offsetY;
if(e.offsetX >= (win.clientWidth - 3)) {
win.style.cursor = 'ew-resize';
window_dragging = true;
}
else {
win.style.cursor = 'default';
window_dragging = false;
}
}
function window_mousemove(win, e) {
}
function window_mouseup(win, e) {
}
function drawGrid() {
if(showGrid == true) {
context.clearRect(0,0,grid.width,grid.height);
context.lineWidth = 0.5;
context.strokeStyle = "#808080";
for(var ix = 0; ix < grid.width; ix += gridSize) {
context.beginPath();
context.moveTo(ix, 0);
context.lineTo(ix, grid.height);
context.stroke();
context.beginPath();
context.moveTo(0, ix);
context.lineTo(grid.width, ix);
context.stroke();
}
} else {
context.clearRect(0,0,grid.width,grid.height);
}
}
function resetDragHint(e) {
if(!selected) {
return;
}
if(selected.style.position == 'absolute') {
if((e.offsetX >= (parseFloat(selected.style.width) - 10)) && (e.offsetY >= (parseFloat(selected.style.height) - 10))) {
selected.style.cursor = "nwse-resize";
dragHint = "rightbottomresize";
} else if((e.offsetY < 10) && (e.offsetX >= (parseFloat(selected.style.width) - 10))) {
selected.style.cursor = "nesw-resize";
dragHint = "righttopresize";
} else if((e.offsetX <= 10) && (e.offsetY >= (parseFloat(selected.style.height) - 10))) {
selected.style.cursor = "nesw-resize";
dragHint = "leftbottomresize";
} else if((e.offsetX <= 10) && (e.offsetY <= 10)) {
selected.style.cursor = "nwse-resize";
dragHint = "lefttopresize";
} else if(e.offsetX >= (parseFloat(selected.style.width) - 10)) {
selected.style.cursor = "ew-resize";
dragHint = "rightresize";
} else if(e.offsetY >= (parseFloat(selected.style.height) - 10)) {
selected.style.cursor = "ns-resize";
dragHint = "bottomresize";
} else if(e.offsetX <= 10) {
selected.style.cursor = "ew-resize";
dragHint = "leftresize";
} else if(e.offsetY <= 10) {
selected.style.cursor = "ns-resize";
dragHint = "topresize";
} else {
selected.style.cursor = "move";
dragHint = "move";
}
} else {
if((e.offsetX >= (parseFloat(selected.style.width) - 10)) && (e.offsetY >= (parseFloat(selected.style.height) - 10))) {
selected.style.cursor = "nwse-resize";
dragHint = "rightbottomresize";
} else if(e.offsetX >= (parseFloat(selected.style.width) - 10)) {
selected.style.cursor = "ew-resize";
dragHint = "rightresize";
} else if(e.offsetY >= (parseFloat(selected.style.height) - 10)) {
selected.style.cursor = "ns-resize";
dragHint = "bottomresize";
} else {
selected.style.cursor = "move";
dragHint = "move";
}
}
}
function mousedown(e) {
let mouseabove = document.elementFromPoint(e.clientX, e.clientY);
if((typeof selected === 'undefined') || (selected != mouseabove)) {
mode = 'NEWSELECTION';
if((typeof selected !== 'undefined') && (selected.nodeName == "DIV")) {
document.designMode = 'off';
selected.contentEditable = false;
selected.blur();
selected.style.userSelect = 'none';
}
if((typeof selected !== 'undefined') && selected) {
selected.style.outline = '';
}
selected = mouseabove;
selected.style.outline = '2px solid #0088ff';
getLayerMap(selected);
} else {
if(mode != "TEXT") {
mode = "DOWNONSELECTED";
}
}
if(mode != 'TEXT') {
resetDragHint(e);
}
mousedownx = e.clientX;
mousedowny = e.clientY;
displayParameters();
return true;
}
function mouseup(e) {
if(mode == "TEXT") {
return true;
}
if(mode == "DOWNONSELECTED") {
if((selected.nodeName == "DIV") || (selected.nodeName == "CODE")) {
document.designMode = 'on';
selected.style.userSelect = 'auto';
selected.contentEditable = true;
selected.style.cursor = 'text';
selected.focus();
mode = "TEXT";
return true;
}
}
if(draggingHTML) {
draggingHTML = null;
}
if(selected && (mode == 'MOVED') && (selected.style.position == 'absolute')) {
selected.style.pointerEvents = 'none';
let dragover = document.elementFromPoint(e.clientX, e.clientY);
selected.style.pointerEvents = 'auto';
if(dragover.nodeName == 'DIV') {
if(dragover.id != selected.parentElement.id) {
dragover.appendChild(selected);
selected.style.left = ((selected.getBoundingClientRect().x + e.offsetX - mousedownx) - dragover.getBoundingClientRect().x) + 'px';
selected.style.top = ((selected.getBoundingClientRect().y + e.offsetY - mousedowny) - dragover.getBoundingClientRect().y) + 'px';
}
}
} else if(selected && (mode == 'MOVED') && pendingDragover) {
pendingDragover.prepend(selected);
selected.style.left = parseFloat(pendingDragover.style.left) + "px";
selected.style.top = parseFloat(pendingDragover.style.top) + "px";
}
pendingDragover = null;
hideDropIndicator();
mode = "MOUSEUP";
return true;
}
function mousemove(e) {
if(mode == "MOUSEUP") {
resetDragHint(e);
} else {
if(mode == "TEXT") {
return true;
}
if((selected.style.position == 'static') ||
(typeof selected.style.position === 'undefined') ||
(selected.style.position == '')) {
if(dragHint == "move") {
if(mode != "MOVED") {
mode = "MOVED";
}
selected.style.pointerEvents = 'none';
let dragover = document.elementFromPoint(e.clientX, e.clientY);
selected.style.pointerEvents = 'auto';
if(dragover.nodeName == 'DIV') {
pendingDragover = dragover;
showDropIndicator(dragover);
}
return true;
} else if(dragHint == "rightbottomresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.width = (parseFloat(selected.style.width) + e.movementX) + "px";
selected.style.height = (parseFloat(selected.style.height) + e.movementY) + "px";
} else if(dragHint == "rightresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.width = (parseFloat(selected.style.width) + e.movementX) + "px";
} else if(dragHint == "bottomresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.height = (parseFloat(selected.style.height) + e.movementY) + "px";
}
} else if(selected.style.position == 'absolute') {
if(dragHint == "move") {
if(mode != "MOVED") {
saveUndo();
mode = "MOVED";
}
selected.style.left = (parseFloat(selected.style.left) + e.movementX) + "px";
selected.style.top = (parseFloat(selected.style.top) + e.movementY) + "px";
} else if(dragHint == "rightbottomresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.width = (parseFloat(selected.style.width) + e.movementX) + "px";
selected.style.height = (parseFloat(selected.style.height) + e.movementY) + "px";
} else if(dragHint == "lefttopresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.left = (parseFloat(selected.style.left) + e.movementX) + "px";
selected.style.top = (parseFloat(selected.style.top) + e.movementY) + "px";
selected.style.width = (parseFloat(selected.style.width) - e.movementX) + "px";
selected.style.height = (parseFloat(selected.style.height) - e.movementY) + "px";
} else if(dragHint == "leftbottomresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.left = (parseFloat(selected.style.left) + e.movementX) + "px";
selected.style.width = (parseFloat(selected.style.width) - e.movementX) + "px";
selected.style.height = (parseFloat(selected.style.height) + e.movementY) + "px";
} else if(dragHint == "righttopresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.top = (parseFloat(selected.style.top) + e.movementY) + "px";
selected.style.height = (parseFloat(selected.style.height) - e.movementY) + "px";
selected.style.width = (parseFloat(selected.style.width) + e.movementX) + "px";
} else if(dragHint == "rightresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.width = (parseFloat(selected.style.width) + e.movementX) + "px";
} else if(dragHint == "bottomresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.height = (parseFloat(selected.style.height) + e.movementY) + "px";
} else if(dragHint == "leftresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.left = (parseFloat(selected.style.left) + e.movementX) + "px";
selected.style.width = (parseFloat(selected.style.width) - e.movementX) + "px";
} else if(dragHint == "topresize") {
if(mode != "RESIZED") {
saveUndo();
mode = "RESIZED";
}
selected.style.top = (parseFloat(selected.style.top) + e.movementY) + "px";
selected.style.height = (parseFloat(selected.style.height) - e.movementY) + "px";
}
displayParameters();
}
return true;
}
}
function heading(name) {
let properties = document.getElementById('properties');
properties.insertAdjacentHTML('beforeend', "<tr><td colspan=\"2\" style=\"background-color: #abc; padding: 4px; font-weight: bold;\">" + name + ":</td></tr>");
}
function setColorProperty(event) {
selected.style.setProperty(event.target.id, document.getElementById(event.target.id).value);
}
function getColorProperty(cssprop) {
let value = selected.style.getPropertyValue(cssprop);
if(value.substring(0, 4) == "rgb(") {
document.getElementById(cssprop).value = value;
}
else {
selected.style.removeProperty(cssprop);
}
}
function setSizeProperty(event) {
var value = document.getElementById(event.target.id);
var units = document.getElementById(event.target.id + "Units");
if(value.value == "") {
units.value = "";
} else if(units && units.value == "") {
units.value = "px";
}
if(units) {
selected.style.setProperty(event.target.id, value.value + units.value);
}
}
function getSizeProperty(cssprop) {
let size = selected.style.getPropertyValue(cssprop);
if(size) {
document.getElementById(cssprop).value = parseInt(size);
document.getElementById(cssprop + "Units").value = size.replace(/[0-9]/g, '');
}
}
function property(name, payload, cssprop, initfun, changefun) {
let properties = document.getElementById('properties');
properties.insertAdjacentHTML('beforeend', "<tr><td style=\"background-color: #cdf; padding: 3px 4px; vertical-align: middle; white-space: nowrap;\">" + name + ":</td><td style=\"background-color: #cdf; padding: 3px 4px; vertical-align: middle;\">" + payload + "</td></tr>");
if(initfun) {
initfun(cssprop);
}
if(cssprop) {
document.getElementById(cssprop).addEventListener('input', changefun);
let prop = document.getElementById(cssprop + "Units");
if(prop) {
prop.addEventListener('change', changefun);
}
}
}
function propsize(title, cssprop) {
property(title,
"<div style=\"display: flex; align-items: center; gap: 4px;\">" +
"<input type=\"number\" id=\"" + cssprop + "\" style=\"flex: 1 1 auto; min-width: 0; box-sizing: border-box;\">" +
"<select id=\"" + cssprop + "Units\" style=\"flex: 0 0 auto;\">" +
" <option value=\"\"></option>" +
" <option value=\"px\">px</option>" +
" <option value=\"%\">%</option>" +
"</select></div>",
cssprop,
getSizeProperty,
setSizeProperty);
}
function propcolor(title, cssprop) {
property(title,
"<input type=\"color\" id=\"" + cssprop + "\" style=\"height: 18px; width: 50px; margin: 0px; padding: 0px; border: none; width:85%;\">",
cssprop,
getColorProperty,
setColorProperty);
}
function displayParameters() {
if(!selected) {
itemparameters.innerHTML = "";
return;
}
itemparameters.innerHTML = "<div style=\"width: 300px; max-width: 300px;\"><table id=\"properties\" style=\"width: 300px; table-layout: fixed;\"><colgroup><col style=\"width: 35%;\"><col style=\"width: 65%;\"></colgroup></table></div>";
property("Type", selected.nodeName);
property("Id", selected.id);
property("Display",
"<select id=\"display\" style=\"width: 100%; float: right;\">" +
" <option value=\"inline\">Inline</option>" +
" <option value=\"block\">Block</option>" +
" <option value=\"inline-block\">Inline Block</option>" +
" <option value=\"none\">None</option>" +
"</select>",
"display",
() => { document.getElementById('display').value = selected.style.display; },
() => { selected.style.display = document.getElementById('display').value; }
);
if(selected.id != "mainpage") {
heading("Geometry");
property("Position",
"<select id=\"position\" style=\"width: 100%; float: right;\">" +
" <option value=\"absolute\">Absolute</option>" +
" <option value=\"static\">Static</option>" +
" <option value=\"relative\">Relative</option>" +
"</select>",
"position",
() => { document.getElementById('position').value = selected.style.position; },
() => { saveUndo();
selected.style.position = document.getElementById('position').value;
if(document.getElementById('position').value == 'absolute') {
selected.style.left = selected.getBoundingClientRect().x + 'px';
selected.style.top = selected.getBoundingClientRect().y + 'px';
}
displayParameters();
}
);
if(selected.style.position == 'absolute') {
propsize("Left", "left");
propsize("Top", "top");
}
propsize("Width", "width");
propsize("Height", "height");
}
if(selected.nodeName != 'IMG') {
heading("Font");
propcolor("Color", "color");
}
heading("Margins");
propsize("Left", "margin-left");
propsize("Top", "margin-top");
propsize("Right", "margin-right");
propsize("Bottom", "margin-bottom");
if(selected.id != "mainpage") {
heading("Border");
propsize("Width", "border-width");
propcolor("Color", "border-color");
}
heading("Background");
propcolor("Color", "background-color");
heading("Padding");
propsize("Left", "padding-left");
propsize("Top", "padding-top");
propsize("Right", "padding-right");
propsize("Bottom", "padding-bottom");
}
function newImage(filename, e) {
saveUndo();
let img = '<img id="newitem" src="/assets/' + filename + '" style="width: 150px;">';
mainpage.insertAdjacentHTML('beforeend', img);
}
function handleFiles(files) {
}
function b64encode(str) {
return btoa(unescape(encodeURIComponent(str)));
}
function save(form) {
form.html.value = b64encode(document.getElementById('mainpage').innerHTML);
form.exit.value = '';
form.submit();
}
function savenexit(form) {
form.html.value = b64encode(document.getElementById('mainpage').innerHTML);
form.exit.value = 'yes';
form.submit();
}
function exitnosave(form) {
form.html.value = '';
form.exit.value = 'yes';
form.submit();
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 488 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 457 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 470 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 492 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.
File diff suppressed because it is too large. Load diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 811 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 815 KiB

@@ -0,0 +1,76 @@
(function() {
var form = document.getElementById('newemail-form');
if (!form)
return;
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 navigateTo(url) {
var a = document.createElement('a');
a.href = url;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
var body = document.getElementById('newemail-body');
var toolbar = document.getElementById('newemail-toolbar');
toolbar.addEventListener('click', function(e) {
var btn = e.target.closest('button');
if (!btn)
return;
body.focus();
var cmd = btn.getAttribute('data-cmd');
if (cmd === 'createLink') {
var url = window.prompt('Link URL:');
if (url)
document.execCommand('createLink', false, url);
} else {
document.execCommand(cmd, false, null);
}
});
var errorDiv = document.getElementById('newemail-error');
var sendBtn = document.getElementById('newemail-send-btn');
var cancelBtn = document.getElementById('newemail-cancel-btn');
cancelBtn.addEventListener('click', function() {
navigateTo('/admin/email');
});
sendBtn.addEventListener('click', function() {
var to = document.getElementById('newemail-to').value.trim();
var subject = document.getElementById('newemail-subject').value.trim();
var html = body.innerHTML.trim();
errorDiv.textContent = '';
if (!to) {
errorDiv.textContent = 'A recipient address is required.';
return;
}
if (!html) {
errorDiv.textContent = 'The message body is empty.';
return;
}
sendBtn.classList.add('newemail-sending');
post('/email/send', { to: to, subject: subject, body: html })
.then(function(res) {
sendBtn.classList.remove('newemail-sending');
if (!res.ok) {
errorDiv.textContent = res.error || 'Could not send the message.';
return;
}
navigateTo('/admin/email');
})
.catch(function() {
sendBtn.classList.remove('newemail-sending');
errorDiv.textContent = 'Could not send the message.';
});
});
})();
Loaded 100 of 678 files, more files were not shown because too many files have changed in this diff. Show more