Ejemplo n.º 1
0
 def __new__(cls, value):
     if isinstance(value, str):
         try:
             return X509Certificate(file_content(value))
         except Exception, e:
             log.warn("Certificate file '%s' could not be loaded: %s" % (value, str(e)))
             return None
Ejemplo n.º 2
0
 def send_command(self, command, headers):
     try:
         parsed_headers = dict(header.split(": ", 1) for header in headers)
     except:
         raise RelayError("Could not parse headers from OpenSIPs")
     try:
         call_id = parsed_headers["call_id"]
     except KeyError:
         raise RelayError("Missing call_id header")
     session = self.sessions.get(call_id, None)
     if session and session.expire_time is None:
         relay = session.relay_ip
         if relay not in self.relays:
             raise RelayError("Relay for this session (%s) is no longer connected" % relay)
         return self.relays[relay].send_command(command, headers)
     ## We do not have a session for this call_id or the session is already expired
     if command == "update":
         preferred_relay = parsed_headers.get("media_relay")
         try_relays = deque(protocol for protocol in self.relays.itervalues() if protocol.active and protocol.ip != preferred_relay)
         random.shuffle(try_relays)
         if preferred_relay is not None:
             protocol = self.relays.get(preferred_relay)
             if protocol is not None and protocol.active:
                 try_relays.appendleft(protocol)
             else:
                 log.warn("user requested media_relay %s is not available" % preferred_relay)
         defer = self._try_next(try_relays, command, headers)
         defer.addCallback(self._add_session, try_relays, call_id, parsed_headers)
         return defer
     elif command == 'remove' and session:
         ## This is the remove we received for an expired session for which we triggered dialog termination
         del self.sessions[call_id]
         return 'removed'
     else:
         raise RelayError("Got `%s' command from OpenSIPS for unknown session with call-id `%s'" % (command, call_id))
Ejemplo n.º 3
0
 def _remove_expired_sessions(self):
     now, limit = time(), DispatcherConfig.cleanup_expired_sessions_after
     obsolete = [k for k, s in ifilter(lambda (k, s): s.expire_time and (now-s.expire_time>=limit), self.sessions.iteritems())]
     if obsolete:
         [self.sessions.pop(call_id) for call_id in obsolete]
         log.warn("found %d expired sessions which were not removed during the last %d hours" % (len(obsolete), round(limit/3600.0)))
     return KeepRunning
Ejemplo n.º 4
0
 def __init__(self):
     main_config_file = process.config_file(Config.config_file)
     if main_config_file is None:
         raise RuntimeError("Cannot find the radius configuration file: `%s'" % Config.config_file)
     try:
         config = dict(line.rstrip("\n").split(None, 1) for line in open(main_config_file) if len(line.split(None, 1)) == 2 and not line.startswith("#"))
         secrets = dict(line.rstrip("\n").split(None, 1) for line in open(config["servers"]) if len(line.split(None, 1)) == 2 and not line.startswith("#"))
         server = config["acctserver"]
         try:
             server, acctport = server.split(":")
             acctport = int(acctport)
         except ValueError:
             acctport = 1813
         secret = secrets[server]
         dicts = [RadiusDictionaryFile(config["dictionary"])]
         if Config.additional_dictionary:
             additional_dictionary = process.config_file(Config.additional_dictionary)
             if additional_dictionary:
                 dicts.append(RadiusDictionaryFile(additional_dictionary))
             else:
                 log.warn("Could not load additional RADIUS dictionary file: `%s'" % Config.additional_dictionary)
         raddict = pyrad.dictionary.Dictionary(*dicts)
         timeout = int(config["radius_timeout"])
         retries = int(config["radius_retries"])
     except Exception, e:
         log.fatal("cannot read the RADIUS configuration file")
         raise
Ejemplo n.º 5
0
 def _PE_debitbalance(self, line):
     valid_answers = ('Ok', 'Failed', 'Not prepaid')
     lines = line.splitlines()
     try:
         result = lines[0].strip().capitalize()
     except IndexError:
         raise ValueError("Empty reply from rating engine")
     if result not in valid_answers:
         log.error("Invalid reply from rating engine: `%s'" %
                   lines[0].strip())
         log.warn("Rating engine possible failed query: %s" %
                  self.__request)
         raise RatingEngineError('Invalid rating engine response')
     elif result == 'Failed':
         log.warn("Rating engine failed query: %s" % self.__request)
         raise RatingEngineError('Rating engine failed query')
     else:
         try:
             timelimit = int(lines[1].split('=', 1)[1].strip())
             totalcost = lines[2].strip()
         except:
             log.error(
                 "Invalid reply from rating engine for DebitBalance on lines 2, 3: `%s'"
                 % ("', `".join(lines[1:3])))
             timelimit = None
             totalcost = 0
         return timelimit, totalcost
