Search is not available for this dataset
text
stringlengths
75
104k
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def __from_xml(self,value): """Initialize a `VCardAdr` object from and XML element. :Parameters: - `value`: field value as an XML node :Types: - `value`: `libxml2.xmlNode`""" n=value.children vns=get_node_ns(value) while n: if n.type!=...
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" return rfc2425encode("adr",u';'.join(quote_semicolon(val) for val in (self.pobox,self.extadr,self.street,self.locality, self.r...
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" return rfc2425encode("label",u"\n".join(self.lines), {"type":",".join(self.type)})
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" return rfc2425encode("geo",u';'.join(quote_semicolon(val) for val in (self.lat,self.lon)))
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" if self.unit: return rfc2425encode("org",u';'.join(quote_semicolon(val) for val in (self.name,self.unit))) e...
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" if self.uri: return rfc2425encode(self.name,self.uri,{"value":"uri"}) elif self.sound: return rfc2425encode(self.name,self.sound)
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" if s...
def rfc2426(self): """RFC2426-encode the field content. :return: the field in the RFC 2426 format. :returntype: `str`""" if self.type: p={"type":self.type} else: p={} return rfc2425encode(self.name,self.cred,p)
def as_xml(self,parent): """Create vcard-tmp XML representation of the field. :Parameters: - `parent`: parent node for the element :Types: - `parent`: `libxml2.xmlNode` :return: xml node with the field data. :returntype: `libxml2.xmlNode`""" n=pa...
def __make_fn(self): """Initialize the mandatory `self.fn` from `self.n`. This is a workaround for buggy clients which set only one of them.""" s=[] if self.n.prefix: s.append(self.n.prefix) if self.n.given: s.append(self.n.given) if self.n.middle...
def __from_xml(self,data): """Initialize a VCard object from XML node. :Parameters: - `data`: vcard to parse. :Types: - `data`: `libxml2.xmlNode`""" ns=get_node_ns(data) if ns and ns.getContent()!=VCARD_NS: raise ValueError("Not in the %r name...
def __from_rfc2426(self,data): """Initialize a VCard object from an RFC2426 string. :Parameters: - `data`: vcard to parse. :Types: - `data`: `libxml2.xmlNode`, `unicode` or `str`""" data=from_utf8(data) lines=data.split("\n") started=0 cur...
def _process_rfc2425_record(self,data): """Parse single RFC2425 record and update attributes of `self`. :Parameters: - `data`: the record (probably multiline) :Types: - `data`: `unicode`""" label,value=data.split(":",1) value=value.replace("\\n","\n").rep...
def rfc2426(self): """Get the RFC2426 representation of `self`. :return: the UTF-8 encoded RFC2426 representation. :returntype: `str`""" ret="begin:VCARD\r\n" ret+="version:3.0\r\n" for _unused, value in self.content.items(): if value is None: ...
def complete_xml_element(self, xmlnode, _unused): """Complete the XML node with `self` content. Should be overriden in classes derived from `StanzaPayloadObject`. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace,...
def update_state(self): """Update current status of the item and compute time of the next state change. :return: the new state. :returntype: :std:`datetime`""" self._lock.acquire() try: now = datetime.utcnow() if self.state == 'new': ...
def _deactivate(self): """Remove the fetcher from cache and mark it not active.""" self.cache.remove_fetcher(self) if self.active: self._deactivated()
def got_it(self, value, state = "new"): """Handle a successfull retrieval and call apriopriate handler. Should be called when retrieval succeeds. Do nothing when the fetcher is not active any more (after one of handlers was already called). :Parameters: - `value`: ...
def error(self, error_data): """Handle a retrieval error and call apriopriate handler. Should be called when retrieval fails. Do nothing when the fetcher is not active any more (after one of handlers was already called). :Parameters: - `error_data`: additional info...
def timeout(self): """Handle fetcher timeout and call apriopriate handler. Is called by the cache object and should _not_ be called by fetcher or application. Do nothing when the fetcher is not active any more (after one of handlers was already called).""" if not self.a...
def _try_backup_item(self): """Check if a backup item is available in cache and call the item handler if it is. :return: `True` if backup item was found. :returntype: `bool`""" if not self._backup_state: return False item = self.cache.get_item(self.address, s...
def request_object(self, address, state, object_handler, error_handler = None, timeout_handler = None, backup_state = None, timeout = timedelta(minutes=60), freshness_period = None, expiration_period = None, purge_period = None): """Request an object with given ad...
def invalidate_object(self, address, state = 'stale'): """Force cache item state change (to 'worse' state only). :Parameters: - `state`: the new state requested. :Types: - `state`: `str`""" self._lock.acquire() try: item = self.get_item(addres...
def add_item(self, item): """Add an item to the cache. Item state is updated before adding it (it will not be 'new' any more). :Parameters: - `item`: the item to add. :Types: - `item`: `CacheItem` :return: state of the item after addition. :retu...
def get_item(self, address, state = 'fresh'): """Get an item from the cache. :Parameters: - `address`: its address. - `state`: the worst state that is acceptable. :Types: - `address`: any hashable - `state`: `str` :return: the item or `No...
def update_item(self, item): """Update state of an item in the cache. Update item's state and remove the item from the cache if its new state is 'purged' :Parameters: - `item`: item to update. :Types: - `item`: `CacheItem` :return: new state of ...
def purge_items(self): """Remove purged and overlimit items from the cache. TODO: optimize somehow. Leave no more than 75% of `self.max_items` items in the cache.""" self._lock.acquire() try: il=self._items_list num_items = len(il) need_remov...
def tick(self): """Do the regular cache maintenance. Must be called from time to time for timeouts and cache old items purging to work.""" self._lock.acquire() try: now = datetime.utcnow() for t,f in list(self._active_fetchers): if t > now...
def remove_fetcher(self, fetcher): """Remove a running fetcher from the list of active fetchers. :Parameters: - `fetcher`: fetcher instance. :Types: - `fetcher`: `CacheFetcher`""" self._lock.acquire() try: for t, f in list(self._active_fetcher...
def set_fetcher(self, fetcher_class): """Set the fetcher class. :Parameters: - `fetcher_class`: the fetcher class. :Types: - `fetcher_class`: `CacheFetcher` based class """ self._lock.acquire() try: self._fetcher = fetcher_class ...
def request_object(self, object_class, address, state, object_handler, error_handler = None, timeout_handler = None, backup_state = None, timeout = None, freshness_period = None, expiration_period = None, purge_period = None): """Request an object of given class, with given a...
def tick(self): """Do the regular cache maintenance. Must be called from time to time for timeouts and cache old items purging to work.""" self._lock.acquire() try: for cache in self._caches.values(): cache.tick() finally: self._lo...
def register_fetcher(self, object_class, fetcher_class): """Register a fetcher class for an object class. :Parameters: - `object_class`: class to be retrieved by the fetcher. - `fetcher_class`: the fetcher class. :Types: - `object_class`: `classobj` ...
def unregister_fetcher(self, object_class): """Unregister a fetcher class for an object class. :Parameters: - `object_class`: class retrieved by the fetcher. :Types: - `object_class`: `classobj` """ self._lock.acquire() try: cache = se...
def _register_client_authenticator(klass, name): """Add a client authenticator class to `CLIENT_MECHANISMS_D`, `CLIENT_MECHANISMS` and, optionally, to `SECURE_CLIENT_MECHANISMS` """ # pylint: disable-msg=W0212 CLIENT_MECHANISMS_D[name] = klass items = sorted(CLIENT_MECHANISMS_D.items(), key = _k...
def _register_server_authenticator(klass, name): """Add a client authenticator class to `SERVER_MECHANISMS_D`, `SERVER_MECHANISMS` and, optionally, to `SECURE_SERVER_MECHANISMS` """ # pylint: disable-msg=W0212 SERVER_MECHANISMS_D[name] = klass items = sorted(SERVER_MECHANISMS_D.items(), key = _k...
def sasl_mechanism(name, secure, preference = 50): """Class decorator generator for `ClientAuthenticator` or `ServerAuthenticator` subclasses. Adds the class to the pyxmpp.sasl mechanism registry. :Parameters: - `name`: SASL mechanism name - `secure`: if the mechanims can be considered ...
def check_password(self, username, password, properties): """Check the password validity. Used by plain-text authentication mechanisms. Default implementation: retrieve a "plain" password for the `username` and `realm` using `self.get_password` and compare it with the password ...
def encode(self): """Base64-encode the data contained in the reply when appropriate. :return: encoded data. :returntype: `unicode` """ if self.data is None: return "" elif not self.data: return "=" else: ret = standard_b64encod...
def handle_authorized(self, event): """Send session esteblishment request if the feature was advertised by the server. """ stream = event.stream if not stream: return if not stream.initiator: return if stream.features is None: r...
def _decode_asn1_string(data): """Convert ASN.1 string to a Unicode string. """ if isinstance(data, BMPString): return bytes(data).decode("utf-16-be") else: return bytes(data).decode("utf-8")
def display_name(self): """Get human-readable subject name derived from the SubjectName or SubjectAltName field. """ if self.subject_name: return u", ".join( [ u", ".join( [ u"{0}={1}".format(k,v) for k, v in dn_tuple ] ) fo...
def get_jids(self): """Return JIDs for which this certificate is valid (except the domain wildcards). :Returtype: `list` of `JID` """ result = [] if ("XmppAddr" in self.alt_names or "DNS" in self.alt_names or "SRVName" in self....
def verify_server(self, server_name, srv_type = 'xmpp-client'): """Verify certificate for a server. :Parameters: - `server_name`: name of the server presenting the cerificate - `srv_type`: service type requested, as used in the SRV record :Types: - `server_na...
def verify_jid_against_common_name(self, jid): """Return `True` if jid is listed in the certificate commonName. :Parameters: - `jid`: JID requested (domain part only) :Types: - `jid`: `JID` :Returntype: `bool` """ if not self.common_names: ...
def verify_jid_against_srv_name(self, jid, srv_type): """Check if the cerificate is valid for given domain-only JID and a service type. :Parameters: - `jid`: JID requested (domain part only) - `srv_type`: service type, e.g. 'xmpp-client' :Types: - `ji...
def verify_client(self, client_jid = None, domains = None): """Verify certificate for a client. Please note that `client_jid` is only a hint to choose from the names, other JID may be returned if `client_jid` is not included in the certificate. :Parameters: - `clien...
def from_ssl_socket(cls, ssl_socket): """Load certificate data from an SSL socket. """ cert = cls() try: data = ssl_socket.getpeercert() except AttributeError: # PyPy doesn't have .getppercert return cert logger.debug("Certificate data ...
def _decode_names(self): """Decode names (hopefully ASCII or UTF-8) into Unicode. """ if self.subject_name is not None: subject_name = [] for part in self.subject_name: new_part = [] for name, value in part: try: ...
def from_ssl_socket(cls, ssl_socket): """Get certificate data from an SSL socket. """ try: data = ssl_socket.getpeercert(True) except AttributeError: # PyPy doesn't have .getpeercert data = None if not data: logger.debug("No certifi...
def from_der_data(cls, data): """Decode DER-encoded certificate. :Parameters: - `data`: the encoded certificate :Types: - `data`: `bytes` :Return: decoded certificate data :Returntype: ASN1CertificateData """ # pylint: disable=W0212 ...
def _decode_subject(self, subject): """Load data from a ASN.1 subject. """ self.common_names = [] subject_name = [] for rdnss in subject: for rdns in rdnss: rdnss_list = [] for nameval in rdns: val_type = nameval.get...
def _decode_validity(self, validity): """Load data from a ASN.1 validity value. """ not_after = validity.getComponentByName('notAfter') not_after = str(not_after.getComponent()) if isinstance(not_after, GeneralizedTime): self.not_after = datetime.strptime(not_after, "...
def _decode_alt_names(self, alt_names): """Load SubjectAltName from a ASN.1 GeneralNames value. :Values: - `alt_names`: the SubjectAltNama extension value :Types: - `alt_name`: `GeneralNames` """ for alt_name in alt_names: tname = alt_name.get...
def from_file(cls, filename): """Load certificate from a file. """ with open(filename, "r") as pem_file: data = pem.readPemFromFile(pem_file) return cls.from_der_data(data)
def main(): """Parse the command-line arguments and run the bot.""" parser = argparse.ArgumentParser(description = 'XMPP echo bot', parents = [XMPPSettings.get_arg_parser()]) parser.add_argument('--debug', action = 'store_const', dest = 'log_level'...
def run(self): """Request client connection and start the main loop.""" if self.args.roster_cache and os.path.exists(self.args.roster_cache): logging.info(u"Loading roster from {0!r}" .format(self.args.roster_cache)) try: ...
def add_handler(self, handler): """Add a handler object. :Parameters: - `handler`: the object providing event handler methods :Types: - `handler`: `EventHandler` """ if not isinstance(handler, EventHandler): raise TypeError, "Not an EventHandl...
def remove_handler(self, handler): """Remove a handler object. :Parameters: - `handler`: the object to remove """ with self.lock: if handler in self.handlers: self.handlers.remove(handler) self._update_handlers()
def _update_handlers(self): """Update `_handler_map` after `handlers` have been modified.""" handler_map = defaultdict(list) for i, obj in enumerate(self.handlers): for dummy, handler in inspect.getmembers(obj, callable): if not hasattr(handler, "_pyxmpp_event...
def dispatch(self, block = False, timeout = None): """Get the next event from the queue and pass it to the appropriate handlers. :Parameters: - `block`: wait for event if the queue is empty - `timeout`: maximum time, in seconds, to wait if `block` is `True` :Type...
def flush(self, dispatch = True): """Read all events currently in the queue and dispatch them to the handlers unless `dispatch` is `False`. Note: If the queue contains `QUIT` the events after it won't be removed. :Parameters: - `dispatch`: if the events should be ha...
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 loop_iteration(self, timeout = 60): """A loop iteration - check any scheduled events and I/O available and run the handlers. """ next_timeout, sources_handled = self._call_timeout_handlers() if self._quit: return sources_handled if self._timeout is not Non...
def Normalize(str_): """The Normalize(str) function. This one also accepts Unicode string input (in the RFC only UTF-8 strings are used). """ # pylint: disable=C0103 if isinstance(str_, bytes): str_ = str_.decode("utf-8") return SASLPREP.prepare(str_)...
def HMAC(self, key, str_): """The HMAC(key, str) function.""" # pylint: disable=C0103 return hmac.new(key, str_, self.hash_factory).digest()
def Hi(self, str_, salt, i): """The Hi(str, salt, i) function.""" # pylint: disable=C0103 Uj = self.HMAC(str_, salt + b"\000\000\000\001") # U1 result = Uj for _ in range(2, i + 1): Uj = self.HMAC(str_, Uj) # Uj = HMAC(str, Uj-1) result = sel...
def challenge(self, challenge): """Process a challenge and return the response. :Parameters: - `challenge`: the challenge from server. :Types: - `challenge`: `bytes` :return: the response or a failure indicator. :returntype: `sasl.Response` or `sasl.Fail...
def _make_response(self, nonce, salt, iteration_count): """Make a response for the first challenge from the server. :return: the response or a failure indicator. :returntype: `sasl.Response` or `sasl.Failure` """ self._salted_password = self.Hi(self.Normalize(self.password), sal...
def _final_challenge(self, challenge): """Process the second challenge from the server and return the response. :Parameters: - `challenge`: the challenge from server. :Types: - `challenge`: `bytes` :return: the response or a failure indicator. :r...
def finish(self, data): """Process success indicator from the server. Process any addiitional data passed with the success. Fail if the server was not authenticated. :Parameters: - `data`: an optional additional data with success. :Types: - `data`: `byte...
def feature_uri(uri): """Decorating attaching a feature URI (for Service Discovery or Capability to a XMPPFeatureHandler class.""" def decorator(class_): """Returns a decorated class""" if "_pyxmpp_feature_uris" not in class_.__dict__: class_._pyxmpp_feature_uris = set() ...
def _iq_handler(iq_type, payload_class, payload_key, usage_restriction): """Method decorator generator for decorating <iq type='get'/> stanza handler methods in `XMPPFeatureHandler` subclasses. :Parameters: - `payload_class`: payload class expected - `payload_key`: payload class specific fi...
def _stanza_handler(element_name, stanza_type, payload_class, payload_key, usage_restriction): """Method decorator generator for decorating <message/> or <presence/> stanza handler methods in `XMPPFeatureHandler` subclasses. :Parameters: -...
def message_stanza_handler(stanza_type = None, payload_class = None, payload_key = None, usage_restriction = "post-auth"): """Method decorator generator for decorating <message/> stanza handler methods in `XMPPFeatureHandler` subclasses. :Parameters: - `payload_class`: paylo...
def presence_stanza_handler(stanza_type = None, payload_class = None, payload_key = None, usage_restriction = "post-auth"): """Method decorator generator for decorating <presence/> stanza handler methods in `XMPPFeatureHandler` subclasses. :Parameters: - `payload_class`: pay...
def payload_element_name(element_name): """Class decorator generator for decorationg `StanzaPayload` subclasses. :Parameters: - `element_name`: XML element qname handled by the class :Types: - `element_name`: `unicode` """ def decorator(klass): """The payload_element_nam...
def stream_element_handler(element_name, usage_restriction = None): """Method decorator generator for decorating stream element handler methods in `StreamFeatureHandler` subclasses. :Parameters: - `element_name`: stream element QName - `usage_restriction`: optional usage restriction: "initi...
def complete_xml_element(self, xmlnode, doc): """Complete the XML node with `self` content. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace, but no attributes or content. - `doc`: document to which the elemen...
def _new_from_xml(cls, xmlnode): """Create a new `Option` object from an XML element. :Parameters: - `xmlnode`: the XML element. :Types: - `xmlnode`: `libxml2.xmlNode` :return: the object created. :returntype: `Option` """ label = from_ut...
def add_option(self, value, label): """Add an option for the field. :Parameters: - `value`: option values. - `label`: option label (human-readable description). :Types: - `value`: `list` of `unicode` - `label`: `unicode` """ if typ...
def complete_xml_element(self, xmlnode, doc): """Complete the XML node with `self` content. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace, but no attributes or content. - `doc`: document to which the elemen...
def _new_from_xml(cls, xmlnode): """Create a new `Field` object from an XML element. :Parameters: - `xmlnode`: the XML element. :Types: - `xmlnode`: `libxml2.xmlNode` :return: the object created. :returntype: `Field` """ field_type = xmln...
def add_field(self, name = None, values = None, field_type = None, label = None, options = None, required = False, desc = None, value = None): """Add a field to the item. :Parameters: - `name`: field name. - `values`: raw field values. Not to be used together with `v...
def complete_xml_element(self, xmlnode, doc): """Complete the XML node with `self` content. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace, but no attributes or content. - `doc`: document to which the elemen...
def _new_from_xml(cls, xmlnode): """Create a new `Item` object from an XML element. :Parameters: - `xmlnode`: the XML element. :Types: - `xmlnode`: `libxml2.xmlNode` :return: the object created. :returntype: `Item` """ child = xmlnode.chi...
def add_item(self, fields = None): """Add and item to the form. :Parameters: - `fields`: fields of the item (they may be added later). :Types: - `fields`: `list` of `Field` :return: the item added. :returntype: `Item` """ item = Item(fiel...
def make_submit(self, keep_types = False): """Make a "submit" form using data in `self`. Remove uneeded information from the form. The information removed includes: title, instructions, field labels, fixed fields etc. :raise ValueError: when any required field has no value. :P...
def complete_xml_element(self, xmlnode, doc): """Complete the XML node with `self` content. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace, but no attributes or content. - `doc`: document to which the elemen...
def __from_xml(self, xmlnode): """Initialize a `Form` object from an XML element. :Parameters: - `xmlnode`: the XML element. :Types: - `xmlnode`: `libxml2.xmlNode` """ self.fields = [] self.reported_fields = [] self.items = [] self...