Skip to content

Commit 598a0c7

Browse files
committed
fix(mem): Fix memory leak in _accept() functions where aborted requests were not correctly cleaned up
Fix inspired by PR #21 from @willmmiles
1 parent 12a7c4f commit 598a0c7

File tree

2 files changed

+33
-10
lines changed

2 files changed

+33
-10
lines changed

src/AsyncTCP.cpp

+31-10
Original file line numberDiff line numberDiff line change
@@ -1624,21 +1624,42 @@ void AsyncServer::end() {
16241624

16251625
// runs on LwIP thread
16261626
int8_t AsyncServer::_accept(tcp_pcb *pcb, int8_t err) {
1627-
// ets_printf("+A: 0x%08x\n", pcb);
1628-
if (_connect_cb) {
1629-
AsyncClient *c = new (std::nothrow) AsyncClient(pcb);
1630-
if (c) {
1631-
c->setNoDelay(_noDelay);
1632-
const int8_t err = _tcp_accept(this, c);
1633-
if (err != ERR_OK) {
1627+
if (pcb) {
1628+
if (_connect_cb) {
1629+
AsyncClient *c = new (std::nothrow) AsyncClient(pcb);
1630+
if (c && c->pcb()) {
1631+
c->setNoDelay(_noDelay);
1632+
if (_tcp_accept(this, c) == ERR_OK) {
1633+
return ERR_OK; // success
1634+
}
1635+
}
1636+
if (c->pcb()) {
1637+
// Couldn't allocate accept event
1638+
// We can't let the client object call in to close, as we're on the LWIP thread; it could deadlock trying to RPC to itself
1639+
c->_pcb = nullptr;
16341640
tcp_abort(pcb);
1641+
log_e("_accept failed: couldn't allocate client");
1642+
return ERR_ABRT;
1643+
}
1644+
if (c) {
1645+
// Couldn't complete setup
1646+
// pcb has already been aborted
16351647
delete c;
1648+
pcb = nullptr;
1649+
log_e("_accept failed: couldn't complete setup");
1650+
return ERR_ABRT;
16361651
}
1637-
return err;
16381652
}
1653+
if (pcb) {
1654+
if (tcp_close(pcb) != ERR_OK) {
1655+
tcp_abort(pcb);
1656+
}
1657+
}
1658+
} else {
1659+
log_e("_accept failed: pcb is NULL");
1660+
return ERR_ABRT;
16391661
}
1640-
tcp_abort(pcb);
1641-
log_d("_accept failed");
1662+
log_e("_accept failed");
16421663
return ERR_OK;
16431664
}
16441665

src/AsyncTCP.h

+2
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,8 @@ class AsyncClient {
246246
}
247247

248248
protected:
249+
friend class AsyncServer;
250+
249251
bool _connect(ip_addr_t addr, uint16_t port);
250252

251253
tcp_pcb *_pcb;

0 commit comments

Comments
 (0)