Ejemplo n.º 6
0
 def _save_calls(self, result):
     if self.calls:
         log.info('Saving calls')
         calls_file = '%s/%s' % (process.runtime_directory, backup_calls_file)
         try:
             f = open(calls_file, 'w')
         except:
             pass
         else:
             for call in self.calls.values():
                 call.application = None
                 ## we will mark timers with 'running' or 'idle', depending on their current state,
                 ## to be able to correctly restore them later (Timer objects cannot be pickled)
                 if call.timer is not None:
                     if call.inprogress:
                         call.timer.cancel()
                         call.timer = 'running' ## temporary mark that this timer was running
                     else:
                         call.timer = 'idle'    ## temporary mark that this timer was not running
             failed_dump = False
             try:
                 try:
                     cPickle.dump(self.calls, f)
                 except Exception, why:
                     log.warn("Failed to dump call list: %s" % why)
                     failed_dump = True
             finally:
                 f.close()
             if failed_dump:
                 try:    os.unlink(calls_file)
                 except: pass
             else:
                 log.info("Saved calls: %s" % str(self.calls.keys()))
         self.calls = {}
Ejemplo n.º 7
0
 def __new__(typ, value):
     if isinstance(value, basestring):
         try:
             return X509PrivateKey(file_content(value))
         except Exception, e:
             log.warn("Private key file '%s' could not be loaded: %s" % (value, str(e)))
             return None
Ejemplo n.º 8
0
 def __new__(cls, value):
     if value is None:
         return None
     elif not isinstance(value, basestring):
         raise TypeError("value must be a string, unicode or None")
     if value.strip() == '':
         return None
     valid_uris = []
     for uri in re.split(r'\s*,\s*', value):
         scheme, host, path, params, query, fragment = urlparse.urlparse(
             uri)
         if host and scheme in ('http', 'https'):
             for u in valid_uris:
                 if u == uri or uri.startswith(u) or u.startswith(uri):
                     log.warn("ignoring XCAP Root URI %r (similar to %r)" %
                              (uri, u))
                     break
             else:
                 valid_uris.append(uri)
         else:
             log.warn("Invalid XCAP Root URI: %r" % uri)
     if not valid_uris:
         return None
     instance = str.__new__(cls, valid_uris[0])
     instance.uris = tuple(valid_uris)
     return instance
Ejemplo n.º 9
0
 def read(cls, cfgfile=None, section=None):
     """Read the settings from the given file and section"""
     cfgfile = cfgfile or cls.__cfgfile__
     section = section or cls.__section__
     if None in (cfgfile, section):
         raise ValueError(
             "A config file and section are required for reading settings")
     if isinstance(cfgfile, ConfigFile):
         config_file = cfgfile
     else:
         config_file = cls.__cfgtype__(cfgfile)
     if isinstance(section, basestring):
         section_list = (section, )
     else:
         section_list = section
     for section in section_list:
         for name, value in config_file.get_section(section,
                                                    filter=cls.__settings__,
                                                    default=[]):
             try:
                 setattr(cls, name, value)
             except Exception, e:
                 msg = "ignoring invalid config value: %s.%s=%s (%s)." % (
                     section, name, value, e)
                 log.warn(msg, **config_file.log_context)
Ejemplo n.º 10
0
 def __on_exit(self):
     if self._pidfile:
         try:
             os.unlink(self._pidfile)
         except OSError, why:
             log.warn("unable to delete pidfile %s: %s" %
                      (self._pidfile, str(why)))
Ejemplo n.º 11
0
 def session_expired(self, session):
     connector = self.dispatcher_connectors.get(session.dispatcher)
     if connector is None:
         connector = self.old_connectors.get(session.dispatcher)
     if connector and connector.state == "connected":
         connector.transport.write(" ".join(["expired", cjson.encode(session.statistics)]) + "\r\n")
     else:
         log.warn("dispatcher for expired session is no longer online, statistics are lost!")
Ejemplo n.º 12
0
 def __new__(cls, value):
     if isinstance(value, basestring):
         try:
             return X509Certificate(file_content(value))
         except Exception, e:
             log.warn("Certificate file '%s' could not be loaded: %s" %
                      (value, str(e)))
             return None
Ejemplo n.º 13
0
 def __new__(cls, value):
     if isinstance(value, str):
         try:
             return X509PrivateKey(file_content(value))
         except Exception, e:
             log.warn("Private key file '%s' could not be loaded: %s" %
                      (value, str(e)))
             return None
Ejemplo n.º 14
0
 def session_expired(self, session):
     connector = self.dispatcher_connectors.get(session.dispatcher)
     if connector is None:
         connector = self.old_connectors.get(session.dispatcher)
     if connector and connector.state == "connected":
         connector.transport.write(" ".join(["expired", cjson.encode(session.statistics)]) + "\r\n")
     else:
         log.warn("dispatcher for expired session is no longer online, statistics are lost!")
Ejemplo n.º 15
0
 def _cb_purge_sessions(self, result, relay_ip):
     relay_sessions = cjson.decode(result)
     relay_call_ids = [session["call_id"] for session in relay_sessions]
     for session_id, session in self.sessions.items():
         if session.expire_time is None and session.relay_ip == relay_ip and session_id not in relay_call_ids:
             log.warn("Session %s is no longer on relay %s, statistics are probably lost" % (session_id, relay_ip))
             if session.dialog_id is not None:
                 self.dispatcher.opensips_management.end_dialog(session.dialog_id)
             del self.sessions[session_id]
