Indy icon indicating copy to clipboard operation
Indy copied to clipboard

Memory leak in OpenSSL

Open rlebeau opened this issue 7 years ago • 0 comments

Within OpenSSL, error queue data structures are allocated automatically for new threads and must be freed when the thread terminates.

Currently, TIdServerIOHandlerSSLOpenSSL does not handle this. Modifying TIdSSLSocket.Destroy() removed the leaks:

destructor TIdSSLSocket.Destroy;
begin
  if fSSL <> nil then begin
    //SSL_set_shutdown(fSSL, SSL_SENT_SHUTDOWN);
    SSL_shutdown(fSSL);
    SSL_free(fSSL);
    fSSL := nil;
  end;
  FreeAndNil(fSSLCipher);
  FreeAndNil(fPeerCert);
  ERR_remove_thread_state(0); <---- Add this line
  inherited Destroy;
end;

However, TIdSSLSocket is not tied to any particular thread, so its destructor is not the best place to call ERR_remove_thread_state(). A better approach is to hook into the threads that are managed by the TIdSchedulerOfThread... components directly and do the cleanup during thread shutdowns. Derive a new class from TIdThreadWithTaskClass, override its virtual AfterExecute() method to call ERR_remove_thread_state(), assign the desired TIdSchedulerOfThread... component to the TIdTCPServer.Scheduler property, and assign the custom class type to the TIdSchedulerOfThread.ThreadClass property.

Need to figure out a way to make this more automated.

rlebeau avatar Apr 06 '17 00:04 rlebeau