예제 #1
0
    def __init__(
        self, name=None, to=None, typ=None, frm=None, attrs=None, payload=None, timestamp=None, xmlns=None, node=None
    ):
        """ Constructor, name is the name of the stanza i.e. "message" or "presence" or "iq".
			to is the value of "to" attribure, "typ" - "type" attribute
			frn - from attribure, attrs - other attributes mapping, payload - same meaning as for simplexml payload definition
			timestamp - the time value that needs to be stamped over stanza
			xmlns - namespace of top stanza node
			node - parsed or unparsed stana to be taken as prototype.
		"""
        if attrs is None:
            attrs = {}
        if to:
            attrs["to"] = to
        if frm:
            attrs["from"] = frm
        if typ:
            attrs["type"] = typ
        Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node)
        if not node and xmlns:
            self.setNamespace(xmlns)
        to = self.getAttr("to")
        if to:
            self.setTo(to)
        frm = self.getAttr("from")
        if frm:
            self.setFrom(frm)
        if timestamp is not None:
            self.setTimestamp(timestamp)
예제 #2
0
    def bind(self, resource):
        while self.bound is None and self.owner.process(1):
            pass

        resource = Node('resource', payload=[resource])
        res = self.owner.Dispatcher.send_and_wait_for_response(
            Protocol('iq',
                     tye='set',
                     payload=[
                         Node('bind',
                              attrs={'xmlns': NS_BIND},
                              payload=[resource])
                     ]))
        if is_result_node(res):
            self.bound.append(res.get_tag('bind').get_tag_data('jid'))
            jid = JID(res.get_tag('bind').get_tag_data('jid'))
            self.owner.user = jid.get_node()
            self.owner.resource = jid.get_resource()
            self.enable()
            res = self.owner.Dispatcher.send_and_wait_for_response(
                Protocol(
                    'iq',
                    tye='set',
                    payload=[Node('session', attrs={'xmlns': NS_SESSION})]))
            if is_result_node(res):
                self.session = 1
                return 'ok'
            else:
                self.session = 0
        else:
            return ''
예제 #3
0
def gen_error(node,
              error_code='500',
              error_type='wait',
              error_name='internal-server-error',
              text=None,
              childs=False):
    """Генерирует ошибку из Node. По умолчанию internal-server-error."""
    err = Node(node.getName())
    if node['to']: err['from'] = node['to']
    if node['from']: err['to'] = node['from']
    if node['id']: err['id'] = node['id']
    err['type'] = 'error'
    if childs:
        for c in node.getChildren():
            if not c: continue
            err.addChild(node=c)
    e = err.addChild('error')
    e['type'] = error_type
    e['code'] = error_code
    e.addChild(error_name).setNamespace("urn:ietf:params:xml:ns:xmpp-stanzas")
    if text:
        t = e.addChild("text")
        t.setNamespace("urn:ietf:params:xml:ns:xmpp-stanzas")
        t.addData(text)
    return err
예제 #4
0
 def __init__(self, name=None, value=None, typ=None, required=0, label=None, desc=None, options=None, node=None):
     """ Create new data field of specified name,value and type.
         Also 'required','desc' and 'options' fields can be set.
         Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new datafiled.
         """
     if options is None:
         options = []
     Node.__init__(self, "field", node=node)
     if name:
         self.setVar(name)
     if type(value) in [list, tuple]:
         self.setValues(value)
     elif value:
         self.setValue(value)
     if typ:
         self.setType(typ)
     elif not typ and not node:
         self.setType("text-single")
     if required:
         self.setRequired(required)
     if label:
         self.setLabel(label)
     if desc:
         self.setDesc(desc)
     if options:
         self.setOptions(options)
