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

Harden parallel browser networking

Cache DNS answers for concurrent workers, fix TCP retransmit/connect races, raise the socket table to 12, and give each browser window unique helper files via SYS_GETPID.
Johannes Zellner 1 неделя назад
Родитель
Сommit
789b6cb931
11 измененных файлов с 214 добавлено и 57 удалено
  1. 7 5
      AGENTS.md
  2. 19 8
      browser.c
  3. 97 1
      dns.c
  4. 11 8
      docs/network.html
  5. 3 3
      docs/userland.html
  6. 1 1
      netcore.c
  7. 2 0
      syscall.c
  8. 3 0
      syscall.h
  9. 37 6
      tcp.c
  10. 29 25
      ucmd_curl.c
  11. 5 0
      ucmd_lib.h

+ 7 - 5
AGENTS.md

@@ -539,8 +539,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   server from option 6). `netcmd.c` — the
   `netinfo`/`netrecv`/`netsend`/`netip`/`dhcp`/`pong`/`ping`/`netregs`
   commands.  `dns.c/h` — a minimal resolver (one recursive A query over UDP,
-  name-compression aware; `netdns` shows/sets the server, `host <name>`
-  resolves).  `ntp.c/h` — a minimal SNTP client (RFC 4330): one 48-byte
+  name-compression aware, one query in flight plus a five-minute A-record
+  cache for parallel stack callers; `netdns` shows/sets the server,
+  `host <name>` resolves).  `ntp.c/h` — a minimal SNTP client (RFC 4330): one 48-byte
   request to UDP port 123, three one-second tries, origin-timestamp
   validation and the reply's transmit timestamp converted from the 1900
   epoch to UTC.  `SYS_NTP_SYNC` exposes it to the Date & Time app; the
@@ -870,7 +871,8 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   position is within the viewport plus 160 px; deferred images are loaded as
   the page scrolls.  Network work runs in up to `FETCH_WORKERS` (three)
   headless `curl __serve` helper processes (`ucmd_curl.c`), each with its own
-  `/share/bfreqN`, `bfbodyN`, `bfmetaN` and `bfdoneN` files.  The browser
+  `/share/bf<session>_<slot>*` files (`session` comes from the browser pid, so
+  two browser windows cannot collide).  The browser
   starts jobs, harvests completed ones from its main loop and decodes them,
   so text and scrolling stay responsive while several TCP/TLS connections are
   in flight; page/CSS/script fetches stay ordered.  Each helper keeps its own
@@ -962,7 +964,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   pauses while one owns it, and the reaper force-releases it if that process
   dies (`sys_net_reap`, driven by `netdev_owner()`/`netdev_release_all()`).
   TCP clients do NOT take that lease: `tcp.c` keeps a table of up to
-  `TCP_CLIENT_MAX` (six) connections, one per process, each with its own 4 KB
+  `TCP_CLIENT_MAX` (twelve) connections, one per process, each with its own 4 KB
   receive queue and source port.  `TCP_CONNECT/PEER_MSS/SEND/RECV/CLOSE` keep
   their ABI and look the connection up by calling pid; `NET_NEXT_HOP`/`NET_ARP`
   provide the route to the peer.  Every stack syscall drains the NIC through
@@ -1572,7 +1574,7 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
 
 21. The TCP backlog's early-request buffers cost 8 KB of kernel BSS
     (8 slots x 1 KB), and the FAT listing cache another 5 KB.  The command
-    pack is out of the kernel now, so `_end` keeps ~100 KB of headroom below
+    pack is out of the kernel now, so `_end` keeps ~70 KB of headroom below
     the `0x90000` wall; the remaining limit is kernel code/buffers only.
 
 22. Browser limits: JavaScript runs inline and external classic scripts on

+ 19 - 8
browser.c

