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.
26 def __init__(self, parent):
27 super(FreeswitchConfigServer, self).__init__(parent)
31 self.is_running = False
33 GenClass(self.parent().model) for GenClass in (
36 self.httpRequestParser = HttpRequestParser(self)
38 def setSocketData(self, host, port):
40 Set host and port for socket to listen on.
42 If the settings differ from previous values, server gets restarted.
44 # Check if restart is needed before new settings are applied.
45 needs_restart = (host, port) != (self.host, self.port)
51 # Restart server if necessary.
55 def startServer(self):
57 Start listening on our socket.
59 if not self.is_running:
60 if self.host and self.port:
61 self.newConnection.connect(self.clientConnecting)
62 self.listen(QtNetwork.QHostAddress(self.host), self.port)
63 self.is_running = True
67 Stop listening on our socket.
71 self.is_running = False
73 def restartServer(self):
80 def clientConnecting(self):
82 Handle client connection.
84 if self.hasPendingConnections():
85 self.socket = self.nextPendingConnection()
86 self.socket.readyRead.connect(self.receiveData)
88 def receiveData(self):
89 # TODO: read in chunks.
90 for line in str(self.socket.readAll()).split('\r\n'):
91 self.httpRequestParser.handle(line)
94 class HttpParseError(Exception):
96 Error parsing HTTP request.
100 class HttpRequestParser(object):
102 A simple state machine for parsing HTTP requests.
104 HTTP_NONE, HTTP_REQUEST, HTTP_HEADERS, HTTP_EMPTY, HTTP_MESSAGE, \
106 HTTP_STATES = ['NONE', 'REQUEST', 'HEADERS', 'EMPTY', 'MESSAGE', 'DONE']
108 def __init__(self, parent):
114 Reset parser to initial state.
116 # Initial values for request data.
118 self.request_path = None
119 self.http_version = None
124 self.state = self.HTTP_NONE
126 def handle(self, line):
128 Dispatch line to current state handler.
130 for state in self.HTTP_STATES:
131 if getattr(self, 'HTTP_%s' % state) == self.state:
132 getattr(self, 'handle%s' % state.title())(line)
135 raise HttpParseError('Unknown HTTP state')
137 def handleNone(self, line):
139 Pass line to next state.
144 def handleRequest(self, line):
146 Retrieve HTTP method, request path and HTTP version from request.
148 self.method, self.request_path, self.http_version = line.split(' ')
151 def handleHeaders(self, line):
153 Parse headers while not found an empty line.
156 key, value = line.split(': ')
157 self.headers[key] = value
162 def handleEmpty(self, line):
164 Empty line separator is found - proceed to next state.
168 def handleMessage(self, line):
170 Append to message body.
172 self.data = dict(pair.split('=', 2) for pair in line.split('&'))
174 for k, v in self.data.items():
178 for generator in self.parent.generators:
179 if generator.canHandle(self.headers):
181 return generator.generateConfig(self.headers)
185 class FreeswitchConfigGenerator(object):
187 Base class for generating XML configs.
193 def __init__(self, model):
196 def canHandle(self, params):
197 for key, value in self.param_match.iteritems():
198 if params.get(key, None) != value:
203 def baseElements(self):
204 root_elt = etree.Element('document')
205 section_elt = etree.SubElement(
206 root_elt, 'section', name=self.section_name)
207 return root_elt, section_elt
208 baseElements = property(baseElements)
210 def generateConfig(self, params):
211 return NotImplemented
213 def addParams(parent_elt, params):
214 for name, value in params:
215 etree.SubElement(parent_elt, 'param', name=name, value=value)
218 class SofiaConfGenerator(FreeswitchConfigGenerator):
220 Generates sofia.conf.xml config file.
222 param_match = {'section': 'configuration', 'key_value': 'sofia.conf'}
223 section_name = 'configuration'
224 config_name = 'sofia.conf'
226 def generateConfig(self, params):
228 root_elt, section_elt = self.baseElements
230 # Create configuration, settings and profiles elements.
231 configuration_elt = etree.SubElement(
232 section_elt, 'configuration', name=self.config_name,
233 description='%s config' % self.config_name)
234 settings_elt = etree.SubElement(configuration_elt, 'settings')
235 profiles_elt = etree.SubElement(self.settings_elt, 'profiles')
237 # Create all profiles for current host.
238 for profile in self.parent.get_profiles():
239 profile_elt = etree.SubElement(profiles_elt, 'profile')
241 # Create domains for current profile.
242 domains_elt = etree.SubElement(profile_elt, 'domains')
243 for domain in self.parent.get_domains_for_profile(profile):
244 domain_elt = etree.SubElement(
245 domains_elt, 'domain', name=domain.host_name,
246 alias='true', parse='true')
248 # Create settings for current profile.
249 settings_elt = etree.SubElement(profile_elt, 'settings')
251 ('dialplan', 'XML,enum'),
252 ('ext-sip-ip', profile.ext_sip_ip),
253 ('ext-rtp-ip', profile.ext_rtp_ip),
254 ('sip-ip', profile.sip_ip),
255 ('rtp-ip', profile.rtp_ip),
256 ('sip-port', profile.sip_port),
258 ('rtp-timer-name', 'soft'),
259 ('codec-prefs', 'PCMU@20i'),
262 ('dtmf-duration', '100'),
264 ('accept-blind-reg', profile.accept_blind_registration),
265 ('auth-calls', profile.authenticate_calls))
266 self.add_params(settings_elt, params)
268 # Create gateways for current profile.
269 gateways_elt = etree.SubElement(profile, 'gateways')
270 for gateway in self.parent.get_gateways_for_profile(profile):
271 gateway_elt = etree.SubElement(gateways_elt, 'gateway', name=gateway.name)
273 ('username', gateway.username),
274 ('realm', gateway.realm),
275 ('from-domain', gateway.from_domain),
276 ('password', gateway.password),
277 ('retry-seconds', gateway.retry_seconds),
278 ('expire-seconds', gateway.expire_seconds),
279 ('caller-id-in-from', gateway.caller_id_in_from),
280 ('extension', gateway.extension),
281 # TODO: proxy, register
282 ('expire-seconds', gateway.expire_seconds),
283 ('retry-seconds', gateway.retry_seconds))
284 self.add_params(gateway_elt, params)