Пример #1
0
 def global_tcpip_forward(self, data):
     host_to_bind, port_to_bind = forwarding.unpackGlobal_tcpip_forward(data)
     if port_to_bind != 0:
         # Don't allow the port to bind to be specified
         return 0
     try:
         listener = reactor.listenTCP(port_to_bind, 
                                      forwarding.SSHListenForwardingFactory(self.conn,
                                                                            (host_to_bind, port_to_bind),
                                                                            forwarding.SSHListenServerForwardingChannel))
         # We don't set the 'interface' attribute because we want to listen on 0.0.0.0
         # Same effect as adding GatewayPorts yes to sshd_config
     except CannotListenError:
         return 0
     else:
         timeout = ServerConfig.session_timeout
         if timeout != 0:
             log.msg('Session timeout set to %d seconds' % timeout)
             timer = reactor.callLater(timeout, self._terminate_session)
         else:
             log.msg('Session duration is unlimited')
             timer = None
         port_to_bind = listener.getHost().port
         self.listeners[(host_to_bind, port_to_bind)] = Listener(listener, timer)
         return 1, struct.pack('>L', port_to_bind)
     finally:
         hostname = TunnelItServer().hostname
         self.conn.transport.sendDebug(">>> TunnelIt Remote Host: %s/%s" % (hostname[0], hostname[2][0]), alwaysDisplay=True)
         self.conn.transport.sendDebug(">>> TunnelIt Remote Port: %s" % port_to_bind, alwaysDisplay=True)
Пример #2
0
 def _NH_IncomingRequestRejected(self, notification):
     request = notification.sender
     if request is not self.incoming_request:
         return
     log.msg('Incoming request rejected')
     self.incoming_request = None
     reactor.callLater(30, self._end_current_session)
Пример #3
0
 def _handle_event(self, event):
     networks = self.networks
     role_map = ThorEntitiesRoleMap(
         event.message
     )  # mapping between role names and lists of nodes with that role
     role = 'rating_server'
     try:
         network = networks[role]
     except KeyError:
         from thor import network as thor_network
         network = thor_network.new(ThorNodeConfig.multiply)
         networks[role] = network
     new_nodes = set([node.ip for node in role_map.get(role, [])])
     old_nodes = set(network.nodes)
     added_nodes = new_nodes - old_nodes
     removed_nodes = old_nodes - new_nodes
     if added_nodes:
         for node in added_nodes:
             network.add_node(node)
             address = RatingEngineAddress(node)
             self.rating_connections[address] = RatingEngine(address)
         plural = 's' if len(added_nodes) != 1 else ''
         log.msg("Added rating node%s: %s" %
                 (plural, ', '.join(added_nodes)))
     if removed_nodes:
         for node in removed_nodes:
             network.remove_node(node)
             address = RatingEngineAddress(node)
             self.rating_connections[address].shutdown()
             del self.rating_connections[address]
         plural = 's' if len(removed_nodes) != 1 else ''
         log.msg("Removed rating node%s: %s" %
                 (plural, ', '.join(removed_nodes)))
Пример #4
0
 def handle_event(self, event):
     # print "Received event: %s" % event
     networks = self.networks
     role_map = ThorEntitiesRoleMap(
         event.message
     )  ## mapping between role names and lists of nodes with that role
     for role in ["msrprelay_server"]:
         try:
             network = networks[
                 role]  ## avoid setdefault here because it always evaluates the 2nd argument
         except KeyError:
             from thor import network as thor_network
             network = thor_network.new(Config.multiply)
             networks[role] = network
         new_nodes = set([node.ip for node in role_map.get(role, [])])
         old_nodes = set(network.nodes)
         added_nodes = new_nodes - old_nodes
         removed_nodes = old_nodes - new_nodes
         if removed_nodes:
             for node in removed_nodes:
                 network.remove_node(node)
             plural = len(removed_nodes) != 1 and 's' or ''
             log.msg("removed %s node%s: %s" %
                     (role, plural, ', '.join(removed_nodes)))
         if added_nodes:
             for node in added_nodes:
                 network.add_node(node)
             plural = len(added_nodes) != 1 and 's' or ''
             log.msg("added %s node%s: %s" %
                     (role, plural, ', '.join(added_nodes)))
