Commit d1d837c3 authored by jan.koester's avatar jan.koester
Browse files

some fixes

parent 8c6bef63
Loading
Loading
Loading
Loading
+100 −188
Changes for src/http.cpp: 100 added lines, 188 removed lines.
Original line number Diff line number Diff line
@@ -34,6 +34,7 @@
#include <iterator>
#include <map>
#include <iomanip>
#include <random>

#include "config.h"

@@ -55,82 +56,33 @@ libhttppp::HttpUrl::HttpUrl(){
libhttppp::HttpUrl::HttpUrl(const std::string& url, bool http3): HttpUrl(url.c_str(),http3){
}


libhttppp::HttpUrl::HttpUrl(const char* url, bool http3){
  HTTPException exp;
  if(http3){
    _protocol=HttpProtocol::HTTP3;
    _port=443;
  }else if(strncmp("https",url,5)==0){
    _protocol=HttpProtocol::HTTPS;
    _port=443;
  }else if(strncmp("http",url,4)==0){
    _protocol=HttpProtocol::HTTP;
    _port=80;
  }else{
    exp[HTTPException::Error] << "Httpurl: protocol not supported!";
    throw exp;
  }
  if (http3) { _protocol = HttpProtocol::HTTP3; _port = 443; }
  else if (std::strncmp(url, "https://", 8) == 0) { _protocol = HTTPS; _port = 443; url += 8; }
  else if (std::strncmp(url, "http://", 7) == 0)  { _protocol = HTTP;  _port = 80;  url += 7; }
  else if (std::strncmp(url, "https", 5) == 0)    { _protocol = HTTPS; _port = 443; }
  else if (std::strncmp(url, "http", 4) == 0)     { _protocol = HTTP;  _port = 80;  }
  else { exp[HTTPException::Error] << "Httpurl: protocol not supported!"; throw exp; }

  _path = "/";

  size_t urls=strlen(url);

  bool doted=false;

  size_t hstartp=std::string::npos;
  size_t pstart=std::string::npos,pend=urls;

  size_t pos;

  for(pos=0; pos<urls; ++pos){
    if(url[pos]==':'){
      doted=true;
    }else{
      doted=false;
      continue;
    }

    if(doted){
      if(url[++pos]=='/'){
        if(url[++pos]=='/' ){
          hstartp=++pos;
          while(pos < urls){
            if(url[pos]==':' || url[pos]=='/'){
              break;
            }
            ++pos;
          };
          std::copy(url+hstartp,url+pos,std::back_inserter(_host));
          break;
        }
      }
    }
  }

  while(pos<urls){
    if (url[pos]==':' ){
      pstart=++pos;
      while(isdigit(url[pos])==0){
        pend=pos;
        ++pos;
      };
  const char* p = url;
  const char* host_start = p;
  while (*p && *p != ':' && *p != '/') ++p;
  _host.assign(host_start, p - host_start);

      if(pend-pstart>254){
        exp[HTTPException::Error] << "Httpurl: Port range are Wrong !";
        throw exp;
  if (*p == ':') {
    ++p;
    const char* digits = p;
    while (*p && std::isdigit((unsigned char)*p)) ++p;
    if (p == digits || (p - digits) > 5) {
      exp[HTTPException::Error] << "Httpurl: Port range are Wrong !"; throw exp;
    }
      char tmp[255];
      std::copy(url+pstart,url+pend,tmp);
      _port=atoi(tmp);
    }else if (url[pos]=='/'){
      _path.clear();
      std::copy(url+pos,url+urls,std::back_inserter(_path));
      break;
    }
    ++pos;
    _port = std::atoi(std::string(digits, p - digits).c_str());
  }

  if (*p == '/') _path.assign(p);
}

libhttppp::HttpUrl::HttpUrl(const HttpUrl& src){
@@ -1229,18 +1181,12 @@ size_t libhttppp::HttpRequest::parse() {
          return no_query.substr(slash); // include leading '/'
        }

        // authority-form (CONNECT): "host:port"
        // No path component → normalize to "/"
        return "/";
      };

      _RequestURL = extract_path(_Request);
    }


    // 8) Parse header fields (from cursor to end of header buffer)
    // Each header line: key ":" value "\r\n"
    // We will lowercase KEY safely; VALUE is left as-is (trimmed), **not** lowercased.
    size_t line_start = cursor;

    while (line_start < header.size()) {
@@ -2130,169 +2076,135 @@ libhttppp::HttpAuth::~HttpAuth(){


void libhttppp::HttpAuth::parse(libhttppp::HttpRequest &curreq) {
  HttpHeader::HeaderData *hau = curreq.getHeaderData("authorization");
  if (!hau) return;

  auto parseDigestParameters = [this](const std::string& params) {

    size_t current_pos = 0;
    while (current_pos < params.length()) {

      current_pos = params.find_first_not_of(" ,", current_pos);
      if (current_pos == std::string::npos) break; // Finished

      size_t equals_pos = params.find('=', current_pos);
      if (equals_pos == std::string::npos) break; // Malformed

      std::string key = params.substr(current_pos, equals_pos - current_pos);
      key.erase(std::remove_if(key.begin(), key.end(), ::isspace), key.end());

      size_t value_start = equals_pos + 1;

      if (params[value_start] == '"') {
        value_start++;
        size_t value_end = params.find('"', value_start);
        if (value_end == std::string::npos) break;
        std::string value = params.substr(value_start, value_end - value_start);
        current_pos = value_end + 1;
      } else {
        size_t value_end = params.find(',', value_start);
        if (value_end == std::string::npos) value_end = params.length();

        std::string value = params.substr(value_start, value_end - value_start);
        value.erase(std::remove_if(value.begin(), value.end(), ::isspace), value.end());

        current_pos = value_end;
        if (key == "realm") {
           setRealm(value);
        }  /*else if (key == "nonce") {
        setNonce(value);
      }*/
      }
      // ... and so on for all expected Digest parameters
    }
  auto starts_with_icase = [](const std::string& s, const char* p){
    size_t n = std::strlen(p); if (s.size() < n) return false;
    for (size_t i = 0; i < n; ++i)
      if (std::tolower((unsigned char)s[i]) != std::tolower((unsigned char)p[i])) return false;
    return true;
  };

  HttpHeader::HeaderData *hau = curreq.getHeaderData("authorization");
  if (!hau)
    return;

  // Use a variable to hold the extracted token/parameters string
  std::string token_data;
  std::string token_data;            // raw (un-lowercased) token/params
  netplus::base64 base64str;
  _Authtype = -1; // Initialize to prevent unexpected behavior
  _Authtype = -1;

  for (HttpHeader::HeaderData::Values *cval = hau->getfirstValue(); cval; cval = cval->nextvalue()) {
  for (auto *cval = hau->getfirstValue(); cval; cval = cval->nextvalue()) {
    const std::string& raw = cval->getvalue();

    // Use a local reference for the header value to avoid confusing the outer 'authstr'
    std::string header_value = cval->getvalue();
    // trim leading spaces
    size_t i = 0; while (i < raw.size() && std::isspace((unsigned char)raw[i])) ++i;
    std::string s = (i ? raw.substr(i) : raw);

    for (size_t it = 0; it < header_value.length(); ++it) {
        header_value[it] = static_cast<char>(
            std::tolower(static_cast<unsigned char>(header_value[it]))
        );
    }
    // --- BASIC AUTH PARSING ---
    size_t at = header_value.find("basic ");
    if (at != std::string::npos) {
      at += 6; // Move 'at' past "basic"
    if (starts_with_icase(s, "Basic ")) {
      _Authtype = BASICAUTH;

      token_data = header_value.substr(at);

      while (at < token_data.length() && token_data[at] == ' ') {
        at++;
      }

      token_data = s.substr(6);
      // trim left spaces of token
      size_t j = 0; while (j < token_data.size() && token_data[j] == ' ') ++j;
      token_data.erase(0, j);
      base64str.setEncodedData(token_data);
      break; // Stop parsing header values
      break;
    }

    at = header_value.find("digest ");
    if (at != std::string::npos) {
      at += 7;
    if (starts_with_icase(s, "Digest ")) {
      _Authtype = DIGESTAUTH;

      while (at < header_value.length() && header_value[at] == ' ') {
        at++;
      token_data = s.substr(7);
      size_t j = 0; while (j < token_data.size() && token_data[j] == ' ') ++j;
      token_data.erase(0, j);
      break;
    }
  }

      token_data = header_value.substr(at);
  auto parseDigestParameters = [this](const std::string& params) {
    size_t p = 0;
    while (p < params.size()) {
      p = params.find_first_not_of(" ,", p);
      if (p == std::string::npos) break;
      size_t eq = params.find('=', p);
      if (eq == std::string::npos) break;
      std::string key = params.substr(p, eq - p);
      key.erase(std::remove_if(key.begin(), key.end(), ::isspace), key.end());

      break;
      size_t v0 = eq + 1;
      std::string value;
      if (v0 < params.size() && params[v0] == '"') {
        ++v0;
        size_t v1 = params.find('"', v0);
        if (v1 == std::string::npos) break;
        value = params.substr(v0, v1 - v0);
        p = v1 + 1;
      } else {
        size_t v1 = params.find(',', v0);
        if (v1 == std::string::npos) v1 = params.size();
        value = params.substr(v0, v1 - v0);
        value.erase(std::remove_if(value.begin(), value.end(), ::isspace), value.end());
        p = v1;
      }

      if (key == "realm") setRealm(value);
      // add more keys as needed
    }
  };

  switch (_Authtype) {
    case BASICAUTH: {
      std::string clearstr;
      base64str >> clearstr;
      std::cout << clearstr << std::endl;

      size_t clearpos = clearstr.find(':');

      if (clearpos != std::string::npos) {
        std::string username = clearstr.substr(0, clearpos);
        std::string password = clearstr.substr(clearpos + 1);
        setUsername(username);
        setPassword(password);
      } else {
        HTTPException e;
        e[HTTPException::Error] << "Basic Auth payload missing separator ':'";
      base64str >> clearstr;                     // "user:pass"
      size_t colon = clearstr.find(':');
      if (colon == std::string::npos) {
        HTTPException e; e[HTTPException::Error] << "Basic Auth payload missing separator ':'";
        throw e;
      }
      setUsername(clearstr.substr(0, colon));
      setPassword(clearstr.substr(colon + 1));
    } break;

    case DIGESTAUTH: {
      if (!token_data.empty()) {
        parseDigestParameters(token_data);
      } else {
        HTTPException e;
        e[HTTPException::Error] << "Digest Auth header is empty";
        throw e;
      if (token_data.empty()) {
        HTTPException e; e[HTTPException::Error] << "Digest Auth header is empty"; throw e;
      }
      parseDigestParameters(token_data);
    } break;

    default: {
      HTTPException e;
      e[HTTPException::Error] << "No valid authorization method found";
      throw e;
      HTTPException e; e[HTTPException::Error] << "No valid authorization method found"; throw e;
    }
  }
}



void libhttppp::HttpAuth::setAuth(libhttppp::HttpResponse &curresp){
  HttpHeader::HeaderData *dat = curresp.setHeaderData("WWW-Authenticate");
  HttpHeader::HeaderData::Values cval;

  auto random_hex = [] (size_t n) {
    static thread_local std::mt19937_64 rng{std::random_device{}()};
    static const char* hex = "0123456789abcdef";
    std::string s; s.reserve(n);
    for (size_t i = 0; i < n; ++i) s.push_back(hex[rng() & 0xF]);
    return s;
  };

  switch (_Authtype) {
    case BASICAUTH: {
      cval<<"basic";

      if(!_Realm.empty()){
        cval << " realm=\""+_Realm+"\"";
      }
      cval << "Basic";
      if (!_Realm.empty()) cval << " realm=\"" + _Realm + "\"";
    } break;
    case DIGESTAUTH: {
      cval << "digest";
      if(!_Realm.empty()){
        cval << " realm=\""+_Realm+"\"";
      }
      std::string nonce;
      for(size_t noncepos=0; noncepos<=16; noncepos++){
        int random[]={1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f','\0'};
        for(size_t rdpos=0; random[rdpos]!='\0'; rdpos++){
          nonce[noncepos]=random[rdpos];
        }
      }
      cval << "Digest";
      if (!_Realm.empty()) cval << " realm=\"" + _Realm + "\"";
      std::string nonce = random_hex(32);
      cval << " nonce=\"" + nonce + "\"";
    } break;
    default: {
      HTTPException e;
      e[HTTPException::Error] << "no auth method choose !";
      throw e;
      HTTPException e; e[HTTPException::Error] << "no auth method choose !"; throw e;
    }
  }
  dat->push_back(cval);
}


void libhttppp::HttpAuth::setAuthType(int authtype){
  _Authtype=authtype;
}