nodepp icon indicating copy to clipboard operation
nodepp copied to clipboard

HTTP/HTTPS client has no response-body framing (chunked / Content-Length / close-terminated)

Open binaryduke opened this issue 4 months ago • 6 comments

The HTTP and HTTPS clients have no way to read a response body correctly, because there is no RFC-7230 message-framing logic anywhere in the library. Grepping the tree for Transfer-Encoding, chunked, Content-Length or any body-reading helper returns nothing (checked in V1.4.0 and current main / V1.5.0).

Symptom

Issuing a GET against any real-world server and trying to read the body via stream::await / resolve / pipe gives a truncated body, a hang, or the raw chunked framing bytes mixed into the payload — depending on how the server chose to frame the response. There is no correct way to consume the body today.

Why it can't be worked around cleanly at the call site

The caller cannot know which of the three framings the server used without parsing the headers and then applying the matching read strategy — which is precisely the logic that belongs in the client.

What's needed

A read_body() on the http/https client implementing the standard three cases:

  1. Transfer-Encoding: chunked → read and de-chunk until the terminating zero-length chunk
  2. Content-Length: N → read exactly N bytes
  3. neither → read until the server closes the connection (close-terminated)

We have implemented exactly this as an additive http::read_body() / https::read_body() (~186 lines, no change to stream::await / resolve / pipe, so nothing existing breaks). Happy to open a PR if you want it.

Related, and arguably a regression

V1.5.0 appears to have removed the request-side Content-Length write that V1.4.0 had. If so, an outgoing POST body is now itself unframeable — the same class of bug in the other direction. Worth a look.

binaryduke avatar Jul 11 '26 16:07 binaryduke

Following up on this one, since #32 moved so quickly — we have this implemented and tested, and we're happy to open a PR.

What we have:

  • http::read_body() / https::read_body() — additive, ~186 lines
  • Implements the three RFC-7230 cases: Transfer-Encoding: chunked (de-chunk to the terminating zero-length chunk), Content-Length: N (read exactly N), and neither (read until the server closes)
  • stream::await / resolve / pipe are untouched, so nothing existing changes behaviour
  • Proven in production against a real-world scraping endpoint (chunked responses, ~20 documents parsed per call)

Two notes that may affect how you'd want it shaped:

  1. We wrote it against V1.4.0. If you'd prefer it against current main (V1.5.0_1), say the word and we'll rebase before opening the PR.

  2. V1.5.0 appears to have removed the request-side Content-Length write that V1.4.0 had. If that's right, an outgoing POST body is now unframeable too — the same class of bug in the other direction. Worth a look, and we'd be glad to include a fix for that in the same PR if you agree it's a regression.

Just let us know which branch you'd like it against.

binaryduke avatar Jul 12 '26 06:07 binaryduke

Correction: our "V1.5.0 removed the request-side Content-Length write" claim was wrong.

We compared against our own patched working tree instead of a clean checkout, and misread our own patch's absence as a regression on your side. There was no regression. Sorry for the noise.

Restated correctly — Content-Length appears nowhere in include/ in either version:

git grep -in content-length 1.4.0 -- include/   # no output
git grep -in content-length 1.5.0 -- include/   # no output

So it's a long-standing gap present in both, not something 1.5.0 broke. Please don't spend any time hunting it.

Our patch closes it in both directions:

  • request side — write Content-Length when a body is present, so an outgoing POST body is framed;
  • response side — an RFC 7230 §3.3.3 body-length reader: Transfer-Encoding: chunked decoded properly (chunk-extensions and trailers, terminating on the explicit 0\r\n chunk); Content-Length: N read as an exact bounded count; and neither-present falling back to read-until-close with an idle deadline, so a peer that goes quiet without ever closing can't hang the caller.

All three drain the client's borrow buffer first, since read_header() / read_line() may already have pulled body bytes off the socket in the same underlying read as the headers — skipping that silently dropped body bytes in an earlier version of ours.

It is purely additive: stream::await() / resolve() / pipe() are untouched, so no existing caller changes behaviour. The new entry points are http::read_body() / https::read_body().

