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=None):
27 super(FreeswitchConfigServer, self).__init__(parent)
31 self.is_running = False
33 self.httpRequestParser = HttpRequestParser()
35 def setSocketData(self, host, port):
37 Set host and port for socket to listen on.
39 If the settings differ from previous values, server gets restarted.
41 # Check if restart is needed before new settings are applied.
42 needs_restart = (host, port) != (self.host, self.port)
48 # Restart server if necessary.
50 print 'restartin', self.host, self.port
53 def startServer(self):
55 Start listening on our socket.
57 if not self.is_running:
58 if self.host and self.port:
59 self.newConnection.connect(self.clientConnecting)
60 self.listen(QtNetwork.QHostAddress(self.host), self.port)
61 self.is_running = True
65 Stop listening on our socket.
69 self.is_running = False
71 def restartServer(self):
78 def clientConnecting(self):
80 Handle client connection.
82 if self.hasPendingConnections():
83 self.socket = self.nextPendingConnection()
84 self.socket.readyRead.connect(self.receiveData)
86 def receiveData(self):
87 # TODO: read in chunks.
88 for line in str(self.socket.readAll()).split('\r\n'):
89 self.httpRequestParser.handle(line)
92 class HttpParseError(Exception):
94 Error parsing HTTP request.
98 class HttpRequestParser(object):
100 A simple state machine for parsing HTTP requests.
102 HTTP_NONE, HTTP_REQUEST, HTTP_HEADERS, HTTP_EMPTY, HTTP_MESSAGE, \
104 HTTP_STATES = ['NONE', 'REQUEST', 'HEADERS', 'EMPTY', 'MESSAGE', 'DONE']
107 super(HttpRequestParser, self).__init__()
112 Reset parser to initial state.
114 # Initial values for request data.
116 self.request_path = None
117 self.http_version = None
122 self.state = self.HTTP_NONE
124 def handle(self, line):
126 Dispatch line to current state handler.
128 for state in self.HTTP_STATES:
129 if getattr(self, 'HTTP_%s' % state) == self.state:
130 getattr(self, 'handle%s' % state.title())(line)
133 raise HttpParseError('Unknown HTTP state')
135 def handleNone(self, line):
137 Pass line to next state.
142 def handleRequest(self, line):
144 Retrieve HTTP method, request path and HTTP version from request.
146 self.method, self.request_path, self.http_version = line.split(' ')
149 def handleHeaders(self, line):
151 Parse headers while not found an empty line.
154 key, value = line.split(': ')
155 self.headers[key] = value
160 def handleEmpty(self, line):
162 Empty line separator is found - proceed to next state.
166 def handleMessage(self, line):
168 Append to message body.
170 self.data = dict(pair.split('=', 2) for pair in line.split('&'))
172 for k, v in self.data.items():
176 for generator in self.generators:
177 if generator.canHandle(self.headers):
179 return generator.generateConfig(self.headers)
183 class FreeswitchConfigGenerator(object):
185 Base class for generating XML configs.
191 def __init__(self, model):
194 def canHandle(self, params):
195 for key, value in self.param_match.iteritems():
196 if params.get(key, None) != value:
201 def baseElements(self):
202 root_elt = etree.Element('document')
203 section_elt = etree.SubElement(
204 root_elt, 'section', name=self.section_name)
205 return root_elt, section_elt
206 baseElements = property(baseElements)
208 def generateConfig(self, params):
209 return NotImplemented
211 def addParams(parent_elt, params):
212 for name, value in params:
213 etree.SubElement(parent_elt, 'param', name=name, value=value)
216 class SofiaConfGenerator(FreeswitchConfigGenerator):
218 Generates sofia.conf.xml config file.
220 param_match = {'section': 'configuration', 'key_value': 'sofia.conf'}
221 section_name = 'configuration'
222 config_name = 'sofia.conf'
224 def generateConfig(self, params):
226 root_elt, section_elt = self.baseElements
228 # Create configuration, settings and profiles elements.
229 configuration_elt = etree.SubElement(
230 section_elt, 'configuration', name=self.config_name,
231 description='%s config' % self.config_name)
232 settings_elt = etree.SubElement(configuration_elt, 'settings')
233 profiles_elt = etree.SubElement(self.settings_elt, 'profiles')
235 # Create all profiles for current host.
236 for profile in self.parent.get_profiles():
237 profile_elt = etree.SubElement(profiles_elt, 'profile')
239 # Create domains for current profile.
240 domains_elt = etree.SubElement(profile_elt, 'domains')
241 for domain in self.parent.get_domains_for_profile(profile):
242 domain_elt = etree.SubElement(
243 domains_elt, 'domain', name=domain.host_name,
244 alias='true', parse='true')
246 # Create settings for current profile.
247 settings_elt = etree.SubElement(profile_elt, 'settings')
249 ('dialplan', 'XML,enum'),
250 ('ext-sip-ip', profile.ext_sip_ip),
251 ('ext-rtp-ip', profile.ext_rtp_ip),
252 ('sip-ip', profile.sip_ip),
253 ('rtp-ip', profile.rtp_ip),
254 ('sip-port', profile.sip_port),
256 ('rtp-timer-name', 'soft'),
257 ('codec-prefs', 'PCMU@20i'),
260 ('dtmf-duration', '100'),
262 ('accept-blind-reg', profile.accept_blind_registration),
263 ('auth-calls', profile.authenticate_calls))
264 self.add_params(settings_elt, params)
266 # Create gateways for current profile.
267 gateways_elt = etree.SubElement(profile, 'gateways')
268 for gateway in self.parent.get_gateways_for_profile(profile):
269 gateway_elt = etree.SubElement(gateways_elt, 'gateway', name=gateway.name)
271 ('username', gateway.username),
272 ('realm', gateway.realm),
273 ('from-domain', gateway.from_domain),
274 ('password', gateway.password),
275 ('retry-seconds', gateway.retry_seconds),
276 ('expire-seconds', gateway.expire_seconds),
277 ('caller-id-in-from', gateway.caller_id_in_from),
278 ('extension', gateway.extension),
279 # TODO: proxy, register
280 ('expire-seconds', gateway.expire_seconds),
281 ('retry-seconds', gateway.retry_seconds))
282 self.add_params(gateway_elt, params)