/* browser: a small HTML/CSS browser built on ngui, the image library and the
* shared uhttp client.
*
* Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
* the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
* decoded with img.c and drawn inline. Page-scoped buffers (page body,
* rules and image bitmaps) come from the ring-3 libc heap; each image gets an
* exact-size decode arena that is freed as soon as the scaled bitmap exists.
* The DOM and the image/CSS I/O scratch use fixed static arenas.
*/
#include
#include
#include
#include
#include
#include "ucmd_lib.h"
#include "ngui.h"
#include "browser_html.h"
#include "js_browser.h"
#include "uhttp.h"
#include "uhttp_cookie.h"
#include "img.h"
#include "inflate.h"
#include "ufont.h"
#include "svg_raster.h"
static void svg_cache_clear(void);
static unsigned char *decode_arena; /* see decode_arena_get() */
static unsigned int decode_arena_size;
/* Start wide enough for the desktop nav; smaller screens fall back to
* 960x640 and 780x540, which still fit a 1024x768 panel. */
#define BR_W 1100
#define BR_H 700
#define BR_TOOLBAR_H 30
#define BR_STATUS_H 18
#define BR_PAGE_MAX (2u * 1024u * 1024u)
#define BR_IMG_FILE_MAX (512u * 1024u)
#define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
#define BR_MAX_IMAGES 256
/* Decoded display bitmaps share the page heap: cap their total pixels
* (RGB565 plus an optional alpha plane) instead of their count. */
#define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
#define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
#define BR_IMG_LAYOUT_W 1000
/* An image job may hold a fetch helper this long. The page/script
* deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
* must not starve the other images of all four helpers that long. */
#define BR_IMG_JOB_TIMEOUT_MS 30000u
#define BR_CSS_MAX (832u * 1024u)
#define BR_CSS_COMP_MAX (192u * 1024u)
/* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
* dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
#define BR_SCRIPT_MAX (2u * 1024u * 1024u)
#define FETCH_ABORT (-2)
/* Session cache for remote stylesheets (per launch; cleared at startup). */
#define CSS_CACHE_MAX 16
#define CSS_CACHE_FILE_MAX (256u * 1024u)
#define CSS_CACHE_PREFIX "bcss-"
#define SCRIPT_CACHE_MAX 24
#define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
#define SCRIPT_CACHE_PREFIX "bjs-"
#define BR_MAX_SHEETS 6
#define BR_HISTORY 16
#define BR_URL_MAX 512
#define BR_STATUS_MAX 200
#define BR_IMG_RGB565(r, g, b) \
((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
#define BR_GRAY 0x8410
enum {
ID_URL = 1,
ID_GO,
ID_BACK,
ID_FORWARD,
ID_RELOAD,
ID_HOME
};
#define ACT_NAV (1u << 0)
#define ACT_BACK (1u << 1)
#define ACT_FORWARD (1u << 2)
#define ACT_RELOAD (1u << 3)
#define ACT_HOME (1u << 4)
#define ACT_CLOSE (1u << 5)
#define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
ACT_HOME | ACT_CLOSE)
struct br_image {
int state; /* 0 empty, 1 ready */
struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
int native_w, native_h;
unsigned int url_hash; /* source, 0 = not shareable */
char err[32];
};
static struct ngui ui;
static struct ngui_input url_in;
static struct ngui_scroll page_scroll;
static struct br_doc doc;
static struct br_image images[BR_MAX_IMAGES];
static int image_count;
static unsigned int image_pixels;
/* Painted border boxes, in page/screen coordinates (layout starts at
* page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
struct br_layout_box {
int x, y;
int w, h;
unsigned char valid;
};
static struct br_layout_box layout_boxes[BR_MAX_NODES];
/* Images are loaded one per main-loop iteration so the parsed page stays
* interactive while a slow network/TLS fetch or 4K decode is in progress. */
static int preload_active;
static int preload_max_jobs;
static int preload_pending;
static int preload_wait;
static unsigned int preload_node;
static int preload_loaded;
static int preload_scroll;
static int preload_rescan;
static char post_status_text[BR_STATUS_MAX];
static int post_status_error;
static unsigned int post_status_ttl;
/* Content-relative position/height of each , recorded by the measure
* pass so image loading can be deferred until it is near the viewport. */
static unsigned short img_top[BR_MAX_NODES];
static unsigned short img_h[BR_MAX_NODES];
/* One reusable I/O buffer: the two halves double as the gzip input scratch
* for page/CSS fetches, where the heap has no room for another multi-megabyte
* body. Decode arenas are allocated per image instead of living here. */
static unsigned char *image_io_buf;
static struct ufont_face *font_faces[BR_MAX_FACES];
#define image_file_buf (image_io_buf)
#define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
#define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
static struct inflate image_inflate_ws;
#if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
#error "CSS scratch must fit in image_io_buf"
#endif
static char page_url[BR_URL_MAX];
static char page_title[BR_TITLE_MAX];
static char cwd[64];
static int page_is_local;
static int page_loading;
static char status_text[BR_STATUS_MAX];
static unsigned int status_until;
static int status_error;
static char history[BR_HISTORY][BR_URL_MAX];
static int hist_len, hist_pos;
static char click_url[BR_URL_MAX];
static char pending_url[BR_URL_MAX];
#define BR_POST_MAX 4096
static char pending_post[BR_POST_MAX];
static unsigned int pending_post_len;
/* The pending navigation is a POST even when its body is empty (a form
* without fields, e.g. the OIDC consent auto-submit). */
static int pending_post_is;
/* window "resize" bookkeeping: the page width the last event was for. */
static int resize_sent_w = -1;
static int resize_pending;
static unsigned int pending_action;
static int cancel_fetch;
static int quit;
static struct ngui_rect page_rect;
static unsigned short *page_backbuf;
static int pagebuf_w, pagebuf_h;
static int page_cache_valid;
static int page_cache_scroll;
static unsigned int page_cache_nnode;
static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
static int layout_valid, layout_left, layout_right;
/* Height of the page viewport: what html/body height:100% resolves to. */
static int layout_view_h;
static unsigned int layout_nnode;
static int layout_content_h;
/* layout output */
struct lay_run {
unsigned int off;
unsigned short len;
unsigned short gap;
unsigned short color;
unsigned short href;
char lit[28];
short img;
signed short dy; /* inline image vertical offset */
unsigned short iw, ih;
unsigned short w;
unsigned char font_px, bold, italic, mono, underline, strike;
unsigned char overline, font_face;
unsigned char transform_scale;
unsigned char origin_x_kind, origin_y_kind;
signed short scale_x, scale_y, rotate_x100;
signed short origin_x, origin_y;
unsigned char has_lit;
unsigned int form; /* node + 1, 0 = not a control */
unsigned char form_kind;
unsigned char form_disabled;
};
struct lay {
int draw;
struct ngui *ui;
int left, right;
int y;
int line_x, line_y, line_h;
int line_left, line_right;
int parent_top;
int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
int cb_h; /* definite content height of the containing block for
* percentage heights; 0 = indefinite (auto) */
int run_x;
int align;
int depth;
int space_pending;
unsigned char float_active;
int float_left, float_right, float_bottom;
struct lay_run runs[96];
int nruns;
};
struct hit {
int x, y, w, h;
unsigned short node;
};
/* Live form state; the DOM attributes stay the initial/default value. */
#define FORM_MAX 64
#define FORM_VALUE_MAX 63
enum {
FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
};
struct form_state {
unsigned int node;
char value[FORM_VALUE_MAX + 1];
unsigned char len, caret, checked, selected, used;
};
static struct form_state form_states[FORM_MAX];
static unsigned int form_focus;
static unsigned int form_dirty;
static int form_descendant(unsigned int node, unsigned int form);
static int form_submit_form(unsigned int node, int fire_event);
static int link_fragment_nav(unsigned int node);
static void history_push(const char *url);
static void form_reset_event(unsigned int form);
static unsigned int s_len(const char *s);
static int s_eq(const char *a, const char *b);
static void form_key(int k);
static void form_click(unsigned int node);
static void style_for_node(unsigned int node, struct br_style *out);
static int form_disabled(unsigned int node)
{
struct br_node *n = &doc.nodes[node];
if (n->attr_flags & BR_ATTR_DISABLED)
return 1;
return br_find_attr(&doc, node, "disabled") != 0;
}
static int form_kind_of(unsigned int node)
{
const char *type = br_type(&doc, node);
if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
return FORM_TEXTAREA;
if (doc.nodes[node].tag == BR_TAG_SELECT)
return FORM_SELECT;
if (doc.nodes[node].tag == BR_TAG_BUTTON) {
if (s_eq(type, "reset"))
return FORM_RESET;
if (s_eq(type, "button"))
return FORM_BUTTON;
return FORM_SUBMIT;
}
if (s_eq(type, "password"))
return FORM_PASSWORD;
if (s_eq(type, "checkbox"))
return FORM_CHECKBOX;
if (s_eq(type, "radio"))
return FORM_RADIO;
if (s_eq(type, "submit"))
return FORM_SUBMIT;
if (s_eq(type, "reset"))
return FORM_RESET;
if (s_eq(type, "button"))
return FORM_BUTTON;
return FORM_TEXT;
}
static unsigned int form_option_count(unsigned int node)
{
unsigned int c, n = 0;
for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
if (doc.nodes[c].type == BR_NODE_ELEM &&
doc.nodes[c].tag == BR_TAG_OPTION)
n++;
return n;
}
static unsigned int form_option_selected(unsigned int node)
{
unsigned int c, i = 0;
for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
if (doc.nodes[c].type != BR_NODE_ELEM ||
doc.nodes[c].tag != BR_TAG_OPTION)
continue;
if (br_find_attr(&doc, c, "selected"))
return i;
i++;
}
return 0;
}
static unsigned int form_option_text(unsigned int node, unsigned int idx,
char *out, unsigned int cap)
{
unsigned int c, i = 0;
for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
if (doc.nodes[c].type != BR_NODE_ELEM ||
doc.nodes[c].tag != BR_TAG_OPTION)
continue;
if (i == idx)
return br_text_content(&doc, c, out, cap);
i++;
}
return 0;
}
static struct form_state *form_get(unsigned int node, int create)
{
struct form_state *slot = 0;
unsigned int i;
for (i = 0; i < FORM_MAX; i++) {
if (form_states[i].used) {
if (form_states[i].node == node)
return &form_states[i];
} else if (!slot) {
slot = &form_states[i];
}
}
if (!create || !slot)
return 0;
slot->node = node;
slot->len = 0;
slot->caret = 0;
slot->checked = br_find_attr(&doc, node, "checked") != 0;
slot->selected = form_option_selected(node);
slot->used = 1;
{
unsigned int n = 0;
if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
n = br_text_content(&doc, node, slot->value,
FORM_VALUE_MAX + 1);
} else {
const char *v = br_value(&doc, node);
if (v) {
n = s_len(v);
if (n > FORM_VALUE_MAX)
n = FORM_VALUE_MAX;
for (unsigned int j = 0; j < n; j++)
slot->value[j] = v[j];
}
if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
n = br_text_content(&doc, node, slot->value,
FORM_VALUE_MAX + 1);
}
if (n > FORM_VALUE_MAX)
n = FORM_VALUE_MAX;
slot->value[n] = '\0';
slot->len = (unsigned char)n;
slot->caret = (unsigned char)n;
}
return slot;
}
static void form_reset_state(void)
{
unsigned int i;
for (i = 0; i < FORM_MAX; i++)
form_states[i].used = 0;
form_focus = 0;
}
/* A with element content (an icon / , a label)
* is laid out like a normal element so that content shows; only a text or
* empty button is drawn as a native control. Clicks still reach it
* through the box hit test. */
static int button_has_elements(unsigned int node)
{
unsigned int c;
if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
return 0;
for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
if (doc.nodes[c].type == BR_NODE_ELEM)
return 1;
return 0;
}
static int form_is_control(unsigned int node)
{
unsigned int tag;
if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
return 0;
tag = doc.nodes[node].tag;
return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
tag == BR_TAG_SELECT ||
(tag == BR_TAG_BUTTON && !button_has_elements(node));
}
#define HIT_MAX 96
static struct hit hits[HIT_MAX];
static int nhits;
static unsigned short block_h[BR_MAX_NODES];
/* Measure-pass top of each block, in the same document coordinates as
* img_top[] (layout_boxes[] is rewritten in screen coordinates by every
* paint, so it cannot drive the lazy background loader). */
static unsigned short block_top[BR_MAX_NODES];
static char li_marker[BR_MAX_NODES][12];
/* one connection object; the browser fetches one resource at a time */
/* ---- tiny strings ---- */
static unsigned int s_len(const char *s)
{
unsigned int n = 0;
while (s && s[n])
n++;
return n;
}
static void s_copy(char *d, const char *s, unsigned int cap)
{
unsigned int i = 0;
if (!cap)
return;
while (s && s[i] && i + 1 < cap) {
d[i] = s[i];
i++;
}
d[i] = '\0';
}
static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
{
while (s && *s && *n + 1 < cap)
d[(*n)++] = *s++;
d[*n] = '\0';
}
static void s_append_dec(char *d, unsigned int *n, unsigned int v,
unsigned int cap)
{
char tmp[12];
unsigned int i = 0, j;
do {
tmp[i++] = (char)('0' + v % 10);
v /= 10;
} while (v && i < sizeof(tmp));
for (j = 0; j < i && *n + 1 < cap; j++)
d[(*n)++] = tmp[i - 1 - j];
d[*n] = '\0';
}
static int s_eq(const char *a, const char *b)
{
while (*a && *b) {
if (*a != *b)
return 0;
a++;
b++;
}
return *a == *b;
}
static int starts_with(const char *s, const char *p)
{
unsigned int i = 0;
while (p[i]) {
if (s[i] != p[i])
return 0;
i++;
}
return 1;
}
static int contains_ci(const char *s, const char *p)
{
unsigned int i, j;
for (i = 0; s[i]; i++) {
for (j = 0; p[j]; j++) {
char a = s[i + j];
if (a >= 'A' && a <= 'Z')
a = (char)(a - 'A' + 'a');
if (a != p[j])
break;
}
if (!p[j])
return 1;
}
return 0;
}
static char *trim(char *s)
{
unsigned int n;
while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
s++;
n = s_len(s);
while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
s[n - 1] == '\r' || s[n - 1] == '\n'))
s[--n] = '\0';
return s;
}
/* ---- per-process heap ---- */
static int heap_start(void)
{
image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
if (!image_io_buf)
return -1;
page_backbuf = (unsigned short *)malloc(
(unsigned int)ui.w * (unsigned int)ui.h * 2u);
pagebuf_w = page_backbuf ? ui.w : 0;
pagebuf_h = page_backbuf ? ui.h : 0;
page_cache_valid = 0;
return 0;
}
static void heap_clear(void)
{
memset(font_faces, 0, sizeof(font_faces));
ngui_font_detach(&ui);
svg_cache_clear();
decode_arena = 0; /* lives in the page heap too */
decode_arena_size = 0;
heap_reset();
/* The document arenas live in that heap; drop the stale pointers so
* the next br_parse_plain() allocates fresh ones. */
doc.nodes = 0;
doc.text = 0;
doc.attrs = 0;
image_io_buf = 0;
page_backbuf = 0;
pagebuf_w = pagebuf_h = 0;
page_cache_valid = 0;
}
static void browser_rules_alloc(void)
{
struct br_rule *rules;
rules = (struct br_rule *)malloc(
(unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
}
/* ---- status ---- */
static void set_status(const char *s, int err, unsigned int ttl_ms)
{
s_copy(status_text, s, sizeof(status_text));
status_error = err;
status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
ngui_invalidate(&ui);
}
/* ---- JavaScript ---- */
static int resolve_link(const char *base, const char *href, char *out,
unsigned int cap);
static char js_last_status[BR_STATUS_MAX];
static int js_last_error;
static void js_host_status(const char *msg, int error)
{
s_copy(js_last_status, msg, sizeof(js_last_status));
js_last_error = error;
set_status(msg, error, 6000);
}
static void js_host_report(const char *msg)
{
u_puts("[js] ");
u_puts(msg);
u_putc('\n');
s_copy(js_last_status, msg, sizeof(js_last_status));
js_last_error = 1;
set_status(msg, 1, 8000);
}
static void js_host_navigate(const char *url)
{
char resolved[BR_URL_MAX];
if (!url || !url[0])
return;
if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
return;
s_copy(pending_url, resolved, sizeof(pending_url));
pending_action |= ACT_NAV;
cancel_fetch = 1;
}
/* Same-document fragment change (location.hash, an click,
* back/forward between fragments): the page URL, address bar and history
* follow, nothing is reloaded. `push` adds a history entry. */
static int page_set_fragment(const char *url, int push)
{
if (!url || !url[0] || s_len(url) >= sizeof(page_url))
return -1;
s_copy(page_url, url, sizeof(page_url));
s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
url_in.len = s_len(url_in.text);
url_in.cursor = url_in.len;
url_in.scroll = 0;
if (push)
history_push(page_url);
ngui_invalidate(&ui);
return 0;
}
static int js_host_set_hash(const char *url)
{
return page_set_fragment(url, 1);
}
/* 1 when `url` is this page with a different #fragment (and JavaScript runs
* the page, so a hash router can react). */
static int same_doc_fragment(const char *url)
{
unsigned int a = 0, b = 0;
if (!js_browser_active() || !url)
return 0;
while (url[a] && url[a] != '#')
a++;
while (page_url[b] && page_url[b] != '#')
b++;
return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
!s_eq(url, page_url);
}
static void js_host_changed(void)
{
/* Class/style/attribute mutations change computed styles, not just the
* text: drop the per-node style cache before the next layout. */
br_reset_styles(&doc);
layout_valid = 0;
/* Script-built content (Angular's ng-repeat cards) brings new images
* and inline background styles: rescan once the main loop is idle. */
preload_rescan = 1;
ngui_invalidate(&ui);
}
static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
{
if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
return 0;
*x = layout_boxes[node].x - page_rect.x;
*y = layout_boxes[node].y - page_rect.y;
*w = layout_boxes[node].w;
*h = layout_boxes[node].h;
return 1;
}
static void form_copy_out(const char *s, char *buf, int cap)
{
int i = 0;
if (!buf || cap <= 0)
return;
while (s && s[i] && i + 1 < cap) {
buf[i] = s[i];
i++;
}
buf[i] = '\0';
}
static int js_host_form_value(unsigned int node, char *buf, int cap)
{
struct form_state *fs;
int kind;
if (!form_is_control(node))
return 0;
kind = form_kind_of(node);
if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
return 0;
if (kind == FORM_SELECT) {
char opt[64] = "";
unsigned int c, i = 0;
fs = form_get(node, 1);
if (!fs)
return 0;
form_option_text(node, fs->selected, opt, sizeof(opt));
for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
if (doc.nodes[c].type != BR_NODE_ELEM ||
doc.nodes[c].tag != BR_TAG_OPTION)
continue;
if (i == fs->selected) {
const char *v = br_value(&doc, c);
if (v && v[0])
form_copy_out(v, buf, cap);
else
form_copy_out(opt, buf, cap);
return 1;
}
i++;
}
form_copy_out(opt, buf, cap);
return 1;
}
fs = form_get(node, 1);
if (!fs)
return 0;
form_copy_out(fs->value, buf, cap);
return 1;
}
static int js_host_form_checked(unsigned int node)
{
struct form_state *fs;
int kind;
if (!form_is_control(node))
return -1;
kind = form_kind_of(node);
if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
return -1;
fs = form_get(node, 1);
return fs ? fs->checked : 0;
}
static int js_host_form_selected(unsigned int node)
{
struct form_state *fs;
if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
return -1;
fs = form_get(node, 1);
return fs ? fs->selected : 0;
}
static int js_host_form_set_value(unsigned int node, const char *value)
{
struct form_state *fs;
unsigned int n;
if (!form_is_control(node))
return 0;
fs = form_get(node, 1);
if (!fs)
return 0;
n = s_len(value ? value : "");
if (n > FORM_VALUE_MAX)
n = FORM_VALUE_MAX;
for (unsigned int i = 0; i < n; i++)
fs->value[i] = value[i];
fs->value[n] = '\0';
fs->len = (unsigned char)n;
fs->caret = (unsigned char)n;
layout_valid = 0;
ngui_invalidate(&ui);
return 1;
}
static int js_host_form_set_checked(unsigned int node, int checked)
{
struct form_state *fs;
int kind;
if (!form_is_control(node))
return 0;
kind = form_kind_of(node);
if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
return 0;
fs = form_get(node, 1);
if (!fs)
return 0;
fs->checked = (unsigned char)(checked != 0);
layout_valid = 0;
ngui_invalidate(&ui);
return 1;
}
static int js_host_form_set_selected(unsigned int node, int index)
{
struct form_state *fs;
unsigned int n;
if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
return 0;
fs = form_get(node, 1);
if (!fs)
return 0;
n = form_option_count(node);
if (index < 0)
index = 0;
if (n && (unsigned int)index >= n)
index = (int)n - 1;
fs->selected = (unsigned char)index;
layout_valid = 0;
ngui_invalidate(&ui);
return 1;
}
static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
{
unsigned int i;
int n = 0;
if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
doc.nodes[form].tag != BR_TAG_FORM)
return 0;
for (i = 0; i < doc.nnode && n < cap; i++) {
struct br_node *nd = &doc.nodes[i];
if (i == form || nd->type != BR_NODE_ELEM)
continue;
if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
continue;
if (!form_descendant(i, form))
continue;
out[n++] = i;
}
return n;
}
static int js_host_form_submit(unsigned int form)
{
form_submit_form(form, 0);
return 1;
}
static int js_host_form_reset(unsigned int form)
{
form_reset_event(form);
return 1;
}
static void css_computed_name(const char *p, char *out, int cap)
{
int n = 0;
for (; p && *p && n + 2 < cap; p++) {
char c = *p;
if (c >= 'A' && c <= 'Z') {
out[n++] = '-';
c = (char)(c - 'A' + 'a');
} else if (c == '_') {
c = '-';
} else if (c >= 'a' && c <= 'z') {
/* keep */
}
out[n++] = c;
}
out[n] = '\0';
if (!strcmp(out, "css-float"))
strcpy(out, "float");
}
static void css_rgb(unsigned short c, char *buf, int cap)
{
int r = ((c >> 11) & 31) * 255 / 31;
int g = ((c >> 5) & 63) * 255 / 63;
int b = (c & 31) * 255 / 31;
snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
}
static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
int font_px)
{
if (unit == 4) {
snprintf(buf, cap, "auto");
} else if (unit == 0) {
snprintf(buf, cap, "%dpx", raw);
} else if (unit == 1) {
snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
} else if (unit == 2) {
/* Chrome's getComputedStyle() reports used pixel values. */
snprintf(buf, cap, "%dpx", font_px * raw / 100);
} else if (unit == 3) {
snprintf(buf, cap, "%dpx",
(int)br_root_font_px() * raw / 100);
} else {
snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
raw / 100, raw % 100, px);
}
}
static int js_host_computed(unsigned int node, const char *property,
char *buf, int cap)
{
struct br_style st;
char name[40];
if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
return 0;
buf[0] = '\0';
css_computed_name(property, name, sizeof(name));
style_for_node(node, &st);
if (!strcmp(name, "display")) {
const char *v = "inline";
if (st.display == BR_DISPLAY_BLOCK)
v = "block";
else if (st.display == BR_DISPLAY_NONE)
v = "none";
else if (st.display == BR_DISPLAY_FLEX)
v = "flex";
else if (st.display == BR_DISPLAY_GRID)
v = "grid";
else if (st.display == BR_DISPLAY_INLINE_BLOCK)
v = "inline-block";
snprintf(buf, cap, "%s", v);
} else if (!strcmp(name, "position")) {
static const char *pos[] = {
"static", "absolute", "fixed", "relative", "sticky"
};
snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
} else if (!strcmp(name, "width") || !strcmp(name, "height")) {
int is_w = name[0] == 'w';
int kind = is_w ? st.width_kind : st.height_kind;
int val = is_w ? st.width : st.height;
if (kind == 3) {
if (is_w)
snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
st.width_calc_pct / 100,
st.width_calc_pct % 100,
st.width_calc_px);
else
snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
st.height_calc_pct / 100,
st.height_calc_pct % 100,
st.height_calc_px);
} else if (kind == 1) {
snprintf(buf, cap, "%dpx", val);
} else if (kind == 2) {
snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
} else {
snprintf(buf, cap, "auto");
}
} else if (!strcmp(name, "color") ||
!strcmp(name, "background-color")) {
if (!strcmp(name, "background-color") && !st.has_bg)
snprintf(buf, cap, "rgba(0, 0, 0, 0)");
else
css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
} else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
int is_fill = name[0] == 'f';
int mode = is_fill ? st.fill_mode : st.stroke_mode;
if (mode == BR_PAINT_COLOR)
css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
else if (mode == BR_PAINT_CURRENT)
css_rgb(st.color, buf, cap);
else if (mode == BR_PAINT_UNSET && is_fill)
snprintf(buf, cap, "rgb(0, 0, 0)");
else if (mode == BR_PAINT_URL)
snprintf(buf, cap, "url()");
else
snprintf(buf, cap, "none");
} else if (!strcmp(name, "font-size")) {
snprintf(buf, cap, "%dpx", st.font_px);
} else if (!strcmp(name, "font-weight")) {
snprintf(buf, cap, "%s", st.bold ? "700" : "400");
} else if (!strcmp(name, "font-style")) {
snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
} else if (!strcmp(name, "font-family")) {
if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
br_font_face_family(st.font_face)[0])
snprintf(buf, cap, "%s",
br_font_face_family(st.font_face));
else
snprintf(buf, cap, "%s",
st.mono ? "monospace" : "sans-serif");
} else if (!strcmp(name, "text-align")) {
static const char *al[] = { "left", "center", "right", "justify" };
snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
} else if (!strcmp(name, "float")) {
snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
st.float_left == 2 ? "right" : "none");
} else if (!strcmp(name, "clear")) {
static const char *cl[] = { "none", "left", "right", "both" };
snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
} else if (!strcmp(name, "opacity")) {
snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
} else if (!strcmp(name, "visibility")) {
snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
} else if (!strcmp(name, "overflow")) {
snprintf(buf, cap, "%s",
st.overflow_hidden ? "hidden" : "visible");
} else if (!strcmp(name, "white-space")) {
snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
} else if (!strcmp(name, "text-transform")) {
snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
} else if (!strcmp(name, "box-sizing")) {
snprintf(buf, cap, "%s",
st.box_sizing ? "border-box" : "content-box");
} else if (!strcmp(name, "line-height")) {
if (st.line_h_px)
snprintf(buf, cap, "%dpx", st.line_h_px);
else if (st.line_h_pct)
snprintf(buf, cap, "%d%%", st.line_h_pct);
else
snprintf(buf, cap, "normal");
} else if (!strcmp(name, "z-index")) {
if (st.z_set)
snprintf(buf, cap, "%d", st.z_index);
else
snprintf(buf, cap, "auto");
} else if (!strcmp(name, "top") || !strcmp(name, "left") ||
!strcmp(name, "right") || !strcmp(name, "bottom")) {
int set = name[0] == 't' ? st.top_set :
name[0] == 'l' ? st.left_set :
name[0] == 'r' ? st.right_set : st.bottom_set;
int v = name[0] == 't' ? st.top :
name[0] == 'l' ? st.left :
name[0] == 'r' ? st.right : st.bottom;
if (set)
snprintf(buf, cap, "%dpx", v);
else
snprintf(buf, cap, "auto");
} else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
!strcmp(name, "margin-bottom") ||
!strcmp(name, "margin-left") ||
!strcmp(name, "padding-top") ||
!strcmp(name, "padding-right") ||
!strcmp(name, "padding-bottom") ||
!strcmp(name, "padding-left")) {
int is_pad = name[0] == 'p';
int side = name[strlen(name) - 1] == 'p' ? 0 :
name[strlen(name) - 1] == 't' ? 1 :
name[strlen(name) - 1] == 'm' ? 2 : 3;
/* last letter: top p, right t, bottom m, left t (ambiguity). */
if (!strcmp(name, "margin-right") ||
!strcmp(name, "padding-right"))
side = 1;
else if (!strcmp(name, "margin-bottom") ||
!strcmp(name, "padding-bottom"))
side = 2;
else if (!strcmp(name, "margin-left") ||
!strcmp(name, "padding-left"))
side = 3;
else
side = 0;
side += is_pad ? 4 : 0;
css_mp_value(buf, cap,
side == 0 ? st.mt : side == 1 ? st.mr :
side == 2 ? st.mb : side == 3 ? st.ml :
side == 4 ? st.pt : side == 5 ? st.pr :
side == 6 ? st.pb : st.pl,
st.mp_unit[side], st.mp_calc_px[side],
st.font_px);
} else if (!strcmp(name, "border-top-width") ||
!strcmp(name, "border-right-width") ||
!strcmp(name, "border-bottom-width") ||
!strcmp(name, "border-left-width")) {
int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
name[7] == 'b' ? 2 : 3;
snprintf(buf, cap, "%dpx", st.border_w[side]);
} else if (!strcmp(name, "border-top-color") ||
!strcmp(name, "border-right-color") ||
!strcmp(name, "border-bottom-color") ||
!strcmp(name, "border-left-color")) {
int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
name[7] == 'b' ? 2 : 3;
if (st.border_w[side] && !st.border_t[side])
css_rgb(st.border_c[side], buf, cap);
else
snprintf(buf, cap, "rgba(0, 0, 0, 0)");
} else if (!strcmp(name, "background-image")) {
if (st.bg_image)
snprintf(buf, cap, "url(\"%s\")",
br_bg_image_url(st.bg_image - 1));
else
snprintf(buf, cap, "none");
} else if (!strcmp(name, "background-repeat")) {
static const char *rp[] = {
"repeat", "no-repeat", "repeat-x", "repeat-y"
};
snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
st.bg_repeat : 0]);
} else if (!strcmp(name, "background-position")) {
if (st.bg_pos_x_kind == 1)
snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
st.bg_pos_y);
else
snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
st.bg_pos_y);
} else if (!strcmp(name, "background-size")) {
if (st.bg_size_kind == 3)
snprintf(buf, cap, "cover");
else if (st.bg_size_kind == 4)
snprintf(buf, cap, "contain");
else if (st.bg_size_kind == 1)
snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
st.bg_size_h);
else if (st.bg_size_kind == 2)
snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
st.bg_size_h);
else
snprintf(buf, cap, "auto");
} else if (!strcmp(name, "transform")) {
char tmp[128];
unsigned int n = 0;
if (!st.transform_set) {
snprintf(buf, cap, "none");
} else {
tmp[0] = '\0';
if (st.tx || st.ty) {
snprintf(tmp + n, sizeof(tmp) - n,
"translate(%dpx, %dpx)", st.tx, st.ty);
n = (unsigned int)strlen(tmp);
}
if (st.transform_scale) {
snprintf(tmp + n, sizeof(tmp) - n,
"%sscale(%d.%02d, %d.%02d)",
n ? " " : "", st.scale_x / 100,
st.scale_x % 100, st.scale_y / 100,
st.scale_y % 100);
n = (unsigned int)strlen(tmp);
if (st.rotate_x100) {
snprintf(tmp + n, sizeof(tmp) - n,
" rotate(%d.%02ddeg)",
st.rotate_x100 / 100,
st.rotate_x100 % 100);
}
} else if (st.rotate_x100) {
snprintf(tmp + n, sizeof(tmp) - n,
"%srotate(%d.%02ddeg)",
n ? " " : "", st.rotate_x100 / 100,
st.rotate_x100 % 100);
}
snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
}
} else {
return 0;
}
return buf[0] != '\0';
}
static int js_host_click(unsigned int node)
{
char url[BR_URL_MAX];
const char *href;
if (node >= doc.nnode)
return 0;
if (form_is_control(node)) {
form_click(node); /* dispatches its own click event */
return 1;
}
/* element.click() fires a bubbling, cancelable click before the
* default action, like a real click (delegated list handlers). */
if (!js_browser_event(node, "click", 1, 1))
return 1;
if (link_fragment_nav(node))
return 1;
href = br_href(&doc, node);
if (resolve_link(page_url, href, url, sizeof(url)) != 0)
return 0;
s_copy(pending_url, url, sizeof(pending_url));
pending_action |= ACT_NAV;
cancel_fetch = 1;
ngui_invalidate(&ui);
return 1;
}
static int fetch_script_text(const char *url, unsigned char **out,
unsigned int *outlen, char *err,
unsigned int errcap);
struct fetch_worker;
static struct fetch_worker *fetch_worker_alloc(void);
static void fetch_worker_release(struct fetch_worker *w);
static int fetch_worker_submit(struct fetch_worker *w, const char *url,
unsigned int cap, const char *post,
unsigned int post_len, unsigned int node,
int bg, char *err, unsigned int errcap);
static int fetch_worker_wait(struct fetch_worker *w, char *err,
unsigned int errcap);
static int fetch_worker_read_body(struct fetch_worker *w,
unsigned char *plain,
unsigned int plaincap,
unsigned char *comp,
unsigned int compcap,
int *truncated, char *err,
unsigned int errcap);
static void fetch_workers_stop_all(void);
static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
unsigned int cap, const char *method,
const char *ctype, const char *post,
unsigned int post_len, unsigned int node,
int bg, char *err, unsigned int errcap);
static int script_cache_has(const char *url);
static void script_cache_put(const char *url, const unsigned char *data,
unsigned int len);
static unsigned int script_cache_hash(const char *s);
static int fetch_worker_poll(struct fetch_worker *w, char *err,
unsigned int errcap);
static void fetch_workers_cancel_busy(void);
static void worker_wait_ui(void);
static int fetch_worker_status(const struct fetch_worker *w);
/* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
* module load: the wait must not pump input, or a click would dispatch DOM
* events into the middle of the running script. */
static int fetch_wait_passive;
static void script_error(const char *what, const char *url, const char *why)
{
char msg[192];
unsigned int n = 0;
s_append(msg, &n, what, sizeof(msg));
if (url && url[0]) {
s_append(msg, &n, " ", sizeof(msg));
s_append(msg, &n, url, sizeof(msg));
}
if (why && why[0]) {
s_append(msg, &n, ": ", sizeof(msg));
s_append(msg, &n, why, sizeof(msg));
}
js_host_report(msg);
}
/* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
/* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
* body (FETCH_POST_MAX in ucmd_curl.c). */
#define JS_HTTP_MAX (2u * 1024u * 1024u)
#define JS_HTTP_POST_MAX (16u * 1024u)
/* struct fetch_meta / fetch_worker internals come later in the file. */
static int js_worker_http(const char *method, const char *url,
const char *ctype, const char *body,
unsigned int body_len, struct js_http_resp *r,
char *err, int errcap);
static int js_host_http(const char *method, const char *url,
const char *ctype, const char *body,
unsigned int body_len, struct js_http_resp *r,
char *err, int errcap)
{
if (pending_action) {
s_copy(err, "page is navigating", (unsigned int)errcap);
return -1;
}
if (url[0] == '/') {
/* Local file: GET only. */
unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
int rv;
if (!buf) {
s_copy(err, "out of memory", (unsigned int)errcap);
return -1;
}
rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
(int)JS_HTTP_MAX);
r->status = rv < 0 ? 404 : 200;
r->len = rv < 0 ? 0 : (unsigned int)rv;
buf[r->len] = '\0';
r->body = (char *)buf;
s_copy(r->url, url, sizeof(r->url));
if (contains_ci(url, ".json"))
s_copy(r->ctype, "application/json", sizeof(r->ctype));
return 0;
}
if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
return -1;
}
if (body_len > JS_HTTP_POST_MAX) {
s_copy(err, "request body too large", (unsigned int)errcap);
return -1;
}
return js_worker_http(method, url, ctype, body, body_len, r, err,
errcap);
}
/* Module source for the engine's loader: the boot script cache first, then
* one blocking fetch with input pumping disabled (the loader runs inside
* JavaScript). */
static char *js_host_load_script(const char *url, unsigned int *len)
{
unsigned char *data = 0;
char err[64];
int rv;
fetch_wait_passive++;
set_status("Loading module...", 0, 0);
rv = fetch_script_text(url, &data, len, err, sizeof(err));
fetch_wait_passive--;
if (rv != 0) {
script_error("Cannot load module", url,
rv == FETCH_ABORT ? "navigation" : err);
return 0;
}
return (char *)data;
}
/* Web Storage lives in /share, outside the page heap that every navigation
* resets: localStorage per origin for the boot, sessionStorage per origin
* and browser window. */
#define JS_ORIGIN_MAX 160
/* scheme://host[:port] of the page (a local page's whole path). */
static void js_page_origin(char *origin, unsigned int cap)
{
unsigned int i = 0, slashes = 0;
while (page_url[i] && i + 1 < cap) {
if (page_url[i] == '/' && ++slashes == 3)
break;
origin[i] = page_url[i];
i++;
}
origin[i] = '\0';
}
static void js_origin_path(const char *origin, char *out, unsigned int cap)
{
unsigned int n = 0;
s_append(out, &n, "/share/bls", cap);
s_append_dec(out, &n, script_cache_hash(origin), cap);
}
static void js_storage_path(int kind, char *out, unsigned int cap)
{
char origin[JS_ORIGIN_MAX];
unsigned int n = 0;
js_page_origin(origin, sizeof(origin));
if (!kind) {
js_origin_path(origin, out, cap);
return;
}
s_append(out, &n, "/share/bss", cap);
if (kind) {
s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
s_append(out, &n, "-", cap);
}
s_append_dec(out, &n, script_cache_hash(origin), cap);
}
static void persist_mark_origin(const char *origin);
static int persist_store_lookup(const char *origin, char *out, int cap);
static int js_host_storage(int kind, const char *set, char *out, int cap)
{
char path[48], origin[JS_ORIGIN_MAX];
int rv;
js_storage_path(kind, path, sizeof(path));
if (set) {
if (kind) {
if (!set[0] || !strcmp(set, "{}")) {
u_syscall1(SYS_UNLINK, (int)path);
return 0;
}
} else {
/* localStorage keeps an explicit "{}" rather than no
* file: a missing /share file means "not loaded from
* /data yet", and a cleared store must not come back
* from the disk copy before it is flushed. */
if (!set[0])
set = "{}";
js_page_origin(origin, sizeof(origin));
persist_mark_origin(origin);
}
return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
(int)strlen(set)) < 0 ? -1 : 0;
}
rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
if (rv < 0 && !kind) {
/* First use this boot: the persistent copy on /data. */
js_page_origin(origin, sizeof(origin));
rv = persist_store_lookup(origin, out, cap);
if (rv >= 0)
u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
}
if (rv < 0)
return -1;
out[rv] = '\0';
return rv;
}
/* ---- persistence on /data ----
*
* /share is the working copy (RAM, shared by every helper and window); the
* installed disk's /data volume keeps the cookie jar and localStorage
* across reboots when it is mounted. The browser owns the disk copies: at
* start it restores the jar into /share, and its main loop writes back
* whatever changed at most every PERSIST_MS, so a burst of cookie or
* setItem updates costs one FAT write. The helpers only touch /share (they
* are killed on focus loss, so they cannot be trusted to flush). Without a
* /data mount every disk access simply fails. Both files are plaintext
* bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
#define PERSIST_MS 3000u
#define SHARE_COOKIES "/share/bcookies"
#define DATA_COOKIES "/data/BCOOKIES.BIN"
#define DATA_STORE "/data/BSTORE.DAT"
#define DATA_STORE_MAGIC "NBLS1\n"
#define DATA_STORE_MAX (192u * 1024u)
#define PERSIST_DIRTY_MAX 8
static unsigned int persist_due;
static unsigned int cookie_sum_saved;
static int cookie_sum_valid;
static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
static int persist_ndirty;
static unsigned int persist_sum(const unsigned char *p, unsigned int n)
{
unsigned int h = 2166136261u, i;
for (i = 0; i < n; i++)
h = (h ^ p[i]) * 16777619u;
return h;
}
/* Called once at startup, before any helper runs. */
static void persist_restore(void)
{
unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
int n;
if (!jar)
return;
n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
(int)sizeof(struct uhttp_jar));
if (n != (int)sizeof(struct uhttp_jar)) {
n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
(int)sizeof(struct uhttp_jar));
if (n == (int)sizeof(struct uhttp_jar)) {
u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
(int)jar, n);
cookie_sum_saved = persist_sum(jar, (unsigned int)n);
cookie_sum_valid = 1;
}
}
free(jar);
persist_due = u_ticks_ms() + PERSIST_MS;
}
static void persist_mark_origin(const char *origin)
{
int i;
for (i = 0; i < persist_ndirty; i++)
if (s_eq(persist_dirty[i], origin))
return;
if (persist_ndirty < PERSIST_DIRTY_MAX)
s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
}
/* BSTORE.DAT: "NBLS1\n", then per origin "\n\n\n".
* Walk it; returns 1 with the record's fields, 0 at the end. */
static int store_next(const char *buf, unsigned int len, unsigned int *pos,
unsigned int *o_off, unsigned int *o_len,
unsigned int *d_off, unsigned int *d_len,
unsigned int *rec_end)
{
unsigned int p = *pos, v = 0;
if (p >= len)
return 0;
*o_off = p;
while (p < len && buf[p] != '\n')
p++;
if (p >= len)
return 0;
*o_len = p - *o_off;
p++;
while (p < len && buf[p] >= '0' && buf[p] <= '9')
v = v * 10 + (unsigned int)(buf[p++] - '0');
if (p >= len || buf[p] != '\n')
return 0;
p++;
if (v > len - p)
return 0;
*d_off = p;
*d_len = v;
p += v;
if (p < len && buf[p] == '\n')
p++;
*rec_end = p;
*pos = p;
return 1;
}
static int store_load(char **out)
{
char *buf = (char *)malloc(DATA_STORE_MAX + 1);
int n;
*out = buf;
if (!buf)
return -1;
n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
(int)DATA_STORE_MAX);
if (n < (int)s_len(DATA_STORE_MAGIC) ||
!starts_with(buf, DATA_STORE_MAGIC))
return 0;
return n;
}
static int persist_store_lookup(const char *origin, char *out, int cap)
{
char *buf;
unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
unsigned int olen = s_len(origin);
int n = store_load(&buf), rv = -1;
while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
&dl, &e)) {
if (ol == olen && !memcmp(buf + oo, origin, olen)) {
if ((int)dl < cap) {
memcpy(out, buf + d, dl);
out[dl] = '\0';
rv = (int)dl;
}
break;
}
}
free(buf);
return rv;
}
/* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
static void persist_store_flush(void)
{
char *old, *nb, path[48];
unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
int n = store_load(&old), i, w;
nb = (char *)malloc(DATA_STORE_MAX + 1);
if (n < 0 || !nb) {
free(old);
free(nb);
return;
}
s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
/* Untouched origins first, in their old order. */
while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
&dl, &e)) {
int dirty = 0;
for (i = 0; i < persist_ndirty; i++)
if (s_len(persist_dirty[i]) == ol &&
!memcmp(persist_dirty[i], old + oo, ol))
dirty = 1;
if (dirty || nn + (e - oo) > DATA_STORE_MAX)
continue;
memcpy(nb + nn, old + oo, e - oo);
nn += e - oo;
}
/* Then the changed ones (an emptied store is dropped). */
for (i = 0; i < persist_ndirty; i++) {
char num[12];
unsigned int k = 0;
js_origin_path(persist_dirty[i], path, sizeof(path));
w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
(int)DATA_STORE_MAX);
if (w <= 2) /* missing or "{}" */
continue;
s_append_dec(num, &k, (unsigned int)w, sizeof(num));
if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
DATA_STORE_MAX) {
set_status("Saved site data is full; a site's "
"localStorage was not saved", 1, 6000);
continue;
}
s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
nb[nn++] = '\n';
s_append(nb, &nn, num, DATA_STORE_MAX);
nb[nn++] = '\n';
memcpy(nb + nn, old, (unsigned int)w);
nn += (unsigned int)w;
nb[nn++] = '\n';
}
u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
persist_ndirty = 0;
free(old);
free(nb);
}
static void persist_cookies_flush(void)
{
unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
unsigned int sum;
int n;
if (!jar)
return;
n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
(int)sizeof(struct uhttp_jar));
if (n == (int)sizeof(struct uhttp_jar)) {
sum = persist_sum(jar, (unsigned int)n);
if (!cookie_sum_valid || sum != cookie_sum_saved) {
if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
(int)jar, n) >= 0) {
cookie_sum_saved = sum;
cookie_sum_valid = 1;
}
}
}
free(jar);
}
/* Main-loop hook: write back to /data at most every PERSIST_MS. */
static void persist_tick(void)
{
unsigned int now = u_ticks_ms();
if ((int)(now - persist_due) < 0)
return;
persist_due = now + PERSIST_MS;
persist_cookies_flush();
if (persist_ndirty)
persist_store_flush();
}
/* : download the page's module graph on all
* helpers at once into the boot script cache, before any script runs. The
* engine's module loader is sequential (one blocking fetch per import), so
* without this a Vite app with a dozen chunks pays every round trip in a
* row. Failures are ignored; the loader fetches what is missing. */
#define MODULE_PRELOAD_MAX 24
static void prefetch_module_preloads(void)
{
static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
struct fetch_worker *slot[MODULE_PRELOAD_MAX];
unsigned int count = 0, next = 0, done = 0, i;
char err[64];
for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
struct br_node *nd = &doc.nodes[i];
const char *rel, *href;
if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
continue;
rel = br_rel(&doc, i);
href = br_href(&doc, i);
if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
continue;
if (resolve_link(page_url, href, urls[count],
sizeof(urls[count])) != 0 ||
urls[count][0] == '/' || script_cache_has(urls[count]))
continue;
slot[count++] = 0;
}
if (!count)
return;
set_status("Loading modules...", 0, 0);
while (done < count) {
struct fetch_worker *w;
while (next < count && (w = fetch_worker_alloc()) != 0) {
if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
0, 0, 0, err,
sizeof(err)) != 0) {
fetch_worker_release(w);
done++;
} else {
slot[next] = w;
}
next++;
}
worker_wait_ui();
if (cancel_fetch || pending_action) {
fetch_workers_cancel_busy();
return;
}
for (i = 0; i < next; i++) {
unsigned char *body;
int rv, tr = 0;
if (!slot[i])
continue;
rv = fetch_worker_poll(slot[i], err, sizeof(err));
if (rv == 0)
continue;
body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
(unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
if (body) {
rv = fetch_worker_read_body(slot[i], body,
BR_SCRIPT_MAX, image_io_buf,
BR_PAGE_COMP_MAX, &tr, err,
sizeof(err));
if (rv > 0 && !tr)
script_cache_put(urls[i], body,
(unsigned int)rv);
free(body);
}
fetch_worker_release(slot[i]);
slot[i] = 0;
done++;
}
u_sleep_ms(10);
}
}
/* Script prefetch state: one entry per