forked from SeattleTestbed/seattlelib_v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsockettimeout.r2py
351 lines (270 loc) · 9.09 KB
/
sockettimeout.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
"""
<Author>
Justin Cappos, Armon Dadgar
This is a rewrite of the previous version by Richard Jordan
<Start Date>
26 Aug 2009
<Description>
A library that causes sockets to timeout if a recv / send call would
block for more than an allotted amount of time.
"""
random = dy_import_module("random.r2py")
class SocketTimeoutError(Exception):
"""The socket timed out before receiving a response"""
class timeout_socket():
"""
<Purpose>
Provides a socket like object which supports custom timeouts
for send() and recv().
"""
# Initialize with the socket object and a default timeout
def __init__(self,socket,timeout=10, checkintv=0.1):
"""
<Purpose>
Initializes a timeout socket object.
<Arguments>
socket:
A socket like object to wrap. Must support send,recv,close.
timeout:
The default timeout for send() and recv().
checkintv:
How often socket operations (send,recv) should check if
they can run. The smaller the interval the more time is
spent busy waiting.
"""
# Store the socket, timeout and check interval
self.socket = socket
self.timeout = timeout
self.checkintv = checkintv
# Allow changing the default timeout
def settimeout(self,timeout=10):
"""
<Purpose>
Allows changing the default timeout interval.
<Arguments>
timeout:
The new default timeout interval. Defaults to 10.
Use 0 for no timeout. Given in seconds.
"""
# Update
self.timeout = timeout
# Wrap close
def close(self):
"""
See socket.close()
"""
return self.socket.close()
# Provide a recv() implementation
def recv(self,bytes,timeout=None):
"""
<Purpose>
Allows receiving data from the socket object with a custom timeout.
<Arguments>
bytes:
The maximum amount of bytes to read
timeout:
(Optional) Defaults to the value given at initialization, or by settimeout.
If provided, the socket operation will timeout after this amount of time (sec).
Use 0 for no timeout.
<Exceptions>
As with socket.recv(), socket.willblock(). Additionally, SocketTimeoutError is
raised if the operation times out.
<Returns>
The data received from the socket.
"""
# Set the timeout if None
if timeout is None:
timeout = self.timeout
# Get the start time
starttime = getruntime()
elapsed_time = 0
while elapsed_time < timeout:
try:
data = self.socket.recv(bytes)
except SocketWouldBlockError:
sleep(self.checkintv)
elapsed_time = getruntime() - starttime
else:
break
else:
raise SocketTimeoutError, "recv() timed out!!"
return data
# Provide a send() implementation
def send(self,data,timeout=None):
"""
<Purpose>
Allows sending data with the socket object with a custom timeout.
<Arguments>
data:
The data to send
timeout:
(Optional) Defaults to the value given at initialization, or by settimeout.
If provided, the socket operation will timeout after this amount of time (sec).
Use 0 for no timeout.
<Exceptions>
As with socket.send(), socket.willblock(). Additionally, SocketTimeoutError is
raised if the operation times out.
<Returns>
The number of bytes sent.
"""
# Set the timeout if None
if timeout is None:
timeout = self.timeout
# Get the start time
starttime = getruntime()
elapsed_time = 0
while elapsed_time < timeout:
try:
sentbytes = self.socket.send(data)
except SocketWouldBlockError:
sleep(self.checkintv)
elapsed_time = getruntime() - starttime
else:
break
else:
raise SocketTimeoutError, "send() timed out!!"
return sentbytes
# Wrapper class for TCPServerSocket in emulcomm
class timeout_server_socket():
"""
<Purpose>
Provides a TCPSeverSocket like object which supports custom timeouts
for getconnection().
"""
def __init__(self, socket,timeout=10, checkintv=0.1):
"""
<Purpose>
Initializes a timeout TCPServerSocket object.
<Arguments>
socket:
A socket like object to wrap. Must support getconnection, close.
timeout:
The default timeout for getconnection().
checkintv:
How often socket operations (getconnection) should check if
they can run. The smaller the interval the more time is
spent busy waiting.
"""
self.socket = socket
self.timeout = timeout
self.checkintv = checkintv
# Allow changing the default timeout
def settimeout(self,timeout=10):
"""
<Purpose>
Allows changing the default timeout interval.
<Arguments>
timeout:
The new default timeout interval. Defaults to 10.
Use 0 for no timeout. Given in seconds.
"""
# Update
self.timeout = timeout
def getconnection(self, timeout=None):
"""
<Purpose>
Allows accecpting new connection on TCPSeverSocket object with a custom
timeout.
<Arguments>
timeout:
(Optional) Defaults to the value given at initialization, or by settimeout.
If provided, the socket operation will timeout after this amount of time (sec).
Use 0 for no timeout.
<Exceptions>
As with TCPSeverSocket.getconnection(). Additionally, SocketTimeoutError
is raised if the operation times out.
<Returns>
A 3-tuple consisting of remoteip, remoteport and client socket.
"""
# Set the timeout if None
if timeout is None:
timeout = self.timeout
# Get the start time.
starttime = getruntime()
elapsed_time = 0
while elapsed_time < timeout:
try:
remoteip, remoteport, realsocketlikeobject = self.socket.getconnection()
except SocketWouldBlockError:
sleep(self.checkintv)
elapsed_time = getruntime() - starttime
else:
break
else:
raise SocketTimeoutError, "getconnection() timed out!"
thissocketlikeobject = timeout_socket(realsocketlikeobject, timeout)
return (remoteip, remoteport, thissocketlikeobject)
# Wrap close
def close(self):
"""
See socket.close()
"""
self.socket.close()
def timeout_openconnection(desthost, destport, localip=None, localport=None, timeout=5):
"""
<Purpose>
Wrapper for openconnection. Very, very similar
<Args>
Similar to Repy's openconnection, but will try to automatically come
up with localip and localport if omitted.
<Exception>
Raises the same exceptions as openconnection.
<Side Effects>
Creates a socket object for the user
<Returns>
socket obj on success
"""
# Initialize localip and localport (if not set by caller)
if localip is None:
localip = getmyip()
if localport is None:
# Get the ports available to our vessel (#1375)
# (I'll try all of the nominally available ports, not only
# the ones that are currently unused, because port usage might
# change while we still set up things here.)
available_resources, ignore, ignore = getresources()
portrange = list(available_resources['connport'])
# Shuffle the portrange to make it unlikely we ever reuse the
# same quintuple twice in a row (#1362)
random.random_shuffle(portrange)
else:
portrange = [localport]
for myport in portrange:
try:
realsocketlikeobject = openconnection(desthost, destport, localip, myport, timeout)
# Heureka, we found a usable port. Continue outside of the for loop.
break
except (DuplicateTupleError, CleanupInProgressError,
AlreadyListeningError, AddressBindingError):
# These are "legitimate" in the sense that there is something
# in our very program already using the port we just tried.
pass
except ResourceForbiddenError:
# The port is not in the restrictions file. This can only
# happen if the user supplied us with the ``localport'' argument.
raise
except Exception:
# E.g. RepyArgumentError due to using a FQDN instead of an
# IP address argument -- the user's fault, really.
raise
else:
# Checked the whole port range without success
raise AddressBindingError, "Could not find any usable source port in the range " + str(portrange) + " on IP address " + str(localip) + "."
thissocketlikeobject = timeout_socket(realsocketlikeobject, timeout)
return thissocketlikeobject
def timeout_listenforconnection(localip, localport, timeout=5):
"""
<Purpose>
Wrapper for waitforconn. Essentially does the same thing...
<Args>
Same as Repy waitforconn with the addition of a timeout argument.
<Exceptions>
Same as Repy waitforconn
<Side Effects>
Sets up event listener which calls function on messages.
<Returns>
Handle to listener.
"""
realsocketlikeobject = listenforconnection(localip, localport)
thissocketlikeobject = timeout_server_socket(realsocketlikeobject, timeout)
return thissocketlikeobject