Compare commits
17
Commits
tls
..
1d3d30cd05
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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
|
||||
.history/*
|
||||
html
|
||||
latex
|
||||
latex*.pre-*
|
||||
+7
-4
@@ -1,14 +1,17 @@
|
||||
#include "Command.h"
|
||||
#include "Log.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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,23 @@ namespace core {
|
||||
CommandList::CommandList(std::string delimiter, int depth) : delimiter(delimiter), depth(depth) {}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
|
||||
+7
-2
@@ -12,8 +12,13 @@ namespace core {
|
||||
}
|
||||
|
||||
void ConsoleServer::logSend(std::string out) {
|
||||
for(auto *session : sessions)
|
||||
((ConsoleSession *)session)->writeLog(out);
|
||||
// Was unlocked entirely (and iterated raw pointers before
|
||||
// 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) {
|
||||
|
||||
@@ -7,10 +7,16 @@ namespace core {
|
||||
|
||||
INotify::INotify(EPoll &ePoll) : Socket(ePoll, "INotify") {
|
||||
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() {
|
||||
shutdown();
|
||||
std::lock_guard<std::mutex> guard(knownINotifiesMutex());
|
||||
knownINotifies().erase(this);
|
||||
}
|
||||
|
||||
int INotify::addWatch(coreutils::ZString &watch) {
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
# define __INotify_h__
|
||||
|
||||
#include "Socket.h"
|
||||
#include <set>
|
||||
#include <mutex>
|
||||
|
||||
namespace core {
|
||||
|
||||
@@ -29,6 +31,41 @@ namespace core {
|
||||
virtual void inMovedTo(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;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
+87
-3
@@ -128,7 +128,6 @@ namespace core
|
||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM";
|
||||
writeSocket();
|
||||
}
|
||||
inHandler = false;
|
||||
// A graceful shutdown() (session.terminate() -> "goodbye" reply
|
||||
// queued via write(), then shutdown() called - see e.g. IMAP's
|
||||
// LOGOUT/POP3's QUIT/SMTP's QUIT) used to make keepAlive false
|
||||
@@ -145,7 +144,7 @@ namespace core
|
||||
// drain to a peer that's already gone is pointless, not graceful)
|
||||
// - gives that queued reply a real chance to go out before this
|
||||
// socket actually closes.
|
||||
bool keepAlive = !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
|
||||
// immediately eligible for delivery to ANY worker thread's
|
||||
@@ -162,8 +161,45 @@ namespace core
|
||||
// the last thing that ever touches `this`, with the return value
|
||||
// already captured in a local (`keepAlive`) beforehand.
|
||||
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor();
|
||||
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();
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -272,6 +308,26 @@ namespace core
|
||||
// the confirmed real damage (a 55GB, then 12.9GB debug log)
|
||||
// this caused before being noticed.
|
||||
coreutils::Log(coreutils::LOG_EXCEPT) << "Socket " << getDescriptor() << ": " << consecutiveWriteStalls << " consecutive writes made zero progress - giving up and shutting down.";
|
||||
// shutdown() alone only sets shutDown=true and expects the
|
||||
// fifo to drain normally before the connection actually
|
||||
// closes (see eventReceived()'s keepAlive: "!shutDown ||
|
||||
// (fifo.size() > 0 && !readHangup)") - exactly backwards
|
||||
// for THIS path, since the whole reason we're here is that
|
||||
// the front of the fifo can never be sent. Leaving it
|
||||
// queued meant keepAlive stayed true forever, resetSocket()
|
||||
// kept re-arming EPOLLWRNORM because fifo.size() > 0, the
|
||||
// very next write attempt hit this identical stall
|
||||
// immediately, and shutdown() got called again - forever,
|
||||
// at whatever rate the kernel could fire EPOLLWRNORM.
|
||||
// Confirmed live: 2.4 million+ repeats of this exact log
|
||||
// line for one socket in under 4 milliseconds, pegging a
|
||||
// worker thread at 100% CPU indefinitely (a real game
|
||||
// server, brought down by nothing more than an ordinary
|
||||
// port-scanner connection). Clearing the undeliverable data
|
||||
// here lets keepAlive correctly evaluate to just !shutDown
|
||||
// (now false) on the very next cycle, so the connection
|
||||
// actually tears down instead of spinning forever.
|
||||
std::queue<std::string>().swap(fifo);
|
||||
shutdown("stuck write retry loop - no progress after repeated attempts");
|
||||
}
|
||||
}
|
||||
@@ -283,7 +339,35 @@ namespace core
|
||||
outlock.lock();
|
||||
fifo.emplace(data);
|
||||
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(!inHandler)
|
||||
resetSocket();
|
||||
lock.unlock();
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "ZString.h"
|
||||
#include <queue>
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
#include <sys/epoll.h>
|
||||
|
||||
namespace core {
|
||||
@@ -123,6 +124,23 @@ namespace core {
|
||||
|
||||
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.
|
||||
|
||||
void setBufferSize(int length);
|
||||
@@ -199,7 +217,11 @@ namespace core {
|
||||
int descriptor = -1;
|
||||
std::mutex outlock;
|
||||
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.
|
||||
|
||||
+39
-14
@@ -1,26 +1,39 @@
|
||||
#include "Subscription.h"
|
||||
#include "Log.h"
|
||||
#include "MString.h"
|
||||
#include "TCPSession.h"
|
||||
#include "TCPSocket.h"
|
||||
#include <algorithm>
|
||||
|
||||
namespace core {
|
||||
|
||||
Subscription::Subscription(std::string id, std::string mode)
|
||||
: id(id), mode(mode), owner(NULL), handler(NULL) {}
|
||||
Subscription::Subscription(coreutils::MString id, coreutils::MString mode)
|
||||
: id(id), mode(mode), owner(""), handler(NULL) {}
|
||||
|
||||
Subscription::Subscription(std::string id, TCPSession &session, std::string mode)
|
||||
: id(id), mode(mode), owner(&session), handler(NULL) {}
|
||||
Subscription::Subscription(coreutils::MString id, coreutils::MString owner, coreutils::MString mode)
|
||||
: id(id), mode(mode), owner(owner), handler(NULL) {}
|
||||
|
||||
Subscription::Subscription(std::string id, TCPSession &session, std::string mode, SubscriptionHandler *handler)
|
||||
: id(id), mode(mode), owner(&session), handler(handler) {
|
||||
// coreutils::Log(coreutils::LOG_DEBUG_3) << "Subscription '" << id << "' with handler '" << handler->name << "'";
|
||||
Subscription::Subscription(coreutils::MString id, coreutils::MString owner, coreutils::MString ownership, coreutils::MString mode, SubscriptionHandler *handler, coreutils::MString will, coreutils::MString timer)
|
||||
: id(id), ownership(ownership), mode(mode), owner(owner), handler(handler), will(will), timer(timer) {
|
||||
coreutils::Log(coreutils::LOG_DEBUG_3) << owner;
|
||||
coreutils::Log(coreutils::LOG_DEBUG_3) << will;
|
||||
subscriptionOwner(owner, will);
|
||||
}
|
||||
|
||||
Subscription::~Subscription() {
|
||||
|
||||
std::stringstream out;
|
||||
|
||||
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) {
|
||||
subscriber->write(out.str());
|
||||
if (auto safe = subscriber->pin())
|
||||
safe->write(out.str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,21 +42,27 @@ namespace core {
|
||||
handler->onSubscribe(session, this);
|
||||
else
|
||||
onSubscribe(session);
|
||||
|
||||
subscribers.push_back(&session);
|
||||
return 1;
|
||||
}
|
||||
|
||||
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) {
|
||||
subscribers.erase(subscriber++);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
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) {
|
||||
if (handler)
|
||||
handler->process(request, out, session, this);
|
||||
@@ -53,8 +72,14 @@ namespace core {
|
||||
}
|
||||
|
||||
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)
|
||||
(*subscriber)->write(out.str());
|
||||
if (auto safe = (*subscriber)->pin())
|
||||
safe->write(out.str());
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -73,9 +98,9 @@ namespace core {
|
||||
void Subscription::sendToAll(std::stringstream &data, TCPSession &sender) {
|
||||
for (auto session : subscribers)
|
||||
if (session != &sender)
|
||||
session->write(data.str());
|
||||
if (auto safe = session->pin())
|
||||
safe->write(data.str());
|
||||
data.str("");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+16
-11
@@ -1,24 +1,24 @@
|
||||
#ifndef __Subscription_h__
|
||||
#define __Subscription_h__
|
||||
|
||||
#include "SubscriptionHandler.h"
|
||||
#include "MString.h"
|
||||
#include "SessionFilter.h"
|
||||
#include "SubscriptionHandler.h"
|
||||
#include "ZString.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
|
||||
namespace core
|
||||
{
|
||||
namespace core {
|
||||
|
||||
class TCPSession;
|
||||
|
||||
class Subscription {
|
||||
|
||||
public:
|
||||
Subscription(std::string id, std::string mode = "*AUTHOR");
|
||||
Subscription(std::string id, TCPSession &session, std::string mode);
|
||||
Subscription(std::string id, TCPSession &session, std::string mode, SubscriptionHandler *handler);
|
||||
Subscription(coreutils::MString id, coreutils::MString mode = "*AUTHOR");
|
||||
Subscription(coreutils::MString id, coreutils::MString owner, coreutils::MString mode);
|
||||
Subscription(coreutils::MString id, coreutils::MString owner, coreutils::MString ownership, coreutils::MString mode, SubscriptionHandler *handler, coreutils::MString selection, coreutils::MString time);
|
||||
virtual ~Subscription();
|
||||
|
||||
int subscribe(TCPSession &session);
|
||||
@@ -29,7 +29,7 @@ namespace core
|
||||
virtual int onSubscribe(TCPSession &session);
|
||||
|
||||
int event(std::stringstream &out);
|
||||
|
||||
bool subscriptionOwner(coreutils::MString owner, coreutils::MString selection);
|
||||
bool ifSubscriber(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, SessionFilter filter);
|
||||
|
||||
std::string id;
|
||||
std::string mode;
|
||||
TCPSession *owner;
|
||||
|
||||
coreutils::MString id;
|
||||
coreutils::MString mode;
|
||||
coreutils::MString owner;
|
||||
coreutils::MString subscriptionOwners;
|
||||
coreutils::MString selectionOfOwnerForSubscription;
|
||||
coreutils::MString will;
|
||||
coreutils::MString ownership;
|
||||
coreutils::MString timer;
|
||||
SubscriptionHandler *handler;
|
||||
|
||||
std::vector<TCPSession *> subscribers;
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+154
-32
@@ -1,25 +1,37 @@
|
||||
#include "SubscriptionManager.h"
|
||||
#include "Log.h"
|
||||
#include "Subscription.h"
|
||||
#include "SubscriptionHandlerFactory.h"
|
||||
#include "TCPServer.h"
|
||||
#include <algorithm>
|
||||
#include "SubscriptionHandlerFactory.h"
|
||||
#include <mutex>
|
||||
|
||||
namespace core {
|
||||
namespace core
|
||||
{
|
||||
|
||||
int SubscriptionManager::add(Subscription &subscription) {
|
||||
int SubscriptionManager::add(Subscription &subscription)
|
||||
{
|
||||
lock.lock();
|
||||
subscriptions.insert(std::make_pair(subscription.id, &subscription));
|
||||
lock.unlock();
|
||||
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 countPublished = 0;
|
||||
int count = 0;
|
||||
|
||||
lock.lock();
|
||||
std::string temp = "";
|
||||
coreutils::MString temp = "";
|
||||
for (auto [key, subscription] : subscriptions)
|
||||
{
|
||||
if (temp != "")
|
||||
@@ -28,10 +40,41 @@ namespace core {
|
||||
temp = "";
|
||||
}
|
||||
countSubscribed += subscription->unsubscribe(session);
|
||||
if (subscription->owner == &session)
|
||||
if (subscription->subscriptionOwners == coreutils::MString(session.alias))
|
||||
{
|
||||
temp = key;
|
||||
delete subscription;
|
||||
if (subscription->selectionOfOwnerForSubscription == "*DIE")
|
||||
{
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -46,58 +89,137 @@ namespace core {
|
||||
return countSubscribed;
|
||||
}
|
||||
|
||||
int SubscriptionManager::processCommand(coreutils::ZString &request, TCPSession &session) {
|
||||
if (request[0].equals("publish")) {
|
||||
int SubscriptionManager::processCommand(coreutils::ZString &request, TCPSession &session)
|
||||
{
|
||||
// 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;
|
||||
if(request.getList().size() > 3) {
|
||||
factory->getSubscriptionHandler(request[3].str());
|
||||
if (request.getList().size() > 3)
|
||||
{
|
||||
handler = factory->getSubscriptionHandler(request[4].str());
|
||||
}
|
||||
newSubscription = new Subscription(request[1].str(), session, request[2].str(), handler);
|
||||
if (request[2] == "*OWNER")
|
||||
{
|
||||
newSubscription = new Subscription(request[1].str(), session.alias, request[2].str(), request[3].str(), handler, request[5].str(), request[6].str());
|
||||
subscriptions.insert(std::make_pair(request[1].str(), newSubscription));
|
||||
newSubscription->owner = &session;
|
||||
return 1;
|
||||
} else if (request[0].equals("catalog")) {
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
else if (request[0] == "catalog")
|
||||
{
|
||||
session.out << ":catalog:";
|
||||
for (auto const &[key, subscription] : subscriptions) {
|
||||
for (auto const &[key, subscription] : subscriptions)
|
||||
{
|
||||
session.out << subscription->id << ";";
|
||||
}
|
||||
session.out << std::endl;
|
||||
return 1;
|
||||
} else if (request[0].equals("invite")) {
|
||||
}
|
||||
else if (request[0] == "invite")
|
||||
{
|
||||
std::stringstream out;
|
||||
coreutils::Log(coreutils::LOG_DEBUG_1) << request[2];
|
||||
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;
|
||||
temp << "invite:" << request[1] << ":" << *(std::string *)session.alias;
|
||||
temp << "invite:" << request[1] << ":" << invitee;
|
||||
tempSession->write(temp.str());
|
||||
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[0].equals("unpublish")) {
|
||||
if (request[1].equals(subscription->id))
|
||||
{
|
||||
if (request[0] == "unpublish")
|
||||
{
|
||||
subscriptions.erase(request[1].str());
|
||||
} else if (request[0].equals("subscribe")) {
|
||||
}
|
||||
else if (request[0] == "subscribe")
|
||||
{
|
||||
subscription->subscribe(session);
|
||||
return 1;
|
||||
} else if (request[0].equals("unsubscribe")) {
|
||||
}
|
||||
else if (request[0] == "unsubscribe")
|
||||
{
|
||||
subscription->unsubscribe(session);
|
||||
return 1;
|
||||
} else if (request[0].equals("event")) {
|
||||
}
|
||||
else if (request[0] == "event")
|
||||
{
|
||||
std::stringstream out;
|
||||
subscription->process(request, out, session);
|
||||
if (subscription->mode == "*ANYONE") {
|
||||
subscription->event(out);
|
||||
return 1;
|
||||
} else if (subscription->mode == "*SUBSCRIBERS") {
|
||||
if (subscription->ifSubscriber(session)) {
|
||||
if (subscription->mode == "*ANYONE")
|
||||
{
|
||||
subscription->event(out);
|
||||
return 1;
|
||||
}
|
||||
} else if (subscription->mode == "*AUTHOR") {
|
||||
if (subscription->owner == &session) {
|
||||
else if (subscription->mode == "*SUBSCRIBERS")
|
||||
{
|
||||
if (subscription->ifSubscriber(session))
|
||||
{
|
||||
subscription->event(out);
|
||||
return 1;
|
||||
}
|
||||
|
||||
+10
-4
@@ -2,32 +2,38 @@
|
||||
#define __SubscriptionManager_h__
|
||||
|
||||
#include "Command.h"
|
||||
#include "MString.h"
|
||||
#include "SessionFilter.h"
|
||||
#include "Subscription.h"
|
||||
#include "SubscriptionHandler.h"
|
||||
#include "TCPSession.h"
|
||||
#include "ZString.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace core {
|
||||
|
||||
//*AUTHOR -> Dies when player disconnects
|
||||
//*ANYONE -> Does not die when player disconnects
|
||||
//*SUBSCRIPTION -> Does not die when player disconnects
|
||||
//*OWNER -> Does die and transfers Ownership before he does
|
||||
|
||||
class SubscriptionHandlerFactory;
|
||||
|
||||
class SubscriptionManager : public Command {
|
||||
|
||||
public:
|
||||
|
||||
int add(Subscription &subscription);
|
||||
int removeSessionSubscriptions(TCPSession &session);
|
||||
int processCommand(coreutils::ZString &request, TCPSession &session) override;
|
||||
|
||||
bool onClearSubscription(coreutils::MString temp, coreutils::MString key);
|
||||
SubscriptionHandlerFactory *factory = NULL;
|
||||
|
||||
private:
|
||||
Subscription *subscription;
|
||||
std::map<std::string, Subscription *> subscriptions;
|
||||
std::map<coreutils::MString, Subscription *> subscriptions;
|
||||
Subscription *newSubscription;
|
||||
std::mutex lock;
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
+92
-18
@@ -9,6 +9,20 @@ namespace core {
|
||||
TCPServer::TCPServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo, std::string delimiter, int depth, std::string text)
|
||||
: TCPSocket(ePoll, tlsInfo, text), commands(delimiter, depth) {
|
||||
|
||||
// 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");
|
||||
|
||||
setDescriptor(socket(AF_INET, SOCK_STREAM, 0));
|
||||
int yes = 1;
|
||||
setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
|
||||
@@ -18,6 +32,14 @@ namespace core {
|
||||
|
||||
if (listen(getDescriptor(), 20) < 0)
|
||||
throw coreutils::Exception("Error on listen to socket");
|
||||
|
||||
// See isKnownListeningSocket()'s own doc comment - registers this
|
||||
// listening socket as safe for Thread::run() to dispatch to
|
||||
// directly, distinct from the shared_ptr-owned TCPSession registry.
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
|
||||
listeningSockets().insert(this);
|
||||
}
|
||||
}
|
||||
|
||||
TCPServer::~TCPServer() {
|
||||
@@ -29,8 +51,20 @@ namespace core {
|
||||
coreutils::Log(coreutils::LOG_DEBUG_2) << "Connection request is being received on socket " << getDescriptor() << ".";
|
||||
lock.lock();
|
||||
TCPSession *session = accept();
|
||||
if (session)
|
||||
sessions.push_back(session);
|
||||
// The shared_ptr constructed here IS the session's real, strong
|
||||
// ownership from now on (see sessions' own doc comment). A second
|
||||
// reference to the SAME shared_ptr (never a second, independent
|
||||
// std::shared_ptr<TCPSession>(session) call on the same raw
|
||||
// pointer - that would create a second, competing control block
|
||||
// and a guaranteed double-free) also goes into the tryGet()
|
||||
// registry, which is what Thread::run()'s epoll dispatch actually
|
||||
// uses to safely reach this object (see TCPSession::tryGet()'s
|
||||
// own comment on why).
|
||||
if (session) {
|
||||
auto sessionPtr = std::shared_ptr<TCPSession>(session);
|
||||
sessions.push_back(sessionPtr);
|
||||
TCPSession::registerLive(session, sessionPtr);
|
||||
}
|
||||
// Must run ON THE SESSION, not `this` (the listening server) - the
|
||||
// unqualified registerSocket()/acceptSocket() calls this replaced
|
||||
// built the SSL* handshake state on the SERVER's own TLS-base
|
||||
@@ -56,7 +90,8 @@ namespace core {
|
||||
|
||||
TCPSession * TCPServer::accept() {
|
||||
|
||||
try {
|
||||
try
|
||||
{
|
||||
|
||||
TCPSession *session = getSocketAccept(ePoll);
|
||||
session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength));
|
||||
@@ -82,14 +117,32 @@ namespace core {
|
||||
}
|
||||
|
||||
void TCPServer::removeFromSessionList(TCPSession *session) {
|
||||
std::vector<TCPSession *>::iterator cursor;
|
||||
lock.lock();
|
||||
for(cursor = sessions.begin(); cursor < sessions.end(); ++cursor)
|
||||
if(*cursor == session) {
|
||||
for (auto cursor = sessions.begin(); cursor < sessions.end(); ++cursor)
|
||||
if (cursor->get() == session)
|
||||
{
|
||||
// Drops the one strong-owning reference. If nothing else is
|
||||
// currently pin()'d to this session, the object is actually
|
||||
// destroyed right here, synchronously - same timing as
|
||||
// before this change for the common (no-contention) case.
|
||||
// If some other thread IS mid-call via its own pin()'d
|
||||
// shared_ptr right now, destruction is safely deferred until
|
||||
// that reference is released too, instead of the crash
|
||||
// (double-delete / use-after-free, confirmed live via
|
||||
// AddressSanitizer under concurrent load) that raw-pointer
|
||||
// ownership produced here before.
|
||||
sessions.erase(cursor);
|
||||
break;
|
||||
}
|
||||
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) {
|
||||
@@ -100,13 +153,30 @@ namespace core {
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
for (auto *sessionx : sessions)
|
||||
for (auto &sessionx : sessions)
|
||||
{
|
||||
session.out << "|" << ++sequence;
|
||||
sessionx->output(session.out);
|
||||
@@ -116,32 +186,36 @@ namespace core {
|
||||
}
|
||||
|
||||
void TCPServer::sendToAll(std::stringstream &data) {
|
||||
for (auto session : sessions)
|
||||
std::lock_guard guard(lock);
|
||||
for (auto &session : sessions)
|
||||
session->write(data.str());
|
||||
data.str("");
|
||||
}
|
||||
|
||||
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender) {
|
||||
for (auto session : sessions)
|
||||
if (session != &sender)
|
||||
std::lock_guard guard(lock);
|
||||
for (auto &session : sessions)
|
||||
if (session.get() != &sender)
|
||||
session->write(data.str());
|
||||
data.str("");
|
||||
}
|
||||
|
||||
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 (session != &sender)
|
||||
if (session.get() != &sender)
|
||||
session->write(data.str());
|
||||
data.str("");
|
||||
}
|
||||
|
||||
TCPSession *TCPServer::getSessionByAlias(void *alias) {
|
||||
std::shared_ptr<TCPSession> TCPServer::getSessionByAlias(void *alias) {
|
||||
coreutils::Log(coreutils::LOG_DEBUG_1) << alias;
|
||||
for (auto session : sessions)
|
||||
if (session->compareAlias(alias))
|
||||
std::lock_guard guard(lock);
|
||||
for (auto &session : sessions)
|
||||
if (session->alias == alias)
|
||||
return session;
|
||||
return NULL;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
}
|
||||
+86
-4
@@ -9,6 +9,8 @@
|
||||
# include "TCPSession.h"
|
||||
# include "TCPSocket.h"
|
||||
# include "TLSInfo.h"
|
||||
# include <mutex>
|
||||
# include <set>
|
||||
|
||||
namespace core {
|
||||
|
||||
@@ -60,8 +62,20 @@ namespace core {
|
||||
///
|
||||
/// The list of sessions that are currently open and being maintained by this object.
|
||||
///
|
||||
/// This is the one real, strong-owning reference per live session -
|
||||
/// see TCPSession::pin()'s own doc comment for the full reasoning.
|
||||
/// Every other place that keeps a TCPSession* around (Subscription::
|
||||
/// subscribers, a Zephora-specific sessionsByPlayerName map, etc.)
|
||||
/// is just a non-owning observer and must pin() before touching the
|
||||
/// object. A session stops existing, for real, the instant its
|
||||
/// entry here is erased and every other outstanding pin() (if any
|
||||
/// thread happened to be mid-call) has released its own reference -
|
||||
/// removeFromSessionList() is the only place that ever removes an
|
||||
/// entry, and Thread::run() calls it instead of ever calling
|
||||
/// `delete` on a TCPSession directly (see its own comment).
|
||||
///
|
||||
|
||||
std::vector<TCPSession *> sessions;
|
||||
std::vector<std::shared_ptr<TCPSession>> sessions;
|
||||
|
||||
///
|
||||
/// The commands object is a CommandList and is used to store Command objects to be
|
||||
@@ -119,10 +133,13 @@ namespace core {
|
||||
|
||||
///
|
||||
/// 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);
|
||||
|
||||
protected:
|
||||
///
|
||||
@@ -159,9 +176,74 @@ namespace core {
|
||||
|
||||
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:
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
+117
-1
@@ -3,6 +3,9 @@
|
||||
|
||||
# include "SessionFilter.h"
|
||||
# include "TCPSocket.h"
|
||||
# include <map>
|
||||
# include <memory>
|
||||
# include <mutex>
|
||||
# include <sstream>
|
||||
|
||||
namespace core {
|
||||
@@ -22,7 +25,120 @@ namespace core {
|
||||
///
|
||||
///
|
||||
|
||||
class TCPSession : public TCPSocket {
|
||||
class TCPSession : public TCPSocket, public std::enable_shared_from_this<TCPSession> {
|
||||
|
||||
public:
|
||||
|
||||
///
|
||||
/// pin() safely upgrades a raw TCPSession* (as stored in
|
||||
/// Subscription::subscribers, ZephoraServer's own
|
||||
/// sessionsByPlayerName, GroupManager's membership lists, etc.)
|
||||
/// into a real, ownership-extending shared_ptr before it's used.
|
||||
///
|
||||
/// The core problem this solves: every crash found and root-caused
|
||||
/// this session (SubscriptionManager.cpp/TCPServer.cpp/Socket.cpp's
|
||||
/// own fixes) was the same shape - one thread calling a method
|
||||
/// (write(), a destructor) on a TCPSession* while another thread
|
||||
/// concurrently deleted that same object, because nothing actually
|
||||
/// guaranteed the object stayed alive for the duration of the
|
||||
/// call. Mutex-based fixes at each individual call site kept
|
||||
/// narrowing the window without fully closing it, and a mutex
|
||||
/// around every write() call also isn't what the fifo-based
|
||||
/// design (see Socket::write()) was going for in the first place -
|
||||
/// no thread should have to block just to hand off a message.
|
||||
///
|
||||
/// TCPServer::sessions now holds the one real, strong-owning
|
||||
/// shared_ptr<TCPSession> per live session (see its own comment).
|
||||
/// Every OTHER place that stores a TCPSession* for later use is a
|
||||
/// plain observer, not an owner - it must call pin() and check for
|
||||
/// null immediately before touching the object, rather than
|
||||
/// dereferencing the raw pointer directly. pin() returns nullptr
|
||||
/// (instead of throwing, unlike raw shared_from_this()) once the
|
||||
/// object's last real owner has let go and it's on its way out -
|
||||
/// at that point there is nothing left to safely do with it, and
|
||||
/// the caller should just skip it as if it were never there,
|
||||
/// exactly like a stale/already-unsubscribed entry.
|
||||
///
|
||||
/// This adds no blocking anywhere: shared_ptr's own refcounting is
|
||||
/// a couple of atomic increments, not a mutex - the actual
|
||||
/// deletion still only ever happens once, whenever the last
|
||||
/// outstanding shared_ptr (held by TCPServer::sessions, or
|
||||
/// briefly by whichever thread(s) are mid-call via their own
|
||||
/// pin()'d reference) goes out of scope.
|
||||
///
|
||||
|
||||
std::shared_ptr<TCPSession> pin() {
|
||||
try { return shared_from_this(); }
|
||||
catch (const std::bad_weak_ptr &) { return nullptr; }
|
||||
}
|
||||
|
||||
///
|
||||
/// A second, distinct safety problem pin()/shared_from_this()
|
||||
/// alone cannot solve: Thread::run()'s epoll dispatch loop starts
|
||||
/// from a raw `void*` (epoll_event.data.ptr) whose TYPE isn't known
|
||||
/// yet - the original code cast it straight to `Socket*` and
|
||||
/// called virtual methods on it; an early version of this fix used
|
||||
/// dynamic_cast<TCPSession*> to identify session objects before
|
||||
/// calling pin(). Both of those REQUIRE reading the pointed-to
|
||||
/// object's own memory (its vtable, at minimum) to work at all -
|
||||
/// confirmed live via AddressSanitizer that dynamic_cast on a
|
||||
/// stale pointer (one epoll handed out for a TCPSession that
|
||||
/// something else had already fully destroyed and freed on another
|
||||
/// thread) segfaults outright, before pin()'s own safety logic
|
||||
/// ever gets a chance to run.
|
||||
///
|
||||
/// tryGet() sidesteps this entirely: it looks the raw pointer VALUE
|
||||
/// up as a key in a plain map, and only ever touches a weak_ptr's
|
||||
/// own control block (a separate heap allocation that outlives the
|
||||
/// TCPSession object itself for as long as any weak_ptr or
|
||||
/// shared_ptr referencing it exists) - never the TCPSession's own
|
||||
/// memory - to decide whether it's still valid. That makes it safe
|
||||
/// to call on ANY raw pointer value, including ones that turn out
|
||||
/// to be completely unrelated to this registry (never a
|
||||
/// TCPSession, e.g. a listening TCPServer/ConsoleServer - see
|
||||
/// TCPServer::isKnownListeningSocket() for how Thread::run()
|
||||
/// distinguishes that case) or ones pointing at freed memory.
|
||||
///
|
||||
/// registerLive()/unregisterLive() are called exactly once each,
|
||||
/// by TCPServer::connectionRequest() and removeFromSessionList()
|
||||
/// respectively - see their own comments for why those are the
|
||||
/// right, and only, call sites.
|
||||
///
|
||||
|
||||
static void registerLive(TCPSession *raw, std::shared_ptr<TCPSession> owner) {
|
||||
std::lock_guard<std::mutex> guard(registryMutex());
|
||||
registry()[raw] = owner;
|
||||
}
|
||||
|
||||
static void unregisterLive(TCPSession *raw) {
|
||||
std::lock_guard<std::mutex> guard(registryMutex());
|
||||
registry().erase(raw);
|
||||
}
|
||||
|
||||
static std::shared_ptr<TCPSession> tryGet(void *raw) {
|
||||
std::lock_guard<std::mutex> guard(registryMutex());
|
||||
auto it = registry().find((TCPSession *)raw);
|
||||
if (it == registry().end())
|
||||
return nullptr;
|
||||
return it->second.lock();
|
||||
}
|
||||
|
||||
private:
|
||||
// Function-local statics (constructed on first use, in whichever
|
||||
// translation unit/thread reaches them first, thread-safely per
|
||||
// C++11's own guarantee for static local initialization) instead
|
||||
// of ordinary static data members - avoids needing a .cpp
|
||||
// definition for these two and any static-initialization-order
|
||||
// concerns with other translation units, since TCPSession.h is
|
||||
// included widely.
|
||||
static std::mutex ®istryMutex() {
|
||||
static std::mutex m;
|
||||
return m;
|
||||
}
|
||||
static std::map<TCPSession *, std::weak_ptr<TCPSession>> ®istry() {
|
||||
static std::map<TCPSession *, std::weak_ptr<TCPSession>> r;
|
||||
return r;
|
||||
}
|
||||
|
||||
public:
|
||||
|
||||
|
||||
@@ -79,13 +79,25 @@ namespace core {
|
||||
CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))lock_callback);
|
||||
SSLeay_add_ssl_algorithms();
|
||||
RAND_load_file("/dev/hwrng", 1024);
|
||||
if(!(ctx = SSL_CTX_new(SSLv23_server_method())))
|
||||
ctx = buildContext(tlsInfo);
|
||||
}
|
||||
}
|
||||
|
||||
// The per-context cert/key/cipher/verify setup factored out of
|
||||
// createContext() above so addSNIContext() (below) can build
|
||||
// additional contexts - one per extra hostname - without repeating
|
||||
// the ONE-TIME, process-wide OpenSSL library init that stays in
|
||||
// createContext() itself (SSL_library_init(), the lockarray, RAND
|
||||
// seeding): that part must only ever run once per process, not once
|
||||
// per hostname.
|
||||
SSL_CTX *TLS::buildContext(TLSInfo *tlsInfo) {
|
||||
SSL_CTX *newCtx;
|
||||
if(!(newCtx = 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);
|
||||
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER);
|
||||
// SSL_CTX_set_generate_session_id(ctx, generate_session_id);
|
||||
SSL_CTX_set_cipher_list(ctx, "ECDH-ECDSA-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA");
|
||||
SSL_CTX_set_mode(newCtx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
|
||||
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
|
||||
@@ -96,11 +108,11 @@ namespace core {
|
||||
// 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(ctx, tlsInfo->certificate.c_str()) <= 0)
|
||||
if(SSL_CTX_use_certificate_chain_file(newCtx, tlsInfo->certificate.c_str()) <= 0)
|
||||
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.");
|
||||
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.");
|
||||
// Client-certificate verification (mutual TLS) is opt-in, not the
|
||||
// default - a public-facing site (e.g. a real Let's Encrypt
|
||||
@@ -112,18 +124,45 @@ namespace core {
|
||||
// existing internal/mTLS use of this class (any config that DOES
|
||||
// set tls.caCertificate) keeps behaving exactly as before.
|
||||
if(tlsInfo->cACertificate.getLength() > 0) {
|
||||
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
|
||||
SSL_CTX_set_verify_depth(ctx, 1);
|
||||
if(!SSL_CTX_load_verify_locations(ctx, tlsInfo->cACertificate.c_str(), NULL))
|
||||
SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL);
|
||||
SSL_CTX_set_verify_depth(newCtx, 1);
|
||||
if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL))
|
||||
throw coreutils::Exception("Cannot verify locations.");
|
||||
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).";
|
||||
} else {
|
||||
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required).";
|
||||
}
|
||||
return newCtx;
|
||||
}
|
||||
|
||||
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) {
|
||||
int ret;
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "ZString.h"
|
||||
#include "TLSInfo.h"
|
||||
#include <openssl/ssl.h>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace core {
|
||||
|
||||
@@ -46,6 +48,26 @@ namespace core {
|
||||
|
||||
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);
|
||||
|
||||
// A never-configured TLS object (either the listening TCPServer
|
||||
// itself when constructed with tlsInfo=NULL, or a TCPSession spawned
|
||||
// from one via TLS(SSL_CTX*)) must default to a real NULL here, not
|
||||
@@ -79,6 +101,28 @@ namespace core {
|
||||
bool initialized = false;
|
||||
SSL *ssl;
|
||||
|
||||
// The actual cert/key-loading + cipher/session-cache setup shared
|
||||
// by both the base context (createContext(), unchanged) and every
|
||||
// additional per-hostname context addSNIContext() builds - factored
|
||||
// out so there's exactly one place that does this, not two copies
|
||||
// drifting apart.
|
||||
SSL_CTX *buildContext(TLSInfo *tlsInfo);
|
||||
|
||||
// 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);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
+74
-6
@@ -1,5 +1,7 @@
|
||||
#include "Thread.h"
|
||||
#include "EPoll.h"
|
||||
#include "TCPServer.h"
|
||||
#include "INotify.h"
|
||||
#include <sys/epoll.h>
|
||||
|
||||
namespace core {
|
||||
@@ -100,13 +102,79 @@ namespace core {
|
||||
} else if(rc > 0) {
|
||||
for(int ix = 0; ix < rc; ++ix) {
|
||||
++count;
|
||||
if(((Socket *)events[ix].data.ptr)->eventReceived(events[ix], ++ePoll.eventId)) {
|
||||
// coreutils::Log(coreutils::LOG_DEBUG_4) << "return true";
|
||||
// ePoll.resetSocket((Socket *)events[ix].data.ptr);
|
||||
// events[ix].data.ptr is a raw pointer of UNKNOWN validity at
|
||||
// this point - it could be a live TCPSession, a listening
|
||||
// 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 {
|
||||
((Socket *)events[ix].data.ptr)->shutDown = true;
|
||||
// coreutils::Log(coreutils::LOG_DEBUG_4) << "return false";
|
||||
delete (Socket *)events[ix].data.ptr;
|
||||
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 {
|
||||
// Neither registry recognizes this pointer - almost
|
||||
// certainly a stale/duplicate epoll event for a
|
||||
// TCPSession that has already been fully destroyed and
|
||||
// unregistered elsewhere. There is nothing safe to do
|
||||
// with it except leave it alone entirely.
|
||||
coreutils::Log(coreutils::LOG_DEBUG_1) << "Ignoring stale/unrecognized epoll event (pointer " << rawPtr << ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,27 @@
|
||||
#include <sys/timerfd.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));
|
||||
setTimer(delay);
|
||||
}
|
||||
|
||||
Timer::~Timer() {
|
||||
Timer::~Timer()
|
||||
{
|
||||
}
|
||||
|
||||
void Timer::setTimer(double delay) {
|
||||
void Timer::setTimer(double delay)
|
||||
{
|
||||
|
||||
double integer;
|
||||
double fraction;
|
||||
@@ -29,10 +39,10 @@ namespace core {
|
||||
timer.it_value.tv_nsec = (int)(fraction * 1000000000);
|
||||
|
||||
timerfd_settime(getDescriptor(), 0, &timer, NULL);
|
||||
|
||||
}
|
||||
|
||||
void Timer::clearTimer() {
|
||||
void Timer::clearTimer()
|
||||
{
|
||||
|
||||
struct itimerspec timer;
|
||||
|
||||
@@ -44,19 +54,22 @@ namespace core {
|
||||
timerfd_settime(getDescriptor(), 0, &timer, NULL);
|
||||
}
|
||||
|
||||
double Timer::getElapsed() {
|
||||
double Timer::getElapsed()
|
||||
{
|
||||
struct itimerspec timer;
|
||||
timerfd_gettime(getDescriptor(), &timer);
|
||||
double toTimeout = (double)((timer.it_value.tv_sec * 1000000000L) + timer.it_value.tv_nsec) / 1000000000L;
|
||||
return delayValue - toTimeout;
|
||||
}
|
||||
|
||||
void Timer::onDataReceived(std::string data) {
|
||||
void Timer::onDataReceived(std::string data)
|
||||
{
|
||||
onTimeout();
|
||||
}
|
||||
|
||||
double Timer::getEpoch() {
|
||||
return (double)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() /1000000000L;
|
||||
double Timer::getEpoch()
|
||||
{
|
||||
return (double)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() / 1000000000L;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
#ifndef __Timer_h__
|
||||
#define __Timer_h__
|
||||
|
||||
#include "Socket.h"
|
||||
#include "EPoll.h"
|
||||
#include "Socket.h"
|
||||
|
||||
namespace core {
|
||||
namespace core
|
||||
{
|
||||
|
||||
///
|
||||
/// Timer
|
||||
@@ -15,7 +16,8 @@ namespace core {
|
||||
/// interface. It cannot be instantiated directly but must be extended.
|
||||
///
|
||||
|
||||
class Timer : Socket {
|
||||
class Timer : Socket
|
||||
{
|
||||
|
||||
public:
|
||||
Timer(EPoll &ePoll);
|
||||
@@ -48,7 +50,6 @@ namespace core {
|
||||
double getEpoch();
|
||||
|
||||
protected:
|
||||
|
||||
///
|
||||
/// This method is called when the time out occurs.
|
||||
///
|
||||
@@ -58,7 +59,6 @@ namespace core {
|
||||
private:
|
||||
void onDataReceived(std::string data) override;
|
||||
double delayValue;
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user