Compare commits

...
25 Commits
Author SHA1 Message Date
barantandClaude Opus 5.5 a8514d9689 Add STARTTLS and strict CRLF framing; fix accept races and TLS stalls
STARTTLS (in-session TLS upgrade, RFC 3207 / 2595 style):
- TCPServer::enableStartTLS(TLSInfo&) builds startTLSContext for a
  plain-text listener; TCPSession::startTLS(ctx) sends the queued
  ready reply in clear (Socket::flushPlain), discards any input
  pipelined after the command (CVE-2011-0411 injection class), then
  switches the socket to TLS and starts the handshake.
- TLS::buildContext() is static and runs process-wide OpenSSL init
  exactly once, so it can be called from createContext(),
  addSNIContext() and enableStartTLS(); frees a half-built context on
  error; SSL_CTX_use_PrivateKey_file() failure is detected (<= 0).
- ~TLS() frees the per-connection SSL object (leaked one per TLS
  connection before).

TLS receive stall:
- TCPSocket::receiveData() drains SSL_pending() before returning. A
  TLS record holds up to 16KB but reads are 4KB; with EPOLLET the rest
  of a record sat inside OpenSSL with no event to wake it, stalling
  large uploads (e.g. SMTP DATA) mid-stream.

Line framing (opt-in, defaults unchanged):
- TCPSocket::strictCRLF: only CR LF ends a line. SMTP needs this:
  accepting bare CR/LF as line ends is what makes SMTP smuggling
  (CVE-2023-51764/51765/51766) possible, and the lenient mode also
  split a CR LF straddling two reads into two lines, inserting a blank
  line into message bodies.
- TCPSocket::maxLineLength + onLineTooLong(): bound the line buffer so
  a peer that never sends a terminator can't exhaust memory.

Races that silently dropped connections (EPOLLONESHOT event delivered
before the object was registered, so Thread::run() ignored it and the
one-shot registration was spent):
- TCPServer constructor binds, listens and registers the listener
  before setDescriptor() arms it (about 3 startups in 8 accepted
  nothing, ever).
- TCPServer::accept() registers the session (sessions +
  registerLive) and, for implicit TLS, creates its SSL object before
  arming the fd (10-15% of a 40-connection burst never got a
  greeting). A failed ::accept() no longer creates and leaks a session.

Duplicate output:
- TCPSession::send() clears `out` before write() re-arms the socket;
  a handler running on another worker in that window re-sent the
  previous text (clients saw the greeting twice and every later reply
  shifted by one).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0121tAhQVe4qbCwYgVjKQS4B
2026-11-02 11:56:49 -08:00
barantandClaude Opus 5.5 c0e1d87ac1 Ignore SIGPIPE process-wide in EPoll
Writing to a socket the peer has already reset raises SIGPIPE, whose
default action kills the whole process. Socket.cpp carried a
sigpipe_handler but nothing ever installed it. OpenSSL's SSL_write()
calls write() itself, so MSG_NOSIGNAL can't cover TLS - ignore the
signal once for every server built on EPoll. Reproduced: a burst of
TLS clients disconnecting mid-session killed the server within a few
rounds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0121tAhQVe4qbCwYgVjKQS4B
2026-11-02 11:56:49 -08:00
barantandClaude Opus 5.5 4918654715 Implement IPAddress::getClientAddress()
It was a stub that always returned "", so everything keyed on the
client address saw an empty string: SPF checks in BARANTMail were run
against no IP at all, Received: headers had no address, and
IPAddressList black/white lists could never match.
getClientAddressAndPort() also used inet_ntoa() (a static buffer shared
across threads) and printed the port in network byte order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0121tAhQVe4qbCwYgVjKQS4B
2026-11-02 11:56:49 -08:00
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 1a15f6ced8 Add real authentication to ConsoleServer/ConsoleSession, fix CommandList help
ConsoleSession's login flow never actually checked anything: the
entered username was discarded and the password was never compared,
so any input (including blank) reached the command prompt. Confirmed
live via an unauthenticated login against BARANTMail's admin console
on port 1027, which was reachable externally. ConsoleServer now takes
an optional credentialChecker callback consulted by the WAIT_PASSWORD
state; omitting it preserves the old accept-anything behavior for any
other use of this class.

Separately, the console never prompted until the client's first line
arrived - that line was silently discarded just to kick the state
machine off, shifting every subsequent line one slot early. Harmless
under the old accept-anything login, but it broke real credential
checking outright (the typed password was compared against the typed
username, etc). ConsoleSession::onConnected() now starts the state
machine immediately on connect instead.

