-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmultiplexer.r2py
1668 lines (1253 loc) · 50.4 KB
/
multiplexer.r2py
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
"""
Author: Armon Dadgar
Start Date: February 16th, 2009
Description:
Provides a means of multiplexing any stream-like connection into a multiple
socket-like connections.
Details:
There are 3 main objects in the Multiplexer
++ MultiplexerFrame
-- This objects is like a meta-"packet" in that it encapsulates a some data with a header
-- The header allows the Multiplexer to route the data to the correct destination
++ Multiplexer
-- This object is takes a single stream-like object that has the properties of being
-- in-order and lossless and multiplexes that single connection into any number of virtual connections.
-- At its heart, there is one thread the socketReader which reads all incoming data and either evaluates control messages
-- or buffers data for clients
++ MultiplexerSocket
-- When the multiplexer creates virtual sockets, a MultiplexerSocket is returned. This socket is tied to its parent multiplexer
-- since that parent buffers all of the incoming data for this socket.
These three objects are wrapped in several mux_* functions, which abstract the details of the Multiplexer
and provide a repy like interface for easily multiplexing a normal TCP connection. mux_remap can be used to
multiplex any type of connection.
"""
dy_import_module_symbols("librepysocket.r2py")
# This is to help send dictionaries as strings
dy_import_module_symbols("deserialize.r2py")
# Define Module Constants
#
# How many digits can be used to indicate header length
MULTIPLEXER_FRAME_HEADER_DIGITS = 3
MULTIPLEXER_FRAME_DIVIDER = ";" # What character is used to divide a frame header
# These are the valid Message Types
MULTIPLEXER_DATA_FORWARD = 0
MULTIPLEXER_CONN_TERM = 1
MULTIPLEXER_CONN_BUF_SIZE = 2
MULTIPLEXER_INIT_CLIENT = 3
MULTIPLEXER_INIT_STATUS = 4
# Special Case
MULTIPLEXER_FRAME_NOT_INIT = -1
# Valid Multiplexer responses to init
MULTIPLEXER_STATUS_CONFIRMED = "CONFIRMED"
MULTIPLEXER_STATUS_FAILED = "FAILED"
# Defines a delay period for the initialization of a multiplexer object
# This is to allow the user to specify waitfunctions before the multiplexer is started
# So that any queued openconn requests are not immediately rejected
MULTIPLEXER_START_DELAY = 1
# Core unit of the Specification, this is used for multiplexing a single connection,
# and for initializing connections
class MultiplexerFrame():
# Set the frame instance variables
def __init__(self):
self.headerSize = 0
self.mesgType = MULTIPLEXER_FRAME_NOT_INIT
self.contentLength = 0
self.referenceID = 0
self.content = ""
# So that we display properly
def __repr__(self):
try:
return self.toString()
except AttributeError:
return "<MultiplexerFrame instance, MULTIPLEXER_FRAME_NOT_INIT>"
def initClientFrame(self,requestedID, remotehost, remoteport, localip, localport):
"""
<Purpose>
Makes the frame a MULTIPLEXER_INIT_CLIENT frame
<Arguments>
requestedID:
The requested Identifier for this new virtual socket
ip:
Our IP address reported to the partner multiplexer
port:
Our port reported to the partner multiplexer
"""
# Set the requestedID in the frame
self.referenceID = requestedID
# Set the content as a dict
requestDict = {'localip':remotehost,'localport':remoteport,'remoteip':localip,'remoteport':localport}
self.content = str(requestDict)
self.contentLength = len(self.content)
# Set the correct frame message type
self.mesgType = MULTIPLEXER_INIT_CLIENT
def initResponseFrame(self,requestedID,response):
"""
<Purpose>
Makes the frame a MULTIPLEXER_INIT_STATUS frame
<Arguments>
requestedID:
A reference to the requestedID of the MULTIPLEXER_INIT_CLIENT message
response:
The response message.
"""
# Set the requestedID in the frame
self.referenceID = requestedID
# Set the frame content
self.content = response
# Set the content length
self.contentLength = len(self.content)
# Set the correct frame message type
self.mesgType = MULTIPLEXER_INIT_STATUS
def initDataFrame(self,referenceID, content):
"""
<Purpose>
Makes the frame a MULTIPLEXER_DATA_FORWARD frame
<Arguments>
referenceID:
The referenceID that this frame should be routed to.
content:
The content that should be sent to the destination.
"""
# Strip any colons in the mac address
self.referenceID = referenceID
# Set the frame content
self.content = str(content)
# Set the content length
self.contentLength = len(self.content)
# Set the correct frame message type
self.mesgType = MULTIPLEXER_DATA_FORWARD
def initConnTermFrame(self,referenceID):
"""
<Purpose>
Makes the frame a MULTIPLEXER_CONN_TERM frame
<Arguments>
referenceID:
The referenceID of the socket that should be disconnected.
"""
# Strip any colons in the mac address
self.referenceID = referenceID
# Set the frame content
self.content = ""
# Set the content length
self.contentLength = 0
# Set the correct frame message type
self.mesgType = MULTIPLEXER_CONN_TERM
def initConnBufSizeFrame(self,referenceID, bufferSize):
"""
<Purpose>
Makes the frame a MULTIPLEXER_CONN_BUF_SIZE frame
<Arguments>
referenceID:
The referenceID of the scoket that should be altered.
bufferSize:
The new buffer size for the client.
"""
# Strip any colons in the mac address
self.referenceID = referenceID
# Set the frame content, convert the bufferSize into a string
self.content = str(bufferSize)
# Set the content length
self.contentLength = len(self.content)
# Set the correct frame message type
self.mesgType = MULTIPLEXER_CONN_BUF_SIZE
def initFromSocket(self, inSocket):
"""
<Purpose>
Constructs a frame object given a socket which contains only frames.
<Arguments>
inSocket:
The socket to read from.
<Exceptions>
An EnvironmentError will be raised if an unexpected header is received. This could happen if the socket is closed.
"""
# Read in the header frame size
headerSize = inSocket.recv(MULTIPLEXER_FRAME_HEADER_DIGITS+len(MULTIPLEXER_FRAME_DIVIDER))
headerSize = headerSize.rstrip(MULTIPLEXER_FRAME_DIVIDER)
try:
headerSize = int(headerSize)-1
except:
raise EnvironmentError, "Failed to convert: "+headerSize+" to an integer!"
header = inSocket.recv(headerSize)
if len(header) == headerSize:
# Setup header
self._parseStringHeader(header)
if self.contentLength != 0:
content = "" # Store the data we have received so far
recieved = 0 # Track the amount of data we have
# Loop until we receive all of the data
while recieved < self.contentLength:
newContent = inSocket.recv(self.contentLength - recieved)
newLength = len(newContent)
# Check the length
if newLength == 0:
raise EnvironmentError, "Received null dataset!"
else:
# Store the new data
recieved += newLength
content += newContent
# Assign the content
self.content = content
else:
raise EnvironmentError, "Unexpected Header Size!"
# Takes a string representing the header, and initializes the frame
def _parseStringHeader(self, header):
# Explode based on the divider
headerFields = header.split(MULTIPLEXER_FRAME_DIVIDER,2)
(msgtype, contentlength, ref) = headerFields
try:
# Convert the types
msgtype = int(msgtype)
contentlength = int(contentlength)
# Strip the last semicolon off
ref = int(ref.rstrip(MULTIPLEXER_FRAME_DIVIDER))
# Setup the Frame
self.mesgType = msgtype
self.contentLength = contentlength
self.referenceID = ref
except:
raise EnvironmentError, "Failed to parse header: "+header+" with fields: "+str(headerFields)
def toString(self):
"""
<Purpose>
Converts the frame to a string.
<Exceptions>
Raises an AttributeError exception if the frame is not yet initialized.
<Returns>
A string based representation of the string.
"""
if self.mesgType == MULTIPLEXER_FRAME_NOT_INIT:
raise AttributeError, "Frame is not yet initialized!"
# Create header
frameHeader = MULTIPLEXER_FRAME_DIVIDER + str(self.mesgType) + MULTIPLEXER_FRAME_DIVIDER + str(self.contentLength) + \
MULTIPLEXER_FRAME_DIVIDER + str(self.referenceID) + MULTIPLEXER_FRAME_DIVIDER
# Determine variable header size
headerSize = str(len(frameHeader)).rjust(MULTIPLEXER_FRAME_HEADER_DIGITS,"0")
if len(headerSize) > MULTIPLEXER_FRAME_HEADER_DIGITS:
raise AttributeError, "Frame Header too large! Max:"+ MULTIPLEXER_FRAME_HEADER_DIGITS+ " Actual:"+ len(headerSize)
return headerSize + frameHeader + self.content
# This helps abstract the details of a Multiplexed connection
class Multiplexer():
def __init__(self, socket, info=None):
"""
<Purpose>
Initializes the Multiplexer object.
<Arguments>
socket:
Socket like object that is used for multiplexing
info:
A dictionary object. Its key/value pairs will be injected into mux.socketInfo.
This can be used to store custom data, or to override localip, localport, remoteip, and remoteport.
It is optional.
"""
# If we are given a socket, assume it is setup
if socket != None:
# Is everything setup?
self.connectionInit = True
# Default incoming and outgoing buffer size expansion value
# Defaults to 128 kilobytes
self.defaultBufSize = 128*1024
# This is the main socket
self.socket = socket
# This dictionary contains information about this socket
# This just has some junk default values, and is filled in during init
self.socketInfo = {"localip":"127.0.0.1","localport":0,"remoteip":"127.0.0.1","remoteport":0}
# Locks, this is to make sure only one thread is reading or writing at any time
self.readLock = getlock()
self.writeLock = getlock()
# Callback function that is passed a socket object
# Maps a host (e.g. 127.0.0.1) to a dictionary of ports -> functions
# So callBackFunctions["127.0.0.1"][50] returns the user function for host 127.0.0.1 port 50
self.callbackFunction = {}
# This dictionary keeps track of sockets we are waiting to open, e.g. openconn has been called
# but the partner multiplexer has not responded yet
self.pendingSockets = {}
# If we want a new client, what number should we request?
self.nextReferenceID = 0
# A dictionary that associates reference ID's to their MultiplexerSocket objects
self.virtualSockets = {}
self.virtualSocketsLock = getlock()
# Inject or override socket info given to use
if info is not None:
for key, value in info.items():
self.socketInfo[key] = value
# Set error if one occurs in socketReader
self.error = None
# Callback function in case of fatal error
self.errorDelegate = None
# Launch event to handle the multiplexing
# Wait a few seconds so that the user has a chance to set waitforconn
settimer(MULTIPLEXER_START_DELAY, self._socketReader, ())
else:
raise ValueError, "Must pass in a valid socket!"
# So that we display properly
def __repr__(self):
# Format a nice string with some of our info
return "<Multiplexer setup:"+str(self.isAlive())+ \
" buf_size:"+str(self.defaultBufSize)+ \
" counter:"+str(self.nextReferenceID)+ \
" info:"+str(self.socketInfo)+">"
# Returns the status of the multiplexer
def isAlive(self):
"""
<Purpose>
Returns the status of the multiplexer. Since the multiplexer is mostly handled by internal threads,
user programs will not receive exceptions on a fatal error, like the underlying socket closing.
This function returns the status, or setErrorDelegate can be used to be informed proactively.
<Returns>
True, if the multiplexer is alive and functional. False otherwise.
"""
# Just use connectionInit, that is our internal variable
return self.connectionInit
# Closes the Multiplexer, and cleans up
def close(self, closeSocket=True):
"""
<Purpose>
Closes the Multiplexer object. Also closes all virtual sockets associated with this connection.
<Arguments>
closeSocket:
If true, the master socket will be closed as well.
"""
# Prevent more reading or writing
try:
self.readLock.release()
except:
# See below
pass
finally:
self.readLock.acquire()
try:
self.writeLock.release()
except:
# Exception is thrown if the lock is already unlocked
pass
finally:
self.writeLock.acquire()
# The Mux is no longer initialized
self.connectionInit = False
# Close each individual socket
for refID, sock in self.virtualSockets.items():
self._closeCONN(sock, refID)
# Close the real socket
if closeSocket and self.socket != None:
self.socket.close()
self.socket = None
# Cancel all pending sockets, this is so they get
# connection refused instead of timed out
for refID, info in self.pendingSockets.items():
# Cancel the timeout timer
try:
canceltimer(info[2])
except:
# There might have not been any timer set
pass
# Set the handle to None, so that Connection Refused is infered
info[2] = None
# Unblock openconn
try:
info[1].release()
except:
pass
# Check if we have an error delegate and an error
if self.error != None and self.errorDelegate != None:
# Call the error delegate, with self and the error
self.errorDelegate(self, self.error[0], self.error[1])
# Remove the error, to prevent multiple notifications
self.error = None
# Stops additional listener threads
def stopcomm(self,handle):
"""
<Purpose>
Stops listening for the selected waithandle
<Arguments>
handle:
A handle returned from waitforconn
"""
# Convert handle back to tuple, unpack it
(ip, port) = deserialize(handle)
# Deletes the callback function on the specified port
if ip in self.callbackFunction and port in self.callbackFunction[ip]:
del self.callbackFunction[ip][port]
# Private: Recieves a single frame
def _recvFrame(self):
# Check if we are initialized
if not self.isAlive():
raise AttributeError, "Multiplexer is not yet initialized or is closed!"
# Init frame
frame = MultiplexerFrame()
try:
# Get the read lock
self.readLock.acquire()
# Construct frame, this blocks
frame.initFromSocket(self.socket)
except Exception, exp:
# Store the error
self.error = ("_recvFrame", exp)
# We need to close the multiplexer
self.close()
# Re-raise the exception
raise EnvironmentError, "Fatal Error:"+str(exp)
# Release the lock
self.readLock.release()
# Return the frame
return frame
# Private: Sends a single frame
def _sendFrame(self,frame):
# Check if we are initialized
if not self.isAlive():
raise AttributeError, "Multiplexer is not yet initialized or is closed!"
try:
# Get the send lock
self.writeLock.acquire()
# Send the frame!
self.socket.send(frame.toString())
except Exception, exp:
# Store the error
self.error = ("_sendFrame", exp)
# We need to close the multiplexer
self.close()
# Re-raise the exception
raise EnvironmentError, "Fatal Error:"+str(exp)
# release the send lock
self.writeLock.release()
def _send(self,referenceID, data):
"""
<Purpose>
Sends data as a frame over the socket.
<Arguments>
referenceID:
The target to send the data to.
data:
The data to send to the target.
<Exceptions>
If the connection is not initialized, an AttributeError is raised. Socket error can be raised if the socket is closed during transmission.
"""
# Build the frame
frame = MultiplexerFrame()
# Initialize it
frame.initDataFrame(referenceID, data)
# Send it!
self._sendFrame(frame)
def openconn(self, desthost, destport, localip=None,localport=None,timeout=15):
"""
<Purpose>
Opens a connection, returning a socket-like object
<Arguments>
See repy's openconn
<Side Effects>
None
<Returns>
A socket like object.
"""
# Check if we are initialized
if not self.isAlive():
raise AttributeError, "Multiplexer is not yet initialized or is closed!"
# Check for default values
if localip == None:
localip = self.socketInfo["localip"]
if localport == None:
localport = self.socketInfo["localport"]
# Create an MULTIPLEXER_INIT_CLIENT frame
frame = MultiplexerFrame()
# Get a new id
requestedID = self.nextReferenceID
# Increment the counter
self.nextReferenceID = self.nextReferenceID + 1
# Setup the frame
frame.initClientFrame(requestedID, desthost, destport, localip, localport)
# Add this request to the pending sockets, add a bool to hold if this was successful, and a lock that we use for blocking
# The third element is a timer handle, that is used for the timeout
self.pendingSockets[requestedID] = [False, getlock(), None]
# Send the request
self._sendFrame(frame)
# Now we block until the request is handled, or until we reach the timeout
# Set a timer to unblock us after a timeout
self.pendingSockets[requestedID][2] = settimer(timeout, self._openconn_timeout, [requestedID])
# Acquire the lock twice, and wait for it to be release
self.pendingSockets[requestedID][1].acquire()
self.pendingSockets[requestedID][1].acquire()
# Were we successful?
success = self.pendingSockets[requestedID][0]
# Get the timer handle
handle = self.pendingSockets[requestedID][2]
# Remove the request
del self.pendingSockets[requestedID]
# At this point we've been unblocked, so were we successful?
if success:
# Create info dictionary
info = {"localip":localip,"localport":localport,"remoteip":desthost,"remoteport":destport}
# Return a virtual socket
socket = MultiplexerSocket(requestedID, self, self.defaultBufSize, info)
# By default there is no data, so set the lock
socket.socketLocks["nodata"].acquire()
# Lock the virtual sockets dictionary
self.virtualSocketsLock.acquire()
# Create the entry for it, add the data to it
self.virtualSockets[requestedID] = socket
# Release the dictionary lock
self.virtualSocketsLock.release()
return socket
# We failed or timed out
else:
if handle == None:
# Our partner responded, but not with MULTIPLEXER_STATUS_CONFIRMED
raise EnvironmentError, "Connection Refused!"
else:
# Our connection timed out
raise EnvironmentError, "Connection timed out!"
# Unblocks openconn after a timeout
def _openconn_timeout(self, refID):
# Release the socket, so that openconn can continue execution
try:
self.pendingSockets[refID][1].release()
except:
# This is just to be safe
pass
def waitforconn(self, localip, localport, function):
"""
<Purpose>
Waits for a connection to a port. Calls function with a socket-like object if it succeeds.
<Arguments>
localip:
The local IP to listen on
localport:
The local port to bind to
function:
The function to call. It should take four arguments: (remoteip, remoteport, socketlikeobj, None, multiplexer)
If your function has an uncaught exception, the socket-like object it is using will be closed.
<Side Effects>
Starts an event handler that listens for connections.
<Returns>
A handle that can be used with stopcomm
"""
# Check if we are initialized
if not self.isAlive():
raise AttributeError, "Multiplexer is not yet initialized or is closed!"
# Check if this is a new host, make a new dictionary
if not localip in self.callbackFunction:
self.callbackFunction[localip] = {}
# Setup the user function to call if there is a new client
self.callbackFunction[localip][localport] = function
# Generate a handle, string version of tuple (ip, port)
return str((localip,localport))
# Handles a client closing a connection
def _closeCONN(self,socket, refID):
# Close the socket
socket.socketInfo["closed"] = True
# Release the client sockets nodata and sending locks, so that they immediately see the message
# Wrap in try/catch since release will fail on a non-acquired lock
try:
socket.socketLocks["nodata"].release()
except:
pass
try:
socket.socketLocks["outgoing"].release()
except:
pass
# Handles a MULTIPLEXER_CONN_BUF_SIZE message
# Increases the amount we can send out
def _conn_buf_size(self,socket, num):
# Acquire a lock for the socket
socket.socketLocks["send"].acquire()
# Increase the buffer size
socket.bufferInfo["outgoing"] = num
# Release the outgoing lock, this unblocks socket.send
try:
socket.socketLocks["outgoing"].release()
except:
# That means the lock was already released
pass
# Release the socket
socket.socketLocks["send"].release()
# Handles a new client connecting
def _new_client(self, frame, refID):
# Do an internal error check
if self._virtualSock(refID) != None:
raise Exception, "Attempting to connect with a used reference ID!"
# Get the request info
id = frame.referenceID # Get the ID from the frame
info = deserialize(frame.content) # Get the socket info from
# What port are they trying to connect to?
requestedHost = info["localip"]
requestedPort = info["localport"]
# Check for a callback function
if requestedHost in self.callbackFunction and requestedPort in self.callbackFunction[requestedHost]:
userfunc = self.callbackFunction[requestedHost][requestedPort]
# Send a failure message and return
else:
# Respond to our parter, send a failure message
resp = MultiplexerFrame()
resp.initResponseFrame(id,MULTIPLEXER_STATUS_FAILED)
self._sendFrame(resp)
return
# Get the main dictionary lock
self.virtualSocketsLock.acquire()
# Create the socket
socket = MultiplexerSocket(id, self, self.defaultBufSize, info)
# We need to increase our reference counter now, so as to prevent duplicates
self.nextReferenceID = id + 1
# Respond to our parter, send a success message
resp = MultiplexerFrame()
resp.initResponseFrame(id,MULTIPLEXER_STATUS_CONFIRMED)
self._sendFrame(resp)
# Create the entry for it, add the data to it
self.virtualSockets[refID] = socket
# By default there is no data, so set the lock
socket.socketLocks["nodata"].acquire()
# If the frame is a data frame, add the data
if frame.mesgType == MULTIPLEXER_DATA_FORWARD:
self._incoming_client_data(frame, socket)
# Release the main dictionary lock
self.virtualSocketsLock.release()
# Make sure the user code is safe, launch an event for it
try:
settimer(0, userfunc, (info["remoteip"], info["remoteport"], socket, None, self))
except:
# Close the socket
socket.close()
# Handles incoming data for an existing client
def _incoming_client_data(self, frame, socket):
# Acquire a lock for the socket
socket.socketLocks["recv"].acquire()
# Increase the buffer size
socket.buffer += frame.content
# Release the outgoing lock, this unblocks socket.send
try:
socket.socketLocks["nodata"].release()
except:
# That means the lock was already released
pass
# Release the socket
socket.socketLocks["recv"].release()
# Handles MULTIPLEXER_INIT_STATUS messages for a pending client
def _pending_client(self, frame, refID):
# Return if the referenced client is not in the pending list
if not (refID in self.pendingSockets):
return
# Cancel the timeout timer
try:
canceltimer(self.pendingSockets[refID][2])
except:
# Be careful of race condition where the timer is cleaned up
# before we run.
pass
# Set the handle to None
self.pendingSockets[refID][2] = None
# Has our partner confirmed the connection? If so, then update the pending socket
if frame.content == MULTIPLEXER_STATUS_CONFIRMED:
self.pendingSockets[refID][0] = True
# Unblock openconn
try:
self.pendingSockets[refID][1].release()
except:
pass
# Simple function to determine if a client is connected,
# and if so returns their virtual socket
def _virtualSock(self,refID):
# Get the main dictionary lock
self.virtualSocketsLock.acquire()
if refID in self.virtualSockets:
sock = self.virtualSockets[refID]
else:
sock = None
# Release the main dictionary lock
self.virtualSocketsLock.release()
return sock
# This is launched as an event to handle multiplexing the connection
def _socketReader(self):
# If this thread crashes, close the multiplexer
try:
# This thread is responsible for reading all incoming frames,
# so it pushes data into the buffers, initializes new threads for each new client
# and handles all administrative frames
while True:
# Should we quit?
if not self.isAlive():
break
# Read in a frame
try:
frame = self._recvFrame()
refID = frame.referenceID
frameType = frame.mesgType
except:
# This is probably because the socket is now closed, so lets loop around and see
continue
# It is possible we recieved a close command while doing recv, so lets check again and handle this
if not self.isAlive():
break
# Get the virtual socket if it exists
socket = self._virtualSock(refID)
# Handle MULTIPLEXER_INIT_CLIENT
if frameType == MULTIPLEXER_INIT_CLIENT:
self._new_client(frame, refID)
# Handle MULTIPLEXER_INIT_STATUS
elif frameType == MULTIPLEXER_INIT_STATUS:
self._pending_client(frame, refID)
# Handle MULTIPLEXER_CONN_TERM
elif frameType == MULTIPLEXER_CONN_TERM:
# If the socket is none, that means this client is already terminated
if socket != None:
self._closeCONN(socket, refID)
# Handle MULTIPLEXER_CONN_BUF_SIZE
elif socket != None and frameType == MULTIPLEXER_CONN_BUF_SIZE:
self. _conn_buf_size(socket, int(frame.content))
# Handle MULTIPLEXER_DATA_FORWARD
elif frameType == MULTIPLEXER_DATA_FORWARD:
# Does this client socket exists? If so, append to their buffer
# This is a new client, we need to call the user callback function
if socket == None:
self._new_client(frame, refID)
else:
self._incoming_client_data(frame,socket)
# We don't know what this is, so panic
else:
raise Exception, "Unhandled Frame type: "+ str(frame)
# We caught an exception, close the multiplexer and exit
except Exception, err:
# Store the error
self.error = ("_socketReader", err)
# Close
self.close()
def setErrorDelegate(self, func):
"""
<Purpose>
Allows a user-defined function to be notified if the Multiplexer is closed internally, without a call to close().
<Arguments>
func:
The user function to be called after close() is completed due to an error condition.
The function should take the following arguments:
-mux : A reference to the multiplexer object
-location : A string reference to the point of failure
-exp : The actually exception that caused the internal failure
Set the func to None to disable the error delegation.
<Returns>
None.
"""
# Assign the user function to the internal callback handle
self.errorDelegate = func
# A socket like object with an understanding that it is part of a Multiplexer
# Has the same functions as the socket like object in repy
class MultiplexerSocket():
def __init__(self, id, mux, buf, info):
# Initialize
# Reference ID
self.id = id
# Pointer to the master Multiplexer
self.mux = mux
# Socket information
self.socketInfo = {"closed":False,"localip":"","localport":0,"remoteip":"","remoteport":0}
# Actual buffer of unread data
self.buffer = ""
# Buffering Information
self.bufferInfo = {"incoming":buf,"outgoing":buf}
# Various locks used in the socket
self.socketLocks = {"recv":getlock(),"send":getlock(),"nodata":getlock(),"outgoing":getlock()}
# Inject or override socket info given to use
for key, value in info.items():
self.socketInfo[key] = value
def close(self):
"""
<Purpose>