Просмотр исходного кода

Speed up browser page loading

Index CSS rules by their rightmost selector component and apply matches in document order, cutting large-page style computation by 6-19x.  Keep a long-lived fetch helper with numbered requests, HTTP/TLS keep-alive and a done marker, and skip variable expansion copies for blocks without var().
Johannes Zellner 2 недель назад
Родитель
Сommit
e404955594
4 измененных файлов с 419 добавлено и 83 удалено
  1. 75 20
      browser.c
  2. 184 6
      browser_html.c
  3. 8 0
      browser_html.h
  4. 152 57
      ucmd_curl.c

+ 75 - 20
browser.c

@@ -730,6 +730,7 @@ static int inflate_trunc(const unsigned char *src, unsigned int len,
 #define FETCH_REQ  "/share/bfreq"
 #define FETCH_BODY "/share/bfbody"
 #define FETCH_META "/share/bfmeta"
+#define FETCH_DONE "/share/bfdone"
 #define FETCH_ABORT (-2)
 
 struct fetch_meta {
@@ -746,6 +747,8 @@ static void draw(unsigned int *action);
 static void handle_keys(unsigned int *action);
 static void handle_page_click(unsigned int *action);
 static int fetch_helper_tty = -2;
+static int fetch_helper_pid = -1;
+static unsigned int fetch_seq;
 static struct fetch_meta fetch_meta;
 
 static unsigned int meta_uint(char **pp)
@@ -801,13 +804,48 @@ static void worker_wait_ui(void)
 	ngui_end(&ui);
 }
 
+static void fetch_helper_stop(void)
+{
+	int i;
+
+	if (fetch_helper_pid > 0) {
+		u_kill((unsigned int)fetch_helper_pid);
+		for (i = 0; i < 40 && u_alive((unsigned int)fetch_helper_pid); i++)
+			u_sleep_ms(5);
+		/* Let the reaper release the NIC before the next request. */
+		u_sleep_ms(10);
+	}
+	fetch_helper_pid = -1;
+}
+
+static int fetch_helper_start(char *err, unsigned int errcap)
+{
+	if (fetch_helper_pid > 0 &&
+	    u_alive((unsigned int)fetch_helper_pid))
+		return 0;
+	fetch_helper_pid = -1;
+	if (fetch_helper_tty == -2) {
+		int t = u_tty_create();
+
+		fetch_helper_tty = t > 0 ? t : 0;
+	}
+	fetch_helper_pid = u_spawn("/ramfs/bin/curl", "__serve",
+				   fetch_helper_tty, "/");
+	if (fetch_helper_pid <= 0) {
+		fetch_helper_pid = -1;
+		s_copy(err, "cannot start network helper", errcap);
+		return -1;
+	}
+	return 0;
+}
+
 static int worker_fetch(const char *url, unsigned int cap,
 			struct fetch_meta *m, char *err, unsigned int errcap)
 {
-	static char req[768], meta[1024];
+	static char req[768], meta[1024], done[24];
 	char *p;
-	unsigned int n = 0, deadline, i;
-	int rn, pid;
+	unsigned int n = 0, deadline;
+	int rn, mseq, retried = 0;
 	struct sys_stat st;
 
 	if (cancel_fetch || pending_action)
@@ -817,39 +855,50 @@ static int worker_fetch(const char *url, unsigned int cap,
 		s_copy(err, "network helper unavailable", errcap);
 		return -1;
 	}
+	fetch_seq++;
+	if (!fetch_seq)
+		fetch_seq = 1;
+	s_append_dec(req, &n, fetch_seq, sizeof(req));
+	s_append(req, &n, " ", sizeof(req));
 	s_append_dec(req, &n, cap, sizeof(req));
 	s_append(req, &n, " ", sizeof(req));
 	s_append(req, &n, url, sizeof(req));
 	s_append(req, &n, "\n", sizeof(req));
+	u_syscall1(SYS_UNLINK, (int)FETCH_DONE);
 	u_syscall1(SYS_UNLINK, (int)FETCH_META);
 	if (u_syscall3(SYS_WRITE_FILE, (int)FETCH_REQ, (int)req, (int)n) < 0) {
 		s_copy(err, "cannot queue network request", errcap);
 		return -1;
 	}
-	if (fetch_helper_tty == -2) {
-		int t = u_tty_create();
-
-		fetch_helper_tty = t > 0 ? t : 0;
-	}
-	pid = u_spawn("/ramfs/bin/curl", "__fetch", fetch_helper_tty, "/");
-	if (pid <= 0) {
-		s_copy(err, "cannot start network helper", errcap);
+	if (fetch_helper_start(err, errcap) != 0)
 		return -1;
-	}
 	deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
-	while (u_alive(pid)) {
+	for (;;) {
 		worker_wait_ui();
 		if (cancel_fetch || pending_action) {
-			u_kill(pid);
-			for (i = 0; i < 40 && u_alive(pid); i++)
-				u_sleep_ms(5);
-			/* The reaper releases a dead helper's NIC ownership;
-			 * give it a scheduling chance before the next request. */
-			u_sleep_ms(10);
+			fetch_helper_stop();
 			return FETCH_ABORT;
 		}
+		rn = u_syscall3(SYS_READ_FILE, (int)FETCH_DONE, (int)done,
+				(int)(sizeof(done) - 1));
+		if (rn > 0) {
+			done[rn] = '\0';
+			p = done;
+			mseq = (int)meta_uint(&p);
+			if (mseq == (int)fetch_seq)
+				break;
+		}
+		if (!u_alive((unsigned int)fetch_helper_pid)) {
+			fetch_helper_pid = -1;
+			if (!retried && fetch_helper_start(err, errcap) == 0) {
+				retried = 1;
+				continue;
+			}
+			s_copy(err, "network helper stopped", errcap);
+			return -1;
+		}
 		if ((int)(u_ticks_ms() - deadline) >= 0) {
-			u_kill(pid);
+			fetch_helper_stop();
 			s_copy(err, "network request timed out", errcap);
 			return -1;
 		}
@@ -865,6 +914,11 @@ static int worker_fetch(const char *url, unsigned int cap,
 	}
 	meta[rn] = '\0';
 	p = meta;
+	mseq = (int)meta_uint(&p);
+	if (mseq != (int)fetch_seq) {
+		s_copy(err, "stale network response", errcap);
+		return -1;
+	}
 	m->status = (int)meta_uint(&p);
 	m->error = (int)meta_uint(&p);
 	m->trunc = (int)meta_uint(&p);
@@ -3117,6 +3171,7 @@ void _start(const char *arg)
 			continue;
 		u_sleep_ms(10);
 	}
+	fetch_helper_stop();
 	u_win_close();
 	u_exit(0);
 }

+ 184 - 6
browser_html.c

@@ -5,6 +5,7 @@
 #include "browser_html.h"
 
 static int is_space(char c);
+static int is_ident(char c);
 
 /* ---- storage (one document per process) ---- */
 
@@ -572,12 +573,26 @@ const char *br_type(struct br_doc *d, unsigned int node)
 
 /* ---- document setup / node append ---- */
 
+static void rule_index_reset(struct br_doc *d)
+{
+	unsigned int i;
+
+	for (i = 0; i < BR_MAX_RULES; i++)
+		d->rule_next[i] = 0xFFFF;
+	for (i = 0; i < BR_RULE_HASH; i++)
+		d->rule_bucket[i] = 0xFFFF;
+	for (i = 0; i < BR_TAG_MAX; i++)
+		d->rule_tag[i] = 0xFFFF;
+	d->rule_any = 0xFFFF;
+}
+
 void br_doc_init(struct br_doc *d)
 {
 	unsigned int i;
 
 	for (i = 0; i < sizeof(*d); i++)
 		((unsigned char *)d)[i] = 0;
+	rule_index_reset(d);
 	d->nodes = nodes_store;
 	d->text = text_store;
 	d->attrs = attr_store;
@@ -597,6 +612,7 @@ static void doc_reset(struct br_doc *d)
 	d->attrs_used = 1;
 	d->attrs[0] = '\0';
 	d->nrules = 0;
+	rule_index_reset(d);
 	d->title[0] = '\0';
 	d->inline_css_len = 0;
 	d->nvars = 0;
@@ -2042,6 +2058,73 @@ static int media_list_matches(const char *s, unsigned int len)
 	return 0;
 }
 
+static unsigned int rule_hash(const char *s, unsigned int len)
+{
+	unsigned int h = 2166136261u, i;
+
+	for (i = 0; i < len; i++) {
+		char c = s[i];
+
+		if (c >= 'A' && c <= 'Z')
+			c = (char)(c - 'A' + 'a');
+		h ^= (unsigned char)c;
+		h *= 16777619u;
+	}
+	return h % BR_RULE_HASH;
+}
+
+/* Index a parsed rule by the most selective component of its rightmost
+ * compound selector.  br_style_for() then only visits rules that can
+ * possibly match a node instead of scanning every rule. */
+static void rule_index_add(struct br_doc *d, unsigned int idx,
+			   const char *key, unsigned int len)
+{
+	unsigned int i, cpos = 0, clen = 0, ipos = 0, ilen = 0;
+	unsigned short *head;
+
+	for (i = 0; i < len; i++) {
+		if (key[i] == '.' || key[i] == '#') {
+			unsigned int st = i + 1, n = 0;
+
+			while (st + n < len && is_ident(key[st + n]))
+				n++;
+			if (key[i] == '#') {
+				ipos = st;
+				ilen = n;
+			} else if (n) {
+				cpos = st;
+				clen = n;
+			}
+			i = st + n - 1;
+		}
+	}
+	if (ilen)
+		head = &d->rule_bucket[rule_hash(key + ipos, ilen)];
+	else if (clen)
+		head = &d->rule_bucket[rule_hash(key + cpos, clen)];
+	else if (len == 5 && ci_eq_n(key, ":root", 5))
+		head = &d->rule_tag[BR_TAG_HTML];
+	else if (len && is_ident(key[0])) {
+		char name[16];
+		unsigned int n = 0, tag;
+
+		while (n < len && n + 1 < sizeof(name) && is_ident(key[n])) {
+			name[n] = key[n];
+			n++;
+		}
+		name[n] = '\0';
+		tag = br_tag_from_name(name);
+		if (tag != BR_TAG_UNKNOWN && tag < BR_TAG_MAX)
+			head = &d->rule_tag[tag];
+		else
+			head = &d->rule_any;
+	} else {
+		head = &d->rule_any;
+	}
+	d->rule_next[idx] = *head;
+	*head = (unsigned short)idx;
+}
+
 static int css_collect_only;
 
 static void parse_css(struct br_doc *d, const char *s, unsigned int len)
@@ -2165,10 +2248,20 @@ static void parse_css(struct br_doc *d, const char *s, unsigned int len)
 				off = store_attr(d, sel, k, 79);
 				if (off) {
 					struct br_rule *r = &d->rules[d->nrules++];
+					unsigned int ks = 0, q;
+
+					for (q = 0; q < k; q++)
+						if (sel[q] == ' ' || sel[q] == '>')
+							ks = q + 1;
 					r->sel_off = off;
+					r->key_off = store_attr(d, sel + ks,
+								 k - ks, 79);
 					r->nd = (unsigned char)nd;
 					for (k = 0; k < nd; k++)
 						r->d[k] = decls[k];
+					rule_index_add(d, d->nrules - 1,
+						       attr_ptr(d, r->key_off),
+						       s_len(attr_ptr(d, r->key_off)));
 				}
 			}
 			j = q + 1;
@@ -2389,6 +2482,93 @@ static int selector_match(struct br_doc *d, unsigned int node, const char *s,
 	return (int)selector_specificity(s, len);
 }
 
+#define RULE_MATCH_MAX 512
+
+struct rule_match {
+	unsigned short idx;
+	short spec;
+};
+
+static struct rule_match rule_matches[RULE_MATCH_MAX];
+static unsigned int nrule_matches;
+
+static void rule_try(struct br_doc *d, unsigned int node, unsigned int idx)
+{
+	struct br_rule *r = &d->rules[idx];
+	const char *key = attr_ptr(d, r->key_off);
+	int spec;
+
+	if (key[0] && !compound_match(d, node, key, s_len(key)))
+		return;
+	spec = selector_match(d, node, attr_ptr(d, r->sel_off),
+			      s_len(attr_ptr(d, r->sel_off)));
+	if (spec < 0)
+		return;
+	if (nrule_matches < RULE_MATCH_MAX) {
+		rule_matches[nrule_matches].idx = (unsigned short)idx;
+		rule_matches[nrule_matches].spec = (short)spec;
+		nrule_matches++;
+	}
+}
+
+static void rule_scan_list(struct br_doc *d, unsigned int node,
+			   unsigned short head)
+{
+	while (head != 0xFFFF) {
+		rule_try(d, node, head);
+		head = d->rule_next[head];
+	}
+}
+
+static void rule_scan_class(struct br_doc *d, unsigned int node,
+			    const char *cls, unsigned int len)
+{
+	if (len)
+		rule_scan_list(d, node,
+			       d->rule_bucket[rule_hash(cls, len)]);
+}
+
+static void rule_collect(struct br_doc *d, unsigned int node)
+{
+	const char *cls = attr_ptr(d, d->nodes[node].class_off);
+	const char *id = attr_ptr(d, d->nodes[node].id_off);
+	unsigned int tag = d->nodes[node].tag;
+	unsigned int i;
+
+	nrule_matches = 0;
+	rule_scan_list(d, node, d->rule_any);
+	if (tag < BR_TAG_MAX)
+		rule_scan_list(d, node, d->rule_tag[tag]);
+	if (id[0])
+		rule_scan_list(d, node,
+			       d->rule_bucket[rule_hash(id, s_len(id))]);
+	i = 0;
+	while (cls[i]) {
+		unsigned int st, n;
+
+		while (cls[i] && is_space(cls[i]))
+			i++;
+		st = i;
+		while (cls[i] && !is_space(cls[i]))
+			i++;
+		n = i - st;
+		if (n)
+			rule_scan_class(d, node, cls + st, n);
+	}
+	/* Rules must cascade in document order even though the index visits
+	 * them in bucket order. */
+	for (i = 1; i < nrule_matches; i++) {
+		struct rule_match m = rule_matches[i];
+		unsigned int j = i;
+
+		while (j > 0 && rule_matches[j - 1].idx > m.idx) {
+			rule_matches[j] = rule_matches[j - 1];
+			j--;
+		}
+		rule_matches[j] = m;
+	}
+}
+
 static void apply_decl(struct br_style *st, const struct br_decl *dcl)
 {
 	switch (dcl->prop) {
@@ -2605,14 +2785,12 @@ void br_style_for(struct br_doc *d, unsigned int node,
 			out->color = c;
 	}
 
-	for (i = 0; i < d->nrules; i++) {
-		struct br_rule *r = &d->rules[i];
-		const char *sel = attr_ptr(d, r->sel_off);
-		int spec = selector_match(d, node, sel, s_len(sel));
+	rule_collect(d, node);
+	for (i = 0; i < nrule_matches; i++) {
+		struct br_rule *r = &d->rules[rule_matches[i].idx];
+		int spec = rule_matches[i].spec;
 		unsigned int k;
 
-		if (spec < 0)
-			continue;
 		for (k = 0; k < r->nd; k++)
 			cascade_decl(out, &r->d[k], spec, best, best_imp);
 	}

+ 8 - 0
browser_html.h

@@ -12,6 +12,8 @@
 #define BR_CSS_SIZE      12288
 #define BR_MAX_RULES     2304
 #define BR_MAX_VARS      512
+#define BR_TAG_MAX       128
+#define BR_RULE_HASH     256
 #define BR_DECLS         16
 #define BR_TITLE_MAX     96
 
@@ -127,6 +129,7 @@ struct br_decl {
 
 struct br_rule {
 	unsigned int sel_off;       /* selector text in the attr arena */
+	unsigned int key_off;       /* rightmost compound, for a fast prefilter */
 	unsigned char nd;
 	struct br_decl d[BR_DECLS];
 };
@@ -148,6 +151,11 @@ struct br_doc {
 	unsigned int var_name[BR_MAX_VARS];
 	unsigned int var_val[BR_MAX_VARS];
 	unsigned int nvars;
+	/* Rule index: rightmost class/id/tag -> linked list of rule indices. */
+	unsigned short rule_next[BR_MAX_RULES];
+	unsigned short rule_bucket[BR_RULE_HASH];
+	unsigned short rule_tag[BR_TAG_MAX];
+	unsigned short rule_any;
 	int truncated;
 	int plain;                  /* text/plain: one preformatted text node */
 };

+ 152 - 57
ucmd_curl.c

@@ -60,6 +60,7 @@ static const struct uhttp_hooks hooks = {
 #define FETCH_REQ   "/share/bfreq"
 #define FETCH_BODY  "/share/bfbody"
 #define FETCH_META  "/share/bfmeta"
+#define FETCH_DONE  "/share/bfdone"
 #define FETCH_MAX   (2u * 1024u * 1024u)
 
 static unsigned int c_len(const char *s)
@@ -113,17 +114,79 @@ static void fetch_fail(unsigned int status, int err, const char *ctype,
 	u_syscall3(SYS_WRITE_FILE, (int)FETCH_META, (int)meta, (int)n);
 }
 
+static void write_meta(unsigned int seq, int with_seq, struct uhttp *h,
+		       int err, unsigned int body_len, unsigned int body_trunc)
+{
+	char meta[1024];
+	unsigned int n = 0;
+
+	if (with_seq) {
+		app_dec(meta, &n, seq, sizeof(meta));
+		app_ch(meta, &n, '\n', sizeof(meta));
+	}
+	app_dec(meta, &n, (unsigned int)h->resp.status, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, (unsigned int)err, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, body_trunc, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_str(meta, &n, h->resp.content_encoding, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_str(meta, &n, h->resp.content_type, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_str(meta, &n, h->resp.final_url, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	app_dec(meta, &n, body_len, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
+	u_syscall3(SYS_WRITE_FILE, (int)FETCH_META, (int)meta, (int)n);
+}
+
+/* Fetch one URL through a possibly reused keep-alive connection. */
+static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
+			 unsigned char *buf, unsigned int *outlen,
+			 unsigned int *outtrunc, int *outerr)
+{
+	unsigned int total = 0;
+	int rv, trunc = 0, err = 0;
+
+	*outlen = 0;
+	*outtrunc = 0;
+	*outerr = 0;
+	rv = uhttp_open(h, url, 0, 0);
+	if (rv == UHTTP_ERR_BUSY) {
+		int tries;
+
+		for (tries = 0; tries < 50 && rv == UHTTP_ERR_BUSY; tries++) {
+			u_sleep_ms(20);
+			rv = uhttp_open(h, url, 0, 0);
+		}
+	}
+	if (rv != 0) {
+		*outerr = rv;
+		return;
+	}
+	for (;;) {
+		rv = uhttp_read(h, buf + total, cap - total,
+				UHTTP_IDLE_TIMEOUT_MS);
+		if (rv > 0) {
+			total += (unsigned int)rv;
+			if (total >= cap) {
+				trunc = 1;
+				break;
+			}
+			continue;
+		}
+		if (rv < 0)
+			err = rv;
+		break;
+	}
+	*outlen = total;
+	*outtrunc = (unsigned int)trunc;
+	*outerr = err;
+}
+
 static void fetch_once(void)
 {
 	static struct uhttp h;
 	char req[768];
-	char meta[768];
-	unsigned char *buf, *body;
-	unsigned int cap = 0, total = 0, n = 0;
+	unsigned char *buf;
+	unsigned int cap = 0;
 	unsigned int body_len = 0, body_trunc = 0;
-	unsigned int i, trunc = 0;
-	int rn, rv, err = 0;
-	const char *enc_out;
+	unsigned int i;
+	int rn, err = 0;
 
 	rn = u_syscall3(SYS_READ_FILE, (int)FETCH_REQ, (int)req,
 			(int)(sizeof(req) - 1));
@@ -154,64 +217,95 @@ static void fetch_once(void)
 
 	uhttp_init(&h);
 	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
-	rv = uhttp_open(&h, req + i, 0, 0);
-	/* The browser cancels a page load by killing our predecessor.  It can
-	 * still own the single NIC receiver for a tick or two, so a fresh
-	 * helper waits briefly instead of failing the new page outright. */
-	if (rv == UHTTP_ERR_BUSY) {
-		int tries;
+	helper_fetch(&h, req + i, cap, buf, &body_len, &body_trunc, &err);
+	if (body_len)
+		u_syscall3(SYS_WRITE_FILE, (int)FETCH_BODY, (int)buf,
+			   (int)body_len);
+	write_meta(0, 0, &h, err, body_len, body_trunc);
+	uhttp_close(&h);
+	u_mem_free();
+	u_exit(err ? 1 : 0);
+}
 
-		for (tries = 0; tries < 50 && rv == UHTTP_ERR_BUSY; tries++) {
-			u_sleep_ms(20);
-			rv = uhttp_open(&h, req + i, 0, 0);
-		}
-	}
-	if (rv != 0) {
-		err = rv;
-		fetch_fail(0, err, h.resp.content_type,
-			   h.resp.content_encoding, h.resp.final_url);
-		uhttp_close(&h);
-		u_mem_free();
+/* Long-lived helper: the browser writes a numbered request, we fetch it
+ * (reusing the same TCP/TLS connection whenever the host is unchanged) and
+ * publish body + meta + a small done marker.  Idle instances exit and
+ * release the NIC after ten seconds. */
+static void fetch_serve(void)
+{
+	static struct uhttp h;
+	char req[768];
+	unsigned char *buf;
+	unsigned int last_seq = 0, idle = 0;
+
+	buf = (unsigned char *)u_mem_alloc(FETCH_MAX);
+	if (!buf)
 		u_exit(1);
-	}
+	uhttp_init(&h);
+	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
+	h.keepalive = 1;
 
 	for (;;) {
-		rv = uhttp_read(&h, buf + total, cap - total,
-				UHTTP_IDLE_TIMEOUT_MS);
-		if (rv > 0) {
-			total += (unsigned int)rv;
-			if (total >= cap) {
-				trunc = 1;
-				break;
+		unsigned int seq = 0, cap = 0, body_len = 0, body_trunc = 0;
+		char done[16];
+		unsigned int dn = 0;
+		unsigned int i = 0;
+		char *url;
+		int rn, err = 0;
+
+		rn = u_syscall3(SYS_READ_FILE, (int)FETCH_REQ, (int)req,
+				(int)(sizeof(req) - 1));
+		if (rn <= 0) {
+			url = 0;
+		} else {
+			req[rn] = '\0';
+			while (req[i] >= '0' && req[i] <= '9') {
+				seq = seq * 10 + (unsigned int)(req[i] - '0');
+				i++;
 			}
+			while (req[i] == ' ')
+				i++;
+			while (req[i] >= '0' && req[i] <= '9') {
+				cap = cap * 10 + (unsigned int)(req[i] - '0');
+				i++;
+			}
+			while (req[i] == ' ')
+				i++;
+			while (rn > 0 && (req[rn - 1] == '\n' ||
+					  req[rn - 1] == '\r'))
+				req[--rn] = '\0';
+			url = (i < (unsigned int)rn) ? req + i : 0;
+		}
+		if (!url || !url[0] || seq == last_seq) {
+			idle++;
+			u_sleep_ms(50);
+			if (idle >= 200)
+				break;
 			continue;
 		}
-		if (rv < 0) {
-			err = rv;
+		idle = 0;
+		last_seq = seq;
+		if (cap == 0 || cap > FETCH_MAX)
+			cap = FETCH_MAX;
+
+		helper_fetch(&h, url, cap, buf, &body_len, &body_trunc, &err);
+		if (body_len)
+			u_syscall3(SYS_WRITE_FILE, (int)FETCH_BODY, (int)buf,
+				   (int)body_len);
+		write_meta(seq, 1, &h, err, body_len, body_trunc);
+		app_dec(done, &dn, seq, sizeof(done));
+		u_syscall3(SYS_WRITE_FILE, (int)FETCH_DONE, (int)done, (int)dn);
+
+		if (err || body_trunc || h.peer_close) {
+			h.keepalive = 0;
+			uhttp_close(&h);
+			h.keepalive = 1;
 		}
-		break;
 	}
-
-	body = buf;
-	body_len = total;
-	body_trunc = trunc;
-	enc_out = h.resp.content_encoding;
-	if (body_len)
-		u_syscall3(SYS_WRITE_FILE, (int)FETCH_BODY, (int)body,
-			   (int)body_len);
-
-	app_dec(meta, &n, (unsigned int)h.resp.status, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
-	app_dec(meta, &n, (unsigned int)err, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
-	app_dec(meta, &n, body_trunc, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
-	app_str(meta, &n, enc_out, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
-	app_str(meta, &n, h.resp.content_type, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
-	app_str(meta, &n, h.resp.final_url, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
-	app_dec(meta, &n, body_len, sizeof(meta)); app_ch(meta, &n, '\n', sizeof(meta));
-	u_syscall3(SYS_WRITE_FILE, (int)FETCH_META, (int)meta, (int)n);
-
+	h.keepalive = 0;
 	uhttp_close(&h);
 	u_mem_free();
-	u_exit(err ? 1 : 0);
+	u_exit(0);
 }
 
 void _start(const char *arg)
@@ -221,10 +315,11 @@ void _start(const char *arg)
 	unsigned int total = 0;
 	int rv;
 
-	if (arg && c_len(arg) == 7 && arg[0] == '_' &&
-	    arg[1] == '_' && arg[2] == 'f' && arg[3] == 'e' &&
-	    arg[4] == 't' && arg[5] == 'c' && arg[6] == 'h') {
-		fetch_once();
+	if (arg && c_len(arg) == 7 && arg[0] == '_' && arg[1] == '_') {
+		if (arg[2] == 'f')
+			fetch_once();
+		else if (arg[2] == 's')
+			fetch_serve();
 	}
 	if (!arg || !arg[0]) {
 		u_puts("curl: usage curl <http|https://host[:port]/[path]>\n");