CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
NetworkConnections.h
Go to the documentation of this file.
1
43
327#if !defined(_NETWORKCONNECTIONS_H_)
328#define _NETWORKCONNECTIONS_H_
329
330#pragma once
331
332// #define UDPCON_PRINT_DEBUG
333// #define UDPCON_PRINTBINARY_DEBUG
334// #define TCPCON_PRINT_DEBUG
335// #define TCPCON_PRINTBINARY_DEBUG
336
337#include "ThreadManager.h"
338#include "HTML.h"
339//#include "PsyTime.h"
340
341#ifdef _USE_SSL_
342 #include "openssl/bio.h"
343 #include <openssl/ssl.h>
344 #include <openssl/err.h>
345#endif // _USE_SSL_
346
347namespace cmlabs{
348
352#define NOENC 1
353#define SSLENC 2
354#define AESENC 3
356
359#define TCPCON 1
360#define UDPCON 2
361#define SSLCON 3
362#define AESCON 4
364
367#define INITIALBUFFERSIZE 4096
368
372#define NETWORKERROR_ACCEPT 1
373#define NETWORKERROR_RECEIVE 2
374#define NETWORKERROR_SEND_ERROR 3
375#define NETWORKERROR_SEND_TIMEOUT 4
376#define NETWORKERROR_MEMORYFULL 5
377#define NETWORKERROR_GREETING_ERROR 6
379
380class TCPListener;
381class TCPConnection;
382class UDPConnection;
383class NetworkConnection;
384
394public:
405 virtual bool registerError(uint16 error, TCPListener* con) = 0;
406};
407
418public:
426 virtual bool receiveData(char* data, uint32 size, NetworkConnection* con) = 0;
431 virtual bool registerError(uint16 error, NetworkConnection* con) = 0;
432};
433
434
435
436
437
438
439
451class TCPListener : public Runnable {
452public:
454
455 TCPListener();
456 virtual ~TCPListener();
462 bool setSSLCertificate(const char* sslCertPath, const char* sslKeyPath);
470 bool init(uint16 port, uint8 encryption, NetworkConnectionReceiver* receiver = NULL, NetworkDataReceiver* dataReceiver = NULL);
474 bool disconnect(uint16 error = 0);
476 bool isConnected();
478 uint64 getLocalAddress();
479
486 NetworkConnection* acceptConnection(uint32 timeout);
487
488private:
489 void disconnectInternal(uint16 error); // cleanup without taking mutex (used by init failure paths and disconnect())
490 uint8 encryption;
491 uint64 localAddress;
492 uint64 lastActivity;
493 SOCKET socket;
495 NetworkDataReceiver* dataReceiver;
496 utils::Mutex mutex;
497
498 std::string sslCertPath;
499 std::string sslKeyPath;
500
501 bool run();
502};
503
523public:
529 virtual bool disconnect(uint16 error = 0);
533 virtual bool reconnect(uint32 timeoutMS) = 0;
537 virtual bool didConnect(int timeout = 0);
541 virtual bool didConnect(SOCKET s, int timeout);
545 virtual bool isConnected(int timeout = 0);
548 virtual bool isRemote();
550 virtual uint64 getRemoteAddress();
553 bool setConnectTimeout(uint32 timeoutMS);
554
563 virtual bool send(const char* data, uint32 size, uint64 receiver = 0) = 0;
564// virtual int32 peekStream();
572 virtual bool receive(char* data, uint32 size, uint32 timeout, bool peek = false);
580 virtual bool receiveAvailable(char* data, uint32& size, uint32 maxSize, uint32 timeout, bool peek = false);
583 virtual bool discard(uint32 size);
586 virtual uint32 clearBuffer();
587
591 virtual bool waitForDataToRead(uint32 timeout);
595 virtual bool waitForDataToBeWritten(uint32 timeout);
596
598 virtual uint32 getOutputSpeed();
600 virtual uint32 getInputSpeed();
601
603 virtual uint8 getConnectionType();
604
609 bool setGreetingData(const char* data, uint32 size);
612
613protected:
614 void disconnectInternal(uint16 error); // cleanup without taking mutex (call when mutex already held, or from disconnect())
615
616 uint8 type;
620 uint32 threadID;
622 bool remote;
623 uint32 bufferLen;
629 char* buffer;
635
636 virtual int32 readIntoBuffer();
637 virtual bool resizeBuffer(uint32 len);
638 virtual bool run();
639};
640
641
649public:
651
656 bool initForOutputOnly();
662 bool connect(uint16 port, NetworkDataReceiver* receiver = NULL);
668 bool send(const char* data, uint32 size, uint64 receiver = 0);
671 bool reconnect(uint32 timeoutMS);
674 bool setDefaultReceiver(uint64 receiver);
676 uint64 getLocalAddress();
677
678protected:
680};
681
682
692public:
694
702 bool connect(SOCKET s, uint64 localAddr, NetworkDataReceiver* receiver = NULL);
707 bool connect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver* receiver = NULL);
715 bool connect(const char* addr, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver = NULL);
724 bool connect(const uint32* addresses, uint16 addressCount, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver = NULL);
729 bool delayedConnect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver* receiver);
736 bool delayedConnect(const char* addr, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver);
740 bool send(const char* data, uint32 size, uint64 receiver = 0);
743 bool reconnect(uint32 timeoutMS);
744
745protected:
748 bool findRemoteAddress(uint64& addr);
749};
750
752
767public:
769
774 bool init();
778 bool init(const char *certFile, const char *keyFile);
779
780 // Client certificate verification policy. Default (allowSelfSigned=false):
781 // verify the peer certificate against the OS/CA trust store (secure by
782 // default). setAllowSelfSigned(true) disables peer verification for this
783 // connection only. SetDefaultAllowSelfSigned() sets the process-wide
784 // default (e.g. from <psyspec allowselfsigned="yes">); per-connection
785 // settings override it either way. Call before init()/connect().
786 void setAllowSelfSigned(bool allow);
787 bool getAllowSelfSigned() const { return allowSelfSigned; }
788 static void SetDefaultAllowSelfSigned(bool allow);
789 static bool GetDefaultAllowSelfSigned();
790
791 // Hostname verification: when peer verification is on (allowSelfSigned ==
792 // false) and a hostname is known, the peer certificate must also match
793 // that hostname (SSL_set1_host) and SNI is sent. The hostname is recorded
794 // automatically by connect(const char* addr, ...) when addr is not an IP
795 // literal; setVerifyHostName() sets/overrides it explicitly (empty string
796 // clears it -> chain-of-trust check only). Call before connect().
797 void setVerifyHostName(const char* host);
798 const char* getVerifyHostName() const { return verifyHostName.c_str(); }
799
800 // Custom CA location for peer verification: when set, peer certificates
801 // are verified against this CA file and/or directory (PEM) instead of the
802 // OS default trust store. NULL/empty clears. SetDefaultCALocation() sets
803 // the process-wide default (e.g. from <psyspec cafile="..." capath="...">);
804 // per-connection settings override it. Call before init()/connect().
805 void setCALocation(const char* caFile, const char* caPath);
806 static void SetDefaultCALocation(const char* caFile, const char* caPath);
807#ifdef _USE_SSL_
808 // Returns the SSL_CTX verify mode currently configured (for tests)
809 int getVerifyMode();
810#endif //_USE_SSL_
814 bool connect(SOCKET s, uint64 localAddr, NetworkDataReceiver* receiver = NULL);
818 bool connect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver* receiver = NULL);
826 bool connect(const char* addr, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver = NULL);
831 bool connect(const uint32* addresses, uint16 addressCount, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver = NULL);
835 bool delayedConnect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver* receiver);
840 bool delayedConnect(const char* addr, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver);
844 bool send(const char* data, uint32 size, uint64 receiver = 0);
847 bool reconnect(uint32 timeoutMS);
849 bool isConnected(int timeout = 0);
851 bool didConnect(int timeout = 0);
854 bool disconnect(uint16 error = 0);
855
858 int32 peekStream();
861 int32 readIntoBuffer();
863 bool receive(char* data, uint32 size, uint32 timeout, bool peek = false);
865 bool receiveAvailable(char* data, uint32& size, uint32 maxSize, uint32 timeout, bool peek = false);
866
867 std::string certinfo;
868
869protected:
870 bool findRemoteAddress(uint64& addr);
873 std::string verifyHostName;
874 std::string caFile;
875 std::string caPath;
876 static std::string DefaultCAFile;
877 static std::string DefaultCAPath;
878 #ifdef _USE_SSL_
879 bool applyClientVerify();
880 SSL_CTX *ctx;
881 SSL *ssl;
882 BIO *certbio;
883 BIO *outbio;
884#endif //_USE_SSL_
885};
886
893
897bool NetworkTest_TCPServer(uint16 port, uint32 count = 0);
901bool NetworkTest_TCPClient(const char* address, uint16 port, uint32 count = 0);
906bool NetworkTest_SendReceiveData(TCPConnection* con, char* data, uint32 dataLen, uint32 c, bool receiveFirst = false);
907
908}
909
910#endif // _NETWORKCONNECTIONS_H_
HTML/URL helper utilities: entity encoding/decoding, MIME type lookup and URL component parsing.
Process-wide thread registry and lifecycle manager: the concurrency core of CMSDK.
#define THREAD_RET
Definition Utils.h:127
#define THREAD_FUNCTION_CALL
Definition Utils.h:129
#define THREAD_ARG
Definition Utils.h:130
#define SOCKET
Definition Utils.h:134
Abstract base class for all point-to-point network connections.
virtual bool send(const char *data, uint32 size, uint64 receiver=0)=0
Send raw bytes on the connection.
virtual uint32 clearBuffer()
Discard all currently buffered input.
NetworkDataReceiver * receiver
virtual bool waitForDataToBeWritten(uint32 timeout)
Block until the socket is writable.
bool setConnectTimeout(uint32 timeoutMS)
Set the timeout used by subsequent connect()/reconnect() attempts.
virtual bool receiveAvailable(char *data, uint32 &size, uint32 maxSize, uint32 timeout, bool peek=false)
Receive whatever bytes are available (up to maxSize).
virtual bool receive(char *data, uint32 size, uint32 timeout, bool peek=false)
Receive exactly size bytes into data, waiting up to timeout ms.
virtual bool disconnect(uint16 error=0)
Close the connection and release the socket.
virtual bool waitForDataToRead(uint32 timeout)
Block until data is readable (buffered or on the socket).
char * greetingData
Owned copy of the greeting bytes (NULL if unset).
void disconnectInternal(uint16 error)
virtual bool resizeBuffer(uint32 len)
virtual bool discard(uint32 size)
Drop size bytes from the front of the receive buffer (after a peek).
virtual bool didConnect(int timeout=0)
Check/complete an in-progress (delayed) connect on the existing socket.
virtual bool isConnected(int timeout=0)
Test whether the connection is currently alive.
bool setGreetingData(const char *data, uint32 size)
Set greeting bytes sent automatically right after a connection is established (used e....
virtual bool reconnect(uint32 timeoutMS)=0
Re-establish the connection to the previously known remote endpoint.
uint32 greetingSize
Size of greetingData in bytes.
Callback interface for asynchronous delivery of newly accepted connections.
virtual bool registerError(uint16 error, TCPListener *con)=0
Called when the listener encounters an error.
virtual bool receiveNetworkConnection(NetworkConnection *con)=0
Called when the listener has accepted a new connection.
Callback interface for asynchronous (push) delivery of received bytes.
virtual bool receiveData(char *data, uint32 size, NetworkConnection *con)=0
Called when data has been read from the socket.
virtual bool registerError(uint16 error, NetworkConnection *con)=0
Called when the connection encounters an error (e.g.
Runnable()
Initialise flags: not running, allowed to continue.
static std::string DefaultCAFile
bool isConnected(int timeout=0)
Test whether the connection is currently alive.
bool receiveAvailable(char *data, uint32 &size, uint32 maxSize, uint32 timeout, bool peek=false)
Receive whatever bytes are available (up to maxSize).
bool init()
Initialise the OpenSSL context for a client-side connection.
bool findRemoteAddress(uint64 &addr)
bool didConnect(int timeout=0)
Check/complete an in-progress (delayed) connect on the existing socket.
std::string certinfo
Human-readable summary of the peer certificate (subject/issuer), filled after handshake.
void setCALocation(const char *caFile, const char *caPath)
static std::string DefaultCAPath
void setVerifyHostName(const char *host)
friend THREAD_RET THREAD_FUNCTION_CALL SSLConnectionRun(THREAD_ARG arg)
bool disconnect(uint16 error=0)
Shut down the TLS session and close the socket.
const char * getVerifyHostName() const
bool receive(char *data, uint32 size, uint32 timeout, bool peek=false)
Receive exactly size bytes into data, waiting up to timeout ms.
bool send(const char *data, uint32 size, uint64 receiver=0)
Send bytes over the encrypted stream.
bool connect(SOCKET s, uint64 localAddr, NetworkDataReceiver *receiver=NULL)
Adopt an already-accepted socket and perform the server-side TLS handshake.
static bool GetDefaultAllowSelfSigned()
void setAllowSelfSigned(bool allow)
int32 peekStream()
Peek how many decrypted bytes are pending inside the SSL layer.
bool reconnect(uint32 timeoutMS)
Reconnect and re-handshake to the previous endpoint.
static void SetDefaultCALocation(const char *caFile, const char *caPath)
static void SetDefaultAllowSelfSigned(bool allow)
bool delayedConnect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver *receiver)
Begin a non-blocking connect (TLS handshake completes in didConnect()).
int32 readIntoBuffer()
Read decrypted bytes from the SSL layer into the internal buffer.
Plain TCP stream connection (client-initiated or accepted from a listener).
friend THREAD_RET THREAD_FUNCTION_CALL TCPConnectionRun(THREAD_ARG arg)
Thread entry point for a TCPConnection's push-mode reader loop.
bool findRemoteAddress(uint64 &addr)
Query the OS for the peer address of the connected socket.
bool send(const char *data, uint32 size, uint64 receiver=0)
Send bytes on the stream (see NetworkConnection::send()).
bool connect(SOCKET s, uint64 localAddr, NetworkDataReceiver *receiver=NULL)
Adopt an already-connected socket (server side, from a TCPListener).
bool delayedConnect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver *receiver)
Begin a non-blocking connect; completion is checked with didConnect().
bool reconnect(uint32 timeoutMS)
Reconnect to the previously resolved remote endpoint.
TCP server socket: binds a port and accepts inbound connections (plain or SSL).
friend THREAD_RET THREAD_FUNCTION_CALL TCPListenerRun(THREAD_ARG arg)
Thread entry point for a TCPListener's internal accept loop.
NetworkConnection * acceptConnection(uint32 timeout)
Synchronously wait for and accept one inbound connection.
bool setSSLCertificate(const char *sslCertPath, const char *sslKeyPath)
Set the SSL certificate and private key used for inbound SSL connections.
bool disconnect(uint16 error=0)
Stop listening and close the socket.
bool init(uint16 port, uint8 encryption, NetworkConnectionReceiver *receiver=NULL, NetworkDataReceiver *dataReceiver=NULL)
Bind and start listening on a port.
bool initForOutputOnly()
Create an unbound socket usable only for sending datagrams.
bool reconnect(uint32 timeoutMS)
Rebind the local port (UDP has no session to re-establish).
bool send(const char *data, uint32 size, uint64 receiver=0)
Send one datagram.
bool connect(uint16 port, NetworkDataReceiver *receiver=NULL)
Bind a local UDP port for receiving datagrams.
uint64 defaultReceiver
Default destination endpoint for send() when none is given.
friend THREAD_RET THREAD_FUNCTION_CALL UDPConnectionRun(THREAD_ARG arg)
Thread entry point for a UDPConnection's push-mode reader loop.
bool setDefaultReceiver(uint64 receiver)
Set the default destination used by send() when receiver == 0.
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:463
THREAD_RET THREAD_FUNCTION_CALL TCPListenerRun(THREAD_ARG arg)
Thread entry point for a TCPListener's internal accept loop.
bool NetworkTest_TCPClient(const char *address, uint16 port, uint32 count=0)
Loopback test client matching NetworkTest_TCPServer().
THREAD_RET THREAD_FUNCTION_CALL UDPConnectionRun(THREAD_ARG arg)
Thread entry point for a UDPConnection's push-mode reader loop.
bool NetworkTest_TCPServer(uint16 port, uint32 count=0)
Loopback test server: listens on port and echoes test payloads.
THREAD_RET THREAD_FUNCTION_CALL TCPConnectionRun(THREAD_ARG arg)
Thread entry point for a TCPConnection's push-mode reader loop.
bool NetworkTest_SendReceiveData(TCPConnection *con, char *data, uint32 dataLen, uint32 c, bool receiveFirst=false)
Send-and-verify helper used by the TCP tests.
THREAD_RET THREAD_FUNCTION_CALL SSLConnectionRun(THREAD_ARG arg)