예제 #5
0
 def __init__(self, typ=None, data=[], title=None, node=None):
     """
         title and instructions: optional. SHOULD NOT contain newlines.
         Several instructions MAY be present.
         type={ form | submit | cancel | result } # iq: { result | set | set | result }
         'cancel' form contains no fields. Other forms contains AT LEAST one field.
         title MAY be included in forms of type "form|result"
     """
     Node.__init__(self, 'x', node=node)
     if node:
         newkids = []
         for n in self.getChildren():
             if n.getName() == 'field': newkids.append(DataField(node=n))
             else: newkids.append(n)
         self.kids = newkids
     if typ: self.setType(typ)
     self.setNamespace(NS_DATA)
     if title: self.setTitle(title)
     if type(data) == type({}):
         newdata = []
         for name in data.keys():
             newdata.append(DataField(name, data[name]))
         data = newdata
     for child in data:
         if type(child) in [type(''), type(u'')]:
             self.addInstructions(child)
         elif child.__class__.__name__ == 'DataField':
             self.kids.append(child)
         else:
             self.kids.append(DataField(node=child))
예제 #6
0
    def __init__(self, typ=None, data=[], title=None, node=None):
        """
            Create new dataform of type 'typ'. 'data' is the list of DataField
            instances that this dataform contains, 'title' - the title string.
            You can specify the 'node' argument as the other node to be used as
            base for constructing this dataform.

            title and instructions is optional and SHOULD NOT contain newlines.
            Several instructions MAY be present.
            'typ' can be one of ('form' | 'submit' | 'cancel' | 'result' )
            'typ' of reply iq can be ( 'result' | 'set' | 'set' | 'result' ) respectively.
            'cancel' form can not contain any fields. All other forms contains AT LEAST one field.
            'title' MAY be included in forms of type "form" and "result"
        """
        Node.__init__(self, 'x', node=node)
        if node:
            newkids = []
            for n in self.getChildren():
                if n.getName() == 'field': newkids.append(DataField(node=n))
                else: newkids.append(n)
            self.kids = newkids
        if typ: self.setType(typ)
        self.setNamespace(NS_DATA)
        if title: self.setTitle(title)
        if isinstance(data, dict):
            newdata = []
            for name in data.keys():
                newdata.append(DataField(name, data[name]))
            data = newdata
        for child in data:
            if isinstance(child, basestring): self.addInstructions(child)
            elif child.__class__.__name__ == 'DataField':
                self.kids.append(child)
            else:
                self.kids.append(DataField(node=child))
예제 #7
0
 def __init__(self,
              name=None,
              to=None,
              typ=None,
              frm=None,
              attrs={},
              payload=[],
              timestamp=None,
              xmlns=NS_CLIENT,
              node=None):
     if not attrs: attrs = {}
     if to: attrs['to'] = to
     if frm: attrs['from'] = frm
     if typ: attrs['type'] = typ
     Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node)
     if not node: self.setNamespace(xmlns)
     if self['to']: self.setTo(self['to'])
     if self['from']: self.setFrom(self['from'])
     if node and type(self) == type(
             node
     ) and self.__class__ == node.__class__ and self.attrs.has_key('id'):
         del self.attrs['id']
     self.timestamp = None
     for x in self.getTags('x', namespace=NS_DELAY):
         try:
             if x.getAttr('stamp') > self.getTimestamp():
                 self.setTimestamp(x.getAttr('stamp'))
         except:
             pass
     if timestamp is not None:
         self.setTimestamp(
             timestamp)  # To auto-timestamp stanza just pass timestamp=''
