Adding support for DB access from unit tests
[ipypbx] / src / ipypbx / http.py
1 # Copyright (c) Stas Shtin, 2010
2
3 # This file is part of IPyPBX.
4
5 # IPyPBX is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9
10 # IPyPBX is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License
16 # along with IPyPBX.  If not, see <http://www.gnu.org/licenses/>.
17
18 import xml.etree.ElementTree as etree
19 from PyQt4 import QtCore, QtNetwork
20
21
22 class FreeswitchConfigServer(QtNetwork.QTcpServer):
23     """
24     TCP server that receives config requests from freeswitch.
25     """
26     configNotFound = '''
27 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
28 <document type="freeswitch/xml">
29   <section name="result">
30     <result status="not found" />
31   </section>
32 </document>
33     '''
34     responseTemplate = '''HTTP/1.1 200 OK
35 Content-Type: text/xml; charset=utf-8
36 Content-Length: %i
37
38 %s'''
39   
40     def __init__(self, window):
41         super(FreeswitchConfigServer, self).__init__(window)
42
43         self.host = None
44         self.port = None
45         self.connection_id = None
46         self.is_running = False
47         self.generators = [
48             GenClass(window, self) for GenClass in (
49                 SofiaConfGenerator,)]
50         
51         self.httpRequestParser = HttpRequestParser(self)
52         
53     def setSocketData(self, host, port, connection_id):
54         """
55         Set host and port for socket to listen on.
56
57         If the settings differ from previous values, server gets restarted.
58         """
59         # Check if restart is needed before new settings are applied.
60         needs_restart = (
61             (host, port) != (self.host, self.port)) and connection_id
62
63         # Save new settings.
64         self.host = host
65         self.port = port
66         if connection_id:
67             self.connection_id = connection_id
68
69         # Restart server if necessary.
70         if needs_restart:
71             self.restartServer()
72
73     def startServer(self):
74         """
75         Start listening on our socket.
76         """
77         if not self.is_running:
78             if self.host and self.port:
79                 self.newConnection.connect(self.clientConnecting)
80                 self.listen(QtNetwork.QHostAddress(self.host), self.port)
81                 self.is_running = True
82
83     def stopServer(self):
84         """
85         Stop listening on our socket.
86         """
87         if self.is_running:
88             self.close()
89             self.is_running = False
90
91     def restartServer(self):
92         """
93         Restart server.
94         """
95         self.stopServer()
96         self.startServer()
97
98     def clientConnecting(self):
99         """
100         Handle client connection.
101         """
102         if self.hasPendingConnections():
103             self.socket = self.nextPendingConnection()
104             self.socket.readyRead.connect(self.receiveData)
105
106     def receiveData(self):
107         # TODO: read in chunks.
108         for line in str(self.socket.readAll()).split('\r\n'):
109             print self.httpRequestParser.i, line
110             self.httpRequestParser.handle(line)
111
112         response = self.httpRequestParser.result or self.configNotFound
113         http_response = self.responseTemplate % (len(response), response)
114         self.socket.write(http_response)
115         print
116         print http_response
117         print
118         self.httpRequestParser.reset()        
119         self.socket.close()
120
121 class HttpParseError(Exception):
122     """
123     Error parsing HTTP request.
124     """
125
126
127 class HttpRequestParser(object):
128     """
129     A simple state machine for parsing HTTP requests.
130     """
131     HTTP_NONE, HTTP_REQUEST, HTTP_HEADERS, HTTP_EMPTY, HTTP_MESSAGE, \
132         HTTP_DONE = range(6)
133     HTTP_STATES = ['NONE', 'REQUEST', 'HEADERS', 'EMPTY', 'MESSAGE', 'DONE']
134     
135     def __init__(self, parent):
136         self.parent = parent
137         self.i = 0
138         self.reset()
139
140     def reset(self):
141         """
142         Reset parser to initial state.
143         """
144         self.i += 1
145         # Initial values for request data.
146         self.method = None
147         self.request_path = None
148         self.http_version = None
149         self.headers = {}
150         self.data = {}
151         self.result = None
152         
153         # Set initial state.
154         self.state = self.HTTP_NONE        
155
156     def handle(self, line):
157         """
158         Dispatch line to current state handler.
159         """
160         for state in self.HTTP_STATES:
161             if getattr(self, 'HTTP_%s' % state) == self.state:
162                 getattr(self, 'handle%s' % state.title())(line)
163                 break
164         else:
165             raise HttpParseError('Unknown HTTP state')
166                 
167     def handleNone(self, line):
168         """
169         Pass line to next state.
170         """
171         self.state += 1
172         self.handle(line)
173
174     def handleRequest(self, line):
175         """
176         Retrieve HTTP method, request path and HTTP version from request.
177         """
178         try:
179             self.method, self.request_path, self.http_version = line.split(' ')
180             self.state += 1
181         except ValueError:
182             pass
183
184     def handleHeaders(self, line):
185         """
186         Parse headers while not found an empty line.
187         """
188         if line:
189             key, value = line.split(': ')
190             self.headers[key] = value
191         else:
192             self.state += 1
193             self.handle(line)
194
195     def handleEmpty(self, line):
196         """
197         Empty line separator is found - proceed to next state.
198         """
199         self.state += 1
200
201     def handleMessage(self, line):
202         """
203         Append to message body.
204         """
205         self.data = dict(pair.split('=', 2) for pair in line.split('&'))
206
207         #for k, v in self.data.items():
208         #    print k, '=>', v
209         #print
210
211         for generator in self.parent.generators:
212             if generator.canHandle(self.data):
213                 self.state += 1
214                 self.result = etree.tostring(generator.generateConfig(
215                     self.headers))
216                 break
217
218
219 class FreeswitchConfigGenerator(object):
220     """
221     Base class for generating XML configs.
222     """
223     
224     param_match = {}
225
226     def __init__(self, model, parent):
227         self.model = model
228         self.parent = parent
229
230     def database(self):
231         """
232         Return database instance.
233         """
234         return self.model.controllers['connection'].model.database()
235     database = property(database)
236
237     def canHandle(self, params):
238         """
239         Check if this generator can handle a request from freeswitch.
240         """
241         for key, value in self.param_match.iteritems():
242             if params.get(key, None) != value:
243                 return False
244         else:
245             return True
246
247     def baseElements(self):
248         root_elt = etree.Element('document', type='freeswitch/xml')
249         section_elt = etree.SubElement(
250             root_elt, 'section', name=self.param_match['section'])
251         return root_elt, section_elt
252     baseElements = property(baseElements)
253
254     def generateConfig(self, params):
255         return NotImplemented
256
257     @staticmethod
258     def addParams(parent_elt, params):
259         """
260         Create params element based on data passed in a list.
261         """
262         for name, value in params:
263             etree.SubElement(
264                 parent_elt, 'param', name=name, value=str(value))
265             
266         
267 class SofiaConfGenerator(FreeswitchConfigGenerator):
268     """
269     Generates sofia.conf.xml config file.
270     """
271     param_match = {'section': 'configuration', 'key_value': 'sofia.conf'}
272     config_name = 'sofia.conf'
273
274     def generateConfig(self, params):
275         # Get base elements.
276         root_elt, section_elt = self.baseElements
277
278         # Create configuration, settings and profiles elements.
279         configuration_elt = etree.SubElement(
280             section_elt, 'configuration', name=self.config_name,
281             description='%s config' % self.config_name)
282         profiles_elt = etree.SubElement(configuration_elt, 'profiles')
283
284         database = self.database
285         
286         # Create all profiles for current host.
287         profiles_query = database.exec_(
288             '''
289             select id, name, external_sip_ip, external_rtp_ip, sip_ip, rtp_ip,
290             sip_port, accept_blind_registration, authenticate_calls
291             from ipypbxweb_sipprofile where connection_id = %i
292             ''' % self.parent.connection_id)
293         while profiles_query.next():
294             # Create profile element.
295             profile_id, _ok = profiles_query.value(0).toInt()
296             profile_elt = etree.SubElement(
297                 profiles_elt, 'profile',
298                 name=profiles_query.value(1).toString())
299
300             # Create domains for current profile.
301             domains_elt = etree.SubElement(profile_elt, 'domains')
302             domains_query = database.exec_(
303                 'select host_name from ipypbxweb_domain where sip_profile_id = '
304                 '%i' % profile_id)
305             while domains_query.next():
306                 domain_elt = etree.SubElement(
307                     domains_elt, 'domain',
308                     name=domains_query.value(0).toString(), alias='true',
309                     parse='true')
310
311
312             profile_sip_port, _ok = profiles_query.value(6).toInt()
313
314             # Create settings for current profile.
315             settings_elt = etree.SubElement(profile_elt, 'settings')
316             params = (
317                 ('dialplan', 'XML,enum'),
318                 ('ext-sip-ip', profiles_query.value(2).toString()),
319                 ('ext-rtp-ip', profiles_query.value(3).toString()),
320                 ('sip-ip', profiles_query.value(4).toString()),
321                 ('rtp-ip', profiles_query.value(5).toString()),
322                 ('sip-port', profile_sip_port),
323                 ('nonce-ttl', '60'),
324                 ('rtp-timer-name', 'soft'),
325                 ('codec-prefs', 'PCMU@20i'),
326                 ('debug', '1'),
327                 ('rfc2833-pt', '1'),
328                 ('dtmf-duration', '100'),
329                 ('codec-ms', '20'),
330                 ('accept-blind-reg', profiles_query.value(7).toBool()),
331                 ('auth-calls', profiles_query.value(8).toBool()))
332             self.addParams(settings_elt, params)
333
334             # Create gateways for current profile.
335             gateways_elt = etree.SubElement(profile_elt, 'gateways')
336             gateways_query = database.exec_(
337                 '''
338                 select name, username, realm, from_domain, password,
339                 retry_in_seconds, expire_in_seconds, caller_id_in_from_field,
340                 extension
341                 from ipypbxweb_gateway where sip_profile_id = %i
342                 '''  % profile_id)
343             while gateways_query.next():
344                 # Create gateway element.
345                 gateway_elt = etree.SubElement(
346                     gateways_elt, 'gateway', name=gateways_query.value(0).toString())
347                 retry_seconds, _ok = gateways_query.value(5).toInt()
348                 expire_seconds, _ok = gateways_query.value(6).toInt()
349                 params = (
350                     ('username', gateways_query.value(1).toString()),
351                     ('realm', gateways_query.value(2).toString()),
352                     ('from-domain', gateways_query.value(3).toString()),
353                     ('password', gateways_query.value(4).toString()),
354                     ('retry-seconds', retry_seconds),
355                     ('expire-seconds', expire_seconds),
356                     ('caller-id-in-from', gateways_query.value(7).toBool()),
357                     ('extension', gateways_query.value(8).toString()),
358                     # TODO: proxy, register
359                     )
360                 self.addParams(gateway_elt, params)
361
362         return root_elt    
363
364 class DirectoryGenerator(FreeswitchConfigGenerator):
365     """
366     Generates user directory.
367     """
368     param_match = {'section': 'directory'}
369
370     def generateConfig(self, params):
371         #Get base elemenets.
372         root_elt, section_elt = self.baseELements
373
374         database = self.database
375
376         # Find profile id from params.
377         profile_query = database.exec_(
378             '''
379             select id from ipypbxweb_sipprofile
380             where name= '%s' and connection_id = %i limit 1
381             ''' % (params['profile'], self.parent.connection_id))
382
383         _ok = False
384         if profile_query.next():
385             profile_id, _ok = profile_query.value(0).toInt()
386
387         if not _ok:
388             # Matching SIP profile not found.
389             return
390         
391         # List all domains for this profile.        
392         domains_query = database.exec_(
393             '''
394             select id, host_name from ipypbxweb_domain
395             where sip_profile_id = %i
396             ''' % profile_id)
397
398         while domains_query.next():
399             domain_id, _ok = domains_query.value(0).toInt()
400
401             # Create domaim element.
402             domain_elt = etree.SubElement(
403                 section_elt, 'domain', name=domains_query.value(1).toString())
404             
405             # TODO: add domain params section if we need it, i.e.:
406             #<params>
407             #     <param name="dial-string"
408             #            value="{presence_id=${dialed_user}@${dialed_domain}}$\
409             #                   {sofia_contact(${dialed_user}@${dialed_domain})}"/>
410             #</params>            
411
412             # For new we put all users into one group called default.
413             groups_elt = etree.SubElement(domain_elt, 'groups')
414             group_elt = etree.SubElement(groups_elt, 'group', name='default')
415
416             users_elt = etree.SubElement(group_elt, 'users')
417
418             users_query = database.exec_(
419                 '''
420                 select user_id, password from ipypbxweb_endpoint
421                 where domain_id = %i
422                 ''' % domain_id)
423
424             # Create user entries for all endpoints for this domain.
425             while users_query.next():
426                 user_elt = etree.SubElement(
427                     users_elt, 'user', id=users_query.value(0).toString())
428
429                 # Specify endpoint password.
430                 params = (
431                     ('password', users_query.value(1).toString()),
432                     )
433                 self.addParams(user_elt, params)
434
435         return root_elt