@@ -1810,6 +1810,7 @@ struct fetch_worker {
 
 static struct fetch_worker fetch_workers[FETCH_WORKERS];
 static int fetch_tty = -2;
+static unsigned int fetch_session;
 static unsigned int fetch_seq;
 static struct fetch_meta fetch_meta;
 
@@ -1866,12 +1867,16 @@ static void worker_wait_ui(void)
 	ngui_end(&ui);
 }
 
-static void fetch_path(char *out, unsigned int cap, const char *base, int slot)
+static void fetch_path(char *out, unsigned int cap, const char *kind,
+		       unsigned int session, int slot)
 {
 	unsigned int n = 0;
 
-	s_append(out, &n, base, cap);
+	s_append(out, &n, "/share/bf", cap);
+	s_append_dec(out, &n, session, cap);
+	s_append(out, &n, "_", cap);
 	s_append_dec(out, &n, (unsigned int)slot, cap);
+	s_append(out, &n, kind, cap);
 }
 
 static void fetch_pool_init(void)
@@ -1882,16 +1887,20 @@ static void fetch_pool_init(void)
 	if (ready)
 		return;
 	ready = 1;
+	fetch_session = ((unsigned int)u_getpid() << 16) ^
+			(u_ticks_ms() & 0xFFFFu);
+	if (!fetch_session)
+		fetch_session = 1;
 	for (i = 0; i < FETCH_WORKERS; i++) {
 		struct fetch_worker *w = &fetch_workers[i];
 
 		w->pid = -1;
 		w->slot = i;
-		fetch_path(w->req, sizeof(w->req), "/share/bfreq", i);
-		fetch_path(w->body, sizeof(w->body), "/share/bfbody", i);
-		fetch_path(w->meta, sizeof(w->meta), "/share/bfmeta", i);
-		fetch_path(w->done, sizeof(w->done), "/share/bfdone", i);
-		fetch_path(w->post, sizeof(w->post), "/share/bfpost", i);
+		fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
+		fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
+		fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
+		fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
+		fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
 	}
 }
 