예제 #8
0
    def __init__(self, typ=None, data=[], title=None, node=None):
        """
            Create new dataform of type 'typ'. 'data' is the list of DataField
            instances that this dataform contains, 'title' - the title string.
            You can specify the 'node' argument as the other node to be used as
            base for constructing this dataform.

            title and instructions is optional and SHOULD NOT contain newlines.
            Several instructions MAY be present.
            'typ' can be one of ('form' | 'submit' | 'cancel' | 'result' )
            'typ' of reply iq can be ( 'result' | 'set' | 'set' | 'result' ) respectively.
            'cancel' form can not contain any fields. All other forms contains AT LEAST one field.
            'title' MAY be included in forms of type "form" and "result"
        """
        Node.__init__(self,'x',node=node)
        if node:
            newkids=[]
            for n in self.getChildren():
                if n.getName()=='field': newkids.append(DataField(node=n))
                else: newkids.append(n)
            self.kids=newkids
        if typ: self.setType(typ)
        self.setNamespace(NS_DATA)
        if title: self.setTitle(title)
        if type(data)==type({}):
            newdata=[]
            for name in data.keys(): newdata.append(DataField(name,data[name]))
            data=newdata
        for child in data:
            if type(child) in [type(''),type(u'')]: self.addInstructions(child)
            elif child.__class__.__name__=='DataField': self.kids.append(child)
            else: self.kids.append(DataField(node=child))
예제 #9
0
    def __init__(self,
                 name=None,
                 to=None,
                 typ=None,
                 frm=None,
                 attrs=None,
                 xmlns=NS_CLIENT,
                 node=None):
        """ Constructor, name is the name of the stanza i.e. "message" or "presence" or "iq".
			to is the value of "to" attribure, "typ" - "type" attribute
			frn - from attribure, attrs - other attributes mapping, payload - same meaning as for simplexml payload definition
			xmlns - namespace of top stanza node
			node - parsed or unparsed stana to be taken as prototype.
		"""
        if not attrs:
            attrs = {}
        if to:
            attrs["to"] = to
        if frm:
            attrs["from"] = frm
        if typ:
            attrs["type"] = typ
        Node.__init__(self, name=name, attrs=attrs, node=node)
        if xmlns and not node:
            self.setXMLNS(xmlns)
        to = self.getAttr("to")
        if to:
            self.setTo(to)
        frm = self.getAttr("from")
        if frm:
            self.setFrom(frm)
예제 #10
0
 def __init__(self, name=None, to=None, typ=None, frm=None, attrs={}, payload=[], timestamp=None, xmlns=None, node=None):
     """ Constructor, name is the name of the stanza i.e. 'message' or 'presence' or 'iq'.
         to is the value of 'to' attribure, 'typ' - 'type' attribute
         frn - from attribure, attrs - other attributes mapping, payload - same meaning as for simplexml payload definition
         timestamp - the time value that needs to be stamped over stanza
         xmlns - namespace of top stanza node
         node - parsed or unparsed stana to be taken as prototype.
     """
     if not attrs: attrs={}
     if to: attrs['to']=to
     if frm: attrs['from']=frm
     if typ: attrs['type']=typ
     Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node)
     if not node and xmlns: self.setNamespace(xmlns)
     if self['to']: self.setTo(self['to'])
     if self['from']: self.setFrom(self['from'])
     if node and isinstance(self, type(node)) and self.__class__==node.__class__ and 'id' in self.attrs: del self.attrs['id']
     self.timestamp=None
     for d in self.getTags('delay',namespace=NS_DELAY2):
         try:
             if d.getAttr('stamp')<self.getTimestamp2(): self.setTimestamp(d.getAttr('stamp'))
         except: pass
     if not self.timestamp:
         for x in self.getTags('x',namespace=NS_DELAY):
             try:
                 if x.getAttr('stamp')<self.getTimestamp(): self.setTimestamp(x.getAttr('stamp'))
             except: pass
     if timestamp is not None: self.setTimestamp(timestamp)  # To auto-timestamp stanza just pass timestamp=''
예제 #11
0
 def __init__(self,data=None,node=None):
     Node.__init__(self,'x',node=node)
     self.setNamespace(NS_DATA)
     dict={}
     if type(data) in [type(()),type([])]:
         for i in data: dict[i]=''
     elif data: dict=data
     for key in dict.keys():
         self.setField(key,dict[key])
예제 #12
0
def gen_iq_result(iq, query=None):
    """Генерирует iq-result из iq-get/set.
	iq - iq-get/set Node, из которого генерировать result
	query - Node, который добавить в iq-result"""
    node = Node('iq')
    node['type'] = 'result'
    if iq['from']: node['to'] = iq['from']
    node['id'] = iq['id']
    node['from'] = iq['to']
    if query and isinstance(query, Node): node.addChild(node=query)
    return node
