From c036ae838ca20f8cbc0899c3277c1199c7067ffc Mon Sep 17 00:00:00 2001 From: Wiebe Cazemier Date: Wed, 9 Dec 2020 16:58:06 +0100 Subject: [PATCH] Buffer fixes --- client.cpp | 31 +++++++++++++++++-------------- client.h | 10 ++++++++-- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/client.cpp b/client.cpp index dcd9247..f0d5873 100644 --- a/client.cpp +++ b/client.cpp @@ -19,16 +19,25 @@ Client::~Client() epoll_ctl(threadData->epollfd, EPOLL_CTL_DEL, fd, NULL); // NOTE: the last NULL can cause crash on old kernels close(fd); free(readbuf); + free(writebuf); } // false means any kind of error we want to get rid of the client for. bool Client::readFdIntoBuffer() { - int read_size = getReadBufMaxWriteSize(); - int n; - while ((n = read(fd, &readbuf[wi], read_size)) != 0) + while ((n = read(fd, &readbuf[wi], getReadBufMaxWriteSize())) != 0) { + if (n > 0) + { + wi += n; + + if (getReadBufBytesUsed() >= readBufsize) + { + growReadBuffer(); + } + } + if (n < 0) { if (errno == EINTR) @@ -38,15 +47,6 @@ bool Client::readFdIntoBuffer() else return false; } - - wi += n; - - if (getReadBufBytesUsed() >= readBufsize) - { - growReadBuffer(); - } - - read_size = getReadBufMaxWriteSize(); } if (n == 0) // client disconnected. @@ -84,6 +84,8 @@ bool Client::writeBufIntoFd() // TODO: ignore the signal BROKEN PIPE we now also int n; while ((n = write(fd, &writebuf[wri], getWriteBufBytesUsed())) != 0) { + if (n > 0) + wri += n; if (n < 0) { if (errno == EINTR) @@ -93,8 +95,6 @@ bool Client::writeBufIntoFd() // TODO: ignore the signal BROKEN PIPE we now also else return false; } - - wri += n; } if (wri == wwi) @@ -148,6 +148,9 @@ bool Client::bufferToMqttPackets(std::vector &packetQueueIn) packetQueueIn.push_back(std::move(packet)); ri += packet_length; + + if (ri > wi) + throw std::runtime_error("hier"); } else break; diff --git a/client.h b/client.h index 37995f5..51e221b 100644 --- a/client.h +++ b/client.h @@ -46,7 +46,7 @@ class Client size_t getReadBufMaxWriteSize() { - size_t available = readBufsize - getReadBufBytesUsed(); + size_t available = readBufsize - wi; return available; } @@ -54,12 +54,14 @@ class Client { const size_t newBufSize = readBufsize * 2; readbuf = (char*)realloc(readbuf, newBufSize); + if (readbuf == NULL) + throw std::runtime_error("Memory allocation failure in growReadBuffer()"); readBufsize = newBufSize; } size_t getWriteBufMaxWriteSize() { - size_t available = writeBufsize - getWriteBufBytesUsed(); + size_t available = writeBufsize - wwi; return available; } @@ -75,6 +77,10 @@ class Client const size_t newBufSize = writeBufsize + add_size; writebuf = (char*)realloc(writebuf, newBufSize); + + if (writebuf == NULL) + throw std::runtime_error("Memory allocation failure in growWriteBuffer()"); + writeBufsize = newBufSize; } -- libgit2 0.21.4