Пример #5
0
 def handle_event(self, event):
     #print "Received event: %s" % event
     networks = self.networks
     role_map = ThorEntitiesRoleMap(event.message) # mapping between role names and lists of nodes with that role
     updated = False
     for role in self.node.roles + ('sip_proxy',):
         try:
             network = networks[role]
         except KeyError:
             from thor import network as thor_network
             network = thor_network.new(ThorNodeConfig.multiply)
             networks[role] = network
         new_nodes = set([node.ip for node in role_map.get(role, [])])
         old_nodes = set(network.nodes)
         added_nodes = new_nodes - old_nodes
         removed_nodes = old_nodes - new_nodes
         if removed_nodes:
             for node in removed_nodes:
                 network.remove_node(node)
             plural = len(removed_nodes) != 1 and 's' or ''
             log.msg("removed %s node%s: %s" % (role, plural, ', '.join(removed_nodes)))
             updated = True
         if added_nodes:
             for node in added_nodes:
                 network.add_node(node)
             plural = len(added_nodes) != 1 and 's' or ''
             log.msg("added %s node%s: %s" % (role, plural, ', '.join(added_nodes)))
             updated = True
     if updated:
         NotificationCenter().post_notification('ThorNetworkGotUpdate', sender=self, data=NotificationData(networks=self.networks))
Пример #6
0
 def _NH_SIPSessionDidEnd(self, notification):
     log.msg('Session ended')
     session = notification.sender
     chat_stream = session.streams[0]
     notification_center = NotificationCenter()
     notification_center.remove_observer(self, sender=chat_stream)
     notification_center.remove_observer(self, sender=session)
Пример #7
0
 def handle_event(self, event):
     #print "Received event: %s" % event
     networks = self.networks
     role_map = ThorEntitiesRoleMap(event.message) # mapping between role names and lists of nodes with that role
     updated = False
     for role in self.node.roles + ('sip_proxy',):
         try:
             network = networks[role]
         except KeyError:
             from thor import network as thor_network
             network = thor_network.new(ThorNodeConfig.multiply)
             networks[role] = network
         new_nodes = set([node.ip for node in role_map.get(role, [])])
         old_nodes = set(network.nodes)
         added_nodes = new_nodes - old_nodes
         removed_nodes = old_nodes - new_nodes
         if removed_nodes:
             for node in removed_nodes:
                 network.remove_node(node)
             plural = len(removed_nodes) != 1 and 's' or ''
             log.msg("removed %s node%s: %s" % (role, plural, ', '.join(removed_nodes)))
             updated = True
         if added_nodes:
             for node in added_nodes:
                 network.add_node(node)
             plural = len(added_nodes) != 1 and 's' or ''
             log.msg("added %s node%s: %s" % (role, plural, ', '.join(added_nodes)))
             updated = True
     if updated:
         NotificationCenter().post_notification('ThorNetworkGotUpdate', sender=self, data=NotificationData(networks=self.networks))
Пример #8
0
 def logout(self):
     # remove all listeners
     for listener in self.listeners.itervalues():
         if listener.disconnect_timer is not None and listener.disconnect_timer.active():
             listener.disconnect_timer.cancel()
         listener.listener.stopListening()
     log.msg('avatar %s logging out (%i)' % (self.username, len(self.listeners)))
Пример #9
0
 def _NH_SIPApplicationDidEnd(self, notification):
     self.trace_manager.stop()
     log.msg('SIP application ended')
     if not self.stopping_event.is_set():
         log.warning('SIP application ended without stopping all subsystems')
         self.stopping_event.set()
     self.stop_event.set()
Пример #10
0
 def __init__(self):
     parser = ChuckNorrisParser()
     for i in [random.randint(1, 100) for i in xrange(5)]:
         try:
             data = urllib.urlopen(
                 "http://4q.cc/index.php?pid=listfacts&person=chuck&page=%d"
                 % i).read()
         except IOError:
             break
         else:
             parser.parse(data)
     facts = parser.facts
     if not facts:
         try:
             facts = open(
                 os.path.realpath(
                     os.path.join(os.path.dirname(__file__), 'facts.txt')),
                 'r').read().split('\n')
         except IOError:
             facts = []
     with open(
             os.path.realpath(
                 os.path.join(os.path.dirname(__file__), 'facts.txt')),
             'w') as f:
         f.write('\n'.join(facts))
     log.msg('%d Chuck Norris facts loaded!' % len(facts))
     random.shuffle(facts)
     self.facts = cycle(facts)