예제 #13
0
 def __init__(self, data=None, node=None):
     Node.__init__(self, 'x', node=node)
     self.setNamespace(NS_DATA)
     dict = {}
     if type(data) in [type(()), type([])]:
         for i in data:
             dict[i] = ''
     elif data:
         dict = data
     for key in dict.keys():
         self.setField(key, dict[key])
예제 #14
0
    def __init__(self, node=None):
        """ Create new empty data item. However, note that, according XEP-0004, DataItem MUST contain ALL
			DataFields described in DataReported.
			Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new
			dataitem.
			"""
        Node.__init__(self, 'item', node=node)
        if node:
            newkids = []
            for n in self.getChildren():
                if n.getName() == 'field': newkids.append(DataField(node=n))
                else: newkids.append(n)
            self.kids = newkids
예제 #15
0
	def __init__(self,node=None):
		""" Create new empty data item. However, note that, according XEP-0004, DataItem MUST contain ALL
			DataFields described in DataReported.
			Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new
			dataitem.
			"""
		Node.__init__(self,'item',node=node)
		if node:
			newkids=[]
			for n in self.getChildren():
				if	n.getName()=='field': newkids.append(DataField(node=n))
				else: newkids.append(n)
			self.kids=newkids
예제 #16
0
 def __init__(self, name=None, to=None, typ=None, frm=None, attrs={}, payload=[], timestamp=None, node=None):
     if not attrs: attrs={}
     if to: attrs['to']=to
     if frm: attrs['from']=frm
     if typ: attrs['type']=typ
     Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node)
     if node and type(self)==type(node) and self.__class__==node.__class__ and self.attrs.has_key('id'): del self.attrs['id']
     self.timestamp=None
     for x in self.getTags('x',namespace=NS_DELAY):
         try:
             if x.getAttr('stamp')>self.getTimestamp(): self.setTimestamp(x.getAttr('stamp'))
         except: pass
     if timestamp is not None: self.setTimestamp(timestamp)  # To auto-timestamp stanza just pass timestamp=''
예제 #17
0
 def __init__(self,name,code=None,typ=None,text=None):
     """ Mandatory parameter: name
         Optional parameters: code, typ, text."""
     if ERRORS.has_key(name): cod,type,txt=ERRORS[name]
     else: cod,type,txt='','cancel',''
     if typ: type=typ
     if code: cod=code
     if text: txt=text
     Node.__init__(self,'error',{'type':type},[Node(NS_STANZAS+' '+name)])
     if txt:
         self.addChild(node=Node(NS_STANZAS+' text',{},[txt]))
         self.addData(txt)
     if cod: self.setAttr('code',cod)
예제 #18
0
    def features_handler(self, dis, feature):
        if not feature.get_tag("mechanisms", namespace=NS_SASL):
            self.startsasl = "not-supported"
            return

        mecs = []
        for mec in feature.get_tag("mechanisms",
                                   namespace=NS_SASL).get_tags("mechanism"):
            mecs.append(mec.get_data())

        self.owner.register_handler("challenge",
                                    self.sasl_handler,
                                    xmlns=NS_SASL)
        self.owner.register_handler("failure",
                                    self.sasl_handler,
                                    xmlns=NS_SASL)
        self.owner.register_handler("success",
                                    self.sasl_handler,
                                    xmlns=NS_SASL)

        if "ANONYMOUS" in mecs and self.username == None:
            node = Node('auth',
                        attrs={
                            "xmlns": NS_SASL,
                            "mechanism": "ANONYMOUS"
                        })
        elif "DIGEST-MD5" in mecs:
            node = Node('auth',
                        attrs={
                            "xmlns": NS_SASL,
                            "mechanism": "DIGEST-MD5"
                        })
        elif "PLAIN" in mecs:
            sasl_data = "%s\x00%s\x00%s" % (self.username + '@' +
                                            self.owner.server, self.username,
                                            self.password)
            node = Node('auth',
                        attrs={
                            "xmlns": NS_SASL,
                            "mechanism": "PLAIN"
                        },
                        payload=[
                            base64.encodestring(sasl_data).replace(
                                '\r', '').replace('\n', '')
                        ])
        else:
            self.startsasl = "fail"
            return

        self.startsasl = "in-process"
        self.owner.send(str(node))
