Skip to content

Commit d017157

Browse files
Fix TCP race condition, remove fixed delay in CC (#5167)
ClientContext::_wait_for_sent() could dereference a TCP's _pcb after the connection was dropped by the OS, resulting in a crash. Move the connection dropped check to catch this case, and replace a fixed millisecond delay() with a yield and timeout value to minimize wasted time when transmission completes.
1 parent 83a8076 commit d017157

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

libraries/ESP8266WiFi/src/include/ClientContext.h

+17-16
Original file line numberDiff line numberDiff line change
@@ -308,39 +308,40 @@ class ClientContext
308308
if (!_pcb)
309309
return true;
310310

311-
int loop = -1;
312311
int prevsndbuf = -1;
313-
max_wait_ms++;
314312

315313
// wait for peer's acks to flush lwIP's output buffer
316-
314+
uint32_t last_sent = millis();
317315
while (1) {
316+
if (millis() - last_sent > (uint32_t) max_wait_ms) {
317+
#ifdef DEBUGV
318+
// wait until sent: timeout
319+
DEBUGV(":wustmo\n");
320+
#endif
321+
// All data was not flushed, timeout hit
322+
return false;
323+
}
318324

319325
// force lwIP to send what can be sent
320326
tcp_output(_pcb);
321327

322328
int sndbuf = tcp_sndbuf(_pcb);
323329
if (sndbuf != prevsndbuf) {
324330
// send buffer has changed (or first iteration)
325-
// we received an ack: restart the loop counter
326331
prevsndbuf = sndbuf;
327-
loop = max_wait_ms;
332+
// We just sent a bit, move timeout forward
333+
last_sent = millis();
328334
}
329335

330-
if (state() != ESTABLISHED || sndbuf == TCP_SND_BUF || --loop <= 0)
331-
break;
332-
333-
delay(1);
334-
}
336+
yield();
335337

336-
#ifdef DEBUGV
337-
if (loop <= 0) {
338-
// wait until sent: timeout
339-
DEBUGV(":wustmo\n");
338+
if ((state() != ESTABLISHED) || (sndbuf == TCP_SND_BUF)) {
339+
break;
340+
}
340341
}
341-
#endif
342342

343-
return max_wait_ms > 0;
343+
// All data flushed
344+
return true;
344345
}
345346

346347
uint8_t state() const

0 commit comments

Comments
 (0)