We've rebased it onto tag 1.5.0 — clean 3-way merge; the only conflict was your new HTTP_NODEPP namespace, which ours now simply extends (no symbol collisions).

Which branch would you like the PR against — main, or the new dev?

One heads-up before you take it: we can't currently run the WebSocket half of our suite on 1.5.0 at all — see #36. If you'd rather we target 1.4.0 until that's resolved, say the word and we'll rebase again.

binaryduke avatar Jul 13 '26 06:07 binaryduke

reply

Let's do this: I took the time to refactor the HTTP code and onganize it to you. It was something I had to do regardless. Help me test this version, and if you find any bugs, open a PR with your modifications based on the production code you're running.

What I added

  • https://github.com/NodeppOfficial/nodepp/blob/dev/include/nodepp/http.h
  • https://github.com/NodeppOfficial/nodepp/blob/dev/include/nodepp/https.h
  • https://github.com/NodeppOfficial/nodepp/blob/dev/include/nodepp/generator.h#L407

1. write_header and POST now write Content-Length

The first thing I did was refactor all the write_header overloads. Now fetch also writes Content-Length based on the body size. I left it unconditional — not tied to POST — in case the W3C ever invents a new method called SEND. You never know.

template< class T > void write_header( const T& fetch, const string_t& path ) const noexcept {
        
    queue_t<string_t> out; 
    set_send_mode( nullptr );

    out.push( string::format( "%s %s %s", fetch.method.get(), path.get(), fetch.version.get() ) );
    
    if( !fetch.body.empty() ){ 
         fetch.headers["Content-Length"] = string::to_string( fetch.body.size() );
    }

    auto x = fetch.headers.raw().first(); 
    while( x != nullptr ){ 
        auto y = x->next; 
        auto &z = x->data;
        out.push( string::format( "%s: %s", z.first.to_capital_case().get(), z.second.get() ) );
        x = y;
    } 
    
    out.push( "\r\n" ); 
    write( array_t<string_t>( out.data() ).join("\r\n") );
            
    if( fetch.method == "HEAD" ){ 
        close(); 
        return; 
    } 
    
    set_send_mode( fetch.headers );
}

Difference from the original version: the old version used concatenation (string1 + string2). That meant calling malloc, allocating a larger block, and copying character by character. This new version uses doubly-linked queues (queue_t) to store everything in nodes, and at the end, array_t::join() creates a single large block with space for the entire string. In theory, it should be faster.


2. HTTP transfer modes

I also added a section to define transfer modes based on request and response headers.

struct DONE { 
    ulong size; 
    int state; 
};

struct NODE {
    generator::file::line  line; 
    DONE mode[2];
    generator::http::read  read;
    generator::http::write write;
};  

ptr_t<NODE> http;  

enum FLAG {
    HTTP_FLAG_UNKNOWN = 0b00000000,
    HTTP_FLAG_CHUNKED = 0b00000001,
    HTTP_FLAG_STREAM  = 0b00000010,
};

void set_http_mode( DONE& mode, header_t header ) const noexcept { 
    mode.state = FLAG::HTTP_FLAG_UNKNOWN; 
    mode.size  = 0UL;
    
    if( !header.has( "Content-Length" ) ) {
        if( !header.has( "Transfer-Encoding" ) ) { 
            return; 
        } else { 
            auto itm = header["Transfer-Encoding"];
            if( itm.to_lower_case().find( "chunked" ).null() ) { 
                mode.state |= FLAG::HTTP_FLAG_UNKNOWN;
            } else { 
                mode.state |= FLAG::HTTP_FLAG_CHUNKED; 
            }
        }
    } else { 
        mode.size  = string::to_ulong( header["Content-Length"] );
        mode.state |= FLAG::HTTP_FLAG_STREAM;
    }
}

void set_recv_mode( header_t header ) const noexcept { 
    set_http_mode( http->mode[0], header ); 
}

void set_send_mode( header_t header ) const noexcept { 
    set_http_mode( http->mode[1], header ); 
}

3. Reusable generators generator::http::read and generator::http::write