Пример #11
0
 def start(self):
     interface = WebServerConfig.local_ip
     port = WebServerConfig.local_port
     cert_path = WebServerConfig.certificate.normalized if WebServerConfig.certificate else None
     cert_chain_path = WebServerConfig.certificate_chain.normalized if WebServerConfig.certificate_chain else None
     if cert_path is not None:
         if not os.path.isfile(cert_path):
             log.error('Certificate file %s could not be found' % cert_path)
             return
         try:
             ssl_ctx_factory = DefaultOpenSSLContextFactory(cert_path, cert_path)
         except Exception:
             log.exception('Creating TLS context')
             log.err()
             return
         if cert_chain_path is not None:
             if not os.path.isfile(cert_chain_path):
                 log.error('Certificate chain file %s could not be found' % cert_chain_path)
                 return
             ssl_ctx = ssl_ctx_factory.getContext()
             try:
                 ssl_ctx.use_certificate_chain_file(cert_chain_path)
             except Exception:
                 log.exception('Setting TLS certificate chain file')
                 log.err()
                 return
         self.listener = reactor.listenSSL(port, self.site, ssl_ctx_factory, backlog=511, interface=interface)
         scheme = 'https'
     else:
         self.listener = reactor.listenTCP(port, self.site, backlog=511, interface=interface)
         scheme = 'http'
     port = self.listener.getHost().port
     self.__dict__['url'] = '%s://%s:%d' % (scheme, WebServerConfig.hostname or interface.normalized, port)
     log.msg('Web server listening for requests on: %s' % self.url)
Пример #12
0
    def handle_event(self, event):
        # print "Received event: %s" % event
        networks = self.networks
        role_map = ThorEntitiesRoleMap(event.message)  ## mapping between role names and lists of nodes with that role
        for role in ["msrprelay_server"]:
            try:
                network = networks[role]  ## avoid setdefault here because it always evaluates the 2nd argument
            except KeyError:
                from thor import network as thor_network

                network = thor_network.new(Config.multiply)
                networks[role] = network
            new_nodes = set([node.ip for node in role_map.get(role, [])])
            old_nodes = set(network.nodes)
            added_nodes = new_nodes - old_nodes
            removed_nodes = old_nodes - new_nodes
            if removed_nodes:
                for node in removed_nodes:
                    network.remove_node(node)
                plural = len(removed_nodes) != 1 and "s" or ""
                log.msg("removed %s node%s: %s" % (role, plural, ", ".join(removed_nodes)))
            if added_nodes:
                for node in added_nodes:
                    network.add_node(node)
                plural = len(added_nodes) != 1 and "s" or ""
                log.msg("added %s node%s: %s" % (role, plural, ", ".join(added_nodes)))
Пример #13
0
def log_access(request, response, reason=None):
    if getattr(request, '_logged', False):
        return
    msg = format_log_message(request, response, reason)
    request._logged = True
    if msg and (response.stream is None or response.stream.length < 5000):
        log.msg(AccessLog(msg))
Пример #14
0
 def _NH_SessionItemDidChange(self, notification):
     if notification.sender is not self.current_session:
         return
     session = notification.sender
     name = session.name or session.uri.user
     log.msg('%s' % (session.status or name))
     log.msg('%s' % session.duration)
 def _NH_SIPSessionDidEnd(self, notification):
     log.msg('Session ended')
     session = notification.sender
     chat_stream = session.streams[0]
     notification_center = NotificationCenter()
     notification_center.remove_observer(self, sender=chat_stream)
     notification_center.remove_observer(self, sender=session)
Пример #16
0
 def _EH_HangupButtonPressed(self):
     if self.incoming_request is not None:
         log.msg('Rejecting incoming request...')
         self.incoming_request.busy()
     elif self.current_session is not None:
         log.msg('Ending session...')
         self.current_session.end()
Пример #17
0
 def _NH_IncomingRequestRejected(self, notification):
     request = notification.sender
     if request is not self.incoming_request:
         return
     log.msg('Incoming request rejected')
     self.lcd_output('Call rejected', delay=2)
     self.lcd_output('')
     self.incoming_request = None
Пример #18
0
 def start(self):
     log.msg("Listening on: %s:%d" % (ServerConfig.address, ServerConfig.root.port))
     log.msg("XCAP root: %s" % ServerConfig.root)
     if ServerConfig.root.startswith('https'):
         self._start_https(reactor)
     else:
         reactor.listenTCP(ServerConfig.root.port, HTTPFactory(self.site), interface=ServerConfig.address)
     reactor.run(installSignalHandlers=ServerConfig.backend.installSignalHandlers)