예제 #19
0
 def __init__(self,name=None,value=None,typ=None,required=0,desc=None,options=[],node=None):
     """ Create new data field of specified name,value and type.
         Also 'required','desc' and 'options' fields can be set.
         Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new datafiled.
         """
     Node.__init__(self,'field',node=node)
     if name: self.setVar(name)
     if isinstance(value, (list, tuple)): self.setValues(value)
     elif value: self.setValue(value)
     if typ: self.setType(typ)
     elif not typ and not node: self.setType('text-single')
     if required: self.setRequired(required)
     if desc: self.setDesc(desc)
     if options: self.setOptions(options)
예제 #20
0
 def __init__(self, name, code=None, typ=None, text=None):
     """ Mandatory parameter: name
         Optional parameters: code, typ, text."""
     if ERRORS.has_key(name): cod, type, txt = ERRORS[name]
     else: cod, type, txt = '', 'cancel', ''
     if typ: type = typ
     if code: cod = code
     if text: txt = text
     Node.__init__(self, 'error', {'type': type},
                   [Node(NS_STANZAS + ' ' + name)])
     if txt:
         self.addChild(node=Node(NS_STANZAS + ' text', {}, [txt]))
         self.addData(txt)
     if cod: self.setAttr('code', cod)
예제 #21
0
    def __init__(self, node=None):
        """ Create new empty 'reported data' field. However, note that, according XEP-0004:
			* It MUST contain one or more DataFields.
			* Contained DataFields SHOULD possess a 'type' and 'label' attribute in addition to 'var' attribute
			* Contained DataFields SHOULD NOT contain a <value/> element.
			Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new
			dataitem.
		"""
        Node.__init__(self, 'reported', node=node)
        if node:
            newkids = []
            for n in self.getChildren():
                if n.getName() == 'field': newkids.append(DataField(node=n))
                else: newkids.append(n)
            self.kids = newkids
예제 #22
0
	def __init__(self,node=None):
		""" Create new empty 'reported data' field. However, note that, according XEP-0004:
			* It MUST contain one or more DataFields.
			* Contained DataFields SHOULD possess a 'type' and 'label' attribute in addition to 'var' attribute
			* Contained DataFields SHOULD NOT contain a <value/> element.
			Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new
			dataitem.
		"""
		Node.__init__(self,'reported',node=node)
		if node:
			newkids=[]
			for n in self.getChildren():
				if	n.getName()=='field': newkids.append(DataField(node=n))
				else: newkids.append(n)
			self.kids=newkids
예제 #23
0
 def __init__(self, name, code=None, typ=None, text=None):
     """ Mandatory parameter: name
         Optional parameters: code, typ, text."""
     if ERRORS.has_key(name):
         cod, type, txt = ERRORS[name]
         ns = name.split()[0]
     else:
         cod, ns, type, txt = '500', NS_STANZAS, 'cancel', ''
     if typ: type = typ
     if code: cod = code
     if text: txt = text
     Node.__init__(self, 'error', {}, [Node(name)])
     if type: self.setAttr('type', type)
     if not cod: self.setName('stream:error')
     if txt: self.addChild(node=Node(ns + ' text', {}, [txt]))
     if cod: self.setAttr('code', cod)
