Files

752 lines
22 KiB
C++

/**
* @file include/ActivMiddleware/ActivBase/Windows/Ip/IpSocket.h
*
* @brief Header file for ip socket class.
*/
#if (!defined ACTIV_BASE_IP_WINDOWS_IP_SOCKET_H)
#define ACTIV_BASE_IP_WINDOWS_IP_SOCKET_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Ip/IpManager.h"
#include "ActivMiddleware/ActivBase/Windows/Ip/WsaBufHelper.h"
#include "ActivMiddleware/ActivBase/Ip/SocketWrapper.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/ActivBase/MutexHelper.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Base ip socket class.
*/
class IpSocket : private Boost::noncopyable
{
public:
//! Return values from OnGet(Rx/Tx)Buffers().
enum GetBuffersResult
{
GET_BUFFERS_RESULT_CLOSE_SOCKET, ///< Major error, close socket.
GET_BUFFERS_RESULT_NO_MORE_BUFFERS, ///< No buffers available, but keep socket alive.
GET_BUFFERS_RESULT_ALREADY_PROCESSED ///< Request has been processed by another layer; do not process but return GET_BUFFERS_RESULT_ALREADY_PROCESSED immediately.
};
//! Return values from On(Rx/Tx)Buffers().
enum CompletionResult
{
COMPLETION_RESULT_CLOSE_SOCKET, ///< Major error, close socket (eg out of protocol data).
COMPLETION_RESULT_OK, ///< Completion data was OK.
COMPLETION_RESULT_ALREADY_PROCESSED ///< Request has been processed by another layer; do not process but return COMPLETION_RESULT_ALREADY_PROCESSED immediately.
};
/**
* @brief Settings.
*/
class Settings
{
public:
/**
* @brief Constructor.
*
* @param shouldCork set TCP_CORK, if available, whilst in tx loop.
*/
Settings(const bool shouldCork = false);
bool m_shouldCork; ///< Set TCP_CORK, if available, whilst in tx loop.
};
/**
* @brief Stats.
*/
class Stats
{
public:
/**
* @brief Constructor.
*
* Note if constructing a Stats object directly, the socket's mutex must be locked (this isn't
* done by the Stats constructor). Alternatively, use the helper function IpSocket::Stats::Get() which will
* lock the mutex for you before gathering the stats.
*
* @param socket to get stats from.
*/
ACTIV_BASE_API Stats(const IpSocket &socket);
//! Destructor.
virtual ~Stats();
/**
* @brief Helper function to get stats for a socket.
*
* This is templatized by a derived socket type and locks the socket before gathering the stats.
*
* @param socket socket to get stats for.
*
* @return Stats for socket.
*/
template <typename SOCKET_TYPE>
static typename SOCKET_TYPE::Stats Get(const SOCKET_TYPE &socket);
/**
* @brief Helper function to create stats for a socket.
*
* This is templatized by a derived socket type and locks the socket before gathering the stats.
*
* @param socket socket to get stats for.
*
* @return Pointer to Stats for socket. Must be deleted as appropriate.
*/
template <typename SOCKET_TYPE>
static typename SOCKET_TYPE::Stats *Create(const SOCKET_TYPE &socket);
HANDLE m_handle;
IpAddress m_remoteAddress; ///< Remote address information.
IpAddress m_localAddress; ///< Local address information.
bool m_rxPosted; ///< Read outstanding.
bool m_txPosted; ///< Write outstanding.
bool m_closePosted; ///< User has requested a close.
bool m_closeOnTxCompletion; ///< Close gracefully when there is no more data to transmit.
uint64_t m_rxBytes; ///< Total bytes received.
uint64_t m_txBytes; ///< Total bytes transmitted.
size_t m_rxMaxIoBytesCount; ///< Number of times rx was terminated due to max IO byte.
size_t m_txMaxIoBytesCount; ///< Number of times tx was terminated due to max IO byte.
size_t m_rxWouldBlockCount; ///< Number of times rx was terminated due to would block.
size_t m_txWouldBlockCount; ///< Number of times tx was terminated due to would block.
size_t m_mutexContentionCount; ///< Approx. number of contentions on the mutex.
};
/**
* @brief Default constructor.
*
* @param ipManager the IpManager that owns the socket.
* @param socketType socket type.
* @param settings the Settings.
*
* @throw Exception.
*/
ACTIV_BASE_API IpSocket(IpManager &ipManager, const int socketType, const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_BASE_API virtual ~IpSocket();
/**
* @brief Read some data.
*
* Generally a read will always be outstanding on a socket, unless an rx handler returns 0 buffers
* from OnGetRxBuffers(), in which case LockedRead() here needs to be called at some point to start reading from the
* socket again.
*
* Note this function will obtain the socket mutex for the duration of the call.
*/
void LockedRead();
/**
* @brief Read some data without obtaining the socket mutex.
*
* As LockedRead(), but do not obtain the socket mutex first (assumes the mutex is already locked).
*/
void PreLockedRead();
/**
* @brief Write some data.
*
* If no write event is set for the socket, this will set one. At some point the event thread will callback OnGetTxBuffers().
*
* Note this function will obtain the socket mutex for the duration of the call.
*/
void LockedWrite();
/**
* @brief Write some data without obtaining the socket mutex.
*
* As LockedWrite(), but do not obtain the socket mutex first (assumes the mutex is already locked).
*/
void PreLockedWrite();
/**
* @brief Append an rx buffer.
*
* @param pData pointer to the buffer to read into.
* @param dataLength the length the buffer.
*
* @throw Exception if the buffer wasn't appended to the rx array.
*/
void AppendRxBuffer(void *pData, const size_t dataLength);
/**
* @brief Get a reference to the receive buffers.
*
* @return Receive buffers reference.
*/
WsaBufHelper &GetRxBuffers();
/**
* @brief Get a reference to the receive buffers.
*
* @return Receive buffers const reference.
*/
const WsaBufHelper &GetRxBuffers() const;
/**
* @brief Enable custom reads on the socket.
*
* After calling this, data received on the socket is dropped on the floor.
* You can feed data into the socket using GetRxBuffers() and ProcessCustomRxCompletion().
*/
void EnableCustomRx();
/**
* @brief Cause the socket to process some data that has been fed to it
* via GetRxBuffers().
*
* The regular OnRxBuffers() callback is invoked, and socket
* cleanup initiated if the OnRxBuffers() handler returns COMPLETION_RESULT_CLOSE_SOCKET.
*
* @param numberOfBytes
*
* @return true if the data was consumed ok; false if not and a socket close has been initiated.
*/
ACTIV_BASE_API const bool ProcessCustomRxCompletion(const size_t numberOfBytes);
/**
* @brief Append a tx buffer.
*
* @param pData pointer to the buffer to transmit.
* @param dataLength the length the buffer.
*
* @throw Exception if the buffer wasn't appended to the tx array.
*/
void AppendTxBuffer(const void *pData, const size_t dataLength);
/**
* @brief Get a reference to the transmit buffers.
*
* @return Transmit buffers reference.
*/
WsaBufHelper &GetTxBuffers();
/**
* @brief Get a reference to the transmit buffers.
*
* @return Transmit buffers const reference.
*/
const WsaBufHelper &GetTxBuffers() const;
/**
* @brief Enable custom writes on the socket.
*
* After calling this, OnGetTxBuffers() is called as normal. However, instead of that
* data being written to the socket, OnCustomTx() will be called instead. Once the custom
* write is complete (e.g. data base64-encoded and sent on a second socket), ProcessCustomTxCompletion()
* should be called.
*/
void EnableCustomTx();
/**
* @brief Process a custom write completion.
*
* @param numberOfBytes
*/
ACTIV_BASE_API void ProcessCustomTxCompletion(const size_t numberOfBytes);
/**
* @brief Get the local address of the socket.
*
* @param ipAddress a reference to an IpAddress object to receive the local socket address.
*/
ACTIV_BASE_API void GetLocalAddress(IpAddress &ipAddress) const;
/**
* @brief Get the remote address of the socket.
*
* @param ipAddress a reference to an IpAddress object to receive the remote socket address.
*/
ACTIV_BASE_API void GetRemoteAddress(IpAddress &ipAddress) const;
/**
* @brief Get the internal rx buffer size.
*
* @param size to receive the buffer size.
*
* @throw Exception.
*/
ACTIV_BASE_API void GetRxBufferSize(int &size) const;
/**
* @brief Set the internal rx buffer size.
*
* This would most likely be used in an overridden OnSetSocketOptions().
*
* @param size the buffer size.
*
* @throw Exception.
*/
ACTIV_BASE_API void SetRxBufferSize(const int size);
/**
* @brief Get the internal tx buffer size.
*
* @param size to receive the buffer size.
*
* @throw Exception.
*/
ACTIV_BASE_API void GetTxBufferSize(int &size) const;
/**
* @brief Set the internal tx buffer size.
*
* This would most likely be used in an overridden OnSetSocketOptions().
*
* @param size the buffer size.
*
* @throw Exception.
*/
ACTIV_BASE_API void SetTxBufferSize(const int size);
/**
* @brief Set type of service.
*
* @param typeOfService IP_TOS value.
*
* @throw Exception.
*/
ACTIV_BASE_API void SetTypeOfService(const byte_t typeOfService);
/**
* @brief Set a socket option.
*
* @param optionName Socket option for which the value is to be set.
* @param pOptionValue Pointer to the buffer in which the value for the requested option is supplied.
* @param optionLength Size of the \a pOptionValue buffer.
* @param level Level at which the option is defined.
*
* @throw Exception if the socket option is not set successfully.
*/
ACTIV_BASE_API void SetSocketOption(const int optionName, const char *pOptionValue, const socklen_t optionLength,
const int level = SOL_SOCKET);
/**
* @brief Get a socket option.
*
* @param optionName Socket option for which the value is to be retrieved.
* @param pOptionValue Pointer to the buffer in which the value for the requested option is to be returned.
* @param pOptionLength Pointer to the size of the \a pOptionValue buffer.
* @param level Level at which the option is defined.
*
* @throw Exception if the socket option is not retrieved successfully.
*/
ACTIV_BASE_API void GetSocketOption(const int optionName, char *pOptionValue, socklen_t *pOptionLength,
const int level = SOL_SOCKET) const;
/**
* @brief Get the socket handle.
*
* @return The socket handle.
*/
ACTIV_BASE_API SOCKET GetSocketHandle() const;
/**
* @brief Get the IpManager.
*
* @return IpManager reference as passed to constructor.
*/
IpManager &GetIpManager() const;
//! Is a callback currently being called?
bool IsInCallback() const;
protected:
/**
* @brief Overridable socket options.
*
* Use SetSocketOption() in an overridden OnSetSocketOptions().
*
* @throw Exception if the socket option is not set correctly.
*/
ACTIV_BASE_API virtual void OnSetSocketOptions();
/**
* @brief Callback to initialize rx / tx state.
*
* @retval true if successful.
* @retval false if unsuccessful and the socket will be closed.
*/
ACTIV_BASE_API virtual bool OnInitializeIo();
/**
* @brief Callback to cleanup rx / tx state.
*
* For example, this will be called when a tcp connection is closed.
*/
ACTIV_BASE_API virtual void OnCleanupIo();
/**
* @brief Callback to get rx buffers.
*
* In an override of this, call the base class OnGetRxBuffers() first. If it returns GET_BUFFERS_RESULT_NO_MORE_BUFFERS,
* call AppendRxBuffer() to attach buffer(s) to read into. Return GET_BUFFERS_RESULT_NO_MORE_BUFFERS when done.
* If the base returns other than GET_BUFFERS_RESULT_NO_MORE_BUFFERS, just return the value immediately.
*
* @retval GET_BUFFERS_RESULT_CLOSE_SOCKET failed to get buffers to read into, close socket.
* @retval GET_BUFFERS_RESULT_NO_MORE_BUFFERS all rx buffers have been appended.
* @retval GET_BUFFERS_RESULT_ALREADY_PROCESSED to indicate to a derived class that it should not append any more buffers.
*/
ACTIV_BASE_API virtual GetBuffersResult OnGetRxBuffers();
/**
* @brief Callback on rx completion.
*
* When overriding this function, you MUST call the base class OnRxBuffers() first, and return
* the result if it isn't COMPLETION_RESULT_OK.
*
* @retval COMPLETION_RESULT_CLOSE_SOCKET socket should be closed
* @retval COMPLETION_RESULT_OK
* @retval COMPLETION_RESULT_ALREADY_PROCESSED the base class has processed the completion.
*/
ACTIV_BASE_API virtual CompletionResult OnRxBuffers();
/**
* @brief Callback on a dummy rx completion.
*
* When overriding this function, you MUST call the base class OnDummyRxCompletion() first, and return
* the result if it isn't COMPLETION_RESULT_OK.
*
* @retval COMPLETION_RESULT_CLOSE_SOCKET socket should be closed
* @retval COMPLETION_RESULT_OK
* @retval COMPLETION_RESULT_ALREADY_PROCESSED the base class has processed the completion.
*/
ACTIV_BASE_API virtual CompletionResult OnDummyRxCompletion(const size_t numberOfBytes) const;
/**
* @brief Callback to get tx buffers.
*
* In an override of this, call the base class OnGetTxBuffers() first. If it returns GET_BUFFERS_RESULT_NO_MORE_BUFFERS,
* call AppendTxBuffer() to attach buffer(s) to read into. Return GET_BUFFERS_RESULT_NO_MORE_BUFFERS when done.
* If the base returns other than GET_BUFFERS_RESULT_NO_MORE_BUFFERS, just return the value immediately.
*
* @retval GET_BUFFERS_RESULT_CLOSE_SOCKET failed to get buffers to write from, close socket
* @retval GET_BUFFERS_RESULT_NO_MORE_BUFFERS all tx buffers have been appended
* @retval GET_BUFFERS_RESULT_ALREADY_PROCESSED to indicate to a derived class that it should not append any more buffers.
*/
ACTIV_BASE_API virtual GetBuffersResult OnGetTxBuffers();
/**
* @brief Callback on tx completion.
*
* When overriding this function, you MUST call the base class OnTxBuffers() first, and return
* the result if it isn't COMPLETION_RESULT_OK.
*
* @retval COMPLETION_RESULT_CLOSE_SOCKET socket should be closed
* @retval COMPLETION_RESULT_OK
* @retval COMPLETION_RESULT_ALREADY_PROCESSED the base class has processed the completion.
*/
ACTIV_BASE_API virtual CompletionResult OnTxBuffers();
/**
* @brief If EnableCustomTx() has been called, this callback will be invoked after OnGetTxBuffers(), instead of
* data being written to the socket. The data (available with GetTxBuffers()) can then be, for example,
* tunnelled in HTTP over another connection.
*
* @return Boolean. False to close the socket.
*/
ACTIV_BASE_API virtual bool OnCustomTx();
/**
* @brief Post a read on a socket.
*
* @return false if a read was not posted on the socket, in which case the socket should be closed.
*/
ACTIV_BASE_API bool PostRead();
/**
* @brief Post a write on a socket.
*
* @return false if a write was not posted on the socket, in which case the socket should be closed.
*/
ACTIV_BASE_API bool PostWrite();
/**
* @brief Invoke the OnCleanupIo() callback if no rx or tx is outstanding.
*
* @return true if all io is complete and rx and tx handlers are fully cleaned up.
*/
ACTIV_BASE_API bool CleanupIo();
/**
* @brief Abortive close on a socket if it hasn't already been closed.
*/
ACTIV_BASE_API void CloseSocket();
/**
* @brief Shutdown a socket.
*
* @return true if the shutdown was successful.
*/
ACTIV_BASE_API bool ShutdownSocket();
/**
* @brief Handle an io failure.
*
* @param gracefully whether to do a graceful shutdown on the socket, or an abortive close.
*/
virtual void HandleIoFailure(const bool gracefully) = 0;
/**
* @brief Overlapped class for writes.
*/
class TxOverlapped : public IoCompletionManager::Overlapped
{
public:
/**
* @brief Constructor.
*
* @param ipSocket IpSocket containing this object.
*/
TxOverlapped(IpSocket &ipSocket);
private:
virtual void OnIoCompletion() ACTIV_OVERRIDE;
IpSocket &m_ipSocket;
};
/**
* @brief Overlapped class for reads.
*/
class RxOverlapped : public IoCompletionManager::Overlapped
{
public:
/**
* @brief Constructor.
*
* @param ipSocket IpSocket containing this object.
*/
RxOverlapped(IpSocket &ipSocket);
private:
virtual void OnIoCompletion() ACTIV_OVERRIDE;
IpSocket &m_ipSocket;
};
/**
* @brief Dummy overlapped class for reads when custom read is enabled; data is dropped on the floor.
*/
class DummyRxOverlapped : public IoCompletionManager::Overlapped
{
public:
/**
* @brief Constructor.
*
* @param ipSocket IpSocket containing this object.
*/
DummyRxOverlapped(IpSocket &ipSocket);
private:
virtual void OnIoCompletion() ACTIV_OVERRIDE;
IpSocket & m_ipSocket;
public:
DWORD m_rxFlags;
byte_t m_rxBuffer[128];
};
IpManager & m_ipManager; ///< This object is managed by an IpManager.
IMutex * const m_pMutex; ///< Mutex.
SocketWrapper m_handle; ///< The underlying socket.
RxOverlapped m_rxOverlapped; ///< Receive overlapped info.
WsaBufHelper m_rxBuffers; ///< WSABUF array for receive.
DWORD m_rxFlags; ///< Flags for WSARecv().
uint64_t m_rxBytes; ///< Total rx bytes.
Boost::scoped_ptr<DummyRxOverlapped> m_pDummyRxOverlapped; ///< Dummy overlapped class for reads when custom read is enabled; data is dropped on the floor.
TxOverlapped m_txOverlapped; ///< Transmission overlapped info.
WsaBufHelper m_txBuffers; ///< WSABUF array for transmission.
DWORD m_txFlags; ///< Flags for WSASend().
uint64_t m_txBytes; ///< Total tx bytes.
IpAddress m_remoteAddress; ///< Remote address information (if socket is connected).
IpAddress m_localAddress; ///< Local address information.
IpAddress m_toAddress; ///< Destination address for current write (connectionless).
IpAddress m_fromAddress; ///< Source address for current read (connectionless).
socklen_t m_fromAddressLength; ///< To receive overlapped length of m_fromAddress.
bool m_closePosted; ///< User has requested a close.
bool m_closeOnTxCompletion; ///< Close gracefully when there is no more data to transmit.
size_t m_inCallbackCount; ///< >0 if a callback is being called.
//! Class to control m_inCallbackCount.
class ScopedIsInCallback
{
public:
ScopedIsInCallback(IpSocket &ipSocket);
~ScopedIsInCallback();
private:
IpSocket &m_ipSocket;
};
private:
/**
* @brief Common i/o initialization.
*/
void InitializeIoCommon();
/**
* @brief Initiate a write operation.
*
* @return true ok, false socket will be closed.
*/
bool InitiateWrite();
/**
* @brief Initiate a custom write operation.
*
* Invokes the OnCustomTx() callback. Any exceptions thrown are caught and false returned.
*
* @return true ok, false socket will be closed.
*/
bool InitiateCustomWrite();
/**
* @brief Initiate a read operation.
*
* @return true ok, false socket will be closed.
*/
bool InitiateRead();
/**
* @brief Process an overlapped write completion.
*/
void ProcessTxCompletion();
/**
* @brief Process an overlapped read completion.
*/
void ProcessRxCompletion();
/**
* @brief Initiate a dummy read; creates overlapped class as required.
*
* @return true ok, false socket will be closed.
*/
bool InitiateDummyRead();
/**
* @brief Post a dummy read.
*
* @return true ok, false socket will be closed.
*/
bool PostDummyRead();
/**
* @brief Process a dummy overlapped read completion.
*/
void ProcessDummyRxCompletion();
const int m_socketType; ///< Type of socket in m_socket.
bool m_isCustomTx; ///< False until EnableCustomTx() is called.
bool m_isCustomRx; ///< False until EnableCustomRx() is called.
bool m_shouldInitiateWrite; ///< Set by (Pre)LockedWrite() if inside a callback.
bool m_shouldInitiateRead; ///< Set by (Pre)LockedRead() if inside a callback.
friend class IpManager; ///< Manager needs access to the objects it is managing.
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpSocket::LockedRead()
{
ScopedMutexLocker scopedMutexLocker(m_pMutex);
PreLockedRead();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpSocket::PreLockedRead()
{
// If a read is currently still in progress, we can't do anything here. Once the read completes, PostRead()
// will be called internally. Similarly, if we're called from within a callback, PostRead() is deferred until the callback
// completes.
if (!IsInCallback())
{
if (!m_rxOverlapped.IsPending())
{
if (!PostRead())
HandleIoFailure(false);
}
}
else
{
m_shouldInitiateRead = true;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpSocket::LockedWrite()
{
ScopedMutexLocker scopedMutexLocker(m_pMutex);
PreLockedWrite();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IpSocket::PreLockedWrite()
{
// If a write is currently still in progress, we can't do anything here. Once the write completes, PostWrite()
// will be called and the data will be taken off the tx handler's queue and written to the socket in the context
// of an io thread. Similarly, if we're called from within a callback, PostWrite() is deferred until the callback
// completes.
if (!IsInCallback())
{
if (!m_txOverlapped.IsPending())
{
if (!PostWrite())
HandleIoFailure(false);
}
}
else
{
m_shouldInitiateWrite = true;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpSocket::Settings::Settings(const bool shouldCork) :
m_shouldCork(shouldCork)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline IpSocket::Stats::~Stats()
{
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_WINDOWS_IP_SOCKET_H)