Пример #19
0
 def start(self):
     log.msg("Listening on: %s:%d" % (ServerConfig.address, ServerConfig.root.port))
     log.msg("XCAP root: %s" % ServerConfig.root)
     if ServerConfig.root.startswith('https'):
         self._start_https(reactor)
     else:
         reactor.listenTCP(ServerConfig.root.port, HTTPFactory(self.site), interface=ServerConfig.address)
     reactor.run(installSignalHandlers=ServerConfig.backend.installSignalHandlers)
Пример #20
0
 def _start_https(self, reactor):
     from gnutls.interfaces.twisted import X509Credentials
     cert, pKey = TLSConfig.certificate, TLSConfig.private_key
     if cert is None or pKey is None:
         log.fatal("the TLS certificates or the private key could not be loaded")
         sys.exit(1)
     credentials = X509Credentials(cert, pKey)
     reactor.listenTLS(ServerConfig.root.port, HTTPFactory(self.site), credentials, interface=ServerConfig.address)
     log.msg("TLS started")
Пример #21
0
 def _NH_SIPEngineDidFail(self, notification):
     log.msg('SIP Engine failed')
     if self.http_listener is not None:
         self.http_listener.stop()
     try:
         reactor.stop()
     except ReactorNotRunning:
         pass
     self.stop_event.set()
Пример #22
0
 def _NH_SIPEngineDidFail(self, notification):
     log.msg('SIP Engine failed')
     if self.http_listener is not None:
         self.http_listener.stop()
     try:
         reactor.stop()
     except ReactorNotRunning:
         pass
     self.stop_event.set()
Пример #23
0
 def _NH_SessionItemNewOutgoing(self, notification):
     session = notification.sender
     if self.current_session is not None:
         reactor.callLater(0, session.end)
         self.current_session.active = True
         return
     log.msg('Outgoing session to %s' % session.uri)
     self.current_session = session
     reactor.callLater(30, self._end_current_session)
Пример #24
0
 def _NH_SIPEngineDidStart(self, notification):
     self.state = 'started'
     engine = Engine()
     for transport in ('udp', 'tcp', 'tls'):
         if getattr(engine, '%s_port' % transport) is not None:
             self.supported_transports.append(transport)
     self.http_listener = HTTPListener()
     self.http_listener.start()
     log.msg('SIP Engine started')
     log.msg('Enabled SIP transports: %s' % ', '.join(transport.upper() for transport in self.supported_transports))
Пример #25
0
def handle_channel(address):
    if request.method == 'POST':
        return 'Done'
    else:
        log.msg('Got status request for %s' % address)
        try:
            return str(channelStatus[address])
        except KeyError:
            log.msg('Got channel status request for unknown address %s' % address)
            abort(404)
Пример #26
0
 def _NH_SessionItemNewOutgoing(self, notification):
     session = notification.sender
     if self.current_session is not None:
         reactor.callLater(0, session.end)
         self.current_session.active = True
         return
     log.msg('Outgoing session to %s' % session.uri)
     name = session.name or session.uri.user
     self.lcd_output('Outgoing call\n%s' % name)
     self.current_session = session
Пример #27
0
 def start(self, roles):
     # Needs to be called from a green thread
     log.msg('Publishing %s roles to SIPThor' % roles)
     self.node = ThorEntity(SIPConfig.local_ip.normalized, roles, version=sylk.__version__)
     self.networks = {}
     self.presence_message = ThorEvent('Thor.Presence', self.node.id)
     self.shutdown_message = ThorEvent('Thor.Leave', self.node.id)
     credentials = X509Credentials(ThorNodeConfig.certificate, ThorNodeConfig.private_key, [ThorNodeConfig.ca])
     credentials.verify_peer = True
     tls_context = TLSContext(credentials)
     EventServiceClient.__init__(self, ThorNodeConfig.domain, tls_context)
Пример #28
0
 def _start_https(self, reactor):
     from gnutls.interfaces.twisted import X509Credentials
     from gnutls.connection import TLSContext, TLSContextServerOptions
     cert, pKey = TLSConfig.certificate, TLSConfig.private_key
     if cert is None or pKey is None:
         log.fatal("the TLS certificates or the private key could not be loaded")
         sys.exit(1)
     credentials = X509Credentials(cert, pKey)
     tls_context = TLSContext(credentials, server_options=TLSContextServerOptions(certificate_request=None))
     reactor.listenTLS(ServerConfig.root.port, HTTPFactory(self.site), tls_context, interface=ServerConfig.address)
     log.msg("TLS started")