예제 #24
0
 def __init__(self,name,code=None,typ=None,text=None):
     """ Create new error node object.
         Mandatory parameter: name - name of error condition.
         Optional parameters: code, typ, text. Used for backwards compartibility with older jabber protocol."""
     if ERRORS.has_key(name):
         cod,type,txt=ERRORS[name]
         ns=name.split()[0]
     else: cod,ns,type,txt='500',NS_STANZAS,'cancel',''
     if typ: type=typ
     if code: cod=code
     if text: txt=text
     Node.__init__(self,'error',{},[Node(name)])
     if type: self.setAttr('type',type)
     if not cod: self.setName('stream:error')
     if txt: self.addChild(node=Node(ns+' text',{},[txt]))
     if cod: self.setAttr('code',cod)
예제 #25
0
 def __init__(self,
              name=None,
              value=None,
              typ=None,
              required=0,
              desc=None,
              options=[],
              node=None):
     Node.__init__(self, 'field', node=node)
     if name: self.setVar(name)
     if type(value) in [list, tuple]: self.setValues(value)
     elif value: self.setValue(value)
     if typ: self.setType(typ)
     elif not typ and not node: self.setType('text-single')
     if required: self.setRequired(required)
     if desc: self.setDesc(desc)
     if options: self.setOptions(options)
예제 #26
0
 def __init__(self,
              name=None,
              to=None,
              typ=None,
              frm=None,
              attrs={},
              payload=[],
              timestamp=None,
              xmlns=None,
              node=None):
     """ Constructor, name is the name of the stanza i.e. 'message' or 'presence' or 'iq'.
         to is the value of 'to' attribure, 'typ' - 'type' attribute
         frn - from attribure, attrs - other attributes mapping, payload - same meaning as for simplexml payload definition
         timestamp - the time value that needs to be stamped over stanza
         xmlns - namespace of top stanza node
         node - parsed or unparsed stana to be taken as prototype.
     """
     if not attrs: attrs = {}
     if to: attrs['to'] = to
     if frm: attrs['from'] = frm
     if typ: attrs['type'] = typ
     Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node)
     if not node and xmlns: self.setNamespace(xmlns)
     if self['to']: self.setTo(self['to'])
     if self['from']: self.setFrom(self['from'])
     if node and isinstance(
             self, type(node)
     ) and self.__class__ == node.__class__ and 'id' in self.attrs:
         del self.attrs['id']
     self.timestamp = None
     for d in self.getTags('delay', namespace=NS_DELAY2):
         try:
             if d.getAttr('stamp') < self.getTimestamp2():
                 self.setTimestamp(d.getAttr('stamp'))
         except:
             pass
     if not self.timestamp:
         for x in self.getTags('x', namespace=NS_DELAY):
             try:
                 if x.getAttr('stamp') < self.getTimestamp():
                     self.setTimestamp(x.getAttr('stamp'))
             except:
                 pass
     if timestamp is not None:
         self.setTimestamp(
             timestamp)  # To auto-timestamp stanza just pass timestamp=''
예제 #27
0
 def __init__(self, name, code=None, typ=None, text=None):
     """ Create new error node object.
         Mandatory parameter: name - name of error condition.
         Optional parameters: code, typ, text. Used for backwards compartibility with older jabber protocol."""
     if ERRORS.has_key(name):
         cod, type, txt = ERRORS[name]
         ns = name.split()[0]
     else:
         cod, ns, type, txt = '500', NS_STANZAS, 'cancel', ''
     if typ: type = typ
     if code: cod = code
     if text: txt = text
     Node.__init__(self, 'error', {}, [Node(name)])
     if type: self.setAttr('type', type)
     if not cod: self.setName('stream:error')
     if txt: self.addChild(node=Node(ns + ' text', {}, [txt]))
     if cod: self.setAttr('code', cod)
예제 #28
0
 def enable(self):
     self.owner.send(
         Node('enable', attrs={
             'xmlns': NS_SESSION_TWO,
             'resume': 'true'
         }))
     self.owner.Dispatcher.register_handler('enabled',
                                            self.enable_handler,
                                            xmlns=NS_SESSION_TWO)
     while not self.owner.process(1):
         pass