@@ -1929,7 +1938,7 @@ static void fetch_workers_stop_all(void)
 static int fetch_worker_start(struct fetch_worker *w, char *err,
 			      unsigned int errcap)
 {
-	char arg[24];
+	char arg[40];
 	unsigned int n = 0;
 
 	if (w->pid > 0 && u_alive((unsigned int)w->pid))
@@ -1942,6 +1951,8 @@ static int fetch_worker_start(struct fetch_worker *w, char *err,
 		fetch_tty = t > 0 ? t : 0;
 	}
 	s_append(arg, &n, "__serve ", sizeof(arg));
+	s_append_dec(arg, &n, fetch_session, sizeof(arg));
+	s_append(arg, &n, " ", sizeof(arg));
 	s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
 	w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
 	if (w->pid <= 0) {

+ 97 - 1
dns.c

@@ -20,7 +20,10 @@
 #define DNS_MAX_ANSWERS 4
 #define DNS_RETRY_MS    1000
 #define DNS_RETRIES     3
-#define DNS_WAIT_MS     5000
+#define DNS_WAIT_MS     15000
+#define DNS_CACHE_MAX   8
+#define DNS_CACHE_TTL_MS 300000
+#define DNS_CACHE_NAME  96
 
 /* Query buffer: 12-byte header + a 255-byte name + qtype/qclass. */
 static unsigned char query_buf[12 + 260 + 4];
@@ -37,6 +40,16 @@ static unsigned char dns_pending_extra[DNS_MAX_ANSWERS][4];
 static unsigned int dns_pending_count;
 static int dns_pending_result;      /* 0 none, 1 answer, -1 failure */
 
+/* Small A-record cache so parallel browser workers that ask for the same
+ * host do not queue a separate query each. */
+struct dns_cache_entry {
+	char name[DNS_CACHE_NAME];
+	unsigned char ip[4];
+	unsigned int age_ms;
+	int used;
+};
+static struct dns_cache_entry dns_cache[DNS_CACHE_MAX];
+
 static void put_dec(unsigned int v)
 {
 	char b[12];
@@ -256,6 +269,77 @@ static void dns_print_answer(const char *name, const unsigned char *ip,
 	io_putchar('\n');
 }
 
+static void dns_print_cached(const char *name, const unsigned char *ip)
+{
+	io_putstr("dns: ");
+	io_putstr(name);
+	io_putstr(" -> ");
+	put_ip(ip);
+	io_putchar('\n');
+}
+
+static int dns_name_eq(const char *a, const char *b)
+{
+	while (*a && *b && *a == *b)
+		a++, b++;
+	return *a == *b;
+}
+
+static int dns_cache_lookup(const char *name, unsigned char ip[4])
+{
+	unsigned int i, now = get_ticks_ms();
+
+	for (i = 0; i < DNS_CACHE_MAX; i++) {
+		if (!dns_cache[i].used ||
+		    !dns_name_eq(dns_cache[i].name, name))
+			continue;
+		if (now - dns_cache[i].age_ms > DNS_CACHE_TTL_MS) {
+			dns_cache[i].used = 0;
+			return 0;
+		}
+		ip[0] = dns_cache[i].ip[0];
+		ip[1] = dns_cache[i].ip[1];
+		ip[2] = dns_cache[i].ip[2];
+		ip[3] = dns_cache[i].ip[3];
+		return 1;
+	}
+	return 0;
+}
+
+static void dns_cache_put(const char *name, const unsigned char ip[4])
+{
+	unsigned int i, n = 0, slot = 0;
+
+	while (name[n] && n + 1 < DNS_CACHE_NAME)
+		n++;
+	if (name[n])                       /* too long: do not truncate */
+		return;
+	for (i = 0; i < DNS_CACHE_MAX; i++) {
+		if (dns_cache[i].used && dns_name_eq(dns_cache[i].name, name)) {
+			slot = i;
+			goto store;
+		}
+	}
+	for (i = 0; i < DNS_CACHE_MAX; i++) {
+		if (!dns_cache[i].used) {
+			slot = i;
+			goto store;
+		}
+		if (dns_cache[i].age_ms < dns_cache[slot].age_ms)
+			slot = i;
+	}
+store:
+	for (i = 0; i < n; i++)
+		dns_cache[slot].name[i] = name[i];
+	dns_cache[slot].name[n] = '\0';
+	dns_cache[slot].ip[0] = ip[0];
+	dns_cache[slot].ip[1] = ip[1];
+	dns_cache[slot].ip[2] = ip[2];
+	dns_cache[slot].ip[3] = ip[3];
+	dns_cache[slot].age_ms = get_ticks_ms();
+	dns_cache[slot].used = 1;
+}
+
 int dns_resolve(const char *name, unsigned char ip[4])
 {
 	unsigned char server[4], hop[4], server_mac[6];
@@ -271,6 +355,10 @@ int dns_resolve(const char *name, unsigned char ip[4])
 		io_putstr("dns: no NIC found\n");
 		return -1;
 	}
+	if (dns_cache_lookup(name, ip)) {
+		dns_print_cached(name, ip);
+		return 0;
+	}
 
 	raw = pid && netdev_owner() == pid;
 	if (!raw)
@@ -294,6 +382,12 @@ int dns_resolve(const char *name, unsigned char ip[4])
 	dns_pending_result = 0;
 	dns_pending_count = 0;
 
+	/* The waiter we just queued behind may have filled the cache. */
+	if (dns_cache_lookup(name, ip)) {
+		dns_print_cached(name, ip);
+		goto out;
+	}
+
 	net_get_dns(server);
 	if (!(server[0] || server[1] || server[2] || server[3])) {
 		/* Home routers usually proxy DNS for their clients. */
@@ -370,6 +464,7 @@ int dns_resolve(const char *name, unsigned char ip[4])
 					goto out;
 				if (r == 0)
 					continue;
+				dns_cache_put(name, ip);
 				dns_print_answer(name, ip, extra, count);
 				r = 0;
 				goto out;
@@ -386,6 +481,7 @@ int dns_resolve(const char *name, unsigned char ip[4])
 							dns_pending_extra[i][j];
 				}
 				count = dns_pending_count;
+				dns_cache_put(name, ip);
 				dns_print_answer(name, ip, extra, count);
 				r = 0;
 				goto out;

+ 11 - 8
docs/network.html

@@ -38,7 +38,7 @@
 			The NIC and the protocol stack live in the kernel; ring-3 commands
 			drive them through <code>SYS_NET_*</code> and <code>SYS_TCP_*</code>.
 			Packet-level commands still take the receiver exclusively through
-			<code>SYS_NET_ACQUIRE</code>, while up to six processes can hold a
+			<code>SYS_NET_ACQUIRE</code>, while up to twelve processes can hold a
 			TCP client connection at the same time.  Every stack syscall drains
 			the NIC through <code>net_pump()</code>, so downloads overlap without
 			sharing one connection or one receive queue.
@@ -197,7 +197,10 @@
 		<h3>DNS</h3>
 		<p>
 			<span class="file">dns.c</span> sends one recursive A query over UDP
-			and handles name compression in the response. <code>netdns</code>
+			and handles name compression in the response.  One query is in
+			flight at a time; parallel stack callers wait for it and then hit a
+			small five-minute A-record cache, so three browser workers asking
+			for the same host cause one DNS query, not three.  <code>netdns</code>
 			shows or sets the server; <code>host &lt;name&gt;</code> resolves.
 			Numeric hosts skip DNS entirely.
 		</p>
@@ -214,9 +217,9 @@
 			to a UTC <code>struct sys_datetime</code> (with the 2036 era wrap
 			handled).  <code>SYS_NTP_SYNC</code> returns that value to ring 3;
 			the Date &amp; Time editor then writes it through
-			<code>SYS_RTC_SET</code>.  The service owns the receiver for the
-			duration, so it reports <code>SYS_NTP_EBUSY</code> while another
-			network command owns the NIC.
+			<code>SYS_RTC_SET</code>.  The service owns the raw receiver for the
+			duration, so it reports <code>SYS_NTP_EBUSY</code> while another raw
+			command or a TCP client is active.
 		</p>
 		<div class="warn">
 			<p><strong>NTP is unauthenticated.</strong> The origin-timestamp
@@ -232,7 +235,7 @@
 		<p>
 			<span class="file">tcp.c</span> implements a small client table, not a
 			general socket layer: each process may hold one connect/send/receive/
-			close connection, and up to <code>TCP_CLIENT_MAX</code> (six)
+			close connection, and up to <code>TCP_CLIENT_MAX</code> (twelve)
 			connections can be active.  Every connection owns a 4 KB receive
 			queue, so one socket's data can never be read or reset by another.
 			The window update is sent whenever the application drains the queue,
@@ -319,7 +322,7 @@
 		<ul>
 			<li><strong>curl</strong> — <code>http://</code> or <code>https://</code> GET with DNS, ARP, redirects (up to five hops), chunked decoding, status/headers/body dump and a TLS warning.</li>
 			<li><strong>uhttp</strong> — shared ring-3 HTTP/1.1 client used by curl and the browser: URL parsing, redirects, chunked decoding, timeouts and TLS.</li>
-			<li><strong>browser</strong> — runs network fetches in up to three headless <code>curl __serve</code> workers, each with its own request/body/meta files under <code>/share</code>.  Images are prefetched in parallel and decoded as jobs complete, so the UI keeps drawing and scrolling.  Each worker keeps its own TCP/TLS connection.</li>
+			<li><strong>browser</strong> — runs network fetches in up to three headless <code>curl __serve</code> workers, each with its own request/body/meta files under <code>/share/bf&lt;session&gt;_&lt;slot&gt;*</code>.  The session id comes from the browser pid, so multiple browser windows do not share queue files.  Images are prefetched in parallel and decoded as jobs complete, so the UI keeps drawing and scrolling.  Each worker keeps its own TCP/TLS connection.</li>
 			<li><strong>websrv</strong> — the server side, speaking HTTP/1.1 + WebDAV over the TCP listener; see <a href="filesystems.html#webdav">Filesystems → WebDAV</a>.</li>
 		</ul>
 		<p>
@@ -341,7 +344,7 @@
 					<tr><td>TLS DRBG</td><td>Weak (RDTSC/ticks/MAC)</td><td>Not suitable for high-value secrets.</td></tr>
 					<tr><td>WebDAV</td><td>No authentication</td><td>Anyone on the LAN can read mounts and write <code>/share</code>.</td></tr>
 					<tr><td>NTP</td><td>Unauthenticated SNTP</td><td>Anyone who can answer for the server name can set the clock.</td></tr>
-					<tr><td>NIC ownership</td><td>Raw lease for packet commands; shared TCP client table</td><td>Raw commands are mutually exclusive; up to six processes can hold one TCP connection each.  A killed owner is force-released.</td></tr>
+					<tr><td>NIC ownership</td><td>Raw lease for packet commands; shared TCP client table</td><td>Raw commands are mutually exclusive; up to twelve processes can hold one TCP connection each.  A killed owner is force-released.</td></tr>
 					<tr><td>Kernel/user isolation</td><td>None (identity map)</td><td>A ring-3 bug can reach any mapped kernel page.</td></tr>
 				</tbody>
 			</table>

+ 3 - 3
docs/userland.html

@@ -224,14 +224,14 @@
 					<tr><td>System info</td><td>12–16, 49–51, 91–92, 102–103, 107</td><td>memory, E820, mouse, storage, blkdev, procinfo, cursor, CPU temp, sensors, EC sensors, Chrome EC sensors, AC/battery</td></tr>
 					<tr><td>Network</td><td>17–47, 106</td><td>NIC config/acquire, raw frames, DHCP/DNS/NTP, TCP client, ARP, cwd</td></tr>
 					<tr><td>Window &amp; WM</td><td>55, 57–72, 80, 83–87</td><td>key poll, WM attach/info/map/present/create_term, window create/present/input/resize</td></tr>
-					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90</td><td>TTY, spawn, alive, kill, chdir, scheduler info, heap alloc/grow/free</td></tr>
+					<tr><td>Process &amp; memory</td><td>73–79, 81, 88–90, 108</td><td>TTY, spawn, getpid, alive, kill, chdir, scheduler info, heap alloc/grow/free</td></tr>
 					<tr><td>TCP server</td><td>93–97, 99–101</td><td>listen, accept, server recv/send/close, peer, speed, MAC set</td></tr>
 				</tbody>
 			</table>
 		</div>
 		<p>
 			The file service is whole-file, not stream-oriented. The network
-			service has a per-process TCP client table (up to six connections)
+			service has a per-process TCP client table (up to twelve connections)
 			and a separate raw NIC lease for packet-level commands. There is no
 			<code>fork</code>, <code>exec</code> or shared memory: a command
 			either runs as its own process from an ELF or calls a kernel command.
@@ -373,7 +373,7 @@
 			<li><strong>Not supported.</strong> Inline event attributes (<code>onclick=</code>), <code>MouseEvent</code>/<code>CustomEvent</code> and <code>once</code>/<code>passive</code> listener options, <code>type="module"</code>, <code>defer</code>/<code>async</code>, <code>MutationObserver</code>/<code>IntersectionObserver</code>, <code>XMLHttpRequest</code>/<code>fetch</code>, <code>DOMParser</code>, canvas/2D contexts and pseudo-class/element selectors. Basic controls render, focus, edit, toggle, select, submit GET queries and POST <code>application/x-www-form-urlencoded</code> bodies (see the compatibility ladder); <code>getComputedStyle</code> covers the engine's properties, and <code>outerHTML</code> only returns the string last assigned to <code>innerHTML</code>.</li>
 			<li><strong>CSS gaps.</strong> Multiple background layers and <code>background-attachment</code> (a non-uniform <code>background-size</code> uses the width scale), 3D/perspective transforms and transformed text/descendants (scale/rotate paint the box and inline images), pseudo-classes/elements, border-radius clipping of descendants, gradients/box-shadow/transitions and <code>color-mix</code>. Flex rows, card grids, tables with rowspan/colspan, inline SVG and CSS variables are supported.</li>
 			<li><strong>Caps.</strong> 2 MB page body, 832 KB CSS, 6144 DOM nodes, 4608 rules, 16 images. Each image gets an <code>img_estimate()</code>-sized decode arena that is freed after the scaled bitmap is made; navigation calls <code>heap_reset()</code> and unmaps the page heap.</li>
-			<li><strong>Fetching.</strong> Up to three worker processes prefetch images in parallel within the viewport plus 160 px; each worker keeps its own TCP/TLS connection and its own request/body/meta files.  Completed images are decoded as jobs finish.  Page, CSS and script fetches stay ordered.</li>
+			<li><strong>Fetching.</strong> Up to three worker processes prefetch images in parallel within the viewport plus 160 px; each worker keeps its own TCP/TLS connection and its own request/body/meta files (keyed by browser pid and worker slot, so multiple windows do not collide).  Completed images are decoded as jobs finish.  Page, CSS and script fetches stay ordered.</li>
 			<li><strong>URL entry.</strong> A dotted name without a scheme that is not a known local file extension is treated as a hostname, so <code>cloudron.io</code> does not hit the local-file stat. Origin-level redirects (the common <code>http://host</code> → <code>https://host</code> → <code>https://www.host</code> chain) are cached per process and in <code>/share/borigins</code>; the first visit still follows them, later visits go straight to the canonical origin. Remote stylesheets are cached under <code>/share/bcss-*</code> for the current boot, so a reload or a fresh browser launch skips the CSS downloads.</li>
 			</ul>
 		<p>

+ 1 - 1
netcore.c

@@ -15,7 +15,7 @@ static unsigned char reply_buf[NETDEV_FRAME_MAX];
 
 /* Stack operations that may sleep between pumps, tracked per process so a
  * killed waiter cannot leave the netkexec/netlog gates stuck. */
-#define NET_STACK_MAX 8
+#define NET_STACK_MAX 16
 static struct {
 	unsigned int pid;
 	unsigned int depth;

+ 2 - 0
syscall.c

@@ -403,6 +403,8 @@ static int syscall_dispatch_locked(int num, int a1, int a2, int a3)
 			return -1;
 		return term_kcmd_spawn(name, arg, (unsigned int)a3);
 	}
+	case SYS_GETPID:
+		return (int)current_proc()->pid;
 	case SYS_ALIVE:
 		return process_is_alive((unsigned int)a1);
 	case SYS_KILL:

+ 3 - 0
syscall.h

@@ -159,6 +159,9 @@
 /* Chrome OS EC temperature/fan/switch snapshot (see cros_ec.c). */
 #define SYS_CROS_EC_SENSORS 107  /* (struct sys_cros_sensors *out) -> 0/-1 */
 
+/* Current process id (used for per-process temporary paths). */
+#define SYS_GETPID        108  /* () -> pid */
+
 /* Stat one path (the file service has no open handle). */
 #define SYS_FS_STAT        98  /* (path, struct sys_stat *out) -> 0/<0 */
 

+ 37 - 6
tcp.c

@@ -22,7 +22,7 @@
 
 /* Client sockets: one per process, plus a little headroom.  4 KB per queue
  * keeps the kernel BSS cost modest (the old single queue was 8 KB). */
-#define TCP_CLIENT_MAX 6
+#define TCP_CLIENT_MAX 12
 #define TCP_RXQ_SIZE   4096
 
 /* Listening port for the server side (0 = not listening).  Declared here
@@ -491,6 +491,17 @@ int tcp_client_connect(unsigned int pid, const unsigned char mac[6],
 		unsigned int flags;
 		int r;
 
+		/* A SYN-ACK may have arrived just after the previous
+		 * deadline check; do not send a second SYN on an open
+		 * connection. */
+		if (c->state == TCP_STATE_ESTABLISHED)
+			return 0;
+		if (c->state == TCP_STATE_CLOSED) {
+			r = cl->err ? cl->err : -2;
+			client_free(cl);
+			return r;
+		}
+
 		flags = net_irq_enter();
 		r = tcp_send_segment(c, TCP_SYN, c->snd_nxt, 0, 0, 0, 1);
 		net_irq_exit(flags);
@@ -511,6 +522,14 @@ int tcp_client_connect(unsigned int pid, const unsigned char mac[6],
 			process_sleep_ms(1);
 		}
 	}
+	if (c->state == TCP_STATE_ESTABLISHED)
+		return 0;
+	if (c->state == TCP_STATE_CLOSED) {
+		int err = cl->err ? cl->err : -2;
+
+		client_free(cl);
+		return err;
+	}
 	client_free(cl);
 	return -1;
 }
@@ -519,6 +538,7 @@ int tcp_client_send(unsigned int pid, const void *buf, unsigned int len)
 {
 	struct tcp_client *cl = client_find(pid);
 	struct tcp_conn *c;
+	unsigned int seq;
 	unsigned int tries;
 
 	if (!cl)
@@ -529,30 +549,41 @@ int tcp_client_send(unsigned int pid, const void *buf, unsigned int len)
 	if (len > c->peer_mss)
 		return -3;
 
+	seq = c->snd_nxt;
+	c->snd_nxt = seq + len;
+
 	for (tries = 0; tries < TCP_RETRIES; tries++) {
-		unsigned int seq = c->snd_nxt;
 		unsigned int deadline = get_ticks_ms() + TCP_RETRY_MS;
 		unsigned int flags;
 		int r;
 
+		/* An ACK may have arrived just after the previous deadline
+		 * check; never resend the payload at a fresh sequence. */
+		if ((int)(c->snd_una - (seq + len)) >= 0)
+			return 0;
+
 		flags = net_irq_enter();
 		r = tcp_send_segment(c, TCP_PSH | TCP_ACK, seq, c->rcv_nxt,
 				     (const unsigned char *)buf, len, 0);
 		net_irq_exit(flags);
-		if (r != 0)
+		if (r != 0) {
+			c->state = TCP_STATE_CLOSED;
+			cl->err = -3;
 			return -3;
-		c->snd_nxt += len;
+		}
 
 		while ((int)(get_ticks_ms() - deadline) < 0) {
 			net_pump(8);
 			if (c->state == TCP_STATE_CLOSED)
 				return cl->err ? cl->err : -2;
-			if ((int)(c->snd_una - c->snd_nxt) >= 0)
+			if ((int)(c->snd_una - (seq + len)) >= 0)
 				return 0;
 			process_sleep_ms(1);
 		}
-		/* Retransmit the whole segment; a duplicate is harmless. */
+		/* Retransmit the whole segment at the same sequence. */
 	}
+	c->state = TCP_STATE_CLOSED;
+	cl->err = -1;
 	return -1;
 }
 

+ 29 - 25
ucmd_curl.c

@@ -101,29 +101,27 @@ static void app_dec(char *d, unsigned int *n, unsigned int v, unsigned int cap)
 		app_ch(d, n, tmp[i - 1 - j], cap);
 }
 
-static void fetch_paths_init(int slot)
+static void fetch_path(char *out, unsigned int cap, const char *kind,
+		       unsigned int session, int slot)
 {
 	unsigned int n = 0;
 
-	app_str(fp.req, &n, "/share/bfreq", sizeof(fp.req));
-	if (slot >= 0)
-		app_dec(fp.req, &n, (unsigned int)slot, sizeof(fp.req));
-	n = 0;
-	app_str(fp.body, &n, "/share/bfbody", sizeof(fp.body));
-	if (slot >= 0)
-		app_dec(fp.body, &n, (unsigned int)slot, sizeof(fp.body));
-	n = 0;
-	app_str(fp.meta, &n, "/share/bfmeta", sizeof(fp.meta));
-	if (slot >= 0)
-		app_dec(fp.meta, &n, (unsigned int)slot, sizeof(fp.meta));
-	n = 0;
-	app_str(fp.done, &n, "/share/bfdone", sizeof(fp.done));
-	if (slot >= 0)
-		app_dec(fp.done, &n, (unsigned int)slot, sizeof(fp.done));
-	n = 0;
-	app_str(fp.post, &n, "/share/bfpost", sizeof(fp.post));
-	if (slot >= 0)
-		app_dec(fp.post, &n, (unsigned int)slot, sizeof(fp.post));
+	app_str(out, &n, "/share/bf", cap);
+	if (slot >= 0) {
+		app_dec(out, &n, session, cap);
+		app_ch(out, &n, '_', cap);
+		app_dec(out, &n, (unsigned int)slot, cap);
+	}
+	app_str(out, &n, kind, cap);
+}
+
+static void fetch_paths_init(unsigned int session, int slot)
+{
+	fetch_path(fp.req, sizeof(fp.req), "req", session, slot);
+	fetch_path(fp.body, sizeof(fp.body), "body", session, slot);
+	fetch_path(fp.meta, sizeof(fp.meta), "meta", session, slot);
+	fetch_path(fp.done, sizeof(fp.done), "done", session, slot);
+	fetch_path(fp.post, sizeof(fp.post), "post", session, slot);
 }
 
 static void fetch_fail(unsigned int status, int err, const char *ctype,
@@ -214,7 +212,7 @@ static void fetch_once(void)
 	static struct uhttp h;
 	char req[768];
 
-	fetch_paths_init(-1);
+	fetch_paths_init(0, -1);
 	unsigned char *buf;
 	unsigned int cap = 0;
 	unsigned int body_len = 0, body_trunc = 0;
@@ -269,7 +267,7 @@ static void fetch_serve(const char *arg)
 	static struct uhttp h;
 	char req[768];
 	unsigned char *buf, *post;
-	unsigned int last_seq = 0, idle = 0;
+	unsigned int last_seq = 0, idle = 0, session = 0;
 	int slot = -1;
 
 	while (arg && *arg == ' ')
@@ -279,11 +277,17 @@ static void fetch_serve(const char *arg)
 	while (arg && *arg == ' ')
 		arg++;
 	if (arg && *arg >= '0' && *arg <= '9') {
-		slot = 0;
 		while (*arg >= '0' && *arg <= '9')
-			slot = slot * 10 + (*arg++ - '0');
+			session = session * 10 + (*arg++ - '0');
+		while (*arg == ' ')
+			arg++;
+		if (*arg >= '0' && *arg <= '9') {
+			slot = 0;
+			while (*arg >= '0' && *arg <= '9')
+				slot = slot * 10 + (*arg++ - '0');
+		}
 	}
-	fetch_paths_init(slot);
+	fetch_paths_init(session, slot);
 
 	buf = (unsigned char *)malloc(FETCH_MAX);
 	post = (unsigned char *)malloc(FETCH_POST_MAX);

+ 5 - 0
ucmd_lib.h

@@ -370,6 +370,11 @@ static inline int u_spawn_kcmd(const char *name, const char *arg, int tty)
 	return u_syscall3(SYS_SPAWN_KCMD, (int)name, (int)arg, tty);
 }
 
+static inline int u_getpid(void)
+{
+	return u_syscall0(SYS_GETPID);
+}
+
 static inline int u_alive(unsigned int pid)
 {
 	return u_syscall1(SYS_ALIVE, (int)pid);