Compare commits

..
20 Commits
Author SHA1 Message Date
Matt ArantandClaude Sonnet 5 4bfede1342 Fix sweepStaleSessions() lock_guard type after lock became recursive_mutex
Merging upstream TCPServer.h changed lock from std::mutex to
std::recursive_mutex (the ConsoleServer self-deadlock fix); this call
site still hardcoded std::lock_guard<std::mutex>, which no longer
compiles since lock_guard cannot bind to a different mutex type. Uses
the same class-template-argument-deduction form every other lock_guard
in this file already uses.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 18:34:51 +00:00
Matt Arant dc6b1dcc56 Merge branch 'master' of git.barant.com:barant/ServerCore 2026-10-06 17:54:37 +00:00
Matt ArantandClaude Sonnet 5 6483729de3 Add a stale/never-active session reaper and raise the listen backlog
TCPServer accepted a connection and never revisited it again once it
stopped generating epoll events - a connection that completes the TCP
handshake and then goes permanently silent (an incomplete TLS
handshake, a port scanner/prober) sat in sessions forever, one
TCPSession + one fd each. sweepStaleSessions() now drops any session
that has gone 30+ seconds without a single byte of real data ever
passing through onDataReceived(), run each time a new connection
arrives rather than needing a dedicated timer. hasReceivedData latches
permanently true on a sessions first real byte, so an ordinary
connected-but-briefly-idle client is never at risk.

Also raised listen()s backlog from 20 to 128, so a burst of connection
attempts has more headroom before the kernel starts dropping SYNs.

Verified live on zephora.barant.com: a silent connection held open was
reaped within the grace window while a real concurrent connection was
left untouched, with the service remaining healthy throughout.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 17:54:20 +00:00
Brad ArantandClaude Sonnet 5 1d3d30cd05 Fix epoll dispatch dropping INotify events, ConsoleServer self-deadlock, and add TLS SNI support
- INotify/Thread epoll dispatch was silently dropping every live
  core::INotify event (an isKnownINotify registry fixes it) - this had
  broken mail delivery for over a week, masked by routine restarts.
- TCPServer::lock self-deadlocked every admin-console connection via a
  plain std::mutex being re-entered; switched to recursive_mutex.
- TLS.cpp/h: SNI-based certificate selection (addSNIContext), the
  groundwork for multi-tenant TLS (qualityiron.vegas alongside
  barant.com on one APIServer process).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-10-06 17:38:37 +00:00
Matt Arant d058322cc6 Move TCPSession lifetime to shared_ptr ownership, fix the whole double-delete/UAF class of crash
Every crash root-caused earlier tonight (Subscription::subscribers,
TCPServer::sessions, the Socket::write()/eventReceived() re-arm race) was
the same underlying shape: some thread calling a method - or Thread::run()
calling delete - on a TCPSession* while another thread concurrently freed
that same object, because nothing actually guaranteed the object stayed
alive for the duration of a call. Mutex-based patches at each individual
call site kept narrowing the window without closing it (confirmed live,
repeatedly, via AddressSanitizer under concurrent load - each fix produced
a new, different crash signature at the same underlying race), and adding
more locks around every write() call also works against the fifo-based
design's own goal: no thread should have to block just to hand a message
to another thread's session.

