55#if !defined(_NETWORKMANAGER_H_)
56#define _NETWORKMANAGER_H_
172 static bool UnitTestHTTPS();
174 static bool UnitTestSSLVerify();
176 static bool UnitTestSSLHostCA();
181 static bool TestHTTP(
const char* host, uint32 port, std::vector<std::string> &urls);
227 NetworkChannel*
createTCPConnection(
const char* addr, uint16 port, uint8 encryption, uint8 protocol,
bool isAsync,
bool autoreconnect, uint32 channelID,
NetworkReceiver* recv, uint64& conid, uint64& location, uint32 timeoutMS = 5000);
244 NetworkChannel*
createTCPConnection(
const uint32* addresses, uint16 addressCount, uint16 port, uint8 encryption, uint8 protocol,
bool isAsync,
bool autoreconnect, uint32 channelID,
NetworkReceiver* recv, uint64& conid, uint64& location, uint32 timeoutMS = 5000);
259 NetworkChannel*
addTCPConnection(
const char* addr, uint16 port, uint8 encryption, uint8 protocol,
bool isAsync, uint32 channelID,
NetworkReceiver* recv, uint64& conid, uint64& location, uint32 timeoutMS = 5000,
const char* greetingData = NULL, uint32 greetingSize = 0);
267 NetworkChannel*
addTCPConnection(uint64 location, uint8 encryption, uint8 protocol,
bool isAsync, uint32 channelID,
NetworkReceiver* recv, uint64& conid, uint32 timeoutMS = 5000,
const char* greetingData = NULL, uint32 greetingSize = 0);
335 std::map<std::string, std::string>& headerEntries,
const char* content,
const char* contentType, uint32 contentSize,
336 bool keepAlive =
false, uint64 ifModifiedSince = 0);
344 std::map<std::string,std::string>& headerEntries, std::map<std::string, HTTPPostEntry*>& bodyEntries,
345 bool keepAlive =
false, uint64 ifModifiedSince = 0);
371#define NETWORKEVENT_CONNECT 1
372#define NETWORKEVENT_RECONNECT 2
373#define NETWORKEVENT_DISCONNECT 3
374#define NETWORKEVENT_DISCONNECT_RETRYING 4
375#define NETWORKEVENT_BUFFER_LOW 5
376#define NETWORKEVENT_BUFFER_FULL 6
377#define NETWORKEVENT_UNPROCESSED_DATA 7
378#define NETWORKEVENT_PROTOCOL_ERROR 8
445 bool startListener(uint64
cid, uint16 port, uint8 encryption, uint8 protocol,
bool isAsync, uint32 protocolTimeout = 3000,
bool isDefaultProtocol =
false);
451 uint64
createTCPConnection(
const char* addr, uint16 port, uint8 encryption, uint8 protocol,
bool isAsync,
bool autoreconnect, uint64& location, uint32 timeoutMS = 5000);
453 uint64
createTCPConnection(uint64 location, uint8 encryption, uint8 protocol,
bool isAsync,
bool autoreconnect, uint32 timeoutMS = 5000);
455 uint64
createTCPConnection(
const uint32* addresses, uint16 addressCount, uint16 port, uint8 encryption, uint8 protocol,
bool isAsync,
bool autoreconnect, uint64& location, uint32 timeoutMS = 5000);
460 uint64
addTCPConnection(
const char* addr, uint16 port, uint8 encryption, uint8 protocol,
bool isAsync, uint64& location, uint32 timeoutMS = 5000,
const char* greetingData = NULL, uint32 greetingSize = 0);
462 uint64
addTCPConnection(uint64 location, uint8 encryption, uint8 protocol,
bool isAsync, uint32 timeoutMS = 5000,
const char* greetingData = NULL, uint32 greetingSize = 0);
465 uint64
createWebsocketConnection(
const char* url,
const char* protocolName,
const char* origin = NULL, uint32 timeoutMS = 5000);
467 uint64
createWebsocketConnection(
const char* uri,
const char* addr, uint16 port, uint8 encryption,
const char* protocolName,
const char* origin = NULL, uint32 timeoutMS = 5000);
Raw socket transport layer: TCP/UDP/SSL connections and TCP listeners with buffered,...
Wire-protocol layer: HTTP request/reply, WebSocket frames, Telnet lines, binary DataMessages,...
#define THREAD_FUNCTION_CALL
The central Psyclone data container: a self-contained binary message with typed, named user entries.
A parsed or generated HTTP response.
A parsed or generated HTTP request (also used for WebSocket upgrade handshakes).
virtual bool receiveHTTPRequest(HTTPRequest *req, NetworkChannel *channel, uint64 conid)
Serve a test page for any request.
One logical network interface: a group of listeners/connections with shared dispatch.
bool setNewReceiver(NetworkReceiver *recv)
Replace the channel's receiver for async dispatch.
bool isConnected(uint64 conid)
static THREAD_RET THREAD_FUNCTION_CALL TelnetServerRun(THREAD_ARG arg)
Thread entry: Telnet server connection loop.
HTTPReply * sendReceiveHTTPRequest(HTTPRequest *req, uint64 conid, uint32 timeout)
Send an HTTP request and block for its reply on the same connection.
bool setSSLAllowSelfSigned(bool allow)
NetworkManager * manager
Owning manager (not owned).
std::queue< HTTPReply * > queueHTTPReplies
bool sendHTTPRequest(HTTPRequest *req, uint64 conid)
Send an HTTP request without waiting for the reply (reply arrives via receiveHTTPReply()/waitForHTTPR...
utils::Mutex channelMutex
uint8 getConnectionType(uint64 conid)
HTTPReply * waitForHTTPReply(uint64 &conid, uint32 ms)
Wait for the next queued HTTP reply (sync-mode HTTP client).
bool enterHTTPReply(HTTPReply *reply, HTTPRequest *req, uint64 conid)
Queue or push an incoming HTTP reply.
uint64 getRemoteAddress(uint64 conid)
std::queue< NetworkEvent * > eventQueue
virtual ~NetworkChannel()
NetworkChannel(NetworkManager *manager)
utils::Semaphore eventQueueSemaphore
uint64 createWebsocketConnection(const char *url, const char *protocolName, const char *origin=NULL, uint32 timeoutMS=5000)
Open a client WebSocket connection from a full URL.
uint32 getOutputSpeed(uint64 conid)
bool setSSLCALocation(const char *caFile, const char *caPath)
std::map< uint16, NetworkThread * > listeners
TCP listener threads by port (owned).
WebsocketData * waitForWebsocketData(uint64 &conid, uint32 ms)
Wait for the next queued WebSocket message.
bool stopListener(uint16 port, uint8 protocol)
Stop a listener on this channel.
utils::Semaphore queueMessagesSemaphore
uint32 getInputSpeed(uint64 conid)
utils::Mutex queueHTTPRequestsMutex
bool enterTelnetLine(TelnetLine *line, uint64 conid)
Queue or push an incoming Telnet line.
static THREAD_RET THREAD_FUNCTION_CALL MessageConnectionRun(THREAD_ARG arg)
Thread entry: binary DataMessage connection loop.
utils::Mutex queueHTTPRepliesMutex
utils::Semaphore queueHTTPRepliesSemaphore
bool endUDPConnection(uint16 port)
Close the UDP connection bound to port.
bool sendMessage(DataMessage *msg, uint64 conid)
Send a DataMessage.
std::map< uint64, NetworkThread * > connectionThreads
Worker threads by connection id (owned).
utils::Semaphore queueTelnetLinesSemaphore
bool enterMessage(DataMessage *msg, uint64 conid)
Queue or push an incoming DataMessage.
utils::Mutex queueWebsocketDataMutex
bool endConnection(uint64 conid)
Gracefully close a connection.
static THREAD_RET THREAD_FUNCTION_CALL ConnectionAutodetectRun(THREAD_ARG arg)
Thread entry: protocol sniffing for a fresh connection (see autoDetectConnection()).
void applySSLClientPolicy(SSLConnection *con)
std::queue< WebsocketData * > queueWebsocketData
TelnetLine * sendReceiveTelnetLine(TelnetLine *line, uint64 conid, uint32 timeout, uint32 size=0)
Send a Telnet line and block for the response line.
friend class NetworkManager
uint64 addTCPConnection(const char *addr, uint16 port, uint8 encryption, uint8 protocol, bool isAsync, uint64 &location, uint32 timeoutMS=5000, const char *greetingData=NULL, uint32 greetingSize=0)
Connect with optional greeting bytes (no autoreconnect); see NetworkManager::addTCPConnection().
uint64 startConnection(NetworkConnection *con, uint8 protocol, bool isAsync, bool autoreconnect, uint32 timeoutMS=5000)
Start the protocol worker thread for an already-connected connection.
bool shutdown()
Stop all worker threads and close all listeners/connections of this channel.
NetworkEvent * waitForNetworkEvent(uint32 ms)
Wait for the next connection lifecycle event (sync mode).
static THREAD_RET THREAD_FUNCTION_CALL HTTPClientRun(THREAD_ARG arg)
Thread entry: HTTP client connection loop (send requests, parse replies).
std::queue< DataMessage * > queueMessages
bool enterNetworkEvent(uint8 type, uint8 protocol, uint64 conid)
Queue or push a lifecycle event.
utils::Mutex queueTelnetLinesMutex
utils::Semaphore queueHTTPRequestsSemaphore
NetworkReceiver * receiver
Async dispatch target (not owned; may be NULL).
std::queue< HTTPRequest * > queueHTTPRequests
bool sendTelnetLine(TelnetLine *line, uint64 conid)
Send a Telnet line.
utils::Semaphore queueWebsocketDataSemaphore
bool sendWebsocketData(WebsocketData *wsData, uint64 conid)
Send a WebSocket frame.
static THREAD_RET THREAD_FUNCTION_CALL NetworkListenerRun(THREAD_ARG arg)
Thread entry: accept loop for a TCP listener.
utils::Mutex eventQueueMutex
utils::Mutex queueMessagesMutex
bool enterHTTPRequest(HTTPRequest *req, uint64 conid)
Queue or push an incoming HTTP request.
std::map< uint16, NetworkThread * > udpListeners
UDP listener threads by port (owned).
bool startListener(uint64 cid, uint16 port, uint8 encryption, uint8 protocol, bool isAsync, uint32 protocolTimeout=3000, bool isDefaultProtocol=false)
Open a listener on this channel (see NetworkManager::createListener() for semantics).
std::queue< uint64 > queueMessageConIDs
uint64 createTCPConnection(const char *addr, uint16 port, uint8 encryption, uint8 protocol, bool isAsync, bool autoreconnect, uint64 &location, uint32 timeoutMS=5000)
Connect to a host by name/IP; see NetworkManager::createTCPConnection().
uint64 autoDetectConnection(NetworkConnection *con, uint16 port, uint32 autoProtocols, uint32 autoProtocolTimeout, uint32 defaultProtocol, bool isAsync, bool autoreconnect)
Adopt an incoming connection whose protocol is not yet known: sniff its first bytes against autoProto...
bool sendHTTPReply(HTTPReply *reply, uint64 conid)
Send an HTTP reply on a server connection.
static THREAD_RET THREAD_FUNCTION_CALL HTTPServerRun(THREAD_ARG arg)
Thread entry: HTTP/WebSocket server connection loop — the built-in web server's per-connection worker...
uint32 cid
Channel id within the manager.
uint64 createUDPConnection(uint16 port, uint8 protocol, bool isAsync, bool autoreconnect)
Bind a UDP port on this channel.
HTTPRequest * waitForHTTPRequest(uint64 &conid, uint32 ms)
Wait for the next queued HTTP request (sync-mode HTTP server).
bool enterWebsocketData(WebsocketData *wsData, uint64 conid)
Queue or push an incoming WebSocket message.
TelnetLine * waitForTelnetLine(uint64 &conid, uint32 ms)
Wait for the next queued Telnet line.
DataMessage * waitForMessage(uint64 &conid, uint32 ms)
Wait for the next queued DataMessage.
std::queue< TelnetLine * > queueTelnetLines
Abstract base class for all point-to-point network connections.
static bool WebsocketTest()
WebSocket upgrade + echo self-test.
friend class NetworkChannel
bool run()
Supervision loop body (delayed connects, reconnection).
utils::Mutex udpOutputConMutex
Serialises use of udpOutputCon.
uint64 lastConnectionID
Last connection id issued.
bool endConnection(uint64 conid)
Gracefully close a connection (thread is asked to finish; entry kept for reuse).
uint8 getConnectionType(uint64 conid)
NetworkChannel * getUDPConnectionByPort(uint16 port)
bool endUDPConnection(uint16 port)
Close the UDP connection bound to port.
std::map< uint64, NetworkChannel * > channelsByConnection
Channel lookup by connection id.
static bool UnitTestHTTP()
Self-test of the built-in HTTP server and client.
bool setSSLCALocation(const char *caFile, const char *caPath)
NetworkChannel * addTCPConnection(const char *addr, uint16 port, uint8 encryption, uint8 protocol, bool isAsync, uint32 channelID, NetworkReceiver *recv, uint64 &conid, uint64 &location, uint32 timeoutMS=5000, const char *greetingData=NULL, uint32 greetingSize=0)
Like createTCPConnection() but sends optional greeting bytes right after connecting (peer identificat...
UDPConnection * udpOutputCon
Shared output-only UDP socket for sendUDPMessage().
static bool TestHTTP(const char *host, uint32 port, std::vector< std::string > &urls)
Fetch a list of URLs from a host and report results (manual test helper).
std::string sslKeyPath
PEM private key path for SSL listeners.
static bool UnitTest()
Basic TCP/message-protocol round-trip self-test.
NetworkChannel * createTCPConnection(const char *addr, uint16 port, uint8 encryption, uint8 protocol, bool isAsync, bool autoreconnect, uint32 channelID, NetworkReceiver *recv, uint64 &conid, uint64 &location, uint32 timeoutMS=5000)
Connect to a remote host by name/IP and start the protocol thread.
bool stopListener(uint16 port, uint8 protocol)
Stop a listener previously opened with createListener().
THREAD_RET THREAD_FUNCTION_CALL NetworkManagerRun(THREAD_ARG arg)
Thread entry point of the manager's supervision loop (do not call directly).
bool setSSLCertificate(const char *sslCertPath, const char *sslKeyPath)
Set the certificate/key used by SSL listeners created via this manager.
std::string sslCertPath
PEM certificate path for SSL listeners.
NetworkChannel * createWebsocketConnection(const char *url, uint32 channelID, NetworkReceiver *recv, uint64 &conid, const char *protocolName=NULL, const char *origin=NULL, uint32 timeoutMS=5000)
Open a client WebSocket connection from a full URL (ws:// or wss://).
uint32 lastChannelID
Last channel id issued.
NetworkChannel * getConnection(uint64 conid)
NetworkChannel * getTCPConnectionByPort(uint16 port)
uint64 addConnection(NetworkChannel *channel)
Register an externally created channel with the manager.
NetworkChannel * createListener(uint16 port, uint8 encryption, uint8 protocol, bool isAsync, uint32 protocolTimeout, bool isDefaultProtocol, uint32 channelID, NetworkReceiver *recv)
Open a listening port for one or more protocols.
uint64 getRemoteAddress(uint64 conid)
HTTPReply * makeHTTPRequest(const char *url, uint32 timeout, const char *content=NULL, uint32 contentSize=0)
Blocking HTTP(S) exchange from a URL string (GET, or POST when content given).
std::map< uint32, NetworkChannel * > channels
All channels by channel id (owned).
NetworkChannel * createUDPConnection(uint16 port, uint8 protocol, bool isAsync, bool autoreconnect, uint32 channelID, NetworkReceiver *recv, uint64 &conid)
Bind a UDP port for datagram traffic.
bool removeConnection(uint64 conid)
Close a connection and remove it from the manager's maps entirely.
virtual ~NetworkManager()
std::map< uint16, NetworkChannel * > listeners
TCP listeners by port.
std::map< uint16, NetworkChannel * > udpListeners
UDP listeners by port.
bool sendUDPMessage(DataMessage *msg, uint64 destination)
Send a DataMessage as a UDP datagram via the shared output socket.
static bool UnitTestDelayedConnect()
Self-test of non-blocking (delayed) connect handling.
bool setSSLAllowSelfSigned(bool allow)
Callback interface for asynchronous delivery of parsed network traffic.
virtual bool receiveTelnetLine(TelnetLine *line, NetworkChannel *channel, uint64 conid)
A Telnet line arrived.
virtual bool receiveMessage(DataMessage *msg, NetworkChannel *channel, uint64 conid)
A binary DataMessage arrived.
virtual bool receiveWebsocketData(WebsocketData *wsData, NetworkChannel *channel, uint64 conid)
A WebSocket message arrived.
virtual bool receiveNetworkEvent(NetworkEvent *evt, NetworkChannel *channel, uint64 conid)
A connection lifecycle event occurred.
virtual bool receiveHTTPRequest(HTTPRequest *req, NetworkChannel *channel, uint64 conid)
An HTTP request arrived on a server connection.
virtual bool receiveHTTPReply(HTTPReply *reply, HTTPRequest *req, NetworkChannel *channel, uint64 conid)
An HTTP reply to an earlier async request arrived.
NetworkThread(NetworkChannel *parent, uint64 id)
uint32 defaultProtocol
Fallback PROTOCOL_* when auto-detection is inconclusive.
NetworkChannel * parent
Owning channel (not owned).
TCPListener * listener
Listener served (owned), or NULL for connections.
uint16 port
Local port (listeners) or 0.
uint32 autoProtocolTimeout
Milliseconds allowed for protocol sniffing.
NetworkConnection * con
Connection served (owned), or NULL for listeners.
bool isAsync
Push to receiver (true) or queue for waitFor*() (false).
uint64 id
Connection or listener id served by this thread.
bool autoreconnect
Re-establish the connection automatically on failure.
uint32 threadID
ThreadManager id of the worker thread.
bool isRunning
True while the worker loop is active.
uint32 autoProtocols
PROTOCOL_* bit set to auto-detect among.
bool shouldContinue
Loop control flag: thread exits when false.
HTTPRequest * lastRequest
Last request pending a reply on this HTTP connection.
Runnable()
Initialise flags: not running, allowed to continue.
SSL/TLS-encrypted TCP connection (OpenSSL) with configurable peer verification.
TCP server socket: binds a port and accepts inbound connections (plain or SSL).
One line of Telnet-style text traffic.
UDP datagram connection (bound port for input, or output-only sender).
One WebSocket frame/message (RFC 6455): parsing, generation and control frames.
virtual bool receiveHTTPRequest(HTTPRequest *req, NetworkChannel *channel, uint64 conid)
Answer the WebSocket upgrade handshake.
virtual bool receiveWebsocketData(WebsocketData *wsData, NetworkChannel *channel, uint64 conid)
Echo received frames back to the client.
Recursive mutual-exclusion lock, optionally named for cross-process use.
Counting semaphore, optionally named for cross-process use.
Notification of a connection lifecycle change (connect, disconnect, buffer state.....
uint64 time
Event timestamp (ms epoch).
uint64 cid
Channel id the event belongs to.
uint8 protocol
PROTOCOL_* of the affected connection.
uint64 conid
Connection id within the channel.
uint8 type
NETWORKEVENT_* event type.