예제 #29
0
 def __init__(self,
              name=None,
              value=None,
              typ=None,
              required=0,
              desc=None,
              options=[],
              node=None):
     """ Create new data field of specified name,value and type.
         Also 'required','desc' and 'options' fields can be set.
         Alternatively other XML object can be passed in as the 'node' parameted to replicate it as a new datafiled.
         """
     Node.__init__(self, 'field', node=node)
     if name: self.setVar(name)
     if type(value) in [list, tuple]: self.setValues(value)
     elif value: self.setValue(value)
     if typ: self.setType(typ)
     elif not typ and not node: self.setType('text-single')
     if required: self.setRequired(required)
     if desc: self.setDesc(desc)
     if options: self.setOptions(options)
예제 #30
0
 def __init__(
     self, name=None, to=None, typ=None, frm=None, attrs=None, payload=None, timestamp=None, xmlns=None, node=None
 ):
     """ Constructor, name is the name of the stanza i.e. 'message' or 'presence' or 'iq'.
         to is the value of 'to' attribure, 'typ' - 'type' attribute
         frn - from attribure, attrs - other attributes mapping, payload - same meaning as for simplexml payload definition
         timestamp - the time value that needs to be stamped over stanza
         xmlns - namespace of top stanza node
         node - parsed or unparsed stana to be taken as prototype.
     """
     if attrs is None:
         attrs = {}
     if payload is None:
         payload = []
     if not attrs:
         attrs = {}
     if to:
         attrs["to"] = to
     if frm:
         attrs["from"] = frm
     if typ:
         attrs["type"] = typ
     Node.__init__(self, tag=name, attrs=attrs, payload=payload, node=node)
     if not node and xmlns:
         self.setNamespace(xmlns)
     if self["to"]:
         self.setTo(self["to"])
     if self["from"]:
         self.setFrom(self["from"])
     if node and type(self) == type(node) and self.__class__ == node.__class__ and self.attrs.has_key("id"):
         del self.attrs["id"]
     self.timestamp = None
     for x in self.getTags("x", namespace=NS_DELAY):
         try:
             if not self.getTimestamp() or x.getAttr("stamp") < self.getTimestamp():
                 self.setTimestamp(x.getAttr("stamp"))
         except:
             pass
     if timestamp is not None:
         self.setTimestamp(timestamp)  # To auto-timestamp stanza just pass timestamp=''
예제 #31
0
	def __init__(self, name=None, to=None, typ=None, frm=None, attrs=None, xmlns=NS_CLIENT, node=None):
		""" Constructor, name is the name of the stanza i.e. "message" or "presence" or "iq".
			to is the value of "to" attribure, "typ" - "type" attribute
			frn - from attribure, attrs - other attributes mapping, payload - same meaning as for simplexml payload definition
			xmlns - namespace of top stanza node
			node - parsed or unparsed stana to be taken as prototype.
		"""
		if not attrs:
			attrs = {}
		if to:
			attrs["to"] = to
		if frm:
			attrs["from"] = frm
		if typ:
			attrs["type"] = typ
		Node.__init__(self, name=name, attrs=attrs, node=node)
		if xmlns and not node:
			self.setXMLNS(xmlns)
		to = self.getAttr("to")
		if to:
			self.setTo(to)
		frm = self.getAttr("from")
		if frm:
			self.setFrom(frm)