Ejemplo n.º 16
0
 def __new__(cls, value):
     if isinstance(value, basestring):
         try:
             return X509PrivateKey(file_content(value))
         except Exception as e:
             log.warn("Private key file '%s' could not be loaded: %s" % (value, str(e)))
             return None
     else:
         raise TypeError('value should be a string')
Ejemplo n.º 17
0
 def _measure_speed(self):
     start_time = time()
     current_byte_counter = sum(session.relayed_bytes for session in self.sessions.itervalues())
     self.bps_relayed = 8 * (current_byte_counter + self.closed_byte_counter - self.active_byte_counter) / Config.traffic_sampling_period
     self.active_byte_counter = current_byte_counter
     self.closed_byte_counter = 0
     us_taken = int((time() - start_time) * 1000000)
     if us_taken > 10000:
         log.warn("Aggregate speed calculation time exceeded 10ms: %d us for %d sessions" % (us_taken, len(self.sessions)))
     return KeepRunning
Ejemplo n.º 18
0
 def new_relay(self, relay):
     old_relay = self.relays.pop(relay.ip, None)
     if old_relay is not None:
         log.warn("Relay at %s reconnected, closing old connection" % relay.ip)
         reactor.callLater(0, old_relay.transport.connectionLost, failure.Failure(ConnectionReplaced("relay reconnected")))
     self.relays[relay.ip] = relay
     timer = self.cleanup_timers.pop(relay.ip, None)
     if timer is not None:
         timer.cancel()
     defer = relay.send_command("sessions", [])
     defer.addCallback(self._cb_purge_sessions, relay.ip)
Ejemplo n.º 19
0
 def _create_table(self, klass):
     if klass._connection is Null or klass.tableExists():
         return
     else:
         log.warn('Table %s does not exists. Creating it now.' % klass.sqlmeta.table)
         saved = klass._connection.debug
         try:
             klass._connection.debug = True
             klass.createTable()
         finally:
             klass._connection.debug = saved
Ejemplo n.º 20
0
 def handle_button_press(self, button):
     if button == ANSWER_BTN:
         self._EH_AnswerButtonPressed()
     elif button == HANGUP_BTN:
         self._EH_HangupButtonPressed()
     elif button == INFO_BTN:
         self._EH_InfoButtonPressed()
     elif button in (SD1_BTN, SD2_BTN, SD3_BTN):
         self._EH_SpeedDialButtonPressed(button)
     else:
         log.warn('Unknown button pressed: %s' % button)
Ejemplo n.º 21
0
 def __init__(self, dburi):
     if ':memory:' in dburi:
         log.warn('SQLite in-memory DB is not supported')
         dburi = None
     self._uri = dburi
     if self._uri is not None:
         try:
             self.conn = connectionForURI(self._uri)
             sqlhub.processConnection = self.conn
         except Exception, e:
             log.error('Error connection with the DB: %s' % e)
             self.conn = Null
Ejemplo n.º 22
0
 def _cb_purge_sessions(self, result, relay_ip):
     relay_sessions = cjson.decode(result)
     relay_call_ids = [session["call_id"] for session in relay_sessions]
     for session_id, session in self.sessions.items():
         if session.expire_time is None and session.relay_ip == relay_ip and session_id not in relay_call_ids:
             log.warn(
                 "Session %s is no longer on relay %s, statistics are probably lost"
                 % (session_id, relay_ip))
             if session.dialog_id is not None:
                 self.dispatcher.opensips_management.end_dialog(
                     session.dialog_id)
             del self.sessions[session_id]
Ejemplo n.º 23
0
 def _remove_expired_sessions(self):
     now, limit = time(), DispatcherConfig.cleanup_expired_sessions_after
     obsolete = [
         k for k, s in ifilter(
             lambda (k, s): s.expire_time and
             (now - s.expire_time >= limit), self.sessions.iteritems())
     ]
     if obsolete:
         [self.sessions.pop(call_id) for call_id in obsolete]
         log.warn(
             "found %d expired sessions which were not removed during the last %d hours"
             % (len(obsolete), round(limit / 3600.0)))
     return KeepRunning
Ejemplo n.º 24
0
 def remove_session(self, call_id, from_tag, to_tag=None, **kw):
     key = self._find_session_key(call_id, from_tag, to_tag)
     try:
         session = self.sessions[key]
     except KeyError:
         log.warn("The dispatcher tried to remove a session which is no longer present on the relay")
         return None
     log.debug("removing session %s" % session)
     session.cleanup()
     self.closed_byte_counter += session.relayed_bytes
     del self.sessions[key]
     reactor.callLater(0, self.relay.remove_session, session.dispatcher)
     return session
Ejemplo n.º 25
0
 def session_expired(self, call_id, from_tag):
     key = (call_id, from_tag)
     try:
         session = self.sessions[key]
     except KeyError:
         log.warn("A session expired that was no longer present on the relay")
         return
     log.debug("expired session %s" % session)
     session.cleanup()
     self.closed_byte_counter += session.relayed_bytes
     del self.sessions[key]
     self.relay.session_expired(session)
     self.relay.remove_session(session.dispatcher)
