Remove Activ libs and includes

This commit is contained in:
John Colvin committed 2023-12-15 13:15:08 -05:00
1 parent 28ed30c944
commit 4b718994be
10967 files changed
-2306716

No files matched your search

@@ -1,180 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/EventManager.h
*
* @brief Header file for Windows event manager.
*/
#if (!defined ACTIV_BASE_WINDOWS_EVENT_MANAGER_H)
#define ACTIV_BASE_WINDOWS_EVENT_MANAGER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/EventManagee.h"
#include "ActivMiddleware/CxxYZ/atomic.h"
#include "ActivMiddleware/CxxYZ/memory.h"
#include "ActivMiddleware/CxxYZ/vector.h"
#include "ActivMiddleware/Misc/ScopedHelper.h"
//! Activ namespace.
namespace Activ
{
class IMutex;
class TraceBufferBase;
//! Event manager class.
class EventManager
{
public:
//! Settings.
class Settings
{
public:
/**
* @brief Constructor.
*
* @param hasMutex
*/
ACTIV_BASE_API Settings(const bool hasMutex);
bool m_hasMutex; ///< Whether to create a mutex.
};
/**
* @brief Get the underlying notification handle, if available.
*
* @param handle reference to receive the handle.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_SUPPORTED the notification type for this EventManager does not support an exportable handle.
*/
ACTIV_BASE_API StatusCode GetNotificationHandle(HANDLE &handle) const;
/**
* @brief Wait for events and distribute.
*
* Should only be called from a single thread. It is safe to add/remove EventManagees from other threads,
* as long as Settings::m_hasMutex is true.
*
* @param timeoutPeriod in ms.
* @param pTraceBuffer optional trace buffer to record timestamp to.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_SHUTTING_DOWN user has requested thread exit.
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_BASE_API StatusCode Distribute(const TimeoutPeriod timeoutPeriod, TraceBufferBase *pTraceBuffer);
/**
* @brief Initiate a shutdown of the manager's thread(s).
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
ACTIV_BASE_API StatusCode Shutdown();
/**
* @brief Create an EventManager using the most suitable underlying mechanism for this platform.
*
* @param settings
*
* @return Pointer to an EventManager.
*
* @throw Exception.
*/
ACTIV_BASE_API static CxxYZ::unique_ptr<EventManager> Create(const Settings &settings);
private:
class CallbackInfo
{
public:
CallbackInfo(EventManagee * const pEventManagee, const SOCKET socket);
EventManagee * const m_pEventManagee;
const SOCKET m_socket;
};
class NotificationEventManagee ACTIV_FINAL : public EventManagee
{
public:
NotificationEventManagee(EventManager &eventManager);
protected:
virtual void OnEvents(const Events events);
};
typedef CxxYZ::shared_ptr<CallbackInfo> CallbackInfoPtr;
typedef CxxYZ::vector<CallbackInfoPtr> CallbackInfoList;
typedef CxxYZ::vector<WSAEVENT> WsaEventList;
/**
* @brief Constructor.
*
* @param settings
*/
EventManager(const Settings &settings);
/**
* @brief Add a handle to the manager.
*
* @param handle the handle to add.
* @param events the set of events to wait on, initially.
* @param pCallback callback to receive event notifications through.
* @param socket (optional) socket associated with @a handle.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode AddFd(const HANDLE handle, const EventManagee::Events events, EventManagee * const pCallback,
const SOCKET socket = INVALID_SOCKET);
/**
* @brief Remove a file description from the manager.
*
* @param handle the handle to remove.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_NOT_FOUND @a handle is not being managed.
*/
StatusCode RemoveFd(const HANDLE handle);
/**
* @brief Modify the set of events for an socket already managed.
*
* @param handle the handle to modify.
* @param events the new set of events to wait on.
* @param pCallback callback to receive event notifications through.
*
* @retval STATUS_CODE_SUCCESS
* @retval ...
*/
StatusCode ModifyEvents(const HANDLE handle, const EventManagee::Events events, EventManagee * const pCallback);
void ProcessEvent(const size_t index, CallbackInfo &callbackInfo);
void ProcessNotificationEvent();
StatusCode InternalModifyEvents(const CallbackInfo &callbackInfo, const EventManagee::Events events);
bool FindIndex(const HANDLE handle, size_t &index);
StatusCode SetNotificationEvent();
const Settings m_settings;
const CxxYZ::unique_ptr<IMutex> m_pMutex;
CxxYZ::atomic_bool m_shutdownPosted; ///< Set when user thread initiates a shutdown.
bool m_shutdownReceived;
ScopedHandle m_notificationEvent;
NotificationEventManagee m_notificationEventManagee;
CallbackInfoList m_callbackInfoList;
WsaEventList m_wsaEventList;
CxxYZ::atomic<uint32_t> m_version; ///< Incremented when the set of events managed changes.
// Used in Distribute().
CallbackInfoList m_distributeCallbackInfoList;
WsaEventList m_distributeWsaEventList;
size_t m_distributeStartIndex;
uint32_t m_distributeVersion;
friend class EventManagee;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_WINDOWS_EVENT_MANAGER_H)
@@ -1,288 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/IoCompletionManager.h
*
* @brief Header file for Windows I/O completion manager classes.
*/
#if (!defined ACTIV_BASE_WINDOWS_IO_COMPLETION_MANAGER_H)
#define ACTIV_BASE_WINDOWS_IO_COMPLETION_MANAGER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/ProcessorAffinity.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/CxxYZ/memory.h"
#include <vector>
//! Activ namespace.
namespace Activ
{
class IMutex;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief I/O completion manager class.
*/
class IoCompletionManager : private Boost::noncopyable
{
public:
typedef long EventId; ///< Type for identification of completion port based IEvent objects.
/**
* @brief Completion keys used by the ACTIV middleware.
*/
enum CompletionKey
{
COMPLETION_KEY_START = 0x7a3c6f19, ///< Arbitrary value to "avoid" clashes.
COMPLETION_KEY_DIE,
COMPLETION_KEY_EVENT,
COMPLETION_KEY_WSA_FAILURE
};
/**
* @brief Overlapped class.
*
* Extends the Windows OVERLAPPED structure and adds a virtual callback for i/o completions.
*/
class Overlapped : public OVERLAPPED
{
public:
/**
* @brief Constructor.
*
* @param ioCompletionManager reference to manager.
* @param pMutex mutex to acquire before invoking OnIoCompletion() callback, or 0 if not required.
*/
Overlapped(IoCompletionManager &ioCompletionManager, IMutex * const pMutex);
//! Destructor.
virtual ~Overlapped();
/**
* @brief Post an i/o completion to the completion port. See Windows PostQueuedCompletionStatus().
*
* Causes OnIoCompletion() to be invoked from a manager thread.
*
* @param numberOfBytes
* @param completionKey
*
* @return boolean.
*/
bool PostIoCompletion(const DWORD numberOfBytes, const CompletionKey completionKey);
/**
* @brief Check if i/o is pending for this object.
*
* @return boolean.
*/
bool IsPending() const;
/**
* @brief Set the pending status for this object.
*
* SetPending(true) after an i/o operation has successfully been initiated using this object.
*
* @param isPending
*/
void SetPending(const bool isPending);
/**
* @brief Check if i/o was successful.
*
* Should be called when processing an OnIoCompletion() callback.
*
* @return boolean.
*/
bool WasSuccessfulCompletion() const;
/**
* @brief Get number of bytes in completion.
*
* Should be called when processing an OnIoCompletion() callback.
*
* @return Number of bytes transferred in i/o operation.
*/
DWORD GetNumberOfBytes() const;
/**
* @brief Set number of bytes in completion.
*
* @param numberOfBytes
*/
void SetNumberOfBytes(const DWORD numberOfBytes);
protected:
/**
* @brief Overlapped i/o has completed.
*
* Note if a mutex was provided to the constructor of the object, it will be acquired before
* invoking this callback.
*/
virtual void OnIoCompletion() = 0;
private:
IoCompletionManager & m_ioCompletionManager; ///< Hook back to manager.
IMutex * const m_pMutex; ///< Mutex, or 0 if none.
bool m_isPending;
bool m_wasSuccessfulCompletion;
DWORD m_numberOfBytes;
friend class IoCompletionManager; ///< Allow manager access.
};
/**
* @brief Settings.
*/
class Settings
{
public:
/**
* @brief Default constructor.
*/
ACTIV_BASE_API Settings();
/**
* @brief Read settings from an ini file.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_BASE_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
UInt m_numberOfIoThreads; ///< Default undefined; let object decide.
ProcessorAffinity m_threadProcessorAffinity; ///< Default: empty; do nothing. Else a list of processor ids to use cyclicly to set launched threads' processor affinity.
HANDLE m_completionPort; ///< Default 0; create a completion port. Otherwise use the provided handle.
};
/**
* @brief Constructor.
*
* @param settings
*
* @throw Exception
*/
ACTIV_BASE_API IoCompletionManager(const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_BASE_API ~IoCompletionManager();
/**
* @brief Attach a handle to the completion port.
*
* @param handle the handle to attach.
*
* @throw OsException.
*/
ACTIV_BASE_API void AttachHandle(const HANDLE handle) const;
/**
* @brief Get the underlying completion port handle.
*
* @return Handle.
*/
ACTIV_BASE_API HANDLE GetHandle() const;
/**
* @brief Run the completion port manager.
*
* @param timeout how long to wait for a completion, or ACTIV_WAIT_INFINITE.
*
* @return true if the completion manager has been shut down.
*/
ACTIV_BASE_API const bool Run(const uint32_t timeout);
protected:
/**
* @brief Callback for an IEvent notification.
*
* @param eventId
*
* @return STATUS_CODE_EXIT to shutdown the IoCompletionManager; any other value is ignored.
*/
ACTIV_BASE_API virtual const StatusCode OnEvent(const EventId eventId);
private:
class IoThread;
//! Io worker thread entry point.
void IoThreadFunction();
typedef CxxYZ::shared_ptr<IoThread> IoThreadPtr;
typedef std::vector<IoThreadPtr> IoThreadList;
DWORD m_concurrency; ///< Number of processors in the system.
IoThreadList m_ioThreadList; ///< List of io threads.
HANDLE m_completionPort; ///< Io completion port.
};
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline IoCompletionManager::Overlapped::Overlapped(IoCompletionManager &ioCompletionManager, IMutex * const pMutex) :
m_ioCompletionManager(ioCompletionManager),
m_pMutex(pMutex),
m_isPending(false)
{
OVERLAPPED *pOverlapped = static_cast<OVERLAPPED *>(this);
::memset(pOverlapped, 0, sizeof(OVERLAPPED));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline IoCompletionManager::Overlapped::~Overlapped()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IoCompletionManager::Overlapped::PostIoCompletion(const DWORD numberOfBytes, const CompletionKey completionKey)
{
return (FALSE != ::PostQueuedCompletionStatus(m_ioCompletionManager.m_completionPort, numberOfBytes, completionKey, this));
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IoCompletionManager::Overlapped::IsPending() const
{
return m_isPending;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IoCompletionManager::Overlapped::SetPending(const bool isPending)
{
m_isPending = isPending;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline bool IoCompletionManager::Overlapped::WasSuccessfulCompletion() const
{
return m_wasSuccessfulCompletion;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline DWORD IoCompletionManager::Overlapped::GetNumberOfBytes() const
{
return m_numberOfBytes;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void IoCompletionManager::Overlapped::SetNumberOfBytes(const DWORD numberOfBytes)
{
m_numberOfBytes = numberOfBytes;
}
} // namespace Activ
#endif // (!defined ACTIV_BASE_WINDOWS_IO_COMPLETION_MANAGER_H)
@@ -1,271 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/Ip/IpManager.h
*
* @brief Header file for base ip manager class.
*/
#if (!defined ACTIV_BASE_IP_WINDOWS_IP_MANAGER_H)
#define ACTIV_BASE_IP_WINDOWS_IP_MANAGER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/ActivBase/Ip/SocketWrapper.h"
#include "ActivMiddleware/ActivBase/Windows/IoCompletionManager.h"
#include "ActivMiddleware/ActivBase/IniFileParser.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Boolean.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include "ActivMiddleware/Misc/MacAddress.h"
#include <vector>
//! Activ namespace.
namespace Activ
{
/**
* @brief Ip manager base class.
*/
class IpManager : public IoCompletionManager
{
public:
/**
* @brief Settings.
*/
class Settings : public IoCompletionManager::Settings
{
public:
/**
* @brief Default constructor.
*/
ACTIV_BASE_API Settings();
/**
* @brief Read settings from an ini file.
*
* @param sectionIterator iterator to an ini file section.
*
* @throw Exception
*/
ACTIV_BASE_API void Read(const IniFileParser::ConstSectionIterator &sectionIterator);
bool m_enableWindowsOverlappedOperations; ///< Default true.
bool m_shouldUseEpoll; ///< Ignored on Windows systems.
uint64_t m_maxIoBytes; ///< Max. bytes to read/write from one socket before checking others. Default 50000, ignored on Windows.
};
/**
* @brief Information on a network interface.
*/
class InterfaceInfo
{
public:
enum InterfaceState
{
INTERFACE_STATE_DOWN,
INTERFACE_STATE_UP
};
/**
* @brief Default constructor.
*/
ACTIV_BASE_API InterfaceInfo();
String m_name;
String m_description;
String m_driverName;
String m_driverVersion;
String m_firmwareVersion;
String m_busInfo;
UInt m_numaNode;
std::vector<uint16_t> m_localCpuList; ///< List of cpus local to the interface.
std::vector<uint16_t> m_socketLocalCpuList; ///< List of cpus in socket local to the interface (m_localCpuList may be limited to a numa node).
UInt m_numberOfRxQueues;
UInt m_numberOfTxQueues;
UInt m_numberOfCombinedQueues;
UInt m_rxRingSize;
UInt m_txRingSize;
Boolean m_useAdaptiveRxCoalescence;
UInt m_rxUsecsCoalescence;
MacAddress m_macAddress;
size_t m_bitsPerSecond; ///< 0 is unknown.
size_t m_mtu;
IpAddressMaskList m_ipAddressList;
size_t m_index; ///< Interface index of the card; 0 is unknown.
size_t m_physicalInterfaceIndex; ///< Index of the physical interface (NetLuidIndex).
UInt m_vlanId;
InterfaceState m_interfaceState; ///< The interface state.
};
typedef std::vector<InterfaceInfo> InterfaceInfoList; ///< Type of list of InterfaceInfo objects.
/**
* @brief Default constructor.
*
* @param settings reference to a Settings object.
*
* @throw Exception
*/
ACTIV_BASE_API IpManager(const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_BASE_API ~IpManager();
/**
* @brief Get reference to settings.
*
* @return Reference to settings as passed to constructor.
*/
ACTIV_BASE_API const Settings &GetSettings() const;
/**
* @brief Resolve a string into an ip address.
*
* The string can be a hostname or ip address.
*
* @param nodeName the name of the node.
* @param portNumber the port number.
* @param ipAddress reference to an IpAddress object to store the ip address.
* @param flags AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST.
* @param timeoutPeriod how long to wait for the call to complete, in ms. Will throw on timeout.
*
* @throw Exception
*/
ACTIV_BASE_API static void GetIpAddress(const String &nodeName, const uint16_t portNumber, IpAddress &ipAddress,
const int flags = 0, const TimeoutPeriod timeoutPeriod = ACTIV_WAIT_INFINITE);
/**
* @brief Get a list of local address.
*
* @param localAddress the address to resolve. If \a localAddress is empty or the hostname, all configured interfaces
* are returned.
* If \a localAddress is one of the "any" addresses (i.e. "0.0.0.0" or "::"), all configured interfaces
* for that protocol (i.e. ipv4 or ipv6) are returned.
* \a localaddress can also be one of the configured interface addresses (eg "172.16.16.2") then only that
* address will be returned.
* @param portNumber optional port to give the returned addresses. Can be 0.
* @param ipAddressList to receive the results.
* @param timeoutPeriod how long to wait for the call to complete, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_TIMEOUT
* @retval ...
*/
ACTIV_BASE_API static StatusCode GetLocalIpAddressList(const String &localAddress, const uint16_t portNumber,
IpAddressList &ipAddressList, const TimeoutPeriod timeoutPeriod = ACTIV_WAIT_INFINITE);
/**
* @brief Get a list of information for network interfaces in the machine.
*
* @param family AF_INET, AF_INET6 or AF_UNSPEC to not filter results.
* @param interfaceInfoList to receive the list of interface information.
*
* @return STATUS_CODE_SUCCESS or an error status code.
*/
ACTIV_BASE_API static StatusCode GetInterfaceInfoList(const int family, InterfaceInfoList &interfaceInfoList);
/**
* @brief Get the network information for an interface that has a specific ip address configured.
*
* @param interfaceAddress the ip address to find.
* @param interfaceInfo to receive the interface information.
*
* @retval STATUS_CODE_SUCCESS or an error status code.
*/
ACTIV_BASE_API static StatusCode GetInterfaceInfo(const IpAddress &interfaceAddress, InterfaceInfo &interfaceInfo);
/**
* @brief Get the hostname and port from a string of the form "host:port".
*
* If there is no "port" portion of the input string, portNumber is reset.
*
* @param hostAndPort a string of the form "host:port".
* @param host reference to a string to receive the host portion of the input string.
* @param portNumber reference to a variable to receive the optional port number portion of the input string.
*
* @retval true.
* @retval false hostAndPort could not be parsed.
*/
ACTIV_BASE_API static bool GetHostAndPort(const String &hostAndPort, String &host, Boost::optional<uint16_t> &portNumber);
/**
* @brief Get the hostname and port from a string of the form "host:port".
*
* If there is no "port" portion of the input string, portNumber is set to 0.
*
* @param hostAndPort a string of the form "host:port".
* @param host reference to a string to receive the host portion of the input string.
* @param portNumber reference to a variable to receive the port number portion of the input string.
*
* @retval true.
* @retval false hostAndPort could not be parsed.
*/
ACTIV_BASE_API static bool GetHostAndPort(const String &hostAndPort, String &host, uint16_t &portNumber);
/**
* @brief Resolve a string into an ip address mask.
*
* The string should be a numeric ip address mask using slash notation.
*
* @param ipAddressMaskString the string form of the ipAddress mask.
* @param ipAddressMask reference to an IpAddressMask object to store the ip address mask.
*
* @throw Exception
*/
ACTIV_BASE_API static void GetIpAddressMask(const String &ipAddressMaskString, IpAddressMask &ipAddressMask);
/**
* @brief Get the hostname.
*
* Note hostname changes will not be picked up by this function.
*
* @return The hostname.
*/
ACTIV_BASE_API static const String &GetHostName();
/**
* @brief Build a list of all the lines from all hosts files.
*
* @param result
*/
ACTIV_BASE_API static void GetHostsFileEntries(std::vector<String> &result);
/**
* @brief Get the address of a winsock extension function.
*
* @param socket the socket to find the extension function for.
* @param fnStorage pointer to place to store the function pointer.
* @param fnStorageSize the size of the function pointer storage.
* @param fnGuid pointer to the guid for the function to find.
* @param fnGuidSize size of the guid.
*
* @throw Exception
*/
ACTIV_BASE_API static void GetExtensionFunction(const SOCKET socket, void *fnStorage, const DWORD fnStorageSize, void *fnGuid,
const DWORD fnGuidSize);
/**
* @brief Create a non-inheritable socket.
*
* @param ipAddress describing type of socket to create.
* @param socketWrapper to reveive the socket.
*
* @throw Exception.
*/
ACTIV_BASE_API static void CreateNonInheritableSocket(const IpAddress &ipAddress, SocketWrapper &socketWrapper);
/**
* @brief Get the last socket error code.
*
* @return Socket error.
*/
ACTIV_BASE_API static int GetLastSocketError();
private:
const Settings m_settings; ///< Settings as passed to constructor.
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_WINDOWS_IP_MANAGER_H)
@@ -1,751 +0,0 @@
/**
* @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)
@@ -1,148 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/Ip/TcpListener.h
*
* @brief Header file for tcp listener class.
*/
#if (!defined ACTIV_BASE_IP_WINDOWS_TCP_LISTENER_H)
#define ACTIV_BASE_IP_WINDOWS_TCP_LISTENER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Ip/IpAddress.h"
#include "ActivMiddleware/ActivBase/Ip/IpManager.h"
#include "ActivMiddleware/ActivBase/Ip/SocketWrapper.h"
#include "ActivMiddleware/ActivBase/MutexHelper.h"
/**
* @brief List of states.
*/
#define ACTIV_TCP_LISTENER_STATE_LIST(d) \
d(STATE_NOT_LISTENING) \
d(STATE_LISTENING)
//! Activ namespace.
namespace Activ
{
/**
* @brief TCP listener class.
*/
class TcpListener : private Boost::noncopyable
{
public:
/**
* @brief Listening states.
*/
enum State
{
ACTIV_TCP_LISTENER_STATE_LIST(ACTIV_DECLARE_VALUE_WITH_COMMA)
NUM_STATES
};
/**
* @brief Settings.
*
* Note m_shouldAcceptConnections isn't used on Windows; it is here for source-code compatibility.
*/
class Settings
{
public:
/**
* @brief Default constructor.
*/
ACTIV_BASE_API Settings(const bool shouldAcceptConnections);
bool m_shouldAcceptConnections;
};
/**
* @brief Constructor.
*
* @param ipManager the IpManager object owning the listening socket.
* @param settings
*
* @throw Exception.
*/
ACTIV_BASE_API TcpListener(IpManager &ipManager, const Settings &settings);
/**
* @brief Destructor.
*/
ACTIV_BASE_API ~TcpListener();
/**
* @brief Start listening.
*
* @param localPort port to listen on.
* @param localAddress optional interface to bind to.
* @param backlog maximum length of the queue of pending connections.
*
* @throw Exception.
*/
ACTIV_BASE_API void Start(const uint16_t localPort, const char *localAddress = 0, const int backlog = SOMAXCONN);
/**
* @brief Start listening.
*
* @param localAddress address to listen on.
* @param backlog maximum length of the queue of pending connections.
*
* @throw Exception.
*/
ACTIV_BASE_API void Start(const IpAddress &localAddress, const int backlog = SOMAXCONN);
/**
* @brief Stop listening.
*
* @return Always returns true.
*
* @throw Exception.
*/
ACTIV_BASE_API bool Stop();
/**
* @brief Get the underlying socket handle.
*
* @return Socket handle.
*/
ACTIV_BASE_API SOCKET GetHandle() const;
/**
* @brief Get the local address of the listening 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 listener state.
*
* @return The current state.
*/
ACTIV_BASE_API State GetState() const;
/**
* @brief Return state in string form.
*
* @return State in string form.
*/
ACTIV_BASE_API static String StateToString(const State state);
protected:
//! A previous Stop() has completed and the lsock is closed. Never called; for compatibility with Posix version.
ACTIV_BASE_API virtual void OnStop();
private:
IpManager & m_ipManager; ///< this object is managed by an IpManager
IMutex * const m_pMutex; ///< mutex
State m_state; ///< state of the listening socket
SocketWrapper m_socket; ///< the underlying listening socket
IpAddress m_localAddress; ///< local bind address
friend class TcpSocket;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_WINDOWS_TCP_LISTENER_H)
@@ -1,480 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/Ip/TcpSocket.h
*
* @brief Header file for tcp socket class.
*/
#if (!defined ACTIV_BASE_IP_WINDOWS_TCP_SOCKET_H)
#define ACTIV_BASE_IP_WINDOWS_TCP_SOCKET_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Ip/IpSocket.h"
#include "ActivMiddleware/ActivBase/FieldTypes/Boolean.h"
#include "ActivMiddleware/ActivBase/FieldTypes/UInt.h"
#include <mswsock.h>
/**
* @brief List of tcp socket states.
*/
#define ACTIV_TCP_SOCKET_STATE_LIST(d) \
d(STATE_INITIALIZED) \
d(STATE_W4_CONNECT) \
d(STATE_W4_ACCEPT) \
d(STATE_CONNECTED) \
d(STATE_W4_DISCONNECT)
//! Activ namespace.
namespace Activ
{
class TcpListener;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief TCP socket class.
*/
class TcpSocket : public IpSocket
{
public:
/**
* @brief Connection states.
*/
enum State
{
ACTIV_TCP_SOCKET_STATE_LIST(ACTIV_DECLARE_VALUE_WITH_COMMA)
NUM_STATES
};
/**
* @brief Settings.
*/
class Settings : public IpSocket::Settings
{
public:
/**
* @brief Constructor.
*
* @param shouldCork set TCP_CORK, if available, whilst in tx loop.
*/
ACTIV_BASE_API Settings(const bool shouldCork = false);
};
/**
* @brief Stats.
*/
class Stats : public IpSocket::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 TcpSocket &socket);
State m_state; ///< Connection state.
bool m_connectPosted; ///< Connect posted.
bool m_acceptPosted; ///< Accept posted.
UInt m_txCompressionPercent; ///< If compressing, compression ratio as % (compressed-bytes / source-bytes).
// OS-level stats; may not be defined.
UInt m_txRtt;
UInt m_txCongestionWindowSize;
UInt m_totalRetransmissions;
UInt m_reorders;
Boolean m_isNagleEnabled;
};
/**
* @brief Constructor.
*
* @param ipManager the IpManager that owns the socket.
* @param settings settings for this socket.
*
* @throw Exception.
*/
ACTIV_BASE_API TcpSocket(IpManager &ipManager, const Settings &settings = Settings());
/**
* @brief Destructor.
*/
ACTIV_BASE_API ~TcpSocket();
/**
* @brief Initiate connection.
*
* @param remoteAddress the remote address to connect to.
* @param remotePort the remote port to connect to (local endian).
* @param localAddress the optional local address to bind to.
* @param localPort the optional local port number to bind to (local endian).
*
* @throw Exception.
*/
ACTIV_BASE_API void Connect(const char *remoteAddress, const uint16_t remotePort, const char *localAddress = 0,
const uint16_t localPort = 0);
/**
* @brief Initiate connection.
*
* @param remoteAddress the remote address to connect to.
* @param localAddress the local address to bind to.
*
* @throw Exception.
*/
ACTIV_BASE_API void Connect(const IpAddress &remoteAddress, const IpAddress &localAddress);
/**
* @brief Initiate connection.
*
* As Connect(), but do not obtain the socket mutex first (assumes the mutex is already locked).
*
* @param remoteAddress the remote address to connect to.
* @param localAddress the local address to bind to.
*
* @throw Exception.
*/
ACTIV_BASE_API void PreLockedConnect(const IpAddress &remoteAddress, const IpAddress &localAddress);
/**
* @brief Set up the local and remote addresses but do not initiate a connection.
*
* NB mutex must already be locked.
*
* @param remoteAddress the remote address to connect to.
* @param localAddress the local address to bind to.
*
* @throw Exception if the socket wasn't in STATE_INITIALIZED.
*/
ACTIV_BASE_API void PreLockedSetAddresses(const IpAddress &remoteAddress, const IpAddress &localAddress);
/**
* @brief Post a connect to an already set up address.
*
* NB mutex must already be locked.
*
* @throw Exception.
*/
ACTIV_BASE_API void PreLockedPostConnect();
/**
* @brief Post a connect to an already set up address.
*
* @throw Exception.
*/
ACTIV_BASE_API void PostConnect();
/**
* @brief Post an accept.
*
* @param listener the server to accept from.
*
* @throw Exception.
*/
ACTIV_BASE_API void Accept(TcpListener &listener);
/**
* @brief Close a connection.
*
* @param gracefully true to only close the socket once any outstanding tx has completed,
* false to force the socket closed immediately.
*
* @retval true the socket is fully closed.
* @retval false a close event will be fired when the socket is fully closed (OnDisconnect()).
*
* @throw Exception.
*/
ACTIV_BASE_API bool Disconnect(const bool gracefully = false);
/**
* @brief Forcably initiate a connection break. If the socket was connected, OnBreak() will be fired.
*
* Note this function will obtain the socket mutex for the duration of the call.
*/
ACTIV_BASE_API void LockedBreak();
/**
* @brief Forcably initiate a connection break. If the socket was connected, OnBreak() will be fired.
*
* As LockedBreak(), but do not obtain the socket mutex first (assumes the mutex is already locked).
*/
ACTIV_BASE_API void PreLockedBreak();
/**
* @brief Get the socket's state.
*
* @return Socket state.
*/
State GetState() const;
/**
* @brief Return state as string.
*
* @return Socket state in string form.
*/
ACTIV_BASE_API static String StateToString(const State state);
/**
* @brief Enable or disable clean shutdown of a connected socket.
*
* After a connection is established (OnConnect(), or OnAccept()), a socket will normally attempt to
* cleanly shutdown when Disconnect() is called (rather than close abortively), sending a FIN packet.
*
* However, this can cause very long delays in closing sockets with some configurations (e.g. connections to a proxy
* which is receiving an infinite HTTP response).
*
* Disabling shutdown will cause an abortive close (TCP RST) to be done instead.
*
* Note the clean shutdown is re-enabled after a reconnect.
*
* This function should only be called inside a callback or when the socket mutex is locked.
*
* @param isEnabled whether to enable or disable clean shutdown.
*/
void PreLockedEnableShutdown(const bool isEnabled);
protected:
// IpSocket overrides.
ACTIV_BASE_API virtual bool OnInitializeIo() ACTIV_OVERRIDE;
ACTIV_BASE_API virtual CompletionResult OnRxBuffers() ACTIV_OVERRIDE;
ACTIV_BASE_API virtual CompletionResult OnDummyRxCompletion(const size_t numberOfBytes) const ACTIV_OVERRIDE;
ACTIV_BASE_API virtual CompletionResult OnTxBuffers() ACTIV_OVERRIDE;
/**
* @brief Connection has closed at the user's request.
*/
ACTIV_BASE_API virtual void OnDisconnect();
/**
* @brief Connection has broken (the user didn't initiate).
*/
ACTIV_BASE_API virtual void OnBreak();
/**
* @brief Connect has been initiated asynchronously.
*
* @throw If an exception propagates outside of an overridden OnConnectPosted(), the connection attempt is aborted and will
* result in an OnConnectFailed() callback.
*/
ACTIV_BASE_API virtual void OnConnectPosted();
/**
* @brief Connect has succeeded.
*/
ACTIV_BASE_API virtual void OnConnect();
/**
* @brief Connect has been aborted (with a Disconnect()) before it completed either successfully or unsuccessfully.
*/
ACTIV_BASE_API virtual void OnConnectAborted();
/**
* @brief Connect has failed.
*
* @param errorCode Win32 error code.
*/
ACTIV_BASE_API virtual void OnConnectFailed(const uint32_t errorCode);
/**
* @brief Accept has succeeded.
*/
ACTIV_BASE_API virtual void OnAccept();
/**
* @brief Accept has been aborted. Calling Disconnect() before an accept has completed will cause this event.
*/
ACTIV_BASE_API virtual void OnAcceptAborted();
/**
* @brief Accept has failed. Stopping the listener will cause this event on an accepting connection.
*
* @param errorCode Win32 error code.
*/
ACTIV_BASE_API virtual void OnAcceptFailed(const uint32_t errorCode);
State m_state; ///< The state of the connection.
private:
/**
* @brief Set up a client side socket.
*
* @throw Exception.
*/
void CreateClientSocket();
/**
* @brief Set up an accepting socket.
*
* @throw Exception.
*/
void CreateAcceptSocket();
/**
* @brief Complete set up of an accepting socket.
*
* @throw Exception.
*/
void CompleteCreateAcceptSocket();
/**
* @brief Do final cleanup on the connection, including firing disconnection events.
*/
void Cleanup();
// IpSocket overrides.
ACTIV_BASE_API virtual void HandleIoFailure(const bool gracefully) ACTIV_OVERRIDE;
/**
* @brief Process connect completion.
*/
void ProcessConnectCompletion();
/**
* @brief Process successful connect completion.
*/
void ProcessSuccessfulConnectCompletion();
/**
* @brief Process accept completion.
*/
void ProcessAcceptCompletion();
/**
* @brief Process successful accept completion.
*/
void ProcessSuccessfulAcceptCompletion();
/**
* @brief Is an overlapped read successful?
*
* @param overlapped
*
* @return false if the socket should be closed.
*/
bool IsSuccessfulRxCompletion(const IoCompletionManager::Overlapped &overlapped) const;
/**
* @brief Sync bsd thread info.
*/
class BsdThreadInfo
{
public:
/**
* @brief Constructor.
*
* @param tcpSocket TcpSocket object initiating the operation.
* @param socket socket to operate on.
*/
BsdThreadInfo(TcpSocket &tcpSocket, const SOCKET socket);
TcpSocket & m_tcpSocket;
SOCKET m_socket;
};
/**
* @brief Sync bsd thread connect info.
*/
class ConnectThreadInfo : public BsdThreadInfo
{
public:
/**
* @brief Constructor.
*
* @param tcpSocket TcpSocket object initiating the connect.
* @param socket socket to connect on.
* @param remoteAddress address to connect to.
*/
ConnectThreadInfo(TcpSocket &tcpSocket, const SOCKET socket, const IpAddress &remoteAddress);
IpAddress m_remoteAddress;
};
/**
* @brief Initiate a bsd sync connect.
*
* @param pConnectThreadInfo info for the connect.
*/
void BsdConnect(ConnectThreadInfo * const pConnectThreadInfo);
/**
* @brief Thread function to invoke bsd connect.
*/
static unsigned WINAPI BsdConnectThread(void *p);
/**
* @brief Initiate a bsd sync accept.
*
* @param pBsdThreadInfo info for the accept.
*/
void BsdAccept(BsdThreadInfo * const pBsdThreadInfo);
/**
* @brief Thread function to invoke bsd accept.
*/
static unsigned WINAPI BsdAcceptThread(void *p);
/**
* @brief Overlapped class for connects.
*/
class ConnectOverlapped : public IoCompletionManager::Overlapped
{
public:
/**
* @brief Constructor.
*
* @param tcpSocket TcpSocket containing this object.
*/
ConnectOverlapped(TcpSocket &tcpSocket);
private:
virtual void OnIoCompletion() ACTIV_OVERRIDE;
TcpSocket &m_tcpSocket;
};
/**
* @brief Overlapped class for accepts.
*/
class AcceptOverlapped : public IoCompletionManager::Overlapped
{
public:
/**
* @brief Constructor.
*
* @param tcpSocket TcpSocket containing this object.
*/
AcceptOverlapped(TcpSocket &tcpSocket);
private:
virtual void OnIoCompletion() ACTIV_OVERRIDE;
TcpSocket &m_tcpSocket;
};
bool m_isShutdownEnabled;
// Client side members.
ConnectOverlapped m_connectOverlapped; ///< Overlapped info for async connect.
LPFN_CONNECTEX m_pConnectEx; ///< Pointer to ConnectEx() function.
IpAddress m_providedLocalAddress; ///< Provided local address.
// Server side members.
static const size_t PADDED_ADDRESS_SIZE = sizeof(SOCKADDR_IN6) + 16;
static const size_t ACCEPT_BUFFER_SIZE = 2 * PADDED_ADDRESS_SIZE;
AcceptOverlapped m_acceptOverlapped; ///< Overlapped info for async accept.
SOCKET m_listeningSocket; ///< The server socket that will accept.
byte_t m_acceptBuffer[ACCEPT_BUFFER_SIZE]; ///< Buffer for addresses.
LPFN_ACCEPTEX m_pAcceptEx; ///< Pointer to AcceptEx() function.
LPFN_GETACCEPTEXSOCKADDRS m_pGetAcceptExSockAddrs; ///< Pointer to GetAcceptExSockAddrs() function.
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_WINDOWS_TCP_SOCKET_H)
@@ -1,292 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/Ip/UdpSocket.h
*
* @brief Header file for udp socket class.
*/
#if (!defined ACTIV_BASE_IP_WINDOWS_UDP_SOCKET_H)
#define ACTIV_BASE_IP_WINDOWS_UDP_SOCKET_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/Ip/IpSocket.h"
/**
* @brief States.
*/
#define ACTIV_UDP_SOCKET_STATE_LIST(d) \
d(STATE_INITIALIZED) \
d(STATE_CREATED) \
d(STATE_CONNECTED) \
d(STATE_W4_CLOSE)
//! Activ namespace.
namespace Activ
{
/**
* @brief UDP socket class.
*/
class UdpSocket : public IpSocket
{
public:
/**
* @brief States.
*/
enum State
{
ACTIV_UDP_SOCKET_STATE_LIST(ACTIV_DECLARE_VALUE_WITH_COMMA)
NUM_STATES
};
/**
* @brief Settings.
*/
class Settings : public IpSocket::Settings
{
public:
/**
* @brief Constructor.
*
* @param shouldCork set TCP_CORK, if available, whilst in tx loop.
*/
ACTIV_BASE_API Settings(const bool shouldCork = false);
};
/**
* @brief Stats.
*/
class Stats : public IpSocket::Stats
{
public:
/**
* @brief Constructor.
*
* Note if constructing a Stats object directly, you 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 UdpSocket &socket);
State m_state; ///< Udp socket state.
};
/**
* @brief Constructor.
*
* @param ipManager the IpManager that owns the socket.
* @param settings settings for this socket.
*
* @throw Exception.
*/
ACTIV_BASE_API UdpSocket(IpManager &ipManager, const Settings &settings = Settings());
/**
* @brief Destructor.
*
* Note a socket is only closed in the destructor.
*/
ACTIV_BASE_API ~UdpSocket();
/**
* @brief Create and bind a socket.
*
* @param localAddressString the local address to bind to in string form.
* @param localPort the local port number to bind to (local endian).
*
* @throw Exception.
*/
ACTIV_BASE_API void Initialize(const String &localAddressString, const uint16_t localPort);
/**
* @brief Create and bind a socket.
*
* @param localAddress the local address to bind to.
*
* @throw Exception.
*/
ACTIV_BASE_API void Initialize(const IpAddress &localAddress);
/**
* @brief Connect to a remote address (filter all traffic from other addresses).
*
* @param remoteAddressString the remote address to connect to in string form.
* @param remotePort the remote port to connect to (local endian).
*
* @throw Exception.
*/
ACTIV_BASE_API void Connect(const String &remoteAddressString, const uint16_t remotePort);
/**
* @brief Connect to a remote address (filter all traffic from other addresses).
*
* @param remoteAddress the remote address to connect to.
*
* @throw Exception.
*/
ACTIV_BASE_API void Connect(const IpAddress &remoteAddress);
/**
* @brief Disconnect from a remote address (allow all traffic).
*
* @throw Exception.
*/
ACTIV_BASE_API void Disconnect();
/**
* @brief Shutdown the socket.
*
* @param gracefully true to only close the socket once any outstanding tx has completed,
* false to force the socket closed immediately.
*
* @retval true the socket is fully closed.
* @retval false a close event will be fired when the socket is fully closed (OnShutdown()).
*/
ACTIV_BASE_API bool Shutdown(const bool gracefully = false);
/**
* @brief Initiate an abortive close on the socket.
*
* This will result in an OnError() if the socket
* was open and not shutting down "cleanly" as the result of a Shutdown() call.
*/
ACTIV_BASE_API void AbortiveClose();
/**
* @brief Join a multicast group.
*
* @param multicastGroupString an ipv4 or ipv6 multicast address string.
* @param interfaceAddressString an ipv4 or ipv6 interface address string.
* @param sourceAddressString an ipv4 or ipv6 source address string. If non-empty, a source specific multicast join is
* attempted.
*
* @throw Exception.
*/
ACTIV_BASE_API void JoinMulticastGroup(const String &multicastGroupString, const String &interfaceAddressString,
const String &sourceAddressString = String(""));
/**
* @brief Leave a multicast group.
*
* @param multicastGroupString an ipv4 or ipv6 multicast address string.
* @param interfaceAddressString an ipv4 or ipv6 interface address string.
* @param sourceAddressString an ipv4 or ipv6 source address string. If non-empty, a source specific multicast leave is
* attempted.
*
* @throw Exception.
*/
ACTIV_BASE_API void LeaveMulticastGroup(const String &multicastGroupString, const String &interfaceAddressString,
const String &sourceAddressString = String(""));
/**
* @brief Set multicast interface for transmission.
*
* @param interfaceAddressString an ipv4 or ipv6 address string.
*
* @throw Exception.
*/
ACTIV_BASE_API void SetMulticastTxInterface(const String &interfaceAddressString);
/**
* @brief Set TTL to be used for multicasting.
*
* @param ttl the TTL.
*
* @throw Exception.
*/
ACTIV_BASE_API void SetMulticastTtl(const int ttl);
/**
* @brief Set TTL to be used for unicasting.
*
* @param ttl the TTL.
*
* @throw Exception.
*/
ACTIV_BASE_API void SetUnicastTtl(const int ttl);
/**
* @brief Set multicast loopback.
*
* @param isEnabled true to enable, false to disable.
*
* @throw Exception.
*/
ACTIV_BASE_API void SetMulticastLoopback(const bool isEnabled);
/**
* @brief Return state as string.
*
* @return Socket state in string form.
*/
ACTIV_BASE_API static String StateToString(const State state);
protected:
// IpSocket overrides
ACTIV_BASE_API virtual CompletionResult OnRxBuffers() ACTIV_OVERRIDE;
ACTIV_BASE_API virtual CompletionResult OnTxBuffers() ACTIV_OVERRIDE;
/**
* @brief Socket has closed due to an error.
*/
ACTIV_BASE_API virtual void OnError();
/**
* @brief Socket has closed after a Shutdown() call.
*/
ACTIV_BASE_API virtual void OnShutdown();
State m_state; ///< The state of the socket.
private:
/**
* @brief Set up a socket.
*
* @throw Exception.
*/
void CreateSocket();
/**
* @brief Do final cleanup on the connection, including firing disconnection events.
*/
void Cleanup();
ACTIV_BASE_API virtual void HandleIoFailure(const bool gracefully) ACTIV_OVERRIDE;
/**
* @brief Join or leave an ipv4 or ipv6 multicast group.
*
* @param multicastGroupString an ipv4 or ipv6 multicast address string.
* @param interfaceAddressString an ipv4 or ipv6 interface address string.
* @param sourceAddressString an ipv4 or ipv6 source address string. If non-empty, a source specific multicast join/leave
* is attempted.
* @param isJoin true to join the group, false to leave.
*
* @throw Exception.
*/
void MulticastGroupAction(const String &multicastGroupString, const String &interfaceAddressString,
const String &sourceAddressString, const bool isJoin);
/**
* @brief Set the multicast tx interface for an ipv4 address.
*
* @param interfaceAddress the local interface address.
*
* @throw Exception.
*/
void SetIpv4MulticastTxInterface(const IpAddress &interfaceAddress);
/**
* @brief Set the multicast tx interface for an ipv6 address.
*
* @param interfaceAddress the local interface address.
*
* @throw Exception.
*/
void SetIpv6MulticastTxInterface(const IpAddress &interfaceAddress);
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_IP_WINDOWS_UDP_SOCKET_H)
@@ -1,306 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/Ip/WsaBufHelper.h
*
* @brief Header file for WSABUF helper classes.
*/
#if (!defined ACTIV_BASE_WINDOWS_IP_WSA_BUF_HELPER_H)
#define ACTIV_BASE_WINDOWS_IP_WSA_BUF_HELPER_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/CrtException.h"
#include "ActivMiddleware/CxxYZ/vector.h"
#include <cassert>
//! Activ namespace.
namespace Activ
{
/**
* @brief WSABUF helper class.
*/
class WsaBuf : public WSABUF
{
public:
//! Get the buffer pointer.
void *GetData();
//! Get the buffer pointer.
const void *GetData() const;
//! Get the buffer length.
size_t GetLength() const;
// Don't add member variables or virtuals!
};
ACTIV_BOOST_STATIC_ASSERT(sizeof(WsaBuf) == sizeof(WSABUF));
// ---------------------------------------------------------------------------------------------------------------------------------
inline void *WsaBuf::GetData()
{
return reinterpret_cast<void *>(buf);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const void *WsaBuf::GetData() const
{
return reinterpret_cast<const void *>(buf);
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t WsaBuf::GetLength() const
{
return static_cast<size_t>(len);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief WSABUF array helper class.
*/
class WsaBufHelper
{
private:
typedef CxxYZ::vector<WsaBuf> WsaBufArray;
public:
typedef WsaBufArray::iterator iterator; ///< Iterator to buffers.
typedef WsaBufArray::const_iterator const_iterator; ///< Iterator to buffers.
/**
* @brief Constructor.
*
* @param initialSize the number of WSABUFs to allocate initially.
*
* @throw Exception.
*/
WsaBufHelper(const size_t initialSize = 10);
/**
* @brief Move constructor.
*
* @param rhs
*/
WsaBufHelper(ACTIV_BOOST_RV_REF(WsaBufHelper) rhs) :
m_initialSize(rhs.m_initialSize),
m_wsaBufArray(CxxYZ::move(rhs.m_wsaBufArray)),
m_numberOfBuffersAvailable(rhs.m_numberOfBuffersAvailable),
m_totalBytesAvailable(rhs.m_totalBytesAvailable),
m_totalBytesInUse(rhs.m_totalBytesInUse)
{
rhs.Reset();
}
//! Destructor.
~WsaBufHelper();
/**
* @brief Move assignment operator.
*
* @param rhs
*
* @return *this
*/
WsaBufHelper &operator=(ACTIV_BOOST_RV_REF(WsaBufHelper) rhs)
{
m_wsaBufArray = CxxYZ::move(rhs.m_wsaBufArray);
m_numberOfBuffersAvailable = rhs.m_numberOfBuffersAvailable;
m_totalBytesAvailable = rhs.m_totalBytesAvailable;
m_totalBytesInUse = rhs.m_totalBytesInUse;
rhs.Reset();
return *this;
}
//! Reset the number of buffers in use.
void Reset();
/**
* @brief Append a new buffer, expand the WSABUF array if required.
*
* @brief pData pointer to the data.
* @brief dataLength the length of the buffer.
*
* @throw Exception if the WSABUF couldn't be resized.
*/
void Append(const void * const pData, const size_t dataLength);
//! Get a pointer to the first WSABUF.
WsaBuf *GetFirstBuffer();
//! Get a const pointer to the first WSABUF.
const WsaBuf *GetFirstBuffer() const;
/**
* @brief Get the number of buffers available (the number of Append()s since the last Reset()).
*
* @return The number of buffers available.
*/
size_t GetNumberOfBuffersAvailable() const;
//! Get the total number of bytes in the WSABUF arary.
size_t GetTotalBytesAvailable() const;
//! Get the total number of bytes in use.
size_t GetTotalBytesInUse() const;
//! Set the total number of bytes in use.
void SetTotalBytesInUse(const size_t totalBytesInUse);
//! Get iterator to first buffer.
iterator begin();
//! Get iterator to past the last buffer.
iterator end();
//! Get const_iterator to first buffer.
const_iterator begin() const;
//! Get const_iterator to past the last buffer.
const_iterator end() const;
private:
ACTIV_BOOST_MOVABLE_BUT_NOT_COPYABLE(WsaBufHelper)
/**
* @brief Extend the WSABUF array.
*
* @throw Exception if the WSABUF couldn't be resized.
*/
ACTIV_BASE_API void Extend();
const size_t m_initialSize; ///< Initial size of the WSABUF array.
WsaBufArray m_wsaBufArray; ///< WSABUF array.
size_t m_numberOfBuffersAvailable; ///< Number of buffers in m_wsaBufArray currently available.
size_t m_totalBytesAvailable; ///< Total number of bytes in WSABUF array.
size_t m_totalBytesInUse; ///< Number of bytes out of m_totalBytes that are in use (e.g. after a receive).
};
// ---------------------------------------------------------------------------------------------------------------------------------
inline WsaBufHelper::WsaBufHelper(const size_t initialSize) :
m_initialSize(initialSize),
m_wsaBufArray(initialSize)
{
assert(0 != initialSize);
Reset();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline WsaBufHelper::~WsaBufHelper()
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void WsaBufHelper::Reset()
{
m_numberOfBuffersAvailable = 0;
m_totalBytesAvailable = 0;
m_totalBytesInUse = 0;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void WsaBufHelper::Append(const void * const pData, const size_t dataLength)
{
// Do we need to extend the WSABUF array?
if (m_numberOfBuffersAvailable == m_wsaBufArray.size())
Extend();
m_wsaBufArray[m_numberOfBuffersAvailable].buf = reinterpret_cast<char *>(const_cast<void *>(pData));
m_wsaBufArray[m_numberOfBuffersAvailable].len = static_cast<DWORD>(dataLength);
m_totalBytesAvailable += dataLength;
++m_numberOfBuffersAvailable;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline WsaBuf *WsaBufHelper::GetFirstBuffer()
{
return &m_wsaBufArray[0];
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline const WsaBuf *WsaBufHelper::GetFirstBuffer() const
{
return &m_wsaBufArray[0];
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t WsaBufHelper::GetNumberOfBuffersAvailable() const
{
return m_numberOfBuffersAvailable;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t WsaBufHelper::GetTotalBytesAvailable() const
{
return m_totalBytesAvailable;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline size_t WsaBufHelper::GetTotalBytesInUse() const
{
return m_totalBytesInUse;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline void WsaBufHelper::SetTotalBytesInUse(const size_t totalBytesInUse)
{
m_totalBytesInUse = totalBytesInUse;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline WsaBufHelper::iterator WsaBufHelper::begin()
{
return m_wsaBufArray.begin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline WsaBufHelper::iterator WsaBufHelper::end()
{
return m_wsaBufArray.begin() + m_numberOfBuffersAvailable;
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline WsaBufHelper::const_iterator WsaBufHelper::begin() const
{
return m_wsaBufArray.begin();
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline WsaBufHelper::const_iterator WsaBufHelper::end() const
{
return m_wsaBufArray.begin() + m_numberOfBuffersAvailable;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
typedef WsaBuf IpBuffer;
typedef WsaBufHelper IpBufferHelper; ///< Common name for vectored/scatter-gather i/o buffer helper.
} // namespace Activ
#endif // (!defined ACTIV_BASE_WINDOWS_IP_WSA_BUF_HELPER_H)
@@ -1,56 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/PrivateCompletionPortEventFactory.h
*
* @brief Header file for the private completion-port event factory class.
*/
#if (!defined ACTIV_BASE_PRIVATE_COMPLETION_PORT_EVENT_FACTORY_H)
#define ACTIV_BASE_PRIVATE_COMPLETION_PORT_EVENT_FACTORY_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/IEvent.h"
#include "ActivMiddleware/Misc/Singleton.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Private completion-port event factory class.
*
* A private event cannot be shared across process boundaries.
*/
class PrivateCompletionPortEventFactory : public Singleton<PrivateCompletionPortEventFactory>
{
public:
/**
* @brief Create an event.
*
* @param completionPortHandle completion port to use.
* @param flags creation flags.
* @param initialState whether the event is initially set upon creation.
*
* @return pointer to an object providing an IEvent interface.
*/
ACTIV_BASE_API IEvent *Create(const HANDLE completionPortHandle, const IEvent::Flags::Type flags = IEvent::Flags::None(),
const bool initialState = false);
/**
* @brief Get a reference to the singleton instance.
*
* @return Reference.
*/
ACTIV_BASE_API static PrivateCompletionPortEventFactory &GetInstance();
private:
/**
* @brief Default constructor.
*/
ACTIV_BASE_API PrivateCompletionPortEventFactory();
friend class Singleton<PrivateCompletionPortEventFactory>;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_PRIVATE_COMPLETION_PORT_EVENT_FACTORY_H)
@@ -1,183 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/RegistryHelper.h
*
* @brief Header file for the registry helper class.
*/
#if (!defined ACTIV_BASE_WINDOWS_REGISTRY_HELPER_H)
#define ACTIV_BASE_WINDOWS_REGISTRY_HELPER_H
#include "ActivMiddleware/ActivBase/External.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Registry helper class.
*
* RegistryHelper wraps up methods for getting, setting and deleting registry values,
* deleting registry keys and enumerating keys and values.
*/
class RegistryHelper
{
public:
/**
* @brief Enumeration of basic types supported by RegistryHelper.
*/
enum Type
{
TYPE_UNSUPPORTED, ///< Unsupported type.
TYPE_UNSIGNED32, ///< Unsigned 32 bit type.
TYPE_STRING, ///< 0 terminated string type.
TYPE_BINARY ///< Variable length binary type.
};
/**
* @brief Destructor.
*/
ACTIV_BASE_API virtual ~RegistryHelper();
/**
* @brief Get an UNSIGNED32 value.
*
* @param keyName the full name of the key holding the value to retrieve.
* @param valueName the name of the value within key \a keyName to retrieve.
* @param value on success, the retrieved value is stored in \a value.
*
* @throw OsException
* @throw BaseException
*/
ACTIV_BASE_API static void GetValue(const char *keyName, const char *valueName, uint32_t &value);
/**
* @brief Get a STRING value.
*
* @param keyName the full name of the key holding the value to retrieve.
* @param valueName the name of the value within key \a keyName to retrieve.
* @param value to receive the string.
*
* @throw OsException
* @throw BaseException
*/
ACTIV_BASE_API static void GetValue(const char *keyName, const char *valueName, String &value);
/**
* @brief Get a BINARY value.
*
* @param keyName the full name of the key holding the value to retrieve.
* @param valueName the name of the value within key \a keyName to retrieve.
* @param value on success, the retrieved buffer is stored in \a value.
* @param maxValueLen the size of the buffer pointed to by \a value.
* On success, maxValueLen will contain the length of the retrieved buffer.
*
* @throw OsException
* @throw BaseException
*/
ACTIV_BASE_API static void GetValue(const char *keyName, const char *valueName, void *value,
uint32_t &maxValueLen);
/**
* @brief Set an UNSIGNED32 value.
*
* @param keyName the full name of the key in which to set the value.
* @param valueName the name of the value within key \a keyName to set.
* @param value the UNSIGNED32 value to set.
*
* @throw OsException
*/
ACTIV_BASE_API static void SetValue(const char *keyName, const char *valueName, const uint32_t value);
/**
* @brief Set a STRING value.
*
* @param keyName the full name of the key in which to set the value.
* @param valueName the name of the value within key \a keyName to set.
* @param value the string to set the value to.
*
* @throw OsException
*/
ACTIV_BASE_API static void SetValue(const char *keyName, const char *valueName, const String &value);
/**
* @brief Set a BINARY value.
*
* @param keyName the full name of the key in which to set the value.
* @param valueName the name of the value within key \a keyName to set.
* @param value pointer to the buffer to store.
* @param valueLen the length of the buffer pointer to by \a value.
*
* @throw OsException
*/
ACTIV_BASE_API static void SetValue(const char *keyName, const char *valueName, const void *value,
const uint32_t valueLen);
/**
* @brief Delete a key and all sub keys.
*
* @param keyName the full name of the key to delete.
*
* @throw OsException
*/
ACTIV_BASE_API static void DeleteKey(const char *keyName);
/**
* @brief Delete a value from a key.
*
* @param keyName the full name of the key containing the value to delete.
* @param valueName the name of the value to delete.
*
* @throw OsException
*/
ACTIV_BASE_API static void DeleteValue(const char *keyName, const char *valueName);
/**
* @brief Enumerate all sub keys of a given key.
*
* The OnKey() callback will be invoked for all sub keys of the given key.
*
* @param keyName the full name of the root key to enumerate from.
*
* @return the number of keys enumerated.
*/
ACTIV_BASE_API size_t EnumerateKeys(const char *keyName);
/**
* @brief Enumerate all values of a given key.
*
* The OnValue() callback will be invoked for all values within the given key.
*
* @param keyName the full name of the key to enumerate values from.
*
* @return the number of values enumerated.
*/
ACTIV_BASE_API size_t EnumerateValues(const char *keyName);
protected:
/**
* @brief The callback invoked by EnumerateKeys().
*
* @param fullKeyName the full key name, including all parent keys.
* @param keyName the key name only.
* @param index the index of the key within it's parent key, 0 based.
*
* @return false to stop enumerating more keys, true to continue.
*/
ACTIV_BASE_API virtual bool OnKey(const char *fullKeyName, const char *keyName, uint_fast32_t index);
/**
* @brief The callback invoked by EnumerateValues().
*
* @param fullKeyName the full key name, including all parent keys.
* @param valueName the name of the enumerated value within \a fullKeyName.
* @param index the index of the value within it's key, 0 based.
* @param type the type of the value.
*
* @return false to stop enumerating more values, true to continue.
*/
ACTIV_BASE_API virtual bool OnValue(const char *fullKeyName, const char *valueName, uint_fast32_t index, Type type);
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_WINDOWS_REGISTRY_HELPER_H)
@@ -1,70 +0,0 @@
/**
* @file include/ActivMiddleware/ActivBase/Windows/SharedCompletionPortEventFactory.h
*
* @brief Header file for the shared socket based event factory class.
*/
#if (!defined ACTIV_BASE_WINDOWS_SHARED_COMPLETION_PORT_EVENT_FACTORY_H)
#define ACTIV_BASE_WINDOWS_SHARED_COMPLETION_PORT_EVENT_FACTORY_H
#include "ActivMiddleware/ActivBase/External.h"
#include "ActivMiddleware/ActivBase/IEvent.h"
#include "ActivMiddleware/ActivBase/Timeout.h"
#include "ActivMiddleware/Misc/Singleton.h"
//! Activ namespace.
namespace Activ
{
/**
* @brief Shared completion-port based event factory class.
*/
class SharedCompletionPortEventFactory : public Singleton<SharedCompletionPortEventFactory>
{
public:
/**
* @brief Create an event.
*
* @param completionPortHandle completion port to use.
* @param name the event name.
* @param flags creation flags.
* @param initialState whether the event is initially set upon creation.
*
* @return pointer to an object providing an IEvent interface.
*
* @throw Exception
*/
ACTIV_BASE_API IEvent *Create(const HANDLE completionPortHandle, const String &name,
const IEvent::Flags::Type flags = IEvent::Flags::None(), const bool initialState = false);
/**
* @brief Open an existing event.
*
* @param name the event name.
* @param timeout how long to wait for the object to exist, in ms.
*
* @return pointer to an object providing an IEvent interface.
*
* @throw Exception
*/
ACTIV_BASE_API IEvent *Open(const String &name, Timeout &timeout = Timeout::GetInfinite());
/**
* @brief Get a reference to the singleton instance.
*
* @return Reference.
*/
ACTIV_BASE_API static SharedCompletionPortEventFactory &GetInstance();
private:
/**
* @brief Default constructor.
*/
ACTIV_BASE_API SharedCompletionPortEventFactory();
friend class Singleton<SharedCompletionPortEventFactory>;
};
} // namespace Activ
#endif // (!defined ACTIV_BASE_WINDOWS_SHARED_COMPLETION_PORT_EVENT_FACTORY_H)