10 #include <arpa/inet.h>
12#if defined(_USE_SSL_) && defined(WINDOWS)
19 #undef X509_EXTENSIONS
21 #undef PKCS7_SIGNER_INFO
36static void LogSSLErrors(
const char* context,
int level) {
40 while ((e = ERR_get_error()) != 0) {
41 ERR_error_string_n(e, buf,
sizeof(buf));
46 LogPrint(0,
LOG_NETWORK, level,
"SSL: %s (no OpenSSL error detail)", context ? context :
"error");
90void TCPListener::disconnectInternal(uint16 error) {
97 if (receiver && error)
103 disconnectInternal(error);
119 this->encryption = encryption;
120 memcpy(((
char*)&localAddress)+
sizeof(uint32), &port,
sizeof(uint16));
124 if((socket=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==
INVALID_SOCKET){
134 setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (
char *) &one,
sizeof(one));
146 setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,&one,
sizeof(one));
149 struct sockaddr_in addr;
150 addr.sin_family= AF_INET;
151 addr.sin_addr.s_addr=INADDR_ANY;
152 addr.sin_port=htons(port);
156 disconnectInternal(0);
165 disconnectInternal(0);
170 if (receiver != NULL) {
171 this->receiver = receiver;
175 disconnectInternal(0);
180 this->dataReceiver = dataReceiver;
192 this->sslCertPath = sslCertPath;
193 this->sslKeyPath = sslKeyPath;
205 while ( (timespent = (
GetTimeNow() - start)/1000) < timeout) {
208 new_sock = accept(socket, NULL, NULL);
210 if ((
int) new_sock < 0) {
219 LogPrint(0,
LOG_NETWORK, 2,
"Shutting down network listener with error code: %d", new_sock);
222 if (err != WSAENOTSOCK)
233 if (encryption ==
SSLENC) {
236 if (!sslCon->
init(sslCertPath.c_str(), sslKeyPath.c_str())) {
245 if (!sslCon->
connect(new_sock, localAddress, dataReceiver)) {
254 else if (encryption ==
AESENC) {
261 if (!newCon->
connect(new_sock, localAddress, dataReceiver)) {
280bool TCPListener::run() {
283 if (receiver == NULL)
289 if (receiver != NULL)
333 mutex.setCancelSafe(
true);
403 receiver->registerError(error,
this);
414 if (len < 128)
return false;
415 char* newBuffer =
new char[len];
458#ifdef TCPCON_PRINT_DEBUG
485 memset(&from, 0,
sizeof(from));
487 int fromLen =
sizeof(from);
489 socklen_t fromLen =
sizeof(from);
496 memcpy(&src, &from.sin_addr.s_addr, 4);
497 uint16 srcPort = ntohs(from.sin_port);
498 memcpy(((
char*)&src) +
sizeof(uint32), &srcPort,
sizeof(uint16));
513 else if (datagram && ((err == WSAECONNRESET) || (err == WSAEMSGSIZE)))
520 if (err != WSAENOTSOCK)
557 if (datagram && c > 0)
561 #ifdef TCPCON_PRINT_DEBUG
564 char* tmp =
new char[count+1];
567 LogPrint(0,
LOG_NETWORK,0,
"<<<<<<< READINTOBUFFER <<<<<<<< TCP RECV BUF %d bytes '%s' (%.3fms) %d / %d\n", count, tmp,
GetTimeAge(start)/1000.0, rounds, resize);
576 #ifdef UDPCON_PRINT_DEBUG
579 char* tmp =
new char[count+1];
582 LogPrint(0,
LOG_NETWORK,0,
"<<<<<<< READINTOBUFFER <<<<<<<< UDP RECV BUF %u bytes '%s'\n", count, tmp);
632 if (!c && dataAvailable) {
640 if ((timespent =
GetTimeAgeMS(start)) >= (int32)timeout)
701 if ((timespent =
GetTimeAgeMS(start)) >= (int32)timeout) {
716 inputSpeed = (uint32)(size*1000000.0/(
double)t);
787 if (!
mutex.enter(1000))
791 int res = recv(
socket, peekBuffer, 1, MSG_PEEK);
809 else if (err == WSAENOTCONN) {}
810 else if (err == WSAENOTSOCK) {}
811 else if (err == WSAEOPNOTSUPP) {}
850 #if GCC_VERSION < 40000
864 ldiv_t d = ldiv(timeout*1000, 1000000);
870 res = select(maxfd, NULL, &wfds, NULL, &tv);
880 if (!
mutex.enter(1000))
883 if (FD_ISSET(
socket, &wfds) != 0) {
884 if (getsockopt(
socket, SOL_SOCKET, SO_ERROR, (
char*)&error, &len) != 0) {
893 else if (wsaError == WSAENETDOWN ) {
896 else if (wsaError == WSAEFAULT ) {
899 else if (wsaError == WSAEINPROGRESS ) {
902 else if (wsaError == WSAEINVAL ) {
905 else if (wsaError == WSAENOPROTOOPT ) {
910 else if (wsaError == WSAENOTSOCK ) {
943 #if GCC_VERSION < 40000
957 ldiv_t d = ldiv(timeout * 1000, 1000000);
963 int res = select(maxfd, NULL, &wfds, NULL, &tv);
973 if (FD_ISSET(s, &wfds) != 0) {
974 if (getsockopt(s, SOL_SOCKET, SO_ERROR, (
char*)&error, &len) != 0) {
982 else if (wsaError == WSAENETDOWN) {
985 else if (wsaError == WSAEFAULT) {
988 else if (wsaError == WSAEINPROGRESS) {
991 else if (wsaError == WSAEINVAL) {
994 else if (wsaError == WSAENOPROTOOPT) {
999 else if (wsaError == WSAENOTSOCK) {
1017 if (!
mutex.enter(1000))
1037 #if GCC_VERSION < 40000
1051 ldiv_t d = ldiv(timeout * 1000, 1000000);
1057 int res = select(maxfd, NULL, &wfds, NULL, &tv);
1065 len =
sizeof(error);
1068 if (FD_ISSET(
socket, &wfds) != 0) {
1069 if (getsockopt(
socket, SOL_SOCKET, SO_ERROR, (
char*)&error, &len) != 0) {
1073 if (wsaError == 0) {
1078 else if (wsaError == WSAENETDOWN) {
1081 else if (wsaError == WSAEFAULT) {
1084 else if (wsaError == WSAEINPROGRESS) {
1087 else if (wsaError == WSAEINVAL) {
1090 else if (wsaError == WSAENOPROTOOPT) {
1095 else if (wsaError == WSAENOTSOCK) {
1117 char* myBuffer = (
char*) malloc(buflen);
1118 if (myBuffer == NULL)
1121 LogPrint(0,
LOG_NETWORK, 2,
"Incoming network connection from %u.%u.%u.%u:%u, started run...",
1126 if (
receive((
char*)&size,
sizeof(size), 50,
true)) {
1128 if (buflen < size) {
1130 myBuffer = (
char*) realloc(myBuffer, buflen);
1131 if (myBuffer == NULL) {
1139 if (!
receive(myBuffer, size, 500)) {
1147 receiver->receiveData(myBuffer, size,
this);
1200 setsockopt(
socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (
char *) &one,
sizeof(one));
1212 setsockopt(
socket,SOL_SOCKET,SO_REUSEADDR,&one,
sizeof(one));
1215 setsockopt(
socket,SOL_SOCKET,SO_BROADCAST,(
char*)&one,
sizeof(one));
1230 memcpy(((
char*)&
localAddress)+
sizeof(uint32), &port,
sizeof(uint16));
1246 setsockopt(
socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (
char *) &one,
sizeof(one));
1258 setsockopt(
socket,SOL_SOCKET,SO_REUSEADDR,&one,
sizeof(one));
1261 setsockopt(
socket,SOL_SOCKET,SO_BROADCAST,(
char*)&one,
sizeof(one));
1265 int rcvbuf = 4 * 1024 * 1024;
1266 setsockopt(
socket, SOL_SOCKET, SO_RCVBUF, (
char*)&rcvbuf,
sizeof(rcvbuf));
1272 BOOL reportReset =
FALSE;
1274 WSAIoctl(
socket, _WSAIOW(IOC_VENDOR, 12), &reportReset,
sizeof(reportReset), NULL, 0, &bytes, NULL, NULL);
1278 struct sockaddr_in addr;
1279 addr.sin_family= AF_INET;
1280 addr.sin_addr.s_addr=INADDR_ANY;
1281 addr.sin_port=htons(port);
1311 sockaddr_in recvAddr;
1312 recvAddr.sin_family = AF_INET;
1322 recvAddr.sin_port = htons(p);
1323 memcpy(&recvAddr.sin_addr.s_addr, &rec, 4);
1333 n = ::sendto(
socket, data + pos, size - pos, 0, (
SOCKADDR*)&recvAddr,
sizeof(sockaddr_in));
1357 if (err == WSAECONNRESET)
1360 LogPrint(0,
LOG_NETWORK, 1,
"UDP send error %d to port %u - socket dropped", err, (uint32)p);
1386 #ifdef UDPCON_PRINT_DEBUG
1388 char* tmp =
new char[size+1];
1389 memcpy(tmp, data, size);
1395 #ifdef UDPCON_PRINTBINARY_DEBUG
1396 char* tmp =
new char[size+1];
1397 memcpy(tmp, data, size);
1402 char* tmp =
new char[1024];
1403 memcpy(tmp, data, 1023);
1459 struct linger tmp = {1, 0};
1460 setsockopt(
socket, SOL_SOCKET, SO_LINGER, (
char *)&tmp,
sizeof(tmp));
1462 setsockopt(
socket, IPPROTO_TCP, TCP_NODELAY, (
char*) &delay,
sizeof(delay));
1468 LogPrint(0,
LOG_NETWORK, 2,
"Incoming TCP connection from %u.%u.%u.%u:%u, starting run...",
1533 struct sockaddr_in saServer;
1534 saServer.sin_family = AF_INET;
1535 saServer.sin_port = htons(
GETIPPORT(addr));
1536 memcpy(&saServer.sin_addr.s_addr, &addr, 4);
1540 if ((res =
::connect(tempSocket, (
struct sockaddr*)&saServer,
sizeof(
struct sockaddr))) != 0) {
1557 struct linger tmp = {1, 0};
1558 setsockopt(tempSocket, SOL_SOCKET, SO_LINGER, (
char *)&tmp,
sizeof(tmp));
1560 setsockopt(tempSocket, IPPROTO_TCP, TCP_NODELAY, (
char*) &delay,
sizeof(delay));
1567 if (!
mutex.enter(1000)) {
1603 for (uint16 n=0; n<addressCount; n++) {
1726 #ifdef TCPCON_PRINT_DEBUG
1728 char* tmp =
new char[size+1];
1729 memcpy(tmp, data, size);
1731 LogPrint(0,
LOG_NETWORK,0,
">>>>>>> SEND >>>>>>>> TCP Sent %u bytes (%.3f) '%s'\n", size, t/1000.0, tmp);
1735 #ifdef TCPCON_PRINTBINARY_DEBUG
1736 char* tmp =
new char[size+1];
1737 memcpy(tmp, data, size);
1742 char* tmp =
new char[1024];
1743 memcpy(tmp, data, 1023);
1745 LogPrint(0,
LOG_NETWORK,0,
">>>>>>> SEND >>>>>>>> TCP Sent %u bytes (%.3f) '%s'\n", size, t / 1000.0, tmp);
1769 struct sockaddr_in remoteAddr;
1775 #if GCC_VERSION < 40000
1778 socklen_t remoteAddrLen;
1781 socklen_t remoteAddrLen;
1785 remoteAddrLen =
sizeof(
struct sockaddr_in);
1787 if (getpeername(
socket, (
struct sockaddr*) &remoteAddr, &remoteAddrLen) != 0)
1790 uint32 address = remoteAddr.sin_addr.s_addr;
1832 OpenSSL_add_all_algorithms();
1834 ERR_load_crypto_strings();
1835 SSL_load_error_strings();
1837 certbio = BIO_new(BIO_s_file());
1838 outbio = BIO_new_fp(stdout, BIO_NOCLOSE);
1890 applyClientVerify();
1902 applyClientVerify();
1909bool SSLConnection::applyClientVerify() {
1913 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
1919 if (SSL_CTX_load_verify_locations(ctx,
1932 bool loadedOSRoots =
false;
1933 HCERTSTORE hStore = CertOpenSystemStoreA(0,
"ROOT");
1935 X509_STORE* store = SSL_CTX_get_cert_store(ctx);
1936 PCCERT_CONTEXT pWinCert = NULL;
1937 while ((pWinCert = CertEnumCertificatesInStore(hStore, pWinCert)) != NULL) {
1938 const unsigned char* enc = pWinCert->pbCertEncoded;
1939 X509* x = d2i_X509(NULL, &enc, pWinCert->cbCertEncoded);
1942 if (X509_STORE_add_cert(store, x) == 1)
1943 loadedOSRoots =
true;
1947 CertCloseStore(hStore, 0);
1954 if (SSL_CTX_set_default_verify_paths(ctx) != 1)
1958 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
1963int SSLConnection::getVerifyMode() {
1966 return SSL_CTX_get_verify_mode(ctx);
1975 const SSL_METHOD *method = SSLv23_server_method();
1977 ctx = SSL_CTX_new(method);
1980 BIO_printf(outbio,
"Unable to create a new SSL context structure.\n");
1986 if ( SSL_CTX_use_certificate_chain_file(ctx, certFile) <= 0) {
1988 LogSSLErrors(
"certificate chain file", 0);
1992 if ( SSL_CTX_use_PrivateKey_file(ctx, keyFile, SSL_FILETYPE_PEM) <= 0) {
1994 LogSSLErrors(
"private key file", 0);
2001 if ( !SSL_CTX_check_private_key(ctx) ) {
2003 fprintf(stderr,
"Private key is invalid.\n");
2020 const SSL_METHOD *method = SSLv23_method();
2022 ctx = SSL_CTX_new(method);
2024 BIO_printf(outbio,
"Unable to create a new SSL context structure.\n");
2033 applyClientVerify();
2064 if (!
mutex.enter(200, __FUNCTION__))
2067 int res = recv(
socket, peekBuffer, 1, MSG_PEEK);
2088 else if (err == WSAENOTCONN) {}
2089 else if (err == WSAEOPNOTSUPP) {}
2132 #if GCC_VERSION < 40000
2146 ldiv_t d = ldiv(timeout*1000, 1000000);
2153 res = select(maxfd, NULL, &wfds, NULL, &tv);
2162 len =
sizeof(error);
2166 if (FD_ISSET(
socket, &wfds) != 0) {
2167 if (getsockopt(
socket, SOL_SOCKET, SO_ERROR, (
char*)&error, &len) != 0) {
2171 if (wsaError == 0) {
2176 else if (wsaError == WSAENETDOWN ) {
2179 else if (wsaError == WSAEFAULT ) {
2182 else if (wsaError == WSAEINPROGRESS ) {
2185 else if (wsaError == WSAEINVAL ) {
2188 else if (wsaError == WSAENOPROTOOPT ) {
2193 else if (wsaError == WSAENOTSOCK ) {
2230 if (!ctx || !(ssl = SSL_new(ctx)))
2244 struct linger tmp = {1, 0};
2245 setsockopt(s, SOL_SOCKET, SO_LINGER, (
char *)&tmp,
sizeof(tmp));
2247 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (
char*) &delay,
sizeof(delay));
2252 SSL_set_fd(ssl, (
int)
socket);
2253 int ret = SSL_accept(ssl);
2258 err = SSL_get_error(ssl, ret);
2259 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
2261 if ((++errCount) > 10) {
2272 ret = SSL_accept(ssl);
2311 if (!ctx && !
init()) {
2314 if (!ctx || !(ssl = SSL_new(ctx))) {
2315 LogSSLErrors(
"SSL_new", 0);
2353 struct sockaddr_in saServer;
2354 saServer.sin_family = AF_INET;
2355 saServer.sin_port = htons(
GETIPPORT(addr));
2356 memcpy(&saServer.sin_addr.s_addr, &addr, 4);
2361 if ((res =
::connect(
socket, (
struct sockaddr*)&saServer,
sizeof(
struct sockaddr))) != 0) {
2382 struct linger tmp = {1, 0};
2383 setsockopt(
socket, SOL_SOCKET, SO_LINGER, (
char *)&tmp,
sizeof(tmp));
2385 setsockopt(
socket, IPPROTO_TCP, TCP_NODELAY, (
char*) &delay,
sizeof(delay));
2388 if (!SSL_set_fd (ssl, (
int)
socket)) {
2389 LogSSLErrors(
"SSL_set_fd", 0);
2398 SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
2405 while ( (ret = SSL_connect(ssl)) != 1) {
2406 switch (SSL_get_error(ssl, ret)) {
2407 case SSL_ERROR_WANT_READ:
2410 case SSL_ERROR_WANT_WRITE:
2418 LogSSLErrors(
"handshake failed", 1);
2437 uint32 certnamemax = 1000;
2441 cert = SSL_get_peer_certificate(ssl);
2443 certname =
new char[certnamemax+1];
2444 certinfo = X509_NAME_oneline(X509_get_subject_name(cert), certname, certnamemax);
2479 if (
verifyHostName.empty() && addr && (inet_addr(addr) == INADDR_NONE))
2490 for (uint16 n=0; n<addressCount; n++) {
2533 if (
verifyHostName.empty() && addr && (inet_addr(addr) == INADDR_NONE))
2562 if (!
mutex.enter(1000)) {
2571 ret = SSL_write(ssl, data, size);
2572 sslErr = (ret <= 0) ? SSL_get_error(ssl, ret) : SSL_ERROR_NONE;
2577 case SSL_ERROR_WANT_READ:
2580 case SSL_ERROR_WANT_WRITE:
2590 if (ret < (
int)size) {
2604 #ifdef TCPCON_PRINT_DEBUG
2606 char* tmp =
new char[size+1];
2607 memcpy(tmp, data, size);
2613 #ifdef TCPCON_PRINTBINARY_DEBUG
2614 char* tmp =
new char[size+1];
2615 memcpy(tmp, data, size);
2645 struct sockaddr_in remoteAddr;
2651 #if GCC_VERSION < 40000
2654 socklen_t remoteAddrLen;
2657 socklen_t remoteAddrLen;
2661 remoteAddrLen =
sizeof(
struct sockaddr_in);
2663 if (getpeername(
socket, (
struct sockaddr*) &remoteAddr, &remoteAddrLen) != 0)
2666 uint32 address = remoteAddr.sin_addr.s_addr;
2684 int count = SSL_pending(ssl);
2702 int pending = SSL_pending(ssl);
2722 else if (count == 0) {
2727 #ifdef TCPCON_PRINT_DEBUG
2728 char* tmp =
new char[count+1];
2731 LogPrint(0,
LOG_NETWORK,0,
"<<<<<<< SSL READINTOBUFFER <<<<<<<< TCP RECV BUF %u bytes '%s'\n", count, tmp);
2765 int count, err, timeleft;
2771 err = SSL_get_error(ssl, count);
2772 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
2780 else if (count > 0) {
2781 #ifdef TCPCON_PRINT_DEBUG
2782 char* tmp =
new char[count+1];
2785 LogPrint(0,
LOG_NETWORK,0,
"<<<<<<< RECEIVE <<<<<<<< TCP RECV AVAIL %u bytes '%s'\n", count, tmp);
2792 if ((timespent = (
GetTimeNow() - start)/1000) >= timeout) {
2799 timeleft = (int)(timeout-timespent);
2848 int count, err, timeleft;
2863 err = SSL_get_error(ssl, count);
2864 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
2872 else if (count > 0) {
2873 #ifdef TCPCON_PRINTBINARY_DEBUG
2874 char* tmp =
new char[count+1];
2884 if ((timespent =
GetTimeAgeMS(start)) >= (int32)timeout) {
2893 timeleft = (int)(timeout-timespent);
2902 inputSpeed = (uint32)(size*1000000.0/(
double)t);
2950 uint32 period = 100000;
2955 printf(
"Could not bind to port %u, exiting... \n\n", port);
2959 char* startdata =
new char[12], *data;
2965 printf(
"\n\nListening to port %u for a new connection... ", port);
2970 if (!con->
receive(startdata, 12, 10000)) {
2971 printf(
"[%u] Could not receive start data, exiting...\n", c);
2974 if ((*(uint32*)startdata) != 123456789) {
2975 printf(
"[%u] Start data wrong, exiting...\n", c);
2978 size = *(((uint32*)startdata)+1);
2979 count = *(((uint32*)startdata)+2);
2981 data =
new char[size];
2983 printf(
"Got it - starting test with size %u and count %u...\n\n", size, count);
2986 if (!con->
receive(data, size, 10000)) {
2987 printf(
"[%u] Could not receive data %u, exiting...\n", port, c);
2990 if (!con->
send(data, size)) {
2991 printf(
"[%u] Could not send data %u, exiting...\n", port, c);
3021 delete [] startdata;
3029 if (!con->
connect(address, port, location, 5000)) {
3031 printf(
"Could not connect to '%s' on port %u, exiting...\n", address, port);
3034 printf(
"Connected to '%s' on port %u, starting test...\n", address, port);
3036 char* startdata =
new char[12];
3037 memset(startdata, 0, 12);
3038 *((uint32*)startdata) = 123456789;
3040 uint32 maxSize = 1024*64, innercount = 20, count = 1000, steps = 64, s, c, step;
3041 char* data =
new char[maxSize];
3042 double* vals =
new double[count];
3043 double* avgvals =
new double[steps];
3044 double* maxvals =
new double[steps];
3045 double* minvals =
new double[steps];
3046 double* stdvals =
new double[steps];
3047 double sum, avg, mx, mn,
std;
3053 for (step=0; step<steps; step++) {
3054 s = (maxSize/steps*(step+1));
3055 *(((uint32*)startdata)+1) = s;
3056 *(((uint32*)startdata)+2) = count * innercount;
3057 if (!con->
send(startdata, 12)) {
3058 printf(
"[%u] Could not send startdata, exiting...\n", port);
3061 printf(
"Step %u size %u...\n", step, s);
3062 for (c=0; c<count; c++) {
3064 for (uint32 i=0; i<innercount; i++) {
3065 if (!con->
send(data, s)) {
3066 printf(
"[%u] Could not send data %u, exiting...\n", port, c);
3069 if (!con->
receive(data, s, 10000)) {
3070 printf(
"[%u] Could not receive data %u, exiting...\n", port, c);
3075 vals[c] = (t2-t1)/(
double)innercount;
3078 sum = avg =
std = 0;
3080 for (c=0; c<count; c++) {
3082 if (vals[c] > mx) mx = vals[c];
3083 if (vals[c] < mn) mn = vals[c];
3088 for (c=0; c<count; c++)
3089 sum += pow((vals[c] - avg), 2);
3090 std = sqrt(sum/count-1);
3092 avgvals[step] = avg;
3095 stdvals[step] =
std;
3098 printf(
"Test results (size, avg, min, max, std in us):\n");
3099 for (step=0; step<steps; step++) {
3100 s = (maxSize/steps*(step+1));
3101 printf(
"%u %u %.3f %.3f %.3f %.3f\n",
3102 step, s, avgvals[step], minvals[step], maxvals[step], stdvals[step]);
3108 delete [] startdata;
3153 uint32 expectC = c*2;
3154 if (!receiveFirst) {
3157 if (!con->
send(data, dataLen)) {
3158 printf(
"[%u] Could not send data, exiting...\n", c);
3164 memset(data, 0, dataLen);
3166 if (!con->
receive(data, dataLen, 10000)) {
3167 printf(
"[%u] Could not receive data, exiting...\n", c);
3172 if (*(uint32*)data != dataLen) {
3173 printf(
"[%u] Did not receive correct length (%u != %u), exiting...\n", c, *(uint32*)data, dataLen);
3178 if (*((uint32*)data+1) != expectC) {
3179 printf(
"[%u] Did not receive correct count (%u != %u), exiting...\n", c, *((uint32*)data+1), expectC);
3184 if (strcmp(data+(2*
sizeof(uint32)),
"Testing") != 0) {
3185 data[dataLen-1] = 0;
3186 printf(
"[%u] Did not receive correct text ('%s' != 'Testing'), exiting...\n", c, data+(2*
sizeof(uint32)));
3190 *((uint32*)data+1) = *((uint32*)data+1) + 1;
3195 if (!con->
send(data, dataLen)) {
3196 printf(
"[%u] Could not send data, exiting...\n", c);
Raw socket transport layer: TCP/UDP/SSL connections and TCP listeners with buffered,...
#define SSLCON
SSL/TLS-encrypted TCP connection.
#define AESENC
AES encryption (reserved; not currently implemented).
#define NETWORKERROR_SEND_TIMEOUT
A write could not complete within the timeout.
#define NETWORKERROR_RECEIVE
A read from the socket failed (peer closed or socket error).
#define TCPCON
Plain TCP stream connection.
#define UDPCON
UDP datagram connection.
#define NETWORKERROR_ACCEPT
accept() failed on a listener socket.
#define NOENC
Plain, unencrypted transport.
#define SSLENC
SSL/TLS encryption (requires build with _USE_SSL_).
#define NETWORKERROR_SEND_ERROR
A write to the socket failed.
#define INITIALBUFFERSIZE
Initial size in bytes of a connection's internal receive buffer; it grows on demand via NetworkConnec...
#define NETWORKERROR_MEMORYFULL
The receive buffer could not grow to hold incoming data.
#define GETIPADDRESSQUAD(a)
#define thread_ret_val(ret)
#define THREAD_FUNCTION_CALL
#define GETIPADDRESSPORT(a, p)
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 getOutputSpeed()
virtual uint32 clearBuffer()
Discard all currently buffered input.
NetworkDataReceiver * receiver
virtual bool waitForDataToBeWritten(uint32 timeout)
Block until the socket is writable.
virtual uint64 getRemoteAddress()
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).
virtual uint8 getConnectionType()
virtual uint32 getInputSpeed()
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....
uint32 greetingSize
Size of greetingData in bytes.
virtual int32 readIntoBuffer()
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.
bool isRunning
Set by the worker while its loop is active.
virtual bool stop(uint32 timeout=200)
Ask the worker loop to finish and wait for it to do so.
uint32 threadID
ThreadManager slot ID of the worker thread (0 until known).
bool shouldContinue
Loop-continuation flag; cleared by stop().
SSL/TLS-encrypted TCP connection (OpenSSL) with configurable peer verification.
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)
static bool DefaultAllowSelfSigned
friend THREAD_RET THREAD_FUNCTION_CALL SSLConnectionRun(THREAD_ARG arg)
bool disconnect(uint16 error=0)
Shut down the TLS session and close the socket.
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.
std::string verifyHostName
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.
static bool CreateThread(THREAD_FUNCTION func, void *args, uint32 &newID, uint32 reqID=0)
Create a new native thread and start it immediately.
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.
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.
uint64 GetTimeNow()
Return the current absolute time (µs since year 0) according to the TMC.
int32 GetTimeAgeMS(uint64 t)
Age of a timestamp relative to now, in milliseconds.
int64 GetTimeAge(uint64 t)
Age of a timestamp relative to now.
bool Sleep(uint32 ms)
Suspend the calling thread.
const char * stristr(const char *str, const char *substr, uint32 len=0)
Case-insensitive strstr.
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
THREAD_RET THREAD_FUNCTION_CALL SSLConnectionRun(THREAD_ARG arg)
bool AESCheckBufferForCompatibility(const char *buffer, uint32 length)
bool SSLCheckBufferForCompatibility(const char *buffer, uint32 length)