CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
NetworkConnections.cpp
Go to the documentation of this file.
1
9#ifndef WINDOWS
10 #include <arpa/inet.h>
11#endif // WINDOWS
12#if defined(_USE_SSL_) && defined(WINDOWS)
13 // CryptoAPI: used to import the Windows ROOT certificate store into
14 // OpenSSL's X509_STORE (OpenSSL's default verify paths point at the
15 // build-time OPENSSLDIR, which does not exist on end-user machines).
16 #include <wincrypt.h>
17 // wincrypt.h defines macros that collide with OpenSSL type names.
18 #undef X509_NAME
19 #undef X509_EXTENSIONS
20 #undef X509_CERT_PAIR
21 #undef PKCS7_SIGNER_INFO
22 #undef OCSP_REQUEST
23 #undef OCSP_RESPONSE
24#endif // _USE_SSL_ && WINDOWS
25
26namespace cmlabs{
27
28#ifdef _USE_SSL_
29// Drain OpenSSL's thread-local error queue and route it through the CMSDK log
30// system instead of dumping it straight to stdout/stderr with
31// ERR_print_errors_fp(). Two reasons: (1) it keeps SSL diagnostics on the
32// normal LOG_NETWORK channel (respecting log level and receiver), so the unit
33// test harness - which silences the log in non-verbose mode - no longer shows
34// raw OpenSSL lines from the negative-path verify tests; (2) real failures are
35// still visible when network logging is enabled. @param level LogPrint level.
36static void LogSSLErrors(const char* context, int level) {
37 unsigned long e;
38 bool any = false;
39 char buf[256];
40 while ((e = ERR_get_error()) != 0) {
41 ERR_error_string_n(e, buf, sizeof(buf));
42 LogPrint(0, LOG_NETWORK, level, "SSL: %s: %s", context ? context : "error", buf);
43 any = true;
44 }
45 if (!any)
46 LogPrint(0, LOG_NETWORK, level, "SSL: %s (no OpenSSL error detail)", context ? context : "error");
47}
48#endif // _USE_SSL_
49
51// SSL Encryption Protocol
53
54bool SSLCheckBufferForCompatibility(const char* buffer, uint32 length) {
55 if (length < 14)
56 return false;
57 return ( utils::stristr(buffer, "ClientVersion ") == buffer );
58}
59
60bool AESCheckBufferForCompatibility(const char* buffer, uint32 length) {
61 if (length < 14)
62 return false;
63 return ( utils::stristr(buffer, "xxxxxxxxx ") == buffer );
64}
65
66
69
70 encryption = NOENC;
71 localAddress = 0;
72 threadID = 0;
73 lastActivity = 0;
74 socket = INVALID_SOCKET;
75 receiver = NULL;
76 dataReceiver = NULL;
77}
78
80 disconnect();
81 localAddress = 0;
82 threadID = 0;
83 lastActivity = 0;
84 socket = INVALID_SOCKET;
85 receiver = NULL;
86 dataReceiver = NULL;
87}
88
89
90void TCPListener::disconnectInternal(uint16 error) {
91 stop();
92 if (socket != INVALID_SOCKET) {
93 shutdown(socket, SD_BOTH);
94 closesocket(socket);
95 socket = INVALID_SOCKET;
96 }
97 if (receiver && error)
98 receiver->registerError(error, this);
99}
100
101bool TCPListener::disconnect(uint16 error) {
102 mutex.enter(1000);
103 disconnectInternal(error);
104 mutex.leave();
105 return true;
106}
107
109 return (socket != INVALID_SOCKET);
110}
111
112bool TCPListener::init(uint16 port, uint8 encryption, NetworkConnectionReceiver* receiver, NetworkDataReceiver* dataReceiver) {
113 if (port == 0) {
114 LogPrint(0, LOG_NETWORK, 0, "Could not start TCPListener on port 0...");
115 return false;
116 }
117
118 mutex.enter(1000);
119 this->encryption = encryption;
120 memcpy(((char*)&localAddress)+sizeof(uint32), &port, sizeof(uint16));
121 // Open TCP port
122
123 // Setup listening on port node->networkPort
124 if((socket=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){
125 LogPrint(0, LOG_NETWORK, 0, "Could not create TCPListener socket (%d)...", utils::GetLastOSErrorNumber());
126 mutex.leave();
127 return false;
128 }
129
130 #ifdef WINDOWS
131 // Set the exclusive address option, preventing other software binding to
132 // non-INADDR_ANY (i.e. interface addresses such as localhost directly)
133 int one = 1;
134 setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *) &one, sizeof(one));
135 #else
136 /*
137 This socket option tells the kernel that even if this port is busy (in
138 the TIME_WAIT state), go ahead and reuse it anyway. If it is busy,
139 but with another state, you will still get an address already in use
140 error. It is useful if your server has been shut down, and then
141 restarted right away while sockets are still active on its port. You
142 should be aware that if any unexpected data comes in, it may confuse
143 your server, but while this is possible, it is not likely.
144 */
145 int one = 1;
146 setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,&one,sizeof(one));
147 #endif
148
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);
153
154 if(bind(socket,(SOCKADDR*)&addr,sizeof(struct sockaddr_in))==SOCKET_ERROR){
155 LogPrint(0, LOG_NETWORK, 0, "Could not create TCPListener on port %u...", port);
156 disconnectInternal(0);
157 mutex.leave();
158 return false;
159 }
160
161 // Set blocking mode
163
164 if(listen(socket,SOMAXCONN)==SOCKET_ERROR){
165 disconnectInternal(0);
166 mutex.leave();
167 return false;
168 }
169
170 if (receiver != NULL) {
171 this->receiver = receiver;
172 // Start networking thread
174 LogPrint(0, LOG_NETWORK, 0, "Could not start TCPListener thread...");
175 disconnectInternal(0);
176 mutex.leave();
177 return false;
178 }
179 }
180 this->dataReceiver = dataReceiver;
181
182 LogPrint(0, LOG_NETWORK, 3, "Started TCPListener thread on port %u...", port);
183 mutex.leave();
184 return true;
185}
186
188 return localAddress;
189}
190
191bool TCPListener::setSSLCertificate(const char* sslCertPath, const char* sslKeyPath) {
192 this->sslCertPath = sslCertPath;
193 this->sslKeyPath = sslKeyPath;
194 return true;
195}
196
198 SOCKET new_sock;
199 TCPConnection* newCon;
200 #ifdef _USE_SSL_
201 SSLConnection* sslCon;
202 #endif // _USE_SSL_
203 uint64 start = GetTimeNow(), timespent;
204
205 while ( (timespent = (GetTimeNow() - start)/1000) < timeout) {
206 // Listen for incoming connections
207 mutex.enter(1000);
208 new_sock = accept(socket, NULL, NULL);
209
210 if ((int) new_sock < 0) {
211 int err = utils::GetLastOSErrorNumber();
212 mutex.leave();
213 if ( (err == SOCKETWOULDBLOCK) || (err == SOCKETTRYAGAIN) ) {
214 // No connection available right now, continue waiting
215 utils::WaitForSocketReadability(socket, (uint32)(timeout-timespent));
216 // printf("[%u] ", GETIPPORT(localAddress));
217 }
218 else {
219 LogPrint(0, LOG_NETWORK, 2, "Shutting down network listener with error code: %d", new_sock);
220 // Socket error, disconnect and exit
221 #ifdef WINDOWS
222 if (err != WSAENOTSOCK)
223 #endif
225 return NULL;
226 }
227 }
228 else {
229 mutex.leave();
230 // We have a winner!
231 // Check for encryption
232 #ifdef _USE_SSL_
233 if (encryption == SSLENC) {
234 LogPrint(0, LOG_NETWORK, 2, "Accepting incoming TCP SSL connection...");
235 sslCon = new SSLConnection();
236 if (!sslCon->init(sslCertPath.c_str(), sslKeyPath.c_str())) {
237 shutdown(new_sock, SD_BOTH);
238 closesocket(new_sock);
239 delete(sslCon);
240 sslCon = NULL;
241 LogPrint(0, LOG_NETWORK, 2, "Failed initing incoming TCP SSL connection...");
242 continue;
243 }
244 LogPrint(0, LOG_NETWORK, 2, "SSL connection initialised");
245 if (!sslCon->connect(new_sock, localAddress, dataReceiver)) {
246 delete(sslCon);
247 sslCon = NULL;
248 LogPrint(0, LOG_NETWORK, 2, "Failed connecting incoming TCP SSL connection...");
249 continue;
250 }
251 LogPrint(0, LOG_NETWORK, 5, "Successfully accepted incoming TCP SSL connection");
252 return sslCon;
253 }
254 else if (encryption == AESENC) {
255 }
256 else {
257 #endif // _USE_SSL_
258 lastActivity = GetTimeNow();
259 newCon = new TCPConnection();
260 // LogPrint(0, LOG_NETWORK, 1, "Incoming connection: %d... ", (int)new_sock);
261 if (!newCon->connect(new_sock, localAddress, dataReceiver)) {
262 //printf("FAILED\n");
263 LogPrint(0, LOG_NETWORK, 2, "Failed connecting incoming TCP connection...");
264 delete(newCon);
265 }
266 else {
267 //printf("SUCCESS\n");
268 LogPrint(0, LOG_NETWORK, 5, "Successfully accepted incoming TCP connection");
269 return newCon;
270 }
271 #ifdef _USE_SSL_
272 }
273 #endif // _USE_SSL_
274 }
275 }
276 return NULL;
277}
278
279
280bool TCPListener::run() {
282
283 if (receiver == NULL)
284 return false;
285
286 isRunning = true;
287 while (shouldContinue) {
288 if ( (con = acceptConnection(100)) != NULL) {
289 if (receiver != NULL)
290 receiver->receiveNetworkConnection(con);
291 else
292 delete(con);
293 }
294 }
295 isRunning = false;
296 return true;
297}
298
299
300
301
302
303
304
305
308
309 type = 0;
310 localAddress = 0;
311 remoteAddress = 0;
312 threadID = 0;
313 lastActivity = 0;
315 remote = false;
317 bufferLen = 0;
318 buffer = NULL;
321 receiver = NULL;
325 greetingData = NULL;
326 greetingSize = 0;
327 // Defence-in-depth for teardown: if a force-cancel path ever survives the
328 // cooperative-only shutdown, the cancel must not land while a worker holds
329 // this buffer mutex (freed by delete(con) -> UAF in the trailing leave()).
330 // setCancelSafe stores its state OUT-OF-LINE, so sizeof(Mutex) and the
331 // layout of NetworkConnection stay byte-identical (required: embedded by
332 // value in layout-sensitive/SWIG-wrapped types).
333 mutex.setCancelSafe(true);
334}
335
337 //printf("~NetworkConnection(%p)\n", this); fflush(stdout);
338 disconnect();
339 localAddress = 0;
340 remoteAddress = 0;
341 threadID = 0;
342 lastActivity = 0;
344 remote = false;
345 if (buffer != NULL)
346 delete [] buffer;
347 bufferLen = 0;
350 receiver = NULL;
351 buffer = NULL;
352 if (greetingData)
353 // delete [], not delete: allocated with new char[size] in setGreetingData().
354 // Scalar delete on an array allocation is an alloc-dealloc mismatch -
355 // undefined behaviour, reported by ASan.
356 delete [] greetingData;
357 greetingData = NULL;
358 greetingSize = 0;
359}
360
361bool NetworkConnection::setGreetingData(const char* data, uint32 size) {
362 if (greetingData)
363 // delete [], not delete: new char[] below (matches the destructor at :353).
364 delete [] greetingData;
365 if (!data)
366 greetingData = NULL;
367 else {
368 greetingData = new char[size];
369 memcpy(greetingData, data, size);
370 }
371 greetingSize = size;
372 return true;
373}
374
375
377 connectTimeoutMS = timeoutMS;
378 return true;
379}
380
384
386 return remote;
387}
388
390 LogPrint(0, LOG_NETWORK, 5, "Shutting down network connection with code: %u", error);
391 stop();
392 if (socket != INVALID_SOCKET) {
393 shutdown(socket, SD_BOTH);
394 try {
396 }
397 catch (...) {}
399 }
400 // NOTE: do NOT clear bufferContentLen/Pos here - a peer that closes right
401 // after replying (HTTP Connection: close) must not wipe the buffered reply.
402 if (receiver && error)
403 receiver->registerError(error, this);
404}
405
407 mutex.enter(1000);
408 disconnectInternal(error);
409 mutex.leave();
410 return true;
411}
412
414 if (len < 128) return false;
415 char* newBuffer = new char[len];
420 }
421 else {
424 }
425
426 if (buffer != NULL)
427 delete [] buffer;
428 bufferLen = len;
429 buffer = newBuffer;
430 return true;
431}
432
433//int32 NetworkConnection::peekStream() {
434//
435// mutex.enter();
436//
437// // and read from the socket
438// int count = ::recvfrom(socket,buffer+bufferContentLen,bufferLen-bufferContentLen,MSG_PEEK,NULL,0);
439// if(count==SOCKET_ERROR) {
440// int err = utils::GetLastOSErrorNumber();
441// mutex.leave();
442// if ( (err == SOCKETWOULDBLOCK) || (err == SOCKETTRYAGAIN) )
443// return 0;
444// else {
445// disconnect(NETWORKERROR_RECEIVE);
446// return -1;
447// }
448// }
449// mutex.leave();
450// return count;
451//}
452
454
455 // Assume that the mutex is locked
456 // LogPrint(0,0,0,"<<<<<<< READINTOBUFFER <<<<<<<<\n");
457
458#ifdef TCPCON_PRINT_DEBUG
459 uint64 start = GetTimeNow();
460#endif
461 int c = 0;
462 int32 count = 0;
463 // The socket is put in non-blocking mode once at connect/accept and is never
464 // flipped back (see TCPConnection::send), so we no longer re-set it here -
465 // that was two fcntl() syscalls on every read of the receive hot path.
466 // Read from the socket while data is still available
467 bool datagram = (type == UDPCON);
468 do {
469 //LogPrint(0,0,0,"<<<<<<< READINTOBUFFER RECVFROM start <<<<<<<<\n");
470 if (datagram) {
471 // UDP: one datagram per call, with its sender. A datagram larger than the free
472 // space is truncated by the OS, so make room for the largest possible one first.
475 if (bufferLen - bufferContentLen < 65536) {
476 if (bufferContentPos) {
480 }
481 if (bufferLen - bufferContentLen < 65536)
482 resizeBuffer(bufferContentLen + 65536 + 1024);
483 }
484 sockaddr_in from;
485 memset(&from, 0, sizeof(from));
486 #ifdef WINDOWS
487 int fromLen = sizeof(from);
488 #else
489 socklen_t fromLen = sizeof(from);
490 #endif
491 c = ::recvfrom(socket, buffer + bufferContentLen, bufferLen - bufferContentLen, 0, (sockaddr*)&from, &fromLen);
492 if (c > 0) {
493 // Packed as UDPConnection::send() unpacks a destination: IPv4 in the low
494 // 4 bytes (network order, as sin_addr), host-order port in the next 2.
495 uint64 src = 0;
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));
499 remoteAddress = src;
500 }
501 }
502 else
504 // c = ::recv(socket,buffer+bufferContentLen,bufferLen-bufferContentLen,0);
505 // LogPrint(0,0,0,"<<<<<<< READINTOBUFFER RECVFROM end %d <<<<<<<<\n", c);
506 if(c==SOCKET_ERROR) {
507 int err = utils::GetLastOSErrorNumber();
508 if ( (err == SOCKETWOULDBLOCK) || (err == SOCKETTRYAGAIN) )
509 break;
510 #ifdef WINDOWS
511 // UDP on Windows: an ICMP "port unreachable" for an earlier datagram surfaces as WSAECONNRESET on the next
512 // recvfrom; and a datagram larger than the buffer as WSAEMSGSIZE. Neither means the socket is broken.
513 else if (datagram && ((err == WSAECONNRESET) || (err == WSAEMSGSIZE)))
514 continue;
515 #endif
516 else {
517 if (datagram)
518 LogPrint(0, LOG_NETWORK, 1, "UDP receive error %d - socket dropped", err);
519 #ifdef WINDOWS
520 if (err != WSAENOTSOCK)
521 #endif
523 return -1;
524 }
525 }
526 if (!c && datagram)
527 break; // a zero-length datagram, not a closed socket (UDP has no connection to close)
528 if (!c) {
529 bool dataAvailable = utils::WaitForSocketReadability(socket, (uint32)(10));
530 if (dataAvailable) {
531 // this indicates that the socket is in a CLOSE_WAIT state,
532 // i.e. the other end has closed the socket so we should too...
533 LogPrint(0, LOG_NETWORK, 2, "*** SOCKET DISCONNECT DETECTED ***\n");
535 }
536 }
537
538 if (c) {
539 //rounds++;
540 count += c;
541 bufferContentLen += c;
542
543 if (bufferLen-bufferContentLen < 512) {
545 //printf("x"); fflush(stdout);
549 }
550 else {
551 //printf("o"); fflush(stdout);
553 }
554 //resize++;
555 }
556 }
557 if (datagram && c > 0)
558 break; // keep remoteAddress true for the message parsed from this datagram
559 } while (c > 0);
560
561 #ifdef TCPCON_PRINT_DEBUG
562 if (this->type == TCPCON) {
563 if (count) {
564 char* tmp = new char[count+1];
565 memcpy(tmp, buffer+bufferContentLen-count, count);
566 tmp[count] = 0;
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);
568 delete [] tmp;
569 }
570 else {
571 // LogPrint(0,LOG_NETWORK,0,"<<<<<<< READINTOBUFFER <<<<<<<< NOTHING\n");
572 }
573 }
574 #endif
575
576 #ifdef UDPCON_PRINT_DEBUG
577 if (this->type == UDPCON) {
578 if (count) {
579 char* tmp = new char[count+1];
580 memcpy(tmp, buffer+bufferContentLen-count, count);
581 tmp[count] = 0;
582 LogPrint(0,LOG_NETWORK,0,"<<<<<<< READINTOBUFFER <<<<<<<< UDP RECV BUF %u bytes '%s'\n", count, tmp);
583 delete [] tmp;
584 }
585 else {
586 // LogPrint(0,LOG_NETWORK,0,"<<<<<<< READINTOBUFFER <<<<<<<< UDP NOTHING\n");
587 }
588 }
589 #endif
590
591 return count;
592}
593
594bool NetworkConnection::receiveAvailable(char* data, uint32& size, uint32 maxSize, uint32 timeout, bool peek) {
595
596 mutex.enter(1000);
597 if (maxSize > bufferLen-bufferContentLen) {
598 if (bufferContentLen + bufferContentPos > maxSize) {
602 }
603 else
605 }
606
607 uint64 start = GetTimeNow();
608 uint32 count = 0;
609 bool dataAvailable;
610
611 int32 c = readIntoBuffer();
612 if (c < 0 && bufferContentLen - bufferContentPos == 0) {
613 mutex.leave();
614 return false;
615 }
616
617 if (timeout > 0) {
618
619 // Wait for full size to be available, if not already
620 int32 timespent = 0;
621 if (bufferContentLen - bufferContentPos < maxSize) {
622 while (true) {
623 mutex.leave();
624 dataAvailable = utils::WaitForSocketReadability(socket, (uint32)(timeout-timespent));
625 mutex.enter(1000);
626 if ((c = readIntoBuffer()) < 0) {
628 break; // connection gone, but serve what we already buffered
629 mutex.leave();
630 return false;
631 }
632 if (!c && dataAvailable) {
633 // this indicates that the socket is in a CLOSE_WAIT state,
634 // i.e. the other end has closed the socket so we should too...
635 LogPrint(0, LOG_NETWORK, 2, "*** SOCKET DISCONNECT DETECTED ***\n");
637 }
638 if (bufferContentLen - bufferContentPos >= maxSize)
639 break;
640 if ((timespent = GetTimeAgeMS(start)) >= (int32)timeout)
641 break;
642 }
643 }
644 }
645
647 if (size > maxSize)
648 size = maxSize;
649
650 inputBytes += size;
651 if ( size > 0 ) {
652 memcpy(data, buffer+bufferContentPos, size);
653 if (!peek) {
654 bufferContentPos += size;
657 }
658 }
659 mutex.leave();
660 return true;
661}
662
663bool NetworkConnection::receive(char* data, uint32 size, uint32 timeout, bool peek) {
664 // Exact-size, timeout-bounded read from the shared receive buffer. The
665 // buffer mutex makes this safe against the connection's reader thread;
666 // while more bytes are needed the mutex is RELEASED around the
667 // WaitForSocketReadability() select() so writers/other readers are not
668 // blocked for the whole timeout. With peek=true the bytes are copied but
669 // left in the buffer — protocol handlers use this to sniff frame headers
670 // (e.g. MessageProtocol peeks size+id before allocating the body buffer).
671
672 mutex.enter(1000);
673
674 uint64 start = GetTimeNow();
675
676 // Only read from the socket if we don't already have enough buffered. A single
677 // readIntoBuffer() drains everything currently available - often the whole
678 // message, or several pipelined messages, in one go - so the body read (and
679 // subsequent messages) are then served straight from the buffer with no
680 // recvfrom() syscall at all. Previously readIntoBuffer() ran on every receive()
681 // regardless, costing a wasted syscall per peek and per body read.
682 if (bufferContentLen - bufferContentPos < size) {
683 int32 c = readIntoBuffer();
684 if (c < 0) {
685 mutex.leave();
686 return false;
687 }
688
689 // Wait for the full size to be available, if not already.
690 int32 timespent = 0;
691 while (bufferContentLen - bufferContentPos < size) {
692 mutex.leave();
693 utils::WaitForSocketReadability(socket, (uint32)(timeout-timespent));
694 mutex.enter(1000);
695 if ((c = readIntoBuffer()) < 0) {
696 mutex.leave();
697 return false;
698 }
700 break;
701 if ((timespent = GetTimeAgeMS(start)) >= (int32)timeout) {
702 mutex.leave();
703 return false;
704 }
705 }
706 }
707
708 // LogPrint(0,LOG_NETWORK,0,"Receiving %u (buffer %u) bytes via network...", size, bufferContentLen - bufferContentPos);
709 //printf("**************** Buffer ok (%u, %u = %u->%u), left (%u), size (%u), next %u, %u ****************\n",
710 // bufferLen, bufferContentLen - bufferContentPos, bufferContentPos, bufferContentLen,
711 // bufferLen-bufferContentLen+bufferContentPos, size,
712 // *(uint32*)(buffer+bufferContentPos), *(uint32*)(buffer+bufferContentPos+4));
713
714 int64 t = GetTimeAge(start);
715 if (t > 0)
716 inputSpeed = (uint32)(size*1000000.0/(double)t);
717 inputBytes += size;
718
719 memcpy(data, buffer+bufferContentPos, size);
720 if (!peek) {
721 bufferContentPos += size;
724 }
725 mutex.leave();
726 return true;
727}
728
729bool NetworkConnection::discard(uint32 size) {
730 mutex.enter(1000);
732 if (bufferContentLen - bufferContentPos >= size) {
733 bufferContentPos += size;
736 inputBytes += size;
737 mutex.leave();
738 return true;
739 }
740 else {
741 mutex.leave();
742 return false;
743 }
744}
745
747 mutex.enter(1000);
750 if (c) {
751 LogPrint(0,LOG_NETWORK,3,"Cleared %u chars from buffer...", c);
752 // if (c > 1)
753 // utils::PrintBinary(buffer+bufferContentPos, c, false, "Cleared Buffer Content");
754 }
756 inputBytes += c;
757 mutex.leave();
758 return c;
759}
760
761
764 return true;
765 else {
767 }
768}
769
773
774
776
777 if (socket == INVALID_SOCKET)
778 return false;
779 // UDP has no connection to lose: an open socket is "connected". Peeking 1 byte of a queued datagram fails on
780 // Windows with WSAEMSGSIZE (and with WSAECONNRESET after an ICMP), and that closed the socket as dead in the
781 // middle of a burst (udpservice: 0 of 1000 replies, 16 Nov 2026).
782 if (type == UDPCON)
783 return true;
784
785 char peekBuffer[1];
786 // First use the socket a bit
787 if (!mutex.enter(1000))
788 return false;
789
791 int res = recv(socket, peekBuffer, 1, MSG_PEEK);
792 if (res > 0) {
793 mutex.leave();
794 return true;
795 }
796 else if (res < 0) {
797 int err = utils::GetLastOSErrorNumber();
798 // UDP needs TRYAGAIN
799 if (err == SOCKETWOULDBLOCK) {
800 mutex.leave();
801 return true;
802 }
803
804 #ifdef WINDOWS
805 else if ((type == UDPCON) && (err == SOCKETTRYAGAIN)) {
806 mutex.leave();
807 return true;
808 }
809 else if (err == WSAENOTCONN) {} // Windows needs this one...
810 else if (err == WSAENOTSOCK) {} // Windows needs this one...
811 else if (err == WSAEOPNOTSUPP) {} // WinCE may need this one...???.
812 #else
813 else if (err == SOCKETTRYAGAIN) {
814 mutex.leave();
815 return true;
816 }
817 #endif //WINDOWS
818 else {
819 // Error will be handled by the caller
821 mutex.leave();
822 return false;
823 }
824 // mutex.leave();
825 }
826 else { // if err == 0
827 // Error will be handled by the caller
829 mutex.leave();
830 return false;
831 }
832
833 struct timeval tv;
834 tv.tv_sec = 0;
835 tv.tv_usec = 10;
836
837 int maxfd = 0;
838 fd_set wfds;
839 // create a list of sockets to check for activity
840 FD_ZERO(&wfds);
841 // specify socket
842 FD_SET(socket, &wfds);
843
844 mutex.leave();
845
846 #ifdef WINDOWS
847 int len;
848 #else
849 #ifdef Darwin
850 #if GCC_VERSION < 40000
851 int len;
852 maxfd = socket + 1;
853 #else
854 socklen_t len;
855 maxfd = socket + 1;
856 #endif // GCC_VERSION < 40000
857 #else
858 socklen_t len;
859 maxfd = socket + 1;
860 #endif
861 #endif
862
863 if (timeout > 0) {
864 ldiv_t d = ldiv(timeout*1000, 1000000);
865 tv.tv_sec = d.quot;
866 tv.tv_usec = d.rem;
867 }
868
869 // Check for writability
870 res = select(maxfd, NULL, &wfds, NULL, &tv);
871
872 if (res <= 0)
873 return false;
874
875 //printf("wait res > 0\n");
876
877 int error;
878 len = sizeof(error);
879
880 if (!mutex.enter(1000))
881 return false;
882
883 if (FD_ISSET(socket, &wfds) != 0) {
884 if (getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len) != 0) {
885
886 int wsaError = utils::GetLastOSErrorNumber();
887 mutex.leave();
888 if (wsaError == 0) {
889 // No error, just unable to send...
890 return true;
891 }
892 #ifdef WINDOWS
893 else if (wsaError == WSAENETDOWN ) {
894 return false;
895 }
896 else if (wsaError == WSAEFAULT ) {
897 return false;
898 }
899 else if (wsaError == WSAEINPROGRESS ) {
900 return false;
901 }
902 else if (wsaError == WSAEINVAL ) {
903 return false;
904 }
905 else if (wsaError == WSAENOPROTOOPT ) {
906 if (error == 0) {
907 return true;
908 }
909 }
910 else if (wsaError == WSAENOTSOCK ) {
911 return false;
912 }
913 #endif
914 return false;
915 }
916 mutex.leave();
917 if (error == 0)
918 return true;
919 }
920 else
921 mutex.leave();
922
923 return false;
924}
925
927 struct timeval tv;
928 tv.tv_sec = 0;
929 tv.tv_usec = 10;
930
931 int maxfd = 0;
932 fd_set wfds;
933 // create a list of sockets to check for activity
934 FD_ZERO(&wfds);
935 // specify socket
936 FD_SET(s, &wfds);
937
938
939 #ifdef WINDOWS
940 int len;
941 #else
942 #ifdef Darwin
943 #if GCC_VERSION < 40000
944 int len;
945 maxfd = s + 1;
946 #else
947 socklen_t len;
948 maxfd = s + 1;
949 #endif // GCC_VERSION < 40000
950 #else
951 socklen_t len;
952 maxfd = s + 1;
953 #endif
954 #endif
955
956 if (timeout > 0) {
957 ldiv_t d = ldiv(timeout * 1000, 1000000);
958 tv.tv_sec = d.quot;
959 tv.tv_usec = d.rem;
960 }
961
962 // Check for writability
963 int res = select(maxfd, NULL, &wfds, NULL, &tv);
964
965 if (res <= 0)
966 return false;
967
968 //printf("wait res > 0\n");
969
970 int error;
971 len = sizeof(error);
972
973 if (FD_ISSET(s, &wfds) != 0) {
974 if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char*)&error, &len) != 0) {
975
976 int wsaError = utils::GetLastOSErrorNumber();
977 if (wsaError == 0) {
978 // No error, just unable to send...
979 return true;
980 }
981 #ifdef WINDOWS
982 else if (wsaError == WSAENETDOWN) {
983 return false;
984 }
985 else if (wsaError == WSAEFAULT) {
986 return false;
987 }
988 else if (wsaError == WSAEINPROGRESS) {
989 return false;
990 }
991 else if (wsaError == WSAEINVAL) {
992 return false;
993 }
994 else if (wsaError == WSAENOPROTOOPT) {
995 if (error == 0) {
996 return true;
997 }
998 }
999 else if (wsaError == WSAENOTSOCK) {
1000 return false;
1001 }
1002 #endif
1003 return false;
1004 }
1005 if (error == 0)
1006 return true;
1007 }
1008 return false;
1009}
1010
1012
1013 if (socket == INVALID_SOCKET)
1014 return false;
1015
1016 // First use the socket a bit
1017 if (!mutex.enter(1000))
1018 return false;
1019
1020 struct timeval tv;
1021 tv.tv_sec = 0;
1022 tv.tv_usec = 10;
1023
1024 int maxfd = 0;
1025 fd_set wfds;
1026 // create a list of sockets to check for activity
1027 FD_ZERO(&wfds);
1028 // specify socket
1029 FD_SET(socket, &wfds);
1030
1031 mutex.leave();
1032
1033 #ifdef WINDOWS
1034 int len;
1035 #else
1036 #ifdef Darwin
1037 #if GCC_VERSION < 40000
1038 int len;
1039 maxfd = socket + 1;
1040 #else
1041 socklen_t len;
1042 maxfd = socket + 1;
1043 #endif // GCC_VERSION < 40000
1044 #else
1045 socklen_t len;
1046 maxfd = socket + 1;
1047 #endif
1048 #endif
1049
1050 if (timeout > 0) {
1051 ldiv_t d = ldiv(timeout * 1000, 1000000);
1052 tv.tv_sec = d.quot;
1053 tv.tv_usec = d.rem;
1054 }
1055
1056 // Check for writability
1057 int res = select(maxfd, NULL, &wfds, NULL, &tv);
1058
1059 if (res <= 0)
1060 return false;
1061
1062 //printf("wait res > 0\n");
1063
1064 int error;
1065 len = sizeof(error);
1066
1067 mutex.enter(1000);
1068 if (FD_ISSET(socket, &wfds) != 0) {
1069 if (getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len) != 0) {
1070
1071 int wsaError = utils::GetLastOSErrorNumber();
1072 mutex.leave();
1073 if (wsaError == 0) {
1074 // No error, just unable to send...
1075 return true;
1076 }
1077#ifdef WINDOWS
1078 else if (wsaError == WSAENETDOWN) {
1079 return false;
1080 }
1081 else if (wsaError == WSAEFAULT) {
1082 return false;
1083 }
1084 else if (wsaError == WSAEINPROGRESS) {
1085 return false;
1086 }
1087 else if (wsaError == WSAEINVAL) {
1088 return false;
1089 }
1090 else if (wsaError == WSAENOPROTOOPT) {
1091 if (error == 0) {
1092 return true;
1093 }
1094 }
1095 else if (wsaError == WSAENOTSOCK) {
1096 return false;
1097 }
1098#endif
1099 return false;
1100 }
1101 mutex.leave();
1102 if (error == 0)
1103 return true;
1104 }
1105 else
1106 mutex.leave();
1107
1108 return false;
1109}
1110
1112 if (receiver == NULL)
1113 return false;
1114
1115 uint32 size;
1116 uint32 buflen = INITIALBUFFERSIZE;
1117 char* myBuffer = (char*) malloc(buflen);
1118 if (myBuffer == NULL)
1119 return false;
1120
1121 LogPrint(0, LOG_NETWORK, 2, "Incoming network connection from %u.%u.%u.%u:%u, started run...",
1123
1124 isRunning = true;
1125 while (shouldContinue) {
1126 if (receive((char*)&size, sizeof(size), 50, true)) {
1127
1128 if (buflen < size) {
1129 buflen = size;
1130 myBuffer = (char*) realloc(myBuffer, buflen);
1131 if (myBuffer == NULL) {
1132 isRunning = false;
1134 return false;
1135 }
1136 }
1137
1138 // Receive the full data structure
1139 if (!receive(myBuffer, size, 500)) {
1140 isRunning = false;
1141 free(myBuffer);
1142 // Error already reported & already disconnected
1143 return false;
1144 }
1145
1146 if (receiver) {
1147 receiver->receiveData(myBuffer, size, this);
1148 }
1149 }
1150 }
1151 isRunning = false;
1152 free(myBuffer);
1153 return true;
1154}
1155
1159
1161 return inputSpeed;
1162}
1163
1165 return type;
1166}
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1182
1185
1187 // Setup socket
1188 mutex.enter(1000);
1189 if((socket=::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==INVALID_SOCKET){
1190 LogPrint(0, LOG_NETWORK, 0, "Could not create UDPConnection socket...");
1192 mutex.leave();
1193 return false;
1194 }
1195
1196 #ifdef WINDOWS
1197 // Set the exclusive address option, preventing other software binding to
1198 // non-INADDR_ANY (i.e. interface addresses such as localhost directly)
1199 int one = 1;
1200 setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *) &one, sizeof(one));
1201 #else
1202 /*
1203 This socket option tells the kernel that even if this port is busy (in
1204 the TIME_WAIT state), go ahead and reuse it anyway. If it is busy,
1205 but with another state, you will still get an address already in use
1206 error. It is useful if your server has been shut down, and then
1207 restarted right away while sockets are still active on its port. You
1208 should be aware that if any unexpected data comes in, it may confuse
1209 your server, but while this is possible, it is not likely.
1210 */
1211 int one = 1;
1212 setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,&one,sizeof(one));
1213 #endif
1214
1215 setsockopt(socket,SOL_SOCKET,SO_BROADCAST,(char*)&one,sizeof(one));
1216
1217 // Set blocking mode
1219
1220 mutex.leave();
1221 return true;
1222}
1223
1225 if (port == 0) {
1226 LogPrint(0, LOG_NETWORK, 0, "Could not start UDPConnection on port 0...");
1227 return false;
1228 }
1229
1230 memcpy(((char*)&localAddress)+sizeof(uint32), &port, sizeof(uint16));
1231 // Open UDP port
1232
1233 // Setup listening on port node->networkPort
1234 mutex.enter(1000);
1235 if((socket=::socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))==INVALID_SOCKET){
1236 LogPrint(0, LOG_NETWORK, 0, "Could not create UDPConnection socket...");
1238 mutex.leave();
1239 return false;
1240 }
1241
1242 #ifdef WINDOWS
1243 // Set the exclusive address option, preventing other software binding to
1244 // non-INADDR_ANY (i.e. interface addresses such as localhost directly)
1245 int one = 1;
1246 setsockopt(socket, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (char *) &one, sizeof(one));
1247 #else
1248 /*
1249 This socket option tells the kernel that even if this port is busy (in
1250 the TIME_WAIT state), go ahead and reuse it anyway. If it is busy,
1251 but with another state, you will still get an address already in use
1252 error. It is useful if your server has been shut down, and then
1253 restarted right away while sockets are still active on its port. You
1254 should be aware that if any unexpected data comes in, it may confuse
1255 your server, but while this is possible, it is not likely.
1256 */
1257 int one = 1;
1258 setsockopt(socket,SOL_SOCKET,SO_REUSEADDR,&one,sizeof(one));
1259 #endif
1260
1261 setsockopt(socket,SOL_SOCKET,SO_BROADCAST,(char*)&one,sizeof(one));
1262 // Room for a burst: a client draining its backlog after an outage sends far faster than one
1263 // reader thread wakes; the 212 KB Linux default overflowed at ~600 datagrams (UdpRcvbufErrors).
1264 {
1265 int rcvbuf = 4 * 1024 * 1024;
1266 setsockopt(socket, SOL_SOCKET, SO_RCVBUF, (char*)&rcvbuf, sizeof(rcvbuf));
1267 }
1268 #ifdef WINDOWS
1269 // Windows reports an ICMP "port unreachable" for an earlier datagram as WSAECONNRESET on this socket; turn that off
1270 // (SIO_UDP_CONNRESET), so one peer that went away cannot break the socket for every other peer.
1271 {
1272 BOOL reportReset = FALSE;
1273 DWORD bytes = 0;
1274 WSAIoctl(socket, _WSAIOW(IOC_VENDOR, 12), &reportReset, sizeof(reportReset), NULL, 0, &bytes, NULL, NULL);
1275 }
1276 #endif
1277
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);
1282
1283 if(bind(socket,(SOCKADDR*)&addr,sizeof(struct sockaddr_in))==SOCKET_ERROR){
1284 LogPrint(0, LOG_NETWORK, 0, "Could not create UDPConnection on port %u...", port);
1286 mutex.leave();
1287 return false;
1288 }
1289 LogPrint(0, LOG_NETWORK, 2, "Created UDPConnection on port %u...", port);
1290
1291 // Set blocking mode
1293
1294 if (receiver != NULL) {
1295 this->receiver = receiver;
1296 // Start networking thread
1298 LogPrint(0, LOG_NETWORK, 0, "Could not start UDPConnection thread...");
1300 mutex.leave();
1301 return false;
1302 }
1303 }
1304
1305 mutex.leave();
1306 return true;
1307}
1308
1309bool UDPConnection::send(const char* data, uint32 size, uint64 receiver) {
1310 uint64 start;
1311 sockaddr_in recvAddr;
1312 recvAddr.sin_family = AF_INET;
1313 int64 t;
1314
1315 if (!receiver && !defaultReceiver) {
1316 // this should broadcast ##############
1317 return false;
1318 }
1319 else {
1320 uint64 rec = receiver ? receiver : defaultReceiver;
1321 uint16 p = GETIPPORT(rec);
1322 recvAddr.sin_port = htons(p);
1323 memcpy(&recvAddr.sin_addr.s_addr, &rec, 4);
1324 if (!sendMutex.enter(500))
1325 return false;
1326 start = GetTimeNow();
1327
1328 uint32 pos = 0;
1329 int32 n;
1330
1331 while (true) {
1332 try {
1333 n = ::sendto(socket, data + pos, size - pos, 0, (SOCKADDR*)&recvAddr, sizeof(sockaddr_in));
1334 }
1335 catch (...) {
1336 // printf("--- UDP error sending reply (%u)...\n", size);
1338 sendMutex.leave();
1339 return false;
1340 }
1341 if (n == SOCKET_ERROR) {
1342 int err = utils::GetLastOSErrorNumber();
1343 // A full send buffer (a burst) is not an error: wait until it drains and send the same datagram again.
1344 // Disconnecting here killed the socket on Windows, where a 1000-datagram burst hits it at once
1345 // (udpservice: 0 of 1000 replies, 16 Nov 2026).
1346 if ((err == SOCKETWOULDBLOCK) || (err == SOCKETTRYAGAIN)) {
1347 if ((t = GetTimeAgeMS(start)) > 10000) {
1349 sendMutex.leave();
1350 return false;
1351 }
1353 continue;
1354 }
1355 #ifdef WINDOWS
1356 // ICMP "port unreachable" from an earlier datagram to a peer that has gone: the socket is fine
1357 if (err == WSAECONNRESET)
1358 continue;
1359 #endif
1360 LogPrint(0, LOG_NETWORK, 1, "UDP send error %d to port %u - socket dropped", err, (uint32)p);
1362 sendMutex.leave();
1363 return false;
1364 }
1365 pos += n;
1366 // Have we written everything?
1367 if (pos >= size)
1368 break;
1369 // else wait for writeability
1371 // check for ridiculous timeout
1372 if ((t = GetTimeAgeMS(start)) > 10000) {
1374 sendMutex.leave();
1375 return false;
1376 }
1377 // and go again
1378 }
1379 }
1380 t = GetTimeAge(start);
1381 if (t > 0)
1382 outputSpeed = (uint32)(size*1000000.0/(double)t);
1383 outputBytes += size;
1384 sendMutex.leave();
1385
1386 #ifdef UDPCON_PRINT_DEBUG
1387 if (size < 1024) {
1388 char* tmp = new char[size+1];
1389 memcpy(tmp, data, size);
1390 tmp[size] = 0;
1391 LogPrint(0,LOG_NETWORK,0,">>>>>>> SEND >>>>>>>> UDP Sent %u bytes '%s' to %u.%u.%u.%u:%u\n", size, tmp, GETIPADDRESSQUAD(receiver), GETIPPORT(receiver));
1392 delete [] tmp;
1393 }
1394 else {
1395 #ifdef UDPCON_PRINTBINARY_DEBUG
1396 char* tmp = new char[size+1];
1397 memcpy(tmp, data, size);
1398 tmp[size] = 0;
1399 LogPrint(0,LOG_NETWORK,0,">>>>>>> SEND >>>>>>>> UDP Sent %u bytes '%s'\n", size, tmp);
1400 delete [] tmp;
1401 #else
1402 char* tmp = new char[1024];
1403 memcpy(tmp, data, 1023);
1404 tmp[1023] = 0;
1405 LogPrint(0,LOG_NETWORK,0,">>>>>>> SEND >>>>>>>> UDP Sent %u bytes '%s' to %u.%u.%u.%u:%u\n", size, tmp, GETIPADDRESSQUAD(receiver), GETIPPORT(receiver));
1406 delete [] tmp;
1407 #endif
1408 }
1409 #endif
1410
1411 return true;
1412}
1413
1414bool UDPConnection::reconnect(uint32 timeoutMS) {
1415 disconnect();
1417}
1418
1421 return true;
1422}
1423
1425 return localAddress;
1426}
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1443
1446
1448 mutex.enter(1000);
1449 bufferContentLen = 0;
1450 bufferContentPos = 0;
1451 localAddress = localAddr;
1452
1453 socket = s;
1455
1456 // Set blocking mode
1458
1459 struct linger tmp = {1, 0};
1460 setsockopt(socket, SOL_SOCKET, SO_LINGER, (char *)&tmp, sizeof(tmp));
1461 int delay = 1;
1462 setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*) &delay, sizeof(delay));
1463 //char buffsize = 1;
1464 //setsockopt(socket, SOL_SOCKET, SO_SNDBUF, &buffsize, sizeof(buffsize));
1465 //buffsize = 1;
1466 //setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &buffsize, sizeof(buffsize));
1467
1468 LogPrint(0, LOG_NETWORK, 2, "Incoming TCP connection from %u.%u.%u.%u:%u, starting run...",
1470
1471 if (receiver != NULL) {
1472 this->receiver = receiver;
1473 // Start networking thread
1475 LogPrint(0, LOG_NETWORK, 0, "Could not start TCPConnection thread...");
1477 mutex.leave();
1478 return false;
1479 }
1480 }
1481
1482 remote = true;
1483 mutex.leave();
1484 return true;
1485}
1486
1487bool TCPConnection::connect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver* receiver) {
1488 // Timeout-aware connect, identical on Winsock and BSD sockets thanks to the
1489 // SOCKET/closesocket/GetLastOSErrorNumber abstractions: the socket is put
1490 // into non-blocking mode first, so ::connect() returns immediately with
1491 // EWOULDBLOCK/EINPROGRESS and didConnect() then select()-waits up to
1492 // timeoutMS for writability (= connection established). On success the
1493 // socket gets SO_LINGER {1,0} (hard close, RST instead of TIME_WAIT) and
1494 // TCP_NODELAY (no Nagle batching — vital for small request/reply frames).
1495 // Passing a NetworkDataReceiver switches the connection to push mode by
1496 // starting a dedicated reader thread (TCPConnectionRun).
1497
1498 // first create a temporary socket so we don't have to block the mutex while connecting
1499 SOCKET tempSocket;
1500
1501 if (timeoutMS) {
1502 if (!connectTimeoutMS)
1503 connectTimeoutMS = timeoutMS;
1504 }
1505 else
1506 timeoutMS = connectTimeoutMS;
1507
1508 if((tempSocket =::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){
1509 int retries = 0;
1510 int err = utils::GetLastOSErrorNumber();
1511 while ((err == SOCKETWOULDBLOCK) || (err == SOCKETTRYAGAIN)) {
1512 utils::Sleep(20);
1513 if ((tempSocket = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) != INVALID_SOCKET)
1514 break;
1516 retries++;
1517 if (retries > 10)
1518 break;
1519 }
1520 if (tempSocket == INVALID_SOCKET) {
1521 // mutex is not locked
1522 LogPrint(0, LOG_NETWORK, 0, "Could not create TCPConnection socket (%d)...", err);
1523 return false;
1524 }
1525 }
1526
1527 bufferContentLen = 0;
1528 bufferContentPos = 0;
1529
1530 // Set blocking mode
1532
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);
1537
1538 // Connect to the server
1539 int res;
1540 if ((res = ::connect(tempSocket, (struct sockaddr*)&saServer, sizeof(struct sockaddr))) != 0) {
1541 int err = utils::GetLastOSErrorNumber();
1542 if ( (err == SOCKETWOULDBLOCK) || (err == SOCKETTRYAGAIN) ) {
1543 if (!didConnect(tempSocket, timeoutMS)) {
1544 closesocket(tempSocket);
1545 return false;
1546 }
1547 }
1548 else {
1549 closesocket(tempSocket);
1550 return false;
1551 }
1552 }
1553
1554 // Set blocking mode
1555 // utils::SetSocketNonBlockingMode(socket);
1556
1557 struct linger tmp = {1, 0};
1558 setsockopt(tempSocket, SOL_SOCKET, SO_LINGER, (char *)&tmp, sizeof(tmp));
1559 int delay = 1;
1560 setsockopt(tempSocket, IPPROTO_TCP, TCP_NODELAY, (char*) &delay, sizeof(delay));
1561 //char buffsize = 1;
1562 //setsockopt(tempSocket, SOL_SOCKET, SO_SNDBUF, &buffsize, sizeof(buffsize));
1563 //buffsize = 1;
1564 //setsockopt(tempSocket, SOL_SOCKET, SO_RCVBUF, &buffsize, sizeof(buffsize));
1565
1566 // Now block the mutex
1567 if (!mutex.enter(1000)) {
1568 LogPrint(0, LOG_NETWORK, 0, "Could not lock connection mutex...");
1569 closesocket(tempSocket);
1570 return false;
1571 }
1572
1573 socket = tempSocket;
1574
1575 if (receiver != NULL) {
1576 this->receiver = receiver;
1577 // Start networking thread
1579 LogPrint(0, LOG_NETWORK, 0, "Could not start TCPConnection thread...");
1581 mutex.leave();
1582 return false;
1583 }
1584 }
1585
1586 remoteAddress = addr;
1587 remote = false;
1588
1589 mutex.leave();
1590 return true;
1591}
1592
1593bool TCPConnection::connect(const char* addr, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver) {
1594 // Resolve address
1595 uint32 address;
1596 if (!utils::LookupIPAddress(addr, address))
1597 return false;
1598 return connect(location = GETIPADDRESSPORT(address, port), timeoutMS, receiver);
1599}
1600
1601bool TCPConnection::connect(const uint32* addresses, uint16 addressCount, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver) {
1602 // Try all addresses
1603 for (uint16 n=0; n<addressCount; n++) {
1604 if (connect(location = GETIPADDRESSPORT(addresses[n], port), timeoutMS, receiver))
1605 return true;
1606 }
1607 return false;
1608}
1609
1610
1611bool TCPConnection::delayedConnect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver* receiver) {
1612 mutex.enter(1000);
1613
1614 connectTimeoutMS = timeoutMS;
1615 remoteAddress = addr;
1616 remote = false;
1617
1618 if (receiver != NULL) {
1619 this->receiver = receiver;
1620 // Start networking thread
1622 LogPrint(0, LOG_NETWORK, 0, "Could not start TCPConnection thread...");
1623 mutex.leave();
1624 return false;
1625 }
1626 }
1627
1628 mutex.leave();
1629 return true;
1630}
1631
1632bool TCPConnection::delayedConnect(const char* addr, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver) {
1633 // Resolve address
1634 uint32 address;
1635 if (!utils::LookupIPAddress(addr, address))
1636 return false;
1637 return delayedConnect(location = GETIPADDRESSPORT(address, port), timeoutMS, receiver);
1638}
1639
1640
1641//#define TCPCON_PRINT_DEBUG
1642
1643bool TCPConnection::send(const char* data, uint32 size, uint64 receiver) {
1644 // Ignore receiver, only for UDP
1645 // ### Consider splitting large data up into smaller chunks ###
1646 if (!size)
1647 return false;
1648 if (!sendMutex.enter(500))
1649 return false;
1650 uint64 start = GetTimeNow();
1651 // The socket stays in non-blocking mode (set once at connect/accept). We used
1652 // to flip it to blocking for the duration of the send and back to non-blocking
1653 // afterwards, which cost four fcntl() syscalls on every message AND raced with
1654 // the receive thread reading the same socket. Instead we drive the non-blocking
1655 // send loop directly and only wait for writeability when the kernel send buffer
1656 // is genuinely full (EWOULDBLOCK).
1657
1658 // Charles:
1659 //const char *data = (const char *) tdata;
1660 // IntT done = 0;
1661 // do {
1662 // int n = write(fd,&(data[done]),length - done);
1663 // if(n < 0) {
1664 // if(errno == EAGAIN || errno == EINTR) // Recoverable error?
1665 // continue;
1666 // return -1;
1667 // }
1668 // done += n;
1669 // } while(done < length);
1670 // return done;
1671
1672 int64 t;
1673 uint32 pos = 0;
1674 int32 n;
1675
1676 while (true) {
1677 try {
1678 n = ::send(socket, data + pos, size - pos, 0);
1679 }
1680 catch (...) {
1681 //printf("--- TCP error sending reply (%u) error: %u...\n", size, WSAGetLastError());
1683 sendMutex.leave();
1684 return false;
1685 }
1686 //n = ::send(socket, data + pos,
1687 // (size - pos>5120000) ? 5120000 : size - pos,
1688 // 0);
1689 if(n == SOCKET_ERROR) {
1690 int err = utils::GetLastOSErrorNumber();
1691 if ((err == SOCKETWOULDBLOCK) || (err == SOCKETTRYAGAIN)) {
1692 // Kernel send buffer is full - wait until it drains, then retry
1693 // the same chunk. Nothing has been consumed, so 'pos' is unchanged.
1694 if ((t = GetTimeAgeMS(start)) > 10000) {
1696 sendMutex.leave();
1697 return false;
1698 }
1700 continue;
1701 }
1702 //printf("--- TCP error sending reply (%u) error: %u...\n", size, WSAGetLastError());
1704 sendMutex.leave();
1705 return false;
1706 }
1707 pos += n;
1708 // Have we written everything?
1709 if (pos >= size)
1710 break;
1711 // check for ridiculous timeout
1712 if ((t = GetTimeAgeMS(start)) > 10000) {
1714 sendMutex.leave();
1715 return false;
1716 }
1717 // and go again
1718 }
1719
1720 t = GetTimeAge(start);
1721 if (t > 0)
1722 outputSpeed = (uint32)(size*1000000.0/(double)t);
1723 outputBytes += size;
1724 sendMutex.leave();
1725
1726 #ifdef TCPCON_PRINT_DEBUG
1727 if (size < 1024) {
1728 char* tmp = new char[size+1];
1729 memcpy(tmp, data, size);
1730 tmp[size] = 0;
1731 LogPrint(0,LOG_NETWORK,0,">>>>>>> SEND >>>>>>>> TCP Sent %u bytes (%.3f) '%s'\n", size, t/1000.0, tmp);
1732 delete [] tmp;
1733 }
1734 else {
1735 #ifdef TCPCON_PRINTBINARY_DEBUG
1736 char* tmp = new char[size+1];
1737 memcpy(tmp, data, size);
1738 tmp[size] = 0;
1739 LogPrint(0,LOG_NETWORK,0,">>>>>>> SEND >>>>>>>> TCP Sent %u bytes '%s'\n", size, tmp);
1740 delete [] tmp;
1741 #else
1742 char* tmp = new char[1024];
1743 memcpy(tmp, data, 1023);
1744 tmp[1023] = 0;
1745 LogPrint(0,LOG_NETWORK,0,">>>>>>> SEND >>>>>>>> TCP Sent %u bytes (%.3f) '%s'\n", size, t / 1000.0, tmp);
1746 delete [] tmp;
1747 #endif
1748 }
1749 #endif
1750
1751
1752// utils::Sleep(100);
1753 return true;
1754}
1755
1756
1757
1758bool TCPConnection::reconnect(uint32 timeoutMS) {
1759 disconnect();
1760 return connect(remoteAddress, timeoutMS, receiver);
1761}
1762
1763
1765
1766 if (socket == INVALID_SOCKET)
1767 return false;
1768
1769 struct sockaddr_in remoteAddr;
1770
1771 #ifdef WINDOWS
1772 int remoteAddrLen;
1773 #else
1774 #ifdef Darwin
1775 #if GCC_VERSION < 40000
1776 int remoteAddrLen;
1777 #else
1778 socklen_t remoteAddrLen;
1779 #endif // GCC_VERSION < 40000
1780 #else
1781 socklen_t remoteAddrLen;
1782 #endif
1783 #endif // WINDOWS
1784
1785 remoteAddrLen = sizeof(struct sockaddr_in);
1786
1787 if (getpeername(socket, (struct sockaddr*) &remoteAddr, &remoteAddrLen) != 0)
1788 return false;
1789
1790 uint32 address = remoteAddr.sin_addr.s_addr;
1791 if ( address == LOCALHOSTIP ) {
1792 // Get the actual local ip address, if possible
1793 utils::GetLocalIPAddress(address);
1794 }
1795 addr = GETIPADDRESSPORT(address, (uint16)remoteAddr.sin_port);
1796 return true;
1797}
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814bool IsSSLInitialised = false;
1815
1816#ifdef _USE_SSL_
1817#ifdef WINDOWS
1818 // #include "openssl/applink.c"
1819#endif
1820#endif
1821
1822
1824 type = SSLCON;
1828 #ifdef _USE_SSL_
1829 if (!IsSSLInitialised) {
1830 // Init SSL
1831 //CRYPTO_malloc_init();
1832 OpenSSL_add_all_algorithms();
1833 //ERR_load_BIO_strings();
1834 ERR_load_crypto_strings();
1835 SSL_load_error_strings();
1836
1837 certbio = BIO_new(BIO_s_file());
1838 outbio = BIO_new_fp(stdout, BIO_NOCLOSE);
1839
1840 SSL_library_init();
1841
1842 IsSSLInitialised = true;
1843 }
1844 ctx = NULL;
1845 ssl = NULL;
1846 #endif // _USE_SSL_
1847}
1848
1850 #ifdef _USE_SSL_
1851 mutex.enter(1000);
1852 if (ctx) {
1853 SSL_CTX_free(ctx);
1854 ctx = NULL;
1855 }
1856 mutex.leave();
1857 #else // _USE_SSL_
1858 #endif // _USE_SSL_
1859}
1860
1861// Process-wide default for client certificate verification. False = verify
1862// peers against the CA trust store (secure by default). Set from the global
1863// <psyspec allowselfsigned="yes"> attribute; per-connection
1864// setAllowSelfSigned() overrides it either way.
1866
1870
1874
1875// Process-wide default custom CA location (set from <psyspec cafile/capath>);
1876// per-connection setCALocation() overrides it. Empty = use OS trust store.
1879
1880void SSLConnection::SetDefaultCALocation(const char* caFile, const char* caPath) {
1881 DefaultCAFile = caFile ? caFile : "";
1882 DefaultCAPath = caPath ? caPath : "";
1883}
1884
1885void SSLConnection::setCALocation(const char* caFile, const char* caPath) {
1886 this->caFile = caFile ? caFile : "";
1887 this->caPath = caPath ? caPath : "";
1888 #ifdef _USE_SSL_
1889 if (ctx)
1890 applyClientVerify();
1891 #endif // _USE_SSL_
1892}
1893
1894void SSLConnection::setVerifyHostName(const char* host) {
1895 verifyHostName = host ? host : "";
1896}
1897
1899 allowSelfSigned = allow;
1900 #ifdef _USE_SSL_
1901 if (ctx)
1902 applyClientVerify();
1903 #endif // _USE_SSL_
1904}
1905
1906#ifdef _USE_SSL_
1907// Configure peer verification on the client context according to the
1908// allowSelfSigned policy for this connection.
1909bool SSLConnection::applyClientVerify() {
1910 if (!ctx)
1911 return false;
1912 if (allowSelfSigned) {
1913 SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
1914 }
1915 else {
1916 if (!caFile.empty() || !caPath.empty()) {
1917 // Verify the server certificate against a custom CA file/dir
1918 // (e.g. a self-minted CA) instead of the OS trust store
1919 if (SSL_CTX_load_verify_locations(ctx,
1920 caFile.empty() ? NULL : caFile.c_str(),
1921 caPath.empty() ? NULL : caPath.c_str()) != 1)
1922 LogPrint(0, LOG_NETWORK, 0, "SSL: could not load CA location (file: %s, path: %s)",
1923 caFile.empty() ? "-" : caFile.c_str(), caPath.empty() ? "-" : caPath.c_str());
1924 }
1925 else {
1926 #ifdef WINDOWS
1927 // Verify the server certificate against the OS trust store.
1928 // OpenSSL's SSL_CTX_set_default_verify_paths() is useless on
1929 // Windows (it points at the build-time OPENSSLDIR), so import
1930 // the Windows ROOT system store into the context's X509 store
1931 // via CryptoAPI instead.
1932 bool loadedOSRoots = false;
1933 HCERTSTORE hStore = CertOpenSystemStoreA(0, "ROOT");
1934 if (hStore) {
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);
1940 if (x) {
1941 // Returns 0 for duplicates - not a failure
1942 if (X509_STORE_add_cert(store, x) == 1)
1943 loadedOSRoots = true;
1944 X509_free(x);
1945 }
1946 }
1947 CertCloseStore(hStore, 0);
1948 }
1949 ERR_clear_error(); // duplicate-cert noise from X509_STORE_add_cert
1950 if (!loadedOSRoots)
1951 LogPrint(0, LOG_NETWORK, 0, "SSL: could not load Windows ROOT certificate store");
1952 #else
1953 // Verify the server certificate against the OS/CA trust store
1954 if (SSL_CTX_set_default_verify_paths(ctx) != 1)
1955 LogPrint(0, LOG_NETWORK, 0, "SSL: could not load default CA trust store");
1956 #endif // WINDOWS
1957 }
1958 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
1959 }
1960 return true;
1961}
1962
1963int SSLConnection::getVerifyMode() {
1964 if (!ctx)
1965 return -1;
1966 return SSL_CTX_get_verify_mode(ctx);
1967}
1968#endif // _USE_SSL_
1969
1970bool SSLConnection::init(const char *certFile, const char *keyFile) {
1971 mutex.enter(1000);
1972 #ifdef _USE_SSL_
1973 LogPrint(0, LOG_NETWORK, 2, "SSL connection init start");
1974 // Compatible with SSLv2, SSLv3 and TLSv1
1975 const SSL_METHOD *method = SSLv23_server_method();
1976 // Create new context from method.
1977 ctx = SSL_CTX_new(method);
1978 if(!ctx) {
1979 LogPrint(0, LOG_NETWORK, 0, "Unable to create a new SSL context structure");
1980 BIO_printf(outbio, "Unable to create a new SSL context structure.\n");
1981 mutex.leave();
1982 return false;
1983 }
1984 LogPrint(0, LOG_NETWORK, 2, "SSL connection init created, setting files...");
1985
1986 if ( SSL_CTX_use_certificate_chain_file(ctx, certFile) <= 0) {
1987 LogPrint(0, LOG_NETWORK, 0, "Unable to use SSL certificate chain file: %s", certFile);
1988 LogSSLErrors("certificate chain file", 0);
1989 mutex.leave();
1990 return false;
1991 }
1992 if ( SSL_CTX_use_PrivateKey_file(ctx, keyFile, SSL_FILETYPE_PEM) <= 0) {
1993 LogPrint(0, LOG_NETWORK, 0, "Unable to use SSL private key file: %s", keyFile);
1994 LogSSLErrors("private key file", 0);
1995 mutex.leave();
1996 return false;
1997 }
1998 LogPrint(0, LOG_NETWORK, 2, "SSL connection init files set");
1999
2000 // Verify that the two keys goto together.
2001 if ( !SSL_CTX_check_private_key(ctx) ) {
2002 LogPrint(0, LOG_NETWORK, 0, "SSL private key invalid: %s", keyFile);
2003 fprintf(stderr, "Private key is invalid.\n");
2004 mutex.leave();
2005 return false;
2006 }
2007 mutex.leave();
2008 LogPrint(0, LOG_NETWORK, 2, "SSL connection init done");
2009 return true;
2010 #else // _USE_SSL_
2011 mutex.leave();
2012 return false;
2013 #endif // _USE_SSL_
2014}
2015
2017 mutex.enter(1000);
2018 #ifdef _USE_SSL_
2019 // Compatible with SSLv2, SSLv3 and TLSv1
2020 const SSL_METHOD *method = SSLv23_method();
2021 // Create new context from method.
2022 ctx = SSL_CTX_new(method);
2023 if(!ctx) {
2024 BIO_printf(outbio, "Unable to create a new SSL context structure.\n");
2025 mutex.leave();
2026 return false;
2027 }
2028
2029 //SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
2030
2031 // Client-side certificate verification (secure by default; see
2032 // setAllowSelfSigned/SetDefaultAllowSelfSigned)
2033 applyClientVerify();
2034
2035 mutex.leave();
2036 return true;
2037 #else // _USE_SSL_
2038 mutex.leave();
2039 return false;
2040 #endif // _USE_SSL_
2041}
2042
2043bool SSLConnection::didConnect(int timeout) {
2044 return NetworkConnection::didConnect(timeout);
2045}
2046
2048
2049 // ######################
2050 //return true;
2051
2052 //printf("ISCON1\n");fflush(stdout);
2053
2054#ifdef _USE_SSL_
2055
2056 if ((socket == INVALID_SOCKET) || !ssl)
2057 return false;
2058
2059 char peekBuffer[1];
2060 // First use the socket a bit
2061
2062 //utils::Sleep(100);
2063
2064 if (!mutex.enter(200, __FUNCTION__))
2065 return false;
2066 //printf("ISCON2\n");fflush(stdout);
2067 int res = recv(socket, peekBuffer, 1, MSG_PEEK);
2068 if (res > 0) {
2069 mutex.leave();
2070 //printf("ISCON3\n");fflush(stdout);
2071 return true;
2072 }
2073 else if (res < 0) {
2074 int err = utils::GetLastOSErrorNumber();
2075 // UDP needs TRYAGAIN
2076 if (err == SOCKETWOULDBLOCK) {
2077 mutex.leave();
2078 //printf("ISCON4\n");fflush(stdout);
2079 return true;
2080 }
2081
2082 #ifdef WINDOWS
2083 else if ((type == UDPCON) && (err == SOCKETTRYAGAIN)) {
2084 mutex.leave();
2085 //printf("ISCON5\n");fflush(stdout);
2086 return true;
2087 }
2088 else if (err == WSAENOTCONN) {} // Windows needs this one...
2089 else if (err == WSAEOPNOTSUPP) {} // WinCE may need this one...???.
2090 #else
2091 else if (err == SOCKETTRYAGAIN) {
2092 mutex.leave();
2093 return true;
2094 }
2095 #endif //WINDOWS
2096 else {
2097 // Error will be handled by the caller
2098 //printf("ISCON6\n");fflush(stdout);
2099 disconnect(0);
2100 mutex.leave();
2101 return false;
2102 }
2103 // mutex.leave();
2104 }
2105 else { // if err == 0
2106 // Error will be handled by the caller
2107 //printf("ISCON7\n");fflush(stdout);
2108 disconnect(0);
2109 mutex.leave();
2110 return false;
2111 }
2112
2113 //printf("ISCON10\n");fflush(stdout);
2114
2115 struct timeval tv;
2116 tv.tv_sec = 0;
2117 tv.tv_usec = 10;
2118
2119 int maxfd = 0;
2120 fd_set wfds;
2121 // create a list of sockets to check for activity
2122 FD_ZERO(&wfds);
2123 // specify socket
2124 FD_SET(socket, &wfds);
2125
2126 mutex.leave();
2127
2128 #ifdef WINDOWS
2129 int len;
2130 #else
2131 #ifdef Darwin
2132 #if GCC_VERSION < 40000
2133 int len;
2134 maxfd = socket + 1;
2135 #else
2136 socklen_t len;
2137 maxfd = socket + 1;
2138 #endif // GCC_VERSION < 40000
2139 #else
2140 socklen_t len;
2141 maxfd = socket + 1;
2142 #endif
2143 #endif
2144
2145 if (timeout > 0) {
2146 ldiv_t d = ldiv(timeout*1000, 1000000);
2147 tv.tv_sec = d.quot;
2148 tv.tv_usec = d.rem;
2149 }
2150
2151 // Check for writability
2152 //printf("ISCON11\n");fflush(stdout);
2153 res = select(maxfd, NULL, &wfds, NULL, &tv);
2154 //printf("ISCON12\n");fflush(stdout);
2155
2156 if (res <= 0)
2157 return false;
2158
2159 //printf("wait res > 0\n");
2160
2161 int error;
2162 len = sizeof(error);
2163
2164 mutex.enter(1000);
2165 //printf("ISCON13\n");fflush(stdout);
2166 if (FD_ISSET(socket, &wfds) != 0) {
2167 if (getsockopt(socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len) != 0) {
2168
2169 int wsaError = utils::GetLastOSErrorNumber();
2170 mutex.leave();
2171 if (wsaError == 0) {
2172 // No error, just unable to send...
2173 return true;
2174 }
2175 #ifdef WINDOWS
2176 else if (wsaError == WSAENETDOWN ) {
2177 return false;
2178 }
2179 else if (wsaError == WSAEFAULT ) {
2180 return false;
2181 }
2182 else if (wsaError == WSAEINPROGRESS ) {
2183 return false;
2184 }
2185 else if (wsaError == WSAEINVAL ) {
2186 return false;
2187 }
2188 else if (wsaError == WSAENOPROTOOPT ) {
2189 if (error == 0) {
2190 return true;
2191 }
2192 }
2193 else if (wsaError == WSAENOTSOCK ) {
2194 return false;
2195 }
2196 #endif
2197 return false;
2198 }
2199 mutex.leave();
2200 if (error == 0)
2201 return true;
2202 }
2203 else
2204 mutex.leave();
2205
2206#endif //_USE_SSL_
2207 return false;
2208}
2209
2210bool SSLConnection::disconnect(uint16 error) {
2211 #ifdef _USE_SSL_
2212 mutex.enter(1000);
2213 if (!ctx || !ssl) {
2214 mutex.leave();
2215 return false;
2216 }
2217 SSL_shutdown(ssl);
2218 SSL_free(ssl);
2219 ssl = NULL;
2220 disconnectInternal(error);
2221 mutex.leave();
2222 return true;
2223 #else // _USE_SSL_
2224 return false;
2225 #endif // _USE_SSL_
2226}
2227
2229 #ifdef _USE_SSL_
2230 if (!ctx || !(ssl = SSL_new(ctx)))
2231 return false;
2232
2233 mutex.enter(1000);
2234 bufferContentLen = 0;
2235 bufferContentPos = 0;
2236 localAddress = localAddr;
2237
2238 socket = s;
2240
2241 // Set blocking mode
2243
2244 struct linger tmp = {1, 0};
2245 setsockopt(s, SOL_SOCKET, SO_LINGER, (char *)&tmp, sizeof(tmp));
2246 int delay = 1;
2247 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char*) &delay, sizeof(delay));
2248
2249 LogPrint(0, LOG_NETWORK, 2, "SSL connection options set, accepting connection...");
2250
2251 remote = true;
2252 SSL_set_fd(ssl, (int)socket);
2253 int ret = SSL_accept(ssl);
2254 int err;
2255 int errCount = 0;
2256
2257 while (ret == -1) {
2258 err = SSL_get_error(ssl, ret);
2259 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
2260
2261 if ((++errCount) > 10) {
2262 LogPrint(0, LOG_NETWORK, 1, "SSL connection accept took too long, disconnecting...");
2263 SSL_shutdown(ssl);
2264 SSL_free(ssl);
2265 ssl = NULL;
2267 mutex.leave();
2268 return false;
2269 }
2270
2272 ret = SSL_accept(ssl);
2273 }
2274 else {
2275 SSL_shutdown(ssl);
2276 SSL_free(ssl);
2277 ssl = NULL;
2279 mutex.leave();
2280 return false;
2281 }
2282 }
2283
2284 LogPrint(0, LOG_NETWORK, 2, "SSL connection accepted, setting up receiver...");
2285
2286 if (receiver != NULL) {
2287 this->receiver = receiver;
2288 // Start networking thread
2290 LogPrint(0, LOG_NETWORK, 0, "Could not start SSLConnection thread...");
2291 SSL_shutdown(ssl);
2292 SSL_free(ssl);
2293 ssl = NULL;
2295 mutex.leave();
2296 return false;
2297 }
2298 }
2299
2300 mutex.leave();
2301 return true;
2302 #else // _USE_SSL_
2303 return false;
2304 #endif // _USE_SSL_
2305}
2306
2307bool SSLConnection::connect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver* receiver) {
2308 #ifdef _USE_SSL_
2309 // Make client SSL connection; create the client context on demand so the
2310 // verification policy is always applied
2311 if (!ctx && !init()) {
2312 return false;
2313 }
2314 if (!ctx || !(ssl = SSL_new(ctx))) {
2315 LogSSLErrors("SSL_new", 0);
2316 return false;
2317 }
2318
2319 // Hostname verification: when peer verification is on and an expected
2320 // hostname is known (recorded by connect(const char*,...) or set via
2321 // setVerifyHostName), require the peer certificate to match it and
2322 // send SNI. With allowSelfSigned or no hostname (raw IP connects),
2323 // only the chain-of-trust check (or none) applies, as before.
2324 if (!allowSelfSigned && !verifyHostName.empty()) {
2325 if (SSL_set1_host(ssl, verifyHostName.c_str()) != 1) {
2326 LogPrint(0, LOG_NETWORK, 0, "SSL: could not set expected hostname '%s' for verification", verifyHostName.c_str());
2327 SSL_free(ssl);
2328 ssl = NULL;
2329 return false;
2330 }
2331 SSL_set_tlsext_host_name(ssl, verifyHostName.c_str());
2332 }
2333
2334 mutex.enter(1000);
2335 if (timeoutMS) {
2336 if (!connectTimeoutMS)
2337 connectTimeoutMS = timeoutMS;
2338 }
2339 else
2340 timeoutMS = connectTimeoutMS;
2341 if((socket=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){
2342 LogPrint(0, LOG_NETWORK, 0, "Could not create SSLListener socket (%d)...", utils::GetLastOSErrorNumber());
2343 mutex.leave();
2344 return false;
2345 }
2346
2347 bufferContentLen = 0;
2348 bufferContentPos = 0;
2349
2350 // Set blocking mode
2352
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);
2357
2358
2359 // Connect to the server
2360 int res;
2361 if ((res = ::connect(socket, (struct sockaddr*)&saServer, sizeof(struct sockaddr))) != 0) {
2362
2363 int err = utils::GetLastOSErrorNumber();
2364 if ( (err == SOCKETWOULDBLOCK) || (err == SOCKETTRYAGAIN) ) {
2365 if (!didConnect(1000)) {
2366 SSL_free(ssl);
2367 ssl = NULL;
2369 mutex.leave();
2370 return false;
2371 }
2372 }
2373 else {
2374 SSL_free(ssl);
2375 ssl = NULL;
2377 mutex.leave();
2378 return false;
2379 }
2380 }
2381
2382 struct linger tmp = {1, 0};
2383 setsockopt(socket, SOL_SOCKET, SO_LINGER, (char *)&tmp, sizeof(tmp));
2384 int delay = 1;
2385 setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, (char*) &delay, sizeof(delay));
2386
2387 // Connect the SSL struct to our connection
2388 if (!SSL_set_fd (ssl, (int)socket)) {
2389 LogSSLErrors("SSL_set_fd", 0);
2390 SSL_free(ssl);
2391 ssl = NULL;
2393 mutex.leave();
2394 return false;
2395 }
2396
2397 //SSL_set_connect_state(ssl);
2398 SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
2399
2400 // Set blocking mode
2401 // utils::SetSocketNonBlockingMode(socket);
2402
2403 int ret; //, err;
2404 // Initiate SSL handshake
2405 while ( (ret = SSL_connect(ssl)) != 1) {
2406 switch (SSL_get_error(ssl, ret)) {
2407 case SSL_ERROR_WANT_READ:
2409 break;
2410 case SSL_ERROR_WANT_WRITE:
2412 break;
2413 default:
2414 // Handshake failed (e.g. peer certificate verification failed).
2415 // Log at level 1 so the detail is available with network logging
2416 // on, but stays off the console in quiet runs (incl. the unit
2417 // test harness's negative-path verify tests).
2418 LogSSLErrors("handshake failed", 1);
2419 SSL_free(ssl);
2420 ssl = NULL;
2422 mutex.leave();
2423 return false;
2424 }
2425 //err = SSL_get_error(ssl, ret);
2426 //if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
2427 // utils::WaitForSocketWriteability(socket, 200);
2428 // if ( (ret = SSL_connect(ssl)) != 1) {
2429 // ERR_print_errors_fp(stderr);
2430 // disconnect();
2431 // mutex.leave();
2432 // return false;
2433 // }
2434 //}
2435 }
2436
2437 uint32 certnamemax = 1000;
2438 char *certname;
2439 X509 *cert = NULL;
2440
2441 cert = SSL_get_peer_certificate(ssl);
2442 if (cert != NULL) {
2443 certname = new char[certnamemax+1];
2444 certinfo = X509_NAME_oneline(X509_get_subject_name(cert), certname, certnamemax);
2445 delete [] certname;
2446 X509_free(cert);
2447 }
2448
2449 if (receiver != NULL) {
2450 this->receiver = receiver;
2451 // Start networking thread
2453 LogPrint(0, LOG_NETWORK, 0, "Could not start SSLConnection thread...");
2454 SSL_free(ssl);
2455 ssl = NULL;
2457 mutex.leave();
2458 return false;
2459 }
2460 }
2461
2462 remoteAddress = addr;
2463 remote = false;
2464
2465 mutex.leave();
2466 return true;
2467 #else // _USE_SSL_
2468 return false;
2469 #endif // _USE_SSL_
2470}
2471
2472bool SSLConnection::connect(const char* addr, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver) {
2473 #ifdef _USE_SSL_
2474 uint32 address;
2475 if (!utils::LookupIPAddress(addr, address))
2476 return false;
2477 // Record the hostname for certificate hostname verification (unless one
2478 // was set explicitly, or addr is an IP literal)
2479 if (verifyHostName.empty() && addr && (inet_addr(addr) == INADDR_NONE))
2480 verifyHostName = addr;
2481 return connect(location = GETIPADDRESSPORT(address, port), timeoutMS, receiver);
2482 #else // _USE_SSL_
2483 return false;
2484 #endif // _USE_SSL_
2485}
2486
2487bool SSLConnection::connect(const uint32* addresses, uint16 addressCount, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver) {
2488 #ifdef _USE_SSL_
2489 // Try all addresses
2490 for (uint16 n=0; n<addressCount; n++) {
2491 if (connect(location = GETIPADDRESSPORT(addresses[n], port), timeoutMS, receiver))
2492 return true;
2493 }
2494 return false;
2495 #else // _USE_SSL_
2496 return false;
2497 #endif // _USE_SSL_
2498}
2499
2500bool SSLConnection::delayedConnect(uint64 addr, uint32 timeoutMS, NetworkDataReceiver* receiver) {
2501 #ifdef _USE_SSL_
2502 mutex.enter(1000);
2503
2504 connectTimeoutMS = timeoutMS;
2505 remoteAddress = addr;
2506 remote = false;
2507
2508 if (receiver != NULL) {
2509 this->receiver = receiver;
2510 // Start networking thread
2512 LogPrint(0, LOG_NETWORK, 0, "Could not start SSLConnection thread...");
2513 mutex.leave();
2514 return false;
2515 }
2516 }
2517
2518 mutex.leave();
2519 return true;
2520 #else // _USE_SSL_
2521 return false;
2522 #endif // _USE_SSL_
2523}
2524
2525bool SSLConnection::delayedConnect(const char* addr, uint16 port, uint64& location, uint32 timeoutMS, NetworkDataReceiver* receiver) {
2526 #ifdef _USE_SSL_
2527 // Resolve address
2528 uint32 address;
2529 if (!utils::LookupIPAddress(addr, address))
2530 return false;
2531 // Record the hostname for certificate hostname verification (unless one
2532 // was set explicitly, or addr is an IP literal)
2533 if (verifyHostName.empty() && addr && (inet_addr(addr) == INADDR_NONE))
2534 verifyHostName = addr;
2535 return delayedConnect(location = GETIPADDRESSPORT(address, port), timeoutMS, receiver);
2536 #else // _USE_SSL_
2537 return false;
2538 #endif // _USE_SSL_
2539}
2540
2541bool SSLConnection::send(const char* data, uint32 size, uint64 receiver) {
2542 #ifdef _USE_SSL_
2543 if (!size)
2544 return false;
2545 // Ignore receiver, only for UDP
2546 if (!sendMutex.enter(500))
2547 return false;
2548 if (!ssl) {
2549 sendMutex.leave();
2550 return false;
2551 }
2552 uint64 start = GetTimeNow();
2553 //utils::SetSocketBlockingMode(socket);
2554
2555 // One SSL object must never be used by two threads at once (OpenSSL rule): the connection's reader thread
2556 // runs SSL_read under 'mutex', so SSL_write takes the same lock. Without it a TLS 1.3 peer's post-handshake
2557 // messages (session tickets, read while the request is written) intermittently lost the request: the
2558 // client then waited for a reply the server never got (seen 50 % against Pebble, and as the psyprobe2
2559 // "HTTPS login (255)" flake). The lock is held only around the OpenSSL calls, not while waiting.
2560 int ret, sslErr;
2561 for (;;) {
2562 if (!mutex.enter(1000)) {
2563 sendMutex.leave();
2564 return false;
2565 }
2566 if (!ssl) {
2567 mutex.leave();
2568 sendMutex.leave();
2569 return false;
2570 }
2571 ret = SSL_write(ssl, data, size);
2572 sslErr = (ret <= 0) ? SSL_get_error(ssl, ret) : SSL_ERROR_NONE;
2573 mutex.leave();
2574 if (ret > 0)
2575 break;
2576 switch (sslErr) {
2577 case SSL_ERROR_WANT_READ:
2579 break;
2580 case SSL_ERROR_WANT_WRITE:
2582 break;
2583 default:
2584 sendMutex.leave();
2586 return false;
2587 }
2588 }
2589
2590 if (ret < (int)size) {
2591 sendMutex.leave();
2593 return false;
2594 }
2596 //utils::SetSocketNonBlockingMode(socket);
2597
2598 int64 t = GetTimeAge(start);
2599 if (t > 0)
2600 outputSpeed = (uint32)(size*1000000.0/(double)t);
2601 outputBytes += size;
2602 sendMutex.leave();
2603
2604 #ifdef TCPCON_PRINT_DEBUG
2605 if (size < 1024) {
2606 char* tmp = new char[size+1];
2607 memcpy(tmp, data, size);
2608 tmp[size] = 0;
2609 LogPrint(0,LOG_NETWORK,0,">>>>>>> SEND >>>>>>>> SSL Sent %u bytes '%s'\n", size, tmp);
2610 delete [] tmp;
2611 }
2612 else {
2613 #ifdef TCPCON_PRINTBINARY_DEBUG
2614 char* tmp = new char[size+1];
2615 memcpy(tmp, data, size);
2616 tmp[size] = 0;
2617 LogPrint(0,LOG_NETWORK,0,">>>>>>> SEND >>>>>>>> SSL Sent %u bytes '%s'\n", size, tmp);
2618 delete [] tmp;
2619 #endif
2620 }
2621 #endif
2622 return true;
2623 #else // _USE_SSL_
2624 return false;
2625 #endif // _USE_SSL_
2626}
2627
2628
2629
2630bool SSLConnection::reconnect(uint32 timeoutMS) {
2631 #ifdef _USE_SSL_
2632 disconnect();
2633 return connect(remoteAddress, timeoutMS, receiver);
2634 #else // _USE_SSL_
2635 return false;
2636 #endif // _USE_SSL_
2637}
2638
2639
2641
2642 if (socket == INVALID_SOCKET)
2643 return false;
2644
2645 struct sockaddr_in remoteAddr;
2646
2647 #ifdef WINDOWS
2648 int remoteAddrLen;
2649 #else
2650 #ifdef Darwin
2651 #if GCC_VERSION < 40000
2652 int remoteAddrLen;
2653 #else
2654 socklen_t remoteAddrLen;
2655 #endif // GCC_VERSION < 40000
2656 #else
2657 socklen_t remoteAddrLen;
2658 #endif
2659 #endif // WINDOWS
2660
2661 remoteAddrLen = sizeof(struct sockaddr_in);
2662
2663 if (getpeername(socket, (struct sockaddr*) &remoteAddr, &remoteAddrLen) != 0)
2664 return false;
2665
2666 uint32 address = remoteAddr.sin_addr.s_addr;
2667 if ( address == LOCALHOSTIP ) {
2668 // Get the actual local ip address, if possible
2669 utils::GetLocalIPAddress(address);
2670 }
2671 addr = GETIPADDRESSPORT(address, (uint16)remoteAddr.sin_port);
2672 return true;
2673}
2674
2676 #ifdef _USE_SSL_
2677 mutex.enter(1000);
2678 if (!ssl) {
2679 mutex.leave();
2680 return -1;
2681 }
2682 // and read from the socket
2683 // int count = ::recvfrom(socket,buffer+bufferContentLen,bufferLen-bufferContentLen,MSG_PEEK,NULL,0);
2684 int count = SSL_pending(ssl);
2685 mutex.leave();
2686 return count;
2687 #else // _USE_SSL_
2688 return -1;
2689 #endif // _USE_SSL_
2690}
2691
2693
2694 // Assume that the mutex is locked
2695
2696 #ifdef _USE_SSL_
2697
2698 if (!ssl)
2699 return -1;
2700
2701 int32 count = 0;
2702 int pending = SSL_pending(ssl);
2703 if (pending <= 0)
2704 return 0;
2705
2706 // Check for buffer resize
2707 if ((int32)bufferLen-(int32)bufferContentLen < pending) {
2708 if ((int32)bufferLen-(int32)bufferContentLen + (int32)bufferContentPos > pending) {
2711 bufferContentPos = 0;
2712 }
2713 else
2715 }
2716
2717 // Read pending bytes from the socket
2718 count = SSL_read(ssl, buffer+bufferContentLen, pending);
2719
2720 if (count < 0)
2721 return 0;
2722 else if (count == 0) {
2724 return -1;
2725 }
2726
2727 #ifdef TCPCON_PRINT_DEBUG
2728 char* tmp = new char[count+1];
2729 memcpy(tmp, buffer+bufferContentLen, count);
2730 tmp[count] = 0;
2731 LogPrint(0,LOG_NETWORK,0,"<<<<<<< SSL READINTOBUFFER <<<<<<<< TCP RECV BUF %u bytes '%s'\n", count, tmp);
2732 delete [] tmp;
2733 #endif
2734
2735 bufferContentLen += count;
2736
2737 return count;
2738 #else // _USE_SSL_
2739 return -1;
2740 #endif // _USE_SSL_
2741}
2742
2743bool SSLConnection::receiveAvailable(char* data, uint32& size, uint32 maxSize, uint32 timeout, bool peek) {
2744
2745 #ifdef _USE_SSL_
2746 mutex.enter(1000);
2747
2748 if (!ssl) {
2749 mutex.leave();
2750 return false;
2751 }
2752
2754 if (bufferContentPos > maxSize) {
2757 bufferContentPos = 0;
2758 }
2759 else
2760 resizeBuffer((bufferLen+maxSize) * 2);
2761 }
2762
2763 uint64 start = GetTimeNow(), timespent;
2764
2765 int count, err, timeleft;
2766 // Do we have enough data in the buffer already
2767 while (bufferContentLen - bufferContentPos < maxSize) {
2768 // and read from the socket
2769 count = SSL_read(ssl,buffer+bufferContentLen,bufferLen-bufferContentLen);
2770 if(count <= 0) {
2771 err = SSL_get_error(ssl, count);
2772 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
2773 }
2774 else {
2775 mutex.leave();
2777 return false;
2778 }
2779 }
2780 else if (count > 0) {
2781 #ifdef TCPCON_PRINT_DEBUG
2782 char* tmp = new char[count+1];
2783 memcpy(tmp, buffer+bufferContentLen, count);
2784 tmp[count] = 0;
2785 LogPrint(0,LOG_NETWORK,0,"<<<<<<< RECEIVE <<<<<<<< TCP RECV AVAIL %u bytes '%s'\n", count, tmp);
2786 delete [] tmp;
2787 #endif
2788 bufferContentLen += count;
2789 if (bufferContentLen - bufferContentPos >= maxSize)
2790 break;
2791 }
2792 if ((timespent = (GetTimeNow() - start)/1000) >= timeout) {
2793 // if (timeout > 0)
2794 // printf("**** TCP::receive available %u ***\n", bufferContentLen - bufferContentPos);
2795 break;
2796 }
2797 else {
2798 mutex.leave();
2799 timeleft = (int)(timeout-timespent);
2800 utils::WaitForSocketReadability(socket, timeleft < 50 ? timeleft : 50);
2801 }
2802 mutex.enter(1000);
2803 }
2804
2806 if (size > maxSize)
2807 size = maxSize;
2808
2809 inputBytes += size;
2810 if ( size > 0 ) {
2811 memcpy(data, buffer+bufferContentPos, size);
2812 if (!peek) {
2813 bufferContentPos += size;
2816 }
2817 }
2818 mutex.leave();
2819 return true;
2820 #else // _USE_SSL_
2821 return false;
2822 #endif // _USE_SSL_
2823}
2824
2825bool SSLConnection::receive(char* data, uint32 size, uint32 timeout, bool peek) {
2826
2827 #ifdef _USE_SSL_
2828 mutex.enter(1000);
2829
2830 if (!ssl) {
2831 mutex.leave();
2832 return false;
2833 }
2834
2836 if (bufferContentPos > size) {
2839 bufferContentPos = 0;
2840 }
2841 else
2842 resizeBuffer((bufferLen+size) * 2);
2843 }
2844
2845 uint64 start = GetTimeNow();
2846 int32 timespent;
2847
2848 int count, err, timeleft;
2849 // Do we have enough data in the buffer already
2850 while (bufferContentLen - bufferContentPos < size) {
2851 if (!ssl) {
2852 mutex.leave();
2853 return false;
2854 }
2855
2856 // and read from the socket
2857
2858 // int count = ::recvfrom(socket,buffer+bufferContentLen,bufferLen-bufferContentLen,0,NULL,0);
2859
2860 count = SSL_read((SSL *)ssl, buffer+bufferContentLen,size);
2861
2862 if(count <= 0) {
2863 err = SSL_get_error(ssl, count);
2864 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
2865 }
2866 else {
2867 mutex.leave();
2869 return false;
2870 }
2871 }
2872 else if (count > 0) {
2873 #ifdef TCPCON_PRINTBINARY_DEBUG
2874 char* tmp = new char[count+1];
2875 memcpy(tmp, buffer+bufferContentLen, count);
2876 tmp[count] = 0;
2877 LogPrint(0,LOG_NETWORK,0,"<<<<<<<< RECEIVE <<<<<<< TCP RECV %u bytes '%s'", count, tmp);
2878 delete [] tmp;
2879 #endif
2880 bufferContentLen += count;
2881 if (bufferContentLen - bufferContentPos >= size)
2882 break;
2883 }
2884 if ((timespent = GetTimeAgeMS(start)) >= (int32)timeout) {
2885 // printf("**** TCP::receive only got %u out of %u bytes ***\n", bufferContentLen - bufferContentPos, size);
2886 mutex.leave();
2887 return false;
2888 }
2889 else {
2890 //utils::Sleep(5);
2891 //uint64 t = GetTimeNow();
2892 mutex.leave();
2893 timeleft = (int)(timeout-timespent);
2894 utils::WaitForSocketReadability(socket, timeleft < 50 ? timeleft : 50);
2895 //printf("WaitForRead: %lu (%lu)\n", GetTimeAgeMS(t), timeout-timespent);
2896 }
2897 mutex.enter(1000);
2898 }
2899
2900 int64 t = GetTimeAge(start);
2901 if (t > 0)
2902 inputSpeed = (uint32)(size*1000000.0/(double)t);
2903 inputBytes += size;
2904
2905 memcpy(data, buffer+bufferContentPos, size);
2906 if (!peek) {
2907 bufferContentPos += size;
2910 }
2911 mutex.leave();
2912 return true;
2913 #else // _USE_SSL_
2914 return false;
2915 #endif // _USE_SSL_
2916}
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2928 if (arg == NULL) thread_ret_val(1);
2929 thread_ret_val((int)(((TCPListener*)arg)->run() ? 0 : 1));
2930}
2931
2933 if (arg == NULL) thread_ret_val(1);
2934 thread_ret_val((int)(((TCPConnection*)arg)->run() ? 0 : 1));
2935}
2936
2938 if (arg == NULL) thread_ret_val(1);
2939 thread_ret_val((int)(((UDPConnection*)arg)->run() ? 0 : 1));
2940}
2941
2943 if (arg == NULL) thread_ret_val(1);
2944 thread_ret_val((int)(((SSLConnection*)arg)->run() ? 0 : 1));
2945}
2946
2947
2948
2949bool NetworkTest_TCPServer(uint16 port, uint32 count2) {
2950 uint32 period = 100000;
2951
2952 TCPListener* listener = new TCPListener();
2953 if (!listener->init(port, NOENC)) {
2954 delete(listener);
2955 printf("Could not bind to port %u, exiting... \n\n", port);
2956 return false;
2957 }
2958
2959 char* startdata = new char[12], *data;
2960 uint32 size, count;
2961 NetworkConnection* con;
2962 uint32 c = 0;
2963 while (true) {
2964 c = 0;
2965 printf("\n\nListening to port %u for a new connection... ", port);
2966 while ( (con = listener->acceptConnection(10000)) == NULL) {}
2967
2968 while (con->isConnected()) {
2969 // Reading count and size
2970 if (!con->receive(startdata, 12, 10000)) {
2971 printf("[%u] Could not receive start data, exiting...\n", c);
2972 break;
2973 }
2974 if ((*(uint32*)startdata) != 123456789) {
2975 printf("[%u] Start data wrong, exiting...\n", c);
2976 break;
2977 }
2978 size = *(((uint32*)startdata)+1);
2979 count = *(((uint32*)startdata)+2);
2980 c = 0;
2981 data = new char[size];
2982
2983 printf("Got it - starting test with size %u and count %u...\n\n", size, count);
2984
2985 while (con->isConnected() && (c++ < count) ) {
2986 if (!con->receive(data, size, 10000)) {
2987 printf("[%u] Could not receive data %u, exiting...\n", port, c);
2988 break;
2989 }
2990 if (!con->send(data, size)) {
2991 printf("[%u] Could not send data %u, exiting...\n", port, c);
2992 break;
2993 }
2994 }
2995 delete [] data;
2996 }
2997 delete(con);
2998
2999
3000 //while (con->isConnected()) {
3001 // t1 = GetTimeNow();
3002 // if (!NetworkTest_SendReceiveData(con, data, dataLen, c, true)) {
3003 // delete(con);
3004 // break;
3005 // }
3006 // t2 = GetTimeNow();
3007 // d += t2-t1;
3008 // if ((c > 0) && (c % period == 0)) {
3009 // printf("Round time: %.3f us...\n", (double)d/period);
3010 // d = 0;
3011 // }
3012 // c++;
3013 // if ( (count > 0) && (c > count) ) {
3014 // delete(con);
3015 // delete(listener);
3016 // return true;;
3017 // }
3018 //}
3019
3020 }
3021 delete [] startdata;
3022 return true;
3023}
3024
3025
3026bool NetworkTest_TCPClient(const char* address, uint16 port, uint32 count2) {
3027 TCPConnection* con = new TCPConnection();
3028 uint64 location;
3029 if (!con->connect(address, port, location, 5000)) {
3030 delete(con);
3031 printf("Could not connect to '%s' on port %u, exiting...\n", address, port);
3032 return false;
3033 }
3034 printf("Connected to '%s' on port %u, starting test...\n", address, port);
3035
3036 char* startdata = new char[12];
3037 memset(startdata, 0, 12);
3038 *((uint32*)startdata) = 123456789;
3039
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;
3048
3049 uint64 t1, t2;
3050
3051 while (con->isConnected()) {
3052
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);
3059 break;
3060 }
3061 printf("Step %u size %u...\n", step, s);
3062 for (c=0; c<count; c++) {
3063 t1 = GetTimeNow();
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);
3067 break;
3068 }
3069 if (!con->receive(data, s, 10000)) {
3070 printf("[%u] Could not receive data %u, exiting...\n", port, c);
3071 break;
3072 }
3073 }
3074 t2 = GetTimeNow();
3075 vals[c] = (t2-t1)/(double)innercount;
3076 }
3077
3078 sum = avg = std = 0;
3079 mx = mn = vals[0];
3080 for (c=0; c<count; c++) {
3081 sum += vals[c];
3082 if (vals[c] > mx) mx = vals[c];
3083 if (vals[c] < mn) mn = vals[c];
3084 }
3085 avg = sum/count;
3086
3087 sum = 0;
3088 for (c=0; c<count; c++)
3089 sum += pow((vals[c] - avg), 2);
3090 std = sqrt(sum/count-1);
3091
3092 avgvals[step] = avg;
3093 maxvals[step] = mx;
3094 minvals[step] = mn;
3095 stdvals[step] = std;
3096 }
3097
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]);
3103 }
3104
3105 break;
3106 }
3107
3108 delete [] startdata;
3109 delete [] data;
3110 delete [] vals;
3111 delete [] avgvals;
3112 delete [] maxvals;
3113 delete [] minvals;
3114 delete [] stdvals;
3115
3116
3117
3118
3119// strcpy(data+(2*sizeof(uint32)), "Testing");
3120
3121// utils::PrintBinary(data, dataLen, true, "Initial Structure");
3122
3123// uint32 c = 0;
3124// uint64 t1, t2, d = 0;
3125
3126
3127
3128
3129
3130
3131 //while (con->isConnected()) {
3132 // t1 = GetTimeNow();
3133 // if (!NetworkTest_SendReceiveData(con, data, dataLen, c)) {
3134 // delete(con);
3135 // return false;
3136 // }
3137 // t2 = GetTimeNow();
3138 // d += t2-t1;
3139 // if ((c > 0) && (c % period == 0)) {
3140 // printf("Round time: %.3f us...\n", (double)d/period);
3141 // d = 0;
3142 // }
3143 // c++;
3144 // if ( (count > 0) && (c > count) )
3145 // break;
3146 //}
3147 delete(con);
3148 return true;
3149}
3150
3151bool NetworkTest_SendReceiveData(TCPConnection* con, char* data, uint32 dataLen, uint32 c, bool receiveFirst) {
3152
3153 uint32 expectC = c*2;
3154 if (!receiveFirst) {
3155 expectC++;
3156 // Send data
3157 if (!con->send(data, dataLen)) {
3158 printf("[%u] Could not send data, exiting...\n", c);
3159 return false;
3160 }
3161 //utils::PrintBinary(data, dataLen, true, "Send1");
3162 }
3163
3164 memset(data, 0, dataLen);
3165 // Wait for reply data
3166 if (!con->receive(data, dataLen, 10000)) {
3167 printf("[%u] Could not receive data, exiting...\n", c);
3168 return false;
3169 }
3170 //utils::PrintBinary(data, dataLen, true, "Receive");
3171 // Check reply data
3172 if (*(uint32*)data != dataLen) {
3173 printf("[%u] Did not receive correct length (%u != %u), exiting...\n", c, *(uint32*)data, dataLen);
3174 // utils::PrintBinary(data, dataLen, true, "Structure");
3175 return false;
3176 }
3177 // Check reply data
3178 if (*((uint32*)data+1) != expectC) {
3179 printf("[%u] Did not receive correct count (%u != %u), exiting...\n", c, *((uint32*)data+1), expectC);
3180 // utils::PrintBinary(data, dataLen, true, "Structure");
3181 return false;
3182 }
3183 // Check reply data
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)));
3187 // utils::PrintBinary(data, dataLen, true, "Structure");
3188 return false;
3189 }
3190 *((uint32*)data+1) = *((uint32*)data+1) + 1;
3191
3192// printf("[%u] Receive OK\n", c);
3193 if (receiveFirst) {
3194 // Send data
3195 if (!con->send(data, dataLen)) {
3196 printf("[%u] Could not send data, exiting...\n", c);
3197 return false;
3198 }
3199 //utils::PrintBinary(data, dataLen, true, "Send2");
3200 }
3201 return true;
3202}
3203
3204
3205}
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)
Definition Utils.h:1688
#define SD_BOTH
Definition Utils.h:168
#define thread_ret_val(ret)
Definition Utils.h:131
#define INVALID_SOCKET
Definition Utils.h:137
#define CHECKNETWORKINIT
Definition Utils.h:1622
#define closesocket(X)
Definition Utils.h:138
#define SOCKETWOULDBLOCK
Definition Utils.h:139
#define THREAD_RET
Definition Utils.h:127
#define LOCALHOSTIP
Definition Utils.h:1681
#define THREAD_FUNCTION_CALL
Definition Utils.h:129
#define SOCKET_ERROR
Definition Utils.h:136
#define LogPrint
Definition Utils.h:330
#define SOCKETTRYAGAIN
Definition Utils.h:140
#define LOG_NETWORK
Definition Utils.h:215
#define GETIPADDRESSPORT(a, p)
Definition Utils.h:1687
struct sockaddr SOCKADDR
Definition Utils.h:135
#define GETIPPORT(a)
Definition Utils.h:1685
#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....
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.
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)
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.
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.
Definition PsyTime.cpp:69
int32 GetTimeAgeMS(uint64 t)
Age of a timestamp relative to now, in milliseconds.
Definition PsyTime.cpp:35
int64 GetTimeAge(uint64 t)
Age of a timestamp relative to now.
Definition PsyTime.cpp:25
bool Sleep(uint32 ms)
Suspend the calling thread.
Definition Utils.cpp:4078
const char * stristr(const char *str, const char *substr, uint32 len=0)
Case-insensitive strstr.
Definition Utils.cpp:8470
int GetLastOSErrorNumber()
Get the last OS error number (errno / GetLastError()).
Definition Utils.cpp:7662
bool WaitForSocketReadability(SOCKET s, int32 timeout)
Wait until a socket has data to read.
Definition Utils.cpp:7720
bool WaitForSocketWriteability(SOCKET s, int32 timeout)
Wait until a socket can be written without blocking.
Definition Utils.cpp:7688
bool GetLocalIPAddress(uint32 &address)
Get the primary local IPv4 address.
Definition Utils.cpp:8042
bool LookupIPAddress(const char *name, uint32 &address)
Resolve a hostname to an IPv4 address.
Definition Utils.cpp:7781
bool SetSocketNonBlockingMode(SOCKET s)
Put a socket into non-blocking mode.
Definition Utils.cpp:7757
THREAD_RET THREAD_FUNCTION_CALL SSLConnectionRun(THREAD_ARG arg)
bool AESCheckBufferForCompatibility(const char *buffer, uint32 length)
bool SSLCheckBufferForCompatibility(const char *buffer, uint32 length)
STL namespace.
#define FALSE
Definition xml_parser.h:121