Пример #29
0
 def start(self, roles):
     # Needs to be called from a green thread
     log.msg("Publishing %s roles to SIPThor" % roles)
     self.node = ThorEntity(SIPConfig.local_ip.normalized, roles, version=sylk.__version__)
     self.networks = {}
     self.presence_message = ThorEvent("Thor.Presence", self.node.id)
     self.shutdown_message = ThorEvent("Thor.Leave", self.node.id)
     credentials = X509Credentials(ThorNodeConfig.certificate, ThorNodeConfig.private_key, [ThorNodeConfig.ca])
     credentials.verify_peer = True
     tls_context = TLSContext(credentials)
     EventServiceClient.__init__(self, ThorNodeConfig.domain, tls_context)
 def incoming_session(self, session):
     # Handle incoming INVITE session
     log.msg('Incoming session from %s' % session.remote_identity.uri)
     try:
         chat_stream = (stream for stream in session.proposed_streams if stream.type=='chat').next()
     except StopIteration:
         session.reject(488)
         return
     else:
         NotificationCenter().add_observer(self, sender=session)
         session.accept([chat_stream])
Пример #31
0
 def start(self, roles):
     # Needs to be called from a green thread
     log.msg('Publishing %s roles to SIPThor' % roles)
     self.node = ThorEntity(SIPConfig.local_ip.normalized, roles, version=sylk.__version__)
     self.networks = {}
     self.presence_message = ThorEvent('Thor.Presence', self.node.id)
     self.shutdown_message = ThorEvent('Thor.Leave', self.node.id)
     credentials = X509Credentials(ThorNodeConfig.certificate, ThorNodeConfig.private_key, [ThorNodeConfig.ca])
     credentials.verify_peer = True
     credentials.session_params.compressions = (COMP_LZO, COMP_DEFLATE, COMP_NULL)
     EventServiceClient.__init__(self, ThorNodeConfig.domain, credentials)
Пример #32
0
 def stop(self):
     log.msg('Null HAL backend stopped')
     notification_center = NotificationCenter()
     notification_center.remove_observer(self, name='IncomingRequestReceived')
     notification_center.remove_observer(self, name='IncomingRequestAccepted')
     notification_center.remove_observer(self, name='IncomingRequestRejected')
     notification_center.remove_observer(self, name='IncomingRequestCancelled')
     notification_center.remove_observer(self, name='SessionItemNewIncoming')
     notification_center.remove_observer(self, name='SessionItemNewOutgoing')
     notification_center.remove_observer(self, name='SessionItemDidChange')
     notification_center.remove_observer(self, name='SessionItemDidEnd')
Пример #33
0
 def clientConnectionLost(self, connector, reason):
     self.cancel_delayed()
     if reason.type != ConnectionDone:
         log.error("Connection with dispatcher at %(host)s:%(port)d was lost: %%s" % connector.__dict__ % reason.value)
     else:
         log.msg("Connection with dispatcher at %(host)s:%(port)d was closed" % connector.__dict__)
     if self.parent.connector_needs_reconnect(connector):
         if isinstance(reason.value, CertificateError) or self.connection_lost:
             self.delayed = reactor.callLater(RelayConfig.reconnect_delay, connector.connect)
         else:
             self.delayed = reactor.callLater(min(RelayConfig.reconnect_delay, 1), connector.connect)
         self.connection_lost = True
Пример #34
0
 def incoming_session(self, session):
     # Handle incoming INVITE session
     log.msg('Incoming session from %s' % session.remote_identity.uri)
     try:
         chat_stream = (stream for stream in session.proposed_streams
                        if stream.type == 'chat').next()
     except StopIteration:
         session.reject(488)
         return
     else:
         NotificationCenter().add_observer(self, sender=session)
         session.accept([chat_stream])
Пример #35
0
 def _NH_SIPEngineDidStart(self, notification):
     self.state = 'started'
     engine = Engine()
     for transport in ('udp', 'tcp', 'tls'):
         if getattr(engine, '%s_port' % transport) is not None:
             self.supported_transports.append(transport)
     self.http_listener = HTTPListener()
     self.http_listener.start()
     log.msg('SIP Engine started')
     log.msg('Enabled SIP transports: %s' %
             ', '.join(transport.upper()
                       for transport in self.supported_transports))