Ejemplo n.º 26
0
 def session_expired(self, call_id, from_tag):
     key = (call_id, from_tag)
     try:
         session = self.sessions[key]
     except KeyError:
         log.warn(
             "A session expired that was no longer present on the relay")
         return
     log.debug("expired session %s" % session)
     session.cleanup()
     self.closed_byte_counter += session.relayed_bytes
     del self.sessions[key]
     self.relay.session_expired(session)
     self.relay.remove_session(session.dispatcher)
Ejemplo n.º 27
0
 def new_relay(self, relay):
     old_relay = self.relays.pop(relay.ip, None)
     if old_relay is not None:
         log.warn("Relay at %s reconnected, closing old connection" %
                  relay.ip)
         reactor.callLater(
             0, old_relay.transport.connectionLost,
             failure.Failure(ConnectionReplaced("relay reconnected")))
     self.relays[relay.ip] = relay
     timer = self.cleanup_timers.pop(relay.ip, None)
     if timer is not None:
         timer.cancel()
     defer = relay.send_command("sessions", [])
     defer.addCallback(self._cb_purge_sessions, relay.ip)
Ejemplo n.º 28
0
 def _measure_speed(self):
     start_time = time()
     current_byte_counter = sum(session.relayed_bytes
                                for session in self.sessions.itervalues())
     self.bps_relayed = 8 * (
         current_byte_counter + self.closed_byte_counter -
         self.active_byte_counter) / RelayConfig.traffic_sampling_period
     self.active_byte_counter = current_byte_counter
     self.closed_byte_counter = 0
     us_taken = int((time() - start_time) * 1000000)
     if us_taken > 10000:
         log.warn(
             "Aggregate speed calculation time exceeded 10ms: %d us for %d sessions"
             % (us_taken, len(self.sessions)))
     return KeepRunning
Ejemplo n.º 29
0
 def remove_session(self, call_id, from_tag, to_tag=None, **kw):
     key = self._find_session_key(call_id, from_tag, to_tag)
     try:
         session = self.sessions[key]
     except KeyError:
         log.warn(
             "The dispatcher tried to remove a session which is no longer present on the relay"
         )
         return None
     log.debug("removing session %s" % session)
     session.cleanup()
     self.closed_byte_counter += session.relayed_bytes
     del self.sessions[key]
     reactor.callLater(0, self.relay.remove_session, session.dispatcher)
     return session
Ejemplo n.º 30
0
 def __new__(cls, description):
     if isinstance(description, (list, tuple)):
         return [Hostname(x) for x in description]
     elif not isinstance(description, basestring):
         raise TypeError("value must be a string, list or tuple")
     if description.lower() == 'none':
         return []
     lst = re.split(r'\s*,\s*', description)
     hosts = []
     for x in lst:
         try:
             host = Hostname(x)
         except ValueError, why:
             log.warn("%s (ignored)" % why)
         else:
             hosts.append(host)
Ejemplo n.º 31
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)
Ejemplo n.º 32
0
 def __new__(cls, description):
     if isinstance(description, (list, tuple)):
         return [Hostname(x) for x in description]
     elif not isinstance(description, basestring):
         raise TypeError("value must be a string, list or tuple")
     if description.lower()=='none':
         return []
     lst = re.split(r'\s*,\s*', description)
     hosts = []
     for x in lst:
         try:
             host = Hostname(x)
         except ValueError, why:
             log.warn("%s (ignored)" % why)
         else:
             hosts.append(host)
Ejemplo n.º 33
0
 def get_setting(self, section, setting, type=str, default=''):
     """Get a setting from a given section using type, or default if missing"""
     try:
         value = self.parser.get(section, setting)
     except:
         return default
     else:
         try:
             if type is bool:
                 return datatypes.Boolean(value)
             else:
                 return type(value)
         except Exception, why:
             msg = "ignoring invalid config value: %s.%s=%s (%s)." % (section, setting, value, why)
             log.warn(msg, **ConfigFile.log_context)
             return default
Ejemplo n.º 34
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)
Ejemplo n.º 35
0
 def get_setting(self, section, setting, type=str, default=''):
     """Get a setting from a given section using type, or default if missing"""
     try:
         value = self.parser.get(section, setting)
     except Exception:
         return default
     else:
         try:
             if type is bool:
                 return datatypes.Boolean(value)
             else:
                 return type(value)
         except Exception, e:
             msg = "ignoring invalid config value: %s.%s=%s (%s)." % (
                 section, setting, value, e)
             log.warn(msg, **ConfigFile.log_context)
             return default
