Compare commits
23
Commits
1a15f6ced8
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8514d9689 | ||
|
|
c0e1d87ac1 | ||
|
|
4918654715 | ||
|
|
4bfede1342 | ||
|
|
dc6b1dcc56 | ||
|
|
6483729de3 | ||
|
|
1d3d30cd05 | ||
|
|
d058322cc6 | ||
|
|
8009564a7a | ||
|
|
0bb926a264 | ||
|
|
3383595296 | ||
|
|
2c65939788 | ||
|
|
1e9b5f1016 | ||
|
|
cfc0b19418 | ||
|
|
bee8b92a6d | ||
|
|
381ed86875 | ||
|
|
3609ed603e | ||
|
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,23 @@ 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));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+7
-2
@@ -12,8 +12,13 @@ namespace core {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
|
|||||||
@@ -11,6 +11,17 @@ 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;
|
||||||
|
|||||||
@@ -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) {
|
||||||
|
|||||||
@@ -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();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+112
-4
@@ -4,6 +4,8 @@
|
|||||||
#include "Log.h"
|
#include "Log.h"
|
||||||
#include "ZString.h"
|
#include "ZString.h"
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <poll.h>
|
||||||
|
#include <sys/socket.h>
|
||||||
|
|
||||||
namespace core
|
namespace core
|
||||||
{
|
{
|
||||||
@@ -128,7 +130,6 @@ namespace core
|
|||||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM";
|
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM";
|
||||||
writeSocket();
|
writeSocket();
|
||||||
}
|
}
|
||||||
inHandler = false;
|
|
||||||
// A graceful shutdown() (session.terminate() -> "goodbye" reply
|
// A graceful shutdown() (session.terminate() -> "goodbye" reply
|
||||||
// queued via write(), then shutdown() called - see e.g. IMAP's
|
// queued via write(), then shutdown() called - see e.g. IMAP's
|
||||||
// LOGOUT/POP3's QUIT/SMTP's QUIT) used to make keepAlive false
|
// LOGOUT/POP3's QUIT/SMTP's QUIT) used to make keepAlive false
|
||||||
@@ -145,7 +146,7 @@ namespace core
|
|||||||
// drain to a peer that's already gone is pointless, not graceful)
|
// drain to a peer that's already gone is pointless, not graceful)
|
||||||
// - gives that queued reply a real chance to go out before this
|
// - gives that queued reply a real chance to go out before this
|
||||||
// socket actually closes.
|
// socket actually closes.
|
||||||
bool keepAlive = !shutDown || (fifo.size() > 0 && !readHangup);
|
bool keepAlive = preventSelfDelete || !shutDown || (fifo.size() > 0 && !readHangup);
|
||||||
|
|
||||||
// resetSocket() re-arms this fd via EPOLL_CTL_MOD, which makes it
|
// resetSocket() re-arms this fd via EPOLL_CTL_MOD, which makes it
|
||||||
// immediately eligible for delivery to ANY worker thread's
|
// immediately eligible for delivery to ANY worker thread's
|
||||||
@@ -162,8 +163,45 @@ namespace core
|
|||||||
// the last thing that ever touches `this`, with the return value
|
// the last thing that ever touches `this`, with the return value
|
||||||
// already captured in a local (`keepAlive`) beforehand.
|
// already captured in a local (`keepAlive`) beforehand.
|
||||||
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor();
|
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor();
|
||||||
if(keepAlive)
|
// 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;
|
||||||
resetSocket();
|
resetSocket();
|
||||||
|
lock.unlock();
|
||||||
|
}
|
||||||
|
// else: this object is about to be delete()'d by Thread::run() the
|
||||||
|
// moment this call returns, unconditionally, regardless of
|
||||||
|
// 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;
|
return keepAlive;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,6 +249,28 @@ namespace core
|
|||||||
return ::write(descriptor, data, 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();
|
||||||
@@ -272,6 +332,26 @@ namespace core
|
|||||||
// the confirmed real damage (a 55GB, then 12.9GB debug log)
|
// the confirmed real damage (a 55GB, then 12.9GB debug log)
|
||||||
// this caused before being noticed.
|
// this caused before being noticed.
|
||||||
coreutils::Log(coreutils::LOG_EXCEPT) << "Socket " << getDescriptor() << ": " << consecutiveWriteStalls << " consecutive writes made zero progress - giving up and shutting down.";
|
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");
|
shutdown("stuck write retry loop - no progress after repeated attempts");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -283,8 +363,36 @@ 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()) {
|
||||||
resetSocket();
|
if(!inHandler)
|
||||||
|
resetSocket();
|
||||||
lock.unlock();
|
lock.unlock();
|
||||||
}
|
}
|
||||||
return 1;
|
return 1;
|
||||||
|
|||||||
@@ -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);
|
||||||
@@ -193,13 +211,33 @@ namespace core {
|
|||||||
|
|
||||||
virtual bool sendNeedsRead() { return false; }
|
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.
|
||||||
|
|||||||
+48
-23
@@ -1,49 +1,68 @@
|
|||||||
#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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
int Subscription::subscribe(TCPSession &session) {
|
int Subscription::subscribe(TCPSession &session) {
|
||||||
if (handler)
|
if (handler)
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,10 +97,10 @@ 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("");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
+17
-12
@@ -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;
|
||||||
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+156
-34
@@ -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")
|
||||||
subscriptions.insert(std::make_pair(request[1].str(), newSubscription));
|
{
|
||||||
newSubscription->owner = &session;
|
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));
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
return 1;
|
return 1;
|
||||||
} else if (request[0].equals("catalog")) {
|
}
|
||||||
|
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);
|
subscription->event(out);
|
||||||
return 1;
|
return 1;
|
||||||
} else if (subscription->mode == "*SUBSCRIBERS") {
|
}
|
||||||
if (subscription->ifSubscriber(session)) {
|
else if (subscription->mode == "*SUBSCRIBERS")
|
||||||
subscription->event(out);
|
{
|
||||||
return 1;
|
if (subscription->ifSubscriber(session))
|
||||||
}
|
{
|
||||||
} else if (subscription->mode == "*AUTHOR") {
|
|
||||||
if (subscription->owner == &session) {
|
|
||||||
subscription->event(out);
|
subscription->event(out);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-15
@@ -2,33 +2,39 @@
|
|||||||
#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 {
|
||||||
|
|
||||||
class SubscriptionHandlerFactory;
|
//*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 SubscriptionManager : public Command {
|
class SubscriptionHandlerFactory;
|
||||||
|
|
||||||
public:
|
class SubscriptionManager : public Command {
|
||||||
|
|
||||||
int add(Subscription &subscription);
|
public:
|
||||||
int removeSessionSubscriptions(TCPSession &session);
|
int add(Subscription &subscription);
|
||||||
int processCommand(coreutils::ZString &request, TCPSession &session) override;
|
int removeSessionSubscriptions(TCPSession &session);
|
||||||
|
int processCommand(coreutils::ZString &request, TCPSession &session) override;
|
||||||
|
bool onClearSubscription(coreutils::MString temp, coreutils::MString key);
|
||||||
|
SubscriptionHandlerFactory *factory = NULL;
|
||||||
|
|
||||||
SubscriptionHandlerFactory *factory = NULL;
|
private:
|
||||||
|
Subscription *subscription;
|
||||||
private:
|
std::map<coreutils::MString, Subscription *> subscriptions;
|
||||||
Subscription *subscription;
|
Subscription *newSubscription;
|
||||||
std::map<std::string, Subscription *> subscriptions;
|
std::mutex lock;
|
||||||
Subscription *newSubscription;
|
|
||||||
std::mutex lock;
|
};
|
||||||
};
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+215
-59
@@ -3,21 +3,67 @@
|
|||||||
#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
|
||||||
throw coreutils::Exception("Error on listen to socket");
|
// 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");
|
||||||
|
}
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
|
||||||
|
listeningSockets().insert(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
setDescriptor(fd);
|
||||||
}
|
}
|
||||||
|
|
||||||
TCPServer::~TCPServer() {
|
TCPServer::~TCPServer() {
|
||||||
@@ -27,25 +73,51 @@ 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,
|
||||||
// Must run ON THE SESSION, not `this` (the listening server) - the
|
// starts its TLS handshake (on the session, not on `this`) before
|
||||||
// unqualified registerSocket()/acceptSocket() calls this replaced
|
// arming the fd - see its own comment.
|
||||||
// built the SSL* handshake state on the SERVER's own TLS-base
|
accept();
|
||||||
// member instead of the newly accepted session's, leaving every
|
|
||||||
// session's own `ssl` uninitialized and segfaulting the first time
|
|
||||||
// real data arrived on it (SSL_read() against a never-SSL_new()'d
|
|
||||||
// pointer - confirmed via gdb). Sessions already correctly inherit
|
|
||||||
// this server's SSL_CTX at construction (TCPSession's own
|
|
||||||
// TLS(SSL_CTX*)-taking constructor) - performTLSHandshake() just
|
|
||||||
// needed to actually be invoked on that object.
|
|
||||||
if (session && tlsInfo)
|
|
||||||
session->performTLSHandshake();
|
|
||||||
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) {
|
void TCPServer::receiveData(coreutils::ZString &buffer) {
|
||||||
// See this override's own doc comment in TCPServer.h - the
|
// See this override's own doc comment in TCPServer.h - the
|
||||||
// listening socket always uses the plain read()/ENOTCONN detection
|
// listening socket always uses the plain read()/ENOTCONN detection
|
||||||
@@ -56,40 +128,103 @@ namespace core {
|
|||||||
|
|
||||||
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.";
|
||||||
// }
|
return NULL;
|
||||||
// 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 << "'.";
|
TCPSession *session = NULL;
|
||||||
|
try {
|
||||||
|
session = getSocketAccept(ePoll);
|
||||||
}
|
}
|
||||||
catch (...) {
|
catch (...) {
|
||||||
coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization.";
|
coreutils::Log(coreutils::LOG_EXCEPT) << "Error creating session object; connection refused.";
|
||||||
|
close(fd);
|
||||||
|
return NULL;
|
||||||
}
|
}
|
||||||
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)
|
||||||
sessions.erase(cursor);
|
{
|
||||||
break;
|
// 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);
|
||||||
|
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) {
|
||||||
@@ -100,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);
|
||||||
@@ -116,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)
|
||||||
return session;
|
if (session->alias == alias)
|
||||||
return NULL;
|
return session;
|
||||||
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+136
-6
@@ -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 -
|
||||||
std::vector<TCPSession *> sessions;
|
/// 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<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,31 @@ 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
|
/// The listening socket itself is never a TLS peer - accepting a
|
||||||
/// connection on it surfaces as a plain read() failing with ENOTCONN
|
/// connection on it surfaces as a plain read() failing with ENOTCONN
|
||||||
@@ -159,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;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+21
-3
@@ -91,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
|
||||||
out.str("");
|
// 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("");
|
||||||
|
write(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool TCPSession::startTLS(SSL_CTX *ctx) {
|
||||||
|
send();
|
||||||
|
return TCPSocket::startTLS(ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPSession::terminate() {
|
void TCPSession::terminate() {
|
||||||
|
|||||||
+131
-3
@@ -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,10 +25,123 @@ namespace core {
|
|||||||
///
|
///
|
||||||
///
|
///
|
||||||
|
|
||||||
class TCPSession : public TCPSocket {
|
class TCPSession : public TCPSocket, public std::enable_shared_from_this<TCPSession> {
|
||||||
|
|
||||||
public:
|
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:
|
||||||
|
|
||||||
///
|
///
|
||||||
///
|
///
|
||||||
///
|
///
|
||||||
@@ -54,6 +170,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.
|
||||||
|
|||||||
+103
-24
@@ -40,18 +40,35 @@ namespace core {
|
|||||||
// session (set in TLS::createContext(), inherited by sessions via
|
// session (set in TLS::createContext(), inherited by sessions via
|
||||||
// TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h).
|
// TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h).
|
||||||
if(ctx) {
|
if(ctx) {
|
||||||
int len;
|
// Loop until OpenSSL has nothing decrypted left over. A single TLS
|
||||||
{
|
// record carries up to 16KB, but `buffer` is 4KB, so one SSL_read()
|
||||||
// Held only around the raw SSL_read call - released before
|
// can leave the rest of a record sitting inside OpenSSL. This socket
|
||||||
// onDataReceived() so the request-handling chain it triggers
|
// is edge-triggered (EPOLLET) and those bytes have already been
|
||||||
// (which reaches Socket::write()/outlock) never runs while
|
// pulled off the fd, so nothing would ever raise another EPOLLIN
|
||||||
// ioLock is held. See ioLock's own doc comment in TCPSocket.h.
|
// for them: the session would stall mid-stream until the peer
|
||||||
std::lock_guard<std::mutex> ioGuard(ioLock);
|
// happened to send something else. Small requests (HTTP headers,
|
||||||
len = TLS::receiveData(buffer);
|
// 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
|
||||||
if(len >= 0) {
|
// common case once STARTTLS is offered - does on every message.
|
||||||
coreutils::ZString zbuffer(buffer.getData(), len);
|
while(true) {
|
||||||
onDataReceived(zbuffer);
|
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 {
|
} else {
|
||||||
Socket::receiveData(buffer);
|
Socket::receiveData(buffer);
|
||||||
@@ -70,6 +87,21 @@ namespace core {
|
|||||||
return ctx && lastSendWantedRead;
|
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() {
|
void TCPSocket::performTLSHandshake() {
|
||||||
// registerSocket() makes this fd eligible for epoll dispatch to ANY
|
// registerSocket() makes this fd eligible for epoll dispatch to ANY
|
||||||
// worker thread immediately. ioLock MUST be acquired BEFORE that
|
// worker thread immediately. ioLock MUST be acquired BEFORE that
|
||||||
@@ -91,14 +123,19 @@ namespace core {
|
|||||||
// (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently
|
// (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently
|
||||||
// finishes a pending handshake on the next SSL_read/SSL_write,
|
// finishes a pending handshake on the next SSL_read/SSL_write,
|
||||||
// which ioLock already serializes against everything else.
|
// which ioLock already serializes against everything else.
|
||||||
|
performTLSHandshake(getDescriptor());
|
||||||
|
}
|
||||||
|
|
||||||
|
void TCPSocket::performTLSHandshake(int fd) {
|
||||||
std::lock_guard<std::mutex> ioGuard(ioLock);
|
std::lock_guard<std::mutex> ioGuard(ioLock);
|
||||||
registerSocket(getDescriptor());
|
registerSocket(fd);
|
||||||
acceptSocket();
|
acceptSocket();
|
||||||
}
|
}
|
||||||
|
|
||||||
void TCPSocket::onDataReceived(coreutils::ZString &data) {
|
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();
|
||||||
@@ -126,14 +163,37 @@ namespace core {
|
|||||||
// the bounded equivalent - it never looks past the length
|
// the bounded equivalent - it never looks past the length
|
||||||
// given, so "no CRLF yet" correctly comes back as "not
|
// given, so "no CRLF yet" correctly comes back as "not
|
||||||
// found" instead of reading off the end of the allocation.
|
// found" instead of reading off the end of the allocation.
|
||||||
char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize);
|
char *found;
|
||||||
char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize);
|
if (strictCRLF)
|
||||||
char *found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl);
|
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;
|
lineLength = found ? (int)(found - lineBuffer) : lineBufferSize;
|
||||||
if (lineLength == 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;
|
||||||
|
}
|
||||||
|
if (skippingLongLine || (maxLineLength && (size_t)lineLength > maxLineLength)) {
|
||||||
|
skippingLongLine = false;
|
||||||
|
onLineTooLong();
|
||||||
|
} else {
|
||||||
|
coreutils::ZString zLine(lineBuffer, lineLength);
|
||||||
|
onLineReceived(zLine);
|
||||||
|
}
|
||||||
|
if (discardInput)
|
||||||
break;
|
break;
|
||||||
coreutils::ZString zLine(lineBuffer, lineLength);
|
|
||||||
onLineReceived(zLine);
|
|
||||||
// lineLength < lineBufferSize is guaranteed by the break
|
// lineLength < lineBufferSize is guaranteed by the break
|
||||||
// above, so this first index is always in bounds; bump
|
// above, so this first index is always in bounds; bump
|
||||||
// past a lone '\r' only if there's still at least one more
|
// past a lone '\r' only if there's still at least one more
|
||||||
@@ -142,10 +202,14 @@ namespace core {
|
|||||||
// after it yet) leave it for the next read to resolve,
|
// after it yet) leave it for the next read to resolve,
|
||||||
// rather than reading lineBuffer[lineBufferSize], one past
|
// rather than reading lineBuffer[lineBufferSize], one past
|
||||||
// the allocation.
|
// the allocation.
|
||||||
if (lineBuffer[lineLength] == '\r')
|
if (strictCRLF)
|
||||||
++lineLength;
|
lineLength += 2;
|
||||||
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
|
else {
|
||||||
++lineLength;
|
if (lineBuffer[lineLength] == '\r')
|
||||||
|
++lineLength;
|
||||||
|
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
|
||||||
|
++lineLength;
|
||||||
|
}
|
||||||
lineBufferSize -= lineLength;
|
lineBufferSize -= lineLength;
|
||||||
if (lineBufferSize > 0)
|
if (lineBufferSize > 0)
|
||||||
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
|
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
|
||||||
@@ -154,6 +218,8 @@ namespace core {
|
|||||||
else if (lineBufferSize >= blockSize) {
|
else if (lineBufferSize >= blockSize) {
|
||||||
coreutils::ZString zBlock(lineBuffer, blockSize);
|
coreutils::ZString zBlock(lineBuffer, blockSize);
|
||||||
onBlockReceived(zBlock);
|
onBlockReceived(zBlock);
|
||||||
|
if (discardInput)
|
||||||
|
break;
|
||||||
lineBufferSize -= blockSize;
|
lineBufferSize -= blockSize;
|
||||||
if (lineBufferSize > 0)
|
if (lineBufferSize > 0)
|
||||||
memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize);
|
memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize);
|
||||||
@@ -170,7 +236,16 @@ namespace core {
|
|||||||
// changes, so the while(lineBufferSize > 0) loop above
|
// changes, so the while(lineBufferSize > 0) loop above
|
||||||
// never yields back to let more data arrive.
|
// never yields back to let more data arrive.
|
||||||
break;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,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;
|
||||||
}
|
}
|
||||||
|
|||||||
+127
@@ -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 {
|
||||||
|
|
||||||
@@ -150,6 +151,85 @@ namespace core {
|
|||||||
|
|
||||||
void performTLSHandshake();
|
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;
|
||||||
@@ -160,6 +240,53 @@ namespace core {
|
|||||||
int lineLength = 0;
|
int lineLength = 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
|
// Socket's own `lock` (guards receiveData) and `outlock` (guards
|
||||||
// writeSocket/the fifo) are two DIFFERENT mutexes - a thread
|
// writeSocket/the fifo) are two DIFFERENT mutexes - a thread
|
||||||
// handling EPOLLIN and a different thread handling EPOLLWRNORM for
|
// handling EPOLLIN and a different thread handling EPOLLWRNORM for
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|
||||||
@@ -65,65 +66,132 @@ 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));
|
||||||
for(int i = 0; i < CRYPTO_num_locks(); ++i)
|
for(int i = 0; i < CRYPTO_num_locks(); ++i)
|
||||||
pthread_mutex_init(&(lockarray[i]), NULL);
|
pthread_mutex_init(&(lockarray[i]), NULL);
|
||||||
CRYPTO_set_id_callback((unsigned long (*)())thread_id);
|
CRYPTO_set_id_callback((unsigned long (*)())thread_id);
|
||||||
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())))
|
});
|
||||||
throw coreutils::Exception("Error while setting server method SSLv23.");
|
}
|
||||||
SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
|
||||||
SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
|
void TLS::createContext(TLSInfo *tlsInfo) {
|
||||||
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
|
if(tlsInfo)
|
||||||
// SSL_CTX_set_generate_session_id(ctx, generate_session_id);
|
ctx = buildContext(tlsInfo);
|
||||||
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");
|
}
|
||||||
// _chain_file (not _file) - loads every certificate in the file,
|
|
||||||
// not just the first. A real Let's Encrypt fullchain.pem is the
|
// The per-context cert/key/cipher/verify setup, shared by
|
||||||
// leaf cert followed by the intermediate CA cert concatenated in
|
// createContext(), addSNIContext() (one context per extra hostname)
|
||||||
// one file specifically so a server can hand both to the client
|
// and TCPServer::enableStartTLS().
|
||||||
// in one shot; SSL_CTX_use_certificate_file() only ever reads the
|
SSL_CTX *TLS::buildContext(TLSInfo *tlsInfo) {
|
||||||
// first PEM block, silently dropping the intermediate - confirmed
|
initializeLibrary();
|
||||||
// via a real handshake against this exact fullchain.pem: clients
|
SSL_CTX *newCtx;
|
||||||
// got "unable to get local issuer certificate" because the server
|
if(!(newCtx = SSL_CTX_new(SSLv23_server_method())))
|
||||||
// only ever sent the leaf, never the intermediate needed to chain
|
throw coreutils::Exception("Error while setting server method SSLv23.");
|
||||||
// up to a root the client already trusts.
|
// A caller may now catch a bad certificate/key and carry on without
|
||||||
if(SSL_CTX_use_certificate_chain_file(ctx, tlsInfo->certificate.c_str()) <= 0)
|
// TLS (BARANTMail does, for STARTTLS) - don't leak the half-built
|
||||||
|
// context on the way out.
|
||||||
|
try {
|
||||||
|
SSL_CTX_set_mode(newCtx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
||||||
|
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.");
|
||||||
// Client-certificate verification (mutual TLS) is opt-in, not the
|
// Client-certificate verification (mutual TLS) is opt-in, not the
|
||||||
// default - a public-facing site (e.g. a real Let's Encrypt
|
// default - a public-facing site (e.g. a real Let's Encrypt
|
||||||
// server cert with no corresponding client CA of its own) has no
|
// server cert with no corresponding client CA of its own) has no
|
||||||
// client certificate to hand out to ordinary visitors, so
|
// client certificate to hand out to ordinary visitors, so
|
||||||
// requesting one via SSL_VERIFY_PEER would surface a "select a
|
// requesting one via SSL_VERIFY_PEER would surface a "select a
|
||||||
// certificate" prompt real browsers can't meaningfully answer.
|
// certificate" prompt real browsers can't meaningfully answer.
|
||||||
// Only enable it when a caCertificate is actually configured -
|
// Only enable it when a caCertificate is actually configured -
|
||||||
// existing internal/mTLS use of this class (any config that DOES
|
// existing internal/mTLS use of this class (any config that DOES
|
||||||
// set tls.caCertificate) keeps behaving exactly as before.
|
// set tls.caCertificate) keeps behaving exactly as before.
|
||||||
if(tlsInfo->cACertificate.getLength() > 0) {
|
if(tlsInfo->cACertificate.getLength() > 0) {
|
||||||
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
|
SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL);
|
||||||
SSL_CTX_set_verify_depth(ctx, 1);
|
SSL_CTX_set_verify_depth(newCtx, 1);
|
||||||
if(!SSL_CTX_load_verify_locations(ctx, tlsInfo->cACertificate.c_str(), NULL))
|
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 (client certificate required).";
|
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required).";
|
||||||
} else {
|
} else {
|
||||||
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required).";
|
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) {
|
||||||
int ret;
|
int ret;
|
||||||
|
|
||||||
|
|||||||
@@ -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,6 +48,36 @@ namespace core {
|
|||||||
|
|
||||||
void createContext(TLSInfo *tlsInfo);
|
void createContext(TLSInfo *tlsInfo);
|
||||||
|
|
||||||
|
///
|
||||||
|
/// 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
|
// A never-configured TLS object (either the listening TCPServer
|
||||||
// itself when constructed with tlsInfo=NULL, or a TCPSession spawned
|
// itself when constructed with tlsInfo=NULL, or a TCPSession spawned
|
||||||
// from one via TLS(SSL_CTX*)) must default to a real NULL here, not
|
// from one via TLS(SSL_CTX*)) must default to a real NULL here, not
|
||||||
@@ -58,6 +90,16 @@ namespace core {
|
|||||||
int sendData(const char *data, int length);
|
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:
|
protected:
|
||||||
// Set by sendData() when the last SSL_write() failed specifically
|
// Set by sendData() when the last SSL_write() failed specifically
|
||||||
@@ -78,7 +120,23 @@ namespace core {
|
|||||||
char *sip_key = (char *)"../testkeys/certs/pbxserver.key";
|
char *sip_key = (char *)"../testkeys/certs/pbxserver.key";
|
||||||
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);
|
||||||
|
|
||||||
};
|
};
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+75
-7
@@ -1,5 +1,7 @@
|
|||||||
#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 {
|
||||||
@@ -100,14 +102,80 @@ namespace core {
|
|||||||
} 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 {
|
||||||
|
pinned->shutDown = true;
|
||||||
|
// Was `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 {
|
} else {
|
||||||
((Socket *)events[ix].data.ptr)->shutDown = true;
|
// Neither registry recognizes this pointer - almost
|
||||||
// coreutils::Log(coreutils::LOG_DEBUG_4) << "return false";
|
// certainly a stale/duplicate epoll event for a
|
||||||
delete (Socket *)events[ix].data.ptr;
|
// 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 << ")";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,19 +54,22 @@ 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,66 +1,66 @@
|
|||||||
#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
|
||||||
/// Set and trigger callback upon specified timeout.
|
///
|
||||||
///
|
/// Set and trigger callback upon specified timeout.
|
||||||
/// The Timer is used to establish a timer using the timer socket
|
///
|
||||||
/// interface. It cannot be instantiated directly but must be extended.
|
/// The Timer is used to establish a timer using the timer socket
|
||||||
///
|
/// interface. It cannot be instantiated directly but must be extended.
|
||||||
|
///
|
||||||
class Timer : Socket {
|
|
||||||
|
class Timer : Socket
|
||||||
public:
|
{
|
||||||
|
|
||||||
|
public:
|
||||||
Timer(EPoll &ePoll);
|
Timer(EPoll &ePoll);
|
||||||
Timer(EPoll &ePoll, double delay);
|
Timer(EPoll &ePoll, double delay);
|
||||||
~Timer();
|
~Timer();
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Use the setTimer() method to set the time out value for timer. Setting the timer
|
/// Use the setTimer() method to set the time out value for timer. Setting the timer
|
||||||
/// also starts the timer countdown. The clearTimer() method can be used to reset
|
/// also starts the timer countdown. The clearTimer() method can be used to reset
|
||||||
/// the timer without triggering the onTimeout() callback.
|
/// the timer without triggering the onTimeout() callback.
|
||||||
///
|
///
|
||||||
/// @param delay the amount of time in seconds to wait before trigering the onTimeout function.
|
/// @param delay the amount of time in seconds to wait before trigering the onTimeout function.
|
||||||
///
|
///
|
||||||
|
|
||||||
void setTimer(double delay);
|
void setTimer(double delay);
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Use the clearTimer() to unset the timer and return the timer to an idle state.
|
/// Use the clearTimer() to unset the timer and return the timer to an idle state.
|
||||||
///
|
///
|
||||||
|
|
||||||
void clearTimer();
|
void clearTimer();
|
||||||
|
|
||||||
///
|
///
|
||||||
/// Use the getElapsed() method to obtain the amount of time that has elapsed since
|
/// Use the getElapsed() method to obtain the amount of time that has elapsed since
|
||||||
/// the timer was set.
|
/// the timer was set.
|
||||||
///
|
///
|
||||||
|
|
||||||
double getElapsed();
|
double getElapsed();
|
||||||
|
|
||||||
double getEpoch();
|
double getEpoch();
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
///
|
||||||
///
|
/// This method is called when the time out occurs.
|
||||||
/// This method is called when the time out occurs.
|
///
|
||||||
///
|
|
||||||
|
virtual void onTimeout() = 0;
|
||||||
virtual void onTimeout() = 0;
|
|
||||||
|
private:
|
||||||
private:
|
void onDataReceived(std::string data) override;
|
||||||
void onDataReceived(std::string data) override;
|
double delayValue;
|
||||||
double delayValue;
|
};
|
||||||
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
Reference in new issue
Block a user