Пример #36
0
 def clientConnectionLost(self, connector, reason):
     self.cancel_delayed()
     if reason.type != ConnectionDone:
         log.error("Connection with dispatcher at %(host)s:%(port)d was lost: %%s" % connector.__dict__ % reason.value)
     else:
         log.msg("Connection with dispatcher at %(host)s:%(port)d was closed" % connector.__dict__)
     if self.parent.connector_needs_reconnect(connector):
         if isinstance(reason.value, CertificateError) or self.connection_lost:
             self.delayed = reactor.callLater(RelayConfig.reconnect_delay, connector.connect)
         else:
             self.delayed = reactor.callLater(min(RelayConfig.reconnect_delay, 1), connector.connect)
         self.connection_lost = True
 def _NH_SIPSessionDidStart(self, notification):
     log.msg('Session started')
     session = notification.sender
     audio_stream = session.streams[0]
     prompt = os.path.realpath(os.path.join(os.path.dirname(__file__), 'jamesbond.wav'))
     player = WavePlayer(audio_stream.mixer, prompt, pause_time=1, initial_play=False)
     audio_stream.bridge.add(player)
     try:
         player.play().wait()
     except WavePlayerError:
         pass
     audio_stream.bridge.remove(player)
     session.end()
Пример #38
0
 def handle_event(self, event):
     # print "Received event: %s" % event
     networks = self.networks
     role_map = ThorEntitiesRoleMap(
         event.message
     )  ## mapping between role names and lists of nodes with that role
     thor_databases = role_map.get('thor_database', [])
     if thor_databases:
         thor_databases.sort(
             lambda x, y: cmp(x.priority, y.priority) or cmp(x.ip, y.ip))
         dburi = thor_databases[0].dburi
     else:
         dburi = None
     self._database.update_dburi(dburi)
     all_roles = role_map.keys() + networks.keys()
     for role in all_roles:
         try:
             network = networks[
                 role]  ## avoid setdefault here because it always evaluates the 2nd argument
         except KeyError:
             from thor import network as thor_network
             if role in [
                     "thor_manager", "thor_monitor", "provisioning_server",
                     "media_relay", "thor_database"
             ]:
                 continue
             else:
                 network = thor_network.new(ThorNodeConfig.multiply)
             networks[role] = network
         new_nodes = set([
             ThorEntityAddress(node.ip, getattr(node, 'control_port', None),
                               getattr(node, 'version', 'unknown'))
             for node in role_map.get(role, [])
         ])
         old_nodes = set(network.nodes)
         ## compute set differences
         added_nodes = new_nodes - old_nodes
         removed_nodes = old_nodes - new_nodes
         if removed_nodes:
             for node in removed_nodes:
                 network.remove_node(node)
                 self.control.discard_link((node.ip, node.control_port))
             plural = len(removed_nodes) != 1 and 's' or ''
             log.msg("removed %s node%s: %s" %
                     (role, plural, ', '.join(removed_nodes)))
         if added_nodes:
             for node in added_nodes:
                 network.add_node(node)
             plural = len(added_nodes) != 1 and 's' or ''
             log.msg("added %s node%s: %s" %
                     (role, plural, ', '.join(added_nodes)))
 def incoming_session(self, session):
     # Handle incoming INVITE session
     log.msg('Incoming session from %s' % session.remote_identity.uri)
     if self.audio_conference is None:
         self.audio_conference = AudioConference()
     try:
         audio_stream = (stream for stream in session.proposed_streams if stream.type=='audio').next()
     except StopIteration:
         session.reject(488)
         return
     else:
         notification_center = NotificationCenter()
         notification_center.add_observer(self, sender=session)
         session.accept([audio_stream])
Пример #40
0
 def _NH_IncomingRequestReceived(self, notification):
     request = notification.sender
     if not request.new_session:
         request.reject()
         return
     if self.current_session is not None:
         request.busy()
         return
     if self.incoming_request is not None:
         request.busy()
         return
     log.msg('Received incoming request from %s' % request.session.remote_identity)
     self.incoming_request = request
     reactor.callLater(5, self._accept_incoming_request)
Пример #41
0
 def incoming_session(self, session):
     # Handle incoming INVITE session
     log.msg('Incoming session from %s' % session.remote_identity.uri)
     if self.audio_conference is None:
         self.audio_conference = AudioConference()
     try:
         audio_stream = (stream for stream in session.proposed_streams
                         if stream.type == 'audio').next()
     except StopIteration:
         session.reject(488)
         return
     else:
         notification_center = NotificationCenter()
         notification_center.add_observer(self, sender=session)
         session.accept([audio_stream])
