Compare commits
30
Commits
5feabd0fde
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8514d9689 | ||
|
|
c0e1d87ac1 | ||
|
|
4918654715 | ||
|
|
4bfede1342 | ||
|
|
dc6b1dcc56 | ||
|
|
6483729de3 | ||
|
|
1d3d30cd05 | ||
|
|
d058322cc6 | ||
|
|
8009564a7a | ||
|
|
0bb926a264 | ||
|
|
3383595296 | ||
|
|
2c65939788 | ||
|
|
1e9b5f1016 | ||
|
|
cfc0b19418 | ||
|
|
bee8b92a6d | ||
|
|
381ed86875 | ||
|
|
3609ed603e | ||
|
|
1a15f6ced8 | ||
|
|
2676aaf84c | ||
|
|
c3e8d70774 | ||
|
|
a51a486560 | ||
|
|
dfb33c0f16 | ||
|
|
989aee9482 | ||
|
|
701d03dcd9 | ||
|
|
b5f4947f7c | ||
|
|
1d16d0c17f | ||
|
|
4230734ee6 | ||
|
|
57f47fdecb | ||
|
|
3a75e920d9 | ||
|
|
9a39b6224c |
No files matched your search
+1
-1
@@ -11,4 +11,4 @@ docs/html
|
|||||||
*/mmap_address.bin
|
*/mmap_address.bin
|
||||||
.history/*
|
.history/*
|
||||||
html
|
html
|
||||||
latex
|
latex*.pre-*
|
||||||
+7
-4
@@ -1,14 +1,17 @@
|
|||||||
#include "Command.h"
|
#include "Command.h"
|
||||||
#include "Log.h"
|
|
||||||
#include "CommandList.h"
|
#include "CommandList.h"
|
||||||
|
#include "Log.h"
|
||||||
|
|
||||||
namespace core {
|
namespace core
|
||||||
|
{
|
||||||
|
|
||||||
int Command::processCommand(coreutils::ZString &request, TCPSession &session) {
|
int Command::processCommand(coreutils::ZString &request, TCPSession &session)
|
||||||
|
{
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Command::output(std::stringstream &out) {
|
void Command::output(std::stringstream &out)
|
||||||
|
{
|
||||||
out << "Write your own command description here for the help system." << std::endl;
|
out << "Write your own command description here for the help system." << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+42
-3
@@ -1,11 +1,30 @@
|
|||||||
#include "CommandList.h"
|
#include "CommandList.h"
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cctype>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
CommandList::CommandList(std::string delimiter, int depth) : delimiter(delimiter), depth(depth) {}
|
CommandList::CommandList(std::string delimiter, int depth) : delimiter(delimiter), depth(depth) {}
|
||||||
|
|
||||||
void CommandList::add(Command &command, std::string name) {
|
void CommandList::add(Command &command, std::string name) {
|
||||||
|
// processRequest() below upper-cases the incoming keyword before
|
||||||
|
// looking it up, but this previously stored whatever case the
|
||||||
|
// caller passed in verbatim - any registration that wasn't
|
||||||
|
// already uppercase (nearly everything outside SMTP/POP3/IMAP's
|
||||||
|
// own RFC-driven uppercase convention) could then NEVER be
|
||||||
|
// matched by any input, since upper-casing a non-uppercase string
|
||||||
|
// can't produce a match against a non-uppercase key. Confirmed:
|
||||||
|
// this alone made every Zephora game command unreachable, along
|
||||||
|
// with this class's own base-level "publish"/"subscribe"/"event"/
|
||||||
|
// etc. registrations (TCPServer's constructor). Folding the same
|
||||||
|
// way here keeps registration and lookup permanently in sync
|
||||||
|
// regardless of what case any given add() call happens to use -
|
||||||
|
// already-uppercase callers (SMTP, the BARANTMail admin console)
|
||||||
|
// are unaffected, since upper-casing an uppercase string is a
|
||||||
|
// no-op.
|
||||||
|
std::transform(name.begin(), name.end(), name.begin(),
|
||||||
|
[](unsigned char c) { return std::toupper(c); });
|
||||||
commands.insert(std::make_pair(name, &command));
|
commands.insert(std::make_pair(name, &command));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,7 +40,20 @@ namespace core {
|
|||||||
request.split(delimiter, depth);
|
request.split(delimiter, depth);
|
||||||
request.reset();
|
request.reset();
|
||||||
try {
|
try {
|
||||||
auto command = commands.at(request[0].str());
|
// Every protocol built on this (SMTP, POP3, IMAP - RFC 5321
|
||||||
|
// 2.4, RFC 1939 3, RFC 3501 2.2.1) specifies that command
|
||||||
|
// keywords are case-insensitive, but commands are always
|
||||||
|
// registered here in uppercase and this was an exact-match
|
||||||
|
// lookup - "mail from:" or "Mail From:" (both legal on the
|
||||||
|
// wire, and not unusual from real clients) silently failed
|
||||||
|
// to dispatch at all. Only the lookup key is case-folded;
|
||||||
|
// the token instances handlers actually receive are
|
||||||
|
// untouched, so any handler doing its own case-sensitive
|
||||||
|
// parsing on arguments is unaffected.
|
||||||
|
std::string key = request[0].str();
|
||||||
|
std::transform(key.begin(), key.end(), key.begin(),
|
||||||
|
[](unsigned char c) { return std::toupper(c); });
|
||||||
|
auto command = commands.at(key);
|
||||||
return command->processCommand(request, session);
|
return command->processCommand(request, session);
|
||||||
}
|
}
|
||||||
catch(...) {
|
catch(...) {
|
||||||
@@ -41,8 +73,15 @@ namespace core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int CommandList::processCommand(coreutils::ZString &request, TCPSession &session) {
|
int CommandList::processCommand(coreutils::ZString &request, TCPSession &session) {
|
||||||
// for(Command *command : commands)
|
// The intent was always "typing help lists the available
|
||||||
// session.out << command->getName() << std::endl;
|
// commands" - this was left as a no-op stub (the commented-out
|
||||||
|
// body even called a Command::getName() that was never added to
|
||||||
|
// the base class) so every registered CommandList - including
|
||||||
|
// the top-level one behind the "help" command itself - silently
|
||||||
|
// did nothing. The map's own key IS the registered name (see
|
||||||
|
// add()), so no getName() is needed at all - just walk it directly.
|
||||||
|
for (auto &pair : commands)
|
||||||
|
session.out << pair.first << std::string("\r\n");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+14
-3
@@ -5,17 +5,28 @@
|
|||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
ConsoleServer::ConsoleServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo) : TCPServer(ePoll, address, tlsInfo, " ", 10, "Console Server") {
|
ConsoleServer::ConsoleServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo,
|
||||||
|
std::function<bool(std::string, std::string)> credentialChecker)
|
||||||
|
: TCPServer(ePoll, address, tlsInfo, " ", 10, "Console Server"), credentialChecker(credentialChecker) {
|
||||||
coreutils::Log(this);
|
coreutils::Log(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
void ConsoleServer::logSend(std::string out) {
|
void ConsoleServer::logSend(std::string out) {
|
||||||
for(auto *session : sessions)
|
// Was unlocked entirely (and iterated raw pointers before
|
||||||
((ConsoleSession *)session)->writeLog(out);
|
// TCPServer::sessions became shared_ptr-owned - see its own doc
|
||||||
|
// comment) despite connectionRequest()/removeFromSessionList()
|
||||||
|
// both mutating this same vector under `lock` from other threads.
|
||||||
|
std::lock_guard guard(lock);
|
||||||
|
for(auto &session : sessions)
|
||||||
|
((ConsoleSession *)session.get())->writeLog(out);
|
||||||
}
|
}
|
||||||
|
|
||||||
TCPSession * ConsoleServer::getSocketAccept(EPoll &ePoll) {
|
TCPSession * ConsoleServer::getSocketAccept(EPoll &ePoll) {
|
||||||
return new ConsoleSession(ePoll, this);
|
return new ConsoleSession(ePoll, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool ConsoleServer::checkCredentials(std::string user, std::string password) {
|
||||||
|
return credentialChecker ? credentialChecker(user, password) : true;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+15
-2
@@ -6,6 +6,8 @@
|
|||||||
# include "EPoll.h"
|
# include "EPoll.h"
|
||||||
# include "LogListener.h"
|
# include "LogListener.h"
|
||||||
# include "TLSInfo.h"
|
# include "TLSInfo.h"
|
||||||
|
# include <functional>
|
||||||
|
# include <string>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
@@ -21,10 +23,16 @@ namespace core {
|
|||||||
public:
|
public:
|
||||||
|
|
||||||
//
|
//
|
||||||
//
|
// credentialChecker, when provided, is consulted by
|
||||||
|
// ConsoleSession's login flow (see its own doc comment) instead
|
||||||
|
// of the previous unconditional accept-anything behavior. Left
|
||||||
|
// defaulting to nullptr so any other, unrelated use of
|
||||||
|
// ConsoleServer that never cared about authentication is
|
||||||
|
// unaffected.
|
||||||
//
|
//
|
||||||
|
|
||||||
ConsoleServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo);
|
ConsoleServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo,
|
||||||
|
std::function<bool(std::string, std::string)> credentialChecker = nullptr);
|
||||||
|
|
||||||
//
|
//
|
||||||
//
|
//
|
||||||
@@ -34,6 +42,11 @@ namespace core {
|
|||||||
|
|
||||||
TCPSession * getSocketAccept(EPoll &ePoll) override;
|
TCPSession * getSocketAccept(EPoll &ePoll) override;
|
||||||
|
|
||||||
|
bool checkCredentials(std::string user, std::string password);
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::function<bool(std::string, std::string)> credentialChecker;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
#include "ConsoleSession.h"
|
#include "ConsoleSession.h"
|
||||||
|
#include "ConsoleServer.h"
|
||||||
#include "TCPServer.h"
|
#include "TCPServer.h"
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
|
|
||||||
@@ -27,6 +28,10 @@ namespace core {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case WAIT_USER_PROFILE:
|
case WAIT_USER_PROFILE:
|
||||||
|
// Previously discarded entirely - nothing captured what was
|
||||||
|
// actually typed here, so a real credential check further
|
||||||
|
// down could never have anything to compare against.
|
||||||
|
enteredUser = data.str();
|
||||||
status = PASSWORD;
|
status = PASSWORD;
|
||||||
protocol(blank);
|
protocol(blank);
|
||||||
break;
|
break;
|
||||||
@@ -37,8 +42,21 @@ namespace core {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case WAIT_PASSWORD:
|
case WAIT_PASSWORD:
|
||||||
|
// The actual check: previously this state unconditionally
|
||||||
|
// advanced to PROMPT regardless of what (if anything) was
|
||||||
|
// entered at either step - any username/password, including
|
||||||
|
// blank, reached the command prompt. checkCredentials()
|
||||||
|
// returns true unconditionally when the owning ConsoleServer
|
||||||
|
// was built without a credentialChecker, preserving that
|
||||||
|
// exact behavior for any other use of this class.
|
||||||
|
if (((ConsoleServer *)server)->checkCredentials(enteredUser, data.str())) {
|
||||||
status = PROMPT;
|
status = PROMPT;
|
||||||
protocol(blank);
|
protocol(blank);
|
||||||
|
} else {
|
||||||
|
out << "Login failed." << "\r\n";
|
||||||
|
status = DONE;
|
||||||
|
protocol(blank);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case PROMPT:
|
case PROMPT:
|
||||||
@@ -68,6 +86,11 @@ namespace core {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void ConsoleSession::onConnected() {
|
||||||
|
coreutils::ZString blank("");
|
||||||
|
protocol(blank);
|
||||||
|
}
|
||||||
|
|
||||||
void ConsoleSession::writeLog(std::string data) {
|
void ConsoleSession::writeLog(std::string data) {
|
||||||
// saveCursor();
|
// saveCursor();
|
||||||
// setCursorLocation(16, 1);
|
// setCursorLocation(16, 1);
|
||||||
|
|||||||
@@ -16,6 +16,14 @@ namespace core {
|
|||||||
/// Extend the protocol() method in order to define the behavior and
|
/// Extend the protocol() method in order to define the behavior and
|
||||||
/// protocol interaction for this socket which is a console session.
|
/// protocol interaction for this socket which is a console session.
|
||||||
///
|
///
|
||||||
|
/// The User:/Password: exchange is a real login when the owning
|
||||||
|
/// ConsoleServer was constructed with a credentialChecker (see its
|
||||||
|
/// own doc comment) - previously the entered username was never
|
||||||
|
/// even stored and the password was never compared against
|
||||||
|
/// anything, so any input (including blank) reached the command
|
||||||
|
/// prompt. A ConsoleServer built without a credentialChecker still
|
||||||
|
/// accepts anything, matching that original behavior exactly.
|
||||||
|
///
|
||||||
|
|
||||||
class ConsoleSession : public TerminalSession {
|
class ConsoleSession : public TerminalSession {
|
||||||
|
|
||||||
@@ -28,11 +36,27 @@ namespace core {
|
|||||||
protected:
|
protected:
|
||||||
void protocol(coreutils::ZString &data) override;
|
void protocol(coreutils::ZString &data) override;
|
||||||
|
|
||||||
|
// Previously absent entirely, so the state machine only ever
|
||||||
|
// advanced on the CLIENT's first line of input - that line was
|
||||||
|
// consumed just to drive WELCOME->LOGIN and was never used as
|
||||||
|
// real content, meaning every subsequent line was shifted one
|
||||||
|
// slot early (what the user typed as their *username* actually
|
||||||
|
// got compared as nothing, their *password* got captured as
|
||||||
|
// enteredUser, and their first real command got compared as the
|
||||||
|
// password). Harmless before real credential checking existed -
|
||||||
|
// any input reached the prompt regardless - but it broke login
|
||||||
|
// outright once checkCredentials() started actually comparing
|
||||||
|
// values. Kicking the state machine off here instead means
|
||||||
|
// "User: " is sent immediately on connect, before the client
|
||||||
|
// has sent anything at all.
|
||||||
|
void onConnected() override;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
enum Status {WELCOME, LOGIN, WAIT_USER_PROFILE, PASSWORD, WAIT_PASSWORD, PROMPT, INPUT, PROCESS, DONE};
|
enum Status {WELCOME, LOGIN, WAIT_USER_PROFILE, PASSWORD, WAIT_PASSWORD, PROMPT, INPUT, PROCESS, DONE};
|
||||||
Status status = WELCOME;
|
Status status = WELCOME;
|
||||||
void doCommand(coreutils::ZString &request);
|
void doCommand(coreutils::ZString &request);
|
||||||
coreutils::ZString command;
|
coreutils::ZString command;
|
||||||
|
std::string enteredUser;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -11,14 +11,41 @@ namespace core {
|
|||||||
|
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPoll starting.";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPoll starting.";
|
||||||
|
|
||||||
|
// Writing to a socket whose peer has already reset it raises
|
||||||
|
// SIGPIPE, and the default action terminates the whole process -
|
||||||
|
// every connection, not just the dead one. Socket.cpp has carried a
|
||||||
|
// sigpipe_handler for this but nothing ever installed it. Plain
|
||||||
|
// writes could use MSG_NOSIGNAL, but OpenSSL's SSL_write() calls
|
||||||
|
// write() itself, so the signal has to be ignored process-wide; the
|
||||||
|
// failed write then just returns EPIPE and that one connection is
|
||||||
|
// closed normally. Reproduced: a burst of STARTTLS clients
|
||||||
|
// disconnecting mid-session killed the server within a few rounds.
|
||||||
|
signal(SIGPIPE, SIG_IGN);
|
||||||
|
|
||||||
maxSockets = 1000;
|
maxSockets = 1000;
|
||||||
epfd = epoll_create1(0);
|
epfd = epoll_create1(0);
|
||||||
terminateThreads = false;
|
terminateThreads = false;
|
||||||
|
started = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
EPoll::~EPoll() {}
|
// Was empty - if this EPoll's worker pool was started but stop() was
|
||||||
|
// never explicitly called (e.g. an exception unwinding the stack
|
||||||
|
// during startup, before the caller's own normal shutdown path could
|
||||||
|
// run), the pool just kept running against this object's - and every
|
||||||
|
// Socket registered with it's - soon-to-be-freed memory. stop() itself
|
||||||
|
// is what actually joins every worker thread before anything gets
|
||||||
|
// torn down; see Thread::~Thread()'s doc comment for the crash this
|
||||||
|
// was confirmed to cause. Guarded by `started` so a never-started
|
||||||
|
// EPoll (numberOfThreads/threads still default) doesn't call stop()
|
||||||
|
// over a garbage thread count, and by `!terminateThreads` so an
|
||||||
|
// EPoll that already went through a normal stop() doesn't do it
|
||||||
|
// (and close an already-closed epfd) twice.
|
||||||
|
EPoll::~EPoll() {
|
||||||
|
if (started && !terminateThreads)
|
||||||
|
stop();
|
||||||
|
}
|
||||||
|
|
||||||
bool EPoll::start(int numberOfThreads, int maxSockets) {
|
bool EPoll::start(int numberOfThreads, int maxSockets, ThreadScope *scope) {
|
||||||
|
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "Starting epoll event processing.";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "Starting epoll event processing.";
|
||||||
|
|
||||||
@@ -32,15 +59,20 @@ namespace core {
|
|||||||
//----------------------------------------------------------------------
|
//----------------------------------------------------------------------
|
||||||
// Create thread objects into vector for number of threads requested.
|
// Create thread objects into vector for number of threads requested.
|
||||||
// Hand all the threads a pointer to the EPoll object so they can run
|
// Hand all the threads a pointer to the EPoll object so they can run
|
||||||
// the socket handlers.
|
// the socket handlers - and, if given, the same shared ThreadScope
|
||||||
|
// so each one runs its onThreadStart()/onThreadEnd() hooks (see
|
||||||
|
// ThreadScope's own doc comment for why - e.g. MySQL client library
|
||||||
|
// per-thread init).
|
||||||
//----------------------------------------------------------------------
|
//----------------------------------------------------------------------
|
||||||
|
|
||||||
for(int ix = 0; ix < numberOfThreads; ++ix)
|
for(int ix = 0; ix < numberOfThreads; ++ix)
|
||||||
threads.emplace_back(*this);
|
threads.emplace_back(*this, scope);
|
||||||
|
|
||||||
for(int ix = 0; ix < numberOfThreads; ++ix)
|
for(int ix = 0; ix < numberOfThreads; ++ix)
|
||||||
threads[ix].start();
|
threads[ix].start();
|
||||||
|
|
||||||
|
started = true;
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,7 +106,16 @@ namespace core {
|
|||||||
|
|
||||||
int EPoll::processCommand(coreutils::ZString &request, TCPSession &session) {
|
int EPoll::processCommand(coreutils::ZString &request, TCPSession &session) {
|
||||||
int sequence = 0;
|
int sequence = 0;
|
||||||
for(auto threadx : threads) {
|
// Was `for(auto threadx : threads)` - copied each live, running
|
||||||
|
// Thread by value. Harmless while ~Thread() was empty, but now
|
||||||
|
// that it actually joins and deletes the underlying std::thread*
|
||||||
|
// (see its own doc comment), a copy going out of scope at the end
|
||||||
|
// of each iteration would join and free the SAME thread the real
|
||||||
|
// vector entry still owns and expects to keep running - a
|
||||||
|
// double-free the next time anything lists threads on a live
|
||||||
|
// server (this method is reachable via the console's own command
|
||||||
|
// dispatch).
|
||||||
|
for(auto &threadx : threads) {
|
||||||
session.out << "|" << ++sequence;
|
session.out << "|" << ++sequence;
|
||||||
threadx.output(session.out);
|
threadx.output(session.out);
|
||||||
session.out << "|" << std::endl;
|
session.out << "|" << std::endl;
|
||||||
|
|||||||
@@ -51,9 +51,13 @@ namespace core {
|
|||||||
///
|
///
|
||||||
/// @param numberOfThreads the number of threads to start for processing epoll entries.
|
/// @param numberOfThreads the number of threads to start for processing epoll entries.
|
||||||
/// @param maxSockets the maximum number of open sockets that epoll will manage.
|
/// @param maxSockets the maximum number of open sockets that epoll will manage.
|
||||||
|
/// @param scope optional - if given, its onThreadStart()/onThreadEnd() run once on
|
||||||
|
/// each worker thread, at the top/bottom of that thread's own lifetime. The SAME
|
||||||
|
/// scope instance is shared across every worker thread - see ThreadScope's own
|
||||||
|
/// doc comment. Not owned by EPoll; caller keeps it alive for the server's lifetime.
|
||||||
///
|
///
|
||||||
|
|
||||||
bool start(int numberOfThreads, int maxSockets); ///< Start the BMAEPoll processing.
|
bool start(int numberOfThreads, int maxSockets, ThreadScope *scope = NULL); ///< Start the BMAEPoll processing.
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Use the stop() method to initiate the shutdown process for the epoll socket management.
|
/// Use the stop() method to initiate the shutdown process for the epoll socket management.
|
||||||
@@ -103,6 +107,12 @@ namespace core {
|
|||||||
int numberOfThreads;
|
int numberOfThreads;
|
||||||
std::vector<Thread> threads;
|
std::vector<Thread> threads;
|
||||||
volatile bool terminateThreads;
|
volatile bool terminateThreads;
|
||||||
|
// Guards ~EPoll()'s own call to stop() - false until start()
|
||||||
|
// actually runs, so a never-started EPoll (numberOfThreads and
|
||||||
|
// threads both still default/empty) doesn't have its destructor
|
||||||
|
// iterate a garbage thread count. See ~EPoll()'s own doc comment
|
||||||
|
// in EPoll.cpp for what this is actually protecting against.
|
||||||
|
bool started;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+38
-11
@@ -7,10 +7,16 @@ namespace core {
|
|||||||
|
|
||||||
INotify::INotify(EPoll &ePoll) : Socket(ePoll, "INotify") {
|
INotify::INotify(EPoll &ePoll) : Socket(ePoll, "INotify") {
|
||||||
setDescriptor(inotify_init());
|
setDescriptor(inotify_init());
|
||||||
|
// See isKnownINotify()'s own doc comment - registers this object
|
||||||
|
// as safe for Thread::run() to dispatch epoll events to directly.
|
||||||
|
std::lock_guard<std::mutex> guard(knownINotifiesMutex());
|
||||||
|
knownINotifies().insert(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
INotify::~INotify() {
|
INotify::~INotify() {
|
||||||
shutdown();
|
shutdown();
|
||||||
|
std::lock_guard<std::mutex> guard(knownINotifiesMutex());
|
||||||
|
knownINotifies().erase(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
int INotify::addWatch(coreutils::ZString &watch) {
|
int INotify::addWatch(coreutils::ZString &watch) {
|
||||||
@@ -28,32 +34,53 @@ namespace core {
|
|||||||
ptr < buffer.getData() + buffer.getLength();
|
ptr < buffer.getData() + buffer.getLength();
|
||||||
ptr += sizeof(struct inotify_event) + event->len) {
|
ptr += sizeof(struct inotify_event) + event->len) {
|
||||||
event = (const struct inotify_event *) ptr;
|
event = (const struct inotify_event *) ptr;
|
||||||
coreutils::ZString name(event->name);
|
|
||||||
|
// event->name only exists - and is only NUL-terminated - when
|
||||||
|
// event->len > 0 (inotify(7): "This field is present only when
|
||||||
|
// the event relates to a file inside a watched directory ...
|
||||||
|
// otherwise ... this field is absent."). For events with
|
||||||
|
// len == 0 (e.g. IN_UNMOUNT, IN_Q_OVERFLOW, IN_IGNORED, or
|
||||||
|
// self-watch events), event->name is not a valid C-string at
|
||||||
|
// all - calling strlen() on it (as the old ZString(const char*)
|
||||||
|
// one-arg constructor did unconditionally here) reads past
|
||||||
|
// whatever garbage follows in the socket's 4096-byte receive
|
||||||
|
// buffer looking for a NUL, a real heap-buffer-overflow read
|
||||||
|
// confirmed via AddressSanitizer under concurrent load (the
|
||||||
|
// eventual heap corruption this caused was previously
|
||||||
|
// misdiagnosed as a MySQL client thread-safety issue, since it
|
||||||
|
// surfaces on whichever EPoll worker thread happens to service
|
||||||
|
// this watcher's socket and corrupts unrelated heap state).
|
||||||
|
// strnlen() bounded by event->len (rather than the one-arg
|
||||||
|
// ZString ctor's unbounded strlen) matches the kernel's actual
|
||||||
|
// guarantee: name is NUL-padded to exactly event->len bytes.
|
||||||
|
coreutils::ZString name = event->len > 0
|
||||||
|
? coreutils::ZString(event->name, strnlen(event->name, event->len))
|
||||||
|
: coreutils::ZString("");
|
||||||
|
|
||||||
if(event->mask & IN_ACCESS)
|
if(event->mask & IN_ACCESS)
|
||||||
inAccess(name);
|
inAccess(name);
|
||||||
if(event->mask & IN_ATTRIB)
|
if(event->mask & IN_ATTRIB)
|
||||||
inAttrib(std::string(event->name));
|
inAttrib(name.str());
|
||||||
if(event->mask & IN_CLOSE_WRITE)
|
if(event->mask & IN_CLOSE_WRITE)
|
||||||
inCloseWrite(std::string(event->name));
|
inCloseWrite(name.str());
|
||||||
if(event->mask & IN_CLOSE_NOWRITE)
|
if(event->mask & IN_CLOSE_NOWRITE)
|
||||||
inCloseNoWrite(std::string(event->name));
|
inCloseNoWrite(name.str());
|
||||||
if(event->mask & IN_CREATE)
|
if(event->mask & IN_CREATE)
|
||||||
inCreate(name);
|
inCreate(name);
|
||||||
if(event->mask & IN_DELETE)
|
if(event->mask & IN_DELETE)
|
||||||
inDelete(std::string(event->name));
|
inDelete(name.str());
|
||||||
if(event->mask & IN_DELETE_SELF)
|
if(event->mask & IN_DELETE_SELF)
|
||||||
inDeleteSelf(std::string(event->name));
|
inDeleteSelf(name.str());
|
||||||
if(event->mask & IN_MODIFY)
|
if(event->mask & IN_MODIFY)
|
||||||
inModify(std::string(event->name));
|
inModify(name.str());
|
||||||
if(event->mask & IN_MOVE_SELF)
|
if(event->mask & IN_MOVE_SELF)
|
||||||
inMoveSelf(std::string(event->name));
|
inMoveSelf(name.str());
|
||||||
if(event->mask & IN_MOVED_FROM)
|
if(event->mask & IN_MOVED_FROM)
|
||||||
inMovedFrom(std::string(event->name));
|
inMovedFrom(name.str());
|
||||||
if(event->mask & IN_MOVED_TO)
|
if(event->mask & IN_MOVED_TO)
|
||||||
inMovedTo(std::string(event->name));
|
inMovedTo(name.str());
|
||||||
if(event->mask & IN_OPEN)
|
if(event->mask & IN_OPEN)
|
||||||
inOpen(std::string(event->name));
|
inOpen(name.str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
# define __INotify_h__
|
# define __INotify_h__
|
||||||
|
|
||||||
#include "Socket.h"
|
#include "Socket.h"
|
||||||
|
#include <set>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
@@ -29,6 +31,41 @@ namespace core {
|
|||||||
virtual void inMovedTo(std::string name) {}
|
virtual void inMovedTo(std::string name) {}
|
||||||
virtual void inOpen(std::string name) {}
|
virtual void inOpen(std::string name) {}
|
||||||
|
|
||||||
|
/// core::INotify is a long-lived Socket subclass that is neither
|
||||||
|
/// a TCPSession (shared_ptr/pin()-owned) nor a listening
|
||||||
|
/// TCPServer - it is normally embedded as a base subobject of a
|
||||||
|
/// server object constructed once in main() and living for the
|
||||||
|
/// whole process (e.g. mail::SMTPServer's queue-directory watch).
|
||||||
|
/// Thread::run()'s epoll dispatch only ever recognized those two
|
||||||
|
/// categories of raw pointer as safe to call directly (see
|
||||||
|
/// TCPServer::isKnownListeningSocket()'s own doc comment) -
|
||||||
|
/// anything else fell through to the "stale/unrecognized epoll
|
||||||
|
/// event" branch and was silently dropped forever. Confirmed
|
||||||
|
/// live: a real IN_CREATE event on a mail queue directory logged
|
||||||
|
/// exactly that "Ignoring stale/unrecognized epoll event" line
|
||||||
|
/// and the newly queued message was never delivered - it just sat
|
||||||
|
/// in the queue until the next process restart, whose
|
||||||
|
/// processExisting() directory scan (a plain synchronous loop,
|
||||||
|
/// entirely independent of epoll) happened to flush the backlog
|
||||||
|
/// and made the bug look intermittent. Registering the instance here,
|
||||||
|
/// mirroring listeningSockets() exactly, gives Thread::run() the
|
||||||
|
/// same kind of safe "yes, dispatch to this raw pointer directly"
|
||||||
|
/// signal for INotify objects too.
|
||||||
|
static bool isKnownINotify(void *ptr) {
|
||||||
|
std::lock_guard<std::mutex> guard(knownINotifiesMutex());
|
||||||
|
return knownINotifies().count(ptr) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::mutex &knownINotifiesMutex() {
|
||||||
|
static std::mutex m;
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
static std::set<void *> &knownINotifies() {
|
||||||
|
static std::set<void *> s;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-4
@@ -38,15 +38,22 @@ namespace core {
|
|||||||
return (sockaddr *)&addr;
|
return (sockaddr *)&addr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Was a stub that always returned "" - so everything keyed on the
|
||||||
|
// client address (SPF checks in BARANTMail, Received: headers,
|
||||||
|
// IPAddressList black/white lists) silently saw an empty string.
|
||||||
std::string IPAddress::getClientAddress() {
|
std::string IPAddress::getClientAddress() {
|
||||||
std::string result;
|
char text[INET_ADDRSTRLEN];
|
||||||
return result;
|
if (!inet_ntop(AF_INET, &addr.sin_addr, text, sizeof(text)))
|
||||||
|
return "";
|
||||||
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string IPAddress::getClientAddressAndPort() {
|
std::string IPAddress::getClientAddressAndPort() {
|
||||||
std::stringstream out;
|
std::stringstream out;
|
||||||
out << inet_ntoa(addr.sin_addr);
|
// inet_ntoa() returns a static buffer shared by every thread, and
|
||||||
out << ":" << addr.sin_port;
|
// sin_port is in network byte order.
|
||||||
|
out << getClientAddress();
|
||||||
|
out << ":" << ntohs(addr.sin_port);
|
||||||
return out.str();
|
return out.str();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+258
-13
@@ -3,6 +3,9 @@
|
|||||||
#include "Exception.h"
|
#include "Exception.h"
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
#include "ZString.h"
|
#include "ZString.h"
|
||||||
|
#include <iostream>
|
||||||
|
#include <poll.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
|
||||||
namespace core
|
namespace core
|
||||||
{
|
{
|
||||||
@@ -70,7 +73,7 @@ namespace core
|
|||||||
bool Socket::eventReceived(struct epoll_event event, long long eventId) {
|
bool Socket::eventReceived(struct epoll_event event, long long eventId) {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process beginning for socket " << getDescriptor();
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process beginning for socket " << getDescriptor();
|
||||||
if(inHandler)
|
if(inHandler)
|
||||||
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ coreutils::Log(coreutils::LOG_DEBUG_2) << "inHandler was already true.";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "inHandler was already true.";
|
||||||
inHandler = true;
|
inHandler = true;
|
||||||
if(event.events & EPOLLRDHUP) {
|
if(event.events & EPOLLRDHUP) {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLRDHUP";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLRDHUP";
|
||||||
@@ -79,24 +82,127 @@ namespace core
|
|||||||
}
|
}
|
||||||
if(event.events & EPOLLIN) {
|
if(event.events & EPOLLIN) {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLIN";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLIN";
|
||||||
|
// A read just happened (or at least an opportunity for OpenSSL
|
||||||
|
// to make progress on whatever it needed a read for) - give any
|
||||||
|
// write that was waiting on that a fresh attempt via this same
|
||||||
|
// call's own trailing resetSocket(), rather than leaving
|
||||||
|
// EPOLLWRNORM permanently un-armed from a single earlier stall.
|
||||||
|
waitingOnReadToWrite = false;
|
||||||
coreutils::ZString zbuffer(buffer, length);
|
coreutils::ZString zbuffer(buffer, length);
|
||||||
lock.lock();
|
// receiveData() calls all the way down through
|
||||||
|
// onDataReceived()/HTTPRequest::doParse()/application request
|
||||||
|
// handling with NO exception protection anywhere in that chain -
|
||||||
|
// confirmed live: a single thrown coreutils::Exception (e.g. a
|
||||||
|
// malformed request hitting a parse-time throw, well before
|
||||||
|
// ApiSession::handleComplete()'s own try/catch around
|
||||||
|
// match.render() ever runs) reached std::terminate() and killed
|
||||||
|
// the entire server process, not just this one connection, since
|
||||||
|
// this runs on an EPoll worker thread and C++ terminates the
|
||||||
|
// whole program on an exception escaping a thread. The old
|
||||||
|
// lock.lock()/lock.unlock() pair (no RAII) also leaked the lock
|
||||||
|
// permanently on this same path - std::lock_guard fixes that as
|
||||||
|
// a side effect of adding the try/catch here.
|
||||||
|
try {
|
||||||
|
std::lock_guard<std::mutex> guard(lock);
|
||||||
receiveData(zbuffer);
|
receiveData(zbuffer);
|
||||||
if(!shutDown) {
|
} catch(coreutils::Exception &e) {
|
||||||
inHandler = false;
|
// Also to stderr, not just Log() - this process's Log class
|
||||||
lock.unlock();
|
// writes through a static listener/file neither this server
|
||||||
resetSocket();
|
// nor its main() ever configures (its own startup banner
|
||||||
|
// uses plain std::cout, not Log at all), so a Log()-only
|
||||||
|
// message here would be silently dropped. stderr reliably
|
||||||
|
// lands in the log file given how this process is started
|
||||||
|
// (both stdout and stderr redirected to the same file).
|
||||||
|
std::cerr << "Exception processing socket " << getDescriptor() << ": " << e.text << std::endl;
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Exception processing socket " << getDescriptor() << ": " << e.text;
|
||||||
|
shutdown("exception during receiveData: " + e.text);
|
||||||
|
} catch(std::exception &e) {
|
||||||
|
std::cerr << "std::exception processing socket " << getDescriptor() << ": " << e.what() << std::endl;
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "std::exception processing socket " << getDescriptor() << ": " << e.what();
|
||||||
|
shutdown(std::string("exception during receiveData: ") + e.what());
|
||||||
|
} catch(...) {
|
||||||
|
std::cerr << "Unknown exception processing socket " << getDescriptor() << std::endl;
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Unknown exception processing socket " << getDescriptor();
|
||||||
|
shutdown("unknown exception during receiveData");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if(event.events & EPOLLWRNORM) {
|
if(event.events & EPOLLWRNORM) {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM";
|
||||||
writeSocket();
|
writeSocket();
|
||||||
|
}
|
||||||
|
// A graceful shutdown() (session.terminate() -> "goodbye" reply
|
||||||
|
// queued via write(), then shutdown() called - see e.g. IMAP's
|
||||||
|
// LOGOUT/POP3's QUIT/SMTP's QUIT) used to make keepAlive false
|
||||||
|
// the moment shutDown was set, in this SAME event cycle that had
|
||||||
|
// just queued that reply - Thread::run() then deletes this object
|
||||||
|
// immediately on a false return, before the reply was ever
|
||||||
|
// written to the actual socket (write() only queues into fifo;
|
||||||
|
// the real send() happens in writeSocket(), only reachable via a
|
||||||
|
// LATER EPOLLWRNORM event this object never lived to receive).
|
||||||
|
// Confirmed live: LOGOUT/QUIT connections closed correctly but
|
||||||
|
// their own final reply line never reached the client. Staying
|
||||||
|
// alive while shutDown is set but fifo still has data - as long
|
||||||
|
// as the peer hasn't already hung up (readHangup - trying to
|
||||||
|
// drain to a peer that's already gone is pointless, not graceful)
|
||||||
|
// - gives that queued reply a real chance to go out before this
|
||||||
|
// socket actually closes.
|
||||||
|
bool keepAlive = preventSelfDelete || !shutDown || (fifo.size() > 0 && !readHangup);
|
||||||
|
|
||||||
|
// resetSocket() re-arms this fd via EPOLL_CTL_MOD, which makes it
|
||||||
|
// immediately eligible for delivery to ANY worker thread's
|
||||||
|
// epoll_wait() - including one already blocked and about to wake
|
||||||
|
// up right away. The old code called resetSocket() from inside
|
||||||
|
// the branches above while several more statements (an
|
||||||
|
// unconditional inHandler write, this Log call, and `return
|
||||||
|
// !shutDown`) still touched `this` afterward - a second thread
|
||||||
|
// could legitimately receive the re-armed event, finish handling
|
||||||
|
// it, and delete this object (Thread::run() does exactly that
|
||||||
|
// when eventReceived() returns false) before this thread's own
|
||||||
|
// remaining statements ran, a heap-use-after-free confirmed via
|
||||||
|
// AddressSanitizer under concurrent load. resetSocket() must be
|
||||||
|
// the last thing that ever touches `this`, with the return value
|
||||||
|
// already captured in a local (`keepAlive`) beforehand.
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor();
|
||||||
|
// Was cleared several statements above (right after the EPOLLIN/
|
||||||
|
// EPOLLWRNORM handling), with no lock held around clearing it or
|
||||||
|
// calling resetSocket() below - a genuinely separate race from the
|
||||||
|
// one documented above: Socket::write() re-arms via this same
|
||||||
|
// resetSocket() (see its own doc comment there) whenever it can
|
||||||
|
// grab `lock`, from whatever thread called it (e.g. a broadcast
|
||||||
|
// hitting this session while ITS OWN eventReceived() call is still
|
||||||
|
// running, past receiveData()'s lock_guard but before reaching
|
||||||
|
// here). A first attempt narrowed this to just checking `inHandler`
|
||||||
|
// in both places, without holding `lock` across the check-and-act
|
||||||
|
// in either one - still a real TOCTOU window (inHandler read as
|
||||||
|
// false here, then write() on another thread sees false too and
|
||||||
|
// wins the race to resetSocket() first), confirmed live via
|
||||||
|
// AddressSanitizer as a genuine double-delete of the same session
|
||||||
|
// object (two threads both reaching ~TCPSession() on it) even
|
||||||
|
// after that narrowing. Holding `lock` for the whole
|
||||||
|
// clear-then-reset sequence - the exact same mutex write() already
|
||||||
|
// takes before its own resetSocket() call - makes the two
|
||||||
|
// mutually exclusive for real: whichever thread gets there first
|
||||||
|
// fully finishes (clearing inHandler and re-arming, or observing
|
||||||
|
// inHandler still true and skipping) before the other can act at
|
||||||
|
// all, closing the window rather than just narrowing it.
|
||||||
|
if(keepAlive) {
|
||||||
|
lock.lock();
|
||||||
inHandler = false;
|
inHandler = false;
|
||||||
resetSocket();
|
resetSocket();
|
||||||
|
lock.unlock();
|
||||||
}
|
}
|
||||||
inHandler = false;
|
// else: this object is about to be delete()'d by Thread::run() the
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor();
|
// moment this call returns, unconditionally, regardless of
|
||||||
return !shutDown;
|
// anything write() does. Leaving inHandler true forever (never
|
||||||
|
// clearing it here) means no other thread's write() can ever
|
||||||
|
// resetSocket() this dying object in the meantime - it has no
|
||||||
|
// future to reset it FOR, and letting write() re-arm it here, even
|
||||||
|
// briefly, was exactly the remaining gap: a third thread could
|
||||||
|
// pick up that re-armed fd and touch/delete an object Thread::run()
|
||||||
|
// was already about to free, a genuine double-delete confirmed
|
||||||
|
// live via AddressSanitizer even after write()/resetSocket() were
|
||||||
|
// otherwise fully serialized against each other.
|
||||||
|
return keepAlive;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Socket::connectionRequest() {}
|
void Socket::connectionRequest() {}
|
||||||
@@ -139,13 +245,116 @@ namespace core
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int Socket::sendData(const char *data, int length) {
|
||||||
|
return ::write(descriptor, data, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Socket::flushPlain(int timeoutMs) {
|
||||||
|
std::lock_guard<std::mutex> guard(outlock);
|
||||||
|
while(fifo.size() > 0) {
|
||||||
|
std::string &front = fifo.front();
|
||||||
|
ssize_t sent = ::send(descriptor, front.data(), front.length(), MSG_NOSIGNAL);
|
||||||
|
if(sent > 0) {
|
||||||
|
if((size_t)sent >= front.length())
|
||||||
|
fifo.pop();
|
||||||
|
else
|
||||||
|
front.erase(0, sent);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if(sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) {
|
||||||
|
struct pollfd pfd = { descriptor, POLLOUT, 0 };
|
||||||
|
if(::poll(&pfd, 1, timeoutMs) > 0)
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
void Socket::writeSocket() {
|
void Socket::writeSocket() {
|
||||||
outlock.lock();
|
outlock.lock();
|
||||||
// coreutils::Log(coreutils::LOG_DEBUG_3) << "writing data to socket " << getDescriptor();
|
// coreutils::Log(coreutils::LOG_DEBUG_3) << "writing data to socket " << getDescriptor();
|
||||||
if(fifo.size() > 0) {
|
if(fifo.size() > 0) {
|
||||||
if(!shutDown)
|
// No longer gated on !shutDown: writeSocket() only ever runs in
|
||||||
int rc = ::write(descriptor, fifo.front().c_str(), fifo.front().length());
|
// response to an EPOLLWRNORM event this object explicitly
|
||||||
|
// re-armed for (see resetSocket()'s own doc comment) - refusing
|
||||||
|
// to actually perform that queued write once shutDown was set
|
||||||
|
// was exactly what left a graceful QUIT/LOGOUT's own reply
|
||||||
|
// stuck in the fifo forever, never reaching the client.
|
||||||
|
{
|
||||||
|
// sendData()'s return value was previously discarded and the
|
||||||
|
// fifo entry popped unconditionally after ONE call - correct
|
||||||
|
// only by accident, since a single write()/SSL_write() call is
|
||||||
|
// never guaranteed to accept an entire buffer. A response
|
||||||
|
// small enough to fit the kernel's socket send buffer in one
|
||||||
|
// shot (true for almost everything on this site, and always
|
||||||
|
// true testing over loopback, where that buffer is
|
||||||
|
// effectively unlimited) went out fine either way - but a
|
||||||
|
// large one (confirmed with a real 208KB response, mostly an
|
||||||
|
// embedded base64 font: fine over loopback, but only ~65KB of
|
||||||
|
// it ever reached a real remote client before the rest was
|
||||||
|
// silently dropped here) left the client waiting forever for
|
||||||
|
// bytes matching its own Content-Length that were never
|
||||||
|
// coming. Now: pop only once the FULL entry has gone out;
|
||||||
|
// otherwise trim off just what was actually sent and leave
|
||||||
|
// the remainder queued - resetSocket() (called at the end of
|
||||||
|
// every eventReceived(), see its own doc comment) keeps
|
||||||
|
// re-arming EPOLLWRNORM as long as the fifo isn't empty, so
|
||||||
|
// the next write-ready event retries this same entry
|
||||||
|
// automatically. A return <= 0 (EAGAIN or a transient error)
|
||||||
|
// sends nothing this round and is handled identically - just
|
||||||
|
// leave the entry queued for the next attempt.
|
||||||
|
int sent = sendData(fifo.front().c_str(), fifo.front().length());
|
||||||
|
if(sent > 0) {
|
||||||
|
consecutiveWriteStalls = 0;
|
||||||
|
waitingOnReadToWrite = false;
|
||||||
|
if((size_t)sent >= fifo.front().length())
|
||||||
fifo.pop();
|
fifo.pop();
|
||||||
|
else
|
||||||
|
fifo.front().erase(0, sent);
|
||||||
|
} else if(sendNeedsRead()) {
|
||||||
|
// Not a stall in the CPU-spinning sense consecutiveWriteStalls
|
||||||
|
// exists to catch - resetSocket() below simply won't re-arm
|
||||||
|
// EPOLLWRNORM while this is true, so there's nothing to busy-
|
||||||
|
// retry until a real EPOLLIN event (already always watched
|
||||||
|
// for) brings in whatever OpenSSL is actually waiting to read.
|
||||||
|
waitingOnReadToWrite = true;
|
||||||
|
} else if(++consecutiveWriteStalls > 50) {
|
||||||
|
// sendData() keeps failing for a reason that has nothing to
|
||||||
|
// do with the socket's own write-readiness (confirmed real
|
||||||
|
// case: TLS::sendData() returning SSL_ERROR_WANT_READ,
|
||||||
|
// which needs a READ to make progress, not another write
|
||||||
|
// attempt) - resetSocket() re-arms EPOLLWRNORM regardless,
|
||||||
|
// and an already-writable TCP socket makes it fire again
|
||||||
|
// immediately, so this cycle would otherwise spin forever
|
||||||
|
// doing real work at the CPU's own top speed. See
|
||||||
|
// consecutiveWriteStalls' own doc comment in Socket.h for
|
||||||
|
// the confirmed real damage (a 55GB, then 12.9GB debug log)
|
||||||
|
// this caused before being noticed.
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Socket " << getDescriptor() << ": " << consecutiveWriteStalls << " consecutive writes made zero progress - giving up and shutting down.";
|
||||||
|
// shutdown() alone only sets shutDown=true and expects the
|
||||||
|
// fifo to drain normally before the connection actually
|
||||||
|
// closes (see eventReceived()'s keepAlive: "!shutDown ||
|
||||||
|
// (fifo.size() > 0 && !readHangup)") - exactly backwards
|
||||||
|
// for THIS path, since the whole reason we're here is that
|
||||||
|
// the front of the fifo can never be sent. Leaving it
|
||||||
|
// queued meant keepAlive stayed true forever, resetSocket()
|
||||||
|
// kept re-arming EPOLLWRNORM because fifo.size() > 0, the
|
||||||
|
// very next write attempt hit this identical stall
|
||||||
|
// immediately, and shutdown() got called again - forever,
|
||||||
|
// at whatever rate the kernel could fire EPOLLWRNORM.
|
||||||
|
// Confirmed live: 2.4 million+ repeats of this exact log
|
||||||
|
// line for one socket in under 4 milliseconds, pegging a
|
||||||
|
// worker thread at 100% CPU indefinitely (a real game
|
||||||
|
// server, brought down by nothing more than an ordinary
|
||||||
|
// port-scanner connection). Clearing the undeliverable data
|
||||||
|
// here lets keepAlive correctly evaluate to just !shutDown
|
||||||
|
// (now false) on the very next cycle, so the connection
|
||||||
|
// actually tears down instead of spinning forever.
|
||||||
|
std::queue<std::string>().swap(fifo);
|
||||||
|
shutdown("stuck write retry loop - no progress after repeated attempts");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
outlock.unlock();
|
outlock.unlock();
|
||||||
}
|
}
|
||||||
@@ -154,7 +363,35 @@ namespace core
|
|||||||
outlock.lock();
|
outlock.lock();
|
||||||
fifo.emplace(data);
|
fifo.emplace(data);
|
||||||
outlock.unlock();
|
outlock.unlock();
|
||||||
|
// Was unconditional - re-arming here (resetSocket() -> EPOLL_CTL_MOD)
|
||||||
|
// while this socket's OWN eventReceived() call is still mid-flight
|
||||||
|
// on another thread (inHandler true - see eventReceived()'s own
|
||||||
|
// comment on exactly this race) makes the fd immediately eligible
|
||||||
|
// for a THIRD thread to pick up a fresh event and potentially
|
||||||
|
// delete this object (Thread::run() does exactly that on a false
|
||||||
|
// return) while the first thread is still touching it - a genuine
|
||||||
|
// use-after-free, matching a real heap-corruption crash confirmed
|
||||||
|
// live via dmesg/AddressSanitizer under concurrent load.
|
||||||
|
// eventReceived() already re-arms itself once it's actually done
|
||||||
|
// (checking the current fifo, which already includes whatever was
|
||||||
|
// just queued above); skip doing it a second, early time from here
|
||||||
|
// while that's still in progress - the data isn't lost, just
|
||||||
|
// picked up on that call's own re-arm instead of this one's.
|
||||||
|
//
|
||||||
|
// inHandler must be re-checked AFTER acquiring `lock`, not just
|
||||||
|
// before try_lock() - checking it first and then separately
|
||||||
|
// acquiring the lock leaves a real TOCTOU gap (this thread reads
|
||||||
|
// inHandler==false, eventReceived() flips it back and forth on
|
||||||
|
// another thread, both end up calling resetSocket()); a first
|
||||||
|
// attempt at this fix only checked before, and a genuine
|
||||||
|
// double-delete of the same session object still reproduced live
|
||||||
|
// under AddressSanitizer despite it. eventReceived() holds this
|
||||||
|
// exact same `lock` across its own inHandler-clear-then-reset
|
||||||
|
// sequence now (see its own comment), so re-checking inHandler
|
||||||
|
// only after try_lock() succeeds makes the two truly mutually
|
||||||
|
// exclusive.
|
||||||
if(lock.try_lock()) {
|
if(lock.try_lock()) {
|
||||||
|
if(!inHandler)
|
||||||
resetSocket();
|
resetSocket();
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
@@ -192,9 +429,17 @@ namespace core
|
|||||||
struct epoll_event event;
|
struct epoll_event event;
|
||||||
event.data.ptr = this;
|
event.data.ptr = this;
|
||||||
event.events = EPOLLIN | EPOLLRDHUP | EPOLLONESHOT | EPOLLET;
|
event.events = EPOLLIN | EPOLLRDHUP | EPOLLONESHOT | EPOLLET;
|
||||||
if(fifo.size() > 0)
|
if(fifo.size() > 0 && !waitingOnReadToWrite)
|
||||||
event.events |= EPOLLWRNORM;
|
event.events |= EPOLLWRNORM;
|
||||||
if(!shutDown)
|
// Was `if(!shutDown)` - refused to re-arm at all once shutting
|
||||||
|
// down, even with data still queued to send (e.g. a graceful
|
||||||
|
// QUIT/LOGOUT's own final reply - see eventReceived()'s own doc
|
||||||
|
// comment on keepAlive for the full chain this broke). Re-arming
|
||||||
|
// for just long enough to drain the fifo, when the peer is still
|
||||||
|
// there to receive it (!readHangup - draining to an already-gone
|
||||||
|
// peer is pointless), is what actually lets that reply go out
|
||||||
|
// before this socket closes.
|
||||||
|
if(!shutDown || (fifo.size() > 0 && !readHangup))
|
||||||
epoll_ctl(ePoll.getDescriptor(), EPOLL_CTL_MOD, getDescriptor(), &event);
|
epoll_ctl(ePoll.getDescriptor(), EPOLL_CTL_MOD, getDescriptor(), &event);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
#include "ZString.h"
|
#include "ZString.h"
|
||||||
#include <queue>
|
#include <queue>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
|
#include <atomic>
|
||||||
#include <sys/epoll.h>
|
#include <sys/epoll.h>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
@@ -123,6 +124,23 @@ namespace core {
|
|||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|
||||||
|
// Set by Timer's own constructor (see its own doc comment) - a
|
||||||
|
// Timer is always a Socket subobject privately/multiply inherited
|
||||||
|
// alongside a session's own real network Socket (e.g. ZephoraSession
|
||||||
|
// : TCPSession, Timer), never a standalone connection with its own
|
||||||
|
// independent lifetime. eventReceived()'s ordinary keepAlive
|
||||||
|
// contract - returning false means "delete me" (see Thread::run(),
|
||||||
|
// which then does exactly that on this object's own Socket* base) -
|
||||||
|
// is correct for a real connection but catastrophic here: deleting
|
||||||
|
// through a pointer to just the Timer subobject deletes the entire
|
||||||
|
// composite object at the WRONG size (Timer/Socket's own smaller
|
||||||
|
// size, not the true derived object's), a new-delete-type-mismatch
|
||||||
|
// confirmed live via AddressSanitizer under concurrent load. A
|
||||||
|
// Timer's own fd is already correctly torn down as part of its
|
||||||
|
// containing object's own destructor chain; it never needs (and
|
||||||
|
// must never trigger) independent deletion through this path.
|
||||||
|
bool preventSelfDelete = false;
|
||||||
|
|
||||||
EPoll &ePoll; // The EPoll control object.
|
EPoll &ePoll; // The EPoll control object.
|
||||||
|
|
||||||
void setBufferSize(int length);
|
void setBufferSize(int length);
|
||||||
@@ -173,13 +191,53 @@ namespace core {
|
|||||||
|
|
||||||
virtual void receiveData(coreutils::ZString &buffer);
|
virtual void receiveData(coreutils::ZString &buffer);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// sendData writes data to the socket descriptor. TLS layer overrides this to
|
||||||
|
/// write through SSL instead of a raw socket write.
|
||||||
|
///
|
||||||
|
/// @return The number of bytes written, or -1 on error.
|
||||||
|
///
|
||||||
|
|
||||||
|
virtual int sendData(const char *data, int length);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Overridden by TCPSocket to report whether the last sendData()
|
||||||
|
/// call failed specifically because the TLS layer needs a READ to
|
||||||
|
/// make progress (SSL_ERROR_WANT_READ), as opposed to any other
|
||||||
|
/// reason - see waitingOnReadToWrite's own doc comment for why
|
||||||
|
/// writeSocket()/resetSocket() need to know this. Always false for
|
||||||
|
/// a plain (non-TLS) socket, which has no such distinction.
|
||||||
|
///
|
||||||
|
|
||||||
|
virtual bool sendNeedsRead() { return false; }
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Synchronously write everything queued in the outbound fifo as
|
||||||
|
/// plain bytes (never through a TLS layer), waiting up to timeoutMs
|
||||||
|
/// for the socket to accept it. Returns false if it couldn't.
|
||||||
|
///
|
||||||
|
/// Only for protocol upgrades (STARTTLS): the server's "go ahead"
|
||||||
|
/// reply has to reach the client in clear text, and the switch to
|
||||||
|
/// TLS has to happen right after the last byte of it - not whenever
|
||||||
|
/// a later EPOLLWRNORM gets around to draining the fifo, by which
|
||||||
|
/// point the session would already be reading TLS. Must be called
|
||||||
|
/// from inside this socket's own eventReceived() (EPOLLONESHOT then
|
||||||
|
/// guarantees no other thread is writing to the fd).
|
||||||
|
///
|
||||||
|
|
||||||
|
bool flushPlain(int timeoutMs);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|
||||||
std::string text;
|
std::string text;
|
||||||
int descriptor = -1;
|
int descriptor = -1;
|
||||||
std::mutex outlock;
|
std::mutex outlock;
|
||||||
bool readHangup = false;
|
bool readHangup = false;
|
||||||
volatile bool inHandler = false;
|
// Was `volatile bool` - volatile gives no actual thread-safety
|
||||||
|
// (no atomicity, no cross-thread visibility guarantee), and this
|
||||||
|
// flag is now load-bearing (see Socket::write()'s own check of it)
|
||||||
|
// rather than just feeding a diagnostic log line.
|
||||||
|
std::atomic<bool> inHandler{false};
|
||||||
|
|
||||||
//-------------------------------------------------------------------------------------
|
//-------------------------------------------------------------------------------------
|
||||||
// the writeSocket is called when epoll has received a write request for a socket.
|
// the writeSocket is called when epoll has received a write request for a socket.
|
||||||
@@ -200,6 +258,36 @@ namespace core {
|
|||||||
|
|
||||||
std::queue<std::string> fifo;
|
std::queue<std::string> fifo;
|
||||||
|
|
||||||
|
// Counts consecutive writeSocket() calls that sent zero bytes for
|
||||||
|
// the SAME queued fifo entry (SSL_ERROR_WANT_READ from
|
||||||
|
// TLS::sendData() is the confirmed real case - see writeSocket()'s
|
||||||
|
// own doc comment). resetSocket() re-arms EPOLLWRNORM whenever the
|
||||||
|
// fifo is non-empty regardless of WHY the last send failed, and an
|
||||||
|
// already-writable TCP socket (the common case) makes EPOLLWRNORM
|
||||||
|
// fire again essentially immediately - so a send that keeps
|
||||||
|
// failing for a reason unrelated to socket writability (like SSL
|
||||||
|
// needing a read first) spins this cycle as fast as the CPU can
|
||||||
|
// run it, forever, with zero actual progress. Confirmed live: one
|
||||||
|
// stuck connection generated a 55GB, then a 12.9GB debug log
|
||||||
|
// before being noticed, at roughly 20 log lines per millisecond.
|
||||||
|
// Reset to 0 on any successful send (even a partial one - real
|
||||||
|
// progress happened); past the threshold, the connection is
|
||||||
|
// clearly never going to un-stick itself and gets shut down.
|
||||||
|
int consecutiveWriteStalls = 0;
|
||||||
|
|
||||||
|
// Set by writeSocket() when the last failed send specifically
|
||||||
|
// needed a read to proceed (sendNeedsRead() true) rather than
|
||||||
|
// being genuinely stalled on write-readiness. resetSocket() skips
|
||||||
|
// adding EPOLLWRNORM to the re-armed event mask while this is
|
||||||
|
// true - re-arming it anyway just spins the CPU as fast as it can
|
||||||
|
// loop, since an already-writable TCP socket keeps firing
|
||||||
|
// EPOLLWRNORM immediately while the actual blocker (more bytes
|
||||||
|
// from the peer) has nothing to do with write-readiness at all.
|
||||||
|
// Cleared on any EPOLLIN event (see eventReceived()) so the write
|
||||||
|
// gets a fresh attempt via that same event's own trailing
|
||||||
|
// resetSocket() call, once there's real reason to expect progress.
|
||||||
|
bool waitingOnReadToWrite = false;
|
||||||
|
|
||||||
void resetSocket();
|
void resetSocket();
|
||||||
|
|
||||||
std::mutex lock;
|
std::mutex lock;
|
||||||
|
|||||||
+39
-14
@@ -1,26 +1,39 @@
|
|||||||
#include "Subscription.h"
|
#include "Subscription.h"
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
|
#include "MString.h"
|
||||||
#include "TCPSession.h"
|
#include "TCPSession.h"
|
||||||
|
#include "TCPSocket.h"
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
Subscription::Subscription(std::string id, std::string mode)
|
Subscription::Subscription(coreutils::MString id, coreutils::MString mode)
|
||||||
: id(id), mode(mode), owner(NULL), handler(NULL) {}
|
: id(id), mode(mode), owner(""), handler(NULL) {}
|
||||||
|
|
||||||
Subscription::Subscription(std::string id, TCPSession &session, std::string mode)
|
Subscription::Subscription(coreutils::MString id, coreutils::MString owner, coreutils::MString mode)
|
||||||
: id(id), mode(mode), owner(&session), handler(NULL) {}
|
: id(id), mode(mode), owner(owner), handler(NULL) {}
|
||||||
|
|
||||||
Subscription::Subscription(std::string id, TCPSession &session, std::string mode, SubscriptionHandler *handler)
|
Subscription::Subscription(coreutils::MString id, coreutils::MString owner, coreutils::MString ownership, coreutils::MString mode, SubscriptionHandler *handler, coreutils::MString will, coreutils::MString timer)
|
||||||
: id(id), mode(mode), owner(&session), handler(handler) {
|
: id(id), ownership(ownership), mode(mode), owner(owner), handler(handler), will(will), timer(timer) {
|
||||||
// coreutils::Log(coreutils::LOG_DEBUG_3) << "Subscription '" << id << "' with handler '" << handler->name << "'";
|
coreutils::Log(coreutils::LOG_DEBUG_3) << owner;
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_3) << will;
|
||||||
|
subscriptionOwner(owner, will);
|
||||||
}
|
}
|
||||||
|
|
||||||
Subscription::~Subscription() {
|
Subscription::~Subscription() {
|
||||||
|
|
||||||
std::stringstream out;
|
std::stringstream out;
|
||||||
|
|
||||||
out << "cancel:" << id << std::endl;
|
out << "cancel:" << id << std::endl;
|
||||||
|
// subscribers holds plain observer pointers, not ownership (see
|
||||||
|
// TCPSession::pin()'s own doc comment) - a subscriber's session may
|
||||||
|
// have already started tearing down on another thread by the time
|
||||||
|
// this runs. pin() safely tells the two cases apart instead of
|
||||||
|
// blindly dereferencing a pointer that might already be mid-
|
||||||
|
// destruction or fully freed.
|
||||||
for (auto subscriber : subscribers) {
|
for (auto subscriber : subscribers) {
|
||||||
subscriber->write(out.str());
|
if (auto safe = subscriber->pin())
|
||||||
|
safe->write(out.str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,21 +42,27 @@ namespace core {
|
|||||||
handler->onSubscribe(session, this);
|
handler->onSubscribe(session, this);
|
||||||
else
|
else
|
||||||
onSubscribe(session);
|
onSubscribe(session);
|
||||||
|
|
||||||
subscribers.push_back(&session);
|
subscribers.push_back(&session);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
int Subscription::unsubscribe(TCPSession &session) {
|
int Subscription::unsubscribe(TCPSession &session) {
|
||||||
for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber) {
|
for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber)
|
||||||
if (*subscriber == &session) {
|
if (*subscriber == &session) {
|
||||||
subscribers.erase(subscriber++);
|
subscribers.erase(subscriber++);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool Subscription::subscriptionOwner(coreutils::MString alias, coreutils::MString ownerSelection) {
|
||||||
|
subscriptionOwners = alias;
|
||||||
|
selectionOfOwnerForSubscription = ownerSelection;
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Owner of Subscription: " << subscriptionOwners;
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Will of Subscription: " << selectionOfOwnerForSubscription;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
int Subscription::process(coreutils::ZString &request, std::stringstream &out, TCPSession &session) {
|
int Subscription::process(coreutils::ZString &request, std::stringstream &out, TCPSession &session) {
|
||||||
if (handler)
|
if (handler)
|
||||||
handler->process(request, out, session, this);
|
handler->process(request, out, session, this);
|
||||||
@@ -53,8 +72,14 @@ namespace core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int Subscription::event(std::stringstream &out) {
|
int Subscription::event(std::stringstream &out) {
|
||||||
|
// See ~Subscription()'s comment above - same pin()-before-use
|
||||||
|
// reasoning applies to every subscriber write here. This is the
|
||||||
|
// broadcast path for every *SUBSCRIBERS-mode topic (chat, item
|
||||||
|
// database updates, etc.) - the exact crash pin() closes here was
|
||||||
|
// confirmed live under concurrent load this session.
|
||||||
for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber)
|
for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber)
|
||||||
(*subscriber)->write(out.str());
|
if (auto safe = (*subscriber)->pin())
|
||||||
|
safe->write(out.str());
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,9 +98,9 @@ namespace core {
|
|||||||
void Subscription::sendToAll(std::stringstream &data, TCPSession &sender) {
|
void Subscription::sendToAll(std::stringstream &data, TCPSession &sender) {
|
||||||
for (auto session : subscribers)
|
for (auto session : subscribers)
|
||||||
if (session != &sender)
|
if (session != &sender)
|
||||||
session->write(data.str());
|
if (auto safe = session->pin())
|
||||||
|
safe->write(data.str());
|
||||||
data.str("");
|
data.str("");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
+16
-11
@@ -1,24 +1,24 @@
|
|||||||
#ifndef __Subscription_h__
|
#ifndef __Subscription_h__
|
||||||
#define __Subscription_h__
|
#define __Subscription_h__
|
||||||
|
|
||||||
#include "SubscriptionHandler.h"
|
#include "MString.h"
|
||||||
#include "SessionFilter.h"
|
#include "SessionFilter.h"
|
||||||
|
#include "SubscriptionHandler.h"
|
||||||
#include "ZString.h"
|
#include "ZString.h"
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <map>
|
#include <map>
|
||||||
|
|
||||||
namespace core
|
namespace core {
|
||||||
{
|
|
||||||
|
|
||||||
class TCPSession;
|
class TCPSession;
|
||||||
|
|
||||||
class Subscription {
|
class Subscription {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
Subscription(std::string id, std::string mode = "*AUTHOR");
|
Subscription(coreutils::MString id, coreutils::MString mode = "*AUTHOR");
|
||||||
Subscription(std::string id, TCPSession &session, std::string mode);
|
Subscription(coreutils::MString id, coreutils::MString owner, coreutils::MString mode);
|
||||||
Subscription(std::string id, TCPSession &session, std::string mode, SubscriptionHandler *handler);
|
Subscription(coreutils::MString id, coreutils::MString owner, coreutils::MString ownership, coreutils::MString mode, SubscriptionHandler *handler, coreutils::MString selection, coreutils::MString time);
|
||||||
virtual ~Subscription();
|
virtual ~Subscription();
|
||||||
|
|
||||||
int subscribe(TCPSession &session);
|
int subscribe(TCPSession &session);
|
||||||
@@ -29,7 +29,7 @@ namespace core
|
|||||||
virtual int onSubscribe(TCPSession &session);
|
virtual int onSubscribe(TCPSession &session);
|
||||||
|
|
||||||
int event(std::stringstream &out);
|
int event(std::stringstream &out);
|
||||||
|
bool subscriptionOwner(coreutils::MString owner, coreutils::MString selection);
|
||||||
bool ifSubscriber(TCPSession &session);
|
bool ifSubscriber(TCPSession &session);
|
||||||
|
|
||||||
bool subInvite(TCPSession &session);
|
bool subInvite(TCPSession &session);
|
||||||
@@ -37,13 +37,18 @@ namespace core
|
|||||||
void sendToAll(std::stringstream &data, TCPSession &sender);
|
void sendToAll(std::stringstream &data, TCPSession &sender);
|
||||||
void sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter);
|
void sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter);
|
||||||
|
|
||||||
std::string id;
|
coreutils::MString id;
|
||||||
std::string mode;
|
coreutils::MString mode;
|
||||||
TCPSession *owner;
|
coreutils::MString owner;
|
||||||
|
coreutils::MString subscriptionOwners;
|
||||||
|
coreutils::MString selectionOfOwnerForSubscription;
|
||||||
|
coreutils::MString will;
|
||||||
|
coreutils::MString ownership;
|
||||||
|
coreutils::MString timer;
|
||||||
SubscriptionHandler *handler;
|
SubscriptionHandler *handler;
|
||||||
|
|
||||||
std::vector<TCPSession *> subscribers;
|
std::vector<TCPSession *> subscribers;
|
||||||
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+154
-32
@@ -1,25 +1,37 @@
|
|||||||
#include "SubscriptionManager.h"
|
#include "SubscriptionManager.h"
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
#include "Subscription.h"
|
#include "Subscription.h"
|
||||||
|
#include "SubscriptionHandlerFactory.h"
|
||||||
#include "TCPServer.h"
|
#include "TCPServer.h"
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include "SubscriptionHandlerFactory.h"
|
#include <mutex>
|
||||||
|
|
||||||
namespace core {
|
namespace core
|
||||||
|
{
|
||||||
|
|
||||||
int SubscriptionManager::add(Subscription &subscription) {
|
int SubscriptionManager::add(Subscription &subscription)
|
||||||
|
{
|
||||||
lock.lock();
|
lock.lock();
|
||||||
subscriptions.insert(std::make_pair(subscription.id, &subscription));
|
subscriptions.insert(std::make_pair(subscription.id, &subscription));
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
int SubscriptionManager::removeSessionSubscriptions(TCPSession &session) {
|
bool SubscriptionManager::onClearSubscription(coreutils::MString temp, coreutils::MString key)
|
||||||
|
{
|
||||||
|
temp = "";
|
||||||
|
key = "";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int SubscriptionManager::removeSessionSubscriptions(TCPSession &session)
|
||||||
|
{
|
||||||
int countSubscribed = 0;
|
int countSubscribed = 0;
|
||||||
int countPublished = 0;
|
int countPublished = 0;
|
||||||
|
int count = 0;
|
||||||
|
|
||||||
lock.lock();
|
lock.lock();
|
||||||
std::string temp = "";
|
coreutils::MString temp = "";
|
||||||
for (auto [key, subscription] : subscriptions)
|
for (auto [key, subscription] : subscriptions)
|
||||||
{
|
{
|
||||||
if (temp != "")
|
if (temp != "")
|
||||||
@@ -28,10 +40,41 @@ namespace core {
|
|||||||
temp = "";
|
temp = "";
|
||||||
}
|
}
|
||||||
countSubscribed += subscription->unsubscribe(session);
|
countSubscribed += subscription->unsubscribe(session);
|
||||||
if (subscription->owner == &session)
|
if (subscription->subscriptionOwners == coreutils::MString(session.alias))
|
||||||
{
|
{
|
||||||
temp = key;
|
if (subscription->selectionOfOwnerForSubscription == "*DIE")
|
||||||
delete subscription;
|
{
|
||||||
|
onClearSubscription(temp, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
else if (subscription->will == "*NEXT")
|
||||||
|
{
|
||||||
|
if (subscription->subscribers.size() < 1)
|
||||||
|
{
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "There is not enough people to move to the next";
|
||||||
|
onClearSubscription(temp, key);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for (auto subscribed = subscription->subscribers.begin(); subscribed < subscription->subscribers.end(); subscribed++)
|
||||||
|
{
|
||||||
|
// pin() before reading .alias - a raw subscriber
|
||||||
|
// pointer here could already be mid-destruction or
|
||||||
|
// fully freed on another thread (see
|
||||||
|
// TCPSession::pin()'s own doc comment).
|
||||||
|
if (auto safe = (*subscribed)->pin())
|
||||||
|
if (safe->alias == session.alias)
|
||||||
|
{
|
||||||
|
subscription->subscribers.erase(subscribed++);
|
||||||
|
}
|
||||||
|
subscription->subscriptionOwner(session.alias, "*NEXT");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Subscription doesn't exist";
|
||||||
|
}
|
||||||
++countPublished;
|
++countPublished;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,58 +89,137 @@ namespace core {
|
|||||||
return countSubscribed;
|
return countSubscribed;
|
||||||
}
|
}
|
||||||
|
|
||||||
int SubscriptionManager::processCommand(coreutils::ZString &request, TCPSession &session) {
|
int SubscriptionManager::processCommand(coreutils::ZString &request, TCPSession &session)
|
||||||
if (request[0].equals("publish")) {
|
{
|
||||||
|
// Every branch below reads or mutates either the `subscriptions` map
|
||||||
|
// or some Subscription's own `subscribers` vector - both of which
|
||||||
|
// removeSessionSubscriptions() (called from ~TCPSession(), on
|
||||||
|
// whatever thread happens to be tearing down a *different*
|
||||||
|
// connection) also reads/mutates, under `lock`. This method used to
|
||||||
|
// take no lock at all, so a session disconnecting on one thread
|
||||||
|
// could run subscribers.erase() concurrently with subscribe()/
|
||||||
|
// event() iterating or push_back()-ing the same vector on another -
|
||||||
|
// an unsynchronized data race. Confirmed live: rapid connect/
|
||||||
|
// subscribe/disconnect cycles against ItemDataBase's "createItem"
|
||||||
|
// subscription produced a real segfault (gdb: Socket::write() ->
|
||||||
|
// resetSocket() dereferencing a corrupted EPoll reference) while
|
||||||
|
// broadcasting to *SUBSCRIBERS. `lock` is a plain, non-recursive
|
||||||
|
// std::mutex, and nothing reachable from this function re-enters
|
||||||
|
// processCommand()/add()/removeSessionSubscriptions() on the same
|
||||||
|
// thread, so holding it for the whole call is safe.
|
||||||
|
std::lock_guard<std::mutex> guard(lock);
|
||||||
|
|
||||||
|
if (request[0] == "publish")
|
||||||
|
{
|
||||||
SubscriptionHandler *handler = NULL;
|
SubscriptionHandler *handler = NULL;
|
||||||
if(request.getList().size() > 3) {
|
if (request.getList().size() > 3)
|
||||||
factory->getSubscriptionHandler(request[3].str());
|
{
|
||||||
|
handler = factory->getSubscriptionHandler(request[4].str());
|
||||||
}
|
}
|
||||||
newSubscription = new Subscription(request[1].str(), session, request[2].str(), handler);
|
if (request[2] == "*OWNER")
|
||||||
|
{
|
||||||
|
newSubscription = new Subscription(request[1].str(), session.alias, request[2].str(), request[3].str(), handler, request[5].str(), request[6].str());
|
||||||
subscriptions.insert(std::make_pair(request[1].str(), newSubscription));
|
subscriptions.insert(std::make_pair(request[1].str(), newSubscription));
|
||||||
newSubscription->owner = &session;
|
|
||||||
return 1;
|
return 1;
|
||||||
} else if (request[0].equals("catalog")) {
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
else if (request[0] == "catalog")
|
||||||
|
{
|
||||||
session.out << ":catalog:";
|
session.out << ":catalog:";
|
||||||
for (auto const &[key, subscription] : subscriptions) {
|
for (auto const &[key, subscription] : subscriptions)
|
||||||
|
{
|
||||||
session.out << subscription->id << ";";
|
session.out << subscription->id << ";";
|
||||||
}
|
}
|
||||||
session.out << std::endl;
|
session.out << std::endl;
|
||||||
return 1;
|
return 1;
|
||||||
} else if (request[0].equals("invite")) {
|
}
|
||||||
|
else if (request[0] == "invite")
|
||||||
|
{
|
||||||
std::stringstream out;
|
std::stringstream out;
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << request[2];
|
coreutils::Log(coreutils::LOG_DEBUG_1) << request[2];
|
||||||
std::string invitee = request[2].str();
|
std::string invitee = request[2].str();
|
||||||
TCPSession *tempSession = session.server->getSessionByAlias(&invitee);
|
// Was getSessionByAlias(&invitee) - getSessionByAlias(void*)
|
||||||
|
// compares by POINTER IDENTITY against each session's own
|
||||||
|
// alias, but &invitee is the address of a local variable that
|
||||||
|
// was just created in this function call - it can never equal
|
||||||
|
// any real session's alias, so this lookup was guaranteed to
|
||||||
|
// return NULL every time, and the result was dereferenced
|
||||||
|
// unconditionally below. Any client sending a bare "invite:"
|
||||||
|
// crashed the entire process, not just its own connection -
|
||||||
|
// same class of bug as the two GuildManager crashes fixed
|
||||||
|
// this session. This generic ServerCore layer has no
|
||||||
|
// name-based session lookup available (that only exists as a
|
||||||
|
// Zephora-specific addition on top of TCPServer), so a real
|
||||||
|
// fix for "find a session by the player name they typed"
|
||||||
|
// isn't possible at this layer without a larger change; this
|
||||||
|
// stops the crash without pretending to fix that gap.
|
||||||
|
// getSessionByAlias() now returns an already-pin()'d
|
||||||
|
// shared_ptr - see its own doc comment - so tempSession itself
|
||||||
|
// guarantees the session stays alive for this write() call
|
||||||
|
// below, no separate pin() needed.
|
||||||
|
auto tempSession = session.server->getSessionByAlias(&invitee);
|
||||||
|
if (!tempSession)
|
||||||
|
{
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "invite: could not find session for " << invitee;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
std::stringstream temp;
|
std::stringstream temp;
|
||||||
temp << "invite:" << request[1] << ":" << *(std::string *)session.alias;
|
temp << "invite:" << request[1] << ":" << invitee;
|
||||||
tempSession->write(temp.str());
|
tempSession->write(temp.str());
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto subscription = subscriptions[request[1].str()];
|
// Was subscriptions[request[1].str()] - map::operator[] default-
|
||||||
|
// constructs (here: NULL) and INSERTS an entry for any id that
|
||||||
|
// isn't already registered, and subscription->id below was then
|
||||||
|
// dereferenced completely unconditionally. Any subscribe:/
|
||||||
|
// unsubscribe:/event: naming an id nobody ever created (confirmed
|
||||||
|
// live: "subscribe:invite", sent by the client on every scene
|
||||||
|
// load, referencing an "invite" subscription that plain doesn't
|
||||||
|
// exist anywhere - real invites are Publish()'d under a
|
||||||
|
// per-group-guid id, not a shared "invite" channel) null-derefs
|
||||||
|
// and takes down the ENTIRE process, every connection included,
|
||||||
|
// not just the one that sent it. find() avoids polluting the map
|
||||||
|
// with the bogus NULL entry too.
|
||||||
|
auto it = subscriptions.find(request[1].str());
|
||||||
|
if (it == subscriptions.end())
|
||||||
|
{
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Unknown subscription id: " << request[1].str();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
auto subscription = it->second;
|
||||||
|
|
||||||
if (request[1].equals(subscription->id)) {
|
if (request[1].equals(subscription->id))
|
||||||
if (request[0].equals("unpublish")) {
|
{
|
||||||
|
if (request[0] == "unpublish")
|
||||||
|
{
|
||||||
subscriptions.erase(request[1].str());
|
subscriptions.erase(request[1].str());
|
||||||
} else if (request[0].equals("subscribe")) {
|
}
|
||||||
|
else if (request[0] == "subscribe")
|
||||||
|
{
|
||||||
subscription->subscribe(session);
|
subscription->subscribe(session);
|
||||||
return 1;
|
return 1;
|
||||||
} else if (request[0].equals("unsubscribe")) {
|
}
|
||||||
|
else if (request[0] == "unsubscribe")
|
||||||
|
{
|
||||||
subscription->unsubscribe(session);
|
subscription->unsubscribe(session);
|
||||||
return 1;
|
return 1;
|
||||||
} else if (request[0].equals("event")) {
|
}
|
||||||
|
else if (request[0] == "event")
|
||||||
|
{
|
||||||
std::stringstream out;
|
std::stringstream out;
|
||||||
subscription->process(request, out, session);
|
subscription->process(request, out, session);
|
||||||
if (subscription->mode == "*ANYONE") {
|
if (subscription->mode == "*ANYONE")
|
||||||
subscription->event(out);
|
{
|
||||||
return 1;
|
|
||||||
} else if (subscription->mode == "*SUBSCRIBERS") {
|
|
||||||
if (subscription->ifSubscriber(session)) {
|
|
||||||
subscription->event(out);
|
subscription->event(out);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
} else if (subscription->mode == "*AUTHOR") {
|
else if (subscription->mode == "*SUBSCRIBERS")
|
||||||
if (subscription->owner == &session) {
|
{
|
||||||
|
if (subscription->ifSubscriber(session))
|
||||||
|
{
|
||||||
subscription->event(out);
|
subscription->event(out);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-4
@@ -2,32 +2,38 @@
|
|||||||
#define __SubscriptionManager_h__
|
#define __SubscriptionManager_h__
|
||||||
|
|
||||||
#include "Command.h"
|
#include "Command.h"
|
||||||
|
#include "MString.h"
|
||||||
|
#include "SessionFilter.h"
|
||||||
#include "Subscription.h"
|
#include "Subscription.h"
|
||||||
#include "SubscriptionHandler.h"
|
#include "SubscriptionHandler.h"
|
||||||
#include "TCPSession.h"
|
#include "TCPSession.h"
|
||||||
#include "ZString.h"
|
#include "ZString.h"
|
||||||
#include <string>
|
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
|
//*AUTHOR -> Dies when player disconnects
|
||||||
|
//*ANYONE -> Does not die when player disconnects
|
||||||
|
//*SUBSCRIPTION -> Does not die when player disconnects
|
||||||
|
//*OWNER -> Does die and transfers Ownership before he does
|
||||||
|
|
||||||
class SubscriptionHandlerFactory;
|
class SubscriptionHandlerFactory;
|
||||||
|
|
||||||
class SubscriptionManager : public Command {
|
class SubscriptionManager : public Command {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
int add(Subscription &subscription);
|
int add(Subscription &subscription);
|
||||||
int removeSessionSubscriptions(TCPSession &session);
|
int removeSessionSubscriptions(TCPSession &session);
|
||||||
int processCommand(coreutils::ZString &request, TCPSession &session) override;
|
int processCommand(coreutils::ZString &request, TCPSession &session) override;
|
||||||
|
bool onClearSubscription(coreutils::MString temp, coreutils::MString key);
|
||||||
SubscriptionHandlerFactory *factory = NULL;
|
SubscriptionHandlerFactory *factory = NULL;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
Subscription *subscription;
|
Subscription *subscription;
|
||||||
std::map<std::string, Subscription *> subscriptions;
|
std::map<coreutils::MString, Subscription *> subscriptions;
|
||||||
Subscription *newSubscription;
|
Subscription *newSubscription;
|
||||||
std::mutex lock;
|
std::mutex lock;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+220
-48
@@ -3,23 +3,69 @@
|
|||||||
#include "Exception.h"
|
#include "Exception.h"
|
||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
#include "TCPSession.h"
|
#include "TCPSession.h"
|
||||||
|
#include <chrono>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
TCPServer::TCPServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo, std::string delimiter, int depth, std::string text)
|
TCPServer::TCPServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo, std::string delimiter, int depth, std::string text)
|
||||||
: TCPSocket(ePoll, tlsInfo, text), commands(delimiter, depth) {
|
: TCPSocket(ePoll, tlsInfo, text), commands(delimiter, depth) {
|
||||||
|
|
||||||
setDescriptor(socket(AF_INET, SOCK_STREAM, 0));
|
// Wires the subscription (pub/sub) command set into this server's
|
||||||
|
// own command dispatch - previously missing entirely here (the
|
||||||
|
// subscriptions member existed but nothing ever routed these verbs
|
||||||
|
// to it), so publish/subscribe/catalog/etc were unreachable on any
|
||||||
|
// TCPServer built after the TLS work, even though SubscriptionManager
|
||||||
|
// itself was still fully implemented.
|
||||||
|
commands.add(subscriptions, "publish");
|
||||||
|
commands.add(subscriptions, "unpublish");
|
||||||
|
commands.add(subscriptions, "subscribe");
|
||||||
|
commands.add(subscriptions, "unsubscribe");
|
||||||
|
commands.add(subscriptions, "catalog");
|
||||||
|
commands.add(subscriptions, "event");
|
||||||
|
commands.add(subscriptions, "invite");
|
||||||
|
|
||||||
|
// Bind, listen and register as a known listening socket BEFORE
|
||||||
|
// setDescriptor() adds the fd to epoll. setDescriptor() arms it
|
||||||
|
// immediately (EPOLLONESHOT), and a brand-new socket that isn't
|
||||||
|
// listening yet reports EPOLLHUP right away. That event used to race
|
||||||
|
// the rest of this constructor: whenever an epoll worker thread
|
||||||
|
// picked it up before the listeningSockets().insert() below,
|
||||||
|
// Thread::run() didn't recognize the pointer and skipped it without
|
||||||
|
// re-arming, so the one-shot registration was spent and the server
|
||||||
|
// never saw another connection - up, bound and listening, but
|
||||||
|
// silently accepting nothing for the life of the process. Reproduced
|
||||||
|
// on an unmodified build: roughly 3 startups in 8 dead on arrival.
|
||||||
|
int fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||||
int yes = 1;
|
int yes = 1;
|
||||||
setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
|
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
|
||||||
|
|
||||||
if (bind(getDescriptor(), address.getPointer(), address.addressLength) < 0)
|
if (bind(fd, address.getPointer(), address.addressLength) < 0) {
|
||||||
throw coreutils::Exception("Error on bind to socket: " + std::to_string(errno));
|
int error = errno;
|
||||||
|
close(fd);
|
||||||
|
throw coreutils::Exception("Error on bind to socket: " + std::to_string(error));
|
||||||
|
}
|
||||||
|
|
||||||
if (listen(getDescriptor(), 20) < 0)
|
// Was 20 - small enough that a burst of connection attempts
|
||||||
|
// arriving faster than this process calls accept() (a port scan,
|
||||||
|
// or just several real clients reconnecting around the same
|
||||||
|
// moment) can fill the kernel's own backlog before the
|
||||||
|
// application layer gets a chance to drain it, silently dropping
|
||||||
|
// the overflow SYNs rather than queuing them. 128 gives real
|
||||||
|
// bursts meaningfully more headroom; still bounded, not unlimited.
|
||||||
|
if (listen(fd, 128) < 0) {
|
||||||
|
close(fd);
|
||||||
throw coreutils::Exception("Error on listen to socket");
|
throw coreutils::Exception("Error on listen to socket");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
|
||||||
|
listeningSockets().insert(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
setDescriptor(fd);
|
||||||
|
}
|
||||||
|
|
||||||
TCPServer::~TCPServer() {
|
TCPServer::~TCPServer() {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "Closing server socket " << getDescriptor() << ".";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "Closing server socket " << getDescriptor() << ".";
|
||||||
close(getDescriptor());
|
close(getDescriptor());
|
||||||
@@ -27,53 +73,158 @@ namespace core {
|
|||||||
|
|
||||||
void TCPServer::connectionRequest() {
|
void TCPServer::connectionRequest() {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "Connection request is being received on socket " << getDescriptor() << ".";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "Connection request is being received on socket " << getDescriptor() << ".";
|
||||||
|
// Outside the lock.lock()/unlock() below, not nested inside it -
|
||||||
|
// sweepStaleSessions() takes the same `lock` itself (see its own
|
||||||
|
// comment), and this mutex isn't recursive.
|
||||||
|
sweepStaleSessions();
|
||||||
lock.lock();
|
lock.lock();
|
||||||
TCPSession *session = accept();
|
// accept() now adds the session to `sessions` and the live registry
|
||||||
if (session)
|
// itself, before its fd is armed - see the comment there.
|
||||||
sessions.push_back(session);
|
// accept() registers the session and, for an implicit-TLS listener,
|
||||||
if(true) {
|
// starts its TLS handshake (on the session, not on `this`) before
|
||||||
registerSocket(session->getDescriptor());
|
// arming the fd - see its own comment.
|
||||||
acceptSocket();
|
accept();
|
||||||
}
|
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void TCPServer::sweepStaleSessions() {
|
||||||
|
// 30 seconds is generous for completing a TCP handshake plus a
|
||||||
|
// TLS handshake plus sending a first real message over any real
|
||||||
|
// network - deliberately not aimed at catching anything borderline,
|
||||||
|
// only connections that never progressed at all.
|
||||||
|
static const std::chrono::seconds GRACE_PERIOD(30);
|
||||||
|
auto now = std::chrono::steady_clock::now();
|
||||||
|
|
||||||
|
// Collect under `lock` (sessions is mutated elsewhere under the
|
||||||
|
// same mutex - see its own doc comment), then drop the lock before
|
||||||
|
// actually removing anything. removeFromSessionList() takes `lock`
|
||||||
|
// itself for each call; calling it while still holding the guard
|
||||||
|
// below would deadlock on this non-recursive mutex.
|
||||||
|
std::vector<TCPSession *> stale;
|
||||||
|
{
|
||||||
|
std::lock_guard guard(lock);
|
||||||
|
for (auto &s : sessions)
|
||||||
|
if (!s->hasReceivedData && (now - s->acceptedAt) > GRACE_PERIOD)
|
||||||
|
stale.push_back(s.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
for (auto *s : stale) {
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "Reaping stale, never-active session " << s->getDescriptor() << ".";
|
||||||
|
removeFromSessionList(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void TCPServer::enableStartTLS(TLSInfo &tlsInfo) {
|
||||||
|
startTLSContext = TLS::buildContext(&tlsInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
void TCPServer::receiveData(coreutils::ZString &buffer) {
|
||||||
|
// See this override's own doc comment in TCPServer.h - the
|
||||||
|
// listening socket always uses the plain read()/ENOTCONN detection
|
||||||
|
// path, never TLS::receiveData(), regardless of whether this server
|
||||||
|
// is TLS-configured.
|
||||||
|
Socket::receiveData(buffer);
|
||||||
|
}
|
||||||
|
|
||||||
TCPSession * TCPServer::accept() {
|
TCPSession * TCPServer::accept() {
|
||||||
|
|
||||||
try {
|
// Called with `lock` held (connectionRequest()).
|
||||||
|
//
|
||||||
|
// The session must be owned by `sessions` and registered with
|
||||||
|
// TCPSession::registerLive() BEFORE setDescriptor() adds its fd to
|
||||||
|
// epoll. setDescriptor() arms the fd and runs onConnected(), which
|
||||||
|
// queues the protocol greeting ("220 ..." for SMTP) and re-arms for
|
||||||
|
// EPOLLWRNORM; another epoll worker can pick that event up at once.
|
||||||
|
// Registration used to happen afterwards, back in
|
||||||
|
// connectionRequest(), so whenever a worker got there first
|
||||||
|
// Thread::run()'s TCPSession::tryGet() didn't know the pointer and
|
||||||
|
// dropped the event without re-arming (EPOLLONESHOT): the client
|
||||||
|
// was connected but never received a single byte. Reproduced on an
|
||||||
|
// unmodified build with 40 simultaneous plain-text SMTP
|
||||||
|
// connections - 4 to 6 per burst stuck before the greeting. For a
|
||||||
|
// mail server that is lost (well, deferred) inbound mail.
|
||||||
|
//
|
||||||
|
// Accepting into a local address first also means a failed
|
||||||
|
// ::accept() (EAGAIN on a spurious wakeup, EMFILE) no longer creates
|
||||||
|
// - and then leaks - a session object at all.
|
||||||
|
|
||||||
TCPSession *session = getSocketAccept(ePoll);
|
struct sockaddr_in address;
|
||||||
session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength));
|
socklen_t addressLength = sizeof(address);
|
||||||
// if(blackList && blackList->contains(session->ipAddress.getClientAddress())) {
|
int fd = ::accept(getDescriptor(), (struct sockaddr *)&address, &addressLength);
|
||||||
// session->shutdown();
|
if (fd < 0) {
|
||||||
// Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is blacklisted and was denied a connection.";
|
if (errno == EMFILE || errno == ENFILE)
|
||||||
// return NULL;
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Too many files open. Refusing connection.";
|
||||||
// }
|
|
||||||
// if(whiteList && !whiteList->contains(session->ipAddress.getClientAddress())) {
|
|
||||||
// session->shutdown();
|
|
||||||
// Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is not authorized and was denied a connection.";
|
|
||||||
// return NULL;
|
|
||||||
// }
|
|
||||||
return session;
|
|
||||||
}
|
|
||||||
catch (coreutils::Exception e) {
|
|
||||||
coreutils::Log(coreutils::LOG_EXCEPT) << "Major error on session initialization. Error is '" << e.text << "'.";
|
|
||||||
}
|
|
||||||
catch (...) {
|
|
||||||
coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization.";
|
|
||||||
}
|
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TCPSession *session = NULL;
|
||||||
|
try {
|
||||||
|
session = getSocketAccept(ePoll);
|
||||||
|
}
|
||||||
|
catch (...) {
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Error creating session object; connection refused.";
|
||||||
|
close(fd);
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
session->ipAddress.addr = address;
|
||||||
|
session->ipAddress.addressLength = addressLength;
|
||||||
|
|
||||||
|
auto sessionPtr = std::shared_ptr<TCPSession>(session);
|
||||||
|
sessions.push_back(sessionPtr);
|
||||||
|
TCPSession::registerLive(session, sessionPtr);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Implicit TLS (this listener was built with a TLSInfo): create
|
||||||
|
// the session's SSL object and start SSL_accept() before the fd
|
||||||
|
// goes into epoll, for the same reason registration comes first -
|
||||||
|
// otherwise a worker can pick up the greeting onConnected() queues
|
||||||
|
// and reach TLS::sendData() before there's an SSL object to send
|
||||||
|
// it through.
|
||||||
|
if (tlsInfo)
|
||||||
|
session->performTLSHandshake(fd);
|
||||||
|
session->setDescriptor(fd);
|
||||||
|
}
|
||||||
|
catch (coreutils::Exception e) {
|
||||||
|
// Already owned and registered, so it is cleaned up through the
|
||||||
|
// normal shutdown path rather than deleted here (deleting would
|
||||||
|
// re-enter removeFromSessionList() while `lock` is held).
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Major error on session initialization. Error is '" << e.text << "'.";
|
||||||
|
session->shutdown("session initialization failed");
|
||||||
|
}
|
||||||
|
catch (...) {
|
||||||
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization.";
|
||||||
|
session->shutdown("session initialization failed");
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
void TCPServer::removeFromSessionList(TCPSession *session) {
|
void TCPServer::removeFromSessionList(TCPSession *session) {
|
||||||
std::vector<TCPSession *>::iterator cursor;
|
|
||||||
lock.lock();
|
lock.lock();
|
||||||
for(cursor = sessions.begin(); cursor < sessions.end(); ++cursor)
|
for (auto cursor = sessions.begin(); cursor < sessions.end(); ++cursor)
|
||||||
if(*cursor == session) {
|
if (cursor->get() == session)
|
||||||
|
{
|
||||||
|
// Drops the one strong-owning reference. If nothing else is
|
||||||
|
// currently pin()'d to this session, the object is actually
|
||||||
|
// destroyed right here, synchronously - same timing as
|
||||||
|
// before this change for the common (no-contention) case.
|
||||||
|
// If some other thread IS mid-call via its own pin()'d
|
||||||
|
// shared_ptr right now, destruction is safely deferred until
|
||||||
|
// that reference is released too, instead of the crash
|
||||||
|
// (double-delete / use-after-free, confirmed live via
|
||||||
|
// AddressSanitizer under concurrent load) that raw-pointer
|
||||||
|
// ownership produced here before.
|
||||||
sessions.erase(cursor);
|
sessions.erase(cursor);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
|
// Removes this pointer from the tryGet() lookup registry too (see
|
||||||
|
// TCPSession::tryGet()'s own comment). Safe to do after releasing
|
||||||
|
// `lock` and regardless of whether the erase() above was actually
|
||||||
|
// the last reference: tryGet() correctly reports "gone" the moment
|
||||||
|
// a session's real refcount hits zero, via the weak_ptr's own
|
||||||
|
// expiration - this call is just tidying the registry map itself,
|
||||||
|
// not something later correctness depends on.
|
||||||
|
TCPSession::unregisterLive(session);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPServer::sessionErrorHandler(std::string errorString, std::stringstream &out) {
|
void TCPServer::sessionErrorHandler(std::string errorString, std::stringstream &out) {
|
||||||
@@ -84,13 +235,30 @@ namespace core {
|
|||||||
return new TCPSession(ePoll, this);
|
return new TCPSession(ePoll, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPServer::output(std::stringstream &out) {
|
void TCPServer::output(std::stringstream &out)
|
||||||
|
{
|
||||||
out << "Use the 'help' command to list the commands for this server." << std::endl;
|
out << "Use the 'help' command to list the commands for this server." << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
int TCPServer::processCommand(coreutils::ZString &request, TCPSession &session) {
|
int TCPServer::processCommand(coreutils::ZString &request, TCPSession &session)
|
||||||
|
{
|
||||||
|
// Was unguarded, like every other method below - `sessions` is
|
||||||
|
// mutated under `lock` by connectionRequest()/removeFromSessionList()
|
||||||
|
// (a session accepting or disconnecting on another thread), but
|
||||||
|
// every READ of it here had no lock at all. Confirmed live via
|
||||||
|
// dmesg: a real segfault at a stable, deterministic instruction
|
||||||
|
// offset (same crash signature as the Subscription::subscribers
|
||||||
|
// race fixed earlier this session, in SubscriptionManager.cpp) -
|
||||||
|
// Socket::write() -> resetSocket() dereferencing a null EPoll
|
||||||
|
// reference, consistent with iterating `sessions` while another
|
||||||
|
// thread concurrently erased and freed one of its entries.
|
||||||
|
// sendToAll() in particular is what most real gameplay broadcasts
|
||||||
|
// (combat, position, chat) go through, so this is very likely the
|
||||||
|
// actual dominant cause of that crash, not just the ItemDataBase
|
||||||
|
// subscriber list this session's earlier fix addressed.
|
||||||
|
std::lock_guard guard(lock);
|
||||||
int sequence = 0;
|
int sequence = 0;
|
||||||
for (auto *sessionx : sessions)
|
for (auto &sessionx : sessions)
|
||||||
{
|
{
|
||||||
session.out << "|" << ++sequence;
|
session.out << "|" << ++sequence;
|
||||||
sessionx->output(session.out);
|
sessionx->output(session.out);
|
||||||
@@ -100,32 +268,36 @@ namespace core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TCPServer::sendToAll(std::stringstream &data) {
|
void TCPServer::sendToAll(std::stringstream &data) {
|
||||||
for (auto session : sessions)
|
std::lock_guard guard(lock);
|
||||||
|
for (auto &session : sessions)
|
||||||
session->write(data.str());
|
session->write(data.str());
|
||||||
data.str("");
|
data.str("");
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender) {
|
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender) {
|
||||||
for (auto session : sessions)
|
std::lock_guard guard(lock);
|
||||||
if (session != &sender)
|
for (auto &session : sessions)
|
||||||
|
if (session.get() != &sender)
|
||||||
session->write(data.str());
|
session->write(data.str());
|
||||||
data.str("");
|
data.str("");
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter) {
|
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter) {
|
||||||
for (auto session : sessions)
|
std::lock_guard guard(lock);
|
||||||
|
for (auto &session : sessions)
|
||||||
if (filter.test(*session))
|
if (filter.test(*session))
|
||||||
if (session != &sender)
|
if (session.get() != &sender)
|
||||||
session->write(data.str());
|
session->write(data.str());
|
||||||
data.str("");
|
data.str("");
|
||||||
}
|
}
|
||||||
|
|
||||||
TCPSession *TCPServer::getSessionByAlias(void *alias) {
|
std::shared_ptr<TCPSession> TCPServer::getSessionByAlias(void *alias) {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << alias;
|
coreutils::Log(coreutils::LOG_DEBUG_1) << alias;
|
||||||
for (auto session : sessions)
|
std::lock_guard guard(lock);
|
||||||
if (session->compareAlias(alias))
|
for (auto &session : sessions)
|
||||||
|
if (session->alias == alias)
|
||||||
return session;
|
return session;
|
||||||
return NULL;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+152
-4
@@ -9,6 +9,8 @@
|
|||||||
# include "TCPSession.h"
|
# include "TCPSession.h"
|
||||||
# include "TCPSocket.h"
|
# include "TCPSocket.h"
|
||||||
# include "TLSInfo.h"
|
# include "TLSInfo.h"
|
||||||
|
# include <mutex>
|
||||||
|
# include <set>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
@@ -60,8 +62,20 @@ namespace core {
|
|||||||
///
|
///
|
||||||
/// The list of sessions that are currently open and being maintained by this object.
|
/// The list of sessions that are currently open and being maintained by this object.
|
||||||
///
|
///
|
||||||
|
/// This is the one real, strong-owning reference per live session -
|
||||||
|
/// see TCPSession::pin()'s own doc comment for the full reasoning.
|
||||||
|
/// Every other place that keeps a TCPSession* around (Subscription::
|
||||||
|
/// subscribers, a Zephora-specific sessionsByPlayerName map, etc.)
|
||||||
|
/// is just a non-owning observer and must pin() before touching the
|
||||||
|
/// object. A session stops existing, for real, the instant its
|
||||||
|
/// entry here is erased and every other outstanding pin() (if any
|
||||||
|
/// thread happened to be mid-call) has released its own reference -
|
||||||
|
/// removeFromSessionList() is the only place that ever removes an
|
||||||
|
/// entry, and Thread::run() calls it instead of ever calling
|
||||||
|
/// `delete` on a TCPSession directly (see its own comment).
|
||||||
|
///
|
||||||
|
|
||||||
std::vector<TCPSession *> sessions;
|
std::vector<std::shared_ptr<TCPSession>> sessions;
|
||||||
|
|
||||||
///
|
///
|
||||||
/// The commands object is a CommandList and is used to store Command objects to be
|
/// The commands object is a CommandList and is used to store Command objects to be
|
||||||
@@ -119,10 +133,36 @@ namespace core {
|
|||||||
|
|
||||||
///
|
///
|
||||||
/// Use the getSessionByAlias to retrieve a session pointer by the value
|
/// Use the getSessionByAlias to retrieve a session pointer by the value
|
||||||
/// of the alias pointer.
|
/// of the alias pointer. Returns an already-pin()'d shared_ptr (null
|
||||||
|
/// if not found) rather than a raw pointer, so callers can't
|
||||||
|
/// accidentally hold onto - or use - a reference that isn't actually
|
||||||
|
/// keeping the session alive.
|
||||||
///
|
///
|
||||||
|
|
||||||
TCPSession *getSessionByAlias(void *alias);
|
std::shared_ptr<TCPSession> getSessionByAlias(void *alias);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Offer TLS as an in-session upgrade (STARTTLS) on an otherwise
|
||||||
|
/// plain-text listener, as SMTP on port 25 requires. Unlike passing
|
||||||
|
/// tlsInfo to the constructor (implicit TLS - the handshake starts
|
||||||
|
/// the moment a connection is accepted, as on ports 465/993/995),
|
||||||
|
/// sessions here start in clear text and switch only when a command
|
||||||
|
/// handler calls TCPSession::startTLS(server->startTLSContext).
|
||||||
|
///
|
||||||
|
/// Throws coreutils::Exception if the certificate or key can't be
|
||||||
|
/// loaded; startTLSContext stays NULL in that case, so a caller that
|
||||||
|
/// catches it can keep serving without STARTTLS.
|
||||||
|
///
|
||||||
|
|
||||||
|
void enableStartTLS(TLSInfo &tlsInfo);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// The context sessions switch to on STARTTLS. NULL until
|
||||||
|
/// enableStartTLS() succeeds - protocol code should only advertise
|
||||||
|
/// STARTTLS when this is set.
|
||||||
|
///
|
||||||
|
|
||||||
|
SSL_CTX *startTLSContext = NULL;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
///
|
///
|
||||||
@@ -132,6 +172,49 @@ namespace core {
|
|||||||
|
|
||||||
void connectionRequest() override;
|
void connectionRequest() override;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Drops any session that completed a TCP accept() but has never
|
||||||
|
/// had a single byte of real data pass through onDataReceived() -
|
||||||
|
/// covers both a TLS handshake that never finishes and a plain
|
||||||
|
/// connection that never sends anything - once it's been open
|
||||||
|
/// longer than a short grace period. Nothing else in this class
|
||||||
|
/// ever revisits an already-accepted session once it stops
|
||||||
|
/// generating epoll events (Thread::run()'s dispatch loop only
|
||||||
|
/// acts on a session when a real event for it arrives), so a
|
||||||
|
/// connection that completes the handshake and then goes
|
||||||
|
/// permanently silent - exactly what a port scan/prober looks
|
||||||
|
/// like from here, as opposed to a normal scan that just connects
|
||||||
|
/// and immediately closes again, which the existing read-hangup
|
||||||
|
/// path already cleans up fine - would otherwise sit in `sessions`
|
||||||
|
/// forever, one TCPSession + one fd each. Called from
|
||||||
|
/// connectionRequest() (see its own call site) so the sweep keeps
|
||||||
|
/// pace with however fast new connections are actually arriving,
|
||||||
|
/// without needing a dedicated timer/thread of its own; a
|
||||||
|
/// legitimate, already-talking client is never at risk, since
|
||||||
|
/// hasReceivedData latches true permanently on its first real byte
|
||||||
|
/// and is never consulted again after that.
|
||||||
|
///
|
||||||
|
|
||||||
|
void sweepStaleSessions();
|
||||||
|
|
||||||
|
///
|
||||||
|
/// The listening socket itself is never a TLS peer - accepting a
|
||||||
|
/// connection on it surfaces as a plain read() failing with ENOTCONN
|
||||||
|
/// (see Socket::receiveData(), which is what actually detects and
|
||||||
|
/// dispatches to connectionRequest() above). When this server is
|
||||||
|
/// TLS-configured, TCPSocket::receiveData()'s normal ctx-based
|
||||||
|
/// dispatch would instead route that same event through
|
||||||
|
/// TLS::receiveData()/SSL_read() against a listening fd that was
|
||||||
|
/// never SSL_accept()-ed at all (real per-connection sessions are
|
||||||
|
/// the only sockets TLS applies to) - confirmed via a real crash
|
||||||
|
/// (SIGSEGV inside SSL_read, called with `this` pointing at this
|
||||||
|
/// server object, not a session). Always using the plain path here,
|
||||||
|
/// regardless of whether tlsInfo is set, keeps connection-detection
|
||||||
|
/// working the same way with or without TLS configured.
|
||||||
|
///
|
||||||
|
|
||||||
|
void receiveData(coreutils::ZString &buffer) override;
|
||||||
|
|
||||||
///
|
///
|
||||||
/// This method is called when the Command associated with this object is requested
|
/// This method is called when the Command associated with this object is requested
|
||||||
/// because a user has typed in the associated command name on a command entry line.
|
/// because a user has typed in the associated command name on a command entry line.
|
||||||
@@ -141,9 +224,74 @@ namespace core {
|
|||||||
|
|
||||||
int processCommand(coreutils::ZString &request, TCPSession &session) override;
|
int processCommand(coreutils::ZString &request, TCPSession &session) override;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
// Was private - ConsoleServer::logSend() (and any other subclass
|
||||||
|
// that iterates `sessions`, itself public further up) needs to be
|
||||||
|
// able to synchronize against the exact same mutex
|
||||||
|
// connectionRequest()/removeFromSessionList() already use, rather
|
||||||
|
// than reading a shared_ptr vector with no locking of its own.
|
||||||
|
//
|
||||||
|
// Was a plain std::mutex - self-deadlocked the accepting thread on
|
||||||
|
// EVERY single connection to ConsoleServer (confirmed live via a
|
||||||
|
// gdb thread dump caught mid-stall): connectionRequest() locks
|
||||||
|
// `lock`, then calls accept(), which constructs the new session -
|
||||||
|
// whose base Socket constructor logs its own creation via
|
||||||
|
// coreutils::Log, whose destructor calls back into
|
||||||
|
// ConsoleServer::logSend() (exactly the synchronization this was
|
||||||
|
// designed for, per the comment above) - which tries to lock this
|
||||||
|
// SAME mutex again, on the SAME thread that already holds it.
|
||||||
|
// std::mutex is not reentrant, so that thread deadlocked
|
||||||
|
// permanently, every time, without ever completing the accept -
|
||||||
|
// this is why the admin console never responded to anything.
|
||||||
|
// Since all of a server's listening sockets share one fixed-size
|
||||||
|
// EPoll worker-thread pool, each such deadlocked thread is gone
|
||||||
|
// for good - enough accumulated connection attempts (even
|
||||||
|
// sporadic ones, e.g. internet-wide port scanners probing every
|
||||||
|
// port) eventually exhausts every worker thread, at which point
|
||||||
|
// the WHOLE server - every listening socket, not just the
|
||||||
|
// console - stops accepting anything new. This is the actual
|
||||||
|
// root cause of BARANTMail's own multi-day-recurring "all ports
|
||||||
|
// simultaneously stop accepting connections" incidents - nothing
|
||||||
|
// to do with DNS/SPF lookup timing, which was a real, separate,
|
||||||
|
// worthwhile fix but not this bug. recursive_mutex lets the same
|
||||||
|
// thread re-enter safely (identical behavior to std::mutex for
|
||||||
|
// every other thread) without changing the locking design at all.
|
||||||
|
std::recursive_mutex lock;
|
||||||
|
|
||||||
|
public:
|
||||||
|
///
|
||||||
|
/// A listening TCPServer/ConsoleServer (as opposed to an accepted
|
||||||
|
/// TCPSession) is constructed once, directly by main(), and lives
|
||||||
|
/// for the whole process - never through the shared_ptr-based
|
||||||
|
/// ownership TCPSession::registerLive()/pin() provide (see their
|
||||||
|
/// own comments), since nothing ever calls `new` on one of these.
|
||||||
|
/// Thread::run()'s epoll dispatch still needs a SAFE way to tell
|
||||||
|
/// "this raw pointer is one of those known-immortal listening
|
||||||
|
/// sockets, fine to call methods on directly" apart from "this is
|
||||||
|
/// an unrecognized/stale pointer that must not be touched at all"
|
||||||
|
/// (see TCPSession::tryGet()'s own comment on why dynamic_cast
|
||||||
|
/// can't make that distinction safely). Registering `this` once,
|
||||||
|
/// in the constructor, into this tiny set is that signal - it's
|
||||||
|
/// checked by address only, never dereferenced for the check
|
||||||
|
/// itself.
|
||||||
|
///
|
||||||
|
|
||||||
|
static bool isKnownListeningSocket(void *ptr) {
|
||||||
|
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
|
||||||
|
return listeningSockets().count(ptr) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
TCPSession *accept();
|
TCPSession *accept();
|
||||||
std::mutex lock;
|
|
||||||
|
static std::mutex &listeningSocketsMutex() {
|
||||||
|
static std::mutex m;
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
static std::set<void *> &listeningSockets() {
|
||||||
|
static std::set<void *> s;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+54
-7
@@ -7,17 +7,32 @@
|
|||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
TCPSession::TCPSession(EPoll &ePoll, std::string text) : TCPSocket(ePoll, text) {
|
TCPSession::TCPSession(EPoll &ePoll, std::string text) : TCPSocket(ePoll, text) {
|
||||||
|
// uuid_t is 16 raw binary bytes, not a NUL-terminated string -
|
||||||
|
// streaming it directly (the old code did `<< uuidObject`) hits
|
||||||
|
// libstdc++'s unsigned-char* operator<< overload, which treats its
|
||||||
|
// argument as a C-string and calls strlen() on it: a real
|
||||||
|
// stack-buffer-overflow read past the 16-byte local, confirmed via
|
||||||
|
// AddressSanitizer under concurrent load. Separately, `alias` was
|
||||||
|
// being pointed at `uuidObject` itself - a stack-local array that is
|
||||||
|
// destroyed the instant this constructor returns, leaving `alias` a
|
||||||
|
// dangling pointer for the rest of the session's life (used by
|
||||||
|
// compareAlias() for session identity). uuid_unparse() into the
|
||||||
|
// `uuid` member (declared for exactly this - see its doc comment)
|
||||||
|
// fixes both: a real NUL-terminated string safe to log, backed by
|
||||||
|
// storage that lives as long as the TCPSession does.
|
||||||
uuid_t uuidObject;
|
uuid_t uuidObject;
|
||||||
uuid_generate(uuidObject);
|
uuid_generate(uuidObject);
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << uuidObject;
|
uuid_unparse(uuidObject, uuid);
|
||||||
alias = (void *)uuidObject;
|
coreutils::Log(coreutils::LOG_DEBUG_1) << uuid;
|
||||||
|
alias = (void *)uuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
TCPSession::TCPSession(EPoll &ePoll, TCPServer *server, std::string text) : TCPSocket(ePoll, server->ctx, text), server(server) {
|
TCPSession::TCPSession(EPoll &ePoll, TCPServer *server, std::string text) : TCPSocket(ePoll, server->ctx, text), server(server) {
|
||||||
uuid_t uuidObject;
|
uuid_t uuidObject;
|
||||||
uuid_generate(uuidObject);
|
uuid_generate(uuidObject);
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << uuidObject;
|
uuid_unparse(uuidObject, uuid);
|
||||||
alias = (void *)uuidObject;
|
coreutils::Log(coreutils::LOG_DEBUG_1) << uuid;
|
||||||
|
alias = (void *)uuid;
|
||||||
}
|
}
|
||||||
|
|
||||||
TCPSession::~TCPSession() {
|
TCPSession::~TCPSession() {
|
||||||
@@ -30,7 +45,21 @@ namespace core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TCPSession::protocol(coreutils::ZString &data) {
|
void TCPSession::protocol(coreutils::ZString &data) {
|
||||||
if (data.getLength() != 0) {
|
// The data.getLength() != 0 guard alone silently swallowed every
|
||||||
|
// blank line a client sent, before it ever reached
|
||||||
|
// CommandList::processRequest() - fine for ordinary command
|
||||||
|
// dispatch (a stray blank line between commands isn't a command),
|
||||||
|
// but CommandList::processRequest() already special-cases
|
||||||
|
// session.grab != NULL to hand the line to the grabbed handler
|
||||||
|
// unconditionally, blank or not - a handler mid-grabInput() (e.g.
|
||||||
|
// __SMTP_DATA reading a message body, or an IMAP APPEND literal)
|
||||||
|
// depends on seeing blank lines as real content, not commands.
|
||||||
|
// With the outer guard unconditional, every message body's
|
||||||
|
// header/body separator - and every blank line within the body
|
||||||
|
// itself - was getting dropped before that handler ever saw it.
|
||||||
|
// Confirmed via a delivered test message with zero CRLFCRLF
|
||||||
|
// sequences anywhere in it, which is what first exposed this.
|
||||||
|
if (grab != NULL || data.getLength() != 0) {
|
||||||
if (!server->commands.processRequest(data, *this)) {
|
if (!server->commands.processRequest(data, *this)) {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << "Received data could not be parsed: " << data.str();
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Received data could not be parsed: " << data.str();
|
||||||
}
|
}
|
||||||
@@ -62,9 +91,27 @@ namespace core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void TCPSession::send() {
|
void TCPSession::send() {
|
||||||
if(out.tellp() > 0)
|
// Take the data and clear `out` BEFORE write(). write() can re-arm
|
||||||
write(out.str());
|
// the fd, and from that moment another epoll worker may send what
|
||||||
|
// was queued, receive the client's next command and run its handler
|
||||||
|
// - which appends to this same `out`. When `out` was only cleared
|
||||||
|
// after write() returned, a handler running in that window saw the
|
||||||
|
// previous text still there and sent it a second time. Reproduced
|
||||||
|
// with the protocol greeting (queued from onRegistered() on the
|
||||||
|
// accepting thread): under a burst of connections some clients got
|
||||||
|
// "220 ..." twice, every later reply then lined up with the wrong
|
||||||
|
// command, and STARTTLS clients read the plain "220 Ready" as their
|
||||||
|
// TLS ServerHello.
|
||||||
|
if(out.tellp() > 0) {
|
||||||
|
std::string data = out.str();
|
||||||
out.str("");
|
out.str("");
|
||||||
|
write(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TCPSession::startTLS(SSL_CTX *ctx) {
|
||||||
|
send();
|
||||||
|
return TCPSocket::startTLS(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPSession::terminate() {
|
void TCPSession::terminate() {
|
||||||
|
|||||||
+129
-1
@@ -3,6 +3,9 @@
|
|||||||
|
|
||||||
# include "SessionFilter.h"
|
# include "SessionFilter.h"
|
||||||
# include "TCPSocket.h"
|
# include "TCPSocket.h"
|
||||||
|
# include <map>
|
||||||
|
# include <memory>
|
||||||
|
# include <mutex>
|
||||||
# include <sstream>
|
# include <sstream>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
@@ -22,7 +25,120 @@ namespace core {
|
|||||||
///
|
///
|
||||||
///
|
///
|
||||||
|
|
||||||
class TCPSession : public TCPSocket {
|
class TCPSession : public TCPSocket, public std::enable_shared_from_this<TCPSession> {
|
||||||
|
|
||||||
|
public:
|
||||||
|
|
||||||
|
///
|
||||||
|
/// pin() safely upgrades a raw TCPSession* (as stored in
|
||||||
|
/// Subscription::subscribers, ZephoraServer's own
|
||||||
|
/// sessionsByPlayerName, GroupManager's membership lists, etc.)
|
||||||
|
/// into a real, ownership-extending shared_ptr before it's used.
|
||||||
|
///
|
||||||
|
/// The core problem this solves: every crash found and root-caused
|
||||||
|
/// this session (SubscriptionManager.cpp/TCPServer.cpp/Socket.cpp's
|
||||||
|
/// own fixes) was the same shape - one thread calling a method
|
||||||
|
/// (write(), a destructor) on a TCPSession* while another thread
|
||||||
|
/// concurrently deleted that same object, because nothing actually
|
||||||
|
/// guaranteed the object stayed alive for the duration of the
|
||||||
|
/// call. Mutex-based fixes at each individual call site kept
|
||||||
|
/// narrowing the window without fully closing it, and a mutex
|
||||||
|
/// around every write() call also isn't what the fifo-based
|
||||||
|
/// design (see Socket::write()) was going for in the first place -
|
||||||
|
/// no thread should have to block just to hand off a message.
|
||||||
|
///
|
||||||
|
/// TCPServer::sessions now holds the one real, strong-owning
|
||||||
|
/// shared_ptr<TCPSession> per live session (see its own comment).
|
||||||
|
/// Every OTHER place that stores a TCPSession* for later use is a
|
||||||
|
/// plain observer, not an owner - it must call pin() and check for
|
||||||
|
/// null immediately before touching the object, rather than
|
||||||
|
/// dereferencing the raw pointer directly. pin() returns nullptr
|
||||||
|
/// (instead of throwing, unlike raw shared_from_this()) once the
|
||||||
|
/// object's last real owner has let go and it's on its way out -
|
||||||
|
/// at that point there is nothing left to safely do with it, and
|
||||||
|
/// the caller should just skip it as if it were never there,
|
||||||
|
/// exactly like a stale/already-unsubscribed entry.
|
||||||
|
///
|
||||||
|
/// This adds no blocking anywhere: shared_ptr's own refcounting is
|
||||||
|
/// a couple of atomic increments, not a mutex - the actual
|
||||||
|
/// deletion still only ever happens once, whenever the last
|
||||||
|
/// outstanding shared_ptr (held by TCPServer::sessions, or
|
||||||
|
/// briefly by whichever thread(s) are mid-call via their own
|
||||||
|
/// pin()'d reference) goes out of scope.
|
||||||
|
///
|
||||||
|
|
||||||
|
std::shared_ptr<TCPSession> pin() {
|
||||||
|
try { return shared_from_this(); }
|
||||||
|
catch (const std::bad_weak_ptr &) { return nullptr; }
|
||||||
|
}
|
||||||
|
|
||||||
|
///
|
||||||
|
/// A second, distinct safety problem pin()/shared_from_this()
|
||||||
|
/// alone cannot solve: Thread::run()'s epoll dispatch loop starts
|
||||||
|
/// from a raw `void*` (epoll_event.data.ptr) whose TYPE isn't known
|
||||||
|
/// yet - the original code cast it straight to `Socket*` and
|
||||||
|
/// called virtual methods on it; an early version of this fix used
|
||||||
|
/// dynamic_cast<TCPSession*> to identify session objects before
|
||||||
|
/// calling pin(). Both of those REQUIRE reading the pointed-to
|
||||||
|
/// object's own memory (its vtable, at minimum) to work at all -
|
||||||
|
/// confirmed live via AddressSanitizer that dynamic_cast on a
|
||||||
|
/// stale pointer (one epoll handed out for a TCPSession that
|
||||||
|
/// something else had already fully destroyed and freed on another
|
||||||
|
/// thread) segfaults outright, before pin()'s own safety logic
|
||||||
|
/// ever gets a chance to run.
|
||||||
|
///
|
||||||
|
/// tryGet() sidesteps this entirely: it looks the raw pointer VALUE
|
||||||
|
/// up as a key in a plain map, and only ever touches a weak_ptr's
|
||||||
|
/// own control block (a separate heap allocation that outlives the
|
||||||
|
/// TCPSession object itself for as long as any weak_ptr or
|
||||||
|
/// shared_ptr referencing it exists) - never the TCPSession's own
|
||||||
|
/// memory - to decide whether it's still valid. That makes it safe
|
||||||
|
/// to call on ANY raw pointer value, including ones that turn out
|
||||||
|
/// to be completely unrelated to this registry (never a
|
||||||
|
/// TCPSession, e.g. a listening TCPServer/ConsoleServer - see
|
||||||
|
/// TCPServer::isKnownListeningSocket() for how Thread::run()
|
||||||
|
/// distinguishes that case) or ones pointing at freed memory.
|
||||||
|
///
|
||||||
|
/// registerLive()/unregisterLive() are called exactly once each,
|
||||||
|
/// by TCPServer::connectionRequest() and removeFromSessionList()
|
||||||
|
/// respectively - see their own comments for why those are the
|
||||||
|
/// right, and only, call sites.
|
||||||
|
///
|
||||||
|
|
||||||
|
static void registerLive(TCPSession *raw, std::shared_ptr<TCPSession> owner) {
|
||||||
|
std::lock_guard<std::mutex> guard(registryMutex());
|
||||||
|
registry()[raw] = owner;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void unregisterLive(TCPSession *raw) {
|
||||||
|
std::lock_guard<std::mutex> guard(registryMutex());
|
||||||
|
registry().erase(raw);
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::shared_ptr<TCPSession> tryGet(void *raw) {
|
||||||
|
std::lock_guard<std::mutex> guard(registryMutex());
|
||||||
|
auto it = registry().find((TCPSession *)raw);
|
||||||
|
if (it == registry().end())
|
||||||
|
return nullptr;
|
||||||
|
return it->second.lock();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Function-local statics (constructed on first use, in whichever
|
||||||
|
// translation unit/thread reaches them first, thread-safely per
|
||||||
|
// C++11's own guarantee for static local initialization) instead
|
||||||
|
// of ordinary static data members - avoids needing a .cpp
|
||||||
|
// definition for these two and any static-initialization-order
|
||||||
|
// concerns with other translation units, since TCPSession.h is
|
||||||
|
// included widely.
|
||||||
|
static std::mutex ®istryMutex() {
|
||||||
|
static std::mutex m;
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
static std::map<TCPSession *, std::weak_ptr<TCPSession>> ®istry() {
|
||||||
|
static std::map<TCPSession *, std::weak_ptr<TCPSession>> r;
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
@@ -55,6 +171,18 @@ namespace core {
|
|||||||
|
|
||||||
void send();
|
void send();
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Upgrade this session to TLS (STARTTLS/STLS). Put the protocol's
|
||||||
|
/// "ready" reply in `out` first, then call this from the command
|
||||||
|
/// handler; it sends that reply in clear text, drops any input
|
||||||
|
/// pipelined behind the command, and starts the handshake. See
|
||||||
|
/// TCPSocket::startTLS() for the details and return value.
|
||||||
|
///
|
||||||
|
/// Pass server->startTLSContext (see TCPServer::enableStartTLS()).
|
||||||
|
///
|
||||||
|
|
||||||
|
bool startTLS(SSL_CTX *ctx);
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Use this method to terminate this TCPSession.
|
/// Use this method to terminate this TCPSession.
|
||||||
///
|
///
|
||||||
|
|||||||
+199
-11
@@ -3,6 +3,8 @@
|
|||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
#include "Exception.h"
|
#include "Exception.h"
|
||||||
#include "errno.h"
|
#include "errno.h"
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
@@ -27,40 +29,222 @@ namespace core {
|
|||||||
out << "|" << ipAddress.getClientAddressAndPort();
|
out << "|" << ipAddress.getClientAddressAndPort();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPSocket::onDataReceived(coreutils::ZString &data) {
|
void TCPSocket::receiveData(coreutils::ZString &buffer) {
|
||||||
|
// Dispatch on `ctx`, not `tlsInfo` - the SSL_CTX*-taking constructor
|
||||||
if(tlsInfo) {
|
// (used for every accepted TCPSession) never sets `tlsInfo` at all,
|
||||||
|
// leaving it as uninitialized garbage that intermittently (whenever
|
||||||
|
// that garbage happened to be non-zero) routed a plain, non-TLS
|
||||||
|
// session's data through SSL_read()/SSL_write() against an
|
||||||
|
// uninitialized SSL*, segfaulting inside libssl. `ctx` is the
|
||||||
|
// reliable signal: real and non-NULL for an actual TLS server/
|
||||||
|
// session (set in TLS::createContext(), inherited by sessions via
|
||||||
|
// TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h).
|
||||||
|
if(ctx) {
|
||||||
|
// Loop until OpenSSL has nothing decrypted left over. A single TLS
|
||||||
|
// record carries up to 16KB, but `buffer` is 4KB, so one SSL_read()
|
||||||
|
// can leave the rest of a record sitting inside OpenSSL. This socket
|
||||||
|
// is edge-triggered (EPOLLET) and those bytes have already been
|
||||||
|
// pulled off the fd, so nothing would ever raise another EPOLLIN
|
||||||
|
// for them: the session would stall mid-stream until the peer
|
||||||
|
// happened to send something else. Small requests (HTTP headers,
|
||||||
|
// single commands) never fill a 4KB read, which is why this didn't
|
||||||
|
// show up before; an SMTP DATA body from another mail server - the
|
||||||
|
// common case once STARTTLS is offered - does on every message.
|
||||||
|
while(true) {
|
||||||
|
int len;
|
||||||
|
bool more;
|
||||||
|
{
|
||||||
|
// Held only around the raw SSL_read/SSL_pending calls -
|
||||||
|
// released before onDataReceived() so the request-handling
|
||||||
|
// chain it triggers (which reaches Socket::write()/outlock)
|
||||||
|
// never runs while ioLock is held. See ioLock's own doc
|
||||||
|
// comment in TCPSocket.h.
|
||||||
|
std::lock_guard<std::mutex> ioGuard(ioLock);
|
||||||
|
len = TLS::receiveData(buffer);
|
||||||
|
more = len > 0 && pendingBytes() > 0;
|
||||||
|
}
|
||||||
|
if(len >= 0) {
|
||||||
|
coreutils::ZString zbuffer(buffer.getData(), len);
|
||||||
|
onDataReceived(zbuffer);
|
||||||
|
}
|
||||||
|
if(!more || shutDown)
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Socket::receiveData(buffer);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int TCPSocket::sendData(const char *data, int length) {
|
||||||
|
if(ctx) {
|
||||||
|
std::lock_guard<std::mutex> ioGuard(ioLock);
|
||||||
|
return TLS::sendData(data, length);
|
||||||
|
} else
|
||||||
|
return Socket::sendData(data, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TCPSocket::sendNeedsRead() {
|
||||||
|
return ctx && lastSendWantedRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TCPSocket::startTLS(SSL_CTX *newCtx) {
|
||||||
|
if(ctx || !newCtx)
|
||||||
|
return false;
|
||||||
|
discardInput = true;
|
||||||
|
if(!flushPlain(10000)) {
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "STARTTLS: ready reply could not be delivered; closing.";
|
||||||
|
shutdown("STARTTLS ready reply could not be delivered");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
ctx = newCtx;
|
||||||
|
performTLSHandshake();
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "STARTTLS: handshake started on socket " << getDescriptor() << ".";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TCPSocket::performTLSHandshake() {
|
||||||
|
// registerSocket() makes this fd eligible for epoll dispatch to ANY
|
||||||
|
// worker thread immediately. ioLock MUST be acquired BEFORE that
|
||||||
|
// call, not after - a first attempt here took the lock AFTER
|
||||||
|
// registerSocket(), which still left a real window: another thread
|
||||||
|
// could win the race for ioLock (via a read/write event on this
|
||||||
|
// same brand-new connection) and have SSL_read/SSL_write silently
|
||||||
|
// complete the handshake on OpenSSL's own initiative, and only
|
||||||
|
// THEN would this thread acquire ioLock and run its own, now
|
||||||
|
// redundant, acceptSocket() (SSL_accept) against an already-
|
||||||
|
// negotiated SSL object - confirmed via gdb `thread apply all bt`
|
||||||
|
// during a live crash: one thread mid-SSL_read, a second thread
|
||||||
|
// simultaneously inside performTLSHandshake, both on the identical
|
||||||
|
// object address. Acquiring ioLock first closes that window
|
||||||
|
// entirely: no other thread can even begin touching this
|
||||||
|
// connection's SSL object until this thread's own handshake
|
||||||
|
// attempt has released the lock. acceptSocket() only attempts
|
||||||
|
// SSL_accept() once and may leave the handshake incomplete
|
||||||
|
// (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently
|
||||||
|
// finishes a pending handshake on the next SSL_read/SSL_write,
|
||||||
|
// which ioLock already serializes against everything else.
|
||||||
|
performTLSHandshake(getDescriptor());
|
||||||
|
}
|
||||||
|
|
||||||
|
void TCPSocket::performTLSHandshake(int fd) {
|
||||||
|
std::lock_guard<std::mutex> ioGuard(ioLock);
|
||||||
|
registerSocket(fd);
|
||||||
|
acceptSocket();
|
||||||
|
}
|
||||||
|
|
||||||
|
void TCPSocket::onDataReceived(coreutils::ZString &data) {
|
||||||
|
|
||||||
if (data.getLength() > 0) {
|
if (data.getLength() > 0) {
|
||||||
|
hasReceivedData = true;
|
||||||
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize + data.getLength());
|
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize + data.getLength());
|
||||||
memcpy(lineBuffer + lineBufferSize, data.getData(), data.getLength());
|
memcpy(lineBuffer + lineBufferSize, data.getData(), data.getLength());
|
||||||
lineBufferSize += data.getLength();
|
lineBufferSize += data.getLength();
|
||||||
while (lineBufferSize > 0) {
|
while (lineBufferSize > 0) {
|
||||||
if (blockSize == 0) {
|
if (blockSize == 0) {
|
||||||
lineLength = strcspn(lineBuffer, "\r\n");
|
// strcspn() treats its argument as a NUL-terminated C
|
||||||
if (lineLength == lineBufferSize)
|
// string and keeps scanning past the end looking for one -
|
||||||
|
// lineBuffer is a raw byte buffer sized via realloc() to
|
||||||
|
// exactly lineBufferSize bytes, with no NUL terminator
|
||||||
|
// appended anywhere. Whenever the buffered data doesn't yet
|
||||||
|
// contain a CRLF (an ordinary, frequent case - a line split
|
||||||
|
// across TCP reads, or mid-way through a long one, e.g. a
|
||||||
|
// large email body), strcspn() read straight past
|
||||||
|
// lineBufferSize into whatever heap memory happened to
|
||||||
|
// follow, hunting for a byte that happened to match '\r',
|
||||||
|
// '\n', or an accidental '\0' - producing a lineLength
|
||||||
|
// larger than the buffer actually holds. Confirmed live via
|
||||||
|
// gdb: SIGSEGV inside a LATER, unrelated realloc() call on
|
||||||
|
// this same lineBuffer, well downstream of where the real
|
||||||
|
// corruption happened (lineBufferSize -= lineLength
|
||||||
|
// underflows when lineLength > lineBufferSize, and that
|
||||||
|
// negative value gets handed to realloc() as a size_t -
|
||||||
|
// realloc(ptr, SIZE_MAX-ish) - during a real inbound SMTP
|
||||||
|
// message with a long quoted-printable line). memchr() is
|
||||||
|
// the bounded equivalent - it never looks past the length
|
||||||
|
// given, so "no CRLF yet" correctly comes back as "not
|
||||||
|
// found" instead of reading off the end of the allocation.
|
||||||
|
char *found;
|
||||||
|
if (strictCRLF)
|
||||||
|
found = (char *)memmem(lineBuffer, lineBufferSize, "\r\n", 2);
|
||||||
|
else {
|
||||||
|
char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize);
|
||||||
|
char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize);
|
||||||
|
found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl);
|
||||||
|
}
|
||||||
|
lineLength = found ? (int)(found - lineBuffer) : lineBufferSize;
|
||||||
|
if (!found) {
|
||||||
|
// No complete line yet. If it has already outgrown
|
||||||
|
// maxLineLength, drop what's buffered (keeping the last
|
||||||
|
// byte, which may be the CR of a CR LF whose LF is still
|
||||||
|
// in flight) and skip the rest of it - see maxLineLength.
|
||||||
|
if (maxLineLength && (size_t)lineBufferSize > maxLineLength) {
|
||||||
|
lineBuffer[0] = lineBuffer[lineBufferSize - 1];
|
||||||
|
lineBufferSize = 1;
|
||||||
|
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize);
|
||||||
|
skippingLongLine = true;
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
|
}
|
||||||
|
if (skippingLongLine || (maxLineLength && (size_t)lineLength > maxLineLength)) {
|
||||||
|
skippingLongLine = false;
|
||||||
|
onLineTooLong();
|
||||||
|
} else {
|
||||||
coreutils::ZString zLine(lineBuffer, lineLength);
|
coreutils::ZString zLine(lineBuffer, lineLength);
|
||||||
onLineReceived(zLine);
|
onLineReceived(zLine);
|
||||||
|
}
|
||||||
|
if (discardInput)
|
||||||
|
break;
|
||||||
|
// lineLength < lineBufferSize is guaranteed by the break
|
||||||
|
// above, so this first index is always in bounds; bump
|
||||||
|
// past a lone '\r' only if there's still at least one more
|
||||||
|
// buffered byte to safely check for a following '\n' -
|
||||||
|
// otherwise (a bare trailing '\r' with nothing buffered
|
||||||
|
// after it yet) leave it for the next read to resolve,
|
||||||
|
// rather than reading lineBuffer[lineBufferSize], one past
|
||||||
|
// the allocation.
|
||||||
|
if (strictCRLF)
|
||||||
|
lineLength += 2;
|
||||||
|
else {
|
||||||
if (lineBuffer[lineLength] == '\r')
|
if (lineBuffer[lineLength] == '\r')
|
||||||
++lineLength;
|
++lineLength;
|
||||||
if (lineBuffer[lineLength] == '\n')
|
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
|
||||||
++lineLength;
|
++lineLength;
|
||||||
|
}
|
||||||
lineBufferSize -= lineLength;
|
lineBufferSize -= lineLength;
|
||||||
if (lineBufferSize > 0)
|
if (lineBufferSize > 0)
|
||||||
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
|
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
|
||||||
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize);
|
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize);
|
||||||
}
|
}
|
||||||
else if (lineBufferSize >= blockLength) {
|
else if (lineBufferSize >= blockSize) {
|
||||||
coreutils::ZString zBlock(lineBuffer, blockLength);
|
coreutils::ZString zBlock(lineBuffer, blockSize);
|
||||||
onBlockReceived(zBlock);
|
onBlockReceived(zBlock);
|
||||||
lineBufferSize -= blockLength;
|
if (discardInput)
|
||||||
|
break;
|
||||||
|
lineBufferSize -= blockSize;
|
||||||
if (lineBufferSize > 0)
|
if (lineBufferSize > 0)
|
||||||
memmove(lineBuffer, lineBuffer + blockLength, lineBufferSize);
|
memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize);
|
||||||
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize);
|
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize);
|
||||||
}
|
}
|
||||||
|
else
|
||||||
|
// Not enough buffered data yet for a full block - stop and
|
||||||
|
// wait for the next read, exactly like the line-mode
|
||||||
|
// branch's own "no complete line yet" break above.
|
||||||
|
// Without this, a block spanning more than one TCP read
|
||||||
|
// (any IMAP APPEND literal bigger than a single read()'s
|
||||||
|
// worth of socket buffer) sends this EPoll worker thread
|
||||||
|
// into an unconditional busy-spin - lineBufferSize never
|
||||||
|
// changes, so the while(lineBufferSize > 0) loop above
|
||||||
|
// never yields back to let more data arrive.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (discardInput) {
|
||||||
|
// See startTLS(): whatever followed the upgrade command in this
|
||||||
|
// read is pre-handshake plain text and is dropped, not processed.
|
||||||
|
discardInput = false;
|
||||||
|
free(lineBuffer);
|
||||||
|
lineBuffer = NULL;
|
||||||
|
lineBufferSize = 0;
|
||||||
|
lineLength = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,6 +256,10 @@ namespace core {
|
|||||||
|
|
||||||
void TCPSocket::onBlockReceived(coreutils::ZString &block) {}
|
void TCPSocket::onBlockReceived(coreutils::ZString &block) {}
|
||||||
|
|
||||||
|
void TCPSocket::onLineTooLong() {
|
||||||
|
shutdown("line exceeded maxLineLength");
|
||||||
|
}
|
||||||
|
|
||||||
void TCPSocket::setBlockSize(int blockSize) {
|
void TCPSocket::setBlockSize(int blockSize) {
|
||||||
this->blockSize = blockSize;
|
this->blockSize = blockSize;
|
||||||
}
|
}
|
||||||
|
|||||||
+193
-1
@@ -6,6 +6,7 @@
|
|||||||
#include "TLS.h"
|
#include "TLS.h"
|
||||||
#include "TLSInfo.h"
|
#include "TLSInfo.h"
|
||||||
#include "IPAddress.h"
|
#include "IPAddress.h"
|
||||||
|
#include <chrono>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
@@ -104,6 +105,131 @@ namespace core {
|
|||||||
|
|
||||||
void setBlockSize(int size = 0);
|
void setBlockSize(int size = 0);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Dispatches to TLS::receiveData (SSL_read) when this socket was constructed with a
|
||||||
|
/// TLSInfo/SSL_CTX, otherwise falls back to Socket::receiveData (plain ::read). Needed
|
||||||
|
/// because Socket and TLS both declare receiveData as unrelated sibling methods -
|
||||||
|
/// Socket::receiveData is virtual but TLS::receiveData does not override it, so without
|
||||||
|
/// this explicit override TLS::receiveData would never be reached and encrypted bytes
|
||||||
|
/// would be handed to onDataReceived as if they were plaintext.
|
||||||
|
///
|
||||||
|
|
||||||
|
virtual void receiveData(coreutils::ZString &buffer) override;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Dispatches to TLS::sendData (SSL_write) when this socket was constructed with a
|
||||||
|
/// TLSInfo/SSL_CTX, otherwise falls back to Socket::sendData (plain ::write). Mirrors
|
||||||
|
/// the receiveData override above for the write path.
|
||||||
|
///
|
||||||
|
|
||||||
|
virtual int sendData(const char *data, int length) override;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// True only when this socket is actually TLS (ctx set) and the
|
||||||
|
/// last sendData() call failed specifically with
|
||||||
|
/// SSL_ERROR_WANT_READ - see TLS::lastSendWantedRead's own doc
|
||||||
|
/// comment for why Socket::writeSocket()/resetSocket() need this.
|
||||||
|
///
|
||||||
|
|
||||||
|
virtual bool sendNeedsRead() override;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Completes the TLS handshake (SSL_new/SSL_set_fd/SSL_accept) for
|
||||||
|
/// THIS socket's own ctx/descriptor. registerSocket()/acceptSocket()
|
||||||
|
/// are protected TLS members, reachable here via an ordinary
|
||||||
|
/// same-class call - the point of exposing this as a public wrapper
|
||||||
|
/// is so a sibling class (TCPServer, which does not inherit
|
||||||
|
/// TCPSocket-the-session's-particular-instance and so cannot reach
|
||||||
|
/// another object's protected members directly) can still trigger
|
||||||
|
/// the handshake on a specific accepted session from
|
||||||
|
/// TCPServer::connectionRequest(), rather than accidentally running
|
||||||
|
/// it against the listening server socket itself (see that call
|
||||||
|
/// site's own comment for the real, confirmed crash this replaces -
|
||||||
|
/// SSL_read() on an accepted session's never-initialized ssl
|
||||||
|
/// member).
|
||||||
|
///
|
||||||
|
|
||||||
|
void performTLSHandshake();
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Same, on an fd that hasn't been handed to setDescriptor() yet.
|
||||||
|
/// TCPServer::accept() uses this for implicit-TLS listeners so the
|
||||||
|
/// SSL object exists before the fd is armed in epoll - otherwise the
|
||||||
|
/// greeting queued by onConnected() can reach TLS::sendData() on
|
||||||
|
/// another worker before there is anything to send it through.
|
||||||
|
///
|
||||||
|
|
||||||
|
void performTLSHandshake(int fd);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Set once, at construction, and never touched again - how long
|
||||||
|
/// this specific socket has been open since accept()/connect(),
|
||||||
|
/// regardless of whether anything has actually happened on it
|
||||||
|
/// since. TCPServer::sweepStaleSessions() reads this (alongside
|
||||||
|
/// hasReceivedData below) to find connections that completed a
|
||||||
|
/// TCP handshake but then never progressed - a scanner/prober
|
||||||
|
/// probing an open port, or a TLS handshake that never finished -
|
||||||
|
/// which otherwise sit in TCPServer::sessions forever: nothing in
|
||||||
|
/// the existing design ever revisits a socket that stops
|
||||||
|
/// generating epoll events (see sweepStaleSessions()'s own doc
|
||||||
|
/// comment for the full reasoning).
|
||||||
|
///
|
||||||
|
|
||||||
|
std::chrono::steady_clock::time_point acceptedAt = std::chrono::steady_clock::now();
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Flips to true the first time onDataReceived() sees a non-empty
|
||||||
|
/// read - true for both a plaintext socket's raw bytes and a TLS
|
||||||
|
/// session's already-decrypted ones, since both paths funnel
|
||||||
|
/// through the same onDataReceived() override below. A session
|
||||||
|
/// that reaches sweepStaleSessions()'s grace period with this
|
||||||
|
/// still false has never had a real exchange of any kind, TLS
|
||||||
|
/// handshake included (a stuck/incomplete SSL_accept() never
|
||||||
|
/// surfaces anything to onDataReceived) - the specific, narrow
|
||||||
|
/// condition that sweep treats as abandoned. Deliberately NOT
|
||||||
|
/// reset afterward and never consulted again once true, so a
|
||||||
|
/// legitimate client that sends something once and then goes
|
||||||
|
/// idle for a long time (an ordinary connected-but-idle game
|
||||||
|
/// session) is never at risk from this - only a connection that
|
||||||
|
/// NEVER said anything at all within the grace window is.
|
||||||
|
///
|
||||||
|
|
||||||
|
bool hasReceivedData = false;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Upgrade this plain-text connection to TLS in place (SMTP
|
||||||
|
/// STARTTLS, IMAP STARTTLS, POP3 STLS). Call it from the command
|
||||||
|
/// handler that accepted the upgrade, AFTER queuing that command's
|
||||||
|
/// "ready" reply - TCPSession::startTLS() does both for you.
|
||||||
|
///
|
||||||
|
/// In order, it:
|
||||||
|
/// 1. writes everything queued so far (the ready reply included)
|
||||||
|
/// to the socket in clear text and waits for it to go out;
|
||||||
|
/// 2. throws away any other input the client already sent in the
|
||||||
|
/// same read as the upgrade command. RFC 3207 section 4 forbids
|
||||||
|
/// a client from pipelining anything after STARTTLS, and acting
|
||||||
|
/// on such bytes is the classic STARTTLS command-injection hole
|
||||||
|
/// (CVE-2011-0411 and its many relatives): an attacker on the
|
||||||
|
/// path appends plain-text commands that the server would then
|
||||||
|
/// treat as if they arrived over the encrypted channel;
|
||||||
|
/// 3. switches this socket to `ctx` and starts the server side of
|
||||||
|
/// the handshake. The client's ClientHello and everything after
|
||||||
|
/// it are read through TLS by the normal receiveData() path.
|
||||||
|
///
|
||||||
|
/// Returns false (and changes nothing) if TLS is already active or
|
||||||
|
/// ctx is NULL; returns false and shuts the connection down if the
|
||||||
|
/// ready reply couldn't be delivered.
|
||||||
|
///
|
||||||
|
|
||||||
|
bool startTLS(SSL_CTX *ctx);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// True once this connection is encrypted, whether it was accepted
|
||||||
|
/// on an implicit-TLS listener or upgraded with startTLS().
|
||||||
|
///
|
||||||
|
|
||||||
|
bool isTLS() { return ctx != NULL; }
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
bool term = false;
|
bool term = false;
|
||||||
TLSInfo *tlsInfo;
|
TLSInfo *tlsInfo;
|
||||||
@@ -112,9 +238,75 @@ namespace core {
|
|||||||
char *lineBuffer = NULL;
|
char *lineBuffer = NULL;
|
||||||
int lineBufferSize = 0;
|
int lineBufferSize = 0;
|
||||||
int lineLength = 0;
|
int lineLength = 0;
|
||||||
int blockLength = 0;
|
|
||||||
int blockSize = 0;
|
int blockSize = 0;
|
||||||
|
|
||||||
|
// Set by startTLS(); tells the onDataReceived() loop that the line
|
||||||
|
// it just dispatched was the upgrade command and everything still
|
||||||
|
// in lineBuffer is pre-handshake plain text that must be dropped,
|
||||||
|
// not processed. See startTLS()'s step 2.
|
||||||
|
bool discardInput = false;
|
||||||
|
|
||||||
|
// Set by the line loop while it is dropping the rest of a line that
|
||||||
|
// already exceeded maxLineLength; see onLineTooLong().
|
||||||
|
bool skippingLongLine = false;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
///
|
||||||
|
/// When true, only CR LF ends a line; a bare CR or bare LF is kept
|
||||||
|
/// as part of the line's content. Default false (a CR, an LF, or CR
|
||||||
|
/// LF each end a line), which existing line protocols rely on.
|
||||||
|
///
|
||||||
|
/// SMTP must use true. RFC 5321 2.3.8 and 4.1.1.4 make <CRLF>.<CRLF>
|
||||||
|
/// the only end-of-data sequence; a server that also accepts bare
|
||||||
|
/// <LF> or <CR> line endings can be made to end a message early on
|
||||||
|
/// "<LF>.<LF>" and then run whatever follows in the same message as
|
||||||
|
/// fresh SMTP commands - "SMTP smuggling" (CVE-2023-51764/-51765/
|
||||||
|
/// -51766), which lets a sender forge mail from any domain that
|
||||||
|
/// relays through the server. The lenient mode also splits a CR LF
|
||||||
|
/// that straddles two reads into two lines, the second one empty.
|
||||||
|
///
|
||||||
|
|
||||||
|
bool strictCRLF = false;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Upper bound on bytes buffered for a single line (0 = no limit).
|
||||||
|
/// When a line grows past it, the buffered part is dropped, the rest
|
||||||
|
/// of that line is skipped up to its terminator, and onLineTooLong()
|
||||||
|
/// is called once in place of onLineReceived() for it. Without a
|
||||||
|
/// bound, a peer that never sends a line terminator grows lineBuffer
|
||||||
|
/// until the process runs out of memory.
|
||||||
|
///
|
||||||
|
|
||||||
|
size_t maxLineLength = 0;
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Called once for each line that exceeded maxLineLength. The default
|
||||||
|
/// closes the connection; protocols that can recover override it to
|
||||||
|
/// reply with an error instead.
|
||||||
|
///
|
||||||
|
|
||||||
|
virtual void onLineTooLong();
|
||||||
|
|
||||||
|
// Socket's own `lock` (guards receiveData) and `outlock` (guards
|
||||||
|
// writeSocket/the fifo) are two DIFFERENT mutexes - a thread
|
||||||
|
// handling EPOLLIN and a different thread handling EPOLLWRNORM for
|
||||||
|
// the SAME connection can therefore call SSL_read and SSL_write on
|
||||||
|
// the SAME `ssl*` concurrently. OpenSSL does not support that: an
|
||||||
|
// SSL object must not be used by more than one thread at a time
|
||||||
|
// (even in 1.1.0+/3.x, which dropped the old app-supplied
|
||||||
|
// CRYPTO_set_locking_callback global-locking API entirely - that
|
||||||
|
// API never protected concurrent use of one SSL object anyway,
|
||||||
|
// only OpenSSL's own internal global state). Confirmed live via
|
||||||
|
// dmesg: "traps: apiserver[...] general protection fault ... in
|
||||||
|
// libssl.so.3" during ordinary interactive use. ioLock serializes
|
||||||
|
// just the raw SSL_read/SSL_write calls themselves (see
|
||||||
|
// receiveData/sendData below) - deliberately NOT the surrounding
|
||||||
|
// request-handling, which already nests `lock` before `outlock`
|
||||||
|
// (receiveData's call chain reaches Socket::write(), which takes
|
||||||
|
// outlock) - wrapping any larger scope in ioLock+lock+outlock
|
||||||
|
// together risks recreating that same ordering as a new cycle.
|
||||||
|
std::mutex ioLock;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <openssl/rand.h>
|
#include <openssl/rand.h>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
@@ -33,6 +34,17 @@ namespace core {
|
|||||||
void handshake_complete(const SSL *ssl, int where, int ret) {
|
void handshake_complete(const SSL *ssl, int where, int ret) {
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_3) << "==>" << SSL_state_string_long(ssl) << "<==" << ret;
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "==>" << SSL_state_string_long(ssl) << "<==" << ret;
|
||||||
if(where & SSL_CB_HANDSHAKE_DONE) {
|
if(where & SSL_CB_HANDSHAKE_DONE) {
|
||||||
|
// Only a context configured with SSL_VERIFY_PEER (see
|
||||||
|
// createContext()'s own cACertificate-gated block) ever sends a
|
||||||
|
// client a CertificateRequest in the first place - ordinary
|
||||||
|
// one-way TLS (a public site's normal case, no caCertificate
|
||||||
|
// configured) never asks the client for one, so
|
||||||
|
// SSL_get_peer_certificate() is unconditionally NULL there and is
|
||||||
|
// not a failure. Checking the mode actually negotiated on THIS
|
||||||
|
// connection (inherited from the context) rather than assuming
|
||||||
|
// every handshake is mutual-TLS is what makes plain
|
||||||
|
// browser-facing HTTPS work at all under this callback.
|
||||||
|
if(SSL_get_verify_mode(ssl) & SSL_VERIFY_PEER) {
|
||||||
X509 *ssl_client_cert = SSL_get_peer_certificate(ssl);
|
X509 *ssl_client_cert = SSL_get_peer_certificate(ssl);
|
||||||
if(!ssl_client_cert)
|
if(!ssl_client_cert)
|
||||||
throw std::string("Unable to get peer certificate.");
|
throw std::string("Unable to get peer certificate.");
|
||||||
@@ -41,6 +53,7 @@ namespace core {
|
|||||||
throw std::string("Certificate verification failed.");
|
throw std::string("Certificate verification failed.");
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_3) << "Certificate verified successfully.";
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "Certificate verified successfully.";
|
||||||
}
|
}
|
||||||
|
}
|
||||||
else
|
else
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_3) << "No client certificate.";
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "No client certificate.";
|
||||||
}
|
}
|
||||||
@@ -53,11 +66,25 @@ namespace core {
|
|||||||
|
|
||||||
TLS::TLS(SSL_CTX *ctx) : ctx(ctx) {}
|
TLS::TLS(SSL_CTX *ctx) : ctx(ctx) {}
|
||||||
|
|
||||||
TLS::~TLS() {}
|
// Each accepted TLS connection gets its own SSL object in
|
||||||
|
// registerSocket(); it was never freed, so every TLS session leaked
|
||||||
|
// one. Harmless for a handful of long-lived connections, but a mail
|
||||||
|
// server opens one per delivery, all day. The fd itself is still
|
||||||
|
// closed by ~Socket() as before - SSL_free() doesn't touch it.
|
||||||
|
TLS::~TLS() {
|
||||||
|
if(initialized)
|
||||||
|
SSL_free(ssl);
|
||||||
|
}
|
||||||
|
|
||||||
void TLS::createContext(TLSInfo *tlsInfo) {
|
// The ONE-TIME, process-wide OpenSSL library init (SSL_library_init(),
|
||||||
|
// the lockarray, RAND seeding). Used to live in createContext(), which
|
||||||
if(tlsInfo) {
|
// was fine while that was the only way a context got built; now that
|
||||||
|
// buildContext() is also reached directly - TCPServer::enableStartTLS()
|
||||||
|
// for STARTTLS, and addSNIContext() - it runs exactly once from there,
|
||||||
|
// whichever path gets to it first.
|
||||||
|
static void initializeLibrary() {
|
||||||
|
static std::once_flag once;
|
||||||
|
std::call_once(once, [] {
|
||||||
SSL_library_init();
|
SSL_library_init();
|
||||||
SSL_load_error_strings();
|
SSL_load_error_strings();
|
||||||
lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
|
lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
|
||||||
@@ -67,30 +94,105 @@ namespace core {
|
|||||||
CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))lock_callback);
|
CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))lock_callback);
|
||||||
SSLeay_add_ssl_algorithms();
|
SSLeay_add_ssl_algorithms();
|
||||||
RAND_load_file("/dev/hwrng", 1024);
|
RAND_load_file("/dev/hwrng", 1024);
|
||||||
if(!(ctx = SSL_CTX_new(SSLv23_server_method())))
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
void TLS::createContext(TLSInfo *tlsInfo) {
|
||||||
|
if(tlsInfo)
|
||||||
|
ctx = buildContext(tlsInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The per-context cert/key/cipher/verify setup, shared by
|
||||||
|
// createContext(), addSNIContext() (one context per extra hostname)
|
||||||
|
// and TCPServer::enableStartTLS().
|
||||||
|
SSL_CTX *TLS::buildContext(TLSInfo *tlsInfo) {
|
||||||
|
initializeLibrary();
|
||||||
|
SSL_CTX *newCtx;
|
||||||
|
if(!(newCtx = SSL_CTX_new(SSLv23_server_method())))
|
||||||
throw coreutils::Exception("Error while setting server method SSLv23.");
|
throw coreutils::Exception("Error while setting server method SSLv23.");
|
||||||
SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
// A caller may now catch a bad certificate/key and carry on without
|
||||||
SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
|
// TLS (BARANTMail does, for STARTTLS) - don't leak the half-built
|
||||||
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
|
// context on the way out.
|
||||||
// SSL_CTX_set_generate_session_id(ctx, generate_session_id);
|
try {
|
||||||
SSL_CTX_set_cipher_list(ctx, "ECDH-ECDSA-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA");
|
SSL_CTX_set_mode(newCtx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
||||||
if(SSL_CTX_use_certificate_file(ctx, tlsInfo->certificate.c_str(), SSL_FILETYPE_PEM) <= 0)
|
SSL_CTX_set_options(newCtx, SSL_OP_NO_TICKET);
|
||||||
|
SSL_CTX_set_session_cache_mode(newCtx, SSL_SESS_CACHE_SERVER);
|
||||||
|
SSL_CTX_set_cipher_list(newCtx, "ECDH-ECDSA-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA");
|
||||||
|
// _chain_file (not _file) - loads every certificate in the file,
|
||||||
|
// not just the first. A real Let's Encrypt fullchain.pem is the
|
||||||
|
// leaf cert followed by the intermediate CA cert concatenated in
|
||||||
|
// one file specifically so a server can hand both to the client
|
||||||
|
// in one shot; SSL_CTX_use_certificate_file() only ever reads the
|
||||||
|
// first PEM block, silently dropping the intermediate - confirmed
|
||||||
|
// via a real handshake against this exact fullchain.pem: clients
|
||||||
|
// got "unable to get local issuer certificate" because the server
|
||||||
|
// only ever sent the leaf, never the intermediate needed to chain
|
||||||
|
// up to a root the client already trusts.
|
||||||
|
if(SSL_CTX_use_certificate_chain_file(newCtx, tlsInfo->certificate.c_str()) <= 0)
|
||||||
throw coreutils::Exception("Error looking up certificate.");
|
throw coreutils::Exception("Error looking up certificate.");
|
||||||
if(SSL_CTX_use_PrivateKey_file(ctx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) < 0)
|
if(SSL_CTX_use_PrivateKey_file(newCtx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) <= 0)
|
||||||
throw coreutils::Exception("Error with private key.");
|
throw coreutils::Exception("Error with private key.");
|
||||||
if(SSL_CTX_check_private_key(ctx) != 1)
|
if(SSL_CTX_check_private_key(newCtx) != 1)
|
||||||
throw coreutils::Exception("Private key does not match certificate.");
|
throw coreutils::Exception("Private key does not match certificate.");
|
||||||
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
|
// Client-certificate verification (mutual TLS) is opt-in, not the
|
||||||
SSL_CTX_set_verify_depth(ctx, 1);
|
// default - a public-facing site (e.g. a real Let's Encrypt
|
||||||
if(!SSL_CTX_load_verify_locations(ctx, tlsInfo->cACertificate.c_str(), NULL))
|
// server cert with no corresponding client CA of its own) has no
|
||||||
|
// client certificate to hand out to ordinary visitors, so
|
||||||
|
// requesting one via SSL_VERIFY_PEER would surface a "select a
|
||||||
|
// certificate" prompt real browsers can't meaningfully answer.
|
||||||
|
// Only enable it when a caCertificate is actually configured -
|
||||||
|
// existing internal/mTLS use of this class (any config that DOES
|
||||||
|
// set tls.caCertificate) keeps behaving exactly as before.
|
||||||
|
if(tlsInfo->cACertificate.getLength() > 0) {
|
||||||
|
SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL);
|
||||||
|
SSL_CTX_set_verify_depth(newCtx, 1);
|
||||||
|
if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL))
|
||||||
throw coreutils::Exception("Cannot verify locations.");
|
throw coreutils::Exception("Cannot verify locations.");
|
||||||
SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str()));
|
SSL_CTX_set_client_CA_list(newCtx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str()));
|
||||||
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated.";
|
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required).";
|
||||||
|
} else {
|
||||||
|
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required).";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(...) {
|
||||||
|
SSL_CTX_free(newCtx);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
return newCtx;
|
||||||
|
}
|
||||||
|
|
||||||
|
int TLS::pendingBytes() {
|
||||||
|
return initialized ? SSL_pending(ssl) : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int TLS::sniCallback(SSL *ssl, int *ad, void *arg) {
|
||||||
|
TLS *self = (TLS *)arg;
|
||||||
|
const char *name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
|
||||||
|
if(name) {
|
||||||
|
auto it = self->sniContexts.find(name);
|
||||||
|
if(it != self->sniContexts.end())
|
||||||
|
SSL_set_SSL_CTX(ssl, it->second);
|
||||||
|
// No match (an unconfigured hostname, or a typo'd Host that still
|
||||||
|
// resolves here via DNS) - fall through and keep whatever SSL_CTX
|
||||||
|
// this SSL* already has, which is the base `ctx` SSL_new() was
|
||||||
|
// constructed from. Exactly the same cert a pre-SNI client (or
|
||||||
|
// one sending no SNI at all) already gets today.
|
||||||
|
}
|
||||||
|
return SSL_TLSEXT_ERR_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
void TLS::addSNIContext(const std::string &hostname, TLSInfo *tlsInfo) {
|
||||||
|
SSL_CTX *newCtx = buildContext(tlsInfo);
|
||||||
|
sniContexts[hostname] = newCtx;
|
||||||
|
if(!sniCallbackRegistered) {
|
||||||
|
SSL_CTX_set_tlsext_servername_callback(ctx, sniCallback);
|
||||||
|
SSL_CTX_set_tlsext_servername_arg(ctx, this);
|
||||||
|
sniCallbackRegistered = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void TLS::registerSocket(int fd) {
|
void TLS::registerSocket(int fd) {
|
||||||
initialized = true;
|
|
||||||
int ret;
|
int ret;
|
||||||
|
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_3) << "TLS socket initializing on socket " << fd << "...";
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "TLS socket initializing on socket " << fd << "...";
|
||||||
@@ -109,6 +211,32 @@ namespace core {
|
|||||||
// if(!SSL_set_generate_session_id(ssl, generate_session_id))
|
// if(!SSL_set_generate_session_id(ssl, generate_session_id))
|
||||||
// throw std::string("Error setting session identifier callback.");
|
// throw std::string("Error setting session identifier callback.");
|
||||||
|
|
||||||
|
// Was set unconditionally as the FIRST statement in this
|
||||||
|
// function (before `ssl` was even assigned) - a flag meant to
|
||||||
|
// mean "ssl is a valid, ready-to-use SSL*" needs to become true
|
||||||
|
// only once that's actually true, at the end, not the start.
|
||||||
|
// Previously set but never actually READ anywhere either -
|
||||||
|
// sendData()/receiveData() below now check it before touching
|
||||||
|
// `ssl` at all. See their own doc comments for the real,
|
||||||
|
// confirmed crash this fixes: a brand-new TLS session's own
|
||||||
|
// greeting (queued in onConnected(), see e.g. IMAPSession.h)
|
||||||
|
// gets written via Socket::write() -> resetSocket(), which - deep
|
||||||
|
// inside TCPServer::accept(), BEFORE TCPServer::connectionRequest()
|
||||||
|
// ever calls this session's own performTLSHandshake() - makes the
|
||||||
|
// fd immediately eligible for an EPOLLWRNORM event on a SEPARATE
|
||||||
|
// epoll worker thread. That thread's TCPSocket::sendData() takes
|
||||||
|
// ioLock (see its own doc comment) and calls straight into
|
||||||
|
// SSL_write() on `ssl`, which is genuinely uninitialized garbage
|
||||||
|
// (TLS.h explicitly documents `ssl` has no default member
|
||||||
|
// initializer) until THIS function runs - ioLock alone doesn't
|
||||||
|
// prevent it, since performTLSHandshake() (the only other place
|
||||||
|
// that takes ioLock) hasn't even been called yet at that point.
|
||||||
|
// Confirmed live via gdb under a mixed-protocol connection-churn
|
||||||
|
// stress test: SIGSEGV inside libssl.so's SSL_write(), called from
|
||||||
|
// TCPSocket::sendData() with ioGuard already held, while
|
||||||
|
// registerSocket()/acceptSocket() for that same session were still
|
||||||
|
// pending on the accepting thread.
|
||||||
|
initialized = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLS::acceptSocket() {
|
void TLS::acceptSocket() {
|
||||||
@@ -134,14 +262,22 @@ namespace core {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void TLS::receiveData(coreutils::ZString &buffer) {
|
int TLS::receiveData(coreutils::ZString &buffer) {
|
||||||
|
|
||||||
|
// `ssl` is genuinely uninitialized until registerSocket() has
|
||||||
|
// fully run (see its own doc comment on `initialized` for the
|
||||||
|
// real crash this prevents) - a racing thread landing here first
|
||||||
|
// just gets "nothing yet", exactly like a real SSL_ERROR_WANT_READ
|
||||||
|
// would report, rather than touching a garbage pointer.
|
||||||
|
if (!initialized)
|
||||||
|
return -1;
|
||||||
|
|
||||||
int len;
|
int len;
|
||||||
std::cout << "receiveData TLS" << std::endl;
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "receiveData TLS on socket.";
|
||||||
|
|
||||||
if((len = ::SSL_read(ssl, buffer.getData(), buffer.getLength())) >= 0) {
|
if((len = ::SSL_read(ssl, buffer.getData(), buffer.getLength())) >= 0) {
|
||||||
std::cout << "receiveData TLS...len=" << len << ":" << buffer << std::endl;
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "receiveData TLS...len=" << len;
|
||||||
// onDataReceived(buffer);
|
return len;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
switch (SSL_get_error(ssl, len)) {
|
switch (SSL_get_error(ssl, len)) {
|
||||||
@@ -161,6 +297,52 @@ namespace core {
|
|||||||
coreutils::Log(coreutils::LOG_DEBUG_3) << "Unknown ERROR on ssl_read.";
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "Unknown ERROR on ssl_read.";
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
int TLS::sendData(const char *data, int length) {
|
||||||
|
|
||||||
|
// Same "ssl isn't ready yet" guard as receiveData() - see
|
||||||
|
// registerSocket()'s doc comment on `initialized` for the real,
|
||||||
|
// confirmed crash this prevents (SIGSEGV in SSL_write() on a
|
||||||
|
// still-uninitialized `ssl`, reached via a brand-new session's own
|
||||||
|
// greeting racing ahead of its own TLS handshake). Returning <= 0
|
||||||
|
// here is already the exact case Socket::writeSocket() treats as
|
||||||
|
// "nothing sent this round, leave it queued and retry on the next
|
||||||
|
// EPOLLWRNORM" - no special-casing needed at any call site.
|
||||||
|
if (!initialized)
|
||||||
|
return -1;
|
||||||
|
|
||||||
|
int len;
|
||||||
|
|
||||||
|
if((len = ::SSL_write(ssl, data, length)) >= 0) {
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "sendData TLS...len=" << len;
|
||||||
|
lastSendWantedRead = false;
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
lastSendWantedRead = false;
|
||||||
|
switch (SSL_get_error(ssl, len)) {
|
||||||
|
case SSL_ERROR_SSL:
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_SSL on ssl_write. error=" << errno;
|
||||||
|
break;
|
||||||
|
case SSL_ERROR_WANT_READ:
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_WANT_READ on ssl_write.";
|
||||||
|
lastSendWantedRead = true;
|
||||||
|
break;
|
||||||
|
case SSL_ERROR_WANT_WRITE:
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_WANT_WRITE on ssl_write.";
|
||||||
|
break;
|
||||||
|
case SSL_ERROR_SYSCALL:
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_SYSCALL on ssl_write. errno=" << errno;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_3) << "Unknown ERROR on ssl_write.";
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
#include "ZString.h"
|
#include "ZString.h"
|
||||||
#include "TLSInfo.h"
|
#include "TLSInfo.h"
|
||||||
#include <openssl/ssl.h>
|
#include <openssl/ssl.h>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
@@ -46,13 +48,72 @@ namespace core {
|
|||||||
|
|
||||||
void createContext(TLSInfo *tlsInfo);
|
void createContext(TLSInfo *tlsInfo);
|
||||||
|
|
||||||
SSL_CTX *ctx;
|
///
|
||||||
|
/// Registers a second (or third, etc.) certificate/key pair for a
|
||||||
|
/// specific hostname on THIS SAME listening socket, via TLS's
|
||||||
|
/// Server Name Indication (SNI) extension - lets one TCPServer
|
||||||
|
/// terminate TLS for multiple unrelated domains, each with its own
|
||||||
|
/// real certificate, without needing a separate listening port or
|
||||||
|
/// process per domain. Must be called after createContext() (or the
|
||||||
|
/// TLSInfo* constructor, which calls it) has already established the
|
||||||
|
/// base `ctx` - that base context keeps serving as both the
|
||||||
|
/// fallback for hostnames not registered here AND the cert offered
|
||||||
|
/// to any client that sends no SNI hostname at all (a bare-IP
|
||||||
|
/// request, or any TLS client old enough to predate SNI). Callers
|
||||||
|
/// that never call this at all (every existing single-site
|
||||||
|
/// TLSInfo* user - BARANTMail, Zephora, ClockPlanet, and a
|
||||||
|
/// single-site APIServer config) see zero behavior change: the SNI
|
||||||
|
/// callback is only ever registered on `ctx` the first time this is
|
||||||
|
/// called, not unconditionally in createContext().
|
||||||
|
///
|
||||||
|
void addSNIContext(const std::string &hostname, TLSInfo *tlsInfo);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Build a server SSL_CTX from tlsInfo without attaching it to any
|
||||||
|
/// object. Used by createContext() for implicit-TLS listeners and by
|
||||||
|
/// TCPServer::enableStartTLS() for a context that plain-text sessions
|
||||||
|
/// only switch to on request (STARTTLS). Throws coreutils::Exception
|
||||||
|
/// if the certificate or key can't be loaded.
|
||||||
|
///
|
||||||
|
|
||||||
|
static SSL_CTX *buildContext(TLSInfo *tlsInfo);
|
||||||
|
|
||||||
|
// A never-configured TLS object (either the listening TCPServer
|
||||||
|
// itself when constructed with tlsInfo=NULL, or a TCPSession spawned
|
||||||
|
// from one via TLS(SSL_CTX*)) must default to a real NULL here, not
|
||||||
|
// garbage - TCPSocket::receiveData()/sendData() key their TLS-vs-
|
||||||
|
// plain dispatch on this exact value (see TCPSocket.cpp).
|
||||||
|
SSL_CTX *ctx = NULL;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
void receiveData(coreutils::ZString &buffer);
|
int receiveData(coreutils::ZString &buffer);
|
||||||
|
int sendData(const char *data, int length);
|
||||||
void registerSocket(int fd);
|
void registerSocket(int fd);
|
||||||
void acceptSocket();
|
void acceptSocket();
|
||||||
|
|
||||||
|
///
|
||||||
|
/// Bytes OpenSSL has already decrypted and is holding for this
|
||||||
|
/// connection but that haven't been returned by receiveData() yet.
|
||||||
|
/// The socket is edge-triggered (EPOLLET), so these never generate
|
||||||
|
/// another EPOLLIN on their own - TCPSocket::receiveData() drains
|
||||||
|
/// them before giving the event back. See its own comment.
|
||||||
|
///
|
||||||
|
|
||||||
|
int pendingBytes();
|
||||||
|
|
||||||
|
protected:
|
||||||
|
// Set by sendData() when the last SSL_write() failed specifically
|
||||||
|
// with SSL_ERROR_WANT_READ (needs a READ to make progress - e.g.
|
||||||
|
// mid-handshake application data, or a post-handshake session
|
||||||
|
// ticket exchange) rather than any other reason. TCPSocket::
|
||||||
|
// sendNeedsRead() reads this (protected, so a subclass can reach
|
||||||
|
// it directly) to tell Socket::writeSocket()/resetSocket() not to
|
||||||
|
// busy-spin retrying the write via EPOLLWRNORM - see their own
|
||||||
|
// doc comments for the confirmed real damage (a 15GB+ debug log,
|
||||||
|
// and every affected connection dropped before ever reading the
|
||||||
|
// client's first command) this caused when unaddressed.
|
||||||
|
bool lastSendWantedRead = false;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
char *sip_cacert = (char *)"../testkeys/certs/pbxca.crt";
|
char *sip_cacert = (char *)"../testkeys/certs/pbxca.crt";
|
||||||
char *sip_cert = (char *)"../testkeys/certs/pbxserver.crt";
|
char *sip_cert = (char *)"../testkeys/certs/pbxserver.crt";
|
||||||
@@ -60,6 +121,22 @@ namespace core {
|
|||||||
bool initialized = false;
|
bool initialized = false;
|
||||||
SSL *ssl;
|
SSL *ssl;
|
||||||
|
|
||||||
|
|
||||||
|
// Owns every SSL_CTX* built by addSNIContext() (the base `ctx` is
|
||||||
|
// owned/freed the same way it always was, untouched by this map).
|
||||||
|
// Keyed by hostname exactly as configured - matched case-
|
||||||
|
// insensitively against the ClientHello's SNI value in the
|
||||||
|
// callback (see TLS.cpp).
|
||||||
|
std::map<std::string, SSL_CTX *> sniContexts;
|
||||||
|
bool sniCallbackRegistered = false;
|
||||||
|
|
||||||
|
// OpenSSL's own SSL_CTX_set_tlsext_servername_callback signature -
|
||||||
|
// a static member (not a free function) so it can reach the owning
|
||||||
|
// TLS instance's private sniContexts via the `arg` parameter
|
||||||
|
// (SSL_CTX_set_tlsext_servername_arg(ctx, this), set alongside the
|
||||||
|
// callback itself in addSNIContext()).
|
||||||
|
static int sniCallback(SSL *ssl, int *ad, void *arg);
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+122
-11
@@ -1,13 +1,40 @@
|
|||||||
#include "Thread.h"
|
#include "Thread.h"
|
||||||
#include "EPoll.h"
|
#include "EPoll.h"
|
||||||
|
#include "TCPServer.h"
|
||||||
|
#include "INotify.h"
|
||||||
#include <sys/epoll.h>
|
#include <sys/epoll.h>
|
||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
Thread::Thread(EPoll &ePoll) : ePoll(ePoll) {}
|
Thread::Thread(EPoll &ePoll) : ePoll(ePoll), _thread(NULL), thread(NULL) {}
|
||||||
Thread::Thread(EPoll &ePoll, ThreadScope *scope) : ePoll(ePoll) {}
|
// Previously discarded `scope` entirely (never assigned to the `thread`
|
||||||
|
// member) - a real, live bug found while adding the first actual caller
|
||||||
|
// of this constructor (APIServer's MysqlThreadScope): the whole point
|
||||||
|
// of passing a scope in was to have it invoked from run() below, which
|
||||||
|
// silently never happened.
|
||||||
|
Thread::Thread(EPoll &ePoll, ThreadScope *scope) : ePoll(ePoll), _thread(NULL), thread(scope) {}
|
||||||
|
|
||||||
Thread::~Thread() {}
|
// Was empty - _thread (heap-allocated in start()) was never joined or
|
||||||
|
// freed here. A joinable std::thread destroyed without join()/detach()
|
||||||
|
// calls std::terminate() immediately, which this leaked-pointer
|
||||||
|
// approach silently sidestepped: the wrapped OS thread just kept
|
||||||
|
// running - polling this Thread's EPoll reference, touching Socket
|
||||||
|
// objects registered with it - even after this object, its EPoll, and
|
||||||
|
// every one of those sockets had already been destroyed out from under
|
||||||
|
// it (confirmed live: an exception thrown during BARANTMail startup,
|
||||||
|
// after EPoll::start() had already spun up its worker pool, unwound
|
||||||
|
// the stack destructing EPoll and its registered sockets while those
|
||||||
|
// still-running threads kept dereferencing them, producing a real
|
||||||
|
// "double free or corruption" crash). join() first (skipped if already
|
||||||
|
// joined via EPoll::stop() having run normally) so the OS thread is
|
||||||
|
// actually gone before anything it might touch gets freed.
|
||||||
|
Thread::~Thread() {
|
||||||
|
if (_thread) {
|
||||||
|
if (_thread->joinable())
|
||||||
|
_thread->join();
|
||||||
|
delete _thread;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
void Thread::start() {
|
void Thread::start() {
|
||||||
_thread = new std::thread(&Thread::run, this);
|
_thread = new std::thread(&Thread::run, this);
|
||||||
@@ -41,6 +68,9 @@ namespace core {
|
|||||||
|
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << "Thread started with thread id " << threadId << ".";
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Thread started with thread id " << threadId << ".";
|
||||||
|
|
||||||
|
if(thread)
|
||||||
|
thread->onThreadStart();
|
||||||
|
|
||||||
count = 0;
|
count = 0;
|
||||||
|
|
||||||
struct epoll_event events[50];
|
struct epoll_event events[50];
|
||||||
@@ -51,27 +81,108 @@ namespace core {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
status = "WAITING";
|
status = "WAITING";
|
||||||
int rc = epoll_wait(ePoll.getDescriptor(), events, 50, -1);
|
// A finite timeout, not the previous -1 (wait forever), is what
|
||||||
|
// makes EPoll::stop() able to return at all: a thread idly
|
||||||
|
// blocked here with no socket activity would otherwise never
|
||||||
|
// re-check isStopping() above, so join()ing it (both
|
||||||
|
// EPoll::stop() and, now, ~Thread() itself) would hang forever.
|
||||||
|
// Costs up to a one-second shutdown latency.
|
||||||
|
int rc = epoll_wait(ePoll.getDescriptor(), events, 50, 1000);
|
||||||
status = "RUNNING";
|
status = "RUNNING";
|
||||||
|
|
||||||
if(rc < 0) {
|
if(rc < 0) {
|
||||||
// TODO: Make log entry indicating status received and ignore for now.
|
// TODO: Make log entry indicating status received and ignore for now.
|
||||||
} else if(rc == 0) {
|
} else if(rc == 0) {
|
||||||
break;
|
// Plain timeout, no socket activity - not itself a signal to
|
||||||
|
// stop (isStopping() above already decides that). Previously
|
||||||
|
// broke out of the loop unconditionally, which the old
|
||||||
|
// infinite wait never actually triggered in practice, but
|
||||||
|
// would have silently ended this thread after any single
|
||||||
|
// idle second once the wait became finite.
|
||||||
} else if(rc > 0) {
|
} else if(rc > 0) {
|
||||||
for(int ix = 0; ix < rc; ++ix) {
|
for(int ix = 0; ix < rc; ++ix) {
|
||||||
++count;
|
++count;
|
||||||
if(((Socket *)events[ix].data.ptr)->eventReceived(events[ix], ++ePoll.eventId)) {
|
// events[ix].data.ptr is a raw pointer of UNKNOWN validity at
|
||||||
// coreutils::Log(coreutils::LOG_DEBUG_4) << "return true";
|
// this point - it could be a live TCPSession, a listening
|
||||||
// ePoll.resetSocket((Socket *)events[ix].data.ptr);
|
// TCPServer/ConsoleServer (immortal, never shared_ptr-owned),
|
||||||
|
// or - the case this whole block exists to handle safely - a
|
||||||
|
// stale/duplicate event for a TCPSession something else
|
||||||
|
// already fully destroyed and freed on another thread.
|
||||||
|
//
|
||||||
|
// A first version of this fix used dynamic_cast<TCPSession*>
|
||||||
|
// to tell these apart, and a version before that cast
|
||||||
|
// straight to Socket* unconditionally (the original code).
|
||||||
|
// BOTH require reading the pointed-to object's own memory
|
||||||
|
// (its vtable, at minimum) to work - confirmed live via
|
||||||
|
// AddressSanitizer that dynamic_cast itself segfaults on a
|
||||||
|
// stale pointer, before any pin()-based safety logic even
|
||||||
|
// runs. TCPSession::tryGet() and TCPServer::isKnownListening
|
||||||
|
// Socket() below never dereference this raw pointer for their
|
||||||
|
// own check - only compare its address against a registry -
|
||||||
|
// so they're safe to call on literally any value here,
|
||||||
|
// known-good or not.
|
||||||
|
void *rawPtr = events[ix].data.ptr;
|
||||||
|
std::shared_ptr<TCPSession> pinned = TCPSession::tryGet(rawPtr);
|
||||||
|
if(pinned) {
|
||||||
|
if(pinned->eventReceived(events[ix], ++ePoll.eventId)) {
|
||||||
|
// keep alive - pinned goes out of scope at the end of
|
||||||
|
// this iteration, releasing this thread's temporary
|
||||||
|
// reference; real ownership (TCPServer::sessions) is
|
||||||
|
// unaffected.
|
||||||
} else {
|
} else {
|
||||||
((Socket *)events[ix].data.ptr)->shutDown = true;
|
pinned->shutDown = true;
|
||||||
// coreutils::Log(coreutils::LOG_DEBUG_4) << "return false";
|
// Was `delete (Socket *)events[ix].data.ptr;`
|
||||||
delete (Socket *)events[ix].data.ptr;
|
// unconditionally, for every socket type, including
|
||||||
|
// real sessions another thread might be mid-call on
|
||||||
|
// right now via its own pin()'d reference. Dropping
|
||||||
|
// the one real owning reference is what actually
|
||||||
|
// frees the object - immediately, if this thread's
|
||||||
|
// own `pinned` (about to go out of scope) was the
|
||||||
|
// last one outstanding; safely deferred otherwise.
|
||||||
|
pinned->server->removeFromSessionList(pinned.get());
|
||||||
|
}
|
||||||
|
} else if(TCPServer::isKnownListeningSocket(rawPtr)) {
|
||||||
|
// Known-immortal (see its own doc comment) - safe to call
|
||||||
|
// directly, unchanged from the original behavior. A
|
||||||
|
// listening socket's own eventReceived() returning false
|
||||||
|
// isn't something that happens in normal operation, but
|
||||||
|
// preserved as-is for parity with the pre-existing code.
|
||||||
|
Socket *rawSocket = (Socket *)rawPtr;
|
||||||
|
if(rawSocket->eventReceived(events[ix], ++ePoll.eventId)) {
|
||||||
|
// keep alive
|
||||||
|
} else {
|
||||||
|
rawSocket->shutDown = true;
|
||||||
|
delete rawSocket;
|
||||||
|
}
|
||||||
|
} else if(INotify::isKnownINotify(rawPtr)) {
|
||||||
|
// A third category of long-lived, non-TCPSession Socket -
|
||||||
|
// see INotify::isKnownINotify()'s own doc comment for the
|
||||||
|
// real, confirmed-live bug this fixes: every INotify event
|
||||||
|
// (e.g. BARANTMail's mail-queue delivery watch) previously
|
||||||
|
// fell all the way through to the "unrecognized" branch
|
||||||
|
// below and was silently dropped forever.
|
||||||
|
Socket *rawSocket = (Socket *)rawPtr;
|
||||||
|
if(rawSocket->eventReceived(events[ix], ++ePoll.eventId)) {
|
||||||
|
// keep alive
|
||||||
|
} else {
|
||||||
|
rawSocket->shutDown = true;
|
||||||
|
delete rawSocket;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Neither registry recognizes this pointer - almost
|
||||||
|
// certainly a stale/duplicate epoll event for a
|
||||||
|
// TCPSession that has already been fully destroyed and
|
||||||
|
// unregistered elsewhere. There is nothing safe to do
|
||||||
|
// with it except leave it alone entirely.
|
||||||
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Ignoring stale/unrecognized epoll event (pointer " << rawPtr << ")";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if(thread)
|
||||||
|
thread->onThreadEnd();
|
||||||
|
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << "Thread ending with thread id " << threadId << ".";
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Thread ending with thread id " << threadId << ".";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,34 @@
|
|||||||
|
|
||||||
namespace core {
|
namespace core {
|
||||||
|
|
||||||
|
///
|
||||||
|
/// ThreadScope
|
||||||
|
///
|
||||||
|
/// Extension point for per-OS-thread setup/teardown in an EPoll worker
|
||||||
|
/// pool. EPoll's threads are long-lived (one persistent event loop per
|
||||||
|
/// thread, for the process's whole lifetime, not spawned per-request) -
|
||||||
|
/// onThreadStart() runs once at the top of each thread, before it
|
||||||
|
/// enters its event loop; onThreadEnd() runs once as that thread is
|
||||||
|
/// shutting down. A single ThreadScope instance is shared across every
|
||||||
|
/// worker thread (passed to EPoll::start()), so overrides should only
|
||||||
|
/// touch thread-LOCAL state from these hooks, never the ThreadScope
|
||||||
|
/// object's own fields, without their own synchronization.
|
||||||
|
///
|
||||||
|
/// Concrete motivating case: a C library that requires explicit
|
||||||
|
/// per-thread initialization before use from a multi-threaded program
|
||||||
|
/// (e.g. the MySQL client library's mysql_thread_init()/
|
||||||
|
/// mysql_thread_end() - see APIServer's MysqlThreadScope) has no other
|
||||||
|
/// clean way to hook into an EPoll worker thread's lifetime.
|
||||||
|
///
|
||||||
|
|
||||||
class ThreadScope {
|
class ThreadScope {
|
||||||
|
|
||||||
public:
|
public:
|
||||||
ThreadScope() {}
|
ThreadScope() {}
|
||||||
|
virtual ~ThreadScope() {}
|
||||||
|
|
||||||
|
virtual void onThreadStart() {}
|
||||||
|
virtual void onThreadEnd() {}
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -2,17 +2,27 @@
|
|||||||
#include <sys/timerfd.h>
|
#include <sys/timerfd.h>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
|
||||||
namespace core {
|
namespace core
|
||||||
|
{
|
||||||
|
|
||||||
Timer::Timer(EPoll &ePoll, double delay = 0.0f) : Socket(ePoll, "Timer") {
|
Timer::Timer(EPoll &ePoll, double delay = 0.0f) : Socket(ePoll, "Timer")
|
||||||
|
{
|
||||||
|
// See preventSelfDelete's own doc comment on Socket - a Timer is
|
||||||
|
// always a subobject of some larger composite (e.g. ZephoraSession
|
||||||
|
// : TCPSession, Timer), never a standalone connection, so its own
|
||||||
|
// eventReceived() must never be allowed to signal "delete me" to
|
||||||
|
// Thread::run()'s generic dispatch.
|
||||||
|
preventSelfDelete = true;
|
||||||
setDescriptor(timerfd_create(CLOCK_REALTIME, 0));
|
setDescriptor(timerfd_create(CLOCK_REALTIME, 0));
|
||||||
setTimer(delay);
|
setTimer(delay);
|
||||||
}
|
}
|
||||||
|
|
||||||
Timer::~Timer() {
|
Timer::~Timer()
|
||||||
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
void Timer::setTimer(double delay) {
|
void Timer::setTimer(double delay)
|
||||||
|
{
|
||||||
|
|
||||||
double integer;
|
double integer;
|
||||||
double fraction;
|
double fraction;
|
||||||
@@ -29,10 +39,10 @@ namespace core {
|
|||||||
timer.it_value.tv_nsec = (int)(fraction * 1000000000);
|
timer.it_value.tv_nsec = (int)(fraction * 1000000000);
|
||||||
|
|
||||||
timerfd_settime(getDescriptor(), 0, &timer, NULL);
|
timerfd_settime(getDescriptor(), 0, &timer, NULL);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Timer::clearTimer() {
|
void Timer::clearTimer()
|
||||||
|
{
|
||||||
|
|
||||||
struct itimerspec timer;
|
struct itimerspec timer;
|
||||||
|
|
||||||
@@ -44,18 +54,21 @@ namespace core {
|
|||||||
timerfd_settime(getDescriptor(), 0, &timer, NULL);
|
timerfd_settime(getDescriptor(), 0, &timer, NULL);
|
||||||
}
|
}
|
||||||
|
|
||||||
double Timer::getElapsed() {
|
double Timer::getElapsed()
|
||||||
|
{
|
||||||
struct itimerspec timer;
|
struct itimerspec timer;
|
||||||
timerfd_gettime(getDescriptor(), &timer);
|
timerfd_gettime(getDescriptor(), &timer);
|
||||||
double toTimeout = (double)((timer.it_value.tv_sec * 1000000000L) + timer.it_value.tv_nsec) / 1000000000L;
|
double toTimeout = (double)((timer.it_value.tv_sec * 1000000000L) + timer.it_value.tv_nsec) / 1000000000L;
|
||||||
return delayValue - toTimeout;
|
return delayValue - toTimeout;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Timer::onDataReceived(std::string data) {
|
void Timer::onDataReceived(std::string data)
|
||||||
|
{
|
||||||
onTimeout();
|
onTimeout();
|
||||||
}
|
}
|
||||||
|
|
||||||
double Timer::getEpoch() {
|
double Timer::getEpoch()
|
||||||
|
{
|
||||||
return (double)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() / 1000000000L;
|
return (double)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() / 1000000000L;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
#ifndef __Timer_h__
|
#ifndef __Timer_h__
|
||||||
#define __Timer_h__
|
#define __Timer_h__
|
||||||
|
|
||||||
#include "Socket.h"
|
|
||||||
#include "EPoll.h"
|
#include "EPoll.h"
|
||||||
|
#include "Socket.h"
|
||||||
|
|
||||||
namespace core {
|
namespace core
|
||||||
|
{
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Timer
|
/// Timer
|
||||||
@@ -15,7 +16,8 @@ namespace core {
|
|||||||
/// interface. It cannot be instantiated directly but must be extended.
|
/// interface. It cannot be instantiated directly but must be extended.
|
||||||
///
|
///
|
||||||
|
|
||||||
class Timer : Socket {
|
class Timer : Socket
|
||||||
|
{
|
||||||
|
|
||||||
public:
|
public:
|
||||||
Timer(EPoll &ePoll);
|
Timer(EPoll &ePoll);
|
||||||
@@ -48,7 +50,6 @@ namespace core {
|
|||||||
double getEpoch();
|
double getEpoch();
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|
||||||
///
|
///
|
||||||
/// This method is called when the time out occurs.
|
/// This method is called when the time out occurs.
|
||||||
///
|
///
|
||||||
@@ -58,7 +59,6 @@ namespace core {
|
|||||||
private:
|
private:
|
||||||
void onDataReceived(std::string data) override;
|
void onDataReceived(std::string data) override;
|
||||||
double delayValue;
|
double delayValue;
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user