예제 #32
0
def node_reader(read, nb=None):
    """Читает входящие данные и возвращает по одному объекту Node."""
    if not nb:
        nb = NodeBuilder()
        #nb.Parse('<stream:stream xmlns="jabber:client">')
    #print 'go'

    if nb.has_received_endtag(1) and nb.getDom().getChildren():
        for node in nb.getDom().getChildren():
            yield node

    while 1:
        d = read()
        #print d
        #print 'read',d
        if not d:
            #print 'no data'
            return
        while '<?' in d:
            d1, nd = d.split('<?', 1)
            nd, d2 = nd.split('>', 1)
            d = d1 + d2
            d = d.strip()
            del nd
        #print 'parse',d
        nb.Parse(d.replace('\x00', ''))
        if not nb.has_received_endtag(1) or not nb.getDom().getChildren():
            if nb.has_received_endtag(0):
                #print nb.getDom()
                #print 'ret'
                return
            elif nb.getDom() and not nb.getDom().getChildren():
                yield Node(node=nb.getDom())
                #nb.getDom().namespace = None
                #if nb.getDom().attrs.get('xmlns'):
                #    nb.getDom().attrs.pop('xmlns')
                #nb.getDom().nsp_cache={}
            #else: print 'wtf?', unicode(nb.getDom()).encode('utf-8'), unicode(nb.getDom().getChildren()[0]).encode('utf-8')
            continue
        #print unicode(nb.getDom()).encode('utf-8')
        for node in nb.getDom().getChildren():
            #self.last_node=node
            node.parent = None
            yield node
        nb.getDom().setPayload([])
예제 #33
0
    def sasl_handler(self, conn, challenge):
        if challenge.get_namespace() != NS_SASL:
            return

        if challenge.get_name() == "failure":
            self.startsasl = "failure"
            try:
                reason = challenge.get_children()[0]
            except Exception as e:
                print e
                reason = challenge
            print str(reason)
            return
        elif challenge.get_name() == "success":
            self.startsasl = "success"
            handlers = self.owner.Dispatcher.dump_handlers()
            self.owner.Dispatcher.Plugout()
            Dispatcher().Plugin(self.owner)
            self.owner.Dispatcher.store_handlers(handlers)
            return
        else:
            incoming_data = challenge.get_data()
            data = base64.decodestring(incoming_data)
            chal = {}
            for pair in re.findall('(\w+\s*=\s*(?:(?:"[^"]+")|(?:[^,]+)))',
                                   data):
                key, val = [x.strip() for x in pair.split("=", 1)]
                if val[0] == '"' and val[-1] == '"':
                    val = val[1:-1]
                chal[key] = val

            if chal.has_key("qop") and "auth" in [
                    x.strip() for x in chal['qop'].split(",")
            ]:
                res = {}
                res['username'] = self.username
                res['realm'] = self.owner.server
                res['nonce'] = chal['nonce']
                cnonce = ''
                for i in range(7):
                    cnonce += hex(int(random.random() * 65536 * 4096))[2:]
                res['cnonce'] = cnonce
                res['nc'] = ('00000001')
                res['qop'] = 'auth'
                res['digest-uri'] = 'xmpp/localhost'
                A1 = C([
                    H(C([res['username'], res['realm'], self.password])),
                    res['nonce'], res['cnonce']
                ])
                A2 = C(['AUTHENTICATE', res['digest-uri']])
                response = HH(
                    C([
                        HH(A1), res['nonce'], res['nc'], res['cnonce'],
                        res['qop'],
                        HH(A2)
                    ]))
                res['response'] = response
                res['charset'] = 'utf-8'
                sasl_data = ''
                for key in [
                        'charset', 'username', 'realm', 'nonce', 'nc',
                        'cnonce', 'digest-uri', 'response', 'qop'
                ]:
                    if key in ['nc', 'qop', 'response', 'charset']:
                        sasl_data += "%s=%s," % (key, res[key])
                    else:
                        sasl_data += '%s="%s",' % (key, res[key])
                node = Node("response",
                            attrs={'xmlns': NS_SASL},
                            payload=[
                                base64.encodestring(sasl_data[:-1]).replace(
                                    '\r', '').replace('\n', '')
                            ])
                self.owner.send(str(node))
            elif chal.has_key("rspauth"):
                node = Node("response", attrs={'xmlns': NS_SASL})
                self.owner.send(str(node))
            else:
                self.startsasl = "failure"
예제 #34
0
 def handler_a(self, dis, stanza):
     global R_H
     R_H += 1
     _id = R_H
     self.send(Node('a', attrs={'xmlns': NS_SESSION_TWO, 'h': _id}))