Commit 533ba907 authored by jan.koester's avatar jan.koester
Browse files

test

parent 7bb541ae
Loading
Loading
Loading
Loading
+176 −92
Changes for src/http.cpp: 176 added lines, 92 removed lines.
Original line number Diff line number Diff line
@@ -243,8 +243,9 @@ const std::vector<char> libhttppp::HttpClient::Get(libhttppp::HttpRequest &nreq)

        nreq.send(*_cltsock);

    int recv,chunklen=0;
        int recv = 0, chunklen = 0;

        // --- read header ---
        try{
            for(;;){
                try{
@@ -267,22 +268,44 @@ const std::vector<char> libhttppp::HttpClient::Get(libhttppp::HttpRequest &nreq)

        libhttppp::HttpResponse res;

    hsize=res.parse(data.data.buf,recv);
        // parse() returns header length in bytes
        hsize = res.parse(data.data.buf, recv);  // header length in bytes

    ++hsize;
        if (hsize > static_cast<size_t>(recv)) {
          libhttppp::HTTPException he;
          he[libhttppp::HTTPException::Error]
          << "header size bigger than received bytes";
          throw he;
        }

    recv-=hsize;
        // bytes of body already in buffer
        recv -= static_cast<int>(hsize);

    std::move(data.data.buf+hsize,data.data.buf+BLOCKSIZE,data.data.buf);
        // shift body down to beginning of buffer
        if (recv > 0) {
          std::memmove(data.data.buf,                // dest
                       data.data.buf + hsize,        // src
                       static_cast<size_t>(recv));   // count
        }

        cpos = 0;

        std::cerr << "---- Transfer-Encoding headers ----\n";
for (auto *chdat = res.getTransferEncoding(); chdat; chdat = chdat->nextvalue()) {
    std::string raw = chdat->getvalue();
    std::cerr << "'" << raw << "'" << " (len=" << raw.size() << ")\n";
}
std::cerr << "-----------------------------------\n";


        // --- detect chunked vs fixed-length ---
        try{
      for(libhttppp::HttpHeader::HeaderData::Values *chdat=res.getTransferEncoding(); chdat; chdat=chdat->nextvalue()){
        std::string clstr;
        std::transform(chdat->getvalue().begin(), chdat->getvalue().end(), clstr.begin(),
            [](unsigned char c){ return static_cast<char>(std::tolower(c)); }
        );
            for (libhttppp::HttpHeader::HeaderData::Values *chdat = res.getTransferEncoding();
                 chdat; chdat = chdat->nextvalue())
            {
                std::string clstr = chdat->getvalue();   // copy header value
                std::transform(clstr.begin(), clstr.end(), clstr.begin(),
                    [](unsigned char c){ return static_cast<char>(std::tolower(c)); });
                if (clstr == "chunked")
                    chunked = true;
            }
@@ -292,23 +315,34 @@ const std::vector<char> libhttppp::HttpClient::Get(libhttppp::HttpRequest &nreq)
            rlen = res.getContentLength();
        }

        // --- non-chunked body ---
        if (!chunked){
            do{
                try{
          std::copy(data.data.buf+cpos,data.data.buf+recv,std::back_inserter(ret));
                    // copy everything we currently have
                    std::copy(data.data.buf + cpos,
                              data.data.buf + recv,
                              std::back_inserter(ret));
                    rlen -= recv;
                    if (rlen > 0){
                        for(;;){
                            cpos = 0;
                            try{
                                recv = _cltsock->recvData(data);
                                if (recv <= 0) {
                                    netplus::NetException ne;
                                    ne[netplus::NetException::Error]
                                        << "Premature EOF while reading HTTP body";
                                    throw ne;
                                }
                                break;
                            }catch(netplus::NetException &e){
                                if (e.getErrorType() == netplus::NetException::Note){
                                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                                    continue;
                                }
                e[netplus::NetException::Error] << "nginxfiler: can't reach nginx server !";
                                e[netplus::NetException::Error]
                                    << "nginxfiler: can't reach nginx server !";
                                throw e;
                            }
                        }
@@ -319,30 +353,47 @@ const std::vector<char> libhttppp::HttpClient::Get(libhttppp::HttpRequest &nreq)
                    throw ee;
                }
            }while (rlen > 0);
    }else{
        }

        // --- chunked body ---
        else{
            int readed = 0;

            for(;;){
                if (recv - cpos > 0){

                    if (readed == chunklen){
            if( (chunklen=readchunk(data.data.buf,recv,cpos)) == 0 ){
                        // need new chunk size
                        chunklen = readchunk(data.data.buf, recv, cpos);
                        if (chunklen == 0){
                            // final chunk: do NOT copy 0\r\n\r\n into ret
                            break;
                        }
                        readed = 0;
                    }

          int len = (chunklen - readed) < (recv - cpos) ? (chunklen - readed)  : (recv - cpos);
                    int can_read = recv - cpos;
                    int remaining = chunklen - readed;
                    int len = std::min(chunklen - readed, recv - cpos);  // number of bytes

                    std::copy(data.data.buf + cpos,
                              data.data.buf + cpos + len,
                              std::back_inserter(ret));

          std::copy(data.data.buf+cpos,data.data.buf+(cpos+len),std::back_inserter(ret));
                    cpos   += len;
                    readed += len;

                }else{
                    cpos = 0;
                    for(;;){
                        try{
                            recv = _cltsock->recvData(data);
                            if (recv <= 0){
                                netplus::NetException ne;
                                ne[netplus::NetException::Error]
                                    << "Premature EOF while reading chunked body";
                                throw ne;
                            }
                            break;
                        }catch(netplus::NetException &e){
                            if (e.getErrorType() != netplus::NetException::Note){
@@ -356,17 +407,20 @@ const std::vector<char> libhttppp::HttpClient::Get(libhttppp::HttpRequest &nreq)
                        }
                    }
                }
      };
            }
        }
    }catch(netplus::NetException &e){
        libhttppp::HTTPException ee;
        ee[libhttppp::HTTPException::Error] << e.what();
        throw ee;
    }

    return ret;
}

const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq,const std::vector<char>& post){
const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq,
                                                    const std::vector<char> &post)
{
    netplus::buffer data(BLOCKSIZE);
    std::vector<char> ret;

@@ -374,6 +428,7 @@ const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq
        size_t hsize = 0;
        int cpos = 0, rlen = 0;
        bool chunked = false;

        std::stringstream host;
        host << _url.getHost() << ":" << _url.getPort();

@@ -382,52 +437,56 @@ const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq
        if (nreq.getRequestURL().empty())
            nreq.setRequestURL("/");
        nreq.setRequestVersion(HTTPVERSION(1.1));
        nreq.setHeaderData("Content-Length")->push_back(post.size());
        nreq.send(*_cltsock);

        size_t sended=0;
        // IMPORTANT: length as string
        nreq.setHeaderData("Content-Length")->push_back(std::to_string(post.size()));
        // (optionally) set content-type:
        // nreq.setHeaderData("Content-Type")->push_back("application/json");

        nreq.send(*_cltsock);

        // Send POST body data
        try {
            size_t sended = 0;
            while (sended != post.size()) {
                netplus::buffer data(post.data()+sended,post.size()-sended);
                sended+=_cltsock->sendData(data,0);
                netplus::buffer outbuf(post.data() + sended,
                                       post.size() - sended);
                sended += _cltsock->sendData(outbuf, 0);
            }
        } catch (netplus::NetException &e) {
            throw HTTPException()[HTTPException::Error] << e.what();
        }

        int recv, chunklen = 0;
        int recv = 0;
        int chunklen = 0;

        // --- TIMEOUT WATCHDOG SETUP ---
        // --- Read HTTP response header (with timeout) ---
        using namespace std::chrono;
        auto start   = steady_clock::now();
        auto timeout = seconds(5); // 5 second maximum wait time for the initial response header
        // --- END WATCHDOG SETUP ---

        auto timeout = seconds(5);

        // Read HTTP response header
        try {
            for (;;) {
                // 🛑 CRITICAL CHECK: Enforce the overall timeout
                if (steady_clock::now() - start > timeout) {
                    throw netplus::NetException()
                        [netplus::NetException::Error] << "Timeout waiting for server response header (5s limit exceeded).";
                        [netplus::NetException::Error]
                        << "Timeout waiting for server response header (5s limit exceeded).";
                }

                try {
                    recv = _cltsock->recvData(data);

                    // Check for immediate EOF after sending request
                    // immediate EOF after request
                    if (recv <= 0) {
                        throw netplus::NetException()[netplus::NetException::Error] << "Server closed connection before sending response.";
                        throw netplus::NetException()
                            [netplus::NetException::Error]
                            << "Server closed connection before sending response.";
                    }
                    break;
                } catch (netplus::NetException &re) {
                    if (re.getErrorType() != netplus::NetException::Note) {
                        throw re;
                    } else {
                        // FIX: Wait politely (10ms) and try again
                        std::this_thread::sleep_for(std::chrono::milliseconds(10));
                        continue;
                    }
@@ -440,21 +499,37 @@ const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq
        }

        libhttppp::HttpResponse res;
        hsize=res.parse(data.data.buf,recv);
        hsize = res.parse(data.data.buf, recv);  // header length in bytes

        ++hsize;
        if (hsize > static_cast<size_t>(recv)) {
            libhttppp::HTTPException ee;
            ee[libhttppp::HTTPException::Error]
                << "nginxfiler: header size bigger than recv'd bytes";
            throw ee;
        }

        recv-=hsize;
        // number of body bytes already read in this recv
        recv -= static_cast<int>(hsize);

        // Shift remaining data to the front of the buffer
        std::move(data.data.buf+hsize,data.data.buf+BLOCKSIZE,data.data.buf);
        if (recv > 0) {
            std::memmove(data.data.buf,                 // dest
                         data.data.buf + hsize,         // src
                         static_cast<size_t>(recv));    // count
        }

        cpos = 0;

        // Determine if response is chunked or has Content-Length
        try {
            for(libhttppp::HttpHeader::HeaderData::Values *chdat=res.getTransferEncoding(); chdat; chdat=chdat->nextvalue()){
                if(chdat->getvalue()=="chunked")
            for (libhttppp::HttpHeader::HeaderData::Values *chdat = res.getTransferEncoding();
                 chdat; chdat = chdat->nextvalue())
            {
                std::string clstr = chdat->getvalue();
                std::transform(clstr.begin(), clstr.end(), clstr.begin(),
                               [](unsigned char c){
                                   return static_cast<char>(std::tolower(c));
                               });
                if (clstr == "chunked")
                    chunked = true;
            }
            if (!chunked)
@@ -463,11 +538,13 @@ const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq
            rlen = res.getContentLength();
        }

        // --- Non-Chunked Body Reading (Content-Length) ---
        // --- Non-Chunked Body Reading ---
        if (!chunked) {
            do {
                try {
                    std::copy(data.data.buf+cpos,data.data.buf+recv,std::back_inserter(ret));
                    std::copy(data.data.buf + cpos,
                              data.data.buf + recv,
                              std::back_inserter(ret));
                    rlen -= recv;
                    if (rlen > 0) {
                        for (;;) {
@@ -475,20 +552,20 @@ const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq
                            try {
                                recv = _cltsock->recvData(data);

                                // 🛑 CRITICAL EOF CHECK: connection closed before Content-Length was satisfied
                                if (recv <= 0) {
                                    throw netplus::NetException()
                                    [netplus::NetException::Error] << "Premature EOF while reading HTTP response body.";
                                        [netplus::NetException::Error]
                                        << "Premature EOF while reading HTTP response body.";
                                }

                                break;
                            } catch (netplus::NetException &e) {
                                if (e.getErrorType() == netplus::NetException::Note) {
                                    // FIX: Wait politely (10ms)
                                    std::this_thread::sleep_for(std::chrono::milliseconds(10));
                                    continue;
                                }
                                e[netplus::NetException::Error] << "nginxfiler: can't reach nginx server !";
                                e[netplus::NetException::Error]
                                    << "nginxfiler: can't reach nginx server !";
                                throw e;
                            }
                        }
@@ -508,15 +585,19 @@ const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq
            for (;;) {
                if (recv - cpos > 0) {
                    if (readed == chunklen) {
                        if( (chunklen=readchunk(data.data.buf,recv,cpos)) == 0 ){
                        chunklen = readchunk(data.data.buf, recv, cpos);
                        if (chunklen == 0) {
                            // final chunk: DO NOT copy 0\r\n\r\n into ret
                            break;
                        }
                        readed = 0;
                    }

                    int len = (chunklen - readed) < (recv - cpos) ? (chunklen - readed) : (recv - cpos);
                    int len = std::min(chunklen - readed, recv - cpos);

                    std::copy(data.data.buf+cpos,data.data.buf+(cpos+len),std::back_inserter(ret));
                    std::copy(data.data.buf + cpos,
                              data.data.buf + cpos + len,
                              std::back_inserter(ret));
                    cpos   += len;
                    readed += len;
                } else {
@@ -525,10 +606,10 @@ const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq
                        try {
                            recv = _cltsock->recvData(data);

                            // 🛑 CRITICAL EOF CHECK: premature connection close
                            if (recv <= 0) {
                                throw netplus::NetException()
                                    [netplus::NetException::Error] << "Premature EOF while reading chunked body.";
                                    [netplus::NetException::Error]
                                    << "Premature EOF while reading chunked body.";
                            }

                            break;
@@ -538,96 +619,85 @@ const std::vector<char> libhttppp::HttpClient::Post(libhttppp::HttpRequest &nreq
                                ee[libhttppp::HTTPException::Error] << e.what();
                                throw ee;
                            } else {
                                // FIX: Wait politely (10ms)
                                std::this_thread::sleep_for(std::chrono::milliseconds(10));
                                continue;
                            }
                        }
                    }
                }
            };
            }
        }
    } catch (netplus::NetException &e) {
        libhttppp::HTTPException ee;
        ee[libhttppp::HTTPException::Error] << e.what();
        throw ee;
    }

    return ret;
}


int libhttppp::HttpClient::readchunk(const char *data,int datasize,int &pos){
    // Skip any leading CRLF from the previous chunk's data terminator
int libhttppp::HttpClient::readchunk(const char *data, int datasize, int &pos)
{
    // 1) Skip CRLF left after previous chunk
    while (pos < datasize && (data[pos] == '\r' || data[pos] == '\n')) {
        ++pos;
    }

    // Now pos should be at the first hex digit of the chunk size line
    // 2) pos is now at first hex digit of size line (or end)
    int start = pos;

    // Find the end of the chunk size line (CR)
    // Find end of size line (up to CR)
    while (pos < datasize && data[pos] != '\r') {
        ++pos;
    }

    if (pos >= datasize) {
        libhttppp::HTTPException ee;
        ee[libhttppp::HTTPException::Error] << "nginxfiler: invalid chunked encoding (incomplete size line)";
        ee[libhttppp::HTTPException::Error]
            << "nginxfiler: invalid chunked encoding (incomplete size line)";
        throw ee;
    }

    int len = pos - start;

    if (len <= 0) {
        // Empty size line is illegal; treat as protocol error
    if (len <= 0 || len >= 512) {
        libhttppp::HTTPException ee;
        ee[libhttppp::HTTPException::Error] << "nginxfiler: invalid chunked encoding (empty chunk size)";
        throw ee;
    }

    if (len >= 512) {
        libhttppp::HTTPException ee;
        ee[libhttppp::HTTPException::Error] << "nginxfiler: chunk size line (" << len
                                            << ") too big, aborting!";
        ee[libhttppp::HTTPException::Error]
            << "nginxfiler: invalid chunk size line length: " << len;
        throw ee;
    }

    char value[512];
    memcpy(value, data + start, len);
    std::memcpy(value, data + start, len);
    value[len] = '\0';

    // Strip optional chunk extensions: "1A3;foo=bar" -> "1A3"
    char *semi = strchr(value, ';');
    if (semi) {
    // Strip chunk extensions: "d57;foo=bar" -> "d57"
    if (char *semi = std::strchr(value, ';')) {
        *semi = '\0';
    }

    char *endptr = nullptr;
    long result = strtol(value, &endptr, 16);
    if (endptr == value) {
        libhttppp::HTTPException ee;
        ee[libhttppp::HTTPException::Error] << "nginxfiler: invalid hex chunk size: '" << value << "'";
        throw ee;
    }
    if (result < 0) {
    long result = std::strtol(value, &endptr, 16);
    if (endptr == value || result < 0) {
        libhttppp::HTTPException ee;
        ee[libhttppp::HTTPException::Error] << "nginxfiler: negative chunk size: " << result;
        ee[libhttppp::HTTPException::Error]
            << "nginxfiler: invalid hex chunk size: '" << value << "'";
        throw ee;
    }

    // Skip CRLF after the size line
    // 3) Skip CRLF after size line
    if (pos + 1 >= datasize || data[pos] != '\r' || data[pos + 1] != '\n') {
        libhttppp::HTTPException ee;
        ee[libhttppp::HTTPException::Error] << "nginxfiler: invalid chunked encoding (missing CRLF after size)";
        ee[libhttppp::HTTPException::Error]
            << "nginxfiler: invalid chunked encoding (missing CRLF after size)";
        throw ee;
    }
    pos += 2; // now pos points at the first byte of the chunk data
    pos += 2;  // NOW pos points at FIRST BYTE OF CHUNK DATA

    // Final chunk: result == 0
    return static_cast<int>(result);
    return static_cast<int>(result); // 0 for final "0\r\n\r\n"
}



libhttppp::HttpHeader::HttpHeader(){
  _firstHeaderData=nullptr;
  _lastHeaderData=nullptr;
@@ -1404,15 +1474,29 @@ size_t libhttppp::HttpRequest::parse() {
      size_t oldiv = 0, iv = 0;
      while (iv < value.size()) {
        if (value[iv] == ';') {
          ncontent->push_back(value.substr(oldiv, iv - oldiv));
          ++iv;
          while (iv < value.size() && value[iv] == ' ') ++iv;
          // substring [oldiv, iv)
          std::string token = value.substr(oldiv, iv - oldiv);
          trim_inplace(token);             // remove leading/trailing spaces
          if (!token.empty()) {
            ncontent->push_back(token);
          }

          ++iv;                            // skip ';'
          while (iv < value.size() && value[iv] == ' ')
            ++iv;                        // skip spaces after ';'
          oldiv = iv;
        } else {
          ++iv;
        }
      }
      ncontent->push_back(value.substr(oldiv));

      // last token (after last ';' or whole value if no ';')
      std::string token = value.substr(oldiv);
      trim_inplace(token);
      if (!token.empty()) {
        ncontent->push_back(token);
      }

    }

  } catch (netplus::NetException& e) {