-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPythonServer.cpp
More file actions
1523 lines (1299 loc) · 39 KB
/
PythonServer.cpp
File metadata and controls
1523 lines (1299 loc) · 39 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
#include <string.h>
#include <locale>
#include <codecvt>
#include <string>
#include "PythonServer.h"
namespace pyride {
#define max( a, b ) (a > b) ? a : b
#if PY_MAJOR_VERSION >= 3
#define PyInt_FromLong PyLong_FromLong
#define PyInt_AsLong PyLong_AsLong
#define PyInt_Check PyLong_Check
#endif
static const char goodByeMsg[] = "\r\nGoodbye from UTS PyRIDE Python Console.\r\n";
PythonServer * PythonServer::s_pPythonServer = NULL;
void * pytelnet_thread( void * processor )
{
((PythonServer *)processor)->continuousProcessing();
return NULL;
}
PythonServer * PythonServer::instance()
{
if (!s_pPythonServer)
s_pPythonServer = new PythonServer();
return s_pPythonServer;
}
PythonServer::PythonServer() :
runThread_( (pthread_t)NULL ),
isActive_( false ),
hasInterpreter_( false ),
intpState_( NULL ),
prevStderr_( NULL ),
prevStdout_( NULL ),
pSysModule_( NULL ),
pMainModule_( NULL ),
pMainScript_( NULL ),
pPyMod_( NULL ),
udpSocket_( INVALID_SOCKET ),
tcpSocket_( INVALID_SOCKET ),
dgramBuffer_( NULL ),
clientDataBuffer_( NULL ),
clientList_( NULL ),
maxFD_( INVALID_SOCKET ),
runningTelnetConsole_( false ),
keepRunning_( false ),
activeSession_( NULL ),
pyModuleExtension_( NULL )
{
customPythonHome[0] = '\0';
customScriptBase[0] = '\0';
initIPAddresses();
pthread_mutexattr_init( &t_mta );
pthread_mutexattr_settype( &t_mta, PTHREAD_MUTEX_RECURSIVE );
pthread_mutex_init( &t_mutex_, &t_mta );
}
PythonServer::~PythonServer()
{
pthread_mutex_destroy( &t_mutex_ );
pthread_mutexattr_destroy( &t_mta );
}
void PythonServer::init( bool enableTelnetConsole, PyModuleExtension * pyModule, const char * scriptDir, const char * pythonHome )
{
pyModuleExtension_ = pyModule;
if (scriptDir) {
strncpy( customScriptBase, scriptDir, 256 );
}
if (pythonHome) {
strncpy( customPythonHome, pythonHome, 256 );
}
if (!initPyInterpreter()) {
ERROR_MSG( "Unable to initialise Python interpreter!\n" );
return;
}
FD_ZERO( &masterFDSet_ );
initUDPListener();
if (enableTelnetConsole)
initTelnetConsole();
keepRunning_ = true;
if (pthread_create( &runThread_, NULL, pytelnet_thread, this ) ) {
ERROR_MSG( "Unable to create thread to pull telnet inputs.\n" );
return;
}
runMainScript();
isActive_ = true;
}
void PythonServer::fini()
{
finiTelnetConsole();
keepRunning_ = false;
pthread_join( runThread_, NULL ); // allow thread to exit
if (dgramBuffer_) {
close( udpSocket_ );
udpSocket_ = INVALID_SOCKET;
delete [] dgramBuffer_;
dgramBuffer_ = NULL;
}
maxFD_ = 0;
FD_ZERO( &masterFDSet_ );
finiPyInterpreter();
}
void PythonServer::initIPAddresses()
{
sAddr_.sin_family = AF_INET;
sAddr_.sin_addr.s_addr = INADDR_ANY;
sAddr_.sin_port = htons( PYTHON_SERVER_PORT );
bcAddr_.sin_family = AF_INET;
inet_pton( AF_INET, PYRIDE_BROADCAST_IP, &bcAddr_.sin_addr.s_addr );
bcAddr_.sin_port = htons( PYTHON_SERVER_PORT );
#ifdef USE_MULTICAST
multiCastReq_.imr_multiaddr.s_addr = bcAddr_.sin_addr.s_addr;
multiCastReq_.imr_interface.s_addr = INADDR_ANY;
#endif
}
bool PythonServer::initUDPListener()
{
if ((udpSocket_ = socket( AF_INET, SOCK_DGRAM, 0 ) ) == INVALID_SOCKET) {
ERROR_MSG( "PythonServer::initUDPListener: unable to create UDP socket.\n" );
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( "PythonServer::initUDPListener: failed to set multicast TTL on UDP socket.\n" );
close( udpSocket_ );
return false;
}
if (setsockopt( udpSocket_, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&multiCastReq_, sizeof( multiCastReq_ ) ) < 0) {
ERROR_MSG( "PythonServer::initUDPListener: failed to join multicast group on UDP socket.\n" );
close( udpSocket_ );
return false;
}
#else // !USE_MULTICAST
if (setsockopt( udpSocket_, SOL_SOCKET, SO_BROADCAST, (char *)&turnon, sizeof( turnon ) ) < 0) {
ERROR_MSG( "PythonServer::initUDPListener: failed to enable broadcast on UDP socket.\n" );
close( udpSocket_ );
return false;
}
#endif
if (setsockopt( udpSocket_, SOL_SOCKET, SO_REUSEADDR, (char *)&turnon, sizeof( turnon ) ) < 0) {
ERROR_MSG( "PythonServer::initUDPListener: failed to enable reuse address on UDP socket.\n" );
close( udpSocket_ );
return false;
}
#ifdef SO_REUSEPORT
setsockopt( udpSocket_, SOL_SOCKET, SO_REUSEPORT, (char *)&turnon, sizeof( turnon ) );
#endif
if (bind( udpSocket_, (struct sockaddr *)&sAddr_, sizeof( sAddr_ ) ) < 0) {
ERROR_MSG( "PythonServer::initUDPListener: unable to bind to network interface.\n" );
close( udpSocket_ );
return false;
}
maxFD_ = max( maxFD_, udpSocket_ );
FD_SET( udpSocket_, &masterFDSet_ );
if (dgramBuffer_ == NULL)
dgramBuffer_ = new unsigned char[PYTHONSERVER_BUFFER_SIZE];
return true;
}
bool PythonServer::initPyInterpreter()
{
struct stat dirInfo;
char scriptPath[256];
char * evnset = getenv( "SCRIPT_HOME" );
if (strlen(customScriptBase) > 0 && stat( customScriptBase, &dirInfo ) == 0 && S_ISDIR(dirInfo.st_mode)) {
strcpy( scriptPath, customScriptBase );
}
else if (evnset && stat( evnset, &dirInfo ) == 0 && S_ISDIR(dirInfo.st_mode)) {
strcpy( scriptPath, evnset );
}
else {
if (strlen(customScriptBase) > 0) {
ERROR_MSG( "Invalid custom script path %s, use default.\n", customScriptBase );
}
else if (evnset) {
ERROR_MSG( "Invalid custom script path %s, use default.\n", evnset );
}
#ifdef ROS_BUILD
int retval = readlink( "/proc/self/exe", scriptPath, 256 );
if (retval > 0) {
strcpy( strrchr( scriptPath, '/' ), "/scripts/" );
}
#else
strcpy( scriptPath, DEFAULT_PYTHON_SCRIPT_PATH );
#endif
}
INFO_MSG( "use script path %s.\n", scriptPath );
PyGILState_STATE gstate;
// initialise Python interpreter
if (Py_IsInitialized()) {
INFO_MSG( "Python interpreter is already in use, restartpython() is not allowed.\n" );
hasInterpreter_ = true;
// we are not the thread starting the python
gstate = PyGILState_Ensure();
}
else {
#if PY_MAJOR_VERSION >= 3
if (strlen(customPythonHome)) {
wchar_t * homeStr = Py_DecodeLocale( customPythonHome, NULL );
Py_SetPythonHome( homeStr );
PyMem_RawFree( homeStr );
}
#else
if (strlen(customPythonHome)) {
Py_SetPythonHome( (char *)customPythonHome );
}
#endif
Py_InitializeEx( 0 );
PyEval_InitThreads();
}
PyThreadState* state = PyThreadState_Get();
intpState_ = state->interp;
// modify existing system path
std::string versionStr = strtok( (char*)Py_GetVersion(), " " );
std::string userPathStr = scriptPath;
char * evnhome = getenv( "HOME" );
if (evnhome) {
std::string userLocalPackagePath = ":";
userLocalPackagePath += evnhome; userLocalPackagePath += "/.local/lib/python";
userLocalPackagePath += versionStr.substr( 0, versionStr.find_last_of( '.' ) );
userPathStr += userLocalPackagePath + "/site-packages";
}
#if PY_MAJOR_VERSION >= 3
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> converter;
std::wstring packagePath = L":";
std::wstring localPackagePath = L":";
std::wstring sysPathStr( Py_GetPath() );
std::wstring versionWStr = converter.from_bytes( versionStr.substr( 0, versionStr.find_last_of( '.' ) ) );
std::wstring uPathWStr = converter.from_bytes( userPathStr );
packagePath += Py_GetPrefix(); packagePath += L"/lib/python";
localPackagePath += Py_GetPrefix(); localPackagePath += L"/local/lib/python";
packagePath += versionWStr;
localPackagePath += versionWStr;
size_t delpos = sysPathStr.find( L':' );
sysPathStr.replace( 0, delpos, uPathWStr );
sysPathStr += localPackagePath + L"/dist-packages";
sysPathStr += localPackagePath + L"/site-packages";
sysPathStr += packagePath + L"/dist-packages";
sysPathStr += packagePath + L"/site-packages";
PySys_SetPath( (wchar_t*)sysPathStr.c_str() );
#else
std::string packagePath = ":";
std::string localPackagePath = ":";
std::string sysPathStr( Py_GetPath() );
packagePath += Py_GetPrefix(); packagePath += "/lib/python";
localPackagePath += Py_GetPrefix(); localPackagePath += "/local/lib/python";
packagePath += versionStr.substr( 0, versionStr.find_last_of( '.' ) );
localPackagePath += versionStr.substr( 0, versionStr.find_last_of( '.' ) );
size_t delpos = sysPathStr.find( ':' );
sysPathStr.replace( 0, delpos, userPathStr );
sysPathStr += localPackagePath + "/dist-packages";
sysPathStr += localPackagePath + "/site-packages";
sysPathStr += packagePath + "/dist-packages";
sysPathStr += packagePath + "/site-packages";
PySys_SetPath( (char*)sysPathStr.c_str() );
#endif
pSysModule_ = PyImport_ImportModule( "sys" );
if (!pSysModule_) {
ERROR_MSG( "PythonServer: Failed to import sys module\n" );
return false;
}
if (!PyObject_HasAttrString( pSysModule_, "argv" )) {
PyObject * argObj = PyList_New( 1 );
#if PY_MAJOR_VERSION >= 3
PyList_SetItem( argObj, 0, PyUnicode_FromString( "" ) );
#else
PyList_SetItem( argObj, 0, PyString_FromString( "" ) );
#endif
PyObject_SetAttrString( pSysModule_, "argv", argObj );
Py_DECREF( argObj );
}
welcomeStr_ = "Welcome to UTS PyRIDE Python Console [Python version ";
welcomeStr_ += versionStr + "]";
pMainModule_ = PyImport_AddModule( "__main__" );
Py_INCREF( pMainModule_ );
if (!pMainModule_) {
// we are in deep trouble should abort
ERROR_MSG( "%s", "PythonServer failed to import __main__ module" );
return false;
}
initModuleExtension();
if (hasInterpreter_) {
PyGILState_Release( gstate );
}
else {
PyEval_SaveThread(); // release the GIL lock so that other threads can acquire it.
}
return true;
}
void PythonServer::finiPyInterpreter()
{
isActive_ = false;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyErr_Clear();
if (pMainScript_) {
Py_DECREF( pMainScript_ );
pMainScript_ = NULL;
}
finiModuleExtension();
if (pSysModule_) {
Py_DECREF( pSysModule_ );
pSysModule_ = NULL;
}
if (pMainModule_) {
Py_DECREF( pMainModule_ );
pMainModule_ = NULL;
}
PyErr_Clear();
if (!hasInterpreter_) {
Py_Finalize();
}
}
void PythonServer::runMainScript()
{
// run main script
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject * mainDict = PyModule_GetDict( pMainModule_ );
pMainScript_ = PyImport_ImportModuleEx( (char *)PYRIDE_MAIN_SCRIPT_NAME, mainDict, mainDict, NULL );
if (pMainScript_) {
PyObject_SetAttrString( pMainModule_, PYRIDE_MAIN_SCRIPT_NAME, pMainScript_ );
PyObject * mainFn = PyObject_GetAttrString( pMainScript_, "main" );
if (mainFn && PyCallable_Check( mainFn )) {
PyObject * pResult = PyObject_CallObject( mainFn, NULL );
if (pResult == NULL) {
ERROR_MSG( "PythonServer: Failed to run main function in script"
" %s\n", PYRIDE_MAIN_SCRIPT_NAME );
PyErr_Print();
PyErr_Clear();
}
else {
Py_DECREF( pResult );
}
}
else {
ERROR_MSG( "PythonServer: missing main function in script %s\n",
PYRIDE_MAIN_SCRIPT_NAME );
}
}
else {
if (PyErr_Occurred() == PyExc_ImportError) {
ERROR_MSG( "PythonServer: Unable to import main script"
" %s\n", PYRIDE_MAIN_SCRIPT_NAME );
PyErr_Print();
}
PyErr_Clear();
}
PyGILState_Release( gstate );
}
bool PythonServer::initTelnetConsole()
{
if (runningTelnetConsole_)
return true;
if ((tcpSocket_ = socket( AF_INET, SOCK_STREAM, 0 )) == INVALID_SOCKET) {
ERROR_MSG( "PythonServer::initTCPListener: unable to create TCP socket.\n" );
return false;
}
int turnon = 1;
if (setsockopt( tcpSocket_, SOL_SOCKET, SO_REUSEADDR, (char *)&turnon, sizeof( turnon ) ) < 0) {
ERROR_MSG( "PythonServer::initTCPListener: failed to enable reuse addr option on TCP socket.\n" );
close( tcpSocket_ );
return false;
}
if (bind( tcpSocket_, (struct sockaddr *)&sAddr_, sizeof( sAddr_ ) ) < 0) {
ERROR_MSG( "PythonServer::initTCPListener: unable to bind to network interface.\n" );
close( tcpSocket_ );
return false;
}
if (listen( tcpSocket_, 5 ) < 0) {
ERROR_MSG( "PythonServer::initTCPListener: unable to listen for incoming data.\n" );
close( tcpSocket_ );
return false;
}
INFO_MSG( "Python server is listening on TCP port %d.\n", PYTHON_SERVER_PORT );
maxFD_ = max( maxFD_, tcpSocket_ );
FD_SET( tcpSocket_, &masterFDSet_ );
if (clientDataBuffer_ == NULL)
clientDataBuffer_ = new unsigned char[PS_RECEIVE_BUFFER_SIZE];
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
prevStderr_ = PyObject_GetAttrString( pSysModule_, "stderr" );
prevStdout_ = PyObject_GetAttrString( pSysModule_, "stdout" );
PyObject_SetAttrString( pSysModule_, "stderr", pPyMod_ );
PyObject_SetAttrString( pSysModule_, "stdout", pPyMod_ );
PyGILState_Release( gstate ); // may not be necessary
runningTelnetConsole_ = true;
return true;
}
void PythonServer::finiTelnetConsole()
{
if (!runningTelnetConsole_)
return;
runningTelnetConsole_ = false;
disconnectClient( NULL, true );
close( tcpSocket_ );
tcpSocket_ = INVALID_SOCKET;
if (prevStderr_) {
PyObject_SetAttrString( pSysModule_, "stderr", prevStderr_ );
Py_DECREF( prevStderr_ );
prevStderr_ = NULL;
}
if (prevStdout_) {
PyObject_SetAttrString( pSysModule_, "stdout", prevStdout_ );
Py_DECREF( prevStdout_ );
prevStdout_ = NULL;
}
if (clientDataBuffer_) {
delete [] clientDataBuffer_;
clientDataBuffer_ = NULL;
}
}
void PythonServer::restartPythonServer()
{
if (hasInterpreter_) {
ERROR_MSG( "Python interpreter was started by other module. We cannot force it to restart.\n" );
return;
}
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
if (prevStderr_) {
PyObject_SetAttrString( pSysModule_, "stderr", prevStderr_ );
Py_DECREF( prevStderr_ );
prevStderr_ = NULL;
}
if (prevStdout_) {
PyObject_SetAttrString( pSysModule_, "stdout", prevStdout_ );
Py_DECREF( prevStdout_ );
prevStdout_ = NULL;
}
PyGILState_Release( gstate ); // may not be necessary
this->finiPyInterpreter();
this->initPyInterpreter();
this->broadcastServerMessage( "\r\nPython Interpreter has been restarted. Attempt to rerun main script.\r\n" );
if (runningTelnetConsole_) {
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
prevStderr_ = PyObject_GetAttrString( pSysModule_, "stderr" );
prevStdout_ = PyObject_GetAttrString( pSysModule_, "stdout" );
PyObject_SetAttrString( pSysModule_, "stderr", pPyMod_ );
PyObject_SetAttrString( pSysModule_, "stdout", pPyMod_ );
PyGILState_Release( gstate ); // may not be necessary
}
this->runMainScript();
//PyEval_ReleaseLock(); // release the GIL lock so that other threads can acquire it.
isActive_ = true;
}
void PythonServer::processIncomingData( fd_set * readyFDSet )
{
struct sockaddr_in cAddr;
int cLen = sizeof( cAddr );
SOCKET_T fd = INVALID_SOCKET;
if (FD_ISSET( udpSocket_, readyFDSet )) {
int readLen = recvfrom( udpSocket_, dgramBuffer_, PS_RECEIVE_BUFFER_SIZE,
0, (sockaddr *)&cAddr, (socklen_t *)&cLen );
if (readLen <= 0) {
ERROR_MSG( "PythonServer::continuousProcessing: error accepting "
"incoming UDP packet. error %d\n", errno );
}
else {
processUDPInput( dgramBuffer_, readLen, cAddr );
}
}
if (!runningTelnetConsole_)
return;
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, cAddr );
}
else if (errno != ECONNABORTED) {
ERROR_MSG( "PythonServer::continuousProcessing: error accepting "
"incoming TCP connection error = %d\n", errno );
}
}
pthread_mutex_lock( &t_mutex_ );
ClientItem * clientPtr = clientList_;
ClientItem * prevClientPtr = clientPtr;
while (clientPtr) {
fd = clientPtr->fd;
if (FD_ISSET( fd, readyFDSet )) {
int readLen = read( fd, clientDataBuffer_, PS_RECEIVE_BUFFER_SIZE );
if (readLen <= 0) {
if (readLen == 0) {
INFO_MSG( "Socket connection %d closed.\n", fd );
}
else {
ERROR_MSG( "PythonServer::continuousProcessing: "
"error reading data stream on %d error = %d.\n", fd, errno );
}
disconnectClient( clientPtr );
}
else {
clientPtr->pSession->processInput( clientPtr, clientDataBuffer_, readLen );
}
}
if (clientPtr->fd == INVALID_SOCKET) { // client has been disconnected
delete clientPtr->pSession;
if (clientPtr == clientList_) { // deletion of first node
clientList_ = clientPtr->pNext;
prevClientPtr = clientList_;
delete clientPtr;
clientPtr = clientList_;
}
else {
prevClientPtr->pNext = clientPtr->pNext;
delete clientPtr;
clientPtr = prevClientPtr->pNext;
}
}
else {
prevClientPtr = clientPtr;
clientPtr = clientPtr->pNext;
}
}
pthread_mutex_unlock( &t_mutex_ );
}
void PythonServer::continuousProcessing()
{
int maxFD = 0;
fd_set readyFDSet;
while (keepRunning_) {
FD_ZERO( &readyFDSet );
memcpy( &readyFDSet, &masterFDSet_, sizeof( masterFDSet_ ) );
maxFD = maxFD_;
select( maxFD + 1, &readyFDSet, NULL, NULL, NULL );
this->processIncomingData( &readyFDSet );
}
}
void PythonServer::processUDPInput( const unsigned char * recBuffer, int recBytes, struct sockaddr_in & cAddr )
{
unsigned char * message = NULL;
int messageSize = 0;
#ifdef USE_ENCRYPTION
if (decryptMessage( (unsigned char *)recBuffer, (int)recBytes, (unsigned char **)&message, (int *)&messageSize ) != 1) {
WARNING_MSG( "Unable to decrypt incoming messasge.\n" );
return;
}
#else
message = (unsigned char *)recBuffer;
messageSize = recBytes;
#endif
char command, subcommand, cID;
if (!messageValidation( message, messageSize, cID, command, subcommand ))
return;
switch (command) {
case ROBOT_TEAM_MSG:
{
if (!pyModuleExtension_)
break;
char ownID = pyModuleExtension_->clientID();
if ((ownID & 0xf) != (cID & 0xf)) {// ignore opposing team message
//WARNING_MSG( "Team message from the opposing team? ignore.\n" );
break;
}
if ((ownID >> 4) == (cID >> 4)) {// ignore own message
break;
}
char * commandData = (char *)message + PYRIDE_MSG_HEADER_SIZE;
int commandDataLen = messageSize - PYRIDE_MSG_MIN_LENGTH;
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject * arg = Py_BuildValue( "(is)", (int)(cID >> 4), std::string( commandData, commandDataLen ).c_str() );
pyModuleExtension_->invokeCallback( "onPeerMessage", arg );
Py_DECREF( arg );
PyGILState_Release( gstate );
}
break;
default:
ERROR_MSG( "PythonServer::processUDPInput()"
"Unknown team message.\n" );
}
}
bool PythonServer::RunMyString( const char * command )
{
// grab thread lock
//DEBUG_MSG( "Run command string: %s\n", command );
if (!pMainModule_) {
// we are in deep trouble should abort
ERROR_MSG( "PythonServer:: RunMyString no __main__ module.\n" );
return false;
}
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject * mainDict = PyModule_GetDict( pMainModule_ );
PyObject * ret = PyRun_String( command, Py_single_input, mainDict, mainDict );
if (ret == NULL) { // python command returns error
PyErr_Print();
PyGILState_Release( gstate );
return false;
}
Py_DECREF( ret );
#if PY_MAJOR_VERSION >= 3
PyObject * f = PySys_GetObject("stdout");
if (f == 0 || PyFile_WriteString( "", f ) != 0)
PyErr_Clear();
#else
if (Py_FlushLine())
PyErr_Clear();
#endif
PyGILState_Release( gstate );
return true;
}
PythonServer::ClientItem * PythonServer::addFdToClientList( const SOCKET_T & fd, struct sockaddr_in & cAddr )
{
ClientItem * newClient = new ClientItem;
newClient->fd = fd;
newClient->addr = cAddr;
newClient->pSession = new PythonSession( this, fd );
newClient->pNext = NULL;
pthread_mutex_lock( &t_mutex_ );
if (clientList_) {
ClientItem * fdPtr = clientList_;
while (fdPtr->pNext) fdPtr = fdPtr->pNext;
fdPtr->pNext = newClient;
}
else {
clientList_ = newClient;
}
FD_SET( fd, &masterFDSet_ );
maxFD_ = max( fd, maxFD_ );
pthread_mutex_unlock( &t_mutex_ );
return newClient;
}
void PythonServer::disconnectClient( ClientItem * client, bool sendNotification )
{
if (sendNotification) { // let the other end to close down the connection first
pthread_mutex_lock( &t_mutex_ );
if (client) {
if (client->fd != INVALID_SOCKET)
client->pSession->sayGoodBye();
}
else {
ClientItem * fdPtr = clientList_;
while (fdPtr) {
if (fdPtr->fd != INVALID_SOCKET)
fdPtr->pSession->sayGoodBye();
fdPtr = fdPtr->pNext;
}
}
pthread_mutex_unlock( &t_mutex_ );
}
pthread_mutex_lock( &t_mutex_ );
if (client) {
if (client->fd != INVALID_SOCKET) {
close( client->fd );
FD_CLR( client->fd, &masterFDSet_ );
client->fd = INVALID_SOCKET; // reset fd. this is also a flag for client item removal
}
}
else { // disconnect all clients
ClientItem * fdPtr = clientList_;
while (fdPtr) {
if (fdPtr->fd != INVALID_SOCKET) {
close( fdPtr->fd );
FD_CLR( fdPtr->fd, &masterFDSet_ );
fdPtr->fd = INVALID_SOCKET;
delete fdPtr->pSession;
fdPtr->pSession = NULL;
}
ClientItem * tmpPtr = fdPtr;
fdPtr = fdPtr->pNext;
delete tmpPtr;
}
clientList_ = NULL;
}
pthread_mutex_unlock( &t_mutex_ );
}
void PythonServer::broadcastServerMessage( const char * mesg )
{
ClientItem * fdPtr = clientList_;
while (fdPtr) {
if (fdPtr->pSession) {
fdPtr->pSession->write( mesg );
fdPtr->pSession->writePrompt();
}
fdPtr = fdPtr->pNext;
}
}
bool PythonServer::messageValidation( const unsigned char * receivedMesg, const int receivedBytes, char & cID,
char & command, char & subcommand )
{
cID = command = subcommand = 0;
//DEBUG_MSG( "Received %d bytes, header as %X|%X|%X|%X%X\n", receivedBytes,
//receivedMesg[0], receivedMesg[1], receivedMesg[2], receivedMesg[3], receivedMesg[4]);
if (receivedBytes < PYRIDE_MSG_MIN_LENGTH ||
receivedMesg[0] != PYRIDE_MSG_INIT ||
receivedMesg[1] != PYRIDE_PROTOCOL_VERSION ||
receivedMesg[receivedBytes-1] != PYRIDE_MSG_END)
{
return false;
}
cID = receivedMesg[2];
command = (receivedMesg[3] >> 4) & 0x0f;
subcommand = receivedMesg[3] & 0x0f;
return true;
}
void PythonServer::initModuleExtension()
{
if (!pyModuleExtension_) {
ERROR_MSG( "No Python extension is known!\n" );
return;
}
pPyMod_ = pyModuleExtension_->init( this );
if (pPyMod_) {
PyObject * modules = PyImport_GetModuleDict();
#if PY_MAJOR_VERSION >= 3
PyObject * nameobj = PyUnicode_FromString( pyModuleExtension_->name().c_str() );
#else
PyObject * nameobj = PyString_FromString( pyModuleExtension_->name().c_str() );
#endif
if (!modules || !nameobj) {
ERROR_MSG( "Error prepare for module extension.\n" );
return;
}
if (PyDict_SetItem( modules, nameobj, pPyMod_ ) != 0 ||
PyObject_SetAttr( pMainModule_, nameobj, pPyMod_ ) != 0)
{
ERROR_MSG( "Unable to insert module extension!\n" );
}
Py_DECREF(nameobj);
}
}
void PythonServer::finiModuleExtension()
{
if (!pyModuleExtension_) {
ERROR_MSG( "No Python extension is known!\n" );
return;
}
pyModuleExtension_->fini();
pPyMod_ = NULL;
}
bool PythonServer::getObjectDir( const std::string & searchStr, std::vector<std::string> & mlist )
{
mlist.clear();
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
PyObject * searchingObj = pMainModule_;
Py_INCREF( searchingObj );
std::string targetStr = searchStr;
std::size_t found, listSize;
while (!targetStr.empty()) {
found = targetStr.find_first_of( "." );
if (found == std::string::npos) {
// search the current object for attr/meth/obj match to the search string
PyObject * metdList = PyObject_Dir( searchingObj );
if (metdList && (listSize = PyList_Size( metdList )) > 0) {
for (int i = 0; i < listSize; i++) {
#if PY_MAJOR_VERSION >= 3
PyObject * unicodeobj = PyUnicode_FromObject( PyList_GetItem( metdList, i ) );
std::string methodStr( PyUnicode_AsUTF8( unicodeobj ) );
Py_DECREF( unicodeobj );
#else
std::string methodStr( PyString_AsString( PyList_GetItem( metdList, i ) ) );
#endif
if (methodStr.find( targetStr ) == 0) {
mlist.push_back( methodStr );
}
}
}
Py_XDECREF( metdList );
targetStr.clear();
}
else {
PyObject * modObj = PyObject_GetAttrString( searchingObj, targetStr.substr( 0, found ).c_str() );
if (modObj) {
targetStr = targetStr.substr( found+1 );
Py_DECREF( searchingObj );
searchingObj = modObj;
if (targetStr.empty()) { // special case give full list of options
PyObject * metdList = PyObject_Dir( searchingObj );
if (metdList && (listSize = PyList_Size( metdList )) > 0) {
for (int i = 0; i < listSize; i++) {
#if PY_MAJOR_VERSION >= 3
PyObject * unicodeobj = PyUnicode_FromObject( PyList_GetItem( metdList, i ) );
std::string methodStr( PyUnicode_AsUTF8( unicodeobj ) );
Py_DECREF( unicodeobj );
#else
std::string methodStr( PyString_AsString( PyList_GetItem( metdList, i ) ) );
#endif
mlist.push_back( methodStr );
}
}
Py_XDECREF( metdList );
}
}
else {
targetStr.clear(); // not found
}
}
}
Py_DECREF( searchingObj );
PyGILState_Release( gstate );
return (mlist.size() > 0);
}
void PythonServer::write( const char * msg )
{
if (activeSession_) {
activeSession_->write( msg );
}
else {
INFO_MSG( "Script: %s\n", msg );
}
}
void PythonServer::broadcastMessage( const char * msg ) // expect NULL terminated string
{
if (!pyModuleExtension_)
return;
int msgSize = strlen( msg );
int dataLength = PYRIDE_MSG_MIN_LENGTH + msgSize;
unsigned char * bcMesg = new unsigned char[dataLength];
unsigned char * msgPtr = bcMesg;
*msgPtr++ = PYRIDE_MSG_INIT;
*msgPtr++ = PYRIDE_PROTOCOL_VERSION;
*msgPtr++ = pyModuleExtension_->clientID();
*msgPtr++ = (ROBOT_TEAM_MSG << 4);
memcpy( (void *)msgPtr, msg, msgSize );
msgPtr += msgSize;
*msgPtr = PYRIDE_MSG_END;
#ifdef USE_ENCRYPTION
unsigned char * encryptedMesg = NULL;
int encryptedLength = 0;
pthread_mutex_lock( &t_mutex_ );
if (encryptMessage( bcMesg, dataLength, &encryptedMesg, &encryptedLength ) == 1) {
sendto( udpSocket_, encryptedMesg, encryptedLength, 0, (struct sockaddr *)&bcAddr_, sizeof( bcAddr_ ) );
}
pthread_mutex_unlock( &t_mutex_ );
#else
pthread_mutex_lock( &t_mutex_ );
sendto( udpSocket_, bcMesg, dataLength, 0, (struct sockaddr *)&bcAddr_, sizeof( bcAddr_ ) );
pthread_mutex_unlock( &t_mutex_ );
#endif
delete [] bcMesg;
}
/**
* PythonSession class
*/
PythonSession::PythonSession( PythonServer * server, SOCKET_T fd ) :
server_( server ),
fd_( fd ),
telnetSubnegotiation_( false ),
promptStr_( ">>> " ),
historyPos_( -1 ),
charPos_( 0 ),
multiline_( "" )
{
this->connectReady();
}
PythonSession::~PythonSession()
{
readBuffer_.clear();
historyBuffer_.clear();
currentLine_ = "";
multiline_ = "";
charPos_ = 0;
}