samedi 31 octobre 2020

OpenSSL memory overload

So, i have a class:

// in tcpserver.h
class TcpServer {
public:
 void mainLoop();
private:
 SSL* ssl;
 SSL_CTX* ssl_ctx;
 std::unordered_map<const char*, std::string> pages;
 // also here many non-related (i think) stuff
};
// in tcpserver.cpp
#include "tcpserver.h"

// too much code of initialization socket and setting it's properties
void TcpServer::mainLoop() {
 int i32ConnectFD;
 std::vector<char> buffer(4096U);
 for (
 ssl = SSL_new(ssl_ctx); // means TcpServer::ssl and TcpServer::ssl_ctx (configurated)
 ;
 SSL_free(ssl),
 ssl = SSL_new(ssl_ctx)
 ) {
  i32ConnectFD = accept(i32SocketFD, (sockaddr*)&cliAddr, &cliAddrLen); // means TcpServer::i32SocketFD, TcpServer::cliAddr and TcpServer::cliAddrLen
  if (i32ConnectFD < 0) { /* handle error */ }
  SSL_set_fd(ssl, i32ConnectFD);
  int code{ 1 };
  if ((code = SSL_accept(ssl)) <= 0) { /* handle error */ }
  int rcv_bytes = SSL_read(ssl, &buffer.front(), buffer.size() - 1);
  std::string request{ buffer.begin(), buffer.end() };
  if (rcv_bytes > 0 && static_cast<size_t>(rcv_bytes) < buffer.size()) {
   int snd_bytes{ 0 };
   for (const auto page : pages) {
    if (request.find(page.first) != std::string::npos) {
     snd_bytes = SSL_write(ssl, &page.second.front(), static_cast<int>(page.second.size()));
     break;
    }
   }
   if (snd_bytes == 0)
    snd_bytes = SSL_write(ssl, &pages["404_default"].front(), static_cast<int>(pages["404_default"].size()));
   // next section of logging with std::cout, std::setw, std::right, std::left and std::flush
   // i test it by myself, so i don't think problem caused here
   SSL_shutdown(ssl);
   closeConnection(i32ConnectFD);
   /*
   void closeConnection(int _fd) {
    shutdown(_fd);
    close(_fd);
   }
   */
  }
 }
}

Problem is memory being overloaded. Every new connection makes +240-260 or +640 or +800-1000 bytes. If you need more code, i can provide it. I have shortened the code as much as possible (OpenSSL only).

Aucun commentaire:

Enregistrer un commentaire