-
Notifications
You must be signed in to change notification settings - Fork 26
/
streamingsocketmanagement.cpp
1808 lines (1576 loc) · 69.6 KB
/
streamingsocketmanagement.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define __STDC_LIMIT_MACROS
#include "streamingsocketmanagement.h"
#include "takmessage.h"
#include "commothread.h"
#include "libxml/tree.h"
#include <sstream>
#include <limits.h>
#include <string.h>
#include <inttypes.h>
#include "openssl/pkcs12.h"
#include "openssl/err.h"
using namespace atakmap::commoncommo;
using namespace atakmap::commoncommo::impl;
using namespace atakmap::commoncommo::impl::thread;
namespace {
const float PROTO_TIMEOUT_SECONDS = 60.0f;
const float DEFAULT_CONN_TIMEOUT_SECONDS = 20.0f;
const float CONN_RETRY_SECONDS = 15.0f;
const float RESOLVE_RETRY_SECONDS = 30.0f;
// Send "ping" to server after this long of no rx activity
const float RX_STALE_SECONDS = 15.0f;
// Repeat "ping" to server this often as long as no rx activity goes on
const float RX_STALE_PING_SECONDS = 4.5f;
// Reset connection after this long of no rx activity
const float RX_TIMEOUT_SECONDS = 25.0f;
const char MESSAGE_END_TOKEN[] = "</event>";
const size_t MESSAGE_END_TOKEN_LEN = sizeof(MESSAGE_END_TOKEN) - 1;
const char *PING_UID_SUFFIX = "-ping";
char *copyString(const std::string &s)
{
char *c = new char[s.length() + 1];
const char *sc = s.c_str();
strcpy(c, sc);
return c;
}
const char *THREAD_NAMES[] = {
"cmostrm.conn",
"cmostrm.io",
"cmostrm.rxq",
};
}
/*************************************************************************/
// StreamingSocketManagement constructor/destructor
StreamingSocketManagement::StreamingSocketManagement(CommoLogger *logger,
const std::string &myuid) :
ThreadedHandler(3, THREAD_NAMES), logger(logger),
resolver(new ResolverQueue(logger, this, RESOLVE_RETRY_SECONDS, RESQ_INFINITE_TRIES)),
connTimeoutSec(DEFAULT_CONN_TIMEOUT_SECONDS),
monitor(true),
sslCtx(NULL),
contexts(), contextMutex(RWMutex::Policy_Fair),
ioNeedsRebuild(false),
upContexts(), upMutex(),
downContexts(), downNeedsRebuild(false), downMutex(),
resolutionContexts(),
myuid(myuid),
myPingUid(myuid + PING_UID_SUFFIX),
rxQueue(), rxQueueMutex(), rxQueueMonitor(),
ifaceListeners(), ifaceListenersMutex(),
listeners(), listenersMutex()
{
ERR_clear_error();
sslCtx = SSL_CTX_new(SSLv23_client_method());
if (sslCtx)
// Be certain openssl doesn't do anything with its internal
// verification as we will do our own (internal verify cannot be made
// to work with in-memory certs)
SSL_CTX_set_verify(sslCtx, SSL_VERIFY_NONE, NULL);
else {
unsigned long errCode = ERR_get_error();
char ebuf[1024];
ERR_error_string_n(errCode, ebuf, 1024);
ebuf[1023] = '\0';
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR, "Cannot create SSL Context! SSL connections will not be available (details: %s)", ebuf);
}
startThreads();
}
StreamingSocketManagement::~StreamingSocketManagement()
{
delete resolver;
stopThreads();
// With the threads all joined, we can remove everything safely
// Clean the rx queue first
while (!rxQueue.empty()) {
RxQueueItem rxi = rxQueue.back();
rxQueue.pop_back();
rxi.implode();
}
// Now tear down all the contexts
ContextMap::iterator iter;
for (iter = contexts.begin(); iter != contexts.end(); ++iter)
delete iter->second;
if (sslCtx) {
SSL_CTX_free(sslCtx);
sslCtx = NULL;
}
}
/*************************************************************************/
// StreamingSocketManagement - interface management
StreamingNetInterface *StreamingSocketManagement::addStreamingInterface(
const char *addr, int port, const CoTMessageType *types,
size_t nTypes, const uint8_t *clientCert, size_t clientCertLen,
const uint8_t *caCert, size_t caCertLen,
const char *certPassword,
const char *caCertPassword,
const char *username, const char *password, CommoResult *resultCode)
{
CommoResult rc = COMMO_ILLEGAL_ARGUMENT;
StreamingNetInterface *ret = NULL;
uint16_t sport = (uint16_t)port;
ConnType connType = CONN_TYPE_TCP;
NetAddress *endpoint = NULL;
SSLConnectionContext *ssl = NULL;
std::string epString;
// First try to parse all the args to get essential connection info
if (port > UINT16_MAX || port < 0) {
rc = COMMO_ILLEGAL_ARGUMENT;
goto done;
}
// Try parsing addr as a string-form of an IP address directly.
// If this fails, endpoint will be null
endpoint = NetAddress::create(addr, sport);
if (clientCert) {
connType = CONN_TYPE_SSL;
try {
ssl = new SSLConnectionContext(myuid,
sslCtx, clientCert, clientCertLen,
caCert, caCertLen, certPassword,
caCertPassword,
username, password);
} catch (SSLArgException &e) {
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR, "Unable to create SSL connection configuration: %s", e.what());
// Remove any lingering open ssl error codes
ERR_clear_error();
rc = e.errCode;
goto done;
}
}
// Get string that is unique based on identifying criteria of the connection
epString = getEndpointString(addr, port, connType);
{
WriteLock lock(contextMutex);
ContextMap::iterator iter = contexts.find(epString);
if (iter != contexts.end()) {
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR,
"Streaming interface %s already exists", epString.c_str());
delete endpoint;
rc = COMMO_ILLEGAL_ARGUMENT;
goto done;
}
ConnectionContext *ctx = new ConnectionContext(epString, addr, sport,
endpoint, connType, ssl);
contexts.insert(ContextMap::value_type(epString, ctx));
ctx->broadcastCoTTypes.insert(types, types + nTypes);
if (endpoint) {
InternalUtils::logprintf(logger, CommoLogger::LEVEL_DEBUG,
"Streaming interface %s added with pre-resolved IP string", epString.c_str());
// Already resolved - go straight to connection
Lock downLock(downMutex);
downContexts.insert(ctx);
} else {
// Needs name resolution
InternalUtils::logprintf(logger, CommoLogger::LEVEL_DEBUG,
"Streaming interface %s added with hostname string %s - going to name resolution", epString.c_str(), addr);
ctx->resolverRequest =
resolver->queueForResolution(ctx->remoteEndpointAddrString);
resolutionContexts.insert(
ResolverMap::value_type(ctx->resolverRequest, ctx));
}
ret = ctx;
rc = COMMO_SUCCESS;
}
done:
if (resultCode)
*resultCode = rc;
return ret;
}
CommoResult StreamingSocketManagement::removeStreamingInterface(
std::string *endpoint, StreamingNetInterface *iface)
{
WriteLock lock(contextMutex);
// Try to erase context from the master list
ContextMap::iterator cmIter = contexts.begin();
for (cmIter = contexts.begin(); cmIter != contexts.end(); ++cmIter) {
if (cmIter->second == iface)
break;
}
if (cmIter == contexts.end())
return COMMO_ILLEGAL_ARGUMENT;
*endpoint = std::string(iface->remoteEndpointId, iface->remoteEndpointLen);
contexts.erase(cmIter);
// Now we know it was one of ours
ConnectionContext *ctx = (ConnectionContext *)iface;
// Remove from up, down, or resolution list, whichever it is in
{
Lock uLock(upMutex);
if (upContexts.erase(ctx) == 1)
ioNeedsRebuild = true;
}
{
Lock dLock(downMutex);
if (downContexts.erase(ctx) == 1)
downNeedsRebuild = true;
}
if (ctx->resolverRequest) {
resolutionContexts.erase(ctx->resolverRequest);
resolver->cancelResolution(ctx->resolverRequest);
}
// Remove any reference in the rxQueue
{
Lock rxqlock(rxQueueMutex);
RxQueue::iterator iter = rxQueue.begin();
while (iter != rxQueue.end()) {
if (iter->ctx == ctx) {
RxQueue::iterator eraseMe = iter;
iter++;
eraseMe->implode();
rxQueue.erase(eraseMe);
} else {
iter++;
}
}
}
// Clean up the context itself
delete ctx;
return COMMO_SUCCESS;
}
void StreamingSocketManagement::resetConnection(ConnectionContext *ctx, CommoTime nextConnTime, bool clearIo)
{
if (ctx->connType == CONN_TYPE_SSL) {
ctx->ssl->writeState = SSLConnectionContext::WANT_NONE;
ctx->ssl->readState = SSLConnectionContext::WANT_NONE;
if (ctx->ssl->ssl) {
if (!ctx->ssl->fatallyErrored)
SSL_shutdown(ctx->ssl->ssl);
SSL_free(ctx->ssl->ssl);
ctx->ssl->ssl = NULL;
}
ctx->ssl->fatallyErrored = false;
}
if (ctx->socket) {
delete ctx->socket;
ctx->socket = NULL;
}
ctx->retryTime = nextConnTime;
if (clearIo) {
while (!ctx->txQueue.empty()) {
TxQueueItem &txi = ctx->txQueue.back();
txi.implode();
ctx->txQueue.pop_back();
}
ctx->txQueueProtoVersion = 0;
ctx->rxBufOffset = 0;
ctx->rxBufStart = 0;
ctx->protoState = ConnectionContext::PROTO_XML_NEGOTIATE;
ctx->protoLen = 0;
ctx->protoBlockedForResponse = false;
}
}
void StreamingSocketManagement::addInterfaceStatusListener(
InterfaceStatusListener* listener)
{
Lock lock(ifaceListenersMutex);
ifaceListeners.insert(listener);
}
void StreamingSocketManagement::removeInterfaceStatusListener(
InterfaceStatusListener* listener)
{
Lock lock(ifaceListenersMutex);
ifaceListeners.erase(listener);
}
std::string StreamingSocketManagement::getEndpointString(
const char *addr, int port, ConnType connType)
{
std::stringstream ss;
switch (connType) {
case CONN_TYPE_SSL:
ss << "ssl:";
break;
case CONN_TYPE_TCP:
ss << "tcp:";
break;
}
ss << addr;
ss << ":";
ss << port;
return ss.str();
}
void StreamingSocketManagement::fireInterfaceChange(ConnectionContext *ctx, bool up)
{
Lock lock(ifaceListenersMutex);
std::set<InterfaceStatusListener *>::iterator iter;
for (iter = ifaceListeners.begin(); iter != ifaceListeners.end(); ++iter) {
InterfaceStatusListener *listener = *iter;
if (up)
listener->interfaceUp(ctx);
else
listener->interfaceDown(ctx);
}
}
void StreamingSocketManagement::fireInterfaceErr(ConnectionContext *ctx,
netinterfaceenums::NetInterfaceErrorCode errCode)
{
Lock lock(ifaceListenersMutex);
std::set<InterfaceStatusListener *>::iterator iter;
for (iter = ifaceListeners.begin(); iter != ifaceListeners.end(); ++iter) {
InterfaceStatusListener *listener = *iter;
listener->interfaceError(ctx, errCode);
}
}
/*************************************************************************/
// StreamingSocketManagement public api: misc
void StreamingSocketManagement::setConnTimeout(float sec)
{
connTimeoutSec = sec;
}
void StreamingSocketManagement::setMonitor(bool en)
{
this->monitor = en;
}
/*************************************************************************/
// StreamingSocketManagement public api: SSL config access
void StreamingSocketManagement::configSSLForConnection(std::string streamingEndpoint, SSL_CTX *sslCtx) COMMO_THROW (std::invalid_argument)
{
ReadLock lock(contextMutex);
ContextMap::iterator iter = contexts.find(streamingEndpoint);
if (iter == contexts.end())
throw std::invalid_argument("Invalid stream endpoint - interface has been removed/disabled");
ConnectionContext *ctx = iter->second;
if (ctx->connType != CONN_TYPE_SSL)
throw std::invalid_argument("Connection is not ssl based");
SSL_CTX_use_certificate(sslCtx, ctx->ssl->cert);
SSL_CTX_use_PrivateKey(sslCtx, ctx->ssl->key);
// Disable ECDH ciphers as demo.atakserver.com fails when they are
// enabled. See: https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1475228
// for similar issues with other servers.
SSL_CTX_set_cipher_list(sslCtx, "DEFAULT:!ECDH");
// Can't use the cert store in ctx->ssl as it is used internally and they
// don't share well in our current openssl version (set_cert_store does
// not increment ref counts!)
// Make a new one
X509_STORE *store = X509_STORE_new();
if (!store)
throw std::invalid_argument("couldn't init cert store");
int nCaCerts = sk_X509_num(ctx->ssl->caCerts);
for (int i = 0; i < nCaCerts; ++i)
X509_STORE_add_cert(store, sk_X509_value(ctx->ssl->caCerts, i));
SSL_CTX_set_cert_store(sslCtx, store);
}
bool StreamingSocketManagement::isEndpointSSL(std::string streamingEndpoint) COMMO_THROW (std::invalid_argument)
{
ReadLock lock(contextMutex);
ContextMap::iterator iter = contexts.find(streamingEndpoint);
if (iter == contexts.end())
throw std::invalid_argument("Invalid stream endpoint - interface has been removed/disabled");
ConnectionContext *ctx = iter->second;
return ctx->connType == CONN_TYPE_SSL;
}
NetAddress *StreamingSocketManagement::getAddressForEndpoint(std::string endpoint) COMMO_THROW (std::invalid_argument)
{
ReadLock lock(contextMutex);
ContextMap::iterator iter = contexts.find(endpoint);
if (iter == contexts.end())
throw std::invalid_argument("Invalid stream endpoint - interface has been removed/disabled");
ConnectionContext *ctx = iter->second;
if (ctx->remoteEndpointAddr) {
return NetAddress::duplicateAddress(ctx->remoteEndpointAddr);
} else
throw std::invalid_argument("Invalid stream endpoint - interface has hostname not yet resolved!");
}
/*************************************************************************/
// StreamingSocketManagement public api: cot messaging
void StreamingSocketManagement::sendMessage(
std::string streamingEndpoint, const CoTMessage *msg)
COMMO_THROW (std::invalid_argument)
{
ReadLock lock(contextMutex);
ContextMap::iterator iter = contexts.find(streamingEndpoint);
if (iter == contexts.end())
throw std::invalid_argument("Invalid stream endpoint - interface has been removed/disabled");
ConnectionContext *ctx = iter->second;
{
Lock upLock(upMutex);
if (upContexts.find(ctx) == upContexts.end())
throw std::invalid_argument("Specified streaming interface is down");
CoTMessage *msgCopy = new CoTMessage(*msg);
//std::string dbgStr((const char *)msgBytes, len);
//InternalUtils::logprintf(logger, CommoLogger::LEVEL_DEBUG, "Stream CoT message to ep %s is: {%s}", streamingEndpoint.c_str(), dbgStr.c_str());
try {
ctx->txQueue.push_front(TxQueueItem(ctx, msgCopy,
ctx->txQueueProtoVersion));
} catch (std::invalid_argument &e) {
delete msgCopy;
throw e;
}
}
}
void StreamingSocketManagement::sendBroadcast(
const CoTMessage *msg, bool ignoreType) COMMO_THROW (std::invalid_argument)
{
CoTMessageType type = msg->getType();
ReadLock lock(contextMutex);
Lock upLock(upMutex);
ContextSet::iterator iter;
for (iter = upContexts.begin(); iter != upContexts.end(); ++iter) {
ConnectionContext *ctx = *iter;
if (ignoreType || ctx->broadcastCoTTypes.find(type) !=
ctx->broadcastCoTTypes.end()) {
CoTMessage *msgCopy = new CoTMessage(*msg);
try {
ctx->txQueue.push_front(TxQueueItem(ctx, msgCopy,
ctx->txQueueProtoVersion));
} catch (std::invalid_argument &e) {
delete msgCopy;
throw e;
}
}
}
}
void StreamingSocketManagement::addStreamingMessageListener(
StreamingMessageListener* listener)
{
Lock lock(listenersMutex);
listeners.insert(listener);
}
void StreamingSocketManagement::removeStreamingMessageListener(
StreamingMessageListener* listener)
{
Lock lock(listenersMutex);
listeners.erase(listener);
}
/*************************************************************************/
// StreamingSocketManagement - ThreadedHandler impl
void StreamingSocketManagement::threadEntry(
size_t threadNum)
{
switch (threadNum) {
case IO_THREADID:
ioThreadProcess();
break;
case RX_QUEUE_THREADID:
recvQueueThreadProcess();
break;
case CONN_MGMT_THREADID:
connectionThreadProcess();
break;
}
}
void StreamingSocketManagement::threadStopSignal(
size_t threadNum)
{
switch (threadNum) {
case IO_THREADID:
break;
case RX_QUEUE_THREADID:
{
Lock rxLock(rxQueueMutex);
rxQueueMonitor.broadcast(rxLock);
break;
}
case CONN_MGMT_THREADID:
break;
}
}
/*************************************************************************/
// StreamingSocketManagement - Connection management thread
// Only invoked on connection thread.
// Assumes underlying socket is fully connected.
// Returns true if not ssl or if is ssl and the ssl connection is completed
// Throws exception if in error
bool StreamingSocketManagement::connectionThreadCheckSsl(ConnectionContext *ctx) COMMO_THROW (SocketException)
{
if (ctx->connType != CONN_TYPE_SSL)
return true;
if (!ctx->ssl->ssl) {
// Need to make ssl context and associate fd
ctx->ssl->ssl = SSL_new(sslCtx);
if (!ctx->ssl->ssl)
throw SocketException(netinterfaceenums::ERR_INTERNAL,
"ssl context creation failed");
// Set certs and key into the context.
// These functions use the pointers as-is, no copies
SSL_use_certificate(ctx->ssl->ssl, ctx->ssl->cert);
SSL_use_PrivateKey(ctx->ssl->ssl, ctx->ssl->key);
if (SSL_set_fd(ctx->ssl->ssl, (int)ctx->socket->getFD()) != 1)
throw SocketException(netinterfaceenums::ERR_INTERNAL,
"associating fd with ssl context failed");
}
ERR_clear_error();
int r = SSL_connect(ctx->ssl->ssl);
if (r == 1) {
// openssl's cert verification during connection cannot be made
// to use an in-memory certificate (only files, and even then seems
// only globally on SSL_CTX and not per-connection like we need).
// So instead we verify ourselves here
// NOTE: we *intentionally* do not check authenticity of peer
// certificate by CN v. hostname comparison or the like (per
// Shawn Bisgrove and ATAK sources at time of writing)
X509 *cert = SSL_get_peer_certificate(ctx->ssl->ssl);
if (!cert)
throw SocketException(netinterfaceenums::ERR_CONN_SSL_NO_PEER_CERT,
"server did not provide a certificate");
bool certOk = ctx->ssl->certChecker->checkCert(cert);
X509_free(cert);
if (!certOk) {
int vResult = ctx->ssl->certChecker->getLastErrorCode();
InternalUtils::logprintf(logger, CommoLogger::LEVEL_DEBUG, "Server cert verification failed: %d - check truststore for this connection", vResult);
throw SocketException(netinterfaceenums::ERR_CONN_SSL_PEER_CERT_NOT_TRUSTED,
"server certificate failed verification - check truststore");
}
// Clear writeState now that we are connected!
ctx->ssl->writeState = SSLConnectionContext::WANT_NONE;
// If there is an auth document, push it on to the tx queue to get sent
if (!ctx->ssl->authMessage.empty()) {
ctx->txQueue.push_front(TxQueueItem(ctx, ctx->ssl->authMessage));
}
return true;
}
if (r == 0)
throw SocketException(netinterfaceenums::ERR_CONN_SSL_HANDSHAKE,
"fatal error performing ssl handshake");
else {
r = SSL_get_error(ctx->ssl->ssl, r);
// if it changes, flag for connection rebuild
if (r == SSL_ERROR_WANT_READ || r == SSL_ERROR_WANT_WRITE) {
SSLConnectionContext::SSLWantState newState;
switch (r) {
case SSL_ERROR_WANT_READ:
newState = SSLConnectionContext::WANT_READ;
break;
case SSL_ERROR_WANT_WRITE:
newState = SSLConnectionContext::WANT_WRITE;
break;
}
if (newState != ctx->ssl->writeState) {
ctx->ssl->writeState = newState;
// Flag for select rebuild
downNeedsRebuild = true;
}
return false;
} else {
if (r == SSL_ERROR_SSL) {
char msg[1024];
ERR_error_string_n(ERR_get_error(), msg, sizeof(msg));
msg[1023] = '\0';
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR, "Error making SSL connection: %s", msg);
ctx->ssl->fatallyErrored = true;
} else if (r == SSL_ERROR_SYSCALL) {
ctx->ssl->fatallyErrored = true;
}
throw SocketException(netinterfaceenums::ERR_CONN_SSL_HANDSHAKE,
"unexpected error in ssl handshake");
}
}
}
void StreamingSocketManagement::connectionThreadProcess()
{
ContextSet pendingContexts;
ContextSet pendingReadContexts;
ContextSet pendingWriteContexts;
NetSelector selector;
while (!threadShouldStop(CONN_MGMT_THREADID)) {
// Hold this the entire iteration, preventing any of our
// in-use contexts from being destroyed.
ReadLock ctxLock(contextMutex);
ContextSet newlyConnectedCtxs;
// Run through all down contexts.
// For each, if no connection in progress and time has come to try
// again, start the connection attempt.
ContextSet::iterator ctxIter;
{
Lock lock(downMutex);
for (ctxIter = downContexts.begin(); ctxIter != downContexts.end(); ++ctxIter) {
ConnectionContext *ctx = *ctxIter;
CommoTime nowTime = CommoTime::now();
if (!ctx->socket && nowTime > ctx->retryTime)
{
try {
ctx->socket = new TcpSocket(ctx->remoteEndpointAddr->family, false);
InternalUtils::logprintf(logger, CommoLogger::LEVEL_INFO, "Initiating streaming network connection for %s", ctx->remoteEndpoint.c_str());
if (ctx->socket->connect(ctx->remoteEndpointAddr)) {
// this connection succeeded immediately
// no need to rebuild just yet,
// just note as connected.
if (connectionThreadCheckSsl(ctx))
newlyConnectedCtxs.insert(ctx);
} else {
// Flag for rebuilding our pending socket set
downNeedsRebuild = true;
// Set connection timeout
ctx->retryTime = nowTime + connTimeoutSec;
}
} catch (SocketException &e) {
InternalUtils::logprintf(logger, CommoLogger::LEVEL_VERBOSE, "streaming socket connection initiation failed (%s); will retry", e.what());
fireInterfaceErr(ctx, e.errCode);
resetConnection(ctx, nowTime + CONN_RETRY_SECONDS, false);
}
}
}
if (downNeedsRebuild) {
std::vector<Socket *> pendingSockets;
std::vector<Socket *> pendingConnSockets;
std::vector<Socket *> pendingReadSockets;
pendingContexts.clear();
pendingWriteContexts.clear();
pendingReadContexts.clear();
for (ctxIter = downContexts.begin(); ctxIter != downContexts.end(); ++ctxIter) {
ConnectionContext *ctx = *ctxIter;
if (ctx->socket) {
if (ctx->connType == CONN_TYPE_SSL && ctx->ssl->writeState == SSLConnectionContext::WANT_READ) {
// Place on to read/write context list
pendingReadSockets.push_back(ctx->socket);
pendingReadContexts.insert(ctx);
} else {
if (ctx->connType == CONN_TYPE_SSL && ctx->ssl->writeState == SSLConnectionContext::WANT_WRITE)
pendingSockets.push_back(ctx->socket);
else
pendingConnSockets.push_back(ctx->socket);
pendingWriteContexts.insert(ctx);
}
pendingContexts.insert(ctx);
}
}
selector.setSockets(&pendingReadSockets, &pendingSockets, &pendingConnSockets);
downNeedsRebuild = false;
}
}
// If we have sockets with pending connections, select on them to see
// if they complete or error. However, skip past this and process
// any immediately connected sockets from above if we have such.
if (newlyConnectedCtxs.empty()) {
try {
if (!selector.doSelect(500)) {
// Timed out
CommoTime nowTime = CommoTime::now();
for (ctxIter = pendingContexts.begin(); ctxIter != pendingContexts.end(); ++ctxIter) {
ConnectionContext *ctx = *ctxIter;
bool stillConnecting = ctx->connType != CONN_TYPE_SSL || ctx->ssl->writeState == SSLConnectionContext::WANT_NONE;
if (nowTime > ctx->retryTime) {
if (stillConnecting)
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR, "Error trying to make network connection for %s - will retry (connection timed out)", ctx->remoteEndpoint.c_str());
else
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR, "Error trying to make network connection for %s - will retry (SSL handshake following connection timed out)", ctx->remoteEndpoint.c_str());
fireInterfaceErr(ctx, netinterfaceenums::ERR_CONN_TIMEOUT);
resetConnection(ctx, nowTime + CONN_RETRY_SECONDS, false);
downNeedsRebuild = true;
}
}
continue;
}
} catch (SocketException &) {
// Weird to get an error here, unless your name is Solaris
// which will apparently error on select() for sockets in error
// state. Anyway, if this happens restart all of them
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR, "Error from tcp connection select() - retrying connections");
CommoTime rTime = CommoTime::now() + CONN_RETRY_SECONDS;
for (ctxIter = pendingContexts.begin(); ctxIter != pendingContexts.end(); ++ctxIter) {
ConnectionContext *ctx = *ctxIter;
fireInterfaceErr(ctx, netinterfaceenums::ERR_CONN_OTHER);
resetConnection(ctx, rTime, false);
}
downNeedsRebuild = true;
continue;
}
// Something is ready; check for writes first as this
// is most common case
CommoTime nowTime = CommoTime::now();
for (ctxIter = pendingWriteContexts.begin(); ctxIter != pendingWriteContexts.end(); ++ctxIter) {
ConnectionContext *ctx = *ctxIter;
bool stillConnecting = ctx->connType != CONN_TYPE_SSL || ctx->ssl->writeState == SSLConnectionContext::WANT_NONE;
try {
if (selector.getLastConnectState(ctx->socket) != NetSelector::WRITABLE) {
if (nowTime > ctx->retryTime) {
if (stillConnecting)
throw SocketException(netinterfaceenums::ERR_CONN_TIMEOUT,
"tcp connection timed out");
else
throw SocketException(netinterfaceenums::ERR_CONN_TIMEOUT,
"SSL handshake following connection timed out");
}
continue;
}
if (stillConnecting) {
netinterfaceenums::NetInterfaceErrorCode errCode;
if (ctx->socket->isSocketErrored(&errCode)) {
throw SocketException(errCode,
"tcp socket connection error");
} else if (connectionThreadCheckSsl(ctx))
newlyConnectedCtxs.insert(ctx);
} else if (ctx->ssl->writeState == SSLConnectionContext::WANT_WRITE) {
// Is ssl and wanted write that is now fulfilled.
if (connectionThreadCheckSsl(ctx))
newlyConnectedCtxs.insert(ctx);
// else it now wants more writing or reading; all handled
// by CheckSsl().
}
} catch (SocketException &e) {
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR, "Error trying to make network connection for %s - will retry (%s)", ctx->remoteEndpoint.c_str(), e.what());
fireInterfaceErr(ctx, e.errCode);
resetConnection(ctx, nowTime + CONN_RETRY_SECONDS, false);
downNeedsRebuild = true;
}
}
for (ctxIter = pendingReadContexts.begin(); ctxIter != pendingReadContexts.end(); ++ctxIter) {
ConnectionContext *ctx = *ctxIter;
try {
if (selector.getLastReadState(ctx->socket) != NetSelector::READABLE) {
if (nowTime > ctx->retryTime)
throw SocketException(netinterfaceenums::ERR_CONN_TIMEOUT,
"SSL handshake following connection timed out waiting on read");
continue;
}
// Only ssl connections go to read pending!
// Just check the connect status.
if (connectionThreadCheckSsl(ctx))
newlyConnectedCtxs.insert(ctx);
} catch (SocketException &e) {
InternalUtils::logprintf(logger, CommoLogger::LEVEL_ERROR, "Error trying to make network connection for %s - will retry (%s)", ctx->remoteEndpoint.c_str(), e.what());
fireInterfaceErr(ctx, e.errCode);
resetConnection(ctx, CommoTime::now() + CONN_RETRY_SECONDS, false);
downNeedsRebuild = true;
}
}
}
if (!newlyConnectedCtxs.empty()) {
{
Lock lock(downMutex);
// Pull each from the down list
for (ctxIter = newlyConnectedCtxs.begin(); ctxIter != newlyConnectedCtxs.end(); ++ctxIter)
downContexts.erase(*ctxIter);
}
for (ctxIter = newlyConnectedCtxs.begin(); ctxIter != newlyConnectedCtxs.end(); ++ctxIter)
fireInterfaceChange(*ctxIter, true);
{
Lock lock(upMutex);
CommoTime now = CommoTime::now();
for (ctxIter = newlyConnectedCtxs.begin(); ctxIter != newlyConnectedCtxs.end(); ++ctxIter) {
InternalUtils::logprintf(logger, CommoLogger::LEVEL_INFO, "Stream connection to %s is up!", (*ctxIter)->remoteEndpoint.c_str());
(*ctxIter)->retryTime = now;
(*ctxIter)->lastRxTime = now;
(*ctxIter)->protoTimeout = now + PROTO_TIMEOUT_SECONDS;
upContexts.insert(*ctxIter);
}
ioNeedsRebuild = true;
}
downNeedsRebuild = true;
}
}
}
/*************************************************************************/
// StreamingSocketManagement - I/O thread
size_t StreamingSocketManagement::ioThreadSslRead(ConnectionContext *ctx) COMMO_THROW (SocketException)
{
ERR_clear_error();
int n = SSL_read(ctx->ssl->ssl, ctx->rxBuf + ctx->rxBufOffset, (int)(ConnectionContext::rxBufSize - ctx->rxBufOffset));
SSLConnectionContext::SSLWantState newState = SSLConnectionContext::WANT_NONE;
if (n <= 0) {
int n0 = n;
n = SSL_get_error(ctx->ssl->ssl, n);
switch (n) {
case SSL_ERROR_WANT_READ:
newState = SSLConnectionContext::WANT_READ;
break;
case SSL_ERROR_WANT_WRITE:
newState = SSLConnectionContext::WANT_WRITE;
break;
case SSL_ERROR_SSL:
case SSL_ERROR_SYSCALL:
ctx->ssl->fatallyErrored = true;
// Intentionally fall-through
default:
InternalUtils::logprintf(logger,
CommoLogger::LEVEL_ERROR,
"SSL Read fatal error - %d, %d",
n0,
n);
throw SocketException();
}
n = 0;
}
ctx->ssl->readState = newState;
return n;
}
size_t StreamingSocketManagement::ioThreadSslWrite(ConnectionContext *ctx, const uint8_t *data, size_t dataLen) COMMO_THROW (SocketException)
{
ERR_clear_error();
int n = SSL_write(ctx->ssl->ssl, data, (int)dataLen);
SSLConnectionContext::SSLWantState newState = SSLConnectionContext::WANT_NONE;
if (n <= 0) {
int n0 = n;
n = SSL_get_error(ctx->ssl->ssl, n);
switch (n) {
case SSL_ERROR_WANT_READ:
newState = SSLConnectionContext::WANT_READ;
break;
case SSL_ERROR_WANT_WRITE:
newState = SSLConnectionContext::WANT_WRITE;
break;
case SSL_ERROR_SSL:
case SSL_ERROR_SYSCALL:
ctx->ssl->fatallyErrored = true;
// Intentionally fall-through
default:
InternalUtils::logprintf(logger,
CommoLogger::LEVEL_ERROR,
"SSL Write fatal error - %d, %d",
n0,
n);
throw SocketException();
}
n = 0;
}
ctx->ssl->writeState = newState;
return n;
}
size_t StreamingSocketManagement::ioThreadWrite(ConnectionContext *ctx, const uint8_t *data, size_t n) COMMO_THROW (SocketException)
{
return ctx->socket->write(data, n);
}
void StreamingSocketManagement::ioThreadProcess()
{
// RX set is all "up" ifaces << rebuild on iface changes
// TX set is all "up" ifaces that are full wqueue << rebuilds on iface changes or tx status change
ContextSet rxSet;
std::vector<Socket *> rxSockets;
ContextSet txSet;
std::vector<Socket *> txSockets;
NetSelector selector;
while (!threadShouldStop(IO_THREADID)) {
ReadLock ctxLock(contextMutex);
ContextSet errorSet;
ContextSet::iterator ctxIter;
ConnectionContext *ctx;
// Set if txSet has changes and tx socket set needs rebuilding
bool txNeedsRebuild = false;
{
Lock upLock(upMutex);
// If list of contexts has externally changed, don't use existing
// socket sets or txSet. Just rebuild everything
if (ioNeedsRebuild) {
txSet.clear();
rxSet.clear();
rxSockets.clear();
txNeedsRebuild = true;
}
for (ctxIter = upContexts.begin(); ctxIter != upContexts.end(); ++ctxIter) {
ctx = *ctxIter;
bool inTxSelection = txSet.find(ctx) != txSet.end();
size_t (StreamingSocketManagement::*writeFunc)(ConnectionContext *ctx, const uint8_t *, size_t);
bool isSSL = ctx->connType == CONN_TYPE_SSL;
bool doTx;
if (isSSL) {
doTx = ctx->ssl->writeState == SSLConnectionContext::WANT_NONE ||
(!ioNeedsRebuild && ((ctx->ssl->writeState == SSLConnectionContext::WANT_WRITE && selector.getLastWriteState(ctx->socket) == NetSelector::WRITABLE) ||
(ctx->ssl->writeState == SSLConnectionContext::WANT_READ && selector.getLastReadState(ctx->socket) == NetSelector::READABLE)));
writeFunc = &StreamingSocketManagement::ioThreadSslWrite;
} else {
doTx = !inTxSelection || selector.getLastWriteState(ctx->socket) == NetSelector::WRITABLE;
writeFunc = &StreamingSocketManagement::ioThreadWrite;
}
try {
if (doTx) {
// Tx might have room
while (!ctx->txQueue.empty() && !ctx->protoBlockedForResponse) {