Just like generator::ws::read/write, generator::file::read/write, and generator::stream::pipe, I added a generators section for HTTP to keep read/write logic separate and reusable:

GENERATOR( read ) {
private:
    enum FLAG {
        HTTP_FLAG_UNKNOWN = 0b00000000,
        HTTP_FLAG_CHUNKED = 0b00000001,
        HTTP_FLAG_STREAM  = 0b00000010,
    };

    string_t bff; 
    ulong size;

public: 
    ulong data = 0;

public: 
    template< class T, class V >
    coEmit( T* fd, char* bf, ulong sx, V& mode ) {
        switch( mode.state ) {
            case FLAG::HTTP_FLAG_STREAM: 
                return stream_http_stream( fd, bf, sx, mode ); 
                break;
            case FLAG::HTTP_FLAG_CHUNKED:
                return chunk_http_chunked( fd, bf, sx, mode ); 
                break;
            default: 
                return default_http_stream( fd, bf, sx, mode ); 
                break;
        }
    }
};

GENERATOR( write ) {
private:
    enum FLAG {
        HTTP_FLAG_UNKNOWN = 0b00000000,
        HTTP_FLAG_CHUNKED = 0b00000001,
        HTTP_FLAG_STREAM  = 0b00000010,
    };

    string_t bff; 
    ulong size;

public: 
    ulong data = 0;

public: 
    template< class T, class V >
    coEmit( T* fd, char* bf, ulong sx, V& mode ) {
        switch( mode.state ) {
            case FLAG::HTTP_FLAG_STREAM: 
                return stream_http_stream( fd, bf, sx, mode ); 
                break;
            case FLAG::HTTP_FLAG_CHUNKED:
                return chunk_http_chunked( fd, bf, sx, mode ); 
                break;
            default: 
                return default_http_stream( fd, bf, sx, mode ); 
                break;
        }
    }
};

What's missing?

  • Transfer-Encoding: chunked → read and de-chunk until the terminating zero-length chunk
  • Content-Length: N → read exactly N bytes
  • Neither → read until the server closes the connection (close-terminated)

If you see anything that doesn't fit or any edge case I missed, open a PR with your changes. The foundation is there — it just needs polishing.

I'm open to collaboration, suggestions, and constructive criticism.

Test:

I've added 2 test examples:

  • https://github.com/NodeppOfficial/nodepp/blob/dev/examples/15-HTTP.cpp#L16
  • https://github.com/NodeppOfficial/nodepp/blob/dev/examples/14-Real-Time-HTML-Render.cpp

EDBCREPO avatar Jul 15 '26 05:07 EDBCREPO

Reproduced the chunked-body framing on MSVC 2022 x64 /std:c++20 against a byte-exact HTTP/1.1 test server. curl confirms the server output is correct in every case; dev's client-side de-chunk does not decode it:

case server bytes dev result
single chunk, one packet 9\r\nWikipedia\r\n0\r\n\r\n raw, undecoded
two chunks, one packet 4\r\nWiki\r\n5\r\npedia\r\n0... raw, undecoded
size line split across two TCP reads "4\r" then "\nWiki..." null (all lost)
close-terminated (no chunking) body then FIN ok