Пример #42
0
    def start(self):
        if 'twisted.internet.reactor' not in sys.modules:
            for name in ('epollreactor', 'kqreactor', 'pollreactor', 'selectreactor'):
                try:    __import__('twisted.internet.%s' % name, globals(), locals(), fromlist=[name]).install()
                except: continue
                else:   break
        from twisted.internet import reactor

        log.msg("Listening on: %s:%d" % (ServerConfig.address, ServerConfig.root.port))
        log.msg("XCAP root: %s" % ServerConfig.root)
        if ServerConfig.root.startswith('https'):
            self._start_https(reactor)
        else:
            reactor.listenTCP(ServerConfig.root.port, HTTPFactory(self.site), interface=ServerConfig.address)
        self.run(reactor)
Пример #43
0
 def _NH_IncomingRequestReceived(self, notification):
     request = notification.sender
     if not request.new_session:
         request.reject()
         return
     if self.current_session is not None:
         request.busy()
         return
     if self.incoming_request is not None:
         request.busy()
         return
     log.msg('Received incoming request from %s' % request.session.remote_identity)
     name = request.session.remote_identity.display_name or request.session.remote_identity.uri.user
     self.lcd_output('Incoming call\n%s' % name)
     self.incoming_request = request
Пример #44
0
    def stop(self):
        log.msg('Falcon HAL backend stopped')
        notification_center = NotificationCenter()
        notification_center.remove_observer(self, name='IncomingRequestReceived')
        notification_center.remove_observer(self, name='IncomingRequestAccepted')
        notification_center.remove_observer(self, name='IncomingRequestRejected')
        notification_center.remove_observer(self, name='SessionItemNewIncoming')
        notification_center.remove_observer(self, name='SessionItemNewOutgoing')
        notification_center.remove_observer(self, name='SessionItemDidChange')
        notification_center.remove_observer(self, name='SessionItemDidEnd')

        # Cleanup hardware stuff
        GPIO.cleanup()
        self._lcd.clear()
        self._lcd_gpio.cleanup()
Пример #45
0
 def _NH_SIPSessionDidStart(self, notification):
     log.msg('Session started')
     session = notification.sender
     audio_stream = session.streams[0]
     prompt = os.path.realpath(
         os.path.join(os.path.dirname(__file__), 'jamesbond.wav'))
     player = WavePlayer(audio_stream.mixer,
                         prompt,
                         pause_time=1,
                         initial_play=False)
     audio_stream.bridge.add(player)
     try:
         player.play().wait()
     except WavePlayerError:
         pass
     audio_stream.bridge.remove(player)
     session.end()
Пример #46
0
 def connectionLost(self, reason):
     if reason.type == ConnectionDone:
         log.msg("Connection with relay at %s was closed" % self.ip)
     elif reason.type == ConnectionReplaced:
         log.warn("Old connection with relay at %s was lost" % self.ip)
     else:
         log.error("Connection with relay at %s was lost: %s" %
                   (self.ip, reason.value))
     for command, defer, timer in self.commands.itervalues():
         timer.cancel()
         defer.errback(RelayError("Relay at %s disconnected" % self.ip))
     if self.timedout is True:
         self.timedout = False
         if self.disconnect_timer.active():
             self.disconnect_timer.cancel()
         self.disconnect_timer = None
     self.factory.connection_lost(self)
Пример #47
0
 def __init__(self):
     load_applications()
     registry = ApplicationRegistry()
     self.applications = dict((app.__appname__, app) for app in registry)
     log.msg('Loaded applications: %s' % ', '.join(self.applications))
     default_application = registry.find_application(
         ServerConfig.default_application)
     if default_application is None:
         log.warning(
             'Default application "%s" does not exist, falling back to "conference"'
             % ServerConfig.default_application)
         ServerConfig.default_application = 'conference'
     else:
         log.msg('Default application: %s' %
                 ServerConfig.default_application)
     self.application_map = dict(
         (item.split(':')) for item in ServerConfig.application_map)
     if self.application_map:
         txt = 'Application map:\n'
         invert_app_map = defaultdict(list)
         for url, app in self.application_map.iteritems():
             invert_app_map[app].append(url)
         for app, urls in invert_app_map.iteritems():
             txt += '    * %s:\n' % app
             for url in urls:
                 txt += '        - %s\n' % url
         log.msg(txt[:-1])
     self.authorization_handler = AuthorizationHandler()
