Sofia.conf generation works
[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 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         self.httpRequestParser.reset()        
116         self.socket.close()
117
118 class HttpParseError(Exception):
119     """
120     Error parsing HTTP request.
121     """
122
123
124 class HttpRequestParser(object):
125     """
126     A simple state machine for parsing HTTP requests.
127     """
128     HTTP_NONE, HTTP_REQUEST, HTTP_HEADERS, HTTP_EMPTY, HTTP_MESSAGE, \
129         HTTP_DONE = range(6)
130     HTTP_STATES = ['NONE', 'REQUEST', 'HEADERS', 'EMPTY', 'MESSAGE', 'DONE']
131     
132     def __init__(self, parent):
133         self.parent = parent
134         self.reset()
135
136     def reset(self):
137         """
138         Reset parser to initial state.
139         """
140         # Initial values for request data.
141         self.method = None
142         self.request_path = None
143         self.http_version = None
144         self.headers = {}
145         self.data = {}
146         self.result = None
147         
148         # Set initial state.
149         self.state = self.HTTP_NONE        
150
151     def handle(self, line):
152         """
153         Dispatch line to current state handler.
154         """
155         for state in self.HTTP_STATES:
156             if getattr(self, 'HTTP_%s' % state) == self.state:
157                 getattr(self, 'handle%s' % state.title())(line)
158                 break
159         else:
160             raise HttpParseError('Unknown HTTP state')
161                 
162     def handleNone(self, line):
163         """
164         Pass line to next state.
165         """
166         self.state += 1
167         self.handle(line)
168
169     def handleRequest(self, line):
170         """
171         Retrieve HTTP method, request path and HTTP version from request.
172         """
173         self.method, self.request_path, self.http_version = line.split(' ')
174         self.state += 1
175
176     def handleHeaders(self, line):
177         """
178         Parse headers while not found an empty line.
179         """
180         if line:
181             key, value = line.split(': ')
182             self.headers[key] = value
183         else:
184             self.state += 1
185             self.handle(line)
186
187     def handleEmpty(self, line):
188         """
189         Empty line separator is found - proceed to next state.
190         """
191         self.state += 1
192
193     def handleMessage(self, line):
194         """
195         Append to message body.
196         """
197         self.data = dict(pair.split('=', 2) for pair in line.split('&'))
198
199         #for k, v in self.data.items():
200         #    print k, '=>', v
201         #print
202
203         for generator in self.parent.generators:
204             if generator.canHandle(self.data):
205                 self.state += 1
206                 self.result = etree.tostring(generator.generateConfig(
207                     self.headers))
208                 break
209
210
211 class FreeswitchConfigGenerator(object):
212     """
213     Base class for generating XML configs.
214     """
215     
216     param_match = {}
217     section_name = None
218
219     def __init__(self, model, parent):
220         self.model = model
221         self.parent = parent
222
223     def canHandle(self, params):
224         for key, value in self.param_match.iteritems():
225             if params.get(key, None) != value:
226                 return False
227         else:
228             return True
229
230     def baseElements(self):
231         root_elt = etree.Element('document')
232         section_elt = etree.SubElement(
233             root_elt, 'section', name=self.section_name)
234         return root_elt, section_elt
235     baseElements = property(baseElements)
236
237     def generateConfig(self, params):
238         return NotImplemented
239
240     @staticmethod
241     def addParams(parent_elt, params):
242         for name, value in params:
243             etree.SubElement(
244                 parent_elt, 'param', name=name, value=str(value))
245             
246         
247 class SofiaConfGenerator(FreeswitchConfigGenerator):
248     """
249     Generates sofia.conf.xml config file.
250     """
251     param_match = {'section': 'configuration', 'key_value': 'sofia.conf'}
252     section_name = 'configuration'
253     config_name = 'sofia.conf'
254
255     def generateConfig(self, params):
256         # Get base elements.
257         root_elt, section_elt = self.baseElements
258
259         # Create configuration, settings and profiles elements.
260         configuration_elt = etree.SubElement(
261             section_elt, 'configuration', name=self.config_name,
262             description='%s config' % self.config_name)
263         settings_elt = etree.SubElement(configuration_elt, 'settings')
264         profiles_elt = etree.SubElement(settings_elt, 'profiles')
265
266         database = self.model.controllers['connection'].model.database()
267         
268         # Create all profiles for current host.
269         profiles_query = database.exec_(
270             '''
271             select id, name, external_sip_ip, external_rtp_ip, sip_ip, rtp_ip,
272             sip_port, accept_blind_registration, authenticate_calls
273             from ipypbxweb_sipprofile where connection_id = %i
274             ''' % self.parent.connection_id)
275         while profiles_query.next():
276             profile_id, _ok = profiles_query.value(0).toInt()
277             profile_elt = etree.SubElement(
278                 profiles_elt, 'profile',
279                 name=profiles_query.value(1).toString())
280
281             # Create domains for current profile.
282             domains_elt = etree.SubElement(profile_elt, 'domains')
283             domains_query = database.exec_(
284                 'select host_name from ipypbxweb_domain where profile_id = '
285                 '%i' % profile_id)
286             while domains_query.next():
287                 domain_elt = etree.SubElement(
288                     domains_elt, 'domain', name=domains_quey.value(0),
289                     alias='true', parse='true')
290
291             profile_sip_port, _ok = profiles_query.value(6).toInt()
292
293             # Create settings for current profile.
294             settings_elt = etree.SubElement(profile_elt, 'settings')
295             params = (
296                 ('dialplan', 'XML,enum'),
297                 ('ext-sip-ip', profiles_query.value(2).toString()),
298                 ('ext-rtp-ip', profiles_query.value(3).toString()),
299                 ('sip-ip', profiles_query.value(4).toString()),
300                 ('rtp-ip', profiles_query.value(5).toString()),
301                 ('sip-port', profile_sip_port),
302                 ('nonce-ttl', '60'),
303                 ('rtp-timer-name', 'soft'),
304                 ('codec-prefs', 'PCMU@20i'),
305                 ('debug', '1'),
306                 ('rfc2833-pt', '1'),
307                 ('dtmf-duration', '100'),
308                 ('codec-ms', '20'),
309                 ('accept-blind-reg', profiles_query.value(7).toBool()),
310                 ('auth-calls', profiles_query.value(8).toBool()))
311             self.addParams(settings_elt, params)
312
313             # Create gateways for current profile.
314             gateways_elt = etree.SubElement(profile_elt, 'gateways')
315             gateways_query = database.exec_(
316                 '''
317                 select name, username, realm, from_domain, password,
318                 retry_seconds, expire_seconds, caller_id_in_from, extension
319                 from ipypbxweb_gateway where sipprofile_id = %i
320                 '''  % profile_id)
321             while gateways_query.next():
322                 gateway_elt = etree.SubElement(
323                     gateways_elt, 'gateway', name=gateways_query.value(0).toString())
324                 retry_seconds, _ok = gateways_query.value(5).toInt()
325                 expire_seconds, _ok = gateways_query.value(6).toInt()
326                 params = (
327                     ('username', gateways_query.value(1).toString()),
328                     ('realm', gateways_query.value(2).toString()),
329                     ('from-domain', gateways_query.value(3).toString()),
330                     ('password', gateways_query.value(4).toString()),
331                     ('retry-seconds', retry_seconds),
332                     ('expire-seconds', expire_seconds),
333                     ('caller-id-in-from', gateways_query.value(7).toBool()),
334                     ('extension', gateways_query.value(8).toString()),
335                     # TODO: proxy, register
336                     )
337                 self.addParams(gateway_elt, params)
338
339         return root_elt