Minor changes required for running 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, database, parent):
41         super(FreeswitchConfigServer, self).__init__(parent)
42
43         self.host = None
44         self.port = None
45         self.connection_id = None
46         self.is_running = False
47         self.generators = [
48             GenClass(database, self) for GenClass in (
49                 SofiaConfGenerator,)]
50         
51         self.httpRequestParser = HttpRequestParser()
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             self.httpRequestParser.handle(line)
110
111         for generator in self.generators:
112             if generator.canHandle(self.httpRequestParser.data):
113                 self.state += 1
114                 self.result = etree.tostring(generator.generateConfig(
115                     self.httpRequestParser.headers))
116                 break
117
118         response = self.httpRequestParser.result or self.configNotFound
119         http_response = self.responseTemplate % (len(response), response)
120         self.socket.write(http_response)
121         self.httpRequestParser.reset()        
122         self.socket.close()
123
124
125 class HttpParseError(Exception):
126     """
127     Error parsing HTTP request.
128     """
129
130
131 class HttpRequestParser(object):
132     """
133     A simple state machine for parsing HTTP requests.
134     """
135     HTTP_NONE, HTTP_REQUEST, HTTP_HEADERS, HTTP_EMPTY, HTTP_BODY, HTTP_DONE = \
136         range(6)
137     HTTP_STATES = ['NONE', 'REQUEST', 'HEADERS', 'EMPTY', 'BODY', 'DONE']
138     
139     def __init__(self):
140         self.reset()
141
142     def reset(self):
143         """
144         Reset parser to initial state.
145         """
146         # Initial values for request data.
147         self.method = None
148         self.request_path = None
149         self.http_version = None
150         self.headers = {}
151         self.data = {}
152         self.result = None
153         
154         # Set initial state.
155         self.state = self.HTTP_NONE        
156
157     def handle(self, line):
158         """
159         Dispatch line to current state handler.
160         """
161         for state in self.HTTP_STATES:
162             if getattr(self, 'HTTP_%s' % state) == self.state:
163                 getattr(self, 'handle%s' % state.title())(line)
164                 break
165         else:
166             raise HttpParseError('Unknown HTTP state')
167                 
168     def handleNone(self, line):
169         """
170         Pass line to next state.
171         """
172         self.state += 1
173         self.handle(line)
174
175     def handleRequest(self, line):
176         """
177         Retrieve HTTP method, request path and HTTP version from request.
178         """
179         try:
180             self.method, self.request_path, self.http_version = line.split(' ')
181             self.state += 1
182         except ValueError:
183             pass
184
185     def handleHeaders(self, line):
186         """
187         Parse headers while not found an empty line.
188         """
189         if line:
190             key, value = line.split(': ')
191             self.headers[key] = value
192         else:
193             self.state += 1
194             self.handle(line)
195
196     def handleEmpty(self, line):
197         """
198         Empty line separator is found - proceed to next state.
199         """
200         self.state += 1
201
202     def handleBody(self, line):
203         """
204         Append to message body.
205         """
206         if self.method != 'POST':
207             raise HttpParseError('Only POST request are supported')
208             
209         self.data = dict(pair.split('=', 2) for pair in line.split('&'))
210
211     def handleDone(self, line):
212         raise HttpParseError("Can't read past request end")
213     
214
215 class FreeswitchConfigGenerator(object):
216     """
217     Base class for generating XML configs.
218     """
219     
220     param_match = {}
221
222     def __init__(self, database, parent):
223         self.database = database
224         self.parent = parent
225
226 #    def database(self):
227 #        """
228 #        Return database instance.
229 #        """
230 #        return self.model.controllers['connection'].model.database()
231
232     def canHandle(self, params):
233         """
234         Check if this generator can handle a request from freeswitch.
235         """
236         for key, value in self.param_match.iteritems():
237             if params.get(key, None) != value:
238                 return False
239         else:
240             return True
241
242     def baseElements(self):
243         root_elt = etree.Element('document', type='freeswitch/xml')
244         section_elt = etree.SubElement(
245             root_elt, 'section', name=self.param_match['section'])
246         return root_elt, section_elt
247     baseElements = property(baseElements)
248
249     def generateConfig(self, params):
250         return NotImplemented
251
252     @staticmethod
253     def addParams(parent_elt, params):
254         """
255         Create params element based on data passed in a list.
256         """
257         for name, value in params:
258             etree.SubElement(
259                 parent_elt, 'param', name=name, value=str(value))
260             
261         
262 class SofiaConfGenerator(FreeswitchConfigGenerator):
263     """
264     Generates sofia.conf.xml config file.
265     """
266     param_match = {'section': 'configuration', 'key_value': 'sofia.conf'}
267     config_name = 'sofia.conf'
268
269     def generateConfig(self, params):
270         # Get base elements.
271         root_elt, section_elt = self.baseElements
272
273         # Create configuration, settings and profiles elements.
274         configuration_elt = etree.SubElement(
275             section_elt, 'configuration', name=self.config_name,
276             description='%s config' % self.config_name)
277         profiles_elt = etree.SubElement(configuration_elt, 'profiles')
278
279         database = self.database
280         
281         # Create all profiles for current host.
282         profiles_query = database.exec_(
283             '''
284             select id, name, external_sip_ip, external_rtp_ip, sip_ip, rtp_ip,
285             sip_port, accept_blind_registration, authenticate_calls
286             from ipypbxweb_sipprofile where connection_id = %i
287             ''' % self.parent.connection_id)
288         while profiles_query.next():
289             # Create profile element.
290             profile_id, _ok = profiles_query.value(0).toInt()
291             profile_elt = etree.SubElement(
292                 profiles_elt, 'profile',
293                 name=profiles_query.value(1).toString())
294
295             # Create domains for current profile.
296             domains_elt = etree.SubElement(profile_elt, 'domains')
297             domains_query = database.exec_(
298                 'select host_name from ipypbxweb_domain where sip_profile_id = '
299                 '%i' % profile_id)
300             while domains_query.next():
301                 domain_elt = etree.SubElement(
302                     domains_elt, 'domain',
303                     name=domains_query.value(0).toString(), alias='true',
304                     parse='true')
305
306
307             profile_sip_port, _ok = profiles_query.value(6).toInt()
308
309             # Create settings for current profile.
310             settings_elt = etree.SubElement(profile_elt, 'settings')
311             params = (
312                 ('dialplan', 'XML,enum'),
313                 ('ext-sip-ip', profiles_query.value(2).toString()),
314                 ('ext-rtp-ip', profiles_query.value(3).toString()),
315                 ('sip-ip', profiles_query.value(4).toString()),
316                 ('rtp-ip', profiles_query.value(5).toString()),
317                 ('sip-port', profile_sip_port),
318                 ('nonce-ttl', '60'),
319                 ('rtp-timer-name', 'soft'),
320                 ('codec-prefs', 'PCMU@20i'),
321                 ('debug', '1'),
322                 ('rfc2833-pt', '1'),
323                 ('dtmf-duration', '100'),
324                 ('codec-ms', '20'),
325                 ('accept-blind-reg', profiles_query.value(7).toBool()),
326                 ('auth-calls', profiles_query.value(8).toBool()))
327             self.addParams(settings_elt, params)
328
329             # Create gateways for current profile.
330             gateways_elt = etree.SubElement(profile_elt, 'gateways')
331             gateways_query = database.exec_(
332                 '''
333                 select name, username, realm, from_domain, password,
334                 retry_in_seconds, expire_in_seconds, caller_id_in_from_field,
335                 extension
336                 from ipypbxweb_gateway where sip_profile_id = %i
337                 '''  % profile_id)
338             while gateways_query.next():
339                 # Create gateway element.
340                 gateway_elt = etree.SubElement(
341                     gateways_elt, 'gateway', name=gateways_query.value(0).toString())
342                 retry_seconds, _ok = gateways_query.value(5).toInt()
343                 expire_seconds, _ok = gateways_query.value(6).toInt()
344                 params = (
345                     ('username', gateways_query.value(1).toString()),
346                     ('realm', gateways_query.value(2).toString()),
347                     ('from-domain', gateways_query.value(3).toString()),
348                     ('password', gateways_query.value(4).toString()),
349                     ('retry-seconds', retry_seconds),
350                     ('expire-seconds', expire_seconds),
351                     ('caller-id-in-from', gateways_query.value(7).toBool()),
352                     ('extension', gateways_query.value(8).toString()),
353                     # TODO: proxy, register
354                     )
355                 self.addParams(gateway_elt, params)
356
357         return root_elt    
358
359 class DirectoryGenerator(FreeswitchConfigGenerator):
360     """
361     Generates user directory.
362     """
363     param_match = {'section': 'directory'}
364
365     def generateConfig(self, params):
366         #Get base elemenets.
367         root_elt, section_elt = self.baseELements
368
369         database = self.database
370
371         # Find profile id from params.
372         profile_query = database.exec_(
373             '''
374             select id from ipypbxweb_sipprofile
375             where name= '%s' and connection_id = %i limit 1
376             ''' % (params['profile'], self.parent.connection_id))
377
378         _ok = False
379         if profile_query.next():
380             profile_id, _ok = profile_query.value(0).toInt()
381
382         if not _ok:
383             # Matching SIP profile not found.
384             return
385         
386         # List all domains for this profile.        
387         domains_query = database.exec_(
388             '''
389             select id, host_name from ipypbxweb_domain
390             where sip_profile_id = %i
391             ''' % profile_id)
392
393         while domains_query.next():
394             domain_id, _ok = domains_query.value(0).toInt()
395
396             # Create domaim element.
397             domain_elt = etree.SubElement(
398                 section_elt, 'domain', name=domains_query.value(1).toString())
399             
400             # TODO: add domain params section if we need it, i.e.:
401             #<params>
402             #     <param name="dial-string"
403             #            value="{presence_id=${dialed_user}@${dialed_domain}}$\
404             #                   {sofia_contact(${dialed_user}@${dialed_domain})}"/>
405             #</params>            
406
407             # For new we put all users into one group called default.
408             groups_elt = etree.SubElement(domain_elt, 'groups')
409             group_elt = etree.SubElement(groups_elt, 'group', name='default')
410
411             users_elt = etree.SubElement(group_elt, 'users')
412
413             users_query = database.exec_(
414                 '''
415                 select user_id, password from ipypbxweb_endpoint
416                 where domain_id = %i
417                 ''' % domain_id)
418
419             # Create user entries for all endpoints for this domain.
420             while users_query.next():
421                 user_elt = etree.SubElement(
422                     users_elt, 'user', id=users_query.value(0).toString())
423
424                 # Specify endpoint password.
425                 params = (
426                     ('password', users_query.value(1).toString()),
427                     )
428                 self.addParams(user_elt, params)
429
430         return root_elt
431
432
433 class DialplanGenerator(FreeswitchConfigGenerator):
434     """
435     Generates XML dialplans.
436     """
437
438     param_match = {'section': 'dialplan'}
439