Пример #48
0
 def start(self):
     interface = WebServerConfig.local_ip
     port = WebServerConfig.local_port
     cert_path = WebServerConfig.certificate.normalized if WebServerConfig.certificate else None
     if cert_path is not None:
         if not os.path.isfile(cert_path):
             log.error('Certificate file %s could not be found' % cert_path)
             return
         try:
             ssl_context = DefaultOpenSSLContextFactory(cert_path, cert_path)
         except Exception:
             log.exception('Creating SSL context')
             log.err()
             return
         self.listener = reactor.listenSSL(port, self.site, ssl_context, backlog=511, interface=interface)
         scheme = 'https'
     else:
         self.listener = reactor.listenTCP(port, self.site, backlog=511, interface=interface)
         scheme = 'http'
     port = self.listener.getHost().port
     self.__dict__['url'] = '%s://%s:%d' % (scheme, WebServerConfig.hostname or interface.normalized, port)
     log.msg('Web server listening for requests on: %s' % self.url)
Пример #49
0
 def _NH_SIPEngineDidEnd(self, notification):
     log.msg('SIP Engine stopped')
     self.state = 'stopped'
     self.http_listener.stop()
     reactor.stop()
Пример #50
0
 def timeoutConnection(self):
     if self.transport:
         log.msg("Timing out client: %s" % str(self.transport.getPeer()))
         channel.http.HTTPChannel.timeoutConnection(self)
Пример #51
0
 def _NH_SIPSessionDidEnd(self, notification):
     log.msg('Session ended')
     session = notification.sender
     audio_stream = session.streams[0]
     self.audio_conference.remove(audio_stream)
     NotificationCenter().remove_observer(self, sender=notification.sender)
Пример #52
0
 def _NH_SIPSessionDidStart(self, notification):
     log.msg('Session started')
     session = notification.sender
     audio_stream = session.streams[0]
     self.audio_conference.add(audio_stream)
Пример #53
0
def signal_handler2(*args):
    """Another sample signal handler"""
    log.msg("second handler received signal %s" % args[0])


# The application name.
name = 'process-example'

# Set the process runtime directory. This is where the pid file and other
# process runtime related files will be created. The default is /var/run
# but in this example we use /tmp because we need a place where we have
# write access even without running as root.
process.runtime_directory = '/tmp'

# These log lines will go to stdout.
log.msg("Starting %s. Check syslog to see what's going on next." % name)
log.msg(
    "Use `watch -n .1 ls /tmp' to see how the pid file is created and deleted."
)

# Set the process to run in the background and create a pid file.
# If daemonize is called without arguments or pidfile is None no pid file
# will be created.
pidfile = process.runtime_file('%s.pid' % name)
try:
    process.daemonize(pidfile)
except ProcessError, e:
    log.fatal(str(e))
    sys.exit(1)

# process was successfully put in the background. Redirect logging to syslog
Пример #54
0
                         notNone=True)
    to_tag = StringCol(length=64, dbName=DatabaseConfig.totag_column)
    info = BLOBCol(
        length=2**24 - 1, dbName=DatabaseConfig.info_column
    )  # 2**24-1 makes it a mediumblob in mysql, that can hold 16 million bytes
    ## Indexes
    callid_idx = DatabaseIndex('call_id', 'from_tag', 'to_tag', unique=True)


try:
    MediaSessions.createTable(ifNotExists=True)
except OperationalError, e:
    log.error("cannot create the `%s' table: %s" %
              (DatabaseConfig.sessions_table, e))
    log.msg(
        "please make sure that the `%s' user has the CREATE and ALTER rights on the `%s' database"
        % (connection.user, connection.db))
    log.msg(
        "then restart the dispatcher, or you can create the table yourself using the following definition:"
    )
    log.msg("----------------- >8 -----------------")
    sql, constraints = MediaSessions.createTableSQL()
    statements = ';\n'.join([sql] + constraints) + ';'
    log.msg(statements)
    log.msg("----------------- >8 -----------------")
    #raise RuntimeError(str(e))


class Accounting(object):
    def __init__(self):
        self.handler = DatabaseAccounting()
Пример #55
0
def signal_handler(*args):
    """A sample signal handler"""
    log.msg("first handler received signal %s" % args[0])
Пример #56
0
 def _NH_SIPSessionDidFail(self, notification):
     log.msg('Session failed')
     NotificationCenter().remove_observer(self, sender=notification.sender)
Пример #57
0
def signal_handler2(*args):
    """Another sample signal handler"""
    log.msg("second handler received signal %s" % args[0])