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=parent.newChild(None,self.name.upper(),None) if self.uri: n.newTextChild(None,"EXTVAL",to_utf8(self.uri)) else: if self.type: n.newTextChild(None,"TYPE",self.type) n.newTextChild(None,"BINVAL",binascii.b2a_base64(self.image)) return n
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!='element': n=n.next continue ns=get_node_ns(n) if (ns and vns and ns.getContent()!=vns.getContent()): n=n.next continue if n.name=='POBOX': self.pobox=unicode(n.getContent(),"utf-8","replace") elif n.name in ('EXTADR', 'EXTADD'): self.extadr=unicode(n.getContent(),"utf-8","replace") elif n.name=='STREET': self.street=unicode(n.getContent(),"utf-8","replace") elif n.name=='LOCALITY': self.locality=unicode(n.getContent(),"utf-8","replace") elif n.name=='REGION': self.region=unicode(n.getContent(),"utf-8","replace") elif n.name=='PCODE': self.pcode=unicode(n.getContent(),"utf-8","replace") elif n.name=='CTRY': self.ctry=unicode(n.getContent(),"utf-8","replace") elif n.name in ("HOME","WORK","POSTAL","PARCEL","DOM","INTL", "PREF"): self.type.append(n.name.lower()) n=n.next if self.type==[]: self.type=["intl","postal","parcel","work"] elif "dom" in self.type and "intl" in self.type: raise ValueError("Both 'dom' and 'intl' specified in vcard ADR")
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.region,self.pcode,self.ctry)), {"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=parent.newChild(None,"ADR",None) for t in ("home","work","postal","parcel","dom","intl","pref"): if t in self.type: n.newChild(None,t.upper(),None) n.newTextChild(None,"POBOX",to_utf8(self.pobox)) n.newTextChild(None,"EXTADD",to_utf8(self.extadr)) n.newTextChild(None,"STREET",to_utf8(self.street)) n.newTextChild(None,"LOCALITY",to_utf8(self.locality)) n.newTextChild(None,"REGION",to_utf8(self.region)) n.newTextChild(None,"PCODE",to_utf8(self.pcode)) n.newTextChild(None,"CTRY",to_utf8(self.ctry)) return n
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=parent.newChild(None,"ADR",None) for t in ("home","work","postal","parcel","dom","intl","pref"): if t in self.type: n.newChild(None,t.upper(),None) for l in self.lines: n.newTextChild(None,"LINE",l) return n
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=parent.newChild(None,"TEL",None) for t in ("home","work","voice","fax","pager","msg","cell","video", "bbs","modem","isdn","pcs","pref"): if t in self.type: n.newChild(None,t.upper(),None) n.newTextChild(None,"NUMBER",to_utf8(self.number)) return n
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=parent.newChild(None,"GEO",None) n.newTextChild(None,"LAT",to_utf8(self.lat)) n.newTextChild(None,"LON",to_utf8(self.lon)) return n
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))) else: return rfc2425encode("org",unicode(quote_semicolon(self.name)))
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=parent.newChild(None,"ORG",None) n.newTextChild(None,"ORGNAME",to_utf8(self.name)) n.newTextChild(None,"ORGUNIT",to_utf8(self.unit)) return n
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=parent.newChild(None,"CATEGORIES",None) for k in self.keywords: n.newTextChild(None,"KEYWORD",to_utf8(k)) return n
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=parent.newChild(None,self.name.upper(),None) if self.uri: n.newTextChild(None,"EXTVAL",to_utf8(self.uri)) elif self.phonetic: n.newTextChild(None,"PHONETIC",to_utf8(self.phonetic)) else: n.newTextChild(None,"BINVAL",binascii.b2a_base64(self.sound)) return n
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 self.value in ("public","private","confidental"): n=parent.newChild(None,self.name.upper(),None) n.newChild(None,self.value.upper(),None) return n return None
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=parent.newChild(None,self.name.upper(),None) if self.type: n.newTextChild(None,"TYPE",self.type) n.newTextChild(None,"CRED",binascii.b2a_base64(self.cred)) return n
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: s.append(self.n.middle) if self.n.family: s.append(self.n.family) if self.n.suffix: s.append(self.n.suffix) s=u" ".join(s) self.content["FN"]=VCardString("FN", s, empty_ok = True)
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 namespace" % (VCARD_NS,)) if data.name!="vCard": raise ValueError("Bad root element name: %r" % (data.name,)) n=data.children dns=get_node_ns(data) while n: if n.type!='element': n=n.next continue ns=get_node_ns(n) if (ns and dns and ns.getContent()!=dns.getContent()): n=n.next continue if not self.components.has_key(n.name): n=n.next continue cl,tp=self.components[n.name] if tp in ("required","optional"): if self.content.has_key(n.name): raise ValueError("Duplicate %s" % (n.name,)) try: self.content[n.name]=cl(n.name,n) except Empty: pass elif tp=="multi": if not self.content.has_key(n.name): self.content[n.name]=[] try: self.content[n.name].append(cl(n.name,n)) except Empty: pass n=n.next
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 current=None for l in lines: if not l: continue if l[-1]=="\r": l=l[:-1] if not l: continue if l[0] in " \t": if current is None: continue current+=l[1:] continue if not started and current and current.upper().strip()=="BEGIN:VCARD": started=1 elif started and current.upper().strip()=="END:VCARD": current=None break elif current and started: self._process_rfc2425_record(current) current=l if started and current: self._process_rfc2425_record(current)
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").replace("\\N","\n") psplit=label.lower().split(";") name=psplit[0] params=psplit[1:] if u"." in name: name=name.split(".",1)[1] name=name.upper() if name in (u"X-DESC",u"X-JABBERID"): name=name[2:] if not self.components.has_key(name): return if params: params=dict([p.split("=",1) for p in params]) cl,tp=self.components[name] if tp in ("required","optional"): if self.content.has_key(name): raise ValueError("Duplicate %s" % (name,)) try: self.content[name]=cl(name,value,params) except Empty: pass elif tp=="multi": if not self.content.has_key(name): self.content[name]=[] try: self.content[name].append(cl(name,value,params)) except Empty: pass else: return
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: continue if type(value) is list: for v in value: ret+=v.rfc2426() else: v=value.rfc2426() ret+=v return ret+"end:VCARD\r\n"
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, but no attributes or content. - `_unused`: document to which the element belongs. :Types: - `xmlnode`: `libxml2.xmlNode` - `_unused`: `libxml2.xmlDoc`""" for _unused1, value in self.content.items(): if value is None: continue if type(value) is list: for v in value: v.as_xml(xmlnode) else: value.as_xml(xmlnode)
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': self.state = 'fresh' if self.state == 'fresh': if now > self.freshness_time: self.state = 'old' if self.state == 'old': if now > self.expire_time: self.state = 'stale' if self.state == 'stale': if now > self.purge_time: self.state = 'purged' self.state_value = _state_values[self.state] return self.state finally: self._lock.release()
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`: fetched object. - `state`: initial state of the object. :Types: - `value`: any - `state`: `str`""" if not self.active: return item = CacheItem(self.address, value, self._item_freshness_period, self._item_expiration_period, self._item_purge_period, state) self._object_handler(item.address, item.value, item.state) self.cache.add_item(item) self._deactivate()
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 information about the error (e.g. `StanzaError` instance). :Types: - `error_data`: fetcher dependant """ if not self.active: return if not self._try_backup_item(): self._error_handler(self.address, error_data) self.cache.invalidate_object(self.address) self._deactivate()
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.active: return if not self._try_backup_item(): if self._timeout_handler: self._timeout_handler(self.address) else: self._error_handler(self.address, None) self.cache.invalidate_object(self.address) self._deactivate()
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, self._backup_state) if item: self._object_handler(item.address, item.value, item.state) return True else: False
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 address and state not worse than `state`. The object will be taken from cache if available, and created/fetched otherwise. The request is asynchronous -- this metod doesn't return the object directly, but the `object_handler` is called as soon as the object is available (this may be before `request_object` returns and may happen in other thread). On error the `error_handler` will be called, and on timeout -- the `timeout_handler`. :Parameters: - `address`: address of the object requested. - `state`: the worst acceptable object state. When 'new' then always a new object will be created/fetched. 'stale' will select any item available in cache. - `object_handler`: function to be called when object is available. It will be called with the following arguments: address, object and its state. - `error_handler`: function to be called on object retrieval error. It will be called with two arguments: requested address and additional error information (fetcher-specific, may be StanzaError for XMPP objects). If not given, then the object handler will be called with object set to `None` and state "error". - `timeout_handler`: function to be called on object retrieval timeout. It will be called with only one argument: the requested address. If not given, then the `error_handler` will be called instead, with error details set to `None`. - `backup_state`: when set and object in state `state` is not available in the cache and object retrieval failed then object with this state will also be looked-up in the cache and provided if available. - `timeout`: time interval after which retrieval of the object should be given up. - `freshness_period`: time interval after which the item created should become 'old'. - `expiration_period`: time interval after which the item created should become 'stale'. - `purge_period`: time interval after which the item created shuld be removed from the cache. :Types: - `address`: any hashable - `state`: "new", "fresh", "old" or "stale" - `object_handler`: callable(address, value, state) - `error_handler`: callable(address, error_data) - `timeout_handler`: callable(address) - `backup_state`: "new", "fresh", "old" or "stale" - `timeout`: `timedelta` - `freshness_period`: `timedelta` - `expiration_period`: `timedelta` - `purge_period`: `timedelta` """ self._lock.acquire() try: if state == 'stale': state = 'purged' item = self.get_item(address, state) if item: object_handler(item.address, item.value, item.state) return if not self._fetcher: raise TypeError("No cache fetcher defined") if not error_handler: def default_error_handler(address, _unused): "Default error handler." return object_handler(address, None, 'error') error_handler = default_error_handler if not timeout_handler: def default_timeout_handler(address): "Default timeout handler." return error_handler(address, None) timeout_handler = default_timeout_handler if freshness_period is None: freshness_period = self.default_freshness_period if expiration_period is None: expiration_period = self.default_expiration_period if purge_period is None: purge_period = self.default_purge_period fetcher = self._fetcher(self, address, freshness_period, expiration_period, purge_period, object_handler, error_handler, timeout_handler, timeout, backup_state) fetcher.fetch() self._active_fetchers.append((fetcher.timeout_time,fetcher)) self._active_fetchers.sort() finally: self._lock.release()
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(address) if item and item.state_value<_state_values[state]: item.state=state item.update_state() self._items_list.sort() finally: self._lock.release()
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. :returntype: `str` """ self._lock.acquire() try: state = item.update_state() if state != 'purged': if len(self._items_list) >= self.max_items: self.purge_items() self._items[item.address] = item self._items_list.append(item) self._items_list.sort() return item.state finally: self._lock.release()
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 `None` if it was not found. :returntype: `CacheItem`""" self._lock.acquire() try: item = self._items.get(address) if not item: return None self.update_item(item) if _state_values[state] >= item.state_value: return item return None finally: self._lock.release()
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 the item. :returntype: `str`""" self._lock.acquire() try: state = item.update_state() self._items_list.sort() if item.state == 'purged': self._purged += 1 if self._purged > 0.25*self.max_items: self.purge_items() return state finally: self._lock.release()
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_remove = num_items - int(0.75 * self.max_items) for _unused in range(need_remove): item=il.pop(0) try: del self._items[item.address] except KeyError: pass while il and il[0].update_state()=="purged": item=il.pop(0) try: del self._items[item.address] except KeyError: pass finally: self._lock.release()
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: break f.timeout() self.purge_items() finally: self._lock.release()
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_fetchers): if f is fetcher: self._active_fetchers.remove((t, f)) f._deactivated() return finally: self._lock.release()
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 finally: self._lock.release()
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 address and state not worse than `state`. The object will be taken from cache if available, and created/fetched otherwise. The request is asynchronous -- this metod doesn't return the object directly, but the `object_handler` is called as soon as the object is available (this may be before `request_object` returns and may happen in other thread). On error the `error_handler` will be called, and on timeout -- the `timeout_handler`. :Parameters: - `object_class`: class (type) of the object requested. - `address`: address of the object requested. - `state`: the worst acceptable object state. When 'new' then always a new object will be created/fetched. 'stale' will select any item available in cache. - `object_handler`: function to be called when object is available. It will be called with the following arguments: address, object and its state. - `error_handler`: function to be called on object retrieval error. It will be called with two arguments: requested address and additional error information (fetcher-specific, may be StanzaError for XMPP objects). If not given, then the object handler will be called with object set to `None` and state "error". - `timeout_handler`: function to be called on object retrieval timeout. It will be called with only one argument: the requested address. If not given, then the `error_handler` will be called instead, with error details set to `None`. - `backup_state`: when set and object in state `state` is not available in the cache and object retrieval failed then object with this state will also be looked-up in the cache and provided if available. - `timeout`: time interval after which retrieval of the object should be given up. - `freshness_period`: time interval after which the item created should become 'old'. - `expiration_period`: time interval after which the item created should become 'stale'. - `purge_period`: time interval after which the item created shuld be removed from the cache. :Types: - `object_class`: `classobj` - `address`: any hashable - `state`: "new", "fresh", "old" or "stale" - `object_handler`: callable(address, value, state) - `error_handler`: callable(address, error_data) - `timeout_handler`: callable(address) - `backup_state`: "new", "fresh", "old" or "stale" - `timeout`: `timedelta` - `freshness_period`: `timedelta` - `expiration_period`: `timedelta` - `purge_period`: `timedelta` """ self._lock.acquire() try: if object_class not in self._caches: raise TypeError("No cache for %r" % (object_class,)) self._caches[object_class].request_object(address, state, object_handler, error_handler, timeout_handler, backup_state, timeout, freshness_period, expiration_period, purge_period) finally: self._lock.release()
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._lock.release()
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` - `fetcher_class`: `CacheFetcher` based class """ self._lock.acquire() try: cache = self._caches.get(object_class) if not cache: cache = Cache(self.max_items, self.default_freshness_period, self.default_expiration_period, self.default_purge_period) self._caches[object_class] = cache cache.set_fetcher(fetcher_class) finally: self._lock.release()
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 = self._caches.get(object_class) if not cache: return cache.set_fetcher(None) finally: self._lock.release()
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 = _key_func, reverse = True) CLIENT_MECHANISMS[:] = [k for (k, v) in items ] SECURE_CLIENT_MECHANISMS[:] = [k for (k, v) in items if v._pyxmpp_sasl_secure]
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 = _key_func, reverse = True) SERVER_MECHANISMS[:] = [k for (k, v) in items ] SECURE_SERVER_MECHANISMS[:] = [k for (k, v) in items if v._pyxmpp_sasl_secure]
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 secure - `True` if it can be used over plain-text channel - `preference`: mechanism preference level (the higher the better) :Types: - `name`: `unicode` - `secure`: `bool` - `preference`: `int` """ # pylint: disable-msg=W0212 def decorator(klass): """The decorator.""" klass._pyxmpp_sasl_secure = secure klass._pyxmpp_sasl_preference = preference if issubclass(klass, ClientAuthenticator): _register_client_authenticator(klass, name) elif issubclass(klass, ServerAuthenticator): _register_server_authenticator(klass, name) else: raise TypeError("Not a ClientAuthenticator" " or ServerAuthenticator class") return klass return decorator
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 provided. May be overridden e.g. to check the password against some external authentication mechanism (PAM, LDAP, etc.). :Parameters: - `username`: the username for which the password verification is requested. - `password`: the password to verify. - `properties`: mapping with authentication properties (those provided to the authenticator's ``start()`` method plus some already obtained via the mechanism). :Types: - `username`: `unicode` - `password`: `unicode` - `properties`: mapping :return: `True` if the password is valid. :returntype: `bool` """ logger.debug("check_password{0!r}".format( (username, password, properties))) pwd, pwd_format = self.get_password(username, (u"plain", u"md5:user:realm:password"), properties) if pwd_format == u"plain": logger.debug("got plain password: {0!r}".format(pwd)) return pwd is not None and password == pwd elif pwd_format in (u"md5:user:realm:password"): logger.debug("got md5:user:realm:password password: {0!r}" .format(pwd)) realm = properties.get("realm") if realm is None: realm = "" else: realm = realm.encode("utf-8") username = username.encode("utf-8") password = password.encode("utf-8") # pylint: disable-msg=E1101 urp_hash = hashlib.md5(b"%s:%s:%s").hexdigest() return urp_hash == pwd logger.debug("got password in unknown format: {0!r}".format(pwd_format)) return False
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_b64encode(self.data) return ret.decode("us-ascii")
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: return element = stream.features.find(SESSION_TAG) if element is None: return logger.debug("Establishing IM session") stanza = Iq(stanza_type = "set") payload = XMLPayload(ElementTree.Element(SESSION_TAG)) stanza.set_payload(payload) self.stanza_processor.set_response_handlers(stanza, self._session_success, self._session_error) stream.send(stanza)
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 ] ) for dn_tuple in self.subject_name ]) for name_type in ("XmppAddr", "DNS", "SRV"): names = self.alt_names.get(name_type) if names: return names[0] return u"<unknown>"
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.alt_names): addrs = self.alt_names.get("XmppAddr", []) addrs += [ addr for addr in self.alt_names.get("DNS", []) if not addr.startswith("*.") ] addrs += [ addr.split(".", 1)[1] for addr in self.alt_names.get("SRVName", []) if (addr.startswith("_xmpp-server.") or addr.startswith("_xmpp-client."))] warn_bad = True elif self.common_names: addrs = [addr for addr in self.common_names if "@" not in addr and "/" not in addr] warn_bad = False else: return [] for addr in addrs: try: jid = JID(addr) if jid not in result: result.append(jid) except JIDError, err: if warn_bad: logger.warning(u"Bad JID in the certificate: {0!r}: {1}" .format(addr, err)) return result
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_name`: `unicode` or `JID` - `srv_type`: `unicode` :Return: `True` if the certificate is valid for given name, `False` otherwise. """ server_jid = JID(server_name) if "XmppAddr" not in self.alt_names and "DNS" not in self.alt_names \ and "SRV" not in self.alt_names: return self.verify_jid_against_common_name(server_jid) names = [name for name in self.alt_names.get("DNS", []) if not name.startswith(u"*.")] names += self.alt_names.get("XmppAddr", []) for name in names: logger.debug("checking {0!r} against {1!r}".format(server_jid, name)) try: jid = JID(name) except ValueError: logger.debug("Not a valid JID: {0!r}".format(name)) continue if jid == server_jid: logger.debug("Match!") return True if srv_type and self.verify_jid_against_srv_name(server_jid, srv_type): return True wildcards = [name[2:] for name in self.alt_names.get("DNS", []) if name.startswith("*.")] if not wildcards or not "." in server_jid.domain: return False logger.debug("checking {0!r} against wildcard domains: {1!r}" .format(server_jid, wildcards)) server_domain = JID(domain = server_jid.domain.split(".", 1)[1]) for domain in wildcards: logger.debug("checking {0!r} against {1!r}".format(server_domain, domain)) try: jid = JID(domain) except ValueError: logger.debug("Not a valid JID: {0!r}".format(name)) continue if jid == server_domain: logger.debug("Match!") return True return False
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: return False for name in self.common_names: try: cn_jid = JID(name) except ValueError: continue if jid == cn_jid: return True return False
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: - `jid`: `JID` - `srv_type`: `unicode` :Returntype: `bool` """ srv_prefix = u"_" + srv_type + u"." srv_prefix_l = len(srv_prefix) for srv in self.alt_names.get("SRVName", []): logger.debug("checking {0!r} against {1!r}".format(jid, srv)) if not srv.startswith(srv_prefix): logger.debug("{0!r} does not start with {1!r}" .format(srv, srv_prefix)) continue try: srv_jid = JID(srv[srv_prefix_l:]) except ValueError: continue if srv_jid == jid: logger.debug("Match!") return True return False
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: - `client_jid`: client name requested. May be `None` to allow any name in one of the `domains`. - `domains`: list of domains we can handle. :Types: - `client_jid`: `JID` - `domains`: `list` of `unicode` :Return: one of the jids in the certificate or `None` is no authorized name is found. """ jids = [jid for jid in self.get_jids() if jid.local] if not jids: return None if client_jid is not None and client_jid in jids: return client_jid if domains is None: return jids[0] for jid in jids: for domain in domains: if are_domains_equal(jid.domain, domain): return jid return None
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 from ssl module: {0!r}".format(data)) if not data: return cert cert.validated = True cert.subject_name = data.get('subject') cert.alt_names = defaultdict(list) if 'subjectAltName' in data: for name, value in data['subjectAltName']: cert.alt_names[name].append(value) if 'notAfter' in data: tstamp = ssl.cert_time_to_seconds(data['notAfter']) cert.not_after = datetime.utcfromtimestamp(tstamp) if sys.version_info.major < 3: cert._decode_names() # pylint: disable=W0212 cert.common_names = [] if cert.subject_name: for part in cert.subject_name: for name, value in part: if name == 'commonName': cert.common_names.append(value) return cert
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: name = name.decode("utf-8") value = value.decode("utf-8") except UnicodeError: continue new_part.append((name, value)) subject_name.append(tuple(new_part)) self.subject_name = tuple(subject_name) for key, old in self.alt_names.items(): new = [] for name in old: try: name = name.decode("utf-8") except UnicodeError: continue new.append(name) self.alt_names[key] = new
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 certificate infromation") return cls() result = cls.from_der_data(data) result.validated = bool(ssl_socket.getpeercert()) return result
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 logger.debug("Decoding DER certificate: {0!r}".format(data)) if cls._cert_asn1_type is None: cls._cert_asn1_type = Certificate() cert = der_decoder.decode(data, asn1Spec = cls._cert_asn1_type)[0] result = cls() tbs_cert = cert.getComponentByName('tbsCertificate') subject = tbs_cert.getComponentByName('subject') logger.debug("Subject: {0!r}".format(subject)) result._decode_subject(subject) validity = tbs_cert.getComponentByName('validity') result._decode_validity(validity) extensions = tbs_cert.getComponentByName('extensions') if extensions: for extension in extensions: logger.debug("Extension: {0!r}".format(extension)) oid = extension.getComponentByName('extnID') logger.debug("OID: {0!r}".format(oid)) if oid != SUBJECT_ALT_NAME_OID: continue value = extension.getComponentByName('extnValue') logger.debug("Value: {0!r}".format(value)) if isinstance(value, Any): # should be OctetString, but is Any # in pyasn1_modules-0.0.1a value = der_decoder.decode(value, asn1Spec = OctetString())[0] alt_names = der_decoder.decode(value, asn1Spec = GeneralNames())[0] logger.debug("SubjectAltName: {0!r}".format(alt_names)) result._decode_alt_names(alt_names) return result
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.getComponentByName('type') value = nameval.getComponentByName('value') if val_type not in DN_OIDS: logger.debug("OID {0} not supported".format(val_type)) continue val_type = DN_OIDS[val_type] value = der_decoder.decode(value, asn1Spec = DirectoryString())[0] value = value.getComponent() try: value = _decode_asn1_string(value) except UnicodeError: logger.debug("Cannot decode value: {0!r}".format(value)) continue if val_type == u"commonName": self.common_names.append(value) rdnss_list.append((val_type, value)) subject_name.append(tuple(rdnss_list)) self.subject_name = tuple(subject_name)
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, "%Y%m%d%H%M%SZ") else: self.not_after = datetime.strptime(not_after, "%y%m%d%H%M%SZ") self.alt_names = defaultdict(list)
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.getName() comp = alt_name.getComponent() if tname == "dNSName": key = "DNS" value = _decode_asn1_string(comp) elif tname == "uniformResourceIdentifier": key = "URI" value = _decode_asn1_string(comp) elif tname == "otherName": oid = comp.getComponentByName("type-id") value = comp.getComponentByName("value") if oid == XMPPADDR_OID: key = "XmppAddr" value = der_decoder.decode(value, asn1Spec = UTF8String())[0] value = _decode_asn1_string(value) elif oid == SRVNAME_OID: key = "SRVName" value = der_decoder.decode(value, asn1Spec = IA5String())[0] value = _decode_asn1_string(value) else: logger.debug("Unknown other name: {0}".format(oid)) continue else: logger.debug("Unsupported general name: {0}" .format(tname)) continue self.alt_names[key].append(value)
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', const = logging.DEBUG, default = logging.INFO, help = 'Print debug messages') parser.add_argument('--quiet', const = logging.ERROR, action = 'store_const', dest = 'log_level', help = 'Print only error messages') parser.add_argument('--trace', action = 'store_true', help = 'Print XML data sent and received') parser.add_argument('--roster-cache', help = 'Store roster in this file') parser.add_argument('jid', metavar = 'JID', help = 'The bot JID') subparsers = parser.add_subparsers(help = 'Action', dest = "action") show_p = subparsers.add_parser('show', help = 'Show roster and exit') show_p.add_argument('--presence', action = 'store_true', help = 'Wait 5 s for contact presence information' ' and display it with the roster') mon_p = subparsers.add_parser('monitor', help = 'Show roster and subsequent changes') mon_p.add_argument('--presence', action = 'store_true', help = 'Show contact presence changes too') add_p = subparsers.add_parser('add', help = 'Add an item to the roster') add_p.add_argument('--subscribe', action = 'store_true', dest = 'subscribe', help = 'Request a presence subscription too') add_p.add_argument('--approve', action = 'store_true', dest = 'approve', help = 'Pre-approve subscription from the contact' ' (requires server support)') add_p.add_argument('contact', metavar = 'CONTACT', help = 'The JID to add') add_p.add_argument('name', metavar = 'NAME', nargs = '?', help = 'Contact name') add_p.add_argument('groups', metavar = 'GROUP', nargs = '*', help = 'Group names') rm_p = subparsers.add_parser('remove', help = 'Remove an item from the roster') rm_p.add_argument('contact', metavar = 'CONTACT', help = 'The JID to remove') upd_p = subparsers.add_parser('update', help = 'Update an item in the roster') upd_p.add_argument('contact', metavar = 'CONTACT', help = 'The JID to update') upd_p.add_argument('name', metavar = 'NAME', nargs = '?', help = 'Contact name') upd_p.add_argument('groups', metavar = 'GROUP', nargs = '*', help = 'Group names') args = parser.parse_args() settings = XMPPSettings() settings.load_arguments(args) if settings.get("password") is None: password = getpass("{0!r} password: ".format(args.jid)) if sys.version_info.major < 3: password = password.decode("utf-8") settings["password"] = password if sys.version_info.major < 3: args.jid = args.jid.decode("utf-8") if getattr(args, "contact", None): args.contact = args.contact.decode("utf-8") if getattr(args, "name", None): args.name = args.name.decode("utf-8") if getattr(args, "groups", None): args.groups = [g.decode("utf-8") for g in args.groups] logging.basicConfig(level = args.log_level) if args.trace: print "enabling trace" handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) for logger in ("pyxmpp2.IN", "pyxmpp2.OUT"): logger = logging.getLogger(logger) logger.setLevel(logging.DEBUG) logger.addHandler(handler) logger.propagate = False if args.action == "monitor" or args.action == "show" and args.presence: # According to RFC6121 it could be None for 'monitor' (no need to send # initial presence to request roster), but Google seems to require that # to send roster pushes settings["initial_presence"] = Presence(priority = -1) else: settings["initial_presence"] = None tool = RosterTool(JID(args.jid), args, settings) try: tool.run() except KeyboardInterrupt: tool.disconnect()
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: self.client.roster_client.load_roster(self.args.roster_cache) except (IOError, ValueError), err: logging.error(u"Could not load the roster: {0!r}".format(err)) self.client.connect() self.client.run()
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 EventHandler" with self.lock: if handler in self.handlers: return self.handlers.append(handler) self._update_handlers()
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_handled"): continue # pylint: disable-msg=W0212 event_class = handler._pyxmpp_event_handled handler_map[event_class].append( (i, handler) ) self._handler_map = handler_map
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` :Types: - `block`: `bool` - `timeout`: `float` :Return: the event handled (may be `QUIT`) or `None` """ logger.debug(" dispatching...") try: event = self.queue.get(block, timeout) except Queue.Empty: logger.debug(" queue empty") return None try: logger.debug(" event: {0!r}".format(event)) if event is QUIT: return QUIT handlers = list(self._handler_map[None]) klass = event.__class__ if klass in self._handler_map: handlers += self._handler_map[klass] logger.debug(" handlers: {0!r}".format(handlers)) # to restore the original order of handler objects handlers.sort(key = lambda x: x[0]) for dummy, handler in handlers: logger.debug(u" passing the event to: {0!r}".format(handler)) result = handler(event) if isinstance(result, Event): self.queue.put(result) elif result and event is not QUIT: return event return event finally: self.queue.task_done()
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 handled (`True`) or ignored (`False`) :Return: `QUIT` if the `QUIT` event was reached. """ if dispatch: while True: event = self.dispatch(False) if event in (None, QUIT): return event else: while True: try: self.queue.get(False) except Queue.Empty: return None
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) else: old_fileno = None prepared = True fileno = handler.fileno() if old_fileno is not None and fileno != old_fileno: del self._handlers[old_fileno] try: self.poll.unregister(old_fileno) except KeyError: # The socket has changed, but the old one isn't registered, # e.g. ``prepare`` wants to connect again pass if not prepared: self._unprepared_handlers[handler] = fileno if not fileno: return self._handlers[fileno] = handler events = 0 if handler.is_readable(): logger.debug(" {0!r} readable".format(handler)) events |= select.POLLIN if handler.is_writable(): logger.debug(" {0!r} writable".format(handler)) events |= select.POLLOUT if events: logger.debug(" registering {0!r} handler fileno {1} for" " events {2}".format(handler, fileno, events)) self.poll.register(fileno, events)
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: {0!r}".format(ret)) if isinstance(ret, HandlerReady): del self._unprepared_handlers[handler] prepared = True elif isinstance(ret, PrepareAgain): if ret.timeout is not None: if self._timeout is not None: self._timeout = min(self._timeout, ret.timeout) else: self._timeout = ret.timeout prepared = False else: raise TypeError("Unexpected result type from prepare()") return prepared
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 None: try: del self._handlers[old_fileno] self.poll.unregister(old_fileno) except KeyError: pass
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 None: timeout = min(timeout, self._timeout) if next_timeout is not None: timeout = min(next_timeout, timeout) for handler in list(self._unprepared_handlers): self._configure_io_handler(handler) events = self.poll.poll(timeout * 1000) self._timeout = None for (fileno, event) in events: if event & select.POLLHUP: self._handlers[fileno].handle_hup() if event & select.POLLNVAL: self._handlers[fileno].handle_nval() if event & select.POLLIN: self._handlers[fileno].handle_read() elif event & select.POLLERR: # if POLLIN was set this condition should be already handled self._handlers[fileno].handle_err() if event & select.POLLOUT: self._handlers[fileno].handle_write() sources_handled += 1 self._configure_io_handler(self._handlers[fileno]) return sources_handled
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_).encode("utf-8")
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 = self.XOR(result, Uj) # ... XOR Uj-1 XOR Uj return result
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.Failure` """ # pylint: disable=R0911 if not challenge: logger.debug("Empty challenge") return Failure("bad-challenge") if self._server_first_message: return self._final_challenge(challenge) match = SERVER_FIRST_MESSAGE_RE.match(challenge) if not match: logger.debug("Bad challenge syntax: {0!r}".format(challenge)) return Failure("bad-challenge") self._server_first_message = challenge mext = match.group("mext") if mext: logger.debug("Unsupported extension received: {0!r}".format(mext)) return Failure("bad-challenge") nonce = match.group("nonce") if not nonce.startswith(self._c_nonce): logger.debug("Nonce does not start with our nonce") return Failure("bad-challenge") salt = match.group("salt") try: salt = a2b_base64(salt) except ValueError: logger.debug("Bad base64 encoding for salt: {0!r}".format(salt)) return Failure("bad-challenge") iteration_count = match.group("iteration_count") try: iteration_count = int(iteration_count) except ValueError: logger.debug("Bad iteration_count: {0!r}".format(iteration_count)) return Failure("bad-challenge") return self._make_response(nonce, salt, iteration_count)
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), salt, iteration_count) self.password = None # not needed any more if self.channel_binding: channel_binding = b"c=" + standard_b64encode(self._gs2_header + self._cb_data) else: channel_binding = b"c=" + standard_b64encode(self._gs2_header) # pylint: disable=C0103 client_final_message_without_proof = (channel_binding + b",r=" + nonce) client_key = self.HMAC(self._salted_password, b"Client Key") stored_key = self.H(client_key) auth_message = ( self._client_first_message_bare + b"," + self._server_first_message + b"," + client_final_message_without_proof ) self._auth_message = auth_message client_signature = self.HMAC(stored_key, auth_message) client_proof = self.XOR(client_key, client_signature) proof = b"p=" + standard_b64encode(client_proof) client_final_message = (client_final_message_without_proof + b"," + proof) return Response(client_final_message)
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. :returntype: `sasl.Response` or `sasl.Failure` """ if self._finished: return Failure("extra-challenge") match = SERVER_FINAL_MESSAGE_RE.match(challenge) if not match: logger.debug("Bad final message syntax: {0!r}".format(challenge)) return Failure("bad-challenge") error = match.group("error") if error: logger.debug("Server returned SCRAM error: {0!r}".format(error)) return Failure(u"scram-" + error.decode("utf-8")) verifier = match.group("verifier") if not verifier: logger.debug("No verifier value in the final message") return Failure("bad-succes") server_key = self.HMAC(self._salted_password, b"Server Key") server_signature = self.HMAC(server_key, self._auth_message) if server_signature != a2b_base64(verifier): logger.debug("Server verifier does not match") return Failure("bad-succes") self._finished = True return Response(None)
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`: `bytes` :return: success or failure indicator. :returntype: `sasl.Success` or `sasl.Failure`""" if not self._server_first_message: logger.debug("Got success too early") return Failure("bad-success") if self._finished: return Success({"username": self.username, "authzid": self.authzid}) else: ret = self._final_challenge(data) if isinstance(ret, Failure): return ret if self._finished: return Success({"username": self.username, "authzid": self.authzid}) else: logger.debug("Something went wrong when processing additional" " data with success?") return Failure("bad-success")
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() class_._pyxmpp_feature_uris.add(uri) return class_ return decorator
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 filtering key - `usage_restriction`: optional usage restriction: "pre-auth" or "post-auth" :Types: - `payload_class`: subclass of `StanzaPayload` - `usage_restriction`: `unicode` """ def decorator(func): """The decorator""" func._pyxmpp_stanza_handled = ("iq", iq_type) func._pyxmpp_payload_class_handled = payload_class func._pyxmpp_payload_key = payload_key func._pyxmpp_usage_restriction = usage_restriction return func return decorator
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: - `element_name`: "message" or "presence" - `stanza_type`: expected value of the 'type' attribute of the stanza - `payload_class`: payload class expected - `payload_key`: payload class specific filtering key - `usage_restriction`: optional usage restriction: "pre-auth" or "post-auth" :Types: - `element_name`: `unicode` - `stanza_type`: `unicode` - `payload_class`: subclass of `StanzaPayload` - `usage_restriction`: `unicode` """ def decorator(func): """The decorator""" func._pyxmpp_stanza_handled = (element_name, stanza_type) func._pyxmpp_payload_class_handled = payload_class func._pyxmpp_payload_key = payload_key func._pyxmpp_usage_restriction = usage_restriction return func return decorator
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`: payload class expected - `stanza_type`: expected value of the 'type' attribute of the stanza. `None` means all types except 'error' - `payload_key`: payload class specific filtering key - `usage_restriction`: optional usage restriction: "pre-auth" or "post-auth" :Types: - `payload_class`: subclass of `StanzaPayload` - `stanza_type`: `unicode` - `usage_restriction`: `unicode` """ if stanza_type is None: stanza_type = "normal" return _stanza_handler("message", stanza_type, payload_class, payload_key, usage_restriction)
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`: payload class expected - `stanza_type`: expected value of the 'type' attribute of the stanza. - `payload_key`: payload class specific filtering key - `usage_restriction`: optional usage restriction: "pre-auth" or "post-auth" :Types: - `payload_class`: subclass of `StanzaPayload` - `stanza_type`: `unicode` - `usage_restriction`: `unicode` """ return _stanza_handler("presence", stanza_type, payload_class, payload_key, usage_restriction)
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_name decorator.""" # pylint: disable-msg=W0212,W0404 from .stanzapayload import STANZA_PAYLOAD_CLASSES from .stanzapayload import STANZA_PAYLOAD_ELEMENTS if hasattr(klass, "_pyxmpp_payload_element_name"): klass._pyxmpp_payload_element_name.append(element_name) else: klass._pyxmpp_payload_element_name = [element_name] if element_name in STANZA_PAYLOAD_CLASSES: logger = logging.getLogger('pyxmpp.payload_element_name') logger.warning("Overriding payload class for {0!r}".format( element_name)) STANZA_PAYLOAD_CLASSES[element_name] = klass STANZA_PAYLOAD_ELEMENTS[klass].append(element_name) return klass return decorator
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: "initiator" or "receiver" :Types: - `element_name`: `unicode` - `usage_restriction`: `unicode` """ def decorator(func): """The decorator""" func._pyxmpp_stream_element_handled = element_name func._pyxmpp_usage_restriction = usage_restriction return func return decorator
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 element belongs. :Types: - `xmlnode`: `libxml2.xmlNode` - `doc`: `libxml2.xmlDoc`""" _unused = doc if self.label is not None: xmlnode.setProp("label", self.label.encode("utf-8")) xmlnode.newTextChild(xmlnode.ns(), "value", self.value.encode("utf-8")) return xmlnode
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_utf8(xmlnode.prop("label")) child = xmlnode.children value = None for child in xml_element_ns_iter(xmlnode.children, DATAFORM_NS): if child.name == "value": value = from_utf8(child.getContent()) break if value is None: raise BadRequestProtocolError("No value in <option/> element") return cls(value, label)
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 type(value) is list: warnings.warn(".add_option() accepts single value now.", DeprecationWarning, stacklevel=1) value = value[0] if self.type not in ("list-multi", "list-single"): raise ValueError("Options are allowed only for list types.") option = Option(value, label) self.options.append(option) return option
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 element belongs. :Types: - `xmlnode`: `libxml2.xmlNode` - `doc`: `libxml2.xmlDoc`""" if self.type is not None and self.type not in self.allowed_types: raise ValueError("Invalid form field type: %r" % (self.type,)) if self.type is not None: xmlnode.setProp("type", self.type) if not self.label is None: xmlnode.setProp("label", to_utf8(self.label)) if not self.name is None: xmlnode.setProp("var", to_utf8(self.name)) if self.values: if self.type and len(self.values) > 1 and not self.type.endswith(u"-multi"): raise ValueError("Multiple values not allowed for %r field" % (self.type,)) for value in self.values: xmlnode.newTextChild(xmlnode.ns(), "value", to_utf8(value)) for option in self.options: option.as_xml(xmlnode, doc) if self.required: xmlnode.newChild(xmlnode.ns(), "required", None) if self.desc: xmlnode.newTextChild(xmlnode.ns(), "desc", to_utf8(self.desc)) return xmlnode
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 = xmlnode.prop("type") label = from_utf8(xmlnode.prop("label")) name = from_utf8(xmlnode.prop("var")) child = xmlnode.children values = [] options = [] required = False desc = None while child: if child.type != "element" or child.ns().content != DATAFORM_NS: pass elif child.name == "required": required = True elif child.name == "desc": desc = from_utf8(child.getContent()) elif child.name == "value": values.append(from_utf8(child.getContent())) elif child.name == "option": options.append(Option._new_from_xml(child)) child = child.next if field_type and not field_type.endswith("-multi") and len(values) > 1: raise BadRequestProtocolError("Multiple values for a single-value field") return cls(name, values, field_type, label, options, required, desc)
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 `value`. - `field_type`: field type. - `label`: field label. - `options`: optional values for the field. - `required`: `True` if the field is required. - `desc`: natural-language description of the field. - `value`: field value or values in a field_type-specific type. May be used only if `values` parameter is not provided. :Types: - `name`: `unicode` - `values`: `list` of `unicode` - `field_type`: `str` - `label`: `unicode` - `options`: `list` of `Option` - `required`: `bool` - `desc`: `unicode` - `value`: `bool` for "boolean" field, `JID` for "jid-single", `list` of `JID` for "jid-multi", `list` of `unicode` for "list-multi" and "text-multi" and `unicode` for other field types. :return: the field added. :returntype: `Field` """ field = Field(name, values, field_type, label, options, required, desc, value) self.fields.append(field) return field
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 element belongs. :Types: - `xmlnode`: `libxml2.xmlNode` - `doc`: `libxml2.xmlDoc`""" for field in self.fields: field.as_xml(xmlnode, doc)
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.children fields = [] while child: if child.type != "element" or child.ns().content != DATAFORM_NS: pass elif child.name == "field": fields.append(Field._new_from_xml(child)) child = child.next return cls(fields)
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(fields) self.items.append(item) return item
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. :Parameters: - `keep_types`: when `True` field type information will be included in the result form. That is usually not needed. :Types: - `keep_types`: `bool` :return: the form created. :returntype: `Form`""" result = Form("submit") for field in self.fields: if field.type == "fixed": continue if not field.values: if field.required: raise ValueError("Required field with no value!") continue if keep_types: result.add_field(field.name, field.values, field.type) else: result.add_field(field.name, field.values) return result
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 element belongs. :Types: - `xmlnode`: `libxml2.xmlNode` - `doc`: `libxml2.xmlDoc`""" if self.type not in self.allowed_types: raise ValueError("Form type %r not allowed." % (self.type,)) xmlnode.setProp("type", self.type) if self.type == "cancel": return ns = xmlnode.ns() if self.title is not None: xmlnode.newTextChild(ns, "title", to_utf8(self.title)) if self.instructions is not None: xmlnode.newTextChild(ns, "instructions", to_utf8(self.instructions)) for field in self.fields: field.as_xml(xmlnode, doc) if self.type != "result": return if self.reported_fields: reported = xmlnode.newChild(ns, "reported", None) for field in self.reported_fields: field.as_xml(reported, doc) for item in self.items: item.as_xml(xmlnode, doc)
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.title = None self.instructions = None if (xmlnode.type != "element" or xmlnode.name != "x" or xmlnode.ns().content != DATAFORM_NS): raise ValueError("Not a form: " + xmlnode.serialize()) self.type = xmlnode.prop("type") if not self.type in self.allowed_types: raise BadRequestProtocolError("Bad form type: %r" % (self.type,)) child = xmlnode.children while child: if child.type != "element" or child.ns().content != DATAFORM_NS: pass elif child.name == "title": self.title = from_utf8(child.getContent()) elif child.name == "instructions": self.instructions = from_utf8(child.getContent()) elif child.name == "field": self.fields.append(Field._new_from_xml(child)) elif child.name == "item": self.items.append(Item._new_from_xml(child)) elif child.name == "reported": self.__get_reported(child) child = child.next