Ejemplo n.º 36
0
 def __init__(self):
     main_config_file = process.config_file(RadiusConfig.config_file)
     if main_config_file is None:
         raise RuntimeError(
             "Cannot find the radius configuration file: `%s'" %
             RadiusConfig.config_file)
     try:
         config = dict(
             line.rstrip("\n").split(None, 1)
             for line in open(main_config_file)
             if len(line.split(None, 1)) == 2 and not line.startswith("#"))
         secrets = dict(
             line.rstrip("\n").split(None, 1)
             for line in open(config["servers"])
             if len(line.split(None, 1)) == 2 and not line.startswith("#"))
         server = config["acctserver"]
         try:
             server, acctport = server.split(":")
             acctport = int(acctport)
         except ValueError:
             acctport = 1813
         secret = secrets[server]
         dicts = [RadiusDictionaryFile(config["dictionary"])]
         if RadiusConfig.additional_dictionary:
             additional_dictionary = process.config_file(
                 RadiusConfig.additional_dictionary)
             if additional_dictionary:
                 dicts.append(RadiusDictionaryFile(additional_dictionary))
             else:
                 log.warn(
                     "Could not load additional RADIUS dictionary file: `%s'"
                     % RadiusConfig.additional_dictionary)
         raddict = pyrad.dictionary.Dictionary(*dicts)
         timeout = int(config["radius_timeout"])
         retries = int(config["radius_retries"])
     except Exception:
         log.fatal("cannot read the RADIUS configuration file")
         raise
     pyrad.client.Client.__init__(self, server, 1812, acctport, secret,
                                  raddict)
     self.timeout = timeout
     self.retries = retries
     if "bindaddr" in config and config["bindaddr"] != "*":
         self.bind((config["bindaddr"], 0))
     EventQueue.__init__(self, self.do_accounting)
Ejemplo n.º 37
0
 def __init__(self, stream):
     self.manager = stream.session.manager
     self._remote_sdp = None
     self.is_on_hold = False
     self.uses_ice = False
     while True:
         self.listener_rtp = None
         self.ports = port_rtp, port_rtcp = self.manager.get_ports()
         try:
             self.listener_rtp = reactor.listenUDP(port_rtp, StreamListenerProtocol(), interface=Config.relay_ip)
             self.listener_rtcp = reactor.listenUDP(port_rtcp, StreamListenerProtocol(), interface=Config.relay_ip)
         except CannotListenError:
             if self.listener_rtp is not None:
                 self.listener_rtp.stopListening()
             self.manager.set_bad_ports(self.ports)
             log.warn("Cannot use port pair %d/%d" % self.ports)
         else:
             break
Ejemplo n.º 38
0
 def send_command(self, command, headers):
     try:
         parsed_headers = dict(header.split(": ", 1) for header in headers)
     except:
         raise RelayError("Could not parse headers from OpenSIPs")
     try:
         call_id = parsed_headers["call_id"]
     except KeyError:
         raise RelayError("Missing call_id header")
     session = self.sessions.get(call_id, None)
     if session and session.expire_time is None:
         relay = session.relay_ip
         if relay not in self.relays:
             raise RelayError(
                 "Relay for this session (%s) is no longer connected" %
                 relay)
         return self.relays[relay].send_command(command, headers)
     ## We do not have a session for this call_id or the session is already expired
     if command == "update":
         preferred_relay = parsed_headers.get("media_relay")
         try_relays = deque(
             protocol for protocol in self.relays.itervalues()
             if protocol.active and protocol.ip != preferred_relay)
         random.shuffle(try_relays)
         if preferred_relay is not None:
             protocol = self.relays.get(preferred_relay)
             if protocol is not None and protocol.active:
                 try_relays.appendleft(protocol)
             else:
                 log.warn("user requested media_relay %s is not available" %
                          preferred_relay)
         defer = self._try_next(try_relays, command, headers)
         defer.addCallback(self._add_session, try_relays, call_id,
                           parsed_headers)
         return defer
     elif command == 'remove' and session:
         ## This is the remove we received for an expired session for which we triggered dialog termination
         del self.sessions[call_id]
         return 'removed'
     else:
         raise RelayError(
             "Got `%s' command from OpenSIPS for unknown session with call-id `%s'"
             % (command, call_id))
Ejemplo n.º 39
0
 def lineReceived(self, line):
     #        log.debug("Got reply from rating engine: %s" % line) #DEBUG
     if not line:
         return
     if self.__timeout_call is not None:
         self.__timeout_call.cancel()
     if self.__request is None:
         log.warn("Got reply for unexisting request: %s" % line)
         return
     try:
         self._respond(
             getattr(self, '_PE_%s' % self.__request.command.lower())(line))
     except AttributeError:
         self._respond(
             "Unknown command in request. Cannot handle reply. Reply is: %s"
             % line,
             success=False)
     except Exception, e:
         self._respond(str(e), success=False)
Ejemplo n.º 40
0
 def __new__(typ, value):
     if isinstance(value, str):
         try:
             f = open(value, 'rt')
         except:
             log.warn("Private key file '%s' could not be open" % value)
             return None
         try:
             try:
                 return crypto.load_privatekey(crypto.FILETYPE_PEM,
                                               f.read())
             except crypto.Error as e:
                 log.warn("Private key file '%s' could not be loaded: %s" %
                          (value, str(e)))
                 return None
         finally:
             f.close()
     else:
         raise TypeError('value should be a string')
