-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxylib.py
364 lines (332 loc) · 12.6 KB
/
proxylib.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
# Copyright 2014 Philippe THIRION
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import socketserver
import re
#import string
# import threading
import time
HOST, PORT = '0.0.0.0', 5060
rx_register = re.compile("^REGISTER")
rx_invite = re.compile("^INVITE")
rx_ack = re.compile("^ACK")
rx_prack = re.compile("^PRACK")
rx_cancel = re.compile("^CANCEL")
rx_bye = re.compile("^BYE")
rx_options = re.compile("^OPTIONS")
rx_subscribe = re.compile("^SUBSCRIBE")
rx_publish = re.compile("^PUBLISH")
rx_notify = re.compile("^NOTIFY")
rx_info = re.compile("^INFO")
rx_message = re.compile("^MESSAGE")
rx_refer = re.compile("^REFER")
rx_update = re.compile("^UPDATE")
rx_from = re.compile("^From:")
rx_cfrom = re.compile("^f:")
rx_to = re.compile("^To:")
rx_cto = re.compile("^t:")
rx_tag = re.compile(";tag")
rx_contact = re.compile("^Contact:")
rx_ccontact = re.compile("^m:")
rx_uri = re.compile("sip:([^@]*)@([^;>$]*)")
rx_addr = re.compile("sip:([^ ;>$]*)")
# rx_addrport = re.compile("([^:]*):(.*)")
rx_code = re.compile("^SIP/2.0 ([^ ]*)")
rx_invalid = re.compile("^193\.169")
rx_invalid2 = re.compile("^11\.")
# rx_cseq = re.compile("^CSeq:")
# rx_callid = re.compile("Call-ID: (.*)$")
# rx_rr = re.compile("^Record-Route:")
rx_request_uri = re.compile("^([^ ]*) sip:([^ ]*) SIP/2.0")
rx_route = re.compile("^Route:")
rx_contentlength = re.compile("^Content-Length:")
rx_ccontentlength = re.compile("^l:")
rx_via = re.compile("^Via:")
rx_cvia = re.compile("^v:")
rx_branch = re.compile(";branch=([^;]*)")
rx_rport = re.compile(";rport$|;rport;")
rx_contact_expires = re.compile("expires=([^;$]*)")
rx_expires = re.compile("^Expires: (.*)$")
# global dictionnary
recordroute = ""
topvia = ""
registrar = {}
def hexdump(chars, sep, width):
while chars:
line = chars[:width]
chars = chars[width:]
line = line.ljust(width, '\000')
def quotechars(chars):
return ''.join(['.', c][c.isalnum()] for c in chars)
class UDPHandler(socketserver.BaseRequestHandler):
def changeRequestUri(self):
# change request uri
md = rx_request_uri.search(self.data[0])
if md:
method = md.group(1)
uri = md.group(2)
if uri in registrar:
uri = "sip:%s" % registrar[uri][0]
self.data[0] = "%s %s SIP/2.0" % (method, uri)
def removeRouteHeader(self):
# delete Route
data = []
for line in self.data:
if not rx_route.search(line):
data.append(line)
return data
def addTopVia(self):
branch = ""
data = []
for line in self.data:
if rx_via.search(line) or rx_cvia.search(line):
md = rx_branch.search(line)
if md:
branch = md.group(1)
via = "%s;branch=%sm" % (topvia, branch)
data.append(via)
# rport processing
if rx_rport.search(line):
text = "received=%s;rport=%d" % self.client_address
via = line.replace("rport", text)
else:
text = "received=%s" % self.client_address[0]
via = "%s;%s" % (line, text)
data.append(via)
else:
data.append(line)
return data
def removeTopVia(self):
data = []
for line in self.data:
if rx_via.search(line) or rx_cvia.search(line):
if not line.startswith(topvia):
data.append(line)
else:
data.append(line)
return data
def checkValidity(self, uri):
addrport, socket, client_addr, validity = registrar[uri]
now = int(time.time())
if validity > now:
return True
else:
del registrar[uri]
return False
def getSocketInfo(self, uri):
addrport, socket, client_addr, validity = registrar[uri]
return (socket, client_addr)
def getDestination(self):
destination = ""
for line in self.data:
if rx_to.search(line) or rx_cto.search(line):
md = rx_uri.search(line)
if md:
destination = "%s@%s" % (md.group(1), md.group(2))
break
return destination
def getOrigin(self):
origin = ""
for line in self.data:
if rx_from.search(line) or rx_cfrom.search(line):
md = rx_uri.search(line)
if md:
origin = "%s@%s" % (md.group(1), md.group(2))
break
return origin
def sendResponse(self, code):
request_uri = "SIP/2.0 " + code
self.data[0] = request_uri
index = 0
data = []
for line in self.data:
data.append(line)
if rx_to.search(line) or rx_cto.search(line):
if not rx_tag.search(line):
data[index] = "%s%s" % (line, ";tag=123456")
if rx_via.search(line) or rx_cvia.search(line):
# rport processing
if rx_rport.search(line):
text = "received=%s;rport=%d" % self.client_address
data[index] = line.replace("rport", text)
else:
text = "received=%s" % self.client_address[0]
data[index] = "%s;%s" % (line, text)
if rx_contentlength.search(line):
data[index] = "Content-Length: 0"
if rx_ccontentlength.search(line):
data[index] = "l: 0"
index += 1
if line == "":
break
data.append("")
text = "\r\n".join(data)
self.socket.sendto(text.encode("utf-8"), self.client_address)
def processRegister(self):
fromm = ""
contact = ""
contact_expires = ""
header_expires = ""
expires = 0
validity = 0
authorization = ""
index = 0
auth_index = 0
data = []
size = len(self.data)
for line in self.data:
if rx_to.search(line) or rx_cto.search(line):
md = rx_uri.search(line)
if md:
fromm = "%s@%s" % (md.group(1), md.group(2))
if rx_contact.search(line) or rx_ccontact.search(line):
md = rx_uri.search(line)
if md:
contact = md.group(2)
else:
md = rx_addr.search(line)
if md:
contact = md.group(1)
md = rx_contact_expires.search(line)
if md:
contact_expires = md.group(1)
md = rx_expires.search(line)
if md:
header_expires = md.group(1)
if rx_invalid.search(contact) or rx_invalid2.search(contact):
if fromm in registrar:
del registrar[fromm]
self.sendResponse("488 Not Acceptable Here")
return
if len(contact_expires) > 0:
expires = int(contact_expires)
elif len(header_expires) > 0:
expires = int(header_expires)
if expires == 0:
if fromm in registrar:
del registrar[fromm]
self.sendResponse("200 VYBAVENE OK")
return
else:
now = int(time.time())
validity = now + expires
registrar[fromm] = [contact, self.socket, self.client_address, validity]
self.sendResponse("200 VYBAVENE OK")
def processInvite(self):
origin = self.getOrigin()
if len(origin) == 0 or not origin in registrar:
self.sendResponse("400 Bad Request")
return
destination = self.getDestination()
if len(destination) > 0:
if destination in registrar and self.checkValidity(destination):
socket, claddr = self.getSocketInfo(destination)
# self.changeRequestUri()
self.data = self.addTopVia()
data = self.removeRouteHeader()
# insert Record-Route
data.insert(1, recordroute)
text = "\r\n".join(data)
socket.sendto(text.encode("utf-8"), claddr)
else:
self.sendResponse("480 Temporarily Unavailable")
else:
self.sendResponse("500 Server Internal Error")
def processAck(self):
destination = self.getDestination()
if len(destination) > 0:
if destination in registrar:
socket, claddr = self.getSocketInfo(destination)
# self.changeRequestUri()
self.data = self.addTopVia()
data = self.removeRouteHeader()
# insert Record-Route
data.insert(1, recordroute)
text = "\r\n".join(data)
socket.sendto(text.encode("utf-8"), claddr)
def processNonInvite(self):
origin = self.getOrigin()
if len(origin) == 0 or not origin in registrar:
self.sendResponse("400 Bad Request")
return
destination = self.getDestination()
if len(destination) > 0:
if destination in registrar and self.checkValidity(destination):
socket, claddr = self.getSocketInfo(destination)
# self.changeRequestUri()
self.data = self.addTopVia()
data = self.removeRouteHeader()
# insert Record-Route
data.insert(1, recordroute)
text = "\r\n".join(data)
socket.sendto(text.encode("utf-8"), claddr)
else:
self.sendResponse("406 Not Acceptable")
else:
self.sendResponse("500 Server Internal Error")
def processCode(self):
origin = self.getOrigin()
if len(origin) > 0:
if origin in registrar:
socket, claddr = self.getSocketInfo(origin)
self.data = self.removeRouteHeader()
data = self.removeTopVia()
text = "\r\n".join(data)
socket.sendto(text.encode("utf-8"), claddr)
def processRequest(self):
# print "processRequest"
if len(self.data) > 0:
request_uri = self.data[0]
if rx_register.search(request_uri):
self.processRegister()
elif rx_invite.search(request_uri):
self.processInvite()
elif rx_ack.search(request_uri):
self.processAck()
elif rx_bye.search(request_uri):
self.processNonInvite()
elif rx_cancel.search(request_uri):
self.processNonInvite()
elif rx_options.search(request_uri):
self.processNonInvite()
elif rx_info.search(request_uri):
self.processNonInvite()
elif rx_message.search(request_uri):
self.processNonInvite()
elif rx_refer.search(request_uri):
self.processNonInvite()
elif rx_prack.search(request_uri):
self.processNonInvite()
elif rx_update.search(request_uri):
self.processNonInvite()
elif rx_subscribe.search(request_uri):
self.sendResponse("200 VYBAVENE OK")
elif rx_publish.search(request_uri):
self.sendResponse("200 VYBAVENE OK")
elif rx_notify.search(request_uri):
self.sendResponse("200 VYBAVENE OK")
elif rx_code.search(request_uri):
self.processCode()
else:
print("Unknown")
# print "message %s unknown" % self.data
def handle(self):
# socket.setdefaulttimeout(120)
data = self.request[0].decode("utf-8")
self.data = data.split("\r\n")
self.socket = self.request[1]
request_uri = self.data[0]
if rx_request_uri.search(request_uri) or rx_code.search(request_uri):
self.processRequest()
else:
if len(data) > 4:
hexdump(data, ' ', 16)