#include "TCPServer.h" #include "EPoll.h" #include "Exception.h" #include "Log.h" #include "TCPSession.h" #include #include namespace core { TCPServer::TCPServer(EPoll &ePoll, IPAddress address, TLSInfo *tlsInfo, std::string delimiter, int depth, std::string text) : TCPSocket(ePoll, tlsInfo, text), commands(delimiter, depth) { // Wires the subscription (pub/sub) command set into this server's // own command dispatch - previously missing entirely here (the // subscriptions member existed but nothing ever routed these verbs // to it), so publish/subscribe/catalog/etc were unreachable on any // TCPServer built after the TLS work, even though SubscriptionManager // itself was still fully implemented. commands.add(subscriptions, "publish"); commands.add(subscriptions, "unpublish"); commands.add(subscriptions, "subscribe"); commands.add(subscriptions, "unsubscribe"); commands.add(subscriptions, "catalog"); commands.add(subscriptions, "event"); commands.add(subscriptions, "invite"); // 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; setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); if (bind(fd, address.getPointer(), address.addressLength) < 0) { int error = errno; close(fd); throw coreutils::Exception("Error on bind to socket: " + std::to_string(error)); } // Was 20 - small enough that a burst of connection attempts // arriving faster than this process calls accept() (a port scan, // or just several real clients reconnecting around the same // moment) can fill the kernel's own backlog before the // application layer gets a chance to drain it, silently dropping // the overflow SYNs rather than queuing them. 128 gives real // bursts meaningfully more headroom; still bounded, not unlimited. if (listen(fd, 128) < 0) { close(fd); throw coreutils::Exception("Error on listen to socket"); } { std::lock_guard guard(listeningSocketsMutex()); listeningSockets().insert(this); } setDescriptor(fd); } TCPServer::~TCPServer() { coreutils::Log(coreutils::LOG_DEBUG_2) << "Closing server socket " << getDescriptor() << "."; close(getDescriptor()); } void TCPServer::connectionRequest() { 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(); // accept() now adds the session to `sessions` and the live registry // itself, before its fd is armed - see the comment there. // accept() registers the session and, for an implicit-TLS listener, // starts its TLS handshake (on the session, not on `this`) before // arming the fd - see its own comment. accept(); 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 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) { // See this override's own doc comment in TCPServer.h - the // listening socket always uses the plain read()/ENOTCONN detection // path, never TLS::receiveData(), regardless of whether this server // is TLS-configured. Socket::receiveData(buffer); } TCPSession * TCPServer::accept() { // 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. struct sockaddr_in address; socklen_t addressLength = sizeof(address); int fd = ::accept(getDescriptor(), (struct sockaddr *)&address, &addressLength); if (fd < 0) { if (errno == EMFILE || errno == ENFILE) coreutils::Log(coreutils::LOG_EXCEPT) << "Too many files open. Refusing connection."; return NULL; } TCPSession *session = NULL; try { session = getSocketAccept(ePoll); } catch (...) { coreutils::Log(coreutils::LOG_EXCEPT) << "Error creating session object; connection refused."; close(fd); return NULL; } session->ipAddress.addr = address; session->ipAddress.addressLength = addressLength; auto sessionPtr = std::shared_ptr(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) { lock.lock(); for (auto cursor = sessions.begin(); cursor < sessions.end(); ++cursor) if (cursor->get() == session) { // Drops the one strong-owning reference. If nothing else is // currently pin()'d to this session, the object is actually // destroyed right here, synchronously - same timing as // before this change for the common (no-contention) case. // If some other thread IS mid-call via its own pin()'d // shared_ptr right now, destruction is safely deferred until // that reference is released too, instead of the crash // (double-delete / use-after-free, confirmed live via // AddressSanitizer under concurrent load) that raw-pointer // ownership produced here before. sessions.erase(cursor); break; } lock.unlock(); // Removes this pointer from the tryGet() lookup registry too (see // TCPSession::tryGet()'s own comment). Safe to do after releasing // `lock` and regardless of whether the erase() above was actually // the last reference: tryGet() correctly reports "gone" the moment // a session's real refcount hits zero, via the weak_ptr's own // expiration - this call is just tidying the registry map itself, // not something later correctness depends on. TCPSession::unregisterLive(session); } void TCPServer::sessionErrorHandler(std::string errorString, std::stringstream &out) { throw coreutils::Exception(errorString); } TCPSession * TCPServer::getSocketAccept(EPoll &ePoll) { return new TCPSession(ePoll, this); } void TCPServer::output(std::stringstream &out) { out << "Use the 'help' command to list the commands for this server." << std::endl; } int TCPServer::processCommand(coreutils::ZString &request, TCPSession &session) { // Was unguarded, like every other method below - `sessions` is // mutated under `lock` by connectionRequest()/removeFromSessionList() // (a session accepting or disconnecting on another thread), but // every READ of it here had no lock at all. Confirmed live via // dmesg: a real segfault at a stable, deterministic instruction // offset (same crash signature as the Subscription::subscribers // race fixed earlier this session, in SubscriptionManager.cpp) - // Socket::write() -> resetSocket() dereferencing a null EPoll // reference, consistent with iterating `sessions` while another // thread concurrently erased and freed one of its entries. // sendToAll() in particular is what most real gameplay broadcasts // (combat, position, chat) go through, so this is very likely the // actual dominant cause of that crash, not just the ItemDataBase // subscriber list this session's earlier fix addressed. std::lock_guard guard(lock); int sequence = 0; for (auto &sessionx : sessions) { session.out << "|" << ++sequence; sessionx->output(session.out); session.out << "|" << std::endl; } return 1; } void TCPServer::sendToAll(std::stringstream &data) { std::lock_guard guard(lock); for (auto &session : sessions) session->write(data.str()); data.str(""); } void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender) { std::lock_guard guard(lock); for (auto &session : sessions) if (session.get() != &sender) session->write(data.str()); data.str(""); } void TCPServer::sendToAll(std::stringstream &data, TCPSession &sender, SessionFilter filter) { std::lock_guard guard(lock); for (auto &session : sessions) if (filter.test(*session)) if (session.get() != &sender) session->write(data.str()); data.str(""); } std::shared_ptr TCPServer::getSessionByAlias(void *alias) { coreutils::Log(coreutils::LOG_DEBUG_1) << alias; std::lock_guard guard(lock); for (auto &session : sessions) if (session->alias == alias) return session; return nullptr; } }