1 # Copyright (c) Stas Shtin, 2010
3 # This file is part of IPyPBX.
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.
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.
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/>.
18 import xml.etree.ElementTree as etree
19 from PyQt4 import QtCore, QtNetwork
22 class FreeswitchConfigServer(QtNetwork.QTcpServer):
24 TCP server that receives config requests from freeswitch.
27 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
28 <document type="freeswitch/xml">
29 <section name="result">
30 <result status="not found" />
34 responseTemplate = '''HTTP/1.1 200 OK
35 Content-Type: text/xml; charset=utf-8
40 def __init__(self, window):
41 super(FreeswitchConfigServer, self).__init__(window)
45 self.connection_id = None
46 self.is_running = False
48 GenClass(window, self) for GenClass in (
51 self.httpRequestParser = HttpRequestParser(self)
53 def setSocketData(self, host, port, connection_id):
55 Set host and port for socket to listen on.
57 If the settings differ from previous values, server gets restarted.
59 # Check if restart is needed before new settings are applied.
61 (host, port) != (self.host, self.port)) and connection_id
67 self.connection_id = connection_id
69 # Restart server if necessary.
73 def startServer(self):
75 Start listening on our socket.
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
85 Stop listening on our socket.
89 self.is_running = False
91 def restartServer(self):
98 def clientConnecting(self):
100 Handle client connection.
102 if self.hasPendingConnections():
103 self.socket = self.nextPendingConnection()
104 self.socket.readyRead.connect(self.receiveData)
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)
112 response = self.httpRequestParser.result or self.configNotFound
113 http_response = self.responseTemplate % (len(response), response)
114 self.socket.write(http_response)
118 self.httpRequestParser.reset()
121 class HttpParseError(Exception):
123 Error parsing HTTP request.
127 class HttpRequestParser(object):
129 A simple state machine for parsing HTTP requests.
131 HTTP_NONE, HTTP_REQUEST, HTTP_HEADERS, HTTP_EMPTY, HTTP_MESSAGE, \
133 HTTP_STATES = ['NONE', 'REQUEST', 'HEADERS', 'EMPTY', 'MESSAGE', 'DONE']
135 def __init__(self, parent):
142 Reset parser to initial state.
145 # Initial values for request data.
147 self.request_path = None
148 self.http_version = None
154 self.state = self.HTTP_NONE
156 def handle(self, line):
158 Dispatch line to current state handler.
160 for state in self.HTTP_STATES:
161 if getattr(self, 'HTTP_%s' % state) == self.state:
162 getattr(self, 'handle%s' % state.title())(line)
165 raise HttpParseError('Unknown HTTP state')
167 def handleNone(self, line):
169 Pass line to next state.
174 def handleRequest(self, line):
176 Retrieve HTTP method, request path and HTTP version from request.
179 self.method, self.request_path, self.http_version = line.split(' ')
184 def handleHeaders(self, line):
186 Parse headers while not found an empty line.
189 key, value = line.split(': ')
190 self.headers[key] = value
195 def handleEmpty(self, line):
197 Empty line separator is found - proceed to next state.
201 def handleMessage(self, line):
203 Append to message body.
205 self.data = dict(pair.split('=', 2) for pair in line.split('&'))
207 #for k, v in self.data.items():
211 for generator in self.parent.generators:
212 if generator.canHandle(self.data):
214 self.result = etree.tostring(generator.generateConfig(
219 class FreeswitchConfigGenerator(object):
221 Base class for generating XML configs.
226 def __init__(self, model, parent):
232 Return database instance.
234 return self.model.controllers['connection'].model.database()
235 database = property(database)
237 def canHandle(self, params):
238 for key, value in self.param_match.iteritems():
239 if params.get(key, None) != value:
244 def baseElements(self):
245 root_elt = etree.Element('document', type='freeswitch/xml')
246 section_elt = etree.SubElement(
247 root_elt, 'section', name=self.param_match['section'])
248 return root_elt, section_elt
249 baseElements = property(baseElements)
251 def generateConfig(self, params):
252 return NotImplemented
255 def addParams(parent_elt, params):
256 for name, value in params:
258 parent_elt, 'param', name=name, value=str(value))
261 class SofiaConfGenerator(FreeswitchConfigGenerator):
263 Generates sofia.conf.xml config file.
265 param_match = {'section': 'configuration', 'key_value': 'sofia.conf'}
266 config_name = 'sofia.conf'
268 def generateConfig(self, params):
270 root_elt, section_elt = self.baseElements
272 # Create configuration, settings and profiles elements.
273 configuration_elt = etree.SubElement(
274 section_elt, 'configuration', name=self.config_name,
275 description='%s config' % self.config_name)
276 profiles_elt = etree.SubElement(configuration_elt, 'profiles')
278 database = self.database
280 # Create all profiles for current host.
281 profiles_query = database.exec_(
283 select id, name, external_sip_ip, external_rtp_ip, sip_ip, rtp_ip,
284 sip_port, accept_blind_registration, authenticate_calls
285 from ipypbxweb_sipprofile where connection_id = %i
286 ''' % self.parent.connection_id)
287 while profiles_query.next():
288 profile_id, _ok = profiles_query.value(0).toInt()
289 profile_elt = etree.SubElement(
290 profiles_elt, 'profile',
291 name=profiles_query.value(1).toString())
293 # Create domains for current profile.
294 domains_elt = etree.SubElement(profile_elt, 'domains')
295 domains_query = database.exec_(
296 'select host_name from ipypbxweb_domain where sip_profile_id = '
298 while domains_query.next():
299 domain_elt = etree.SubElement(
300 domains_elt, 'domain',
301 name=domains_query.value(0).toString(), alias='true',
305 profile_sip_port, _ok = profiles_query.value(6).toInt()
307 # Create settings for current profile.
308 settings_elt = etree.SubElement(profile_elt, 'settings')
310 ('dialplan', 'XML,enum'),
311 ('ext-sip-ip', profiles_query.value(2).toString()),
312 ('ext-rtp-ip', profiles_query.value(3).toString()),
313 ('sip-ip', profiles_query.value(4).toString()),
314 ('rtp-ip', profiles_query.value(5).toString()),
315 ('sip-port', profile_sip_port),
317 ('rtp-timer-name', 'soft'),
318 ('codec-prefs', 'PCMU@20i'),
321 ('dtmf-duration', '100'),
323 ('accept-blind-reg', profiles_query.value(7).toBool()),
324 ('auth-calls', profiles_query.value(8).toBool()))
325 self.addParams(settings_elt, params)
327 # Create gateways for current profile.
328 gateways_elt = etree.SubElement(profile_elt, 'gateways')
329 gateways_query = database.exec_(
331 select name, username, realm, from_domain, password,
332 retry_in_seconds, expire_in_seconds, caller_id_in_from_field,
334 from ipypbxweb_gateway where sip_profile_id = %i
336 while gateways_query.next():
337 gateway_elt = etree.SubElement(
338 gateways_elt, 'gateway', name=gateways_query.value(0).toString())
339 retry_seconds, _ok = gateways_query.value(5).toInt()
340 expire_seconds, _ok = gateways_query.value(6).toInt()
342 ('username', gateways_query.value(1).toString()),
343 ('realm', gateways_query.value(2).toString()),
344 ('from-domain', gateways_query.value(3).toString()),
345 ('password', gateways_query.value(4).toString()),
346 ('retry-seconds', retry_seconds),
347 ('expire-seconds', expire_seconds),
348 ('caller-id-in-from', gateways_query.value(7).toBool()),
349 ('extension', gateways_query.value(8).toString()),
350 # TODO: proxy, register
352 self.addParams(gateway_elt, params)
356 class DirectoryGenerator(FreeswitchConfigGenerator):
358 Generates user directory.
360 param_match = {'section': 'directory'}
362 def generateConfig(self, params):
364 root_elt, section_elt = self.baseELements
366 database = self.database
368 # Find profile id from params.
369 profile_query = database.exec_(
371 select id from ipypbxweb_sipprofile
372 where name= '%s' and connection_id = %i limit 1
373 ''' % (params['profile'], self.parent.connection_id))
376 if profile_query.next():
377 profile_id, _ok = profile_query.value(0).toInt()
380 # Matching SIP profile not found.
383 # List all domains for this profile.
384 domains_query = database.exec_(
386 select id, host_name from ipypbxweb_domain
387 where sip_profile_id = %i
390 while domains_query.next():
391 domain_id, _ok = domains_query.value(0).toInt()
393 # Create domaim element.
394 domain_elt = etree.SubElement(
395 section_elt, 'domain', name=domains_query.value(1).toString())
397 # TODO: add domain params section if we need it, i.e.:
399 # <param name="dial-string"
400 # value="{presence_id=${dialed_user}@${dialed_domain}}$\
401 # {sofia_contact(${dialed_user}@${dialed_domain})}"/>
404 # For new we put all users into one group called default.
405 groups_elt = etree.SubElement(domain_elt, 'groups')
406 group_elt = etree.SubElement(groups_elt, 'group', name='default')
408 users_elt = etree.SubElement(group_elt, 'users')
410 users_query = database.exec_(
412 select user_id, password from ipypbxweb_endpoint
416 # Create user entries for all endpoints for this domain.
417 while users_query.next():
418 user_elt = etree.SubElement(
419 users_elt, 'user', id=users_query.value(0).toString())
421 # Specify endpoint password.
423 ('password', users_query.value(1).toString()),
425 self.addParams(user_elt, params)