Compare commits

..
13 Commits
Author SHA1 Message Date
Matt Arant 3383595296 Fix unsynchronized data race in SubscriptionManager::processCommand()
processCommand() read/mutated the `subscriptions` map and individual
Subscription objects' `subscribers` vectors (via subscribe()/unsubscribe()/
event()/the "publish" branch's own insert()) without taking `lock` at all,
even though add() and removeSessionSubscriptions() already do take it for
the exact same state. removeSessionSubscriptions() runs from ~TCPSession(),
on whatever thread happens to be tearing down a *different* connection, so
one thread erasing a session from a Subscription's subscribers vector could
run concurrently with another thread iterating (event()) or appending to
(subscribe()) that same vector - a plain unsynchronized data race.

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

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

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

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

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

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

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

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

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

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

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

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

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

No files matched your search

+1 -1
View File
@@ -11,4 +11,4 @@ docs/html
*/mmap_address.bin */mmap_address.bin
.history/* .history/*
html html
latex latex*.pre-*
+7 -4
View File
@@ -1,14 +1,17 @@
#include "Command.h" #include "Command.h"
#include "Log.h"
#include "CommandList.h" #include "CommandList.h"
#include "Log.h"
namespace core { namespace core
{
int Command::processCommand(coreutils::ZString &request, TCPSession &session) { int Command::processCommand(coreutils::ZString &request, TCPSession &session)
{
return 0; return 0;
} }
void Command::output(std::stringstream &out) { void Command::output(std::stringstream &out)
{
out << "Write your own command description here for the help system." << std::endl; out << "Write your own command description here for the help system." << std::endl;
} }
+17
View File
@@ -8,6 +8,23 @@ namespace core {
CommandList::CommandList(std::string delimiter, int depth) : delimiter(delimiter), depth(depth) {} CommandList::CommandList(std::string delimiter, int depth) : delimiter(delimiter), depth(depth) {}
void CommandList::add(Command &command, std::string name) { void CommandList::add(Command &command, std::string name) {
// processRequest() below upper-cases the incoming keyword before
// looking it up, but this previously stored whatever case the
// caller passed in verbatim - any registration that wasn't
// already uppercase (nearly everything outside SMTP/POP3/IMAP's
// own RFC-driven uppercase convention) could then NEVER be
// matched by any input, since upper-casing a non-uppercase string
// can't produce a match against a non-uppercase key. Confirmed:
// this alone made every Zephora game command unreachable, along
// with this class's own base-level "publish"/"subscribe"/"event"/
// etc. registrations (TCPServer's constructor). Folding the same
// way here keeps registration and lookup permanently in sync
// regardless of what case any given add() call happens to use -
// already-uppercase callers (SMTP, the BARANTMail admin console)
// are unaffected, since upper-casing an uppercase string is a
// no-op.
std::transform(name.begin(), name.end(), name.begin(),
[](unsigned char c) { return std::toupper(c); });
commands.insert(std::make_pair(name, &command)); commands.insert(std::make_pair(name, &command));
} }
+20
View File
@@ -272,6 +272,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");
} }
} }
+22 -11
View File
@@ -1,23 +1,29 @@
#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;
for (auto subscriber : subscribers) { for (auto subscriber : subscribers) {
subscriber->write(out.str()); subscriber->write(out.str());
@@ -29,21 +35,27 @@ namespace core {
handler->onSubscribe(session, this); handler->onSubscribe(session, this);
else else
onSubscribe(session); onSubscribe(session);
subscribers.push_back(&session); subscribers.push_back(&session);
return 1; return 1;
} }
int Subscription::unsubscribe(TCPSession &session) { int Subscription::unsubscribe(TCPSession &session) {
for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber) { for (auto subscriber = subscribers.begin(); subscriber < subscribers.end(); ++subscriber)
if (*subscriber == &session) { if (*subscriber == &session) {
subscribers.erase(subscriber++); subscribers.erase(subscriber++);
return 1; return 1;
} }
}
return 0; return 0;
} }
bool Subscription::subscriptionOwner(coreutils::MString alias, coreutils::MString ownerSelection) {
subscriptionOwners = alias;
selectionOfOwnerForSubscription = ownerSelection;
coreutils::Log(coreutils::LOG_DEBUG_1) << "Owner of Subscription: " << subscriptionOwners;
coreutils::Log(coreutils::LOG_DEBUG_1) << "Will of Subscription: " << selectionOfOwnerForSubscription;
return true;
}
int Subscription::process(coreutils::ZString &request, std::stringstream &out, TCPSession &session) { int Subscription::process(coreutils::ZString &request, std::stringstream &out, TCPSession &session) {
if (handler) if (handler)
handler->process(request, out, session, this); handler->process(request, out, session, this);
@@ -77,5 +89,4 @@ namespace core {
data.str(""); data.str("");
} }
} }
+16 -11
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;
}; };
} }
+144 -31
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,36 @@ 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++)
{
if ((*subscribed)->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 +84,133 @@ namespace core {
return countSubscribed; return countSubscribed;
} }
int SubscriptionManager::processCommand(coreutils::ZString &request, TCPSession &session) { int SubscriptionManager::processCommand(coreutils::ZString &request, TCPSession &session)
if (request[0].equals("publish")) { {
// Every branch below reads or mutates either the `subscriptions` map
// or some Subscription's own `subscribers` vector - both of which
// removeSessionSubscriptions() (called from ~TCPSession(), on
// whatever thread happens to be tearing down a *different*
// connection) also reads/mutates, under `lock`. This method used to
// take no lock at all, so a session disconnecting on one thread
// could run subscribers.erase() concurrently with subscribe()/
// event() iterating or push_back()-ing the same vector on another -
// an unsynchronized data race. Confirmed live: rapid connect/
// subscribe/disconnect cycles against ItemDataBase's "createItem"
// subscription produced a real segfault (gdb: Socket::write() ->
// resetSocket() dereferencing a corrupted EPoll reference) while
// broadcasting to *SUBSCRIBERS. `lock` is a plain, non-recursive
// std::mutex, and nothing reachable from this function re-enters
// processCommand()/add()/removeSessionSubscriptions() on the same
// thread, so holding it for the whole call is safe.
std::lock_guard<std::mutex> guard(lock);
if (request[0] == "publish")
{
SubscriptionHandler *handler = NULL; SubscriptionHandler *handler = NULL;
if(request.getList().size() > 3) { if (request.getList().size() > 3)
factory->getSubscriptionHandler(request[3].str()); {
handler = factory->getSubscriptionHandler(request[4].str());
} }
newSubscription = new Subscription(request[1].str(), session, request[2].str(), handler); if (request[2] == "*OWNER")
{
newSubscription = new Subscription(request[1].str(), session.alias, request[2].str(), request[3].str(), handler, request[5].str(), request[6].str());
subscriptions.insert(std::make_pair(request[1].str(), newSubscription)); subscriptions.insert(std::make_pair(request[1].str(), newSubscription));
newSubscription->owner = &session;
return 1; return 1;
} else if (request[0].equals("catalog")) { }
return 1;
}
else if (request[0] == "catalog")
{
session.out << ":catalog:"; session.out << ":catalog:";
for (auto const &[key, subscription] : subscriptions) { for (auto const &[key, subscription] : subscriptions)
{
session.out << subscription->id << ";"; session.out << subscription->id << ";";
} }
session.out << std::endl; session.out << std::endl;
return 1; return 1;
} else if (request[0].equals("invite")) { }
else if (request[0] == "invite")
{
std::stringstream out; std::stringstream out;
coreutils::Log(coreutils::LOG_DEBUG_1) << request[2]; coreutils::Log(coreutils::LOG_DEBUG_1) << request[2];
std::string invitee = request[2].str(); std::string invitee = request[2].str();
// 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.
TCPSession *tempSession = session.server->getSessionByAlias(&invitee); TCPSession *tempSession = session.server->getSessionByAlias(&invitee);
if (tempSession == NULL)
{
coreutils::Log(coreutils::LOG_DEBUG_1) << "invite: could not find session for " << invitee;
return 0;
}
std::stringstream temp; std::stringstream temp;
temp << "invite:" << request[1] << ":" << *(std::string *)session.alias; temp << "invite:" << request[1] << ":" << invitee;
tempSession->write(temp.str()); tempSession->write(temp.str());
return 1; return 1;
} }
auto subscription = subscriptions[request[1].str()]; // Was subscriptions[request[1].str()] - map::operator[] default-
// constructs (here: NULL) and INSERTS an entry for any id that
// isn't already registered, and subscription->id below was then
// dereferenced completely unconditionally. Any subscribe:/
// unsubscribe:/event: naming an id nobody ever created (confirmed
// live: "subscribe:invite", sent by the client on every scene
// load, referencing an "invite" subscription that plain doesn't
// exist anywhere - real invites are Publish()'d under a
// per-group-guid id, not a shared "invite" channel) null-derefs
// and takes down the ENTIRE process, every connection included,
// not just the one that sent it. find() avoids polluting the map
// with the bogus NULL entry too.
auto it = subscriptions.find(request[1].str());
if (it == subscriptions.end())
{
coreutils::Log(coreutils::LOG_DEBUG_1) << "Unknown subscription id: " << request[1].str();
return 0;
}
auto subscription = it->second;
if (request[1].equals(subscription->id)) { if (request[1].equals(subscription->id))
if (request[0].equals("unpublish")) { {
if (request[0] == "unpublish")
{
subscriptions.erase(request[1].str()); subscriptions.erase(request[1].str());
} else if (request[0].equals("subscribe")) { }
else if (request[0] == "subscribe")
{
subscription->subscribe(session); subscription->subscribe(session);
return 1; return 1;
} else if (request[0].equals("unsubscribe")) { }
else if (request[0] == "unsubscribe")
{
subscription->unsubscribe(session); subscription->unsubscribe(session);
return 1; return 1;
} else if (request[0].equals("event")) { }
else if (request[0] == "event")
{
std::stringstream out; std::stringstream out;
subscription->process(request, out, session); subscription->process(request, out, session);
if (subscription->mode == "*ANYONE") { if (subscription->mode == "*ANYONE")
subscription->event(out); {
return 1;
} else if (subscription->mode == "*SUBSCRIBERS") {
if (subscription->ifSubscriber(session)) {
subscription->event(out); subscription->event(out);
return 1; return 1;
} }
} else if (subscription->mode == "*AUTHOR") { else if (subscription->mode == "*SUBSCRIBERS")
if (subscription->owner == &session) { {
if (subscription->ifSubscriber(session))
{
subscription->event(out); subscription->event(out);
return 1; return 1;
} }
+10 -4
View File
@@ -2,32 +2,38 @@
#define __SubscriptionManager_h__ #define __SubscriptionManager_h__
#include "Command.h" #include "Command.h"
#include "MString.h"
#include "SessionFilter.h"
#include "Subscription.h" #include "Subscription.h"
#include "SubscriptionHandler.h" #include "SubscriptionHandler.h"
#include "TCPSession.h" #include "TCPSession.h"
#include "ZString.h" #include "ZString.h"
#include <string>
#include <vector> #include <vector>
namespace core { namespace core {
//*AUTHOR -> Dies when player disconnects
//*ANYONE -> Does not die when player disconnects
//*SUBSCRIPTION -> Does not die when player disconnects
//*OWNER -> Does die and transfers Ownership before he does
class SubscriptionHandlerFactory; class SubscriptionHandlerFactory;
class SubscriptionManager : public Command { class SubscriptionManager : public Command {
public: public:
int add(Subscription &subscription); int add(Subscription &subscription);
int removeSessionSubscriptions(TCPSession &session); int removeSessionSubscriptions(TCPSession &session);
int processCommand(coreutils::ZString &request, TCPSession &session) override; int processCommand(coreutils::ZString &request, TCPSession &session) override;
bool onClearSubscription(coreutils::MString temp, coreutils::MString key);
SubscriptionHandlerFactory *factory = NULL; SubscriptionHandlerFactory *factory = NULL;
private: private:
Subscription *subscription; Subscription *subscription;
std::map<std::string, Subscription *> subscriptions; std::map<coreutils::MString, Subscription *> subscriptions;
Subscription *newSubscription; Subscription *newSubscription;
std::mutex lock; std::mutex lock;
}; };
} }
+23 -5
View File
@@ -9,6 +9,20 @@ namespace core {
TCPServer::TCPServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo, std::string delimiter, int depth, std::string text) TCPServer::TCPServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo, std::string delimiter, int depth, std::string text)
: TCPSocket(ePoll, tlsInfo, text), commands(delimiter, depth) { : TCPSocket(ePoll, tlsInfo, text), commands(delimiter, depth) {
// Wires the subscription (pub/sub) command set into this server's
// own command dispatch - previously missing entirely here (the
// subscriptions member existed but nothing ever routed these verbs
// to it), so publish/subscribe/catalog/etc were unreachable on any
// TCPServer built after the TLS work, even though SubscriptionManager
// itself was still fully implemented.
commands.add(subscriptions, "publish");
commands.add(subscriptions, "unpublish");
commands.add(subscriptions, "subscribe");
commands.add(subscriptions, "unsubscribe");
commands.add(subscriptions, "catalog");
commands.add(subscriptions, "event");
commands.add(subscriptions, "invite");
setDescriptor(socket(AF_INET, SOCK_STREAM, 0)); setDescriptor(socket(AF_INET, SOCK_STREAM, 0));
int yes = 1; int yes = 1;
setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); setsockopt(getDescriptor(), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
@@ -56,7 +70,8 @@ namespace core {
TCPSession * TCPServer::accept() { TCPSession * TCPServer::accept() {
try { try
{
TCPSession *session = getSocketAccept(ePoll); TCPSession *session = getSocketAccept(ePoll);
session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength)); session->setDescriptor(::accept(getDescriptor(), (struct sockaddr *)&session->ipAddress.addr, &session->ipAddress.addressLength));
@@ -85,7 +100,8 @@ namespace core {
std::vector<TCPSession *>::iterator cursor; std::vector<TCPSession *>::iterator cursor;
lock.lock(); lock.lock();
for (cursor = sessions.begin(); cursor < sessions.end(); ++cursor) for (cursor = sessions.begin(); cursor < sessions.end(); ++cursor)
if(*cursor == session) { if (*cursor == session)
{
sessions.erase(cursor); sessions.erase(cursor);
break; break;
} }
@@ -100,11 +116,13 @@ 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)
{
int sequence = 0; int sequence = 0;
for (auto *sessionx : sessions) for (auto *sessionx : sessions)
{ {
@@ -139,7 +157,7 @@ namespace core {
TCPSession *TCPServer::getSessionByAlias(void *alias) { TCPSession *TCPServer::getSessionByAlias(void *alias) {
coreutils::Log(coreutils::LOG_DEBUG_1) << alias; coreutils::Log(coreutils::LOG_DEBUG_1) << alias;
for (auto session : sessions) for (auto session : sessions)
if (session->compareAlias(alias)) if (session->alias == alias)
return session; return session;
return NULL; return NULL;
} }
+16 -9
View File
@@ -2,17 +2,21 @@
#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")
{
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 +33,10 @@ namespace core {
timer.it_value.tv_nsec = (int)(fraction * 1000000000); timer.it_value.tv_nsec = (int)(fraction * 1000000000);
timerfd_settime(getDescriptor(), 0, &timer, NULL); timerfd_settime(getDescriptor(), 0, &timer, NULL);
} }
void Timer::clearTimer() { void Timer::clearTimer()
{
struct itimerspec timer; struct itimerspec timer;
@@ -44,18 +48,21 @@ namespace core {
timerfd_settime(getDescriptor(), 0, &timer, NULL); timerfd_settime(getDescriptor(), 0, &timer, NULL);
} }
double Timer::getElapsed() { double Timer::getElapsed()
{
struct itimerspec timer; struct itimerspec timer;
timerfd_gettime(getDescriptor(), &timer); timerfd_gettime(getDescriptor(), &timer);
double toTimeout = (double)((timer.it_value.tv_sec * 1000000000L) + timer.it_value.tv_nsec) / 1000000000L; double toTimeout = (double)((timer.it_value.tv_sec * 1000000000L) + timer.it_value.tv_nsec) / 1000000000L;
return delayValue - toTimeout; return delayValue - toTimeout;
} }
void Timer::onDataReceived(std::string data) { void Timer::onDataReceived(std::string data)
{
onTimeout(); onTimeout();
} }
double Timer::getEpoch() { double Timer::getEpoch()
{
return (double)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() / 1000000000L; return (double)std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count() / 1000000000L;
} }
+5 -5
View File
@@ -1,10 +1,11 @@
#ifndef __Timer_h__ #ifndef __Timer_h__
#define __Timer_h__ #define __Timer_h__
#include "Socket.h"
#include "EPoll.h" #include "EPoll.h"
#include "Socket.h"
namespace core { namespace core
{
/// ///
/// Timer /// Timer
@@ -15,7 +16,8 @@ namespace core {
/// interface. It cannot be instantiated directly but must be extended. /// interface. It cannot be instantiated directly but must be extended.
/// ///
class Timer : Socket { class Timer : Socket
{
public: public:
Timer(EPoll &ePoll); Timer(EPoll &ePoll);
@@ -48,7 +50,6 @@ namespace core {
double getEpoch(); double getEpoch();
protected: protected:
/// ///
/// This method is called when the time out occurs. /// This method is called when the time out occurs.
/// ///
@@ -58,7 +59,6 @@ namespace core {
private: private:
void onDataReceived(std::string data) override; void onDataReceived(std::string data) override;
double delayValue; double delayValue;
}; };
} }