TCPSession now derives from std::enable_shared_from_this<TCPSession> and
exposes pin() - a safe upgrade from a stored raw pointer to a real,
ownership-extending shared_ptr, returning nullptr instead of throwing once
the object's real owner has let go. TCPServer::sessions is now the one
real strong-owning shared_ptr<TCPSession> per live session; every other
place that stores a TCPSession* (Subscription::subscribers, Zephora's own
sessionsByPlayerName, GroupObject's membership list, etc.) is just a
non-owning observer and must pin() before touching the object.

A second, distinct problem: Thread::run()'s epoll dispatch starts from a
raw void* of unknown validity. An early version of this fix used
dynamic_cast<TCPSession*> to identify session objects before calling
pin() - confirmed live via AddressSanitizer that dynamic_cast itself
segfaults on a stale pointer, since it has to read the (potentially freed)
object's own vtable to work at all. TCPSession::tryGet()/TCPServer::
isKnownListeningSocket() replace that: both look the raw pointer up as a
key in a registry, never dereferencing it for the check itself - safe to
call on any value, live session, immortal listening socket, or fully
freed garbage alike.

Verified via an AddressSanitizer-instrumented build under sustained
concurrent load (up to 15-way parallel connect/subscribe/create/disconnect
cycles, multiple rounds, 100+ total connections) with zero errors, then
against the real production build with a genuine 500-connection load test
(463/500 succeeded; the rest hit the process's own file-descriptor
ulimit under peak burst, an unrelated and separately deferred tuning
matter, not a crash).

Files touched: TCPSession.h (enable_shared_from_this, pin(), the tryGet()
registry), TCPServer.h/.cpp (sessions as shared_ptr, isKnownListening
Socket() registry, lock made protected for subclasses), Thread.cpp (the
whole dispatch rewrite), Subscription.cpp/SubscriptionManager.cpp (every
subscriber write() site now pin()s first), ConsoleServer.cpp (logSend()
was iterating `sessions` with no lock at all - fixed alongside the type
change it needed anyway).
2026-09-08 02:24:09 +00:00
Matt Arant 8009564a7a Fix premature socket re-arm race between write() and eventReceived()
Socket::write() unconditionally called resetSocket() (via EPOLL_CTL_MOD)
from whatever thread called it, whenever it could grab `lock` - including
while this same socket's OWN eventReceived() call was still mid-flight on
another thread (past receiveData()'s lock_guard, but before its own
trailing resetSocket()/return). Re-arming makes the fd immediately
eligible for a third thread to pick up a fresh event and, if it decides
to shut the connection down, delete the object outright (Thread::run()
does exactly that on a false return) - while the original thread is still
touching it. A real heap-corruption crash inside libc's malloc internals
was confirmed live via dmesg under concurrent load, consistent with
exactly this: a socket freed while another thread still held a reference
to it.

inHandler existed as a flag already but only fed a diagnostic log line -
never actually gated anything. Made it a real std::atomic<bool> (was
`volatile`, which gives no actual atomicity or cross-thread visibility)
and used it two ways:
- write() now skips its own resetSocket() call entirely while inHandler
  is true - that call's own eventReceived() will re-arm once it's
  actually done, seeing the fifo entry write() just queued.
- eventReceived() itself was clearing inHandler well before its own
  resetSocket() call (several statements up, right after EPOLLIN/
  EPOLLWRNORM handling) - moved the clear to immediately precede that
  call, closing the exposed window down to the minimum achievable
  without restructuring how write() re-arms sockets altogether.

This is a distinct bug from the two subscriber/session-list races fixed
earlier tonight (SubscriptionManager.cpp, TCPServer.cpp) - found while
stress-testing those fixes turned up a third, different crash signature
(heap corruption, not the null-EPoll-reference pattern the earlier two
produced).
2026-09-07 23:52:42 +00:00
Matt Arant 0bb926a264 Fix unsynchronized data race in TCPServer::sessions
connectionRequest()/removeFromSessionList() already lock `lock` around
every mutation of `sessions` (a session accepting or disconnecting), but
every read of it - sendToAll() (all three overloads), getSessionByAlias(),
and the debug-console processCommand() - iterated it with no lock at all.
Exact same bug shape as Subscription::subscribers, fixed earlier today in
SubscriptionManager.cpp, just in a completely separate container.

Confirmed live via dmesg: a real segfault at a stable, deterministic
instruction offset inside the binary, hit twice across separate process
launches tonight - Socket::write() -> resetSocket() dereferencing a null
EPoll reference, the same crash signature as the earlier Subscription fix,
consistent with iterating `sessions` while another thread concurrently
erased and freed one of its entries. sendToAll() backs most real gameplay
broadcasts (combat, position, chat), so this is very likely the actual
dominant cause of tonight's crash - not just the ItemDataBase-specific
subscriber list the earlier fix addressed.

Took the existing `lock` mutex around all five read sites. No new
reentrancy risk: SubscriptionManager's "invite" verb already calls
getSessionByAlias() while holding SubscriptionManager::lock, so the two
mutexes now nest in one fixed order (SubscriptionManager::lock, then
TCPServer::lock) - nothing acquires them in the reverse order anywhere
in this codebase, so no AB-BA deadlock risk.
2026-09-07 23:31:28 +00:00
Matt Arant 3383595296 Fix unsynchronized data race in SubscriptionManager::processCommand()
processCommand() read/mutated the `subscriptions` map and individual
Subscription objects' `subscribers` vectors (via subscribe()/unsubscribe()/
event()/the "publish" branch's own insert()) without taking `lock` at all,
even though add() and removeSessionSubscriptions() already do take it for
the exact same state. removeSessionSubscriptions() runs from ~TCPSession(),
on whatever thread happens to be tearing down a *different* connection, so
one thread erasing a session from a Subscription's subscribers vector could
run concurrently with another thread iterating (event()) or appending to
(subscribe()) that same vector - a plain unsynchronized data race.

Reproduced live while testing an unrelated ItemDataBase fix: rapid connect/
subscribe/disconnect cycles against the "createItem" subscription produced
a real segfault, confirmed via gdb - Socket::write() -> resetSocket()
dereferencing a corrupted EPoll reference, consistent with iterating a
vector that another thread was concurrently erasing from.

Wrapped the whole method body in a std::lock_guard on the same `lock`
mutex SubscriptionManager already has. Verified no reentrancy risk: nothing
reachable from processCommand() (including subscription handlers' own
process()/onSubscribe() implementations) calls back into processCommand(),
add(), or removeSessionSubscriptions() on the same thread, and `lock` is a
plain non-recursive std::mutex, so this can't deadlock.

Verified fix: the exact repro sequence that segfaulted the server twice
now runs clean, server stays up.

Not touched: Subscription::sendToAll() has no live callers (dead code);
dynamically `new`'d *OWNER subscriptions are still never delete()'d when
unpublished (a pre-existing leak, not a crash) - both out of scope here.
2026-09-07 20:18:14 +00:00
Matt Arant 2c65939788 Fix null-deref crash in base invite verb + pick up pending reformat
SubscriptionManager::processCommand()'s "invite" branch looked up its
target via getSessionByAlias(&invitee), where invitee is a std::string
local to that function call. getSessionByAlias(void*) compares by
pointer identity against each session's own alias - the address of a
brand-new local variable can never equal any of those, so the lookup
was guaranteed to return NULL every time, and the result was
dereferenced unconditionally right after. Any client sending a bare
"invite:" command crashed the entire process, not just its own
connection - same class of bug as the two GuildManager crashes fixed
earlier this session, just found afterward while documenting this
file's own mechanics.

This generic ServerCore layer has no name-based session lookup
available (that only exists as a Zephora-specific addition on top of
TCPServer), so this stops the crash with a null check rather than
attempting a real name-based fix, which would need a larger change.

Also includes this file's pending brace-style reformat (K&R -> Allman)
that was sitting uncommitted before this fix - bundled in rather than
left stranded, no functional change from that part.
2026-09-07 18:15:03 +00:00
Matt Arant 1e9b5f1016 Fix null-deref crash on subscribe/unsubscribe/event to unknown subscription id
subscriptions[id] via operator[] default-constructed (NULL) and
inserted an entry for any unregistered id, and the very next line
dereferenced it unconditionally - any client referencing a
subscription id that was never created (e.g. Zephora client sending
subscribe:invite for a channel nobody ever Publish()d) segfaulted the
entire process, not just that connection. Use find() and return
gracefully instead.
2026-09-07 00:48:26 +00:00
Brad Arant cfc0b19418 Fix stuck-write give-up path spinning forever instead of actually closing
shutdown() only sets shutDown=true and expects the fifo to drain
normally before eventReceived()'s keepAlive check
(!shutDown || (fifo.size() > 0 && !readHangup)) lets the connection
close - correct for a graceful QUIT/LOGOUT reply that just needs a few
more successful writes to flush, but exactly backwards for the give-up
path: the whole reason that path was reached 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 wasn't
empty, the very next write attempt hit the identical stall
immediately, and shutdown() got called again - forever, at whatever
rate the kernel could fire EPOLLWRNORM.

Confirmed live on a real internet-facing server (Zephora's game
server, an ordinary port-scanner connection was enough to trigger it):
one socket logged "consecutive writes made zero progress - giving up
and shutting down" 2.4 million+ times in under 4 milliseconds,
pegging a worker thread at 100% CPU indefinitely. The give-up path now
clears the undeliverable fifo entry before calling shutdown(), so
keepAlive correctly evaluates to just !shutDown (now false) on the
next cycle and the connection actually tears down.
2026-09-06 19:41:07 +00:00
Brad Arant bee8b92a6d Fold command names to uppercase at registration, not just at lookup
CommandList::processRequest() upper-cases the incoming keyword before
looking it up, but add() stored whatever case the caller passed in
verbatim - any registration not already uppercase could then never be
matched by any input at all, since upper-casing a non-uppercase string
cannot produce a match against a non-uppercase key. This was invisible
on BARANTMail/APIServer (their own commands - SMTP, POP3/IMAP, the
admin console - all happen to already be registered uppercase) but
confirmed, via a full Zephora game client/server protocol comparison,
to make literally every Zephora game command unreachable, including
the base TCPServer's own publish/subscribe/event/etc. registrations
that the whole subscription layer depends on. Folding at add() time
keeps registration and lookup permanently in sync regardless of
caller case; already-uppercase callers are unaffected (idempotent).
2026-09-06 18:39:30 +00:00
Brad Arant 381ed86875 Untrack scratch .pre-* backup files accidentally swept in by the tls merge commit
The merge commit (3609ed6) used git add -A to handle the large number
of deletes/renames from conflict resolution, which also picked up 22
untracked *.pre-* files - local safety-copy backups made before
editing tracked files, never meant to be committed. Untracked (kept on
disk) rather than deleted, and added *.pre-* to .gitignore so this
does not recur.
2026-09-06 15:35:09 +00:00
Brad Arant 3609ed603e Merge tls into master: bring in subscription ownership, keep all TLS/stability work
tls and master diverged from a July 2024 fork point and never
reconciled - tls carries ~19 months of real socket/TLS stability
fixes (uninitialized tlsInfo, TCPServer::connectionRequest()
unconditionally initializing TLS, the WANT_READ write busy-spin, the
console authentication fix from this session), while master
independently picked up a Subscription/SubscriptionManager rework
(MString-based ownership tracking: owner/ownership/selection/time
fields and a working subscriptionOwner() method) that tls never had.

Every file both branches touched was resolved by keeping tls's side
entirely (Command.h, Socket.cpp, TCPServer.h, TCPSession.cpp/h,
TCPSocket.h were pure reformatting on master's side, or an
alternate/superseded fix for a bug tls already fixed a different way -
e.g. master's TCPSession uuid/alias handling vs tls's existing
uuid_unparse-based fix), with two deliberate exceptions:

- TCPServer.cpp's constructor was missing the
  commands.add(subscriptions, "publish"/"subscribe"/"catalog"/...)
  wiring master had - without it, SubscriptionManager existed but was
  completely unreachable through the normal command dispatch. Restored
  on top of tls's TLS-aware constructor.

- SubscriptionManager.cpp's "invite" command handler had a real
  incompatibility: master's version assigned into an `invitee` member
  typed as coreutils::MString via a stray `(coreutils::MString *)`
  cast that doesn't match the member's actual (non-pointer) type, and
  called session.server.getSessionByAlias() against a TCPServer
  reference - tls made TCPSession::server a pointer (part of removing
  the separate TCPSession2 class), so that call site no longer
  compiles as written. Took tls's cleaner local-variable version
  instead (functionally identical - looks up a session by alias and
  forwards an invite message) and removed the now-unused `invitee`
  member from SubscriptionManager.h.

One additional compile fix needed after resolving conflicts:
Subscription::subscriptionOwners is an MString (master's ownership
design), but TCPSession::alias is void* (tls's identity mechanism,
unchanged and depended on elsewhere) - MString has an implicit
constructor from void* already used successfully elsewhere in this
same file (the "publish" handler's Subscription constructor call),
but operator== doesn't accept the same implicit conversion, so
removeSessionSubscriptions()'s ownership check needed an explicit
coreutils::MString(session.alias) construction to compile.

Also drops output/main (a stray checked-in compiled binary, already
removed on tls) and the doxygen docs/html output (already removed on
tls, was carried on master since the fork).

Verified: full ServerCore rebuild (./compile) succeeds with zero
errors or warnings beyond the one compile fix documented above.
2026-09-06 13:09:15 +00:00
Brad Arant b5f4947f7c minor format change, 2025-06-05 16:54:36 +00:00
Brad Arant 1d16d0c17f merge conflicts resolution with develop->master. 2025-06-05 16:07:50 +00:00
Brad Arant 4230734ee6 Remove intellisense work files. 2025-06-05 16:03:53 +00:00
Brad Arant 57f47fdecb Convert Subscription and SubscriptionManager to MString. 2023-10-26 18:28:51 -07:00
Matt Arant 3a75e920d9 Servercore Changes 2023-10-06 18:31:22 +00:00
Brad 9a39b6224c *NEXT/*DIE 2023-06-19 23:22:46 +00:00
22 changed files with 1121 additions and 251 deletions

No files matched your search

+1 -1
View File
@@ -11,4 +11,4 @@ docs/html
*/mmap_address.bin */mmap_address.bin
.history/* .history/*
html html
latex latex*.pre-*
+7 -4
View File
@@ -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;
} }
+17
View File
@@ -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
View File
@@ -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) {
+6
View File
@@ -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) {
+37
View File
@@ -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;
}
}; };
} }
+88 -4
View File
@@ -128,7 +128,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 +144,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 +161,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;
} }
@@ -272,6 +308,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 +339,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;
+23 -1
View File
@@ -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);
@@ -199,7 +217,11 @@ namespace core {
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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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; };
};
} }
+138 -24
View File
@@ -3,12 +3,28 @@
#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) {
// 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)); setDescriptor(socket(AF_INET, SOCK_STREAM, 0));
int yes = 1; int yes = 1;
setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
@@ -16,8 +32,23 @@ namespace core {
if (bind(getDescriptor(), address.getPointer(), address.addressLength) < 0) if (bind(getDescriptor(), address.getPointer(), address.addressLength) < 0)
throw coreutils::Exception("Error on bind to socket: " + std::to_string(errno)); throw coreutils::Exception("Error on bind to socket: " + std::to_string(errno));
if (listen(getDescriptor(), 20) < 0) // Was 20 - small enough that a burst of connection attempts
// arriving faster than this process calls accept() (a port scan,
// or just several real clients reconnecting around the same
// moment) can fill the kernel's own backlog before the
// application layer gets a chance to drain it, silently dropping
// the overflow SYNs rather than queuing them. 128 gives real
// bursts meaningfully more headroom; still bounded, not unlimited.
if (listen(getDescriptor(), 128) < 0)
throw coreutils::Exception("Error on listen to socket"); 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() { TCPServer::~TCPServer() {
@@ -27,10 +58,26 @@ 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(); TCPSession *session = accept();
if (session) // The shared_ptr constructed here IS the session's real, strong
sessions.push_back(session); // 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 // Must run ON THE SESSION, not `this` (the listening server) - the
// unqualified registerSocket()/acceptSocket() calls this replaced // unqualified registerSocket()/acceptSocket() calls this replaced
// built the SSL* handshake state on the SERVER's own TLS-base // built the SSL* handshake state on the SERVER's own TLS-base
@@ -46,6 +93,33 @@ namespace core {
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::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,7 +130,8 @@ namespace core {
TCPSession * TCPServer::accept() { TCPSession * TCPServer::accept() {
try { try
{
TCPSession *session = getSocketAccept(ePoll); TCPSession *session = getSocketAccept(ePoll);
session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength)); session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength));
@@ -82,14 +157,32 @@ namespace core {
} }
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 +193,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 +226,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;
} }
} }
+113 -6
View File
@@ -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,13 @@ 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);
protected: protected:
/// ///
@@ -132,6 +149,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 +201,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;
}
}; };
} }
+119 -3
View File
@@ -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 &registryMutex() {
static std::mutex m;
return m;
}
static std::map<TCPSession *, std::weak_ptr<TCPSession>> &registry() {
static std::map<TCPSession *, std::weak_ptr<TCPSession>> r;
return r;
}
public:
/// ///
/// ///
/// ///
+1
View File
@@ -99,6 +99,7 @@ namespace core {
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();
+36
View File
@@ -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,41 @@ namespace core {
void performTLSHandshake(); void performTLSHandshake();
///
/// 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;
protected: protected:
bool term = false; bool term = false;
TLSInfo *tlsInfo; TLSInfo *tlsInfo;
+86 -47
View File
@@ -69,61 +69,100 @@ namespace core {
void TLS::createContext(TLSInfo *tlsInfo) { void TLS::createContext(TLSInfo *tlsInfo) {
if(tlsInfo) { if(tlsInfo) {
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()))) ctx = buildContext(tlsInfo);
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");
// _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(ctx, 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)
throw coreutils::Exception("Error with private key.");
if(SSL_CTX_check_private_key(ctx) != 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
// server cert with no corresponding client CA of its own) has no
// client certificate to hand out to ordinary visitors, so
// requesting one via SSL_VERIFY_PEER would surface a "select a
// certificate" prompt real browsers can't meaningfully answer.
// Only enable it when a caCertificate is actually configured -
// existing internal/mTLS use of this class (any config that DOES
// set tls.caCertificate) keeps behaving exactly as before.
if(tlsInfo->cACertificate.getLength() > 0) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_verify_depth(ctx, 1);
if(!SSL_CTX_load_verify_locations(ctx, 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()));
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required).";
} else {
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required).";
}
} }
} }
// 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(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.");
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(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
// server cert with no corresponding client CA of its own) has no
// client certificate to hand out to ordinary visitors, so
// requesting one via SSL_VERIFY_PEER would surface a "select a
// certificate" prompt real browsers can't meaningfully answer.
// Only enable it when a caCertificate is actually configured -
// existing internal/mTLS use of this class (any config that DOES
// set tls.caCertificate) keeps behaving exactly as before.
if(tlsInfo->cACertificate.getLength() > 0) {
SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_verify_depth(newCtx, 1);
if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL))
throw coreutils::Exception("Cannot verify locations.");
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) { void TLS::registerSocket(int fd) {
int ret; int ret;
+45 -1
View File
@@ -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,26 @@ 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);
// 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
@@ -78,7 +100,29 @@ 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;
// 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);
}; };
} }
+75 -7
View File
@@ -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 << ")";
}
} }
} }
} }
+23 -10
View File
@@ -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;
} }
} }
+57 -57
View File
@@ -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