So normal chunked responses come back with the chunk framing still in the body, and a response whose size line straddles a read boundary is lost entirely. The split-boundary loss is downstream of the find() issue reported separately (#38).

Attaching the harness as a regression test: a stdlib-only HTTP/1.1 server (serves /one /multi /chunked /close) plus a small client. Happy to open these as a PR under test/ if useful.

A correct, fragmentation-immune de-chunker that operates on a COMPLETE buffer (so it is immune to both TCP fragmentation and the find() behaviour above):

inline string_t _dechunk_buffer( string_t buf ) noexcept {
    string_t body;
    while( true ) {
        auto nl = buf.find("\r\n");
        if( nl.null() || nl[1] - nl[0] != 2 ){ break; }   // no COMPLETE size line
        ulong size = 0; bool any = false;
        for( int i = 0; i < nl[0]; ++i ) { char c = buf[i];
            if     ( c>='0' && c<='9' ){ size = size*16 + (ulong)(c-'0');    any=true; }
            elif   ( c>='a' && c<='f' ){ size = size*16 + (ulong)(c-'a'+10); any=true; }
            elif   ( c>='A' && c<='F' ){ size = size*16 + (ulong)(c-'A'+10); any=true; }
            else   { break; }                             // chunk-extension ';' etc.
        }
        buf = buf.slice( nl[1], buf.size() );
        if( !any || size == 0 ){ break; }                 // malformed or terminating
        if( buf.size() < size ){ body += buf; break; }    // truncated, salvage
        body += buf.slice( 0, size );
        buf   = buf.slice( size + 2 <= buf.size() ? size + 2 : buf.size(), buf.size() );
    }
    return body;
}

Unit-tested for: single chunk, multi chunk, chunk-extension, large hex size, trailer headers, empty body — all pass.

One caveat on the read side. Feeding this a complete body reliably wants an async slurp — stream::resolve(cli).then(...) over onData + onDrain + stream::pipe. The synchronous _read() busy-loop does not re-poll the socket mid-stream on this build, so it hangs or returns early when a body arrives in multiple segments. That points at a promise-returning read_body(), which is a small API-shape question worth your call:

inline promise_t<string_t,except_t> read_body( http_t& cli ) {
    return stream::resolve( cli ).then([&cli]( string_t raw ){
        return frame_body( cli, raw ); // chunked / Content-Length / close
    });
}

binaryduke avatar Jul 15 '26 11:07 binaryduke

a stdlib-only HTTP/1.1 server
(serves /one /multi /chunked /close) plus a small client. Happy to open these as
a PR under test/ if useful.

yep, a smal test would be really helpfull;

about client chunk-encoding; I've reimplemented chunk_http_chunked, now it must pass your test, also I've solved your issue (#38)

template< class T, class V >
        int chunk_http_chunked( T* fd, char* bf, ulong sx, V& mode ){
            
            string_t &bff = fd->get_borrow();

            do { if( mode.size==0 ){ 

                if( bff.starts_with("\r\n") ){ fd->get_borrow().splice( 0, 2 ); }

                auto x = bff.find("\r\n"); if( x.null() ){ break; }
                auto y = bff.slice_view( 0, x[0] ).find(";");

                if( y.null() ){
                    mode.size = encoder::hex::btoa<ulong>( bff.slice_view( 0, x[0] ) );
                } else {
                    mode.size = encoder::hex::btoa<ulong>( bff.slice_view( 0, y[0] ) );
                }
                
                if( mode.size==0 ){ data=0; return -1; } 
                fd->get_borrow().splice( 0, x[1] );

            } else { if( bff.empty() ){ break; }

                auto sy  = min( mode.size, sx );
                auto tmp = bff.slice_view( 0, sy );
                auto c   = tmp.size();

                memmove( bf, tmp.get(), c ); 

                fd->get_borrow().splice( 0, c );
                mode.size -= min( c,mode.size );
                
                data = c; return -1;

            }} while( 0 );
            
            int /*----*/ c = fd->__read ( bf, sx );

            if  ( c > 0 ){ bff += string_t( bf, c  ); }
            elif( c==-2 ){ data = 0; /*-*/ return  1; }
            else         { data = 0; /*-*/ return -1; }

            data = 0; return 1;

        }

here you have the example I used to test the logic:

#include <nodepp/nodepp.h>

using namespace nodepp;

int test_chunk_encoding( string_t& bff, string_t& msg, ulong& size ){

    do { if( size==0 ){ 

        if( bff.starts_with("\r\n") ){ bff.splice( 0, 2 ); }
        if( !msg.empty() ){ console::done( ">>", msg ); msg.clear(); }

        auto x = bff.find("\r\n"); if( x.null() ){ break; }
        auto y = bff.slice_view( 0, x[0] ).find(";");

        if( y.null() ){
            size = encoder::hex::btoa<ulong>( bff.slice_view( 0, x[0] ) );
        } else {
            size = encoder::hex::btoa<ulong>( bff.slice_view( 0, y[0] ) );
        }
        
        bff.splice( 0, x[1] );

    } else { if( bff.empty() ){ break; }

        auto tmp = bff.slice_view( 0, size );
        auto c   = tmp.size(); msg += tmp;

        bff.splice ( 0, c   );
        size -= min( c,size );

        return 1;

    }} while( true ); 

    return -1;

}

void onMain() {

    string_t borrow ;
    string_t message; ulong size = 0;

    queue_t<string_t> que ({

        "9\r\nWikipedia\r\n",
        "9\r\nWikipedia\r\n9\r\nWikipedia\r\n",
        "9\r\nWikipedia\r\n9\r\nWikipedia\r\n9\r\nWikipedia\r\n",
        "9\r", "\nWikipedia\r\n9\r\nWiki","pedia\r\n9\r\nWikipedia\r\n",
        "9;foo=bar\r", "\nWikipedia\r\n9\r\nWiki","pedia\r\n9\r\nWikipedia\r\n",
        "0\r\n\r\n"

    });

    for( auto x: que.data() ){
        
        borrow += x;
        while( test_chunk_encoding( borrow, message, size )==1 ){ /*unused*/ }

    }

}

OUTPUT

DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 
DONE: >> Wikipedia 

EDBCREPO avatar Jul 16 '26 13:07 EDBCREPO

Feeding this a complete body reliably wants an async slurp

like the idea:

promise_t<http_t,except_t> read_body() const noexcept {

        auto self = type::bind( this );

    return promise_t<http_t,except_t> ([=](
        res_t<http_t> res, rej_t<except_t> rej
    ){

        process::poll( *self, POLL_STATE::READ | POLL_STATE::EDGE, coroutine::add( COROUTINE(){
        coBegin

            if( self->http->mode[0].state & FLAG::HTTP_FLAG_STREAM ){

                while ( self->http->mode[0].size != 0 ){
                coWait( self->http->read( self.get(), 
                        self->get_buffer().data   (), 
                        self->get_buffer().size   (), self->http->mode[0]
                )==1 );
                    self->body += string_t( self->get_buffer().data(), self->http->read.data );
                }

            } else { 
                
                while ( self->is_available() ){
                coWait( self->http->read( self.get(), 
                        self->get_buffer().data   (), 
                        self->get_buffer().size   (), self->http->mode[0]
                )==1 );
                    self->body += string_t( self->get_buffer().data(), self->http->read.data );
                }

            }   res( *self ); 

        coFinish
        }), 0UL );

    }); }

Example:

#include <nodepp/nodepp.h>
#include <nodepp/worker.h>
#include <nodepp/http.h>

using namespace nodepp;

void server() {

    auto server = http::server([=]( http_t cli ){ 

        if( cli.method != "POST" || !cli.headers.has( "Content-Length" ) ){ 
            cli.write_header( 404, header_t({}) );
            cli.write( "not allowed" ); return;
        }

        cli.read_body()

        .then([=]( http_t cli ){
            console::log( "->", cli.body );
            cli.write_header( 200, header_t({}) );
            cli.write( "received" );
        })
        
        .fail([=]( except_t err ){
            console::error( err );
        });

    });

    server.listen( "localhost", 8000, [=]( socket_t server ){
        console::log("server started at http://localhost:8000");
    });

}

void client() {

    fetch_t args;
            args.body    = "hello world!";
            args.method  = "POST";
            args.url     = "http://localhost:8000/";
            args.headers = header_t({
                { "Host", url::host(args.url) }
            });

    http::fetch( args )

    .then([]( http_t cli ){

        cli.read_body()

        .then([=]( http_t cli ){
            console::log( ">>", cli.body );
        })

        .fail([=]( except_t err ){
            console::log( "<>", err.what() );
        });

    })

    .fail([]( except_t err ){
        console::error( err );
    });

}

void onMain() {

    worker::add([=](){ server(); process::wait(); return -1; });
    worker::add([=](){ client(); process::wait(); return -1; });

}

OUTPUT:

server started at http://localhost:8000 
-> hello world! 
>> received 

what do you think? available on V1.4.1

EDBCREPO avatar Jul 17 '26 05:07 EDBCREPO