Ejemplo n.º 41
0
 def __new__(cls, description):
     if description is None:
         return description
     elif isinstance(description, (list, tuple)):
         return [NetworkRange(x) for x in description] or None
     elif not isinstance(description, basestring):
         raise TypeError("value must be a string, list, tuple or None")
     if description.lower() == 'none':
         return None
     lst = re.split(r'\s*,\s*', description)
     ranges = []
     for x in lst:
         try:
             range = NetworkRange(x)
         except NameError:
             log.warn("couldn't resolve hostname: `%s' (ignored)" % x)
         except ValueError:
             log.warn("Invalid network specification: `%s' (ignored)" % x)
         else:
             ranges.append(range)
     return ranges or None
Ejemplo n.º 42
0
    def on_startup(self):
        ## First set up listening on the unix socket
        try:
            gid = grp.getgrnam(self.group)[2]
            mode = 0660
        except (KeyError, IndexError):
            gid = -1
            mode = 0666
        self.listening = reactor.listenUNIX(address=self.path, factory=CallControlFactory(self))
        ## Make it writable only to the SIP proxy group members
        try:
            os.chown(self.path, -1, gid)
            os.chmod(self.path, mode)
        except OSError:
            log.warn("Couldn't set access rights for %s" % self.path)
            log.warn("OpenSIPS may not be able to communicate with us!")

        ## Then setup the CallsMonitor
        self.monitor = CallsMonitor(CallControlConfig.checkInterval, self)
        ## Open the connection to the rating engines
        self.engines = RatingEngineConnections()
Ejemplo n.º 43
0
 def read(cls, cfgfile=None, section=None):
     """Read the settings from the given file and section"""
     cfgfile = cfgfile or cls.__cfgfile__
     section = section or cls.__section__
     if None in (cfgfile, section):
         raise ValueError("A config file and section are required for reading settings")
     if isinstance(cfgfile, ConfigFile):
         config_file = cfgfile
     else:
         config_file = cls.__cfgtype__(cfgfile)
     if isinstance(section, basestring):
         section_list = (section,)
     else:
         section_list = section
     for section in section_list:
         for name, value in config_file.get_section(section, filter=cls.__settings__, default=[]):
             try:
                 setattr(cls, name, value)
             except Exception, e:
                 msg = "ignoring invalid config value: %s.%s=%s (%s)." % (section, name, value, e)
                 log.warn(msg, **config_file.log_context)
Ejemplo n.º 44
0
 def __new__(cls, description):
     if description is None:
         return description
     elif isinstance(description, (list, tuple)):
         return [NetworkRange(x) for x in description] or None
     elif not isinstance(description, basestring):
         raise TypeError("value must be a string, list, tuple or None")
     if description.lower()=='none':
         return None
     lst = re.split(r'\s*,\s*', description)
     ranges = []
     for x in lst:
         try:
             range = NetworkRange(x)
         except NameError:
             log.warn("couldn't resolve hostname: `%s' (ignored)" % x)
         except ValueError:
             log.warn("Invalid network specification: `%s' (ignored)" % x)
         else:
             ranges.append(range)
     return ranges or None
Ejemplo n.º 45
0
 def __read__(cls, cfgfile=None, section=None):
     """Update settings by reading them from the given file and section"""
     cfgfile = cfgfile or cls.__cfgfile__
     section = section or cls.__section__
     if None in (cfgfile, section):
         raise ValueError("A config file and section are required for reading settings")
     if isinstance(cfgfile, ConfigFile):
         config_file = cfgfile
     else:
         config_file = cls.__cfgtype__(cfgfile)
     if isinstance(section, basestring):
         section_list = (section,)
     else:
         section_list = section
     cls.__trace__("reading %s from %s requested as '%s'", cls.__name__, ', '.join(config_file.files), config_file.filename)
     for section in section_list:
         cls.__trace__("reading section '%s'", section)
         for name, value in config_file.get_section(section, filter=cls.__settings__, default=[]):
             try:
                 setattr(cls, name, value)
             except Exception, why:
                 msg = "ignoring invalid config value: %s.%s=%s (%s)." % (section, name, value, why)
                 log.warn(msg, **config_file.log_context)
Ejemplo n.º 46
0
 def __init__(self, stream):
     self.manager = stream.session.manager
     self._remote_sdp = None
     self.is_on_hold = False
     self.uses_ice = False
     while True:
         self.listener_rtp = None
         self.ports = port_rtp, port_rtcp = self.manager.get_ports()
         try:
             self.listener_rtp = reactor.listenUDP(
                 port_rtp,
                 StreamListenerProtocol(),
                 interface=RelayConfig.relay_ip)
             self.listener_rtcp = reactor.listenUDP(
                 port_rtcp,
                 StreamListenerProtocol(),
                 interface=RelayConfig.relay_ip)
         except CannotListenError:
             if self.listener_rtp is not None:
                 self.listener_rtp.stopListening()
             self.manager.set_bad_ports(self.ports)
             log.warn("Cannot use port pair %d/%d" % self.ports)
         else:
             break
Ejemplo n.º 47
0
 def __new__(cls, value):
     if value is None:
         return None
     elif not isinstance(value, basestring):
         raise TypeError("value must be a string, unicode or None")
     if value.strip() == '':
         return None
     valid_uris = []
     for uri in re.split(r'\s*,\s*', value):
         scheme, host, path, params, query, fragment = urlparse.urlparse(uri)
         if host and scheme in ('http', 'https'):
             for u in valid_uris:
                 if u == uri or uri.startswith(u) or u.startswith(uri):
                     log.warn("ignoring XCAP Root URI %r (similar to %r)" % (uri, u))
                     break
             else:
                 valid_uris.append(uri)
         else:
             log.warn("Invalid XCAP Root URI: %r" % uri)
     if not valid_uris:
         return None
     instance = str.__new__(cls, valid_uris[0])
     instance.uris = tuple(valid_uris)
     return instance
Ejemplo n.º 48
0
 def __new__(typ, value):
     if isinstance(value, basestring):
         path = process.config_file(value)
         if path is None:
             log.warn("Private key file '%s' is not readable" % value)
             return None
         try:
             f = open(path, 'rt')
         except:
             log.warn("Private key file '%s' could not be open" % value)
             return None
         try:
             try:
                 return crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
             except crypto.Error, e:
                 log.warn("Private key file '%s' could not be loaded: %s" % (value, str(e)))
                 return None
         finally:
             f.close()
     else:
         raise TypeError, 'value should be a string'
Ejemplo n.º 49
0
 def __new__(typ, value):
     if isinstance(value, basestring):
         path = process.config_file(value)
         if path is None:
             log.warn("Private key file '%s' is not readable" % value)
             return None
         try:
             f = open(path, 'rt')
         except:
             log.warn("Private key file '%s' could not be open" % value)
             return None
         try:
             try:
                 return crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
             except crypto.Error, e:
                 log.warn("Private key file '%s' could not be loaded: %s" % (value, str(e)))
                 return None
         finally:
             f.close()
     else:
         raise TypeError, 'value should be a string'
Ejemplo n.º 50
0
 def _relay_error(self, failure, try_relays, command, headers):
     failure.trap(RelayError)
     failed_relay = try_relays.popleft()
     log.warn("Relay %s failed: %s" % (failed_relay, failure.value))
     return self._try_next(try_relays, command, headers)
Ejemplo n.º 51
0
    private_key = ConfigSetting(type=PrivateKey, value=None)

if ServerConfig.root is None:
    log.fatal("the XCAP root URI is not defined")
    sys.exit(1)

if ServerConfig.backend is None:
    log.fatal("OpenXCAP needs a backend to be specified in order to run")
    sys.exit(1)


# Increase the system limit for the maximum number of open file descriptors
try:
    _resource.setrlimit(_resource.RLIMIT_NOFILE, (99999, 99999))
except ValueError:
    log.warn("Could not raise open file descriptor limit")


class XCAPRoot(resource.Resource, resource.LeafResource):
    addSlash = True

    def allowedMethods(self):
        # not used , but methods were already checked by XCAPAuthResource
        return ('GET', 'PUT', 'DELETE')

    def resourceForURI(self, xcap_uri):
        application = getApplicationForURI(xcap_uri)
        if not xcap_uri.node_selector:
            return XCAPDocument(xcap_uri, application)
        else:
            terminal_selector = xcap_uri.node_selector.terminal_selector
Ejemplo n.º 52
0
 def __on_exit(self):
     if self._pidfile:
         try:
             os.unlink(self._pidfile)
         except OSError, why:
             log.warn("unable to delete pidfile %s: %s" % (self._pidfile, str(why)))
Ejemplo n.º 53
0
 def __new__(cls, value):
     proposed_backends = set(StringList.__new__(cls, value))
     invalid_names = proposed_backends - cls._valid_backends
     for name in invalid_names:
         log.warn("Ignoring invalid accounting module name: `%s'" % name)
     return list(proposed_backends & cls._valid_backends)
Ejemplo n.º 54
0
            raise TypeError("domain name must be a string, unicode or None")
        if name.lower() == 'none':
            return None
        return name

class ThorNetworkConfig(ConfigSection):
    __cfgfile__ = configuration_filename
    __section__ = 'ThorNetwork'

    domain = ConfigSetting(type=SIPThorDomain, value=None)
    node_ip = host.default_ip


if ThorNetworkConfig.domain is None:
    ## SIP Thor is installed but disabled. Fake an ImportError to start in standalone media relay mode.
    log.warn("SIP Thor is installed but disabled from the configuration")
    raise ImportError("SIP Thor is disabled")


class SIPThorMediaRelayBase(EventServiceClient, SRVMediaRelayBase):
    topics = ["Thor.Members"]

    def __init__(self):
        self.node = GenericThorEntity(ThorNetworkConfig.node_ip, ["media_relay"], version=__version__)
        self.presence_message = ThorEvent('Thor.Presence', self.node.id)
        self.shutdown_message = ThorEvent('Thor.Leave', self.node.id)
        credentials = X509Credentials(cert_name='relay')
        credentials.session_params.compressions = (COMP_LZO, COMP_DEFLATE, COMP_NULL)
        self.sipthor_dispatchers = []
        self.additional_dispatchers = []
        EventServiceClient.__init__(self, ThorNetworkConfig.domain, credentials)
Ejemplo n.º 55
0
    __cfgfile__ = xcap.__cfgfile__
    __section__ = 'TLS'

    certificate = ConfigSetting(type=Certificate, value=None)
    private_key = ConfigSetting(type=PrivateKey, value=None)

if ServerConfig.root is None:
    log.fatal("the XCAP root URI is not defined")
    sys.exit(1)

if ServerConfig.backend is None:
    log.fatal("OpenXCAP needs a backend to be specified in order to run")
    sys.exit(1)

if ServerConfig.port:
    log.warn("Port setting is deprecated, please specify the port in the root setting")


class XCAPRoot(resource.Resource, resource.LeafResource):
    addSlash = True

    def allowedMethods(self):
        # not used , but methods were already checked by XCAPAuthResource
        return ('GET', 'PUT', 'DELETE')

    def resourceForURI(self, xcap_uri):
        application = getApplicationForURI(xcap_uri)
        if not xcap_uri.node_selector:
            return XCAPDocument(xcap_uri, application)
        else:
            terminal_selector = xcap_uri.node_selector.terminal_selector
Ejemplo n.º 56
0
 def _relay_error(self, failure, try_relays, command, headers):
     failure.trap(RelayError)
     failed_relay = try_relays.popleft()
     log.warn("Relay %s failed: %s" % (failed_relay, failure.value))
     return self._try_next(try_relays, command, headers)
Ejemplo n.º 57
0
    def _restore_calls(self):
        calls_file = '%s/%s' % (process.runtime_directory, backup_calls_file)
        try:
            f = open(calls_file, 'r')
        except:
            pass
        else:
            try:
                self.calls = cPickle.load(f)
            except Exception, why:
                log.warn("Failed to load calls saved in the previous session: %s" % why)
            f.close()
            try:    os.unlink(calls_file)
            except: pass
            if self.calls:
                log.info("Restoring calls saved previously: %s" % str(self.calls.keys()))
                ## the calls in the 2 sets below are never overlapping because closed and terminated
                ## calls have different database fingerprints. so the dictionary update below is safe
                try:
                    db = self.db if self.db is not None else RadiusDatabase()
                    try:
                        terminated = db.query(RadiusDatabase.RadiusTask(None, 'terminated', calls=self.calls))   ## calls terminated by caller/called
                        didtimeout = db.query(RadiusDatabase.RadiusTask(None, 'timedout', calls=self.calls))     ## calls closed by mediaproxy after a media timeout
                    finally:
                        if self.db is None:
                            db.close()
                except RadiusDatabaseError, e:
                    log.error("Could not query database: %s" % e)
                else:
                    for callid, call in self.calls.items():
                        callinfo = terminated.get(callid) or didtimeout.get(callid)
                        if callinfo:
                            ## call already terminated or did timeout in mediaproxy
                            del self.calls[callid]
                            callinfo['call'] = call
                            call.timer = None
                            continue
                    ## close all calls that were already terminated or did timeout
                    count = 0
                    for callinfo in terminated.values():
                        call = callinfo.get('call')
                        if call is not None:
                            call.end(calltime=callinfo['duration'])
                            count += 1
                    for callinfo in didtimeout.values():
                        call = callinfo.get('call')
                        if call is not None:
                            call.end(sendbye=True)
                            count += 1
                    if count > 0:
                        log.info("Removed %d already terminated call%s" % (count, 's'*(count!=1)))
                for callid, call in self.calls.items():
                    call.application = self
                    if call.timer == 'running':
                        now = time.time()
                        remain = call.starttime + call.timelimit - now
                        if remain < 0:
                            call.timelimit = int(round(now - call.starttime))
                            remain = 0
                        call._setup_timer(remain)
                        call.timer.start()
                    elif call.timer == 'idle':
                        call._setup_timer()

                    # also restore users table
                    self.users.setdefault(call.billingParty, []).append(callid)
Ejemplo n.º 58
0
    private_key = ConfigSetting(type=PrivateKey, value=None)

if ServerConfig.root is None:
    log.fatal("the XCAP root URI is not defined")
    sys.exit(1)

if ServerConfig.backend is None:
    log.fatal("OpenXCAP needs a backend to be specified in order to run")
    sys.exit(1)


# Increase the system limit for the maximum number of open file descriptors
try:
    _resource.setrlimit(_resource.RLIMIT_NOFILE, (99999, 99999))
except ValueError:
    log.warn("Could not raise open file descriptor limit")


class XCAPRoot(resource.Resource, resource.LeafResource):
    addSlash = True

    def allowedMethods(self):
        # not used , but methods were already checked by XCAPAuthResource
        return ('GET', 'PUT', 'DELETE')

    def resourceForURI(self, xcap_uri):
        application = getApplicationForURI(xcap_uri)
        if not xcap_uri.node_selector:
            return XCAPDocument(xcap_uri, application)
        else:
            terminal_selector = xcap_uri.node_selector.terminal_selector