Debian Codegraph @

Xpjproject/tests/pjsua/inc_sip.py

raw symbols SCIP
1 #
2 from socket import *
3 import re
4 import random
5 import time
6 import sys
7 import inc_cfg as cfg
8 from select import *
9
10 # SIP request template
11 req_templ = \
12 """$METHOD $TARGET_URI SIP/2.0\r
13 Via: SIP/2.0/UDP $LOCAL_IP:$LOCAL_PORT;rport;branch=z9hG4bK$BRANCH\r
14 Max-Forwards: 70\r
15 From: <sip:[email protected]>$FROM_TAG\r
16 To: <$TARGET_URI>$TO_TAG\r
17 Contact: <sip:$LOCAL_IP:$LOCAL_PORT;transport=udp>\r
18 Call-ID: [email protected]\r
19 CSeq: $CSEQ $METHOD\r
20 Allow: PRACK, INVITE, ACK, BYE, CANCEL, UPDATE, REFER\r
21 Supported: replaces, 100rel, norefersub\r
22 User-Agent: pjsip.org Python tester\r
23 Content-Length: $CONTENT_LENGTH\r
24 $SIP_HEADERS"""
25
26
27 def is_request(msg):
28 return msg.split(" ", 1)[0] != "SIP/2.0"
29
30 def is_response(msg):
31 return msg.split(" ", 1)[0] == "SIP/2.0"
32
33 def get_code(msg):
34 if msg=="":
35 return 0
36 return int(msg.split(" ", 2)[1])
37
38 def get_tag(msg, hdr="To"):
39 pat = "^" + hdr + ":.*"
40 result = re.search(pat, msg, re.M | re.I)
41 if result==None:
42 return ""
43 line = result.group()
44 #print "line=", line
45 tags = line.split(";tag=")
46 if len(tags)>1:
47 return tags[1]
48 return ""
49 #return re.split("[;& ]", s)
50
51 def get_header(msg, hname):
52 headers = msg.splitlines()
53 for hdr in headers:
54 hfields = hdr.split(": ", 2)
55 if hfields[0]==hname:
56 return hfields[1]
57 return None
58
59 class Dialog:
60 sock = None
61 dst_addr = ""
62 dst_port = 5060
63 local_ip = ""
64 local_port = 0
65 tcp = False
66 call_id = str(random.random())
67 cseq = 0
68 local_tag = ";tag=" + str(random.random())
69 rem_tag = ""
70 last_resp_code = 0
71 inv_branch = ""
72 trace_enabled = True
73 last_request = ""
74 def __init__(self, dst_addr, dst_port=5060, tcp=False, trace=True, local_port=0):
75 self.dst_addr = dst_addr
76 self.dst_port = dst_port
77 self.tcp = tcp
78 self.trace_enabled = trace
79 if tcp==True:
80 self.sock = socket(AF_INET, SOCK_STREAM)
81 self.sock.connect(dst_addr, dst_port)
82 else:
83 self.sock = socket(AF_INET, SOCK_DGRAM)
84 self.sock.bind(("127.0.0.1", local_port))
85
86 self.local_ip, self.local_port = self.sock.getsockname()
87 self.trace("Dialog socket bound to " + self.local_ip + ":" + str(self.local_port))
88
89 def trace(self, txt):
90 if self.trace_enabled:
91 try:
92 print(str(time.strftime("%H:%M:%S ")) + txt)
93 except UnicodeEncodeError:
94 print((str(time.strftime("%H:%M:%S ")) + txt).encode('utf-8'))
95
96 def update_fields(self, msg):
97 if self.tcp:
98 transport_param = ";transport=tcp"
99 else:
100 transport_param = ""
101 msg = msg.replace("$TARGET_URI", "sip:"+self.dst_addr+":"+str(self.dst_port) + transport_param)
102 msg = msg.replace("$LOCAL_IP", self.local_ip)
103 msg = msg.replace("$LOCAL_PORT", str(self.local_port))
104 msg = msg.replace("$FROM_TAG", self.local_tag)
105 msg = msg.replace("$TO_TAG", self.rem_tag)
106 msg = msg.replace("$CALL_ID", self.call_id)
107 msg = msg.replace("$CSEQ", str(self.cseq))
108 branch=str(random.random())
109 msg = msg.replace("$BRANCH", branch)
110 return msg
111
112 def create_req(self, method, sdp, branch="", extra_headers="", body=""):
113 if branch=="":
114 self.cseq = self.cseq + 1
115 msg = req_templ
116 msg = msg.replace("$METHOD", method)
117 msg = msg.replace("$SIP_HEADERS", extra_headers)
118 if branch=="":
119 branch=str(random.random())
120 msg = msg.replace("$BRANCH", branch)
121 if sdp!="":
122 msg = msg.replace("$CONTENT_LENGTH", str(len(sdp)))
123 msg = msg + "Content-Type: application/sdp\r\n"
124 msg = msg + "\r\n"
125 msg = msg + sdp
126 elif body!="":
127 msg = msg.replace("$CONTENT_LENGTH", str(len(body)))
128 msg = msg + "\r\n"
129 msg = msg + body
130 else:
131 msg = msg.replace("$CONTENT_LENGTH", "0")
132 return self.update_fields(msg)
133
134 def create_response(self, request, code, reason, to_tag=""):
135 response = "SIP/2.0 " + str(code) + " " + reason + "\r\n"
136 lines = request.splitlines()
137 for line in lines:
138 hdr = line.split(":", 1)[0]
139 if hdr in ["Via", "From", "To", "CSeq", "Call-ID"]:
140 if hdr=="To" and to_tag!="":
141 line = line + ";tag=" + to_tag
142 elif hdr=="Via":
143 line = line + ";received=127.0.0.1"
144 response = response + line + "\r\n"
145 return response
146
147 def create_invite(self, sdp, extra_headers="", body=""):
148 self.inv_branch = str(random.random())
149 return self.create_req("INVITE", sdp, branch=self.inv_branch, extra_headers=extra_headers, body=body)
150
151 def create_ack(self, sdp="", extra_headers=""):
152 return self.create_req("ACK", sdp, extra_headers=extra_headers, branch=self.inv_branch)
153
154 def create_bye(self, extra_headers=""):
155 return self.create_req("BYE", "", extra_headers)
156
157 def send_msg(self, msg, dst_addr=None):
158 if (is_request(msg)):
159 self.last_request = msg.split(" ", 1)[0]
160 if not dst_addr:
161 dst_addr = (self.dst_addr, self.dst_port)
162 self.trace("============== TX MSG to " + str(dst_addr) + " ============= \n" + msg)
163 self.sock.sendto(msg.encode('utf-8'), 0, dst_addr)
164
165 def wait_msg_from(self, timeout):
166 endtime = time.time() + timeout
167 msg = ""
168 src_addr = None
169 while time.time() < endtime:
170 readset = select([self.sock], [], [], 1)
171 if len(readset[0]) < 1 or not self.sock in readset[0]:
172 if len(readset[0]) < 1:
173 print("select() timeout (will wait for " + str(int(endtime - time.time())) + "more secs)")
174 elif not self.sock in readset[0]:
175 print("select() alien socket")
176 else:
177 print("select other error")
178 continue
179 try:
180 msg, src_addr = self.sock.recvfrom(4096)
181 break
182 except:
183 print("recv() exception: ", sys.exc_info()[0])
184 continue
185
186 msgstr = msg.decode('utf-8')
187 if msgstr=="":
188 return "", None
189 if self.last_request=="INVITE" and self.rem_tag=="":
190 self.rem_tag = get_tag(msgstr, "To")
191 self.rem_tag = self.rem_tag.rstrip("\r\n;")
192 if self.rem_tag != "":
193 self.rem_tag = ";tag=" + self.rem_tag
194 self.trace("=== rem_tag:" + self.rem_tag)
195 self.trace("=========== RX MSG from " + str(src_addr) + " ===========\n" + msgstr)
196 return (msgstr, src_addr)
197
198 def wait_msg(self, timeout):
199 return self.wait_msg_from(timeout)[0]
200
201 # Send request and wait for final response
202 def send_request_wait(self, msg, timeout):
203 t1 = 1.0
204 endtime = time.time() + timeout
205 resp = ""
206 code = 0
207 for i in range(0,5):
208 self.send_msg(msg)
209 resp = self.wait_msg(t1)
210 if resp!="" and is_response(resp):
211 code = get_code(resp)
212 break
213 last_resp = resp
214 while code < 200 and time.time() < endtime:
215 resp = self.wait_msg(endtime - time.time())
216 if resp != "" and is_response(resp):
217 code = get_code(resp)
218 last_resp = resp
219 elif resp=="":
220 break
221 return last_resp
222
223 def hangup(self, last_code=0):
224 self.trace("====== hangup =====")
225 if last_code!=0:
226 self.last_resp_code = last_code
227 if self.last_resp_code>0 and self.last_resp_code<200:
228 msg = self.create_req("CANCEL", "", branch=self.inv_branch, extra_headers="")
229 self.send_request_wait(msg, 5)
230 msg = self.create_ack()
231 self.send_msg(msg)
232 elif self.last_resp_code>=200 and self.last_resp_code<300:
233 msg = self.create_ack()
234 self.send_msg(msg)
235 msg = self.create_bye()
236 self.send_request_wait(msg, 5)
237 else:
238 msg = self.create_ack()
239 self.send_msg(msg)
240
241
242 class SendtoCfg:
243 # Test name
244 name = ""
245 # pjsua InstanceParam
246 inst_param = None
247 # Complete INVITE message. If this is not empty, then this
248 # message will be sent instead and the "sdp" and "extra_headers"
249 # settings will be ignored.
250 complete_msg = ""
251 # Initial SDP
252 sdp = ""
253 # Extra headers to add to request
254 extra_headers = ""
255 # Expected code
256 resp_code = 0
257 # Use TCP?
258 use_tcp = False
259 # List of RE patterns that must exist in response
260 resp_include = []
261 # List of RE patterns that must NOT exist in response
262 resp_exclude = []
263 # Full (non-SDP) body
264 body = ""
265 # Constructor
266 def __init__(self, name, pjsua_args, sdp, resp_code,
267 resp_inc=[], resp_exc=[], use_tcp=False,
268 extra_headers="", body="", complete_msg="",
269 enable_buffer = False):
270 self.complete_msg = complete_msg
271 self.sdp = sdp
272 self.resp_code = resp_code
273 self.resp_include = resp_inc
274 self.resp_exclude = resp_exc
275 self.use_tcp = use_tcp
276 self.extra_headers = extra_headers
277 self.body = body
278 self.inst_param = cfg.InstanceParam("pjsua", pjsua_args)
279 self.inst_param.enable_buffer = enable_buffer
280
281
282 class RecvfromTransaction:
283 # The test title for this transaction
284 title = ""
285 # Optinal list of pjsua command and optional expect patterns
286 # to be invoked to make pjsua send a request
287 # Sample:
288 # (to make call and wait for INVITE to be sent)
289 # cmds = [ ["m"], ["sip:127.0.0.1", "INVITE sip:"] ]
290 cmds = []
291 # Check if the CSeq must be greater than last Cseq?
292 check_cseq = True
293 # List of RE patterns that must exists in incoming request
294 include = []
295 # List of RE patterns that MUST NOT exist in incoming request
296 exclude = []
297 # Response code to send
298 resp_code = 0
299 # Additional list of headers to be sent on the response
300 # Note: no need to add CRLF on the header
301 resp_hdr = []
302 # Message body. This should include the Content-Type header too.
303 # Sample:
304 # body = """Content-Type: application/sdp\r\n
305 # \r\n
306 # v=0\r\n
307 # ...
308 # """
309 body = None
310 # Pattern to be expected on pjsua when receiving the response
311 expect = ""
312 # Required config
313 pj_config = ""
314
315 def __init__(self, title, resp_code, check_cseq=True,
316 include=[], exclude=[], cmds=[], resp_hdr=[], resp_body=None, expect="", pj_config=""):
317 self.title = title
318 self.cmds = cmds
319 self.include = include
320 self.exclude = exclude
321 self.resp_code = resp_code
322 self.resp_hdr = resp_hdr
323 self.body = resp_body
324 self.expect = expect
325 self.pj_config=pj_config
326
327
328 class RecvfromCfg:
329 # Test name
330 name = ""
331 # pjsua InstanceParam
332 inst_param = None
333 # List of RecvfromTransaction
334 transaction = None
335 # Use TCP?
336 tcp = False
337 # Required config
338 pj_config = ""
339
340 # Note:
341 # Any "$PORT" string in the pjsua_args will be replaced
342 # by server port
343 def __init__(self, name, pjsua_args, transaction, tcp=False, pj_config=""):
344 self.name = name
345 self.inst_param = cfg.InstanceParam("pjsua", pjsua_args)
346 self.transaction = transaction
347 self.tcp=tcp
348 self.pj_config=pj_config
349
350
351
352