CommandList::processCommand() was a no-op stub - the intended
"typing help lists the registered commands" body was commented out,
and even referenced a Command::getName() that was never added to the
base class. The map's own key from add() already is the registered
name, so this just walks it directly.
2026-09-06 04:05:59 +00:00
Brad Arant 2676aaf84c Fix TLS write busy-spin on SSL_ERROR_WANT_READ
A TLS sendData() failing with SSL_ERROR_WANT_READ (mid-handshake
application data, or a post-handshake session ticket exchange) has
nothing to do with write-readiness, but resetSocket() kept re-arming
EPOLLWRNORM anyway - an already-writable TCP socket fires that
immediately, so the retry loop spun the CPU as fast as it could
until the connection was eventually dropped, without ever reading
the peer's first command. Confirmed via a 15GB+ debug log from one
stuck connection. sendNeedsRead() lets Socket now tell the
difference and wait for a real EPOLLIN instead of busy-retrying.
2026-09-06 04:05:40 +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
28 changed files with 1697 additions and 322 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;
} }
+26 -2
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));
} }
@@ -56,8 +73,15 @@ namespace core {
} }
int CommandList::processCommand(coreutils::ZString &request, TCPSession &session) { int CommandList::processCommand(coreutils::ZString &request, TCPSession &session) {
// for(Command *command : commands) // The intent was always "typing help lists the available
// session.out << command->getName() << std::endl; // commands" - this was left as a no-op stub (the commented-out
// body even called a Command::getName() that was never added to
// the base class) so every registered CommandList - including
// the top-level one behind the "help" command itself - silently
// did nothing. The map's own key IS the registered name (see
// add()), so no getName() is needed at all - just walk it directly.
for (auto &pair : commands)
session.out << pair.first << std::string("\r\n");
return true; return true;
} }
+14 -3
View File
@@ -5,17 +5,28 @@
namespace core { namespace core {
ConsoleServer::ConsoleServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo) : TCPServer(ePoll, address, tlsInfo, " ", 10, "Console Server") { ConsoleServer::ConsoleServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo,
std::function<bool(std::string, std::string)> credentialChecker)
: TCPServer(ePoll, address, tlsInfo, " ", 10, "Console Server"), credentialChecker(credentialChecker) {
coreutils::Log(this); coreutils::Log(this);
} }
void ConsoleServer::logSend(std::string out) { void ConsoleServer::logSend(std::string out) {
for(auto *session : sessions) // Was unlocked entirely (and iterated raw pointers before
((ConsoleSession *)session)->writeLog(out); // TCPServer::sessions became shared_ptr-owned - see its own doc
// comment) despite connectionRequest()/removeFromSessionList()
// both mutating this same vector under `lock` from other threads.
std::lock_guard guard(lock);
for(auto &session : sessions)
((ConsoleSession *)session.get())->writeLog(out);
} }
TCPSession * ConsoleServer::getSocketAccept(EPoll &ePoll) { TCPSession * ConsoleServer::getSocketAccept(EPoll &ePoll) {
return new ConsoleSession(ePoll, this); return new ConsoleSession(ePoll, this);
} }
bool ConsoleServer::checkCredentials(std::string user, std::string password) {
return credentialChecker ? credentialChecker(user, password) : true;
}
} }
+15 -2
View File
@@ -6,6 +6,8 @@
# include "EPoll.h" # include "EPoll.h"
# include "LogListener.h" # include "LogListener.h"
# include "TLSInfo.h" # include "TLSInfo.h"
# include <functional>
# include <string>
namespace core { namespace core {
@@ -21,10 +23,16 @@ namespace core {
public: public:
// //
// // credentialChecker, when provided, is consulted by
// ConsoleSession's login flow (see its own doc comment) instead
// of the previous unconditional accept-anything behavior. Left
// defaulting to nullptr so any other, unrelated use of
// ConsoleServer that never cared about authentication is
// unaffected.
// //
ConsoleServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo); ConsoleServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo,
std::function<bool(std::string, std::string)> credentialChecker = nullptr);
// //
// //
@@ -34,6 +42,11 @@ namespace core {
TCPSession * getSocketAccept(EPoll &ePoll) override; TCPSession * getSocketAccept(EPoll &ePoll) override;
bool checkCredentials(std::string user, std::string password);
private:
std::function<bool(std::string, std::string)> credentialChecker;
}; };
} }
+25 -2
View File
@@ -1,4 +1,5 @@
#include "ConsoleSession.h" #include "ConsoleSession.h"
#include "ConsoleServer.h"
#include "TCPServer.h" #include "TCPServer.h"
#include "Log.h" #include "Log.h"
@@ -27,6 +28,10 @@ namespace core {
break; break;
case WAIT_USER_PROFILE: case WAIT_USER_PROFILE:
// Previously discarded entirely - nothing captured what was
// actually typed here, so a real credential check further
// down could never have anything to compare against.
enteredUser = data.str();
status = PASSWORD; status = PASSWORD;
protocol(blank); protocol(blank);
break; break;
@@ -37,8 +42,21 @@ namespace core {
break; break;
case WAIT_PASSWORD: case WAIT_PASSWORD:
status = PROMPT; // The actual check: previously this state unconditionally
protocol(blank); // advanced to PROMPT regardless of what (if anything) was
// entered at either step - any username/password, including
// blank, reached the command prompt. checkCredentials()
// returns true unconditionally when the owning ConsoleServer
// was built without a credentialChecker, preserving that
// exact behavior for any other use of this class.
if (((ConsoleServer *)server)->checkCredentials(enteredUser, data.str())) {
status = PROMPT;
protocol(blank);
} else {
out << "Login failed." << "\r\n";
status = DONE;
protocol(blank);
}
break; break;
case PROMPT: case PROMPT:
@@ -68,6 +86,11 @@ namespace core {
} }
} }
void ConsoleSession::onConnected() {
coreutils::ZString blank("");
protocol(blank);
}
void ConsoleSession::writeLog(std::string data) { void ConsoleSession::writeLog(std::string data) {
// saveCursor(); // saveCursor();
// setCursorLocation(16, 1); // setCursorLocation(16, 1);
+24
View File
@@ -16,6 +16,14 @@ namespace core {
/// Extend the protocol() method in order to define the behavior and /// Extend the protocol() method in order to define the behavior and
/// protocol interaction for this socket which is a console session. /// protocol interaction for this socket which is a console session.
/// ///
/// The User:/Password: exchange is a real login when the owning
/// ConsoleServer was constructed with a credentialChecker (see its
/// own doc comment) - previously the entered username was never
/// even stored and the password was never compared against
/// anything, so any input (including blank) reached the command
/// prompt. A ConsoleServer built without a credentialChecker still
/// accepts anything, matching that original behavior exactly.
///
class ConsoleSession : public TerminalSession { class ConsoleSession : public TerminalSession {
@@ -28,11 +36,27 @@ namespace core {
protected: protected:
void protocol(coreutils::ZString &data) override; void protocol(coreutils::ZString &data) override;
// Previously absent entirely, so the state machine only ever
// advanced on the CLIENT's first line of input - that line was
// consumed just to drive WELCOME->LOGIN and was never used as
// real content, meaning every subsequent line was shifted one
// slot early (what the user typed as their *username* actually
// got compared as nothing, their *password* got captured as
// enteredUser, and their first real command got compared as the
// password). Harmless before real credential checking existed -
// any input reached the prompt regardless - but it broke login
// outright once checkCredentials() started actually comparing
// values. Kicking the state machine off here instead means
// "User: " is sent immediately on connect, before the client
// has sent anything at all.
void onConnected() override;
private: private:
enum Status {WELCOME, LOGIN, WAIT_USER_PROFILE, PASSWORD, WAIT_PASSWORD, PROMPT, INPUT, PROCESS, DONE}; enum Status {WELCOME, LOGIN, WAIT_USER_PROFILE, PASSWORD, WAIT_PASSWORD, PROMPT, INPUT, PROCESS, DONE};
Status status = WELCOME; Status status = WELCOME;
void doCommand(coreutils::ZString &request); void doCommand(coreutils::ZString &request);
coreutils::ZString command; coreutils::ZString command;
std::string enteredUser;
}; };
+11
View File
@@ -11,6 +11,17 @@ namespace core {
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPoll starting."; coreutils::Log(coreutils::LOG_DEBUG_2) << "EPoll starting.";
// Writing to a socket whose peer has already reset it raises
// SIGPIPE, and the default action terminates the whole process -
// every connection, not just the dead one. Socket.cpp has carried a
// sigpipe_handler for this but nothing ever installed it. Plain
// writes could use MSG_NOSIGNAL, but OpenSSL's SSL_write() calls
// write() itself, so the signal has to be ignored process-wide; the
// failed write then just returns EPIPE and that one connection is
// closed normally. Reproduced: a burst of STARTTLS clients
// disconnecting mid-session killed the server within a few rounds.
signal(SIGPIPE, SIG_IGN);
maxSockets = 1000; maxSockets = 1000;
epfd = epoll_create1(0); epfd = epoll_create1(0);
terminateThreads = false; terminateThreads = false;
+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;
}
}; };
} }
+11 -4
View File
@@ -38,15 +38,22 @@ namespace core {
return (sockaddr *)&addr; return (sockaddr *)&addr;
} }
// Was a stub that always returned "" - so everything keyed on the
// client address (SPF checks in BARANTMail, Received: headers,
// IPAddressList black/white lists) silently saw an empty string.
std::string IPAddress::getClientAddress() { std::string IPAddress::getClientAddress() {
std::string result; char text[INET_ADDRSTRLEN];
return result; if (!inet_ntop(AF_INET, &addr.sin_addr, text, sizeof(text)))
return "";
return text;
} }
std::string IPAddress::getClientAddressAndPort() { std::string IPAddress::getClientAddressAndPort() {
std::stringstream out; std::stringstream out;
out << inet_ntoa(addr.sin_addr); // inet_ntoa() returns a static buffer shared by every thread, and
out << ":" << addr.sin_port; // sin_port is in network byte order.
out << getClientAddress();
out << ":" << ntohs(addr.sin_port);
return out.str(); return out.str();
} }
+127 -5
View File
@@ -4,6 +4,8 @@
#include "Log.h" #include "Log.h"
#include "ZString.h" #include "ZString.h"
#include <iostream> #include <iostream>
#include <poll.h>
#include <sys/socket.h>
namespace core namespace core
{ {
@@ -80,6 +82,12 @@ namespace core
} }
if(event.events & EPOLLIN) { if(event.events & EPOLLIN) {
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLIN"; coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLIN";
// A read just happened (or at least an opportunity for OpenSSL
// to make progress on whatever it needed a read for) - give any
// write that was waiting on that a fresh attempt via this same
// call's own trailing resetSocket(), rather than leaving
// EPOLLWRNORM permanently un-armed from a single earlier stall.
waitingOnReadToWrite = false;
coreutils::ZString zbuffer(buffer, length); coreutils::ZString zbuffer(buffer, length);
// receiveData() calls all the way down through // receiveData() calls all the way down through
// onDataReceived()/HTTPRequest::doParse()/application request // onDataReceived()/HTTPRequest::doParse()/application request
@@ -122,7 +130,6 @@ namespace core
coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM"; coreutils::Log(coreutils::LOG_DEBUG_2) << "EPOLLWRNORM";
writeSocket(); writeSocket();
} }
inHandler = false;
// A graceful shutdown() (session.terminate() -> "goodbye" reply // A graceful shutdown() (session.terminate() -> "goodbye" reply
// queued via write(), then shutdown() called - see e.g. IMAP's // queued via write(), then shutdown() called - see e.g. IMAP's
// LOGOUT/POP3's QUIT/SMTP's QUIT) used to make keepAlive false // LOGOUT/POP3's QUIT/SMTP's QUIT) used to make keepAlive false
@@ -139,7 +146,7 @@ namespace core
// drain to a peer that's already gone is pointless, not graceful) // drain to a peer that's already gone is pointless, not graceful)
// - gives that queued reply a real chance to go out before this // - gives that queued reply a real chance to go out before this
// socket actually closes. // socket actually closes.
bool keepAlive = !shutDown || (fifo.size() > 0 && !readHangup); bool keepAlive = preventSelfDelete || !shutDown || (fifo.size() > 0 && !readHangup);
// resetSocket() re-arms this fd via EPOLL_CTL_MOD, which makes it // resetSocket() re-arms this fd via EPOLL_CTL_MOD, which makes it
// immediately eligible for delivery to ANY worker thread's // immediately eligible for delivery to ANY worker thread's
@@ -156,8 +163,45 @@ namespace core
// the last thing that ever touches `this`, with the return value // the last thing that ever touches `this`, with the return value
// already captured in a local (`keepAlive`) beforehand. // already captured in a local (`keepAlive`) beforehand.
coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor(); coreutils::Log(coreutils::LOG_DEBUG_1) << "Event process ending for socket " << getDescriptor();
if(keepAlive) // Was cleared several statements above (right after the EPOLLIN/
// EPOLLWRNORM handling), with no lock held around clearing it or
// calling resetSocket() below - a genuinely separate race from the
// one documented above: Socket::write() re-arms via this same
// resetSocket() (see its own doc comment there) whenever it can
// grab `lock`, from whatever thread called it (e.g. a broadcast
// hitting this session while ITS OWN eventReceived() call is still
// running, past receiveData()'s lock_guard but before reaching
// here). A first attempt narrowed this to just checking `inHandler`
// in both places, without holding `lock` across the check-and-act
// in either one - still a real TOCTOU window (inHandler read as
// false here, then write() on another thread sees false too and
// wins the race to resetSocket() first), confirmed live via
// AddressSanitizer as a genuine double-delete of the same session
// object (two threads both reaching ~TCPSession() on it) even
// after that narrowing. Holding `lock` for the whole
// clear-then-reset sequence - the exact same mutex write() already
// takes before its own resetSocket() call - makes the two
// mutually exclusive for real: whichever thread gets there first
// fully finishes (clearing inHandler and re-arming, or observing
// inHandler still true and skipping) before the other can act at
// all, closing the window rather than just narrowing it.
if(keepAlive) {
lock.lock();
inHandler = false;
resetSocket(); resetSocket();
lock.unlock();
}
// else: this object is about to be delete()'d by Thread::run() the
// moment this call returns, unconditionally, regardless of
// anything write() does. Leaving inHandler true forever (never
// clearing it here) means no other thread's write() can ever
// resetSocket() this dying object in the meantime - it has no
// future to reset it FOR, and letting write() re-arm it here, even
// briefly, was exactly the remaining gap: a third thread could
// pick up that re-armed fd and touch/delete an object Thread::run()
// was already about to free, a genuine double-delete confirmed
// live via AddressSanitizer even after write()/resetSocket() were
// otherwise fully serialized against each other.
return keepAlive; return keepAlive;
} }
@@ -205,6 +249,28 @@ namespace core
return ::write(descriptor, data, length); return ::write(descriptor, data, length);
} }
bool Socket::flushPlain(int timeoutMs) {
std::lock_guard<std::mutex> guard(outlock);
while(fifo.size() > 0) {
std::string &front = fifo.front();
ssize_t sent = ::send(descriptor, front.data(), front.length(), MSG_NOSIGNAL);
if(sent > 0) {
if((size_t)sent >= front.length())
fifo.pop();
else
front.erase(0, sent);
continue;
}
if(sent < 0 && (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR)) {
struct pollfd pfd = { descriptor, POLLOUT, 0 };
if(::poll(&pfd, 1, timeoutMs) > 0)
continue;
}
return false;
}
return true;
}
void Socket::writeSocket() { void Socket::writeSocket() {
outlock.lock(); outlock.lock();
// coreutils::Log(coreutils::LOG_DEBUG_3) << "writing data to socket " << getDescriptor(); // coreutils::Log(coreutils::LOG_DEBUG_3) << "writing data to socket " << getDescriptor();
@@ -241,10 +307,18 @@ namespace core
int sent = sendData(fifo.front().c_str(), fifo.front().length()); int sent = sendData(fifo.front().c_str(), fifo.front().length());
if(sent > 0) { if(sent > 0) {
consecutiveWriteStalls = 0; consecutiveWriteStalls = 0;
waitingOnReadToWrite = false;
if((size_t)sent >= fifo.front().length()) if((size_t)sent >= fifo.front().length())
fifo.pop(); fifo.pop();
else else
fifo.front().erase(0, sent); fifo.front().erase(0, sent);
} else if(sendNeedsRead()) {
// Not a stall in the CPU-spinning sense consecutiveWriteStalls
// exists to catch - resetSocket() below simply won't re-arm
// EPOLLWRNORM while this is true, so there's nothing to busy-
// retry until a real EPOLLIN event (already always watched
// for) brings in whatever OpenSSL is actually waiting to read.
waitingOnReadToWrite = true;
} else if(++consecutiveWriteStalls > 50) { } else if(++consecutiveWriteStalls > 50) {
// sendData() keeps failing for a reason that has nothing to // sendData() keeps failing for a reason that has nothing to
// do with the socket's own write-readiness (confirmed real // do with the socket's own write-readiness (confirmed real
@@ -258,6 +332,26 @@ namespace core
// the confirmed real damage (a 55GB, then 12.9GB debug log) // the confirmed real damage (a 55GB, then 12.9GB debug log)
// this caused before being noticed. // this caused before being noticed.
coreutils::Log(coreutils::LOG_EXCEPT) << "Socket " << getDescriptor() << ": " << consecutiveWriteStalls << " consecutive writes made zero progress - giving up and shutting down."; coreutils::Log(coreutils::LOG_EXCEPT) << "Socket " << getDescriptor() << ": " << consecutiveWriteStalls << " consecutive writes made zero progress - giving up and shutting down.";
// shutdown() alone only sets shutDown=true and expects the
// fifo to drain normally before the connection actually
// closes (see eventReceived()'s keepAlive: "!shutDown ||
// (fifo.size() > 0 && !readHangup)") - exactly backwards
// for THIS path, since the whole reason we're here is that
// the front of the fifo can never be sent. Leaving it
// queued meant keepAlive stayed true forever, resetSocket()
// kept re-arming EPOLLWRNORM because fifo.size() > 0, the
// very next write attempt hit this identical stall
// immediately, and shutdown() got called again - forever,
// at whatever rate the kernel could fire EPOLLWRNORM.
// Confirmed live: 2.4 million+ repeats of this exact log
// line for one socket in under 4 milliseconds, pegging a
// worker thread at 100% CPU indefinitely (a real game
// server, brought down by nothing more than an ordinary
// port-scanner connection). Clearing the undeliverable data
// here lets keepAlive correctly evaluate to just !shutDown
// (now false) on the very next cycle, so the connection
// actually tears down instead of spinning forever.
std::queue<std::string>().swap(fifo);
shutdown("stuck write retry loop - no progress after repeated attempts"); shutdown("stuck write retry loop - no progress after repeated attempts");
} }
} }
@@ -269,8 +363,36 @@ namespace core
outlock.lock(); outlock.lock();
fifo.emplace(data); fifo.emplace(data);
outlock.unlock(); outlock.unlock();
// Was unconditional - re-arming here (resetSocket() -> EPOLL_CTL_MOD)
// while this socket's OWN eventReceived() call is still mid-flight
// on another thread (inHandler true - see eventReceived()'s own
// comment on exactly this race) makes the fd immediately eligible
// for a THIRD thread to pick up a fresh event and potentially
// delete this object (Thread::run() does exactly that on a false
// return) while the first thread is still touching it - a genuine
// use-after-free, matching a real heap-corruption crash confirmed
// live via dmesg/AddressSanitizer under concurrent load.
// eventReceived() already re-arms itself once it's actually done
// (checking the current fifo, which already includes whatever was
// just queued above); skip doing it a second, early time from here
// while that's still in progress - the data isn't lost, just
// picked up on that call's own re-arm instead of this one's.
//
// inHandler must be re-checked AFTER acquiring `lock`, not just
// before try_lock() - checking it first and then separately
// acquiring the lock leaves a real TOCTOU gap (this thread reads
// inHandler==false, eventReceived() flips it back and forth on
// another thread, both end up calling resetSocket()); a first
// attempt at this fix only checked before, and a genuine
// double-delete of the same session object still reproduced live
// under AddressSanitizer despite it. eventReceived() holds this
// exact same `lock` across its own inHandler-clear-then-reset
// sequence now (see its own comment), so re-checking inHandler
// only after try_lock() succeeds makes the two truly mutually
// exclusive.
if(lock.try_lock()) { if(lock.try_lock()) {
resetSocket(); if(!inHandler)
resetSocket();
lock.unlock(); lock.unlock();
} }
return 1; return 1;
@@ -307,7 +429,7 @@ namespace core
struct epoll_event event; struct epoll_event event;
event.data.ptr = this; event.data.ptr = this;
event.events = EPOLLIN | EPOLLRDHUP | EPOLLONESHOT | EPOLLET; event.events = EPOLLIN | EPOLLRDHUP | EPOLLONESHOT | EPOLLET;
if(fifo.size() > 0) if(fifo.size() > 0 && !waitingOnReadToWrite)
event.events |= EPOLLWRNORM; event.events |= EPOLLWRNORM;
// Was `if(!shutDown)` - refused to re-arm at all once shutting // Was `if(!shutDown)` - refused to re-arm at all once shutting
// down, even with data still queued to send (e.g. a graceful // down, even with data still queued to send (e.g. a graceful
+63 -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);
@@ -182,13 +200,44 @@ namespace core {
virtual int sendData(const char *data, int length); virtual int sendData(const char *data, int length);
///
/// Overridden by TCPSocket to report whether the last sendData()
/// call failed specifically because the TLS layer needs a READ to
/// make progress (SSL_ERROR_WANT_READ), as opposed to any other
/// reason - see waitingOnReadToWrite's own doc comment for why
/// writeSocket()/resetSocket() need to know this. Always false for
/// a plain (non-TLS) socket, which has no such distinction.
///
virtual bool sendNeedsRead() { return false; }
///
/// Synchronously write everything queued in the outbound fifo as
/// plain bytes (never through a TLS layer), waiting up to timeoutMs
/// for the socket to accept it. Returns false if it couldn't.
///
/// Only for protocol upgrades (STARTTLS): the server's "go ahead"
/// reply has to reach the client in clear text, and the switch to
/// TLS has to happen right after the last byte of it - not whenever
/// a later EPOLLWRNORM gets around to draining the fifo, by which
/// point the session would already be reading TLS. Must be called
/// from inside this socket's own eventReceived() (EPOLLONESHOT then
/// guarantees no other thread is writing to the fd).
///
bool flushPlain(int timeoutMs);
private: private:
std::string text; std::string text;
int descriptor = -1; int descriptor = -1;
std::mutex outlock; std::mutex outlock;
bool readHangup = false; bool readHangup = false;
volatile bool inHandler = false; // Was `volatile bool` - volatile gives no actual thread-safety
// (no atomicity, no cross-thread visibility guarantee), and this
// flag is now load-bearing (see Socket::write()'s own check of it)
// rather than just feeding a diagnostic log line.
std::atomic<bool> inHandler{false};
//------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------
// the writeSocket is called when epoll has received a write request for a socket. // the writeSocket is called when epoll has received a write request for a socket.
@@ -226,6 +275,19 @@ namespace core {
// clearly never going to un-stick itself and gets shut down. // clearly never going to un-stick itself and gets shut down.
int consecutiveWriteStalls = 0; int consecutiveWriteStalls = 0;
// Set by writeSocket() when the last failed send specifically
// needed a read to proceed (sendNeedsRead() true) rather than
// being genuinely stalled on write-readiness. resetSocket() skips
// adding EPOLLWRNORM to the re-armed event mask while this is
// true - re-arming it anyway just spins the CPU as fast as it can
// loop, since an already-writable TCP socket keeps firing
// EPOLLWRNORM immediately while the actual blocker (more bytes
// from the peer) has nothing to do with write-readiness at all.
// Cleared on any EPOLLIN event (see eventReceived()) so the write
// gets a fresh attempt via that same event's own trailing
// resetSocket() call, once there's real reason to expect progress.
bool waitingOnReadToWrite = false;
void resetSocket(); void resetSocket();
std::mutex lock; std::mutex lock;
+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; };
};
} }
+215 -59
View File
@@ -3,21 +3,67 @@
#include "Exception.h" #include "Exception.h"
#include "Log.h" #include "Log.h"
#include "TCPSession.h" #include "TCPSession.h"
#include <chrono>
#include <vector>
namespace core { namespace core {
TCPServer::TCPServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo, std::string delimiter, int depth, std::string text) TCPServer::TCPServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo, std::string delimiter, int depth, std::string text)
: TCPSocket(ePoll, tlsInfo, text), commands(delimiter, depth) { : TCPSocket(ePoll, tlsInfo, text), commands(delimiter, depth) {
setDescriptor(socket(AF_INET, SOCK_STREAM, 0)); // Wires the subscription (pub/sub) command set into this server's
// own command dispatch - previously missing entirely here (the
// subscriptions member existed but nothing ever routed these verbs
// to it), so publish/subscribe/catalog/etc were unreachable on any
// TCPServer built after the TLS work, even though SubscriptionManager
// itself was still fully implemented.
commands.add(subscriptions, "publish");
commands.add(subscriptions, "unpublish");
commands.add(subscriptions, "subscribe");
commands.add(subscriptions, "unsubscribe");
commands.add(subscriptions, "catalog");
commands.add(subscriptions, "event");
commands.add(subscriptions, "invite");
// Bind, listen and register as a known listening socket BEFORE
// setDescriptor() adds the fd to epoll. setDescriptor() arms it
// immediately (EPOLLONESHOT), and a brand-new socket that isn't
// listening yet reports EPOLLHUP right away. That event used to race
// the rest of this constructor: whenever an epoll worker thread
// picked it up before the listeningSockets().insert() below,
// Thread::run() didn't recognize the pointer and skipped it without
// re-arming, so the one-shot registration was spent and the server
// never saw another connection - up, bound and listening, but
// silently accepting nothing for the life of the process. Reproduced
// on an unmodified build: roughly 3 startups in 8 dead on arrival.
int fd = socket(AF_INET, SOCK_STREAM, 0);
int yes = 1; int yes = 1;
setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
if (bind(getDescriptor(), address.getPointer(), address.addressLength) < 0) if (bind(fd, address.getPointer(), address.addressLength) < 0) {
throw coreutils::Exception("Error on bind to socket: " + std::to_string(errno)); int error = errno;
close(fd);
throw coreutils::Exception("Error on bind to socket: " + std::to_string(error));
}
if (listen(getDescriptor(), 20) < 0) // Was 20 - small enough that a burst of connection attempts
throw coreutils::Exception("Error on listen to socket"); // arriving faster than this process calls accept() (a port scan,
// or just several real clients reconnecting around the same
// moment) can fill the kernel's own backlog before the
// application layer gets a chance to drain it, silently dropping
// the overflow SYNs rather than queuing them. 128 gives real
// bursts meaningfully more headroom; still bounded, not unlimited.
if (listen(fd, 128) < 0) {
close(fd);
throw coreutils::Exception("Error on listen to socket");
}
{
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
listeningSockets().insert(this);
}
setDescriptor(fd);
} }
TCPServer::~TCPServer() { TCPServer::~TCPServer() {
@@ -27,25 +73,51 @@ namespace core {
void TCPServer::connectionRequest() { void TCPServer::connectionRequest() {
coreutils::Log(coreutils::LOG_DEBUG_2) << "Connection request is being received on socket " << getDescriptor() << "."; coreutils::Log(coreutils::LOG_DEBUG_2) << "Connection request is being received on socket " << getDescriptor() << ".";
// Outside the lock.lock()/unlock() below, not nested inside it -
// sweepStaleSessions() takes the same `lock` itself (see its own
// comment), and this mutex isn't recursive.
sweepStaleSessions();
lock.lock(); lock.lock();
TCPSession *session = accept(); // accept() now adds the session to `sessions` and the live registry
if (session) // itself, before its fd is armed - see the comment there.
sessions.push_back(session); // accept() registers the session and, for an implicit-TLS listener,
// Must run ON THE SESSION, not `this` (the listening server) - the // starts its TLS handshake (on the session, not on `this`) before
// unqualified registerSocket()/acceptSocket() calls this replaced // arming the fd - see its own comment.
// built the SSL* handshake state on the SERVER's own TLS-base accept();
// member instead of the newly accepted session's, leaving every
// session's own `ssl` uninitialized and segfaulting the first time
// real data arrived on it (SSL_read() against a never-SSL_new()'d
// pointer - confirmed via gdb). Sessions already correctly inherit
// this server's SSL_CTX at construction (TCPSession's own
// TLS(SSL_CTX*)-taking constructor) - performTLSHandshake() just
// needed to actually be invoked on that object.
if (session && tlsInfo)
session->performTLSHandshake();
lock.unlock(); lock.unlock();
} }
void TCPServer::sweepStaleSessions() {
// 30 seconds is generous for completing a TCP handshake plus a
// TLS handshake plus sending a first real message over any real
// network - deliberately not aimed at catching anything borderline,
// only connections that never progressed at all.
static const std::chrono::seconds GRACE_PERIOD(30);
auto now = std::chrono::steady_clock::now();
// Collect under `lock` (sessions is mutated elsewhere under the
// same mutex - see its own doc comment), then drop the lock before
// actually removing anything. removeFromSessionList() takes `lock`
// itself for each call; calling it while still holding the guard
// below would deadlock on this non-recursive mutex.
std::vector<TCPSession *> stale;
{
std::lock_guard guard(lock);
for (auto &s : sessions)
if (!s->hasReceivedData && (now - s->acceptedAt) > GRACE_PERIOD)
stale.push_back(s.get());
}
for (auto *s : stale) {
coreutils::Log(coreutils::LOG_DEBUG_2) << "Reaping stale, never-active session " << s->getDescriptor() << ".";
removeFromSessionList(s);
}
}
void TCPServer::enableStartTLS(TLSInfo &tlsInfo) {
startTLSContext = TLS::buildContext(&tlsInfo);
}
void TCPServer::receiveData(coreutils::ZString &buffer) { void TCPServer::receiveData(coreutils::ZString &buffer) {
// See this override's own doc comment in TCPServer.h - the // See this override's own doc comment in TCPServer.h - the
// listening socket always uses the plain read()/ENOTCONN detection // listening socket always uses the plain read()/ENOTCONN detection
@@ -56,40 +128,103 @@ namespace core {
TCPSession * TCPServer::accept() { TCPSession * TCPServer::accept() {
try { // Called with `lock` held (connectionRequest()).
//
// The session must be owned by `sessions` and registered with
// TCPSession::registerLive() BEFORE setDescriptor() adds its fd to
// epoll. setDescriptor() arms the fd and runs onConnected(), which
// queues the protocol greeting ("220 ..." for SMTP) and re-arms for
// EPOLLWRNORM; another epoll worker can pick that event up at once.
// Registration used to happen afterwards, back in
// connectionRequest(), so whenever a worker got there first
// Thread::run()'s TCPSession::tryGet() didn't know the pointer and
// dropped the event without re-arming (EPOLLONESHOT): the client
// was connected but never received a single byte. Reproduced on an
// unmodified build with 40 simultaneous plain-text SMTP
// connections - 4 to 6 per burst stuck before the greeting. For a
// mail server that is lost (well, deferred) inbound mail.
//
// Accepting into a local address first also means a failed
// ::accept() (EAGAIN on a spurious wakeup, EMFILE) no longer creates
// - and then leaks - a session object at all.
TCPSession *session = getSocketAccept(ePoll); struct sockaddr_in address;
session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength)); socklen_t addressLength = sizeof(address);
// if(blackList && blackList->contains(session->ipAddress.getClientAddress())) { int fd = ::accept(getDescriptor(), (struct sockaddr *)&address, &addressLength);
// session->shutdown(); if (fd < 0) {
// Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is blacklisted and was denied a connection."; if (errno == EMFILE || errno == ENFILE)
// return NULL; coreutils::Log(coreutils::LOG_EXCEPT) << "Too many files open. Refusing connection.";
// } return NULL;
// if(whiteList && !whiteList->contains(session->ipAddress.getClientAddress())) {
// session->shutdown();
// Log(LOG_WARN) << "Client at IP address " << session->ipAddress.getClientAddress() << " is not authorized and was denied a connection.";
// return NULL;
// }
return session;
} }
catch (coreutils::Exception e) {
coreutils::Log(coreutils::LOG_EXCEPT) << "Major error on session initialization. Error is '" << e.text << "'."; TCPSession *session = NULL;
try {
session = getSocketAccept(ePoll);
} }
catch (...) { catch (...) {
coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization."; coreutils::Log(coreutils::LOG_EXCEPT) << "Error creating session object; connection refused.";
close(fd);
return NULL;
} }
return NULL; session->ipAddress.addr = address;
session->ipAddress.addressLength = addressLength;
auto sessionPtr = std::shared_ptr<TCPSession>(session);
sessions.push_back(sessionPtr);
TCPSession::registerLive(session, sessionPtr);
try {
// Implicit TLS (this listener was built with a TLSInfo): create
// the session's SSL object and start SSL_accept() before the fd
// goes into epoll, for the same reason registration comes first -
// otherwise a worker can pick up the greeting onConnected() queues
// and reach TLS::sendData() before there's an SSL object to send
// it through.
if (tlsInfo)
session->performTLSHandshake(fd);
session->setDescriptor(fd);
}
catch (coreutils::Exception e) {
// Already owned and registered, so it is cleaned up through the
// normal shutdown path rather than deleted here (deleting would
// re-enter removeFromSessionList() while `lock` is held).
coreutils::Log(coreutils::LOG_EXCEPT) << "Major error on session initialization. Error is '" << e.text << "'.";
session->shutdown("session initialization failed");
}
catch (...) {
coreutils::Log(coreutils::LOG_EXCEPT) << "Unnspecified error on session initialization.";
session->shutdown("session initialization failed");
}
return session;
} }
void TCPServer::removeFromSessionList(TCPSession *session) { void TCPServer::removeFromSessionList(TCPSession *session) {
std::vector<TCPSession *>::iterator cursor;
lock.lock(); lock.lock();
for(cursor = sessions.begin(); cursor < sessions.end(); ++cursor) for (auto cursor = sessions.begin(); cursor < sessions.end(); ++cursor)
if(*cursor == session) { if (cursor->get() == session)
sessions.erase(cursor); {
break; // Drops the one strong-owning reference. If nothing else is
} // currently pin()'d to this session, the object is actually
// destroyed right here, synchronously - same timing as
// before this change for the common (no-contention) case.
// If some other thread IS mid-call via its own pin()'d
// shared_ptr right now, destruction is safely deferred until
// that reference is released too, instead of the crash
// (double-delete / use-after-free, confirmed live via
// AddressSanitizer under concurrent load) that raw-pointer
// ownership produced here before.
sessions.erase(cursor);
break;
}
lock.unlock(); lock.unlock();
// Removes this pointer from the tryGet() lookup registry too (see
// TCPSession::tryGet()'s own comment). Safe to do after releasing
// `lock` and regardless of whether the erase() above was actually
// the last reference: tryGet() correctly reports "gone" the moment
// a session's real refcount hits zero, via the weak_ptr's own
// expiration - this call is just tidying the registry map itself,
// not something later correctness depends on.
TCPSession::unregisterLive(session);
} }
void TCPServer::sessionErrorHandler(std::string errorString, std::stringstream &out) { void TCPServer::sessionErrorHandler(std::string errorString, std::stringstream &out) {
@@ -100,13 +235,30 @@ namespace core {
return new TCPSession(ePoll, this); return new TCPSession(ePoll, this);
} }
void TCPServer::output(std::stringstream &out) { void TCPServer::output(std::stringstream &out)
{
out << "Use the 'help' command to list the commands for this server." << std::endl; out << "Use the 'help' command to list the commands for this server." << std::endl;
} }
int TCPServer::processCommand(coreutils::ZString &request, TCPSession &session) { int TCPServer::processCommand(coreutils::ZString &request, TCPSession &session)
{
// Was unguarded, like every other method below - `sessions` is
// mutated under `lock` by connectionRequest()/removeFromSessionList()
// (a session accepting or disconnecting on another thread), but
// every READ of it here had no lock at all. Confirmed live via
// dmesg: a real segfault at a stable, deterministic instruction
// offset (same crash signature as the Subscription::subscribers
// race fixed earlier this session, in SubscriptionManager.cpp) -
// Socket::write() -> resetSocket() dereferencing a null EPoll
// reference, consistent with iterating `sessions` while another
// thread concurrently erased and freed one of its entries.
// sendToAll() in particular is what most real gameplay broadcasts
// (combat, position, chat) go through, so this is very likely the
// actual dominant cause of that crash, not just the ItemDataBase
// subscriber list this session's earlier fix addressed.
std::lock_guard guard(lock);
int sequence = 0; int sequence = 0;
for (auto *sessionx : sessions) for (auto &sessionx : sessions)
{ {
session.out << "|" << ++sequence; session.out << "|" << ++sequence;
sessionx->output(session.out); sessionx->output(session.out);
@@ -116,32 +268,36 @@ namespace core {
} }
void TCPServer::sendToAll(std::stringstream &data) { void TCPServer::sendToAll(std::stringstream &data) {
for (auto session : sessions) std::lock_guard guard(lock);
for (auto &session : sessions)
session->write(data.str()); session->write(data.str());
data.str(""); data.str("");
} }
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender) { void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender) {
for (auto session : sessions) std::lock_guard guard(lock);
if (session != &sender) for (auto &session : sessions)
if (session.get() != &sender)
session->write(data.str()); session->write(data.str());
data.str(""); data.str("");
} }
void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter) { void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter) {
for (auto session : sessions) std::lock_guard guard(lock);
for (auto &session : sessions)
if (filter.test(*session)) if (filter.test(*session))
if (session != &sender) if (session.get() != &sender)
session->write(data.str()); session->write(data.str());
data.str(""); data.str("");
} }
TCPSession *TCPServer::getSessionByAlias(void *alias) { std::shared_ptr<TCPSession> TCPServer::getSessionByAlias(void *alias) {
coreutils::Log(coreutils::LOG_DEBUG_1) << alias; coreutils::Log(coreutils::LOG_DEBUG_1) << alias;
for (auto session : sessions) std::lock_guard guard(lock);
if (session->compareAlias(alias)) for (auto &session : sessions)
return session; if (session->alias == alias)
return NULL; return session;
return nullptr;
} }
} }
+136 -6
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,36 @@ namespace core {
/// ///
/// Use the getSessionByAlias to retrieve a session pointer by the value /// Use the getSessionByAlias to retrieve a session pointer by the value
/// of the alias pointer. /// of the alias pointer. Returns an already-pin()'d shared_ptr (null
/// if not found) rather than a raw pointer, so callers can't
/// accidentally hold onto - or use - a reference that isn't actually
/// keeping the session alive.
/// ///
TCPSession *getSessionByAlias(void *alias); std::shared_ptr<TCPSession> getSessionByAlias(void *alias);
///
/// Offer TLS as an in-session upgrade (STARTTLS) on an otherwise
/// plain-text listener, as SMTP on port 25 requires. Unlike passing
/// tlsInfo to the constructor (implicit TLS - the handshake starts
/// the moment a connection is accepted, as on ports 465/993/995),
/// sessions here start in clear text and switch only when a command
/// handler calls TCPSession::startTLS(server->startTLSContext).
///
/// Throws coreutils::Exception if the certificate or key can't be
/// loaded; startTLSContext stays NULL in that case, so a caller that
/// catches it can keep serving without STARTTLS.
///
void enableStartTLS(TLSInfo &tlsInfo);
///
/// The context sessions switch to on STARTTLS. NULL until
/// enableStartTLS() succeeds - protocol code should only advertise
/// STARTTLS when this is set.
///
SSL_CTX *startTLSContext = NULL;
protected: protected:
/// ///
@@ -132,6 +172,31 @@ namespace core {
void connectionRequest() override; void connectionRequest() override;
///
/// Drops any session that completed a TCP accept() but has never
/// had a single byte of real data pass through onDataReceived() -
/// covers both a TLS handshake that never finishes and a plain
/// connection that never sends anything - once it's been open
/// longer than a short grace period. Nothing else in this class
/// ever revisits an already-accepted session once it stops
/// generating epoll events (Thread::run()'s dispatch loop only
/// acts on a session when a real event for it arrives), so a
/// connection that completes the handshake and then goes
/// permanently silent - exactly what a port scan/prober looks
/// like from here, as opposed to a normal scan that just connects
/// and immediately closes again, which the existing read-hangup
/// path already cleans up fine - would otherwise sit in `sessions`
/// forever, one TCPSession + one fd each. Called from
/// connectionRequest() (see its own call site) so the sweep keeps
/// pace with however fast new connections are actually arriving,
/// without needing a dedicated timer/thread of its own; a
/// legitimate, already-talking client is never at risk, since
/// hasReceivedData latches true permanently on its first real byte
/// and is never consulted again after that.
///
void sweepStaleSessions();
/// ///
/// The listening socket itself is never a TLS peer - accepting a /// The listening socket itself is never a TLS peer - accepting a
/// connection on it surfaces as a plain read() failing with ENOTCONN /// connection on it surfaces as a plain read() failing with ENOTCONN
@@ -159,9 +224,74 @@ namespace core {
int processCommand(coreutils::ZString &request, TCPSession &session) override; int processCommand(coreutils::ZString &request, TCPSession &session) override;
protected:
// Was private - ConsoleServer::logSend() (and any other subclass
// that iterates `sessions`, itself public further up) needs to be
// able to synchronize against the exact same mutex
// connectionRequest()/removeFromSessionList() already use, rather
// than reading a shared_ptr vector with no locking of its own.
//
// Was a plain std::mutex - self-deadlocked the accepting thread on
// EVERY single connection to ConsoleServer (confirmed live via a
// gdb thread dump caught mid-stall): connectionRequest() locks
// `lock`, then calls accept(), which constructs the new session -
// whose base Socket constructor logs its own creation via
// coreutils::Log, whose destructor calls back into
// ConsoleServer::logSend() (exactly the synchronization this was
// designed for, per the comment above) - which tries to lock this
// SAME mutex again, on the SAME thread that already holds it.
// std::mutex is not reentrant, so that thread deadlocked
// permanently, every time, without ever completing the accept -
// this is why the admin console never responded to anything.
// Since all of a server's listening sockets share one fixed-size
// EPoll worker-thread pool, each such deadlocked thread is gone
// for good - enough accumulated connection attempts (even
// sporadic ones, e.g. internet-wide port scanners probing every
// port) eventually exhausts every worker thread, at which point
// the WHOLE server - every listening socket, not just the
// console - stops accepting anything new. This is the actual
// root cause of BARANTMail's own multi-day-recurring "all ports
// simultaneously stop accepting connections" incidents - nothing
// to do with DNS/SPF lookup timing, which was a real, separate,
// worthwhile fix but not this bug. recursive_mutex lets the same
// thread re-enter safely (identical behavior to std::mutex for
// every other thread) without changing the locking design at all.
std::recursive_mutex lock;
public:
///
/// A listening TCPServer/ConsoleServer (as opposed to an accepted
/// TCPSession) is constructed once, directly by main(), and lives
/// for the whole process - never through the shared_ptr-based
/// ownership TCPSession::registerLive()/pin() provide (see their
/// own comments), since nothing ever calls `new` on one of these.
/// Thread::run()'s epoll dispatch still needs a SAFE way to tell
/// "this raw pointer is one of those known-immortal listening
/// sockets, fine to call methods on directly" apart from "this is
/// an unrecognized/stale pointer that must not be touched at all"
/// (see TCPSession::tryGet()'s own comment on why dynamic_cast
/// can't make that distinction safely). Registering `this` once,
/// in the constructor, into this tiny set is that signal - it's
/// checked by address only, never dereferenced for the check
/// itself.
///
static bool isKnownListeningSocket(void *ptr) {
std::lock_guard<std::mutex> guard(listeningSocketsMutex());
return listeningSockets().count(ptr) > 0;
}
private: private:
TCPSession *accept(); TCPSession *accept();
std::mutex lock;
static std::mutex &listeningSocketsMutex() {
static std::mutex m;
return m;
}
static std::set<void *> &listeningSockets() {
static std::set<void *> s;
return s;
}
}; };
} }
+21 -3
View File
@@ -91,9 +91,27 @@ namespace core {
} }
void TCPSession::send() { void TCPSession::send() {
if(out.tellp() > 0) // Take the data and clear `out` BEFORE write(). write() can re-arm
write(out.str()); // the fd, and from that moment another epoll worker may send what
out.str(""); // was queued, receive the client's next command and run its handler
// - which appends to this same `out`. When `out` was only cleared
// after write() returned, a handler running in that window saw the
// previous text still there and sent it a second time. Reproduced
// with the protocol greeting (queued from onRegistered() on the
// accepting thread): under a burst of connections some clients got
// "220 ..." twice, every later reply then lined up with the wrong
// command, and STARTTLS clients read the plain "220 Ready" as their
// TLS ServerHello.
if(out.tellp() > 0) {
std::string data = out.str();
out.str("");
write(data);
}
}
bool TCPSession::startTLS(SSL_CTX *ctx) {
send();
return TCPSocket::startTLS(ctx);
} }
void TCPSession::terminate() { void TCPSession::terminate() {
+131 -3
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:
/// ///
/// ///
/// ///
@@ -54,6 +170,18 @@ namespace core {
/// ///
void send(); void send();
///
/// Upgrade this session to TLS (STARTTLS/STLS). Put the protocol's
/// "ready" reply in `out` first, then call this from the command
/// handler; it sends that reply in clear text, drops any input
/// pipelined behind the command, and starts the handshake. See
/// TCPSocket::startTLS() for the details and return value.
///
/// Pass server->startTLSContext (see TCPServer::enableStartTLS()).
///
bool startTLS(SSL_CTX *ctx);
/// ///
/// Use this method to terminate this TCPSession. /// Use this method to terminate this TCPSession.
+107 -24
View File
@@ -40,18 +40,35 @@ namespace core {
// session (set in TLS::createContext(), inherited by sessions via // session (set in TLS::createContext(), inherited by sessions via
// TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h). // TLS(SSL_CTX*)), safely NULL by default otherwise (see TLS.h).
if(ctx) { if(ctx) {
int len; // Loop until OpenSSL has nothing decrypted left over. A single TLS
{ // record carries up to 16KB, but `buffer` is 4KB, so one SSL_read()
// Held only around the raw SSL_read call - released before // can leave the rest of a record sitting inside OpenSSL. This socket
// onDataReceived() so the request-handling chain it triggers // is edge-triggered (EPOLLET) and those bytes have already been
// (which reaches Socket::write()/outlock) never runs while // pulled off the fd, so nothing would ever raise another EPOLLIN
// ioLock is held. See ioLock's own doc comment in TCPSocket.h. // for them: the session would stall mid-stream until the peer
std::lock_guard<std::mutex> ioGuard(ioLock); // happened to send something else. Small requests (HTTP headers,
len = TLS::receiveData(buffer); // single commands) never fill a 4KB read, which is why this didn't
} // show up before; an SMTP DATA body from another mail server - the
if(len >= 0) { // common case once STARTTLS is offered - does on every message.
coreutils::ZString zbuffer(buffer.getData(), len); while(true) {
onDataReceived(zbuffer); int len;
bool more;
{
// Held only around the raw SSL_read/SSL_pending calls -
// released before onDataReceived() so the request-handling
// chain it triggers (which reaches Socket::write()/outlock)
// never runs while ioLock is held. See ioLock's own doc
// comment in TCPSocket.h.
std::lock_guard<std::mutex> ioGuard(ioLock);
len = TLS::receiveData(buffer);
more = len > 0 && pendingBytes() > 0;
}
if(len >= 0) {
coreutils::ZString zbuffer(buffer.getData(), len);
onDataReceived(zbuffer);
}
if(!more || shutDown)
break;
} }
} else { } else {
Socket::receiveData(buffer); Socket::receiveData(buffer);
@@ -66,6 +83,25 @@ namespace core {
return Socket::sendData(data, length); return Socket::sendData(data, length);
} }
bool TCPSocket::sendNeedsRead() {
return ctx && lastSendWantedRead;
}
bool TCPSocket::startTLS(SSL_CTX *newCtx) {
if(ctx || !newCtx)
return false;
discardInput = true;
if(!flushPlain(10000)) {
coreutils::Log(coreutils::LOG_DEBUG_1) << "STARTTLS: ready reply could not be delivered; closing.";
shutdown("STARTTLS ready reply could not be delivered");
return false;
}
ctx = newCtx;
performTLSHandshake();
coreutils::Log(coreutils::LOG_DEBUG_1) << "STARTTLS: handshake started on socket " << getDescriptor() << ".";
return true;
}
void TCPSocket::performTLSHandshake() { void TCPSocket::performTLSHandshake() {
// registerSocket() makes this fd eligible for epoll dispatch to ANY // registerSocket() makes this fd eligible for epoll dispatch to ANY
// worker thread immediately. ioLock MUST be acquired BEFORE that // worker thread immediately. ioLock MUST be acquired BEFORE that
@@ -87,14 +123,19 @@ namespace core {
// (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently // (WANT_READ/WANT_WRITE) - that's fine, OpenSSL transparently
// finishes a pending handshake on the next SSL_read/SSL_write, // finishes a pending handshake on the next SSL_read/SSL_write,
// which ioLock already serializes against everything else. // which ioLock already serializes against everything else.
performTLSHandshake(getDescriptor());
}
void TCPSocket::performTLSHandshake(int fd) {
std::lock_guard<std::mutex> ioGuard(ioLock); std::lock_guard<std::mutex> ioGuard(ioLock);
registerSocket(getDescriptor()); registerSocket(fd);
acceptSocket(); acceptSocket();
} }
void TCPSocket::onDataReceived(coreutils::ZString &data) { void TCPSocket::onDataReceived(coreutils::ZString &data) {
if (data.getLength() > 0) { if (data.getLength() > 0) {
hasReceivedData = true;
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize + data.getLength()); lineBuffer = (char *)realloc(lineBuffer, lineBufferSize + data.getLength());
memcpy(lineBuffer + lineBufferSize, data.getData(), data.getLength()); memcpy(lineBuffer + lineBufferSize, data.getData(), data.getLength());
lineBufferSize += data.getLength(); lineBufferSize += data.getLength();
@@ -122,14 +163,37 @@ namespace core {
// the bounded equivalent - it never looks past the length // the bounded equivalent - it never looks past the length
// given, so "no CRLF yet" correctly comes back as "not // given, so "no CRLF yet" correctly comes back as "not
// found" instead of reading off the end of the allocation. // found" instead of reading off the end of the allocation.
char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize); char *found;
char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize); if (strictCRLF)
char *found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl); found = (char *)memmem(lineBuffer, lineBufferSize, "\r\n", 2);
else {
char *cr = (char *)memchr(lineBuffer, '\r', lineBufferSize);
char *nl = (char *)memchr(lineBuffer, '\n', lineBufferSize);
found = (cr && nl) ? std::min(cr, nl) : (cr ? cr : nl);
}
lineLength = found ? (int)(found - lineBuffer) : lineBufferSize; lineLength = found ? (int)(found - lineBuffer) : lineBufferSize;
if (lineLength == lineBufferSize) if (!found) {
// No complete line yet. If it has already outgrown
// maxLineLength, drop what's buffered (keeping the last
// byte, which may be the CR of a CR LF whose LF is still
// in flight) and skip the rest of it - see maxLineLength.
if (maxLineLength && (size_t)lineBufferSize > maxLineLength) {
lineBuffer[0] = lineBuffer[lineBufferSize - 1];
lineBufferSize = 1;
lineBuffer = (char *)realloc(lineBuffer, lineBufferSize);
skippingLongLine = true;
}
break;
}
if (skippingLongLine || (maxLineLength && (size_t)lineLength > maxLineLength)) {
skippingLongLine = false;
onLineTooLong();
} else {
coreutils::ZString zLine(lineBuffer, lineLength);
onLineReceived(zLine);
}
if (discardInput)
break; break;
coreutils::ZString zLine(lineBuffer, lineLength);
onLineReceived(zLine);
// lineLength < lineBufferSize is guaranteed by the break // lineLength < lineBufferSize is guaranteed by the break
// above, so this first index is always in bounds; bump // above, so this first index is always in bounds; bump
// past a lone '\r' only if there's still at least one more // past a lone '\r' only if there's still at least one more
@@ -138,10 +202,14 @@ namespace core {
// after it yet) leave it for the next read to resolve, // after it yet) leave it for the next read to resolve,
// rather than reading lineBuffer[lineBufferSize], one past // rather than reading lineBuffer[lineBufferSize], one past
// the allocation. // the allocation.
if (lineBuffer[lineLength] == '\r') if (strictCRLF)
++lineLength; lineLength += 2;
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n') else {
++lineLength; if (lineBuffer[lineLength] == '\r')
++lineLength;
if (lineLength < lineBufferSize && lineBuffer[lineLength] == '\n')
++lineLength;
}
lineBufferSize -= lineLength; lineBufferSize -= lineLength;
if (lineBufferSize > 0) if (lineBufferSize > 0)
memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize); memmove(lineBuffer, lineBuffer + lineLength, lineBufferSize);
@@ -150,6 +218,8 @@ namespace core {
else if (lineBufferSize >= blockSize) { else if (lineBufferSize >= blockSize) {
coreutils::ZString zBlock(lineBuffer, blockSize); coreutils::ZString zBlock(lineBuffer, blockSize);
onBlockReceived(zBlock); onBlockReceived(zBlock);
if (discardInput)
break;
lineBufferSize -= blockSize; lineBufferSize -= blockSize;
if (lineBufferSize > 0) if (lineBufferSize > 0)
memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize); memmove(lineBuffer, lineBuffer + blockSize, lineBufferSize);
@@ -166,7 +236,16 @@ namespace core {
// changes, so the while(lineBufferSize > 0) loop above // changes, so the while(lineBufferSize > 0) loop above
// never yields back to let more data arrive. // never yields back to let more data arrive.
break; break;
} }
if (discardInput) {
// See startTLS(): whatever followed the upgrade command in this
// read is pre-handshake plain text and is dropped, not processed.
discardInput = false;
free(lineBuffer);
lineBuffer = NULL;
lineBufferSize = 0;
lineLength = 0;
}
} }
} }
@@ -177,6 +256,10 @@ namespace core {
void TCPSocket::onBlockReceived(coreutils::ZString &block) {} void TCPSocket::onBlockReceived(coreutils::ZString &block) {}
void TCPSocket::onLineTooLong() {
shutdown("line exceeded maxLineLength");
}
void TCPSocket::setBlockSize(int blockSize) { void TCPSocket::setBlockSize(int blockSize) {
this->blockSize = blockSize; this->blockSize = blockSize;
} }
+136
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 {
@@ -123,6 +124,15 @@ namespace core {
virtual int sendData(const char *data, int length) override; virtual int sendData(const char *data, int length) override;
///
/// True only when this socket is actually TLS (ctx set) and the
/// last sendData() call failed specifically with
/// SSL_ERROR_WANT_READ - see TLS::lastSendWantedRead's own doc
/// comment for why Socket::writeSocket()/resetSocket() need this.
///
virtual bool sendNeedsRead() override;
/// ///
/// Completes the TLS handshake (SSL_new/SSL_set_fd/SSL_accept) for /// Completes the TLS handshake (SSL_new/SSL_set_fd/SSL_accept) for
/// THIS socket's own ctx/descriptor. registerSocket()/acceptSocket() /// THIS socket's own ctx/descriptor. registerSocket()/acceptSocket()
@@ -141,6 +151,85 @@ namespace core {
void performTLSHandshake(); void performTLSHandshake();
///
/// Same, on an fd that hasn't been handed to setDescriptor() yet.
/// TCPServer::accept() uses this for implicit-TLS listeners so the
/// SSL object exists before the fd is armed in epoll - otherwise the
/// greeting queued by onConnected() can reach TLS::sendData() on
/// another worker before there is anything to send it through.
///
void performTLSHandshake(int fd);
///
/// Set once, at construction, and never touched again - how long
/// this specific socket has been open since accept()/connect(),
/// regardless of whether anything has actually happened on it
/// since. TCPServer::sweepStaleSessions() reads this (alongside
/// hasReceivedData below) to find connections that completed a
/// TCP handshake but then never progressed - a scanner/prober
/// probing an open port, or a TLS handshake that never finished -
/// which otherwise sit in TCPServer::sessions forever: nothing in
/// the existing design ever revisits a socket that stops
/// generating epoll events (see sweepStaleSessions()'s own doc
/// comment for the full reasoning).
///
std::chrono::steady_clock::time_point acceptedAt = std::chrono::steady_clock::now();
///
/// Flips to true the first time onDataReceived() sees a non-empty
/// read - true for both a plaintext socket's raw bytes and a TLS
/// session's already-decrypted ones, since both paths funnel
/// through the same onDataReceived() override below. A session
/// that reaches sweepStaleSessions()'s grace period with this
/// still false has never had a real exchange of any kind, TLS
/// handshake included (a stuck/incomplete SSL_accept() never
/// surfaces anything to onDataReceived) - the specific, narrow
/// condition that sweep treats as abandoned. Deliberately NOT
/// reset afterward and never consulted again once true, so a
/// legitimate client that sends something once and then goes
/// idle for a long time (an ordinary connected-but-idle game
/// session) is never at risk from this - only a connection that
/// NEVER said anything at all within the grace window is.
///
bool hasReceivedData = false;
///
/// Upgrade this plain-text connection to TLS in place (SMTP
/// STARTTLS, IMAP STARTTLS, POP3 STLS). Call it from the command
/// handler that accepted the upgrade, AFTER queuing that command's
/// "ready" reply - TCPSession::startTLS() does both for you.
///
/// In order, it:
/// 1. writes everything queued so far (the ready reply included)
/// to the socket in clear text and waits for it to go out;
/// 2. throws away any other input the client already sent in the
/// same read as the upgrade command. RFC 3207 section 4 forbids
/// a client from pipelining anything after STARTTLS, and acting
/// on such bytes is the classic STARTTLS command-injection hole
/// (CVE-2011-0411 and its many relatives): an attacker on the
/// path appends plain-text commands that the server would then
/// treat as if they arrived over the encrypted channel;
/// 3. switches this socket to `ctx` and starts the server side of
/// the handshake. The client's ClientHello and everything after
/// it are read through TLS by the normal receiveData() path.
///
/// Returns false (and changes nothing) if TLS is already active or
/// ctx is NULL; returns false and shuts the connection down if the
/// ready reply couldn't be delivered.
///
bool startTLS(SSL_CTX *ctx);
///
/// True once this connection is encrypted, whether it was accepted
/// on an implicit-TLS listener or upgraded with startTLS().
///
bool isTLS() { return ctx != NULL; }
protected: protected:
bool term = false; bool term = false;
TLSInfo *tlsInfo; TLSInfo *tlsInfo;
@@ -151,6 +240,53 @@ namespace core {
int lineLength = 0; int lineLength = 0;
int blockSize = 0; int blockSize = 0;
// Set by startTLS(); tells the onDataReceived() loop that the line
// it just dispatched was the upgrade command and everything still
// in lineBuffer is pre-handshake plain text that must be dropped,
// not processed. See startTLS()'s step 2.
bool discardInput = false;
// Set by the line loop while it is dropping the rest of a line that
// already exceeded maxLineLength; see onLineTooLong().
bool skippingLongLine = false;
protected:
///
/// When true, only CR LF ends a line; a bare CR or bare LF is kept
/// as part of the line's content. Default false (a CR, an LF, or CR
/// LF each end a line), which existing line protocols rely on.
///
/// SMTP must use true. RFC 5321 2.3.8 and 4.1.1.4 make <CRLF>.<CRLF>
/// the only end-of-data sequence; a server that also accepts bare
/// <LF> or <CR> line endings can be made to end a message early on
/// "<LF>.<LF>" and then run whatever follows in the same message as
/// fresh SMTP commands - "SMTP smuggling" (CVE-2023-51764/-51765/
/// -51766), which lets a sender forge mail from any domain that
/// relays through the server. The lenient mode also splits a CR LF
/// that straddles two reads into two lines, the second one empty.
///
bool strictCRLF = false;
///
/// Upper bound on bytes buffered for a single line (0 = no limit).
/// When a line grows past it, the buffered part is dropped, the rest
/// of that line is skipped up to its terminator, and onLineTooLong()
/// is called once in place of onLineReceived() for it. Without a
/// bound, a peer that never sends a line terminator grows lineBuffer
/// until the process runs out of memory.
///
size_t maxLineLength = 0;
///
/// Called once for each line that exceeded maxLineLength. The default
/// closes the connection; protocols that can recover override it to
/// reply with an error instead.
///
virtual void onLineTooLong();
// Socket's own `lock` (guards receiveData) and `outlock` (guards // Socket's own `lock` (guards receiveData) and `outlock` (guards
// writeSocket/the fifo) are two DIFFERENT mutexes - a thread // writeSocket/the fifo) are two DIFFERENT mutexes - a thread
// handling EPOLLIN and a different thread handling EPOLLWRNORM for // handling EPOLLIN and a different thread handling EPOLLWRNORM for
+115 -44
View File
@@ -3,6 +3,7 @@
#include "Log.h" #include "Log.h"
#include <iostream> #include <iostream>
#include <openssl/rand.h> #include <openssl/rand.h>
#include <mutex>
namespace core { namespace core {
@@ -65,65 +66,132 @@ namespace core {
TLS::TLS(SSL_CTX *ctx) : ctx(ctx) {} TLS::TLS(SSL_CTX *ctx) : ctx(ctx) {}
TLS::~TLS() {} // Each accepted TLS connection gets its own SSL object in
// registerSocket(); it was never freed, so every TLS session leaked
// one. Harmless for a handful of long-lived connections, but a mail
// server opens one per delivery, all day. The fd itself is still
// closed by ~Socket() as before - SSL_free() doesn't touch it.
TLS::~TLS() {
if(initialized)
SSL_free(ssl);
}
void TLS::createContext(TLSInfo *tlsInfo) { // The ONE-TIME, process-wide OpenSSL library init (SSL_library_init(),
// the lockarray, RAND seeding). Used to live in createContext(), which
if(tlsInfo) { // was fine while that was the only way a context got built; now that
// buildContext() is also reached directly - TCPServer::enableStartTLS()
// for STARTTLS, and addSNIContext() - it runs exactly once from there,
// whichever path gets to it first.
static void initializeLibrary() {
static std::once_flag once;
std::call_once(once, [] {
SSL_library_init(); SSL_library_init();
SSL_load_error_strings(); SSL_load_error_strings();
lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); lockarray = (pthread_mutex_t *)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
for(int i = 0; i < CRYPTO_num_locks(); ++i) for(int i = 0; i < CRYPTO_num_locks(); ++i)
pthread_mutex_init(&(lockarray[i]), NULL); pthread_mutex_init(&(lockarray[i]), NULL);
CRYPTO_set_id_callback((unsigned long (*)())thread_id); CRYPTO_set_id_callback((unsigned long (*)())thread_id);
CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))lock_callback); CRYPTO_set_locking_callback((void (*)(int, int, const char *, int))lock_callback);
SSLeay_add_ssl_algorithms(); SSLeay_add_ssl_algorithms();
RAND_load_file("/dev/hwrng", 1024); RAND_load_file("/dev/hwrng", 1024);
if(!(ctx = SSL_CTX_new(SSLv23_server_method()))) });
throw coreutils::Exception("Error while setting server method SSLv23."); }
SSL_CTX_set_mode(ctx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET); void TLS::createContext(TLSInfo *tlsInfo) {
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER); if(tlsInfo)
// SSL_CTX_set_generate_session_id(ctx, generate_session_id); ctx = buildContext(tlsInfo);
SSL_CTX_set_cipher_list(ctx, "ECDH-ECDSA-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA"); }
// _chain_file (not _file) - loads every certificate in the file,
// not just the first. A real Let's Encrypt fullchain.pem is the // The per-context cert/key/cipher/verify setup, shared by
// leaf cert followed by the intermediate CA cert concatenated in // createContext(), addSNIContext() (one context per extra hostname)
// one file specifically so a server can hand both to the client // and TCPServer::enableStartTLS().
// in one shot; SSL_CTX_use_certificate_file() only ever reads the SSL_CTX *TLS::buildContext(TLSInfo *tlsInfo) {
// first PEM block, silently dropping the intermediate - confirmed initializeLibrary();
// via a real handshake against this exact fullchain.pem: clients SSL_CTX *newCtx;
// got "unable to get local issuer certificate" because the server if(!(newCtx = SSL_CTX_new(SSLv23_server_method())))
// only ever sent the leaf, never the intermediate needed to chain throw coreutils::Exception("Error while setting server method SSLv23.");
// up to a root the client already trusts. // A caller may now catch a bad certificate/key and carry on without
if(SSL_CTX_use_certificate_chain_file(ctx, tlsInfo->certificate.c_str()) <= 0) // TLS (BARANTMail does, for STARTTLS) - don't leak the half-built
// context on the way out.
try {
SSL_CTX_set_mode(newCtx, SSL_MODE_RELEASE_BUFFERS | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
SSL_CTX_set_options(newCtx, SSL_OP_NO_TICKET);
SSL_CTX_set_session_cache_mode(newCtx, SSL_SESS_CACHE_SERVER);
SSL_CTX_set_cipher_list(newCtx, "ECDH-ECDSA-AES256-GCM-SHA384:DHE-DSS-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA256:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-GCM-SHA384:AES256-SHA256:AES256-SHA:AES128-GCM-SHA256:AES128-SHA256:AES128-SHA");
// _chain_file (not _file) - loads every certificate in the file,
// not just the first. A real Let's Encrypt fullchain.pem is the
// leaf cert followed by the intermediate CA cert concatenated in
// one file specifically so a server can hand both to the client
// in one shot; SSL_CTX_use_certificate_file() only ever reads the
// first PEM block, silently dropping the intermediate - confirmed
// via a real handshake against this exact fullchain.pem: clients
// got "unable to get local issuer certificate" because the server
// only ever sent the leaf, never the intermediate needed to chain
// up to a root the client already trusts.
if(SSL_CTX_use_certificate_chain_file(newCtx, tlsInfo->certificate.c_str()) <= 0)
throw coreutils::Exception("Error looking up certificate."); throw coreutils::Exception("Error looking up certificate.");
if(SSL_CTX_use_PrivateKey_file(ctx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) < 0) if(SSL_CTX_use_PrivateKey_file(newCtx, tlsInfo->key.c_str(), SSL_FILETYPE_PEM) <= 0)
throw coreutils::Exception("Error with private key."); throw coreutils::Exception("Error with private key.");
if(SSL_CTX_check_private_key(ctx) != 1) if(SSL_CTX_check_private_key(newCtx) != 1)
throw coreutils::Exception("Private key does not match certificate."); throw coreutils::Exception("Private key does not match certificate.");
// Client-certificate verification (mutual TLS) is opt-in, not the // Client-certificate verification (mutual TLS) is opt-in, not the
// default - a public-facing site (e.g. a real Let's Encrypt // default - a public-facing site (e.g. a real Let's Encrypt
// server cert with no corresponding client CA of its own) has no // server cert with no corresponding client CA of its own) has no
// client certificate to hand out to ordinary visitors, so // client certificate to hand out to ordinary visitors, so
// requesting one via SSL_VERIFY_PEER would surface a "select a // requesting one via SSL_VERIFY_PEER would surface a "select a
// certificate" prompt real browsers can't meaningfully answer. // certificate" prompt real browsers can't meaningfully answer.
// Only enable it when a caCertificate is actually configured - // Only enable it when a caCertificate is actually configured -
// existing internal/mTLS use of this class (any config that DOES // existing internal/mTLS use of this class (any config that DOES
// set tls.caCertificate) keeps behaving exactly as before. // set tls.caCertificate) keeps behaving exactly as before.
if(tlsInfo->cACertificate.getLength() > 0) { if(tlsInfo->cACertificate.getLength() > 0) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); SSL_CTX_set_verify(newCtx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_verify_depth(ctx, 1); SSL_CTX_set_verify_depth(newCtx, 1);
if(!SSL_CTX_load_verify_locations(ctx, tlsInfo->cACertificate.c_str(), NULL)) if(!SSL_CTX_load_verify_locations(newCtx, tlsInfo->cACertificate.c_str(), NULL))
throw coreutils::Exception("Cannot verify locations."); throw coreutils::Exception("Cannot verify locations.");
SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str())); SSL_CTX_set_client_CA_list(newCtx, SSL_load_client_CA_file(tlsInfo->cACertificate.c_str()));
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required)."; coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (client certificate required).";
} else { } else {
coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required)."; coreutils::Log(coreutils::LOG_INFO) << "Server key authenticated (no client certificate required).";
} }
}
catch(...) {
SSL_CTX_free(newCtx);
throw;
}
return newCtx;
}
int TLS::pendingBytes() {
return initialized ? SSL_pending(ssl) : 0;
}
int TLS::sniCallback(SSL *ssl, int *ad, void *arg) {
TLS *self = (TLS *)arg;
const char *name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
if(name) {
auto it = self->sniContexts.find(name);
if(it != self->sniContexts.end())
SSL_set_SSL_CTX(ssl, it->second);
// No match (an unconfigured hostname, or a typo'd Host that still
// resolves here via DNS) - fall through and keep whatever SSL_CTX
// this SSL* already has, which is the base `ctx` SSL_new() was
// constructed from. Exactly the same cert a pre-SNI client (or
// one sending no SNI at all) already gets today.
}
return SSL_TLSEXT_ERR_OK;
}
void TLS::addSNIContext(const std::string &hostname, TLSInfo *tlsInfo) {
SSL_CTX *newCtx = buildContext(tlsInfo);
sniContexts[hostname] = newCtx;
if(!sniCallbackRegistered) {
SSL_CTX_set_tlsext_servername_callback(ctx, sniCallback);
SSL_CTX_set_tlsext_servername_arg(ctx, this);
sniCallbackRegistered = true;
} }
} }
void TLS::registerSocket(int fd) { void TLS::registerSocket(int fd) {
int ret; int ret;
@@ -251,15 +319,18 @@ namespace core {
if((len = ::SSL_write(ssl, data, length)) >= 0) { if((len = ::SSL_write(ssl, data, length)) >= 0) {
coreutils::Log(coreutils::LOG_DEBUG_3) << "sendData TLS...len=" << len; coreutils::Log(coreutils::LOG_DEBUG_3) << "sendData TLS...len=" << len;
lastSendWantedRead = false;
return len; return len;
} }
else { else {
lastSendWantedRead = false;
switch (SSL_get_error(ssl, len)) { switch (SSL_get_error(ssl, len)) {
case SSL_ERROR_SSL: case SSL_ERROR_SSL:
coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_SSL on ssl_write. error=" << errno; coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_SSL on ssl_write. error=" << errno;
break; break;
case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_READ:
coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_WANT_READ on ssl_write."; coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_WANT_READ on ssl_write.";
lastSendWantedRead = true;
break; break;
case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_WRITE:
coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_WANT_WRITE on ssl_write."; coreutils::Log(coreutils::LOG_DEBUG_3) << "ERROR_WANT_WRITE on ssl_write.";
+72 -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,36 @@ namespace core {
void createContext(TLSInfo *tlsInfo); void createContext(TLSInfo *tlsInfo);
///
/// Registers a second (or third, etc.) certificate/key pair for a
/// specific hostname on THIS SAME listening socket, via TLS's
/// Server Name Indication (SNI) extension - lets one TCPServer
/// terminate TLS for multiple unrelated domains, each with its own
/// real certificate, without needing a separate listening port or
/// process per domain. Must be called after createContext() (or the
/// TLSInfo* constructor, which calls it) has already established the
/// base `ctx` - that base context keeps serving as both the
/// fallback for hostnames not registered here AND the cert offered
/// to any client that sends no SNI hostname at all (a bare-IP
/// request, or any TLS client old enough to predate SNI). Callers
/// that never call this at all (every existing single-site
/// TLSInfo* user - BARANTMail, Zephora, ClockPlanet, and a
/// single-site APIServer config) see zero behavior change: the SNI
/// callback is only ever registered on `ctx` the first time this is
/// called, not unconditionally in createContext().
///
void addSNIContext(const std::string &hostname, TLSInfo *tlsInfo);
///
/// Build a server SSL_CTX from tlsInfo without attaching it to any
/// object. Used by createContext() for implicit-TLS listeners and by
/// TCPServer::enableStartTLS() for a context that plain-text sessions
/// only switch to on request (STARTTLS). Throws coreutils::Exception
/// if the certificate or key can't be loaded.
///
static SSL_CTX *buildContext(TLSInfo *tlsInfo);
// A never-configured TLS object (either the listening TCPServer // A never-configured TLS object (either the listening TCPServer
// itself when constructed with tlsInfo=NULL, or a TCPSession spawned // itself when constructed with tlsInfo=NULL, or a TCPSession spawned
// from one via TLS(SSL_CTX*)) must default to a real NULL here, not // from one via TLS(SSL_CTX*)) must default to a real NULL here, not
@@ -58,14 +90,53 @@ namespace core {
int sendData(const char *data, int length); int sendData(const char *data, int length);
void registerSocket(int fd); void registerSocket(int fd);
void acceptSocket(); void acceptSocket();
///
/// Bytes OpenSSL has already decrypted and is holding for this
/// connection but that haven't been returned by receiveData() yet.
/// The socket is edge-triggered (EPOLLET), so these never generate
/// another EPOLLIN on their own - TCPSocket::receiveData() drains
/// them before giving the event back. See its own comment.
///
int pendingBytes();
protected:
// Set by sendData() when the last SSL_write() failed specifically
// with SSL_ERROR_WANT_READ (needs a READ to make progress - e.g.
// mid-handshake application data, or a post-handshake session
// ticket exchange) rather than any other reason. TCPSocket::
// sendNeedsRead() reads this (protected, so a subclass can reach
// it directly) to tell Socket::writeSocket()/resetSocket() not to
// busy-spin retrying the write via EPOLLWRNORM - see their own
// doc comments for the confirmed real damage (a 15GB+ debug log,
// and every affected connection dropped before ever reading the
// client's first command) this caused when unaddressed.
bool lastSendWantedRead = false;
private: private:
char *sip_cacert = (char *)"../testkeys/certs/pbxca.crt"; char *sip_cacert = (char *)"../testkeys/certs/pbxca.crt";
char *sip_cert = (char *)"../testkeys/certs/pbxserver.crt"; char *sip_cert = (char *)"../testkeys/certs/pbxserver.crt";
char *sip_key = (char *)"../testkeys/certs/pbxserver.key"; char *sip_key = (char *)"../testkeys/certs/pbxserver.key";
bool initialized = false; bool initialized = false;
SSL *ssl; SSL *ssl;
// Owns every SSL_CTX* built by addSNIContext() (the base `ctx` is
// owned/freed the same way it always was, untouched by this map).
// Keyed by hostname exactly as configured - matched case-
// insensitively against the ClientHello's SNI value in the
// callback (see TLS.cpp).
std::map<std::string, SSL_CTX *> sniContexts;
bool sniCallbackRegistered = false;
// OpenSSL's own SSL_CTX_set_tlsext_servername_callback signature -
// a static member (not a free function) so it can reach the owning
// TLS instance's private sniContexts via the `arg` parameter
// (SSL_CTX_set_tlsext_servername_arg(ctx, this), set alongside the
// callback itself in addSNIContext()).
static int sniCallback(SSL *ssl, int *ad, void *arg);
}; };
} }
+75 -7
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