-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathiface.py
1482 lines (1151 loc) · 35.8 KB
/
iface.py
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
#!/usr/bin/python
#
# LICENSE: See LICENSE file.
#
# WARNING: The Windows/Linux iface by is EXPERIMENTAL and has nothing to do
# with good coding, security, etc. USE AT YOUR OWN RISK.
#
# INITIAL SETUP: please scroll down looking for "CONFIGURATION" section.
#
# This app must be run both on -windows and linux.
# Please use either --windows or --linux parameters to specify
# where is it executed.
# *** Architecture
#
# +-------+ +-------+
# : HOST : <--tcp-ctrl-chan- : VM +
# : iface : : iface +
# +-------+ +-------+
# ^ ^ ^ ^
# : : : :
# t t t t
# c c c c
# p p p p
# : : : :
# cmd1 cmd2 cmd1 cmd2
#
# The iface is always running. It's job is to be aware if
# the second iface is online, and to transmit commands to it.
# It should also provide some simple data transmision mechanism
# and/or data storage mechanisms (to e.g. store settings and
# stats).
# The IFACE_VM can assume that the IFACE_HOST is always online.
# The IFACE_HOST should check with the VM manager to see if the
# IFACE_VM machine is online before attempting to send a command.
# Also, if possible, it should try to UDP-ping the IFACE_VM to
# be sure no timeout will occure.
#
# Additionally the IFACE_HOST should be aware of path mapping
# between both machines, and it should provide a way to translate
# a path VM->HOST and HOST->VM. It should be aware of both the
# shared folders via VM mechanisms and SSHFS mounts (though
# they can be placed in a config file or sth).
#
# *** By example
# The l-cmd command executes a linux terminal in the given
# work directory (it also takes care of translating the directory).
# It works the following way:
# 1. User executes l-cmd, which is actually l-cmd.py script.
# 2. The script imports the WinLin Iface library.
# 3. It invokes "l-cmd" with CWD as parameter (by creating a
# tcp connection to the IFACE).
# 4. The IFACE receives the command/parameter and invokes
# the proper command handler.
# 5. The command handler invokes the "path-translate" command
# with CWD as the parameter.
# 6. Since it's a IFACE_HOST command, the translation is done
# in place, and the new path is returned.
# 7. Next, the l-cmd command is sent to IFACE_VM with the
# translated path as CWD.
# 8. On IFACE_VM the l-cmd handler is invoked.
# 9. The handler launches gnome-terminal in the given directory.
# 10. A result is returned all the way.
# Constants for debug level in CONFIGURATION section.
LOG_ERROR = 0
LOG_WARNING = 1
LOG_INFO = 3
LOG_VERBOSE = 5
LOG_DEBUG = 10
import os
import pickle
import select
import socket
import StringIO
import struct
import subprocess
import sys
import time
import threading
if sys.platform != 'win32':
import fcntl
from ifaceconfiglib import cfg
# -------------------------------------------------------------------
# CONFIGURATION (set values from config file)
# -------------------------------------------------------------------
SECRET = cfg.get('main', 'secret')
HOME_PATH_ON_VM = cfg.get('main', 'home_path')
BIND_PORT = cfg.getInt('main', 'bind_port')
TERMINAL_CMD = cfg.get('main', 'terminal_cmd')
REMOTE_IP_LIST = eval(cfg.get('main', 'remote_ip_list'))
CMDS={
"iface-info" : "CMD_iface_info", # Returns some info.
"iface-ping" : "CMD_ping", # Returns "pong"
"iface-openurl" : "CMD_openurl", # Opens http or https url.
"iface-l-cmd" : "CMD_l_cmd", # Spawns a linux console.
"translate-path": "CMD_translate_path", # Translates path.
}
LOG_LEVEL = LOG_DEBUG
# -------------------------------------------------------------------
# End of constants / configs.
# -------------------------------------------------------------------
print "Windows/Linux iface by gynvael.coldwind//vx"
def Usage():
print "usage: iface --windows|--linux"
print ""
print "Run with --windows on Host/Windows or with --linux on VM/Linux."
if len(SECRET) == 0:
print "This is your time running Windows/Linux iface. You first need to set "
print "some things up before you can use it."
print "Please open iface.cfg and set needed values."
sys.exit(1)
if len(sys.argv) != 2:
Usage()
sys.exit(1)
if sys.argv[1] not in ['--windows', '--linux']:
Usage()
sys.exit(2)
IFACE_HOST="HOST"
IFACE_VM="VM"
IFACE={"--windows":IFACE_HOST, "--linux":IFACE_VM}[sys.argv[1]]
IFACE_REMOTE="REMOTE"
IFACE_LOCAL="LOCAL"
BIND_IP={
IFACE_HOST: REMOTE_IP_LIST[0],
IFACE_VM : REMOTE_IP_LIST[1]
}[IFACE]
CTRL_CHANNEL_ONLINE = False
CTRL_CHANNEL_SOCKET = None
CTRL_CHANNEL_THREAD = None
EVENT_CLOSE_CTRL_CHANNEL = threading.Event()
# Host? Then we need another import
if IFACE == IFACE_HOST:
import ctypes
# -------------------------------------------------------------------
# Locked list.
class LockedList():
def __init__(self):
self.lock = threading.Lock()
self.d = []
def snapshot(self):
self.lock.acquire()
d_copy = self.d[:]
self.lock.release()
return d_copy
def append(self, element):
self.lock.acquire()
self.d.append(element)
self.lock.release()
def insert(self, element):
self.lock.acquire()
self.d.insert(0, element)
self.lock.release()
def pop(self):
self.lock.acquire()
res = None
if len(self.d) > 0:
res = self.d.pop()
self.lock.release()
return res
def remove(self, element):
res = False
self.lock.acquire()
if element in self.d:
self.d.remove(element)
res = True
self.lock.release()
return res
def find(self, element):
self.lock.acquire()
res = -1
if element in self.d:
res = self.d.index(element)
self.lock.release()
return res
def raw_lock(self):
self.lock.acquire()
return self.d
def raw_release(self):
self.lock.release()
# -------------------------------------------------------------------
# Safe pickle (via http://nadiana.com/python-pickle-insecure)
class SafeUnpickler(pickle.Unpickler):
PICKLE_SAFE = {
'copy_reg': set(['_reconstructor']),
'__builtin__': set(['object'])
}
def find_class(self, module, name):
if not module in self.PICKLE_SAFE:
raise pickle.UnpicklingError(
'Attempting to unpickle unsafe module %s' % module
)
__import__(module)
mod = sys.modules[module]
if not name in self.PICKLE_SAFE[module]:
raise pickle.UnpicklingError(
'Attempting to unpickle unsafe class %s' % name
)
klass = getattr(mod, name)
return klass
@classmethod
def loads(cls, pickle_string):
return cls(StringIO.StringIO(pickle_string)).load()
# -------------------------------------------------------------------
# Some run-time globals.
ACTIVE_HANDLERS = LockedList()
CTRL_SEND_LIST = LockedList()
EVENT_SEND_LIST_POPULATED = threading.Event()
REPLY_REGISTRY = {}
REPLY_REGISTRY_LOCK = threading.Lock()
CID_COUNTER = 0
CID_COUNTER_LOCK = threading.Lock()
# -------------------------------------------------------------------
# Control packet sender / registry functions.
def CtrlSendReply(cid, result):
global CTRL_SEND_LIST
global EVENT_SEND_LIST_POPULATED
# Create packet.
packet = {
"reply_cid": cid,
"result" : result
}
# Append packet to send list.
CTRL_SEND_LIST.insert(packet)
# Mark list as populated.
EVENT_SEND_LIST_POPULATED.set()
# Done.
return
def CtrlSendRequest(cid, cmd, args):
global CTRL_SEND_LIST
global EVENT_SEND_LIST_POPULATED
# Create packet.
packet = {
"cid" : cid,
"command" : cmd,
"args" : args
}
# Append packet to send list.
CTRL_SEND_LIST.insert(packet)
# Mark list as populated.
EVENT_SEND_LIST_POPULATED.set()
# Done.
return
def CtrlRecvReply(cid, result):
global REPLY_REGISTRY_LOCK
global REPLY_REGISTRY
# Lock the registry.
REPLY_REGISTRY_LOCK.acquire()
# Is anyone waiting for this reply?
if cid not in REPLY_REGISTRY:
# Log it.
Log(LOG_WARNING,
"received ctrl reply (cid=%s), but no one is waiting for it" % (
str(cid)
))
REPLY_REGISTRY_LOCK.release()
return
# Pop it so we can clear the lock.
info = REPLY_REGISTRY.pop(cid)
REPLY_REGISTRY_LOCK.release()
# Set the data and ping the waiting thread.
info["data"].append(result) # Return by adding to refered list.
info["event"].set() # This should wake up the thread.
# That's that.
return
def CtrlRegisterCID(cid):
global REPLY_REGISTRY_LOCK
global REPLY_REGISTRY
# Create info struct.
info = {
"data" : [], # Result will be added here.
"event" : threading.Event()
}
# Register.
REPLY_REGISTRY_LOCK.acquire()
REPLY_REGISTRY[cid] = info
REPLY_REGISTRY_LOCK.release()
# Done.
return info
def CtrlGetCID():
global CID_COUNTER
global CID_COUNTER_LOCK
CID_COUNTER_LOCK.acquire()
ret = CID_COUNTER
CID_COUNTER += 1
CID_COUNTER_LOCK.release()
return ret
# -------------------------------------------------------------------
# Run handler
def RunHandlerByPacket(packet, info):
global EVENT_END
global CMDS
cmd = packet["command"]
arg = packet["args"]
# Is this a special command?
if cmd == "__shutdown":
Log(LOG_INFO, "__shutdown command received")
EVENT_END.set()
return True
# Is this a known command?
if cmd not in CMDS:
Log(LOG_WARNING, "unknown command \"%s\"" % cmd)
raise Exception('unknown command')
# Find the handler.
handler_name = CMDS[cmd]
if handler_name not in globals():
Log(LOG_ERROR,
"handler \"%s\" not found for known command \"%s\"" % (
handler_name, cmd))
raise Exception('handler not found command')
handler = globals()[handler_name]
arg = tuple([info] + list(arg))
# Execute handler.
result = handler(*arg)
return result
# Run handler
def RunHandlerByCtrlPacket(packet):
# This can be either a reply packet, or a new command.
# Let's check.
if "reply_cid" in packet:
# A reply packet.
RunHandlerByCtrlReplyPacket(packet)
elif "command" in packet:
# A command packet.
RunHandlerByCtrlCommandPacket(packet)
else:
# Should never be reached.
Log(LOG_ERROR, "weird ctrl packet, ignoring")
# Done.
return
# Handle reply packet.
def RunHandlerByCtrlReplyPacket(packet):
cid = packet["reply_cid"]
result = packet["result"]
Log(LOG_VERBOSE, "received reply to request (cid=%s)" % (
str(cid)
))
# Commit results.
CtrlRecvReply(cid, result)
# Done.
return
# Handle command packet.
def RunHandlerByCtrlCommandPacket(packet):
global CMDS
global EVENT_END
cmd = packet["command"]
arg = packet["args"]
cid = packet["cid"]
# Log.
Log(LOG_VERBOSE, "remote request (cid=%s) for cmd \"%s\"" % (
str(cid), cmd
))
# Is this a special command?
if cmd == "__shutdown":
Log(LOG_INFO, "__shutdown command received from remote")
EVENT_END.set()
CtrlSendReply(cid, True)
return
# Is this a known command?
if cmd not in CMDS:
Log(LOG_WARNING, "unknown command \"%s\"" % cmd)
return
# Find the handler.
handler_name = CMDS[cmd]
if handler_name not in globals():
Log(LOG_ERROR,
"handler \"%s\" not found for known command \"%s\"" % (
handler_name, cmd))
return
handler = globals()[handler_name]
info = {
"source" : IFACE_REMOTE
}
arg = tuple([info] + list(arg))
# Execute handler.
result = handler(*arg)
# Send reply.
Log(LOG_VERBOSE, "sending reply to request (cid=%s)" % (
str(cid)
))
CtrlSendReply(cid, result)
# Done.
return
# -------------------------------------------------------------------
# CtrlPacket handler thread.
class CtrlPacketHandler(threading.Thread):
def __init__(self, packet):
global ACTIVE_HANDLERS
threading.Thread.__init__(self)
# Copy properties.
self.packet = packet
# Add self to handler list.
ACTIVE_HANDLERS.append(self)
# Start.
self.start()
def run(self):
global ACTIVE_HANDLERS
Log(LOG_DEBUG, "starting new ctrl packet handler thread %s" % (
str(self)))
RunHandlerByCtrlPacket(self.packet)
ACTIVE_HANDLERS.remove(self)
Log(LOG_DEBUG, "ending ctrl packet handler thread %s" % (
str(self)))
return 0
# -------------------------------------------------------------------
# Connection handler thread.
class ThreadHandler(threading.Thread):
def __init__(self, sock, address, conn_type):
global ACTIVE_HANDLERS
threading.Thread.__init__(self)
# Copy properties.
self.sock = sock
self.address = address
self.conn_type = conn_type
# Add self to the list.
ACTIVE_HANDLERS.append(self)
# Start.
self.start()
def run(self):
global ACTIVE_HANDLERS
# Get the packet.
packet = NetHelperRecv(self.sock)
if packet != False:
res = None
try:
# Gather info.
info = {
"source" : self.conn_type
}
res = RunHandlerByPacket(packet, info)
except:
# TODO: Log this
print "Unexpected error:", sys.exc_info()
else:
NetHelperSend(self.sock, res)
# Finalize.
self.sock.close()
self.sock = None
# Remove self and return.
ACTIVE_HANDLERS.remove(self)
return 0
# -------------------------------------------------------------------
# Net helpers.
def NetHelperSend(sock, data):
# Format outgoing data.
data = pickle.dumps(data)
packet = struct.pack("I", len(data)) + data
# Send all.
ret = None
try:
ret = sock.sendall(packet)
except:
Log(LOG_WARNING, "failed sending data to socket %s" % str(sock))
return False
if ret != None:
Log(LOG_WARNING, "failed sending data to socket %s" % str(sock))
return False
Log(LOG_DEBUG, "sent packet of %u size to %s" % (
len(packet), str(sock)))
# Done.
return True
def NetHelperRecvNBytes(sock, length):
totalrecv = 0
data = ""
while totalrecv < length:
remaining = length - totalrecv
if remaining > 0x4000:
remaining = 0x4000
success = False
now_recv = ""
try:
now_recv = sock.recv(remaining)
success = True
except:
pass
if now_recv == 0 or not success:
Log(LOG_WARNING,
"got disconnected while receiving data from socket %s" % (
str(sock)))
return False
data += now_recv
totalrecv = len(data)
return data
def NetHelperRecv(sock):
# Receive 4 bytes.
size_data = NetHelperRecvNBytes(sock, 4)
if size_data == False:
return False
size = struct.unpack("I", size_data)[0]
# Receive packet.
data = NetHelperRecvNBytes(sock, size)
if data == False:
return False
Log(LOG_DEBUG, "recv packet of %u len from %s" % (
size + 4, str(sock)))
# Unpickle.
try:
data = SafeUnpickler.loads(data)
except:
Log(LOG_ERROR, "could not unpickle packet from %s" % str(sock))
return False
# Done.
return data
def NetHelperGetRawPacket(data):
# Packet with data is atleast 4 bytes size.
if len(data) < 4:
return None
# Extract size.
size = struct.unpack("I", data[:4])[0]
Log(LOG_DEBUG, "raw packet size check: declared=%u, is=%u" % (
size, len(data) - 4
))
# Add the already received size bytes.
size += 4
# Is there enough data?
if len(data) < size:
return None
# Get the data and return it.
return data[:size]
def NetHelperRecvFromString(packet):
# This function assumes it's a correct packet.
size = struct.unpack("I", packet[:4])[0]
data = packet[4:]
if len(data) != size:
Log(LOG_ERROR, "sane packet was insane (%u vs %u)" % (
len(data), size
))
Log(LOG_DEBUG, "recv packet of %u len from buffer" % (
size + 4))
# Unpickle.
try:
data = SafeUnpickler.loads(data)
except:
Log(LOG_ERROR, "could not unpickle packet from buffer: %s" %(
sys.ecx_info()
))
raise
# Done.
return data
# -------------------------------------------------------------------
class ThreadCtrlChannelSender(threading.Thread):
def __init__(self, sock):
threading.Thread.__init__(self)
# Copy.
self.sock = sock
# Start.
self.start()
def run(self):
global EVENT_CLOSE_CTRL_CHANNEL
global EVENT_SEND_LIST_POPULATED
global CTRL_SEND_LIST
Log(LOG_DEBUG, "ctrl sender thread started %s" % str(self))
# Until it's time to die.
while not EVENT_CLOSE_CTRL_CHANNEL.is_set():
# Clear the population event.
EVENT_SEND_LIST_POPULATED.clear()
# Clear the list.
while True:
# Try to get something from the list.
data = CTRL_SEND_LIST.pop()
if data == None:
break
# Send it.
NetHelperSend(self.sock, data)
# Wait until the list is populated again.
EVENT_SEND_LIST_POPULATED.wait(1.0)
continue
# Guess it's time to finish.
Log(LOG_DEBUG, "ctrl sender thread finished %s" % str(self))
return 0
# -------------------------------------------------------------------
class ThreadGuardCtrl(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def run(self):
global REMOTE_IP_LIST
global BIND_PORT
global EVENT_END
while not EVENT_END.is_set():
# Try to connect.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if IFACE == IFACE_VM:
flags = fcntl.fcntl(s.fileno(), fcntl.F_GETFD)
fcntl.fcntl(s.fileno(), fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
try:
s.connect((REMOTE_IP_LIST[0], BIND_PORT))
# Poor man's auth.
s.sendall(SECRET)
except:
Log(LOG_DEBUG, "could not connect to host iface")
# Sleep before retry.
time.sleep(5.0)
# Retry.
continue
# Launch handler.
t = ThreadCtrlChannelServer(s, ("n/a", 0))
t.join()
# Got disconnected. Clean up.
s.close()
s = None
continue
# Done
return
# -------------------------------------------------------------------
class ThreadCtrlChannelServer(threading.Thread):
def __init__(self, sock, address):
global CTRL_CHANNEL_THREAD
threading.Thread.__init__(self)
# Copy.
self.sock = sock
self.address = address
self.sender_thread = None
# Replace thread marker.
self.old_thread = CTRL_CHANNEL_THREAD
CTRL_CHANNEL_THREAD = self
# Start.
self.start()
def run(self):
global CTRL_CHANNEL_THREAD
global CTRL_CHANNEL_SOCKET
global CTRL_CHANNEL_ONLINE
global EVENT_CLOSE_CTRL_CHANNEL
global EVENT_END
Log(LOG_DEBUG, "ctrl server thread started %s" % str(self))
# Is there already a channel? If so, replace it.
if self.old_thread:
# Graceful shutdown the old thread.
EVENT_CLOSE_CTRL_CHANNEL.set()
# Wait for old thread to end
self.old_thread.join()
# Make sure this is cleared in either case.
EVENT_CLOSE_CTRL_CHANNEL.clear()
# If we need to end, it's a good time to do it now.
# XXX: Not sure about this workaround, but it should be kinda OK.
if EVENT_END.is_set():
Log(LOG_DEBUG, "ctrl server thread ended gracefully (in) %s" % (
str(self)
))
return 0
# Start initializing everything.
CTRL_CHANNEL_SOCKET = self.sock
CTRL_CHANNEL_THREAD = self
self.sender_thread = ThreadCtrlChannelSender(self.sock)
# Mark as ONLINE.
CTRL_CHANNEL_ONLINE = True
# Main recv loop.
data = ""
while not EVENT_CLOSE_CTRL_CHANNEL.is_set():
# Select.
rr,rw,err = select.select([self.sock], [], [], 1.0)
# Was this a timeout?
if len(rr) == 0 and len(rw) == 0 and len(err) == 0:
continue
# Read.
try:
recv_data = self.sock.recv(0x4000)
except:
Log(LOG_INFO, "control channel died: %s" % (
str(sys.exc_info())))
break
# Closed?
if len(recv_data) == 0:
Log(LOG_INFO, "control channel died")
break
# Add to data.
Log(LOG_DEBUG, "ctrl channel got another %u bytes" % (
len(recv_data)
))
data += recv_data
# There can be more than one packet ready.
fatal_error = False
while True:
# Is the full packet ready?
raw_packet = NetHelperGetRawPacket(data)
if raw_packet == None:
Log(LOG_DEBUG, "no more raw packets ready")
break # Not yet.
# Fix data buffer.
data = data[len(raw_packet):]
# Extract packet.
try:
packet = NetHelperRecvFromString(raw_packet)
except:
Log(LOG_INFO,
"control channel got invalid data, dying: %s" % (
str(sys.exc_info())
))
fatal_error = True
break
# Well, this packet needs to be specially handled.
t = CtrlPacketHandler(packet)
# And that's it I guess.
continue
# Anything bad happend?
if fatal_error:
break
# Conitnue.
continue
# Seems we need to exit.
CTRL_CHANNEL_ONLINE = False
self.sock.close()
# Make sure event is set.
if not EVENT_CLOSE_CTRL_CHANNEL.is_set():
EVENT_CLOSE_CTRL_CHANNEL.set()
# Wait for sender thread.
self.sender_thread.join()
# Finalize
CTRL_CHANNEL_SOCKET = None
Log(LOG_DEBUG, "ctrl server thread ended gracefully %s" % (
str(self)
))
return 0
# -------------------------------------------------------------------
# Main listening thread.
class ThreadMainNet(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
# Just run self.
self.start()
def run(self):
global CMDS
global IFACE
global BIND_PORT
global EVENT_END
global CTRL_CHANNEL_ONLINE
global CTRL_CHANNEL_SOCKET
Log(LOG_DEBUG, "main thread started")
try:
# Create local listening socket.
socket_local = CreateListeningSocket("127.0.0.1", BIND_PORT)
# Create remote listening socket if needed.
socket_remote = False
if IFACE==IFACE_HOST:
socket_remote = CreateListeningSocket(BIND_IP, BIND_PORT)
# Connect to HOST if required.
except socket.error, msg:
Log(LOG_ERROR, msg)
EVENT_END.set() # Make the app exit.
return 1
# Main loop.
# This loop handles only the incomming connections.
# All the handlers/reads/writes are handled in separate threads.
# Is the ctrl channel online?
socket_ctrl = False
# Create translation dict.
sock_to_type = {
socket_local : IFACE_LOCAL,
}
if socket_remote:
sock_to_type[socket_remote] = IFACE_REMOTE
# Create a select list.
socket_poll = [ socket_local ]
if socket_remote:
socket_poll.append(socket_remote)
# Loop
while not EVENT_END.is_set():
# Any incomming connection?
rr,rw,err = select.select(socket_poll,[],[], 1.0)
# Was this a timeout?
if len(rr) == 0 and len(rw) == 0 and len(err) == 0:
continue
# Anything ready to be accepted?
for sock in rr:
(new_sock, address) = sock.accept()
# Is this a local or remote connection?
conn_type = sock_to_type[sock]
Log(LOG_VERBOSE, "connection from %s:%u (%s)" % (
address[0], address[1], conn_type
))
# Is this connection allowed?
if conn_type == IFACE_REMOTE and address[0] not in REMOTE_IP_LIST:
# Kill the connection. It's not allowed.
Log(LOG_INFO,
"killing disallowed REMOTE connection form %s:%u" %
address)
new_sock.close()
new_sock = None
# Continue.
continue
# Poor man's authentication.
try: