Search is not available for this dataset
text
stringlengths
75
104k
def get_int_range_validator(start, stop): """Return an integer range validator to be used with `add_setting`. :Parameters: - `start`: minimum value for the integer - `stop`: the upper bound (maximum value + 1) :Types: - `start`: `int` - `stop`: `i...
def list_all(cls, basic = None): """List known settings. :Parameters: - `basic`: When `True` then limit output to the basic settings, when `False` list only the extra settings. """ if basic is None: return [s for s in cls._defs] else: ...
def get_arg_parser(cls, settings = None, option_prefix = u'--', add_help = False): """Make a command-line option parser. The returned parser may be used as a parent parser for application argument parser. :Parameters: ...
def are_domains_equal(domain1, domain2): """Compare two International Domain Names. :Parameters: - `domain1`: domains name to compare - `domain2`: domains name to compare :Types: - `domain1`: `unicode` - `domain2`: `unicode` :return: True `domain1` and `domain2` are equ...
def _validate_ip_address(family, address): """Check if `address` is valid IP address and return it, in a normalized form. :Parameters: - `family`: ``socket.AF_INET`` or ``socket.AF_INET6`` - `address`: the IP address to validate """ try: info = socket.getaddrinfo(address, 0,...
def __from_unicode(cls, data, check = True): """Return jid tuple from an Unicode string. :Parameters: - `data`: the JID string - `check`: when `False` then the JID is not checked for specification compliance. :Return: (localpart, domainpart, resourcepart) ...
def __prepare_local(data): """Prepare localpart of the JID :Parameters: - `data`: localpart of the JID :Types: - `data`: `unicode` :raise JIDError: if the local name is too long. :raise pyxmpp.xmppstringprep.StringprepError: if the local name...
def __prepare_domain(data): """Prepare domainpart of the JID. :Parameters: - `data`: Domain part of the JID :Types: - `data`: `unicode` :raise JIDError: if the domain name is too long. """ # pylint: disable=R0912 if not data: ...
def __prepare_resource(data): """Prepare the resourcepart of the JID. :Parameters: - `data`: Resourcepart of the JID :raise JIDError: if the resource name is too long. :raise pyxmpp.xmppstringprep.StringprepError: if the resourcepart fails Resourceprep preparati...
def as_unicode(self): """Unicode string JID representation. :return: JID as Unicode string.""" result = self.domain if self.local: result = self.local + u'@' + result if self.resource: result = result + u'/' + self.resource if not JID.cache.has_ke...
def is_ipv6_available(): """Check if IPv6 is available. :Return: `True` when an IPv6 socket can be created. """ try: socket.socket(socket.AF_INET6).close() except (socket.error, AttributeError): return False return True
def is_ipv4_available(): """Check if IPv4 is available. :Return: `True` when an IPv4 socket can be created. """ try: socket.socket(socket.AF_INET).close() except socket.error: return False return True
def shuffle_srv(records): """Randomly reorder SRV records using their weights. :Parameters: - `records`: SRV records to shuffle. :Types: - `records`: sequence of :dns:`dns.rdtypes.IN.SRV` :return: reordered records. :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`""" if not rec...
def reorder_srv(records): """Reorder SRV records using their priorities and weights. :Parameters: - `records`: SRV records to shuffle. :Types: - `records`: `list` of :dns:`dns.rdtypes.IN.SRV` :return: reordered records. :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`""" record...
def stop(self): """Stop the resolver threads. """ with self.lock: for dummy in self.threads: self.queue.put(None)
def _start_thread(self): """Start a new working thread unless the maximum number of threads has been reached or the request queue is empty. """ with self.lock: if self.threads and self.queue.empty(): return if len(self.threads) >= self.max_threads:...
def _run(self, thread_n): """The thread function.""" try: logger.debug("{0!r}: entering thread #{1}" .format(self, thread_n)) resolver = self._make_resolver() while True: request = self.queue.get() ...
def resolve_address(self, hostname, callback, allow_cname = True): """Start looking up an A or AAAA record. `callback` will be called with a list of (family, address) tuples on success. Family is :std:`socket.AF_INET` or :std:`socket.AF_INET6`, the address is IPv4 or IPv6 literal. The l...
def send_message(source_jid, password, target_jid, body, subject = None, message_type = "chat", message_thread = None, settings = None): """Star an XMPP session and send a message, then exit. :Parameters: - `source_jid`: sender JID - `password`: sender password - `target...
def connect(self,server=None,port=None): """Establish a client connection to a server. [component only] :Parameters: - `server`: name or address of the server to use. If not given then use the one specified when creating the object. - `port`: port number ...
def _connect(self,server=None,port=None): """Same as `ComponentStream.connect` but assume `self.lock` is acquired.""" if self.me.node or self.me.resource: raise Value("Component JID may have only domain defined") if not server: server=self.server if not port: ...
def _compute_handshake(self): """Compute the authentication handshake value. :return: the computed hash value. :returntype: `str`""" return hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.secret)).hexdigest()
def _auth(self): """Authenticate on the server. [component only]""" if self.authenticated: self.__logger.debug("_auth: already authenticated") return self.__logger.debug("doing handshake...") hash_value=self._compute_handshake() n=common_root.newT...
def _process_node(self,node): """Process first level element of the stream. Handle component handshake (authentication) element, and treat elements in "jabber:component:accept", "jabber:client" and "jabber:server" equally (pass to `self.process_stanza`). All other elements are p...
def _set_state(self, state): """Set `_state` and notify any threads waiting for the change. """ logger.debug(" _set_state({0!r})".format(state)) self._state = state self._state_cond.notify()
def connect(self, addr, port = None, service = None): """Start establishing TCP connection with given address. One of: `port` or `service` must be provided and `addr` must be a domain name and not an IP address if `port` is not given. When `service` is given try an SRV lookup for that ...
def _connect(self, addr, port, service): """Same as `connect`, but assumes `lock` acquired. """ self._dst_name = addr self._dst_port = port family = None try: res = socket.getaddrinfo(addr, port, socket.AF_UNSPEC, socket.SOCK_ST...
def _resolve_srv(self): """Start resolving the SRV record. """ resolver = self.settings["dns_resolver"] # pylint: disable=W0621 self._set_state("resolving-srv") self.event(ResolvingSRVEvent(self._dst_name, self._dst_service)) resolver.resolve_srv(self._dst_name, self._dst...
def _got_srv(self, addrs): """Handle SRV lookup result. :Parameters: - `addrs`: properly sorted list of (hostname, port) tuples """ with self.lock: if not addrs: self._dst_service = None if self._dst_port: self....
def _resolve_hostname(self): """Start hostname resolution for the next name to try. [called with `lock` acquired] """ self._set_state("resolving-hostname") resolver = self.settings["dns_resolver"] # pylint: disable=W0621 logger.debug("_dst_nameports: {0!r}".format(self._...
def _got_addresses(self, name, port, addrs): """Handler DNS address record lookup result. :Parameters: - `name`: the name requested - `port`: port number to connect to - `addrs`: list of (family, address) tuples """ with self.lock: if not ...
def _start_connect(self): """Start connecting to the next address on the `_dst_addrs` list. [ called with `lock` acquired ] """ family, addr = self._dst_addrs.pop(0) self._socket = socket.socket(family, socket.SOCK_STREAM) self._socket.setblocking(False) self._d...
def _connected(self): """Handle connection success.""" self._auth_properties['remote-ip'] = self._dst_addr[0] if self._dst_service: self._auth_properties['service-domain'] = self._dst_name if self._dst_hostname is not None: self._auth_properties['service-hostname'...
def _continue_connect(self): """Continue connecting. [called with `lock` acquired] :Return: `True` when just connected """ try: self._socket.connect(self._dst_addr) except socket.error, err: logger.debug("Connect error: {0}".format(err)) ...
def _write(self, data): """Write raw data to the socket. :Parameters: - `data`: data to send :Types: - `data`: `bytes` """ OUT_LOGGER.debug("OUT: %r", data) if self._hup or not self._socket: raise PyXMPPIOError(u"Connection closed.") ...
def set_target(self, stream): """Make the `stream` the target for this transport instance. The 'stream_start', 'stream_end' and 'stream_element' methods of the target will be called when appropriate content is received. :Parameters: - `stream`: the stream handler to receive...
def send_stream_head(self, stanza_namespace, stream_from, stream_to, stream_id = None, version = u'1.0', language = None): """ Send stream head via the transport. :Parameters: - `stanza_namespace`: namespace of stream stanzas (e.g. 'jabber:clien...
def send_stream_tail(self): """ Send stream tail via the transport. """ with self.lock: if not self._socket or self._hup: logger.debug(u"Cannot send stream closing tag: already closed") return data = self._serializer.emit_tail() ...
def send_element(self, element): """ Send an element via the transport. """ with self.lock: if self._eof or self._socket is None or not self._serializer: logger.debug("Dropping element: {0}".format( element_to_un...
def prepare(self): """When connecting start the next connection step and schedule next `prepare` call, when connected return `HandlerReady()` """ result = HandlerReady() logger.debug("TCPTransport.prepare(): state: {0!r}".format(self._state)) with self.lock: i...
def is_readable(self): """ :Return: `True` when the I/O channel can be read """ return self._socket is not None and not self._eof and ( self._state in ("connected", "closing") or self._state == "tls-handshake" ...
def wait_for_readability(self): """ Stop current thread until the channel is readable. :Return: `False` if it won't be readable (e.g. is closed) """ with self.lock: while True: if self._socket is None or self._eof: return False ...
def wait_for_writability(self): """ Stop current thread until the channel is writable. :Return: `False` if it won't be readable (e.g. is closed) """ with self.lock: while True: if self._state in ("closing", "closed", "aborted"): re...
def handle_write(self): """ Handle the 'channel writable' state. E.g. send buffered data via a socket. """ with self.lock: logger.debug("handle_write: queue: {0!r}".format(self._write_queue)) try: job = self._write_queue.popleft() ...
def starttls(self, **kwargs): """Request a TLS handshake on the socket ans switch to encrypted output. The handshake will start after any currently buffered data is sent. :Parameters: - `kwargs`: arguments for :std:`ssl.wrap_socket` """ with self.lock: ...
def getpeercert(self): """Return the peer certificate. :ReturnType: `pyxmpp2.cert.Certificate` """ with self.lock: if not self._socket or self._tls_state != "connected": raise ValueError("Not TLS-connected") return get_certificate_from_ssl_socket(...
def _initiate_starttls(self, **kwargs): """Initiate starttls handshake over the socket. """ if self._tls_state == "connected": raise RuntimeError("Already TLS-connected") kwargs["do_handshake_on_connect"] = False logger.debug("Wrapping the socket into ssl") se...
def _continue_tls_handshake(self): """Continue a TLS handshake.""" try: logger.debug(" do_handshake()") self._socket.do_handshake() except ssl.SSLError, err: if err.args[0] == ssl.SSL_ERROR_WANT_READ: self._tls_state = "want_read" ...
def handle_read(self): """ Handle the 'channel readable' state. E.g. read from a socket. """ with self.lock: logger.debug("handle_read()") if self._eof or self._socket is None: return if self._state == "tls-handshake": w...
def handle_hup(self): """ Handle the 'channel hungup' state. The handler should not be writable after this. """ with self.lock: if self._state == 'connecting' and self._dst_addrs: self._hup = False self._set_state("connect") ...
def handle_err(self): """ Handle an error reported. """ with self.lock: if self._state == 'connecting' and self._dst_addrs: self._hup = False self._set_state("connect") return self._socket.close() self._s...
def disconnect(self): """Disconnect the stream gracefully.""" logger.debug("TCPTransport.disconnect()") with self.lock: if self._socket is None: if self._state != "closed": self.event(DisconnectedEvent(self._dst_addr)) self._set...
def _close(self): """Same as `_close` but expects `lock` acquired. """ if self._state != "closed": self.event(DisconnectedEvent(self._dst_addr)) self._set_state("closed") if self._socket is None: return try: self._socket.shutdown(so...
def _feed_reader(self, data): """Feed the stream reader with data received. [ called with `lock` acquired ] If `data` is None or empty, then stream end (peer disconnected) is assumed and the stream is closed. `lock` is acquired during the operation. :Parameters: ...
def event(self, event): """Pass an event to the target stream or just log it.""" logger.debug(u"TCP transport event: {0}".format(event)) if self._stream: event.stream = self._stream self._event_queue.put(event)
def start(self, tag, attrs): """Handle the start tag. Call the handler's 'stream_start' methods with an empty root element if it is top level. For lower level tags use :etree:`ElementTree.TreeBuilder` to collect them. """ if self._level == 0: self._r...
def end(self, tag): """Handle an end tag. Call the handler's 'stream_end' method with an the root element (built by the `start` method). On the first level below root, sent the built element tree to the handler via the 'stanza methods'. Any tag below will be just added...
def feed(self, data): """Feed the parser with a chunk of data. Apropriate methods of `handler` will be called whenever something interesting is found. :Parameters: - `data`: the chunk of data to parse. :Types: - `data`: `str`""" with self.lock: ...
def _from_xml(self, element): """Initialize an ErrorElement object from an XML element. :Parameters: - `element`: XML element to be decoded. :Types: - `element`: :etree:`ElementTree.Element` """ # pylint: disable-msg=R0912 if element.tag != self.e...
def as_xml(self): """Return the XML error representation. :returntype: :etree:`ElementTree.Element`""" result = ElementTree.Element(self.error_qname) result.append(deepcopy(self.condition)) if self.text: text = ElementTree.SubElement(result, self.text_qname) ...
def _from_xml(self, element): """Initialize an ErrorElement object from an XML element. :Parameters: - `element`: XML element to be decoded. :Types: - `element`: :etree:`ElementTree.Element` """ ErrorElement._from_xml(self, element) error_type = e...
def as_xml(self, stanza_namespace = None): # pylint: disable-msg=W0221 """Return the XML error representation. :Parameters: - `stanza_namespace`: namespace URI of the containing stanza :Types: - `stanza_namespace`: `unicode` :returntype: :etree:`ElementTree.Elem...
def run(self): """The thread function. First, call the handler's 'prepare' method until it returns `HandlerReady` then loop waiting for the socket input and calling 'handle_read' on the handler. """ # pylint: disable-msg=R0912 interval = self.settings["poll_inter...
def run(self): """The thread function. Loop waiting for the handler and socket being writable and calling `interfaces.IOHandler.handle_write`. """ while not self._quit: interval = self.settings["poll_interval"] if self.io_handler.is_writable(): ...
def run(self): """The thread function. Calls `self.run()` and if it raises an exception, stores it in self.exc_info and exc_queue """ logger.debug("{0}: entering thread".format(self.name)) while True: try: self.event_dispatcher.loop() excep...
def run(self): """The thread function.""" # pylint: disable-msg=W0212 timeout = self.method._pyxmpp_timeout recurring = self.method._pyxmpp_recurring while not self._quit and timeout is not None: if timeout: time.sleep(timeout) if self._qui...
def _run_io_threads(self, handler): """Start threads for an IOHandler. """ reader = ReadingThread(self.settings, handler, daemon = self.daemon, exc_queue = self.exc_queue) writter = WrittingThread(self.settings, handler, daemon = self.daemo...
def _remove_io_handler(self, handler): """Remove an IOHandler from the pool. """ if handler not in self.io_handlers: return self.io_handlers.remove(handler) for thread in self.io_threads: if thread.io_handler is handler: thread.stop()
def _add_timeout_handler(self, handler): """Add a TimeoutHandler to the pool. """ self.timeout_handlers.append(handler) if self.event_thread is None: return self._run_timeout_threads(handler)
def _run_timeout_threads(self, handler): """Start threads for a TimeoutHandler. """ # pylint: disable-msg=W0212 for dummy, method in inspect.getmembers(handler, callable): if not hasattr(method, "_pyxmpp_timeout"): continue thread = TimeoutThread(m...
def _remove_timeout_handler(self, handler): """Remove a TimeoutHandler from the pool. """ if handler not in self.timeout_handlers: return self.timeout_handlers.remove(handler) for thread in self.timeout_threads: if thread.method.im_self is handler: ...
def start(self, daemon = False): """Start the threads.""" self.daemon = daemon self.io_threads = [] self.event_thread = EventDispatcherThread(self.event_dispatcher, daemon = daemon, exc_queue = self.exc_queue) self.event_thread.start() ...
def stop(self, join = False, timeout = None): """Stop the threads. :Parameters: - `join`: join the threads (wait until they exit) - `timeout`: maximum time (in seconds) to wait when `join` is `True`). No limit when `timeout` is `None`. """ logger.d...
def loop_iteration(self, timeout = 0.1): """Wait up to `timeout` seconds, raise any exception from the threads. """ try: exc_info = self.exc_queue.get(True, timeout)[1] except Queue.Empty: return exc_type, exc_value, ext_stack = exc_info ra...
def _reset(self): """Reset the `LegacyClientStream` object state, making the object ready to handle new connections.""" ClientStream._reset(self) self.available_auth_methods = None self.auth_stanza = None self.registration_callback = None
def _post_connect(self): """Initialize authentication when the connection is established and we are the initiator.""" if not self.initiator: if "plain" in self.auth_methods or "digest" in self.auth_methods: self.set_iq_get_handler("query","jabber:iq:auth", ...
def _post_auth(self): """Unregister legacy authentication handlers after successfull authentication.""" ClientStream._post_auth(self) if not self.initiator: self.unset_iq_get_handler("query","jabber:iq:auth") self.unset_iq_set_handler("query","jabber:iq:auth")
def _try_auth(self): """Try to authenticate using the first one of allowed authentication methods left. [client only]""" if self.authenticated: self.__logger.debug("try_auth: already authenticated") return self.__logger.debug("trying auth: %r" % (self._au...
def auth_in_stage1(self,stanza): """Handle the first stage (<iq type='get'/>) of legacy ("plain" or "digest") authentication. [server only]""" self.lock.acquire() try: if "plain" not in self.auth_methods and "digest" not in self.auth_methods: iq=stanz...
def auth_in_stage2(self,stanza): """Handle the second stage (<iq type='set'/>) of legacy ("plain" or "digest") authentication. [server only]""" self.lock.acquire() try: if "plain" not in self.auth_methods and "digest" not in self.auth_methods: iq=stan...
def _auth_stage1(self): """Do the first stage (<iq type='get'/>) of legacy ("plain" or "digest") authentication. [client only]""" iq=Iq(stanza_type="get") q=iq.new_query("jabber:iq:auth") q.newTextChild(None,"username",to_utf8(self.my_jid.node)) q.newTextChild(No...
def auth_timeout(self): """Handle legacy authentication timeout. [client only]""" self.lock.acquire() try: self.__logger.debug("Timeout while waiting for jabber:iq:auth result") if self._auth_methods_left: self._auth_methods_left.pop(0) fi...
def auth_error(self,stanza): """Handle legacy authentication error. [client only]""" self.lock.acquire() try: err=stanza.get_error() ae=err.xpath_eval("e:*",{"e":"jabber:iq:auth:error"}) if ae: ae=ae[0].name else: ...
def auth_stage2(self,stanza): """Handle the first stage authentication response (result of the <iq type="get"/>). [client only]""" self.lock.acquire() try: self.__logger.debug("Procesing auth response...") self.available_auth_methods=[] if (st...
def _plain_auth_stage2(self, _unused): """Do the second stage (<iq type='set'/>) of legacy "plain" authentication. [client only]""" iq=Iq(stanza_type="set") q=iq.new_query("jabber:iq:auth") q.newTextChild(None,"username",to_utf8(self.my_jid.node)) q.newTextChild(...
def _plain_auth_in_stage2(self, username, _unused, stanza): """Handle the second stage (<iq type='set'/>) of legacy "plain" authentication. [server only]""" password=stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"}) if password: password=from_utf8(passwo...
def _digest_auth_stage2(self, _unused): """Do the second stage (<iq type='set'/>) of legacy "digest" authentication. [client only]""" iq=Iq(stanza_type="set") q=iq.new_query("jabber:iq:auth") q.newTextChild(None,"username",to_utf8(self.my_jid.node)) q.newTextChil...
def _digest_auth_in_stage2(self, username, _unused, stanza): """Handle the second stage (<iq type='set'/>) of legacy "digest" authentication. [server only]""" digest=stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}) if digest: digest=digest[0].getContent()...
def auth_finish(self, _unused): """Handle success of the legacy authentication.""" self.lock.acquire() try: self.__logger.debug("Authenticated") self.authenticated=True self.state_change("authorized",self.my_jid) self._post_auth() finally: ...
def registration_error(self, stanza): """Handle in-band registration error. [client only] :Parameters: - `stanza`: the error stanza received or `None` on timeout. :Types: - `stanza`: `pyxmpp.stanza.Stanza`""" self.lock.acquire() try: ...
def registration_form_received(self, stanza): """Handle registration form received. [client only] Call self.registration_callback with the registration form received as the argument. Use the value returned by the callback will be a filled-in form. :Parameters: ...
def submit_registration_form(self, form): """Submit a registration form. [client only] :Parameters: - `form`: the filled-in form. When form is `None` or its type is "cancel" the registration is to be canceled. :Types: - `form`: `pyxmpp.jabber.data...
def registration_success(self, stanza): """Handle registration success. [client only] Clean up registration stuff, change state to "registered" and initialize authentication. :Parameters: - `stanza`: the stanza received. :Types: - `stanza`: `pyx...
def _add_io_handler(self, handler): """Add an I/O handler to the loop.""" logger.debug('adding io handler: %r', handler) self._unprepared_handlers[handler] = None self._configure_io_handler(handler)
def _configure_io_handler(self, handler): """Register an io-handler at the polling object.""" if self.check_events(): return if handler in self._unprepared_handlers: old_fileno = self._unprepared_handlers[handler] prepared = self._prepare_io_handler(handler) ...
def _prepare_io_handler(self, handler): """Call the `interfaces.IOHandler.prepare` method and remove the handler from unprepared handler list when done. """ logger.debug(" preparing handler: {0!r}".format(handler)) ret = handler.prepare() logger.debug(" prepare result: ...
def _remove_io_handler(self, handler): """Remove an i/o-handler.""" if handler in self._unprepared_handlers: old_fileno = self._unprepared_handlers[handler] del self._unprepared_handlers[handler] else: old_fileno = handler.fileno() if old_fileno is not...
def _handle_event(self, handler, fd, event): """handle I/O events""" # pylint: disable=C0103 logger.debug('_handle_event: %r, %r, %r', handler, fd, event) if event & ioloop.IOLoop.ERROR: handler.handle_hup() if event & ioloop.IOLoop.READ: handler.handle_re...
def request_software_version(stanza_processor, target_jid, callback, error_callback = None): """Request software version information from a remote entity. When a valid response is received the `callback` will be handled with a `VersionPayload` instance as...
def _os_name_factory(settings): """Factory for the :r:`software_os setting` default. """ # pylint: disable-msg=W0613,W0142 return u"{0} {1} {2}".format(platform.system(), platform.release(), platform.machine())