-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPyConnectNetComm.cpp
More file actions
1493 lines (1327 loc) · 40.6 KB
/
PyConnectNetComm.cpp
File metadata and controls
1493 lines (1327 loc) · 40.6 KB
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
/*
* PyConnectNetComm.cpp
*
* Copyright 2006, 2007 Xun Wang.
* This file is part of PyConnect.
*
* PyConnect is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* PyConnect is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef WIN32
#pragma warning( disable: 4309 )
#endif
#ifdef PYTHON_SERVER
#include "Python.h"
#endif
#ifndef WIN32
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
#include <dirent.h>
#include <fnmatch.h>
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <errno.h>
#ifdef LINUX
#include <stddef.h>
#endif
#endif
#include "PyConnectNetComm.h"
#ifndef WIN32
#define max( a, b ) (a > b) ? a : b
#endif
#ifdef WIN32
typedef unsigned long in_addr_t;
#endif
namespace pyconnect {
static int kTCPMSS = 1024;
PyConnectNetComm * PyConnectNetComm::s_pPyConnectNetComm = NULL;
PyConnectNetComm * PyConnectNetComm::instance()
{
if (!s_pPyConnectNetComm)
s_pPyConnectNetComm = new PyConnectNetComm();
return s_pPyConnectNetComm;
}
PyConnectNetComm::PyConnectNetComm() :
ObjectComm(),
pMP_( NULL ),
udpSocket_( INVALID_SOCKET ),
tcpSocket_( INVALID_SOCKET ),
domainSocket_( INVALID_SOCKET ),
dgramBuffer_( NULL ),
clientDataBuffer_( NULL ),
dispatchDataBuffer_( NULL ),
clientFDList_( NULL ),
maxFD_( 0 ),
netCommEnabled_( false ),
IPCCommEnabled_( false ),
invalidUDPSock_( false ),
keepRunning_( true ),
portInUse_( PYCONNECT_NETCOMM_PORT )
{
}
PyConnectNetComm::~PyConnectNetComm()
{
#ifdef WIN32
WSACleanup();
#endif
#ifdef MULTI_THREAD
#ifdef WIN32
DeleteCriticalSection( &g_criticalSection );
#else
pthread_mutex_destroy( &g_mutex );
#endif
#endif
}
void PyConnectNetComm::init( MessageProcessor * pMP, FDSetOwner * fdOwner )
{
endecryptInit();
pMP_ = pMP;
setMP( pMP );
pMP_->addCommObject( this );
pFDOwner_ = fdOwner;
updateMPID();
FD_ZERO( &masterFDSet_ );
#ifdef PYTHON_SERVER
enableNetComm();
#ifndef WIN32
enableIPCComm();
#endif // !WIN32
#endif
}
bool PyConnectNetComm::initUDPListener()
{
if ((udpSocket_ = socket( AF_INET, SOCK_DGRAM, 0 ) ) == INVALID_SOCKET) {
ERROR_MSG( "PyConnectNetComm::initUDPListener: unable to create UDP socket.\n" );
invalidUDPSock_ = true;
return false;
}
// setup broadcast option
int turnon = 1;
#ifdef USE_MULTICAST
char ttl = 30;
if (setsockopt( udpSocket_, IPPROTO_IP, IP_MULTICAST_TTL, (char *)&ttl, sizeof( ttl ) ) < 0) {
ERROR_MSG( "PyConnectNetComm::initUDPListener: failed to set multicast TTL on UDP socket.\n" );
#ifdef WIN32
closesocket( udpSocket_ );
#else
close( udpSocket_ );
#endif
invalidUDPSock_ = true;
return false;
}
if (setsockopt( udpSocket_, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&multiCastReq_, sizeof( multiCastReq_ ) ) < 0) {
ERROR_MSG( "PyConnectNetComm::initUDPListener: failed to join multicast group on UDP socket.\n" );
#ifdef WIN32
closesocket( udpSocket_ );
#else
close( udpSocket_ );
#endif
invalidUDPSock_ = true;
return false;
}
#else // !USE_MULTICAST
if (setsockopt( udpSocket_, SOL_SOCKET, SO_BROADCAST, (char *)&turnon, sizeof( turnon ) ) < 0) {
ERROR_MSG( "PyConnectNetComm::initUDPListener: failed to enable broadcast on UDP socket.\n" );
#ifdef WIN32
closesocket( udpSocket_ );
#else
close( udpSocket_ );
#endif
invalidUDPSock_ = true;
return false;
}
#endif
if (setsockopt( udpSocket_, SOL_SOCKET, SO_REUSEADDR, (char *)&turnon, sizeof( turnon ) ) < 0) {
ERROR_MSG( "PyConnectNetComm::initUDPListener: failed to enable reuse address on UDP socket.\n" );
#ifdef WIN32
closesocket( udpSocket_ );
#else
close( udpSocket_ );
#endif
invalidUDPSock_ = true;
return false;
}
#ifdef SO_REUSEPORT
setsockopt( udpSocket_, SOL_SOCKET, SO_REUSEPORT, (char *)&turnon, sizeof( turnon ) );
#endif
sAddr_.sin_port = htons( PYCONNECT_NETCOMM_PORT );
if (bind( udpSocket_, (struct sockaddr *)&sAddr_, sizeof( sAddr_ ) ) < 0) {
ERROR_MSG( "PyConnectNetComm::initUDPListener: unable to bind to network interface.\n" );
#ifdef WIN32
closesocket( udpSocket_ );
#else
close( udpSocket_ );
#endif
invalidUDPSock_ = true;
return false;
}
#ifdef WIN32
maxFD_++;
#else
maxFD_ = max( maxFD_, udpSocket_ );
#endif
FD_SET( udpSocket_, &masterFDSet_ );
if (pFDOwner_)
pFDOwner_->setFD( udpSocket_ );
if (dgramBuffer_ == NULL)
dgramBuffer_ = new unsigned char[PYCONNECT_UDP_BUFFER_SIZE];
return true;
}
bool PyConnectNetComm::initTCPListener()
{
if ((tcpSocket_ = socket( AF_INET, SOCK_STREAM, 0 )) == INVALID_SOCKET) {
ERROR_MSG( "PyConnectNetComm::initTCPListener: unable to create TCP socket.\n" );
return false;
}
#ifndef WIN32
int turnon = 1;
if (setsockopt( tcpSocket_, SOL_SOCKET, SO_REUSEADDR, (char *)&turnon, sizeof( turnon ) ) < 0) {
ERROR_MSG( "PyConnectNetComm::initTCPListener: failed to enable reuse addr option on TCP socket.\n" );
close( tcpSocket_ );
return false;
}
#endif
int triedPorts = 0;
sAddr_.sin_port = htons( portInUse_ );
int bindRet = bind( tcpSocket_, (struct sockaddr *)&sAddr_, sizeof( sAddr_ ) );
while (bindRet < 0 && triedPorts < PYCONNECT_COMMPORT_RANGE) {
triedPorts++;
sAddr_.sin_port = htons( portInUse_ + triedPorts );
bindRet = bind( tcpSocket_, (struct sockaddr *)&sAddr_, sizeof( sAddr_ ) );
}
if (bindRet < 0) {
ERROR_MSG( "PyConnectNetComm::initTCPListener: unable to bind to network interface.\n" );
#ifdef WIN32
closesocket( tcpSocket_ );
#else
close( tcpSocket_ );
#endif
return false;
}
portInUse_ = sAddr_.sin_port; // now in network byte order
if (listen( tcpSocket_, 5 ) < 0) {
ERROR_MSG( "PyConnectNetComm::initTCPListener: unable to listen for incoming data.\n" );
#ifdef WIN32
closesocket( tcpSocket_ );
#else
close( tcpSocket_ );
#endif
return false;
}
INFO_MSG( "Listening on TCP port %d\n", ntohs( portInUse_ ) & 0xffff );
#ifdef WIN32
maxFD_++;
#else
maxFD_ = max( maxFD_, tcpSocket_ );
#endif
FD_SET( tcpSocket_, &masterFDSet_ );
if (pFDOwner_)
pFDOwner_->setFD( tcpSocket_ );
if (clientDataBuffer_ == NULL)
clientDataBuffer_ = new unsigned char[PYCONNECT_TCP_BUFFER_SIZE];
if (dispatchDataBuffer_ == NULL)
dispatchDataBuffer_ = new unsigned char[PYCONNECT_MSG_BUFFER_SIZE];
return true;
}
void PyConnectNetComm::processIncomingData( fd_set * readyFDSet )
{
struct sockaddr_in cAddr;
int cLen = sizeof( cAddr );
SOCKET_T fd = INVALID_SOCKET;
if (netCommEnabled_) {
if (FD_ISSET( udpSocket_, readyFDSet )) {
int readLen = (int)recvfrom( udpSocket_, (char*)dgramBuffer_, PYCONNECT_UDP_BUFFER_SIZE,
0, (sockaddr *)&cAddr, (socklen_t *)&cLen );
if (readLen <= 0) {
ERROR_MSG( "PyConnectNetComm::continuousProcessing: error accepting "
"incoming UDP packet. error %d\n", errno );
}
else {
processUDPInput( dgramBuffer_, readLen, cAddr );
}
}
if (FD_ISSET( tcpSocket_, readyFDSet )) {
// accept incoming TCP connection and read the stream
fd = accept( tcpSocket_, (sockaddr *)&cAddr, (socklen_t *)&cLen );
if (fd != INVALID_SOCKET) {
addFdToClientList( fd, PyConnectNetComm::NETWORK, &cAddr );
}
#ifdef WIN32
else if (errno != WSAECONNABORTED) {
#else
else if (errno != ECONNABORTED) {
#endif
ERROR_MSG( "PyConnectNetComm::continuousProcessing: error accepting "
"incoming TCP connection error = %d\n", errno );
}
}
}
if (IPCCommEnabled_ && FD_ISSET( domainSocket_, readyFDSet )) {
// accept incoming local socket connection and read the stream
fd = accept( domainSocket_, (sockaddr *)&cAddr, (socklen_t *)&cLen );
if (fd != INVALID_SOCKET) {
addFdToClientList( fd, PyConnectNetComm::LOCALIPC, &cAddr );
}
#ifdef WIN32
else if (errno != WSAECONNABORTED) {
#else
else if (errno != ECONNABORTED) {
#endif
ERROR_MSG( "PyConnectNetComm::continuousProcessing: error accepting "
"incoming local IPC connection error = %d\n", errno );
}
}
ClientFD * FDPtr = clientFDList_;
ClientFD * prevFDPtr = FDPtr;
while (FDPtr) {
fd = FDPtr->fd;
if (FD_ISSET( fd, readyFDSet )) {
#ifdef WIN32
int readLen = recv( fd, (char*)clientDataBuffer_, kTCPMSS, 0 );
#else
int readLen = (int)read( fd, clientDataBuffer_, kTCPMSS );
#endif
if (readLen <= 0) {
if (readLen == 0) {
INFO_MSG( "Socket connection %d closed.\n", fd );
}
else {
ERROR_MSG( "PyConnectNetComm::continuousProcessing: "
"error reading data stream on %d error = %d.\n", fd, errno );
}
objCommChannelShutdown( fd, true );
destroyCurrentClient( FDPtr, prevFDPtr );
continue;
}
else {
#ifdef MULTI_THREAD
#ifdef WIN32
EnterCriticalSection( &g_criticalSection );
#else
pthread_mutex_lock( &g_mutex );
#endif
#endif
setLastUsedCommChannel( fd );
//DEBUG_MSG( "receive data from fd %d\n", fd );
#ifdef MULTI_THREAD
#ifdef WIN32
LeaveCriticalSection( &g_criticalSection );
#else
pthread_mutex_unlock( &g_mutex );
#endif
#endif
MesgProcessResult procResult = MESG_PROCESSED_OK;
unsigned char * dataPtr = clientDataBuffer_;
do {
if (*dataPtr == PYCONNECT_MSG_INIT && FDPtr->dataInfo.expectedDataLength == 0) { // new message
if (readLen < 4) {
ERROR_MSG( "PyConnectNetComm::continuousProcessing: "
"invalid data packet in stream on %d (too small).\n", fd );
break;
}
dataPtr++;
short dataCount = 0;
memcpy( &dataCount, dataPtr, sizeof( short ) ); dataPtr += sizeof( short );
readLen -= 3;
if (dataCount < 0 || dataCount > PYCONNECT_MSG_BUFFER_SIZE) { // encryption buffer size
ERROR_MSG( "PyConnectNetComm::continuousProcessing: "
"invalid data size in stream on %d.\n", fd );
break;
}
else if (dataCount > (readLen - 1)) { // the message needs multiple reads
FDPtr->dataInfo.bufferedDataLength = readLen;
memcpy( FDPtr->dataInfo.bufferedData, dataPtr, FDPtr->dataInfo.bufferedDataLength );
FDPtr->dataInfo.expectedDataLength = dataCount - FDPtr->dataInfo.bufferedDataLength;
readLen = 0;
}
else if (*(dataPtr + dataCount) == PYCONNECT_MSG_END) { // valid message
pMP_->processInput( dataPtr, dataCount, FDPtr->cAddr );
readLen -= (dataCount + 1);
dataPtr += (dataCount + 1);
}
else {
ERROR_MSG( "PyConnectNetComm::continuousProcessing: "
"invalid data packet in stream on %d.\n", fd );
break;
}
}
else if (FDPtr->dataInfo.expectedDataLength > 0) { // patch up cached data
unsigned char * cachedPtr = FDPtr->dataInfo.bufferedData + FDPtr->dataInfo.bufferedDataLength;
if (FDPtr->dataInfo.expectedDataLength > (readLen - 1)) { // continue to cache
memcpy( cachedPtr, dataPtr, readLen );
FDPtr->dataInfo.bufferedDataLength += readLen;
FDPtr->dataInfo.expectedDataLength -= readLen;
readLen = 0;
}
else if (*(dataPtr + FDPtr->dataInfo.expectedDataLength) == PYCONNECT_MSG_END) { // valid message
memcpy( cachedPtr, dataPtr, FDPtr->dataInfo.expectedDataLength );
pMP_->processInput( FDPtr->dataInfo.bufferedData,
FDPtr->dataInfo.bufferedDataLength + FDPtr->dataInfo.expectedDataLength,
FDPtr->cAddr );
readLen -= (FDPtr->dataInfo.expectedDataLength + 1);
if (readLen > 0) {
dataPtr += (FDPtr->dataInfo.expectedDataLength + 1);
}
FDPtr->dataInfo.bufferedDataLength = 0;
FDPtr->dataInfo.expectedDataLength = 0;
}
else {
ERROR_MSG( "PyConnectNetComm::continuousProcessing: "
"unexpected data fragment in data stream on %d.\n", fd );
FDPtr->dataInfo.bufferedDataLength = 0;
FDPtr->dataInfo.expectedDataLength = 0;
break;
}
}
else {
ERROR_MSG( "PyRideNetComm::continuousProcessing: "
"invalid data stream on %d.\n", fd );
FDPtr->dataInfo.bufferedDataLength = 0;
FDPtr->dataInfo.expectedDataLength = 0;
break;
}
} while (readLen > 0);
if (procResult == MESG_TO_SHUTDOWN) {
objCommChannelShutdown( fd );
destroyCurrentClient( FDPtr, prevFDPtr );
continue;
}
}
}
prevFDPtr = FDPtr;
FDPtr = FDPtr->pNext;
}
}
void PyConnectNetComm::continuousProcessing()
{
int maxFD = 0;
fd_set readyFDSet;
while (keepRunning_) {
FD_ZERO( &readyFDSet );
memcpy( &readyFDSet, &masterFDSet_, sizeof( masterFDSet_ ) );
maxFD = maxFD_;
#ifdef MULTI_THREAD
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 200000; // 200ms
#endif
// we must be able to interrupt select since masterFDSet_ might
// be updated by the main thread (i.e. calling PyConnect.connect).
// For this we use timeout as a solution. NOTE: an alternative
// solution for POSIX system might be that still using block select
// but send a signal from main thread to interrupt it when connect
// is completed.
#if defined( MULTI_THREAD )
select( maxFD + 1, &readyFDSet, NULL, NULL, &timeout );
#else
select( maxFD + 1, &readyFDSet, NULL, NULL, NULL ); // blocking select
#endif
this->processIncomingData( &readyFDSet );
}
}
void PyConnectNetComm::dataPacketSender( const unsigned char * data, int size, bool broadcast )
{
if (broadcast) {
// a hack job to pass on TCP port in use in declaration messages
int msgType = verifyNegotiationMsg( data, size );
if (msgType == pyconnect::MODULE_DISCOVERY ||
msgType == pyconnect::MODULE_DECLARE)
{
if (netCommEnabled_) {
unsigned char * modData = new unsigned char[size + sizeof( short )];
memcpy( modData, data, size - 1 ); // exclude message end char
unsigned char * modDataPtr = modData + size - 1;
memcpy( modDataPtr, (unsigned char *)&portInUse_, sizeof( short ) );
modDataPtr += sizeof( short );
*modDataPtr = pyconnect::PYCONNECT_MSG_END;
netBroadcastSend( modData, size + sizeof( short ) );
delete [] modData;
}
if (IPCCommEnabled_) {
localBroadcastSend( data, size );
}
}
else {
if (netCommEnabled_)
netBroadcastSend( data, size );
if (IPCCommEnabled_)
localBroadcastSend( data, size );
}
}
else {
clientDataSend( data, size );
}
}
void PyConnectNetComm::netBroadcastSend( const unsigned char * data, int size )
{
if (size <= 0) return;
unsigned char * outputData = NULL;
int outputLength = 0;
if (encryptMessage( data, size, &outputData, &outputLength ) != 1) {
return;
}
#ifdef MULTI_THREAD
#ifdef WIN32
EnterCriticalSection( &g_criticalSection );
#else
pthread_mutex_lock( &g_mutex );
#endif
#endif
if (netCommEnabled_) {
if (sendto( udpSocket_, (char*)outputData, outputLength, 0, (struct sockaddr *)&bcAddr_, sizeof( bcAddr_ ) ) < 0) {
ERROR_MSG( "PyConnectNetComm::broadcastSend: Error sending UDP broadcast packet.\n" );
}
}
#ifdef MULTI_THREAD
#ifdef WIN32
LeaveCriticalSection( &g_criticalSection );
#else
pthread_mutex_unlock( &g_mutex );
#endif
#endif
}
void PyConnectNetComm::localBroadcastSend( const unsigned char * data, int size )
{
#ifndef WIN32
if (size <= 0) return;
unsigned char * outputData = NULL;
int outputLength = 0;
if (encryptMessage( data, size, &outputData, &outputLength ) != 1) {
return;
}
#ifdef MULTI_THREAD
pthread_mutex_lock( &g_mutex );
#endif
if (IPCCommEnabled_) {
SOCKET_T fd = INVALID_SOCKET;
// make sure connections to all available servers are established
consolidateIPCSockets();
unsigned char * dataPtr = dispatchDataBuffer_;
*dataPtr++ = PYCONNECT_MSG_INIT;
short opl = (short) outputLength;
memcpy( dataPtr, &opl, sizeof( short ) );
dataPtr += sizeof( short );
memcpy( dataPtr, outputData, outputLength );
dataPtr += outputLength;
*dataPtr = PYCONNECT_MSG_END;
outputLength += (2 + sizeof( short ));
for (ClientSocketList::const_iterator iter = liveServerSocketList_.begin();
iter != liveServerSocketList_.end(); ++iter)
{
fd = findOrCreateIPCTalker( *iter );
if (fd != INVALID_SOCKET)
send( fd, dispatchDataBuffer_, outputLength, 0 );
}
}
#ifdef MULTI_THREAD
pthread_mutex_unlock( &g_mutex );
#endif
#endif // !WIN32
}
void PyConnectNetComm::clientDataSend( const unsigned char * data, int size )
{
if (size <= 0) return;
unsigned char * outputData = NULL;
int outputLength = 0;
if (encryptMessage( data, size, &outputData, &outputLength ) != 1) {
return;
}
#ifdef MULTI_THREAD
#ifdef WIN32
EnterCriticalSection( &g_criticalSection );
#else
pthread_mutex_lock( &g_mutex );
#endif
#endif
SOCKET_T mysock = findOrAddCommChanByMsgID( data );
if (mysock != INVALID_SOCKET) {
//DEBUG_MSG( "dispatch data to fd %d\n", mysock );
unsigned char * dataPtr = dispatchDataBuffer_;
*dataPtr++ = PYCONNECT_MSG_INIT;
short opl = (short) outputLength;
memcpy( dataPtr, &opl, sizeof( short ) );
dataPtr += sizeof( short );
memcpy( dataPtr, outputData, outputLength );
dataPtr += outputLength;
*dataPtr = PYCONNECT_MSG_END;
outputLength += (2 + sizeof( short ));
#ifdef WIN32
send( mysock, (char*)dispatchDataBuffer_, outputLength, 0 );
#else
write( mysock, dispatchDataBuffer_, outputLength );
#endif
}
#ifdef MULTI_THREAD
#ifdef WIN32
LeaveCriticalSection( &g_criticalSection );
#else
pthread_mutex_unlock( &g_mutex );
#endif
#endif
}
void PyConnectNetComm::processUDPInput( unsigned char * recBuffer, int recBytes, struct sockaddr_in & cAddr )
{
unsigned char * message = NULL;
int messageSize = 0;
if (decryptMessage( recBuffer, (int)recBytes, &message, (int *)&messageSize ) != 1) {
WARNING_MSG( "Unable to decrypt incoming messasge.\n" );
return;
}
// initialise a new TCP connection
switch (verifyNegotiationMsg( message, messageSize )) {
#ifdef PYTHON_SERVER
case pyconnect::MODULE_DISCOVERY:
break;
case pyconnect::PEER_SERVER_MSG:
{
if (pMP_)
pMP_->processInput( message, messageSize, cAddr );
}
break;
case pyconnect::MODULE_DECLARE:
case pyconnect::PEER_SERVER_DISCOVERY:
#else
case pyconnect::MODULE_DECLARE:
case pyconnect::PEER_SERVER_DISCOVERY:
case pyconnect::PEER_SERVER_MSG:
break;
case pyconnect::MODULE_DISCOVERY:
#endif
{
short port = 0;
// extract TCP port and restore message
unsigned char * portStrPtr = &message[messageSize - sizeof( short ) - 1];
memcpy( (unsigned char *)&port, portStrPtr, sizeof( short ) );
//DEBUG_MSG( "incoming port %d\n", ntohs( port ) & 0xffff );
cAddr.sin_port = port;
message[messageSize - sizeof( short ) - 1] = pyconnect::PYCONNECT_MSG_END;
if (createTCPTalker( cAddr )) { // process udp data
MesgProcessResult procResult = pMP_->processInput( message, messageSize - sizeof( short ), cAddr, true );
if (procResult == MESG_TO_SHUTDOWN) {
SOCKET_T fd = getLastUsedCommChannel();
objCommChannelShutdown( fd );
destroyCurrentClient( fd );
}
}
else {
#ifdef WIN32
ERROR_MSG( "PyConnectNetComm::processUDPInput: Unable to "
"create connection to %s:%d\n", inet_ntoa( cAddr.sin_addr ),
ntohs( cAddr.sin_port ) );
#else
char cAddrStr[INET_ADDRSTRLEN];
inet_ntop( AF_INET, &cAddr.sin_addr.s_addr, cAddrStr, INET_ADDRSTRLEN );
ERROR_MSG( "PyConnectNetComm::processUDPInput: Unable to "
"create connection to %s:%d\n", cAddrStr, ntohs( cAddr.sin_port ) );
#endif
}
}
break;
default:
ERROR_MSG( "PyConnectNetComm::processUDPInput()"
"Unknown negotiation message\n" );
}
}
bool PyConnectNetComm::createTCPTalker( struct sockaddr_in & cAddr )
{
SOCKET_T mySocket = socket( AF_INET, SOCK_STREAM, 0 );
if (mySocket == INVALID_SOCKET)
return false;
if (connect( mySocket, (struct sockaddr *)&cAddr, sizeof( cAddr ) ) < 0) {
#ifdef WIN32
closesocket( mySocket );
#else
close( mySocket );
#endif
return false;
}
addFdToClientList( mySocket, PyConnectNetComm::NETWORK, &cAddr );
return true;
}
#ifndef WIN32
SOCKET_T PyConnectNetComm::findOrCreateIPCTalker( int procID )
{
SOCKET_T mySocket = findFdFromClientListByProcID( procID );
if (mySocket != INVALID_SOCKET)
return mySocket;
mySocket = socket( AF_UNIX, SOCK_STREAM, 0 );
if (mySocket != INVALID_SOCKET) {
struct sockaddr_un dAddr;
memset( &dAddr, 0, sizeof( dAddr ) );
dAddr.sun_family = AF_UNIX;
sprintf( dAddr.sun_path, "%s/%s.%05d", PYCONNECT_DOMAINSOCKET_PATH,
PYCONNECT_CLTSOCKET_PREFIX, procID );
int connLen = int(offsetof( struct sockaddr_un, sun_path ) + strlen( dAddr.sun_path ));
if (connect( mySocket, (struct sockaddr *)&dAddr, connLen ) < 0) {
close( mySocket );
mySocket = INVALID_SOCKET;
}
INFO_MSG( "connect to %s\n", dAddr.sun_path );
struct sockaddr_in dummy;
memset( &dummy, 0, sizeof( dummy ) );
addFdToClientList( mySocket, PyConnectNetComm::LOCALIPC, &dummy, procID );
}
return mySocket;
}
SOCKET_T PyConnectNetComm::findFdFromClientListByProcID( int procID ) // for IPC only
{
bool found = false;
ClientFD * fdPtr = clientFDList_;
while (fdPtr) {
if (fdPtr->domain == PyConnectNetComm::LOCALIPC) {
found = (fdPtr->localProcID == procID);
if (found) break;
}
fdPtr = fdPtr->pNext;
}
if (found) {
setLastUsedCommChannel( fdPtr->fd );
return fdPtr->fd;
}
return INVALID_SOCKET;
}
void PyConnectNetComm::consolidateIPCSockets()
{
DIR * socketDir = opendir( PYCONNECT_DOMAINSOCKET_PATH );
if (!socketDir) {
ERROR_MSG( "Unable to access IPC path %s\n", PYCONNECT_DOMAINSOCKET_PATH );
return;
}
char socketPattern[10];
sprintf( socketPattern, "%s.*", PYCONNECT_CLTSOCKET_PREFIX );
struct dirent * dp = NULL;
ClientSocketList deadSocketList;
liveServerSocketList_.clear();
while ((dp = readdir( socketDir )) != NULL) {
if (fnmatch( socketPattern, dp->d_name, 0 ) == 0) {
// find corresponding process that create the socket
int procID = (int)strtol( strlen( PYCONNECT_CLTSOCKET_PREFIX ) + 1 + dp->d_name, (char **)NULL, 10 );
if (procID == 0) {
ERROR_MSG( "socket file name %s contains invalid process number\n", dp->d_name );
continue;
}
bool foundProc = false;
#ifdef BSD_COMPAT
// check whether the process is still running
int kernQuery[4];
struct kinfo_proc kp;
size_t kplen = sizeof( kp );
kernQuery[0] = CTL_KERN;
kernQuery[1] = KERN_PROC;
kernQuery[2] = KERN_PROC_PID;
kernQuery[3] = procID;
foundProc = ((sysctl( kernQuery, 4, &kp, &kplen, NULL, 0 ) == 0) && kplen > 0);
#else // linux / solaris like
char procIDStr[6];
sprintf( procIDStr, "%d", procID );
DIR * procDir = opendir( "/proc" );
struct dirent * procdp = NULL;
while ((procdp = readdir( procDir )) != NULL && !foundProc) {
foundProc = (strcmp( procIDStr, procdp->d_name ) == 0);
}
closedir( procDir );
#endif
if (foundProc) { //push onto a existing client list
liveServerSocketList_.push_back( procID );
}
else { // push onto a dead socket list
deadSocketList.push_back( procID );
}
}
}
closedir( socketDir );
char deadSocket[20];
for (ClientSocketList::const_iterator iter = deadSocketList.begin();
iter != deadSocketList.end(); ++iter)
{
sprintf( deadSocket, "%s/%s.%05d", PYCONNECT_DOMAINSOCKET_PATH,
PYCONNECT_CLTSOCKET_PREFIX, *iter );
INFO_MSG( "Removing dead socket %s\n", deadSocket );
unlink( deadSocket );
}
deadSocketList.clear();
}
#endif // !WIN32
void PyConnectNetComm::enableNetComm()
{
if (netCommEnabled_)
return;
sAddr_.sin_family = AF_INET;
sAddr_.sin_addr.s_addr = INADDR_ANY;
bcAddr_.sin_family = AF_INET;
#ifdef WIN32
bcAddr_.sin_addr.s_addr = inet_addr( PYCONNECT_BROADCAST_IP );
#else
inet_pton( AF_INET, PYCONNECT_BROADCAST_IP, &bcAddr_.sin_addr.s_addr );
#endif
bcAddr_.sin_port = htons( PYCONNECT_NETCOMM_PORT );
#ifdef USE_MULTICAST
multiCastReq_.imr_multiaddr.s_addr = bcAddr_.sin_addr.s_addr;
multiCastReq_.imr_interface.s_addr = INADDR_ANY;
#endif
netCommEnabled_ = initUDPListener();
netCommEnabled_ &= initTCPListener();
if (!netCommEnabled_) {
ERROR_MSG( "PyConnectNetComm::enableNetComm: Unable to initialise network "
"communication layer!\n" );
#ifdef WIN32
WSACleanup();
#endif
}
}
void PyConnectNetComm::disableNetComm( bool onExit )
{
if (!netCommEnabled_)
return;
#ifdef MULTI_THREAD // maybe little over zealous here
#ifdef WIN32
EnterCriticalSection( &g_criticalSection );
#else
pthread_mutex_lock( &g_mutex );
#endif
#endif
ClientFD * fdPtr = clientFDList_;
while (fdPtr) {
if (fdPtr->domain != PyConnectNetComm::NETWORK) {
fdPtr = fdPtr->pNext;
continue;
}
objCommChannelShutdown( fdPtr->fd, !onExit );
#ifdef WIN32
shutdown( fdPtr->fd, SD_SEND );
closesocket( fdPtr->fd );
#else
close( fdPtr->fd );
#endif
if (pFDOwner_) {
pFDOwner_->clearFD( fdPtr->fd );
}
else {
FD_CLR( fdPtr->fd, &masterFDSet_ );
#ifdef WIN32
maxFD_--; // not really used
#endif
}
ClientFD * tmpPtr = fdPtr;
fdPtr = fdPtr->pNext;
delete tmpPtr;
}
#ifdef USE_MULTICAST
setsockopt( udpSocket_, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&multiCastReq_, sizeof( multiCastReq_ ) );
#endif
#ifdef WIN32
shutdown( udpSocket_, SD_SEND );
closesocket( udpSocket_ );
shutdown( tcpSocket_, SD_SEND );
closesocket( tcpSocket_ );
#else
close( udpSocket_ );
close( tcpSocket_ );
#endif
if (pFDOwner_) {
pFDOwner_->clearFD( udpSocket_ );
pFDOwner_->clearFD( tcpSocket_ );
}
delete [] dgramBuffer_;
dgramBuffer_ = NULL;
#ifdef MULTI_THREAD
#ifdef WIN32
LeaveCriticalSection( &g_criticalSection );
#else
pthread_mutex_unlock( &g_mutex );
#endif
#endif
#ifdef WIN32
WSACleanup();
#endif
netCommEnabled_ = false;
}
#ifndef WIN32
void PyConnectNetComm::enableIPCComm()
{
if (IPCCommEnabled_)
return;
if ((domainSocket_ = socket( AF_UNIX, SOCK_STREAM, 0 )) == INVALID_SOCKET) {
ERROR_MSG( "PyConnectNetComm::enableIPCComm: unable to create unix domain socket.\n" );
return;
}
struct sockaddr_un dAddr;
memset( &dAddr, 0, sizeof( dAddr ) );
dAddr.sun_family = AF_UNIX;
sprintf( dAddr.sun_path, "%s/%s.%05d", PYCONNECT_DOMAINSOCKET_PATH,
PYCONNECT_SVRSOCKET_PREFIX, getpid() );
unlink( dAddr.sun_path );
consolidateIPCSockets();
int bindLen = int(offsetof( struct sockaddr_un, sun_path ) + strlen( dAddr.sun_path ));
if (bind( domainSocket_, (struct sockaddr *)&dAddr, bindLen ) < 0) {
ERROR_MSG( "PyConnectNetComm::enableIPCComm: unable to bind to local domain socket.\n" );
#ifdef WIN32
#else
close( domainSocket_ );
#endif
return;
}
if (listen( domainSocket_, 5 ) < 0) {
ERROR_MSG( "PyConnectNetComm::enableIPCComm: unable to listen on local socket for incoming data.\n" );
#ifdef WIN32
#else
close( domainSocket_ );
#endif
return;
}
// make socket user/group read and write
chmod( dAddr.sun_path, S_IRWXU | S_IRGRP | S_IWGRP );
INFO_MSG( "Listening on local socket %s\n", dAddr.sun_path );
#ifdef WIN32
maxFD_++;
#else
maxFD_ = max( maxFD_, domainSocket_ );