Skip to content

Commit 1aa4b16

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 1aa4b16

File tree

2 files changed

+26
-8
lines changed

2 files changed

+26
-8
lines changed

src/AsyncTCP.cpp

+24-8
Original file line numberDiff line numberDiff line change
@@ -1616,21 +1616,37 @@ 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);
1619+
if (!pcb) {
1620+
log_e("_accept failed: pcb is NULL");
1621+
return ERR_ABRT;
1622+
}
16201623
if (_connect_cb) {
16211624
AsyncClient *c = new (std::nothrow) AsyncClient(pcb);
1622-
if (c) {
1625+
if (c && c->pcb()) {
16231626
c->setNoDelay(_noDelay);
1624-
const int8_t err = _tcp_accept(this, c);
1625-
if (err != ERR_OK) {
1626-
tcp_abort(pcb);
1627-
delete c;
1627+
if (_tcp_accept(this, c) == ERR_OK) {
1628+
return ERR_OK; // success
16281629
}
1629-
return err;
1630+
// Couldn't allocate accept event
1631+
// 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
1632+
c->_pcb = nullptr;
1633+
tcp_abort(pcb);
1634+
log_e("_accept failed: couldn't accept client");
1635+
return ERR_ABRT;
16301636
}
1637+
if (c) {
1638+
// Couldn't complete setup
1639+
// pcb has already been aborted
1640+
delete c;
1641+
pcb = nullptr;
1642+
log_e("_accept failed: couldn't complete setup");
1643+
return ERR_ABRT;
1644+
}
1645+
log_e("_accept failed: couldn't allocate client");
1646+
} else {
1647+
log_e("_accept failed: no onConnect callback");
16311648
}
16321649
tcp_abort(pcb);
1633-
log_d("_accept failed");
16341650
return ERR_OK;
16351651
}
16361652

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)