/* * XSLT 1.0 for johnmcm.com's InfoPath Form Viewer: libxslt and libxml2 behind * a few plain C functions, so views are drawn the same way in every browser * and do not depend on the browser's own XSLT engine (which Chrome plans to * remove). * * Both inputs come from an untrusted file, so nothing may be fetched or * written. The module is built without a file system and libxml2 without * network code; on top of that: * - every external entity, DTD and other parser resource is refused; * - xsl:import and xsl:include load only the stylesheets the page hands * over with the job (xt_add_file), found by the path the importing * stylesheet's href resolves to (or, when the person chose loose files * rather than a folder, by the file name when exactly one has it): at most * 64 of them, 16 imports deep. Nothing else is ever read: every other * document load (document() above all) is refused by the loader, so * document('') can still select the stylesheet itself, which libxslt * copies without loading anything. The names asked for and not handed * over are kept (xt_missing), so the page can ask for those files; * - the XSLT security preferences forbid writing files, creating folders, * and reading or writing the network outright, and allow reading only * the stylesheet's own name and the files handed over; * - only the EXSLT modules that compute (common, math, sets, strings, * dates) are registered: not dyn, func or saxon. * libxslt's template depth, variable and operation limits and libxml2's * XPath operation limit stop runaway recursion and single huge expressions, * but they do not bound running time: a stylesheet can stay inside every one * of them and still run for minutes. The real stop is the page's time limit * (20 s), after which it ends the worker. * * xt_add_file(path, data, len) hands over a stylesheet xsl:import or * xsl:include may load (copied) * xt_clear_files() forgets them (and name matching) * xt_set_match_names(on) also match by file name alone (loose files) * xt_transform(xml, xmlLen, xsl, xslLen, maxOut, url) -> 0 ok, else an * error code; url is the stylesheet's own * path ("styles/form.xsl"), the base its * imports resolve against ("" for view.xsl) * xt_missing() stylesheets asked for and not handed over, * one per line ("?name" when several loose * files had that name) * xt_result() / xt_result_len() the output (UTF-8) after a success * xt_error() the error messages after a failure * xt_release() frees the output */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* Parse options: entities from the internal subset are expanded (libxml2's * amplification limits stay on: no XML_PARSE_HUGE), external ones are never * loaded, and CDATA sections become text, as xsltproc does. Both inputs are * read as UTF-8 whatever their XML declaration says, because the page hands * over text it has already decoded (as a browser's DOMParser does). */ #define PARSE_OPTS (XML_PARSE_NOENT | XML_PARSE_NO_XXE | XML_PARSE_NONET | XML_PARSE_NOCDATA | XML_PARSE_NOWARNING | XML_PARSE_IGNORE_ENC) /* The stylesheet's name when the page gives none, the base of its relative references. */ #define STYLE_URL "view.xsl" /* Stylesheets handed over for xsl:import and xsl:include, and the limits on loading them. */ #define MAX_FILES 512 #define MAX_PARTS 64 #define MAX_IMPORT_DEPTH 16 #define MAX_PATH 1024 #define MAX_DEPTH 1000 #define MAX_VARS 20000 #define MAX_XSLT_OPS 20000000UL #define MAX_XPATH_OPS 200000000UL static char err[1024]; static char missing[2048]; static char styleUrl[MAX_PATH] = STYLE_URL; typedef struct { char *key; char *data; int len; } Part; static Part files[MAX_FILES]; static int nFiles = 0; static int byName = 0; static int loads = 0; static xmlChar *out = NULL; static int outLen = 0; static int ready = 0; /* Every message libxml2 and libxslt report, kept up to the buffer's size. */ static void onError(void *ctx, const char *fmt, ...) { (void)ctx; size_t n = strlen(err); if (n >= sizeof err - 1) return; va_list ap; va_start(ap, fmt); vsnprintf(err + n, sizeof err - n, fmt, ap); va_end(ap); } static void note(const char *msg) { if (!err[0]) snprintf(err, sizeof err, "%s", msg); } static xmlParserInputPtr noEntity(const char *url, const char *id, xmlParserCtxtPtr ctxt) { (void)url; (void)id; (void)ctxt; return NULL; } /* A path with its %-escapes undone, "." and ".." worked out, and no "file:" * scheme or empty parts, into outp (MAX_PATH bytes). */ static void normalize(const char *in, char *outp) { char *u = xmlURIUnescapeString(in, 0, NULL); const char *p = u ? u : in; if (strncasecmp(p, "file://", 7) == 0) p += 7; else if (strncasecmp(p, "file:", 5) == 0) p += 5; char buf[MAX_PATH]; snprintf(buf, sizeof buf, "%s", p); if (u) xmlFree(u); for (char *c = buf; *c; c++) if (*c == '\\') *c = '/'; char *parts[128]; int n = 0; for (char *tok = strtok(buf, "/"); tok; tok = strtok(NULL, "/")) { if (!strcmp(tok, ".")) continue; if (!strcmp(tok, "..") && n && strcmp(parts[n - 1], "..")) { n--; continue; } if (n < 128) parts[n++] = tok; } outp[0] = 0; size_t len = 0; for (int i = 0; i < n; i++) { int w = snprintf(outp + len, MAX_PATH - len, "%s%s", i ? "/" : "", parts[i]); if (w < 0 || (size_t)w >= MAX_PATH - len) break; len += (size_t)w; } } static const char *baseName(const char *path) { const char *slash = strrchr(path, '/'); return slash ? slash + 1 : path; } static void addMissing(const char *prefix, const char *name) { char line[MAX_PATH + 4]; snprintf(line, sizeof line, "%s%s\n", prefix, name); if (strstr(missing, line)) return; size_t n = strlen(missing); snprintf(missing + n, sizeof missing - n, "%s", line); } /* The handed-over file a reference resolves to: by its whole path, or (loose * files only) by a name exactly one of them has. NULL if none; `note` puts * the name on the missing list ("?name" when several had it). */ static Part *lookup(const char *ref, int note) { char key[MAX_PATH]; normalize(ref, key); for (int i = 0; i < nFiles; i++) if (!strcasecmp(files[i].key, key)) return &files[i]; if (byName && !strstr(ref, "://")) { const char *name = baseName(key); Part *hit = NULL; int count = 0; for (int i = 0; i < nFiles; i++) { if (!strcasecmp(baseName(files[i].key), name)) { hit = &files[i]; count++; } } if (count == 1) return hit; if (count > 1) { if (note) addMissing("?", name); return NULL; } } if (note) addMissing("", key[0] ? key : ref); return NULL; } /* xsl:import and xsl:include: only the stylesheets handed over, within the * limits. document() and every other load: nothing. */ static xmlDocPtr memDocument(const xmlChar *uri, xmlDictPtr dict, int options, void *ctxt, xsltLoadType type) { (void)options; if (!uri || (type != XSLT_LOAD_STYLESHEET && type != XSLT_LOAD_START)) return NULL; int depth = 0; for (xsltStylesheetPtr s = (xsltStylesheetPtr)ctxt; s && depth <= MAX_IMPORT_DEPTH; s = s->parent) depth++; if (depth > MAX_IMPORT_DEPTH || ++loads > MAX_PARTS) { snprintf(err, sizeof err, "the stylesheet imports too many other stylesheets\n"); return NULL; } Part *p = lookup((const char *)uri, 1); if (!p) return NULL; xmlParserCtxtPtr pc = xmlNewParserCtxt(); if (!pc) return NULL; /* The stylesheet's dictionary, as libxslt's own loader does: names are shared with it. */ if (dict) { if (pc->dict) xmlDictFree(pc->dict); pc->dict = dict; xmlDictReference(dict); } xmlDocPtr doc = xmlCtxtReadMemory(pc, p->data, p->len, p->key, "UTF-8", PARSE_OPTS); if (!doc) { const xmlError *e = xmlCtxtGetLastError(pc); if (e && e->message) snprintf(err, sizeof err, "%s line %d: %s", p->key, e->line, e->message); } xmlFreeParserCtxt(pc); return doc; } /* Reading: the stylesheet's own name (for document(''), which the loader * then refuses, so libxslt copies the stylesheet), and the files handed * over. While the stylesheet is compiled (no transform yet) a name not * handed over is an import or include to ask the person for. */ static int readCheck(xsltSecurityPrefsPtr sec, xsltTransformContextPtr ctxt, const char *value) { (void)sec; if (!value) return 0; if (!strcmp(value, styleUrl)) return 1; return lookup(value, ctxt == NULL) != NULL; } EMSCRIPTEN_KEEPALIVE void xt_clear_files(void) { for (int i = 0; i < nFiles; i++) { free(files[i].key); free(files[i].data); } nFiles = 0; byName = 0; } EMSCRIPTEN_KEEPALIVE int xt_add_file(const char *path, const char *data, int len) { if (nFiles >= MAX_FILES || !path || !data || len < 0) return 1; char key[MAX_PATH]; normalize(path, key); char *k = strdup(key); char *d = malloc((size_t)len + 1); if (!k || !d) { free(k); free(d); return 1; } memcpy(d, data, (size_t)len); d[len] = 0; files[nFiles].key = k; files[nFiles].data = d; files[nFiles].len = len; nFiles++; return 0; } EMSCRIPTEN_KEEPALIVE void xt_set_match_names(int on) { byName = on; } EMSCRIPTEN_KEEPALIVE const char *xt_missing(void) { return missing; } static xsltSecurityPrefsPtr prefs = NULL; static void setup(void) { if (ready) return; ready = 1; xmlInitParser(); xmlSetExternalEntityLoader(noEntity); xsltSetLoaderFunc(memDocument); xsltSetGenericErrorFunc(NULL, onError); xmlSetGenericErrorFunc(NULL, onError); xsltMaxDepth = MAX_DEPTH; xsltMaxVars = MAX_VARS; prefs = xsltNewSecurityPrefs(); xsltSetSecurityPrefs(prefs, XSLT_SECPREF_READ_FILE, readCheck); xsltSetSecurityPrefs(prefs, XSLT_SECPREF_READ_NETWORK, xsltSecurityForbid); xsltSetSecurityPrefs(prefs, XSLT_SECPREF_WRITE_FILE, xsltSecurityForbid); xsltSetSecurityPrefs(prefs, XSLT_SECPREF_CREATE_DIRECTORY, xsltSecurityForbid); xsltSetSecurityPrefs(prefs, XSLT_SECPREF_WRITE_NETWORK, xsltSecurityForbid); xsltSetDefaultSecurityPrefs(prefs); exsltCommonRegister(); exsltMathRegister(); exsltSetsRegister(); exsltStrRegister(); exsltDateRegister(); } static xmlDocPtr parse(const char *buf, int len, const char *url) { xmlParserCtxtPtr p = xmlNewParserCtxt(); if (!p) return NULL; xmlDocPtr doc = xmlCtxtReadMemory(p, buf, len, url, "UTF-8", PARSE_OPTS); if (!doc) { const xmlError *e = xmlCtxtGetLastError(p); if (e && e->message) snprintf(err, sizeof err, "%s line %d: %s", url, e->line, e->message); else snprintf(err, sizeof err, "%s is not well-formed XML", url); } xmlFreeParserCtxt(p); return doc; } EMSCRIPTEN_KEEPALIVE void xt_release(void) { if (out) xmlFree(out); out = NULL; outLen = 0; } EMSCRIPTEN_KEEPALIVE const char *xt_error(void) { return err; } EMSCRIPTEN_KEEPALIVE const xmlChar *xt_result(void) { return out; } EMSCRIPTEN_KEEPALIVE int xt_result_len(void) { return outLen; } /* 0 ok; 1 the data is not XML; 2 the stylesheet is not XML or not XSLT; * 3 the transform failed; 4 the output is larger than maxOut bytes. */ EMSCRIPTEN_KEEPALIVE int xt_transform(const char *xml, int xmlLen, const char *xsl, int xslLen, int maxOut, const char *url) { setup(); xt_release(); err[0] = 0; missing[0] = 0; loads = 0; if (url && *url) normalize(url, styleUrl); if (!url || !*url || !styleUrl[0]) snprintf(styleUrl, sizeof styleUrl, "%s", STYLE_URL); int rc = 3; xmlDocPtr data = NULL, sdoc = NULL, res = NULL; xsltStylesheetPtr style = NULL; xsltTransformContextPtr ctxt = NULL; sdoc = parse(xsl, xslLen, styleUrl); if (!sdoc) { rc = 2; goto done; } style = xsltParseStylesheetDoc(sdoc); if (!style || style->errors) { if (!style) xmlFreeDoc(sdoc); note("not a readable XSLT stylesheet"); rc = 2; goto done; } /* Always UTF-8 out, whatever xsl:output asks for (no iconv here). */ if (style->encoding) xmlFree(style->encoding); style->encoding = xmlStrdup((const xmlChar *)"UTF-8"); data = parse(xml, xmlLen, "data.xml"); if (!data) { rc = 1; goto done; } ctxt = xsltNewTransformContext(style, data); if (!ctxt) { note("out of memory"); goto done; } xsltSetCtxtSecurityPrefs(prefs, ctxt); ctxt->maxTemplateDepth = MAX_DEPTH; ctxt->maxTemplateVars = MAX_VARS; ctxt->opLimit = MAX_XSLT_OPS; if (ctxt->xpathCtxt) ctxt->xpathCtxt->opLimit = MAX_XPATH_OPS; res = xsltApplyStylesheetUser(style, data, NULL, NULL, NULL, ctxt); if (!res || ctxt->state != XSLT_STATE_OK) { note("the stylesheet could not be applied"); goto done; } xmlChar *buf = NULL; int len = 0; if (xsltSaveResultToString(&buf, &len, res, style) < 0) { note("the result could not be written out"); goto done; } if (len > maxOut) { if (buf) xmlFree(buf); snprintf(err, sizeof err, "the result is larger than %d bytes", maxOut); rc = 4; goto done; } out = buf; outLen = buf ? len : 0; rc = 0; done: if (rc) { /* One message per line, without the trailing newline. */ size_t n = strlen(err); while (n && (err[n - 1] == '\n' || err[n - 1] == ' ')) err[--n] = 0; } if (res) xmlFreeDoc(res); if (ctxt) xsltFreeTransformContext(ctxt); if (data) xmlFreeDoc(data); if (style) xsltFreeStylesheet(style); return rc; }