eidheim / Simple-Web-Server

A very simple, fast, multithreaded, platform independent HTTP and HTTPS server and client library implemented using C++11 and Boost.Asio. Created to be an easy way to make REST resources available from C++ applications.
MIT License
2.61k stars 751 forks source link

Read chunked bug and fix way #200

Closed whyuu closed 6 years ago

whyuu commented 6 years ago

I find a bug when reading chunked data. I get a wrong result when data has only one byte.

I changed it by modify functions

void read_chunked(const std::shared_ptr<Session> &session, const std::shared_ptr<asio::streambuf> &chunked_streambuf, const std::shared_ptr<asio::streambuf> &tmp_streambuf) {

if (tmp_streambuf->size() >= config.max_response_streambuf_size) { session->callback(session->connection, make_error_code::make_error_code(errc::message_size)); return; } // Move excess read data from session->response->streambuf to chunked_streambuf if (session->response->streambuf.size() > 0) { std::ostream chunked_stream(chunked_streambuf.get()); chunked_stream << &session->response->streambuf; ....

if(length > 0) { std::ostream tmp_stream(tmp_streambuf.get()); std::unique_ptr<char[]> buffer(new char[length]); chunked_stream.read(buffer.get(), static_cast(length)); tmp_stream.write(buffer.get(), static_cast(length)); }

        // Remove "\r\n"
        chunked_stream.get();
        chunked_stream.get();

        if(length > 0)
          this->read_chunked(session, chunked_streambuf, tmp_streambuf);
        else {

... }

void read(const std::shared_ptr &session) { .... else if((header_it = session->response->header.find("Transfer-Encoding")) != session->response->header.end() && header_it->second == "chunked") { auto tmp_streambuf = std::make_shared(); // chunked_streambuf is needed as new read buffer with its size adjusted depending on the size of tmp_streambuf auto chunked_streambuf = std::make_shared(config.max_response_streambuf_size - tmp_streambuf->size()); this->read_chunked(session, chunked_streambuf, tmp_streambuf); } ... }

eidheim commented 6 years ago

Thank you @whyuu , but it seems that you have been using an older version. Please try the latest master, issues with the chunked transfer encoding was fixed a little while back.