11#include " HTTPURLEncodedBodyParser.hpp"
22
3+ #define CHUNKSIZE 512
4+ #define MINCHUNKSIZE 64
5+
36namespace httpsserver {
47
58HTTPURLEncodedBodyParser::HTTPURLEncodedBodyParser (HTTPRequest * req):
@@ -13,16 +16,56 @@ HTTPURLEncodedBodyParser::HTTPURLEncodedBodyParser(HTTPRequest * req):
1316{
1417 bodyLength = _request->getContentLength ();
1518 if (bodyLength) {
16- bodyBuffer = new char [bodyLength+1 ];
17- _request->readChars (bodyBuffer, bodyLength);
19+ // We know the body length. We try to read that much and give an error if it fails.
20+ bodyBuffer = (char *)malloc (bodyLength+1 );
21+ if (bodyBuffer == NULL ) {
22+ HTTPS_LOGE (" HTTPURLEncodedBodyParser: out of memory" );
23+ return ;
24+ }
25+ bodyPtr = bodyBuffer;
26+ size_t toRead = bodyLength;
27+ while (toRead > 0 ) {
28+ size_t didRead = _request->readChars (bodyPtr, toRead);
29+ if (didRead == 0 ) {
30+ HTTPS_LOGE (" HTTPURLEncodedBodyParser: short read" );
31+ bodyLength = bodyPtr - bodyBuffer;
32+ break ;
33+ }
34+ bodyPtr += didRead;
35+ toRead -= didRead;
36+ }
37+ } else {
38+ // We don't know the length. Read as much as possible.
39+ bodyBuffer = (char *)malloc (CHUNKSIZE+1 );
40+ if (bodyBuffer == NULL ) {
41+ HTTPS_LOGE (" HTTPURLEncodedBodyParser: out of memory" );
42+ return ;
43+ }
1844 bodyPtr = bodyBuffer;
19- bodyBuffer[bodyLength] = ' \0 ' ;
45+ size_t bufferUsed = 0 ;
46+ size_t bufferAvailable = CHUNKSIZE;
47+ while (!_request->requestComplete ()) {
48+ if (bufferAvailable < MINCHUNKSIZE) {
49+ bodyBuffer = (char *)realloc (bodyBuffer, bufferUsed + CHUNKSIZE+1 );
50+ if (bodyBuffer == NULL ) {
51+ HTTPS_LOGE (" HTTPURLEncodedBodyParser: out of memory" );
52+ return ;
53+ }
54+ bufferAvailable = CHUNKSIZE;
55+ }
56+ size_t didRead = _request->readChars (bodyBuffer+bufferUsed, bufferAvailable);
57+ bufferUsed += didRead;
58+ bufferAvailable -= didRead;
59+ }
60+ bodyLength = bufferUsed;
2061 }
62+ bodyPtr = bodyBuffer;
63+ bodyBuffer[bodyLength] = ' \0 ' ;
2164}
2265
2366HTTPURLEncodedBodyParser::~HTTPURLEncodedBodyParser () {
2467 if (bodyBuffer) {
25- delete[] bodyBuffer;
68+ free ( bodyBuffer) ;
2669 }
2770 bodyBuffer = NULL ;
2871}
0 commit comments