Skip to content

Commit fa2016a

Browse files
committed
fix(mem): Fix memory leak in _accept() functions when _accept is called with a null pcb
Fix inspired by PR #21 from @willmmiles
1 parent 90065c8 commit fa2016a

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
@@ -1616,21 +1616,42 @@ void AsyncServer::end() {
16161616

16171617
// runs on LwIP thread
16181618
int8_t AsyncServer::_accept(tcp_pcb *pcb, int8_t err) {
1619-
// ets_printf("+A: 0x%08x\n", pcb);
1620-
if (_connect_cb) {
1621-
AsyncClient *c = new (std::nothrow) AsyncClient(pcb);
1622-
if (c) {
1623-
c->setNoDelay(_noDelay);
1624-
const int8_t err = _tcp_accept(this, c);
1625-
if (err != ERR_OK) {
1619+
if (pcb) {
1620+
if (_connect_cb) {
1621+
AsyncClient *c = new (std::nothrow) AsyncClient(pcb);
1622+
if (c && c->pcb()) {
1623+
c->setNoDelay(_noDelay);
1624+
if (_tcp_accept(this, c) == ERR_OK) {
1625+
return ERR_OK; // success
1626+
}
1627+
}
1628+
if (c->pcb()) {
1629+
// Couldn't allocate accept event
1630+
// 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
1631+
c->_pcb = nullptr;
16261632
tcp_abort(pcb);
1633+
log_e("_accept failed: couldn't allocate client");
1634+
return ERR_ABRT;
1635+
}
1636+
if (c) {
1637+
// Couldn't complete setup
1638+
// pcb has already been aborted
16271639
delete c;
1640+
pcb = nullptr;
1641+
log_e("_accept failed: couldn't complete setup");
1642+
return ERR_ABRT;
16281643
}
1629-
return err;
16301644
}
1645+
if (pcb) {
1646+
if (tcp_close(pcb) != ERR_OK) {
1647+
tcp_abort(pcb);
1648+
}
1649+
}
1650+
} else {
1651+
log_e("_accept failed: pcb is NULL");
1652+
return ERR_ABRT;
16311653
}
1632-
tcp_abort(pcb);
1633-
log_d("_accept failed");
1654+
log_e("_accept failed");
16341655
return ERR_OK;
16351656
}
16361657

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)