feat(Core): replace ACE network with Boost.Asio (#6574)

This commit is contained in:
Kargatum
2021-07-16 15:43:56 +07:00
committed by GitHub
parent 7449496bb5
commit 8568c4fb33
64 changed files with 3242 additions and 4712 deletions

View File

@@ -4,197 +4,121 @@
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*/
/** \addtogroup u2w User to World Communication
* @{
* \file WorldSocket.h
* \author Derex <derex101@gmail.com>
*/
#ifndef __WORLDSOCKET_H__
#define __WORLDSOCKET_H__
#ifndef _WORLDSOCKET_H
#define _WORLDSOCKET_H
#include "AuthCrypt.h"
#include "Common.h"
#include "Duration.h"
#include <ace/Message_Block.h>
#include <ace/SOCK_Stream.h>
#include <ace/Svc_Handler.h>
#include <ace/Synch_Traits.h>
#include <ace/Unbounded_Queue.h>
#include <mutex>
#include "AuthCrypt.h"
#include "ServerPktHeader.h"
#include "Socket.h"
#include "Util.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "MPSCQueue.h"
#include <boost/asio/ip/tcp.hpp>
#if !defined (ACE_LACKS_PRAGMA_ONCE)
#pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
using boost::asio::ip::tcp;
class ACE_Message_Block;
class WorldPacket;
class WorldSession;
class EncryptablePacket : public WorldPacket
{
public:
EncryptablePacket(WorldPacket const& packet, bool encrypt) : WorldPacket(packet), _encrypt(encrypt)
{
SocketQueueLink.store(nullptr, std::memory_order_relaxed);
}
bool NeedsEncryption() const { return _encrypt; }
std::atomic<EncryptablePacket*> SocketQueueLink;
private:
bool _encrypt;
};
namespace WorldPackets
{
class ServerPacket;
}
/// Handler that can communicate over stream sockets.
typedef ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_NULL_SYNCH> WorldHandler;
/**
* WorldSocket.
*
* This class is responsible for the communication with
* remote clients.
* Most methods return -1 on failure.
* The class uses reference counting.
*
* For output the class uses one buffer (64K usually) and
* a queue where it stores packet if there is no place on
* the queue. The reason this is done, is because the server
* does really a lot of small-size writes to it, and it doesn't
* scale well to allocate memory for every. When something is
* written to the output buffer the socket is not immediately
* activated for output (again for the same reason), there
* is 10ms celling (thats why there is Update() method).
* This concept is similar to TCP_CORK, but TCP_CORK
* uses 200ms celling. As result overhead generated by
* sending packets from "producer" threads is minimal,
* and doing a lot of writes with small size is tolerated.
*
* The calls to Update() method are managed by WorldSocketMgr
* and ReactorRunnable.
*
* For input, the class uses one 4096 bytes buffer on stack
* to which it does recv() calls. And then received data is
* distributed where its needed. 4096 matches pretty well the
* traffic generated by client for now.
*
* The input/output do speculative reads/writes (AKA it tryes
* to read all data available in the kernel buffer or tryes to
* write everything available in userspace buffer),
* which is ok for using with Level and Edge Triggered IO
* notification.
*
*/
class WorldSocket : public WorldHandler
#pragma pack(push, 1)
struct ClientPktHeader
{
uint16 size;
uint32 cmd;
bool IsValidSize() const { return size >= 4 && size < 10240; }
bool IsValidOpcode() const { return cmd < NUM_OPCODE_HANDLERS; }
};
#pragma pack(pop)
struct AuthSession;
class AC_GAME_API WorldSocket : public Socket<WorldSocket>
{
typedef Socket<WorldSocket> BaseSocket;
public:
WorldSocket (void);
virtual ~WorldSocket (void);
WorldSocket(tcp::socket&& socket);
~WorldSocket();
friend class WorldSocketMgr;
WorldSocket(WorldSocket const& right) = delete;
WorldSocket& operator=(WorldSocket const& right) = delete;
/// Check if socket is closed.
bool IsClosed (void) const;
void Start() override;
bool Update() override;
/// Close the socket.
void CloseSocket(std::string const& reason);
void SendPacket(WorldPacket const& packet);
/// Get address of connected peer.
const std::string& GetRemoteAddress (void) const;
void SetSendBufferSize(std::size_t sendBufferSize) { _sendBufferSize = sendBufferSize; }
/// Send A packet on the socket, this function is reentrant.
/// @param pct packet to send
/// @return -1 of failure
int SendPacket(const WorldPacket& pct);
protected:
void OnClose() override;
void ReadHandler() override;
bool ReadHeaderHandler();
/// Add reference to this object.
long AddReference (void);
enum class ReadDataHandlerResult
{
Ok = 0,
Error = 1,
WaitingForQuery = 2
};
/// Remove reference to this object.
long RemoveReference (void);
/// things called by ACE framework.
/// Called on open, the void* is the acceptor.
virtual int open (void*);
/// Called on failures inside of the acceptor, don't call from your code.
virtual int close (u_long);
/// Called when we can read from the socket.
virtual int handle_input (ACE_HANDLE = ACE_INVALID_HANDLE);
/// Called when the socket can write.
virtual int handle_output (ACE_HANDLE = ACE_INVALID_HANDLE);
/// Called when connection is closed or error happens.
virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE,
ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK);
/// Called by WorldSocketMgr/ReactorRunnable.
int Update (void);
ReadDataHandlerResult ReadDataHandler();
private:
/// Helper functions for processing incoming data.
int handle_input_header (void);
int handle_input_payload (void);
int handle_input_missing_data (void);
void CheckIpCallback(PreparedQueryResult result);
/// Help functions to mark/unmark the socket for output.
/// @param g the guard is for m_OutBufferLock, the function will release it
int cancel_wakeup_output();
int schedule_wakeup_output();
/// writes network.opcode log
/// accessing WorldSession is not threadsafe, only do it when holding _worldSessionLock
void LogOpcodeText(OpcodeClient opcode, std::unique_lock<std::mutex> const& guard) const;
/// Drain the queue if its not empty.
int handle_output_queue();
/// sends and logs network.opcode without accessing WorldSession
void SendPacketAndLogOpcode(WorldPacket const& packet);
void HandleSendAuthSession();
void HandleAuthSession(WorldPacket& recvPacket);
void HandleAuthSessionCallback(std::shared_ptr<AuthSession> authSession, PreparedQueryResult result);
void LoadSessionPermissionsCallback(PreparedQueryResult result);
void SendAuthResponseError(uint8 code);
/// process one incoming packet.
/// @param new_pct received packet, note that you need to delete it.
int ProcessIncoming (WorldPacket* new_pct);
bool HandlePing(WorldPacket& recvPacket);
/// Called by ProcessIncoming() on CMSG_AUTH_SESSION.
int HandleAuthSession (WorldPacket& recvPacket);
std::array<uint8, 4> _authSeed;
AuthCrypt _authCrypt;
/// Called by ProcessIncoming() on CMSG_PING.
int HandlePing (WorldPacket& recvPacket);
TimePoint _LastPingTime;
uint32 _OverSpeedPings;
private:
/// Time in which the last ping was received
SystemTimePoint m_LastPingTime;
std::mutex _worldSessionLock;
WorldSession* _worldSession;
bool _authed;
/// Keep track of over-speed pings, to prevent ping flood.
uint32 m_OverSpeedPings;
/// Address of the remote peer
std::string m_Address;
/// Class used for managing encryption of the headers
AuthCrypt m_Crypt;
/// Mutex lock to protect m_Session
std::mutex m_SessionLock;
/// Session to which received packets are routed
WorldSession* m_Session;
/// here are stored the fragments of the received data
WorldPacket* m_RecvWPct;
/// This block actually refers to m_RecvWPct contents,
/// which allows easy and safe writing to it.
/// It wont free memory when its deleted. m_RecvWPct takes care of freeing.
ACE_Message_Block m_RecvPct;
/// Fragment of the received header.
ACE_Message_Block m_Header;
/// Mutex for protecting output related data.
std::mutex m_OutBufferLock;
/// Buffer used for writing output.
ACE_Message_Block* m_OutBuffer;
/// Size of the m_OutBuffer.
size_t m_OutBufferSize;
/// True if the socket is registered with the reactor for output
bool m_OutActive;
std::array<uint8, 4> m_Seed;
MessageBuffer _headerBuffer;
MessageBuffer _packetBuffer;
MPSCQueue<EncryptablePacket, &EncryptablePacket::SocketQueueLink> _bufferQueue;
std::size_t _sendBufferSize;
QueryCallbackProcessor _queryProcessor;
std::string _ipCountry;
};
#endif /* _WORLDSOCKET_H */
/// @}
#endif