_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q259700 | XMPPSerializer.emit_head | validation | def emit_head(self, stream_from, stream_to, stream_id = None,
version = u'1.0', language = None):
"""Return the opening tag of the stream root element.
:Parameters:
- `stream_from`: the 'from' attribute of the stream. May be `None`.
- `stream_to`: the 'to' attribute of the stream. May be `None`.
- `version`: the 'version' of the stream.
- `language`: the 'xml:lang' of the stream
:Types:
- `stream_from`: `unicode`
- `stream_to`: `unicode`
- `version`: `unicode`
- `language`: `unicode`
"""
# pylint: disable-msg=R0913
self._root_prefixes = dict(STANDARD_PREFIXES)
self._root_prefixes[self.stanza_namespace] = None
for namespace, prefix in self._root_prefixes.items():
if not prefix or prefix == "stream":
continue
if namespace in STANDARD_PREFIXES or namespace in STANZA_NAMESPACES:
continue
self._root_prefixes[namespace] = prefix
tag = u"<{0}:stream version={1}".format(STANDARD_PREFIXES[STREAM_NS],
quoteattr(version))
if stream_from:
tag += u" from={0}".format(quoteattr(stream_from))
if stream_to:
tag += u" to={0}".format(quoteattr(stream_to))
if stream_id is not None:
tag += u" id={0}".format(quoteattr(stream_id))
if language is not None:
tag += u" xml:lang={0}".format(quoteattr(language))
for namespace, prefix in self._root_prefixes.items():
if prefix == "xml":
continue
if prefix:
tag += u' xmlns:{0}={1}'.format(prefix, quoteattr(namespace))
else:
tag += u' xmlns={1}'.format(prefix, quoteattr(namespace))
tag += u">"
self._head_emitted = True
return tag | python | {
"resource": ""
} |
q259701 | XMPPSerializer._split_qname | validation | def _split_qname(self, name, is_element):
"""Split an element of attribute qname into namespace and local
name.
:Parameters:
- `name`: element or attribute QName
- `is_element`: `True` for an element, `False` for an attribute
:Types:
- `name`: `unicode`
- `is_element`: `bool`
:Return: namespace URI, local name
:returntype: `unicode`, `unicode`"""
if name.startswith(u"{"):
namespace, name = name[1:].split(u"}", 1)
if namespace in STANZA_NAMESPACES:
namespace = self.stanza_namespace
elif is_element:
raise ValueError(u"Element with no namespace: {0!r}".format(name))
else:
namespace = None
return namespace, name | python | {
"resource": ""
} |
q259702 | XMPPSerializer._make_prefix | validation | def _make_prefix(self, declared_prefixes):
"""Make up a new namespace prefix, which won't conflict
with `_prefixes` and prefixes declared in the current scope.
:Parameters:
- `declared_prefixes`: namespace to prefix mapping for the current
scope
:Types:
- `declared_prefixes`: `unicode` to `unicode` dictionary
:Returns: a new prefix
:Returntype: `unicode`
"""
used_prefixes = set(self._prefixes.values())
used_prefixes |= set(declared_prefixes.values())
while True:
prefix = u"ns{0}".format(self._next_id)
self._next_id += 1
if prefix not in used_prefixes:
break
return prefix | python | {
"resource": ""
} |
q259703 | XMPPSerializer._make_prefixed | validation | def _make_prefixed(self, name, is_element, declared_prefixes, declarations):
"""Return namespace-prefixed tag or attribute name.
Add appropriate declaration to `declarations` when neccessary.
If no prefix for an element namespace is defined, make the elements
namespace default (no prefix). For attributes, make up a prefix in such
case.
:Parameters:
- `name`: QName ('{namespace-uri}local-name')
to convert
- `is_element`: `True` for element, `False` for an attribute
- `declared_prefixes`: mapping of prefixes already declared
at this scope
- `declarations`: XMLNS declarations on the current element.
:Types:
- `name`: `unicode`
- `is_element`: `bool`
- `declared_prefixes`: `unicode` to `unicode` dictionary
- `declarations`: `unicode` to `unicode` dictionary
:Returntype: `unicode`"""
namespace, name = self._split_qname(name, is_element)
if namespace is None:
prefix = None
elif namespace in declared_prefixes:
prefix = declared_prefixes[namespace]
elif namespace in self._prefixes:
prefix = self._prefixes[namespace]
declarations[namespace] = prefix
declared_prefixes[namespace] = prefix
else:
if is_element:
prefix = None
else:
prefix = self._make_prefix(declared_prefixes)
declarations[namespace] = prefix
declared_prefixes[namespace] = prefix
if prefix:
return prefix + u":" + name
else:
return name | python | {
"resource": ""
} |
q259704 | XMPPSerializer._make_ns_declarations | validation | def _make_ns_declarations(declarations, declared_prefixes):
"""Build namespace declarations and remove obsoleted mappings
from `declared_prefixes`.
:Parameters:
- `declarations`: namespace to prefix mapping of the new
declarations
- `declared_prefixes`: namespace to prefix mapping of already
declared prefixes.
:Types:
- `declarations`: `unicode` to `unicode` dictionary
- `declared_prefixes`: `unicode` to `unicode` dictionary
:Return: string of namespace declarations to be used in a start tag
:Returntype: `unicode`
"""
result = []
for namespace, prefix in declarations.items():
if prefix:
result.append(u' xmlns:{0}={1}'.format(prefix, quoteattr(
namespace)))
else:
result.append(u' xmlns={1}'.format(prefix, quoteattr(
namespace)))
for d_namespace, d_prefix in declared_prefixes.items():
if (not prefix and not d_prefix) or d_prefix == prefix:
if namespace != d_namespace:
del declared_prefixes[d_namespace]
return u" ".join(result) | python | {
"resource": ""
} |
q259705 | XMPPSerializer._emit_element | validation | def _emit_element(self, element, level, declared_prefixes):
""""Recursive XML element serializer.
:Parameters:
- `element`: the element to serialize
- `level`: nest level (0 - root element, 1 - stanzas, etc.)
- `declared_prefixes`: namespace to prefix mapping of already
declared prefixes.
:Types:
- `element`: :etree:`ElementTree.Element`
- `level`: `int`
- `declared_prefixes`: `unicode` to `unicode` dictionary
:Return: serialized element
:Returntype: `unicode`
"""
declarations = {}
declared_prefixes = dict(declared_prefixes)
name = element.tag
prefixed = self._make_prefixed(name, True, declared_prefixes,
declarations)
start_tag = u"<{0}".format(prefixed)
end_tag = u"</{0}>".format(prefixed)
for name, value in element.items():
prefixed = self._make_prefixed(name, False, declared_prefixes,
declarations)
start_tag += u' {0}={1}'.format(prefixed, quoteattr(value))
declarations = self._make_ns_declarations(declarations,
declared_prefixes)
if declarations:
start_tag += u" " + declarations
children = []
for child in element:
children.append(self._emit_element(child, level +1,
declared_prefixes))
if not children and not element.text:
start_tag += u"/>"
end_tag = u""
text = u""
else:
start_tag += u">"
if level > 0 and element.text:
text = escape(element.text)
else:
text = u""
if level > 1 and element.tail:
tail = escape(element.tail)
else:
tail = u""
return start_tag + text + u''.join(children) + end_tag + tail | python | {
"resource": ""
} |
q259706 | XMPPSerializer.emit_stanza | validation | def emit_stanza(self, element):
""""Serialize a stanza.
Must be called after `emit_head`.
:Parameters:
- `element`: the element to serialize
:Types:
- `element`: :etree:`ElementTree.Element`
:Return: serialized element
:Returntype: `unicode`
"""
if not self._head_emitted:
raise RuntimeError(".emit_head() must be called first.")
string = self._emit_element(element, level = 1,
declared_prefixes = self._root_prefixes)
return remove_evil_characters(string) | python | {
"resource": ""
} |
q259707 | filter_mechanism_list | validation | def filter_mechanism_list(mechanisms, properties, allow_insecure = False,
server_side = False):
"""Filter a mechanisms list only to include those mechanisms that cans
succeed with the provided properties and are secure enough.
:Parameters:
- `mechanisms`: list of the mechanisms names
- `properties`: available authentication properties
- `allow_insecure`: allow insecure mechanisms
:Types:
- `mechanisms`: sequence of `unicode`
- `properties`: mapping
- `allow_insecure`: `bool`
:returntype: `list` of `unicode`
"""
# pylint: disable=W0212
result = []
for mechanism in mechanisms:
try:
if server_side:
klass = SERVER_MECHANISMS_D[mechanism]
else:
klass = CLIENT_MECHANISMS_D[mechanism]
except KeyError:
logger.debug(" skipping {0} - not supported".format(mechanism))
continue
secure = properties.get("security-layer")
if not allow_insecure and not klass._pyxmpp_sasl_secure and not secure:
logger.debug(" skipping {0}, as it is not secure".format(mechanism))
continue
if not klass.are_properties_sufficient(properties):
logger.debug(" skipping {0}, as the properties are not sufficient"
.format(mechanism))
continue
result.append(mechanism)
return result | python | {
"resource": ""
} |
q259708 | MucRoomHandler.error | validation | def error(self,stanza):
"""
Called when an error stanza is received.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`
"""
err=stanza.get_error()
self.__logger.debug("Error from: %r Condition: %r"
% (stanza.get_from(),err.get_condition)) | python | {
"resource": ""
} |
q259709 | MucRoomUser.update_presence | validation | def update_presence(self,presence):
"""
Update user information.
:Parameters:
- `presence`: a presence stanza with user information update.
:Types:
- `presence`: `MucPresence`
"""
self.presence=MucPresence(presence)
t=presence.get_type()
if t=="unavailable":
self.role="none"
self.affiliation="none"
self.room_jid=self.presence.get_from()
self.nick=self.room_jid.resource
mc=self.presence.get_muc_child()
if isinstance(mc,MucUserX):
items=mc.get_items()
for item in items:
if not isinstance(item,MucItem):
continue
if item.role:
self.role=item.role
if item.affiliation:
self.affiliation=item.affiliation
if item.jid:
self.real_jid=item.jid
if item.nick:
self.new_nick=item.nick
break | python | {
"resource": ""
} |
q259710 | MucRoomState.get_user | validation | def get_user(self,nick_or_jid,create=False):
"""
Get a room user with given nick or JID.
:Parameters:
- `nick_or_jid`: the nickname or room JID of the user requested.
- `create`: if `True` and `nick_or_jid` is a JID, then a new
user object will be created if there is no such user in the room.
:Types:
- `nick_or_jid`: `unicode` or `JID`
- `create`: `bool`
:return: the named user or `None`
:returntype: `MucRoomUser`
"""
if isinstance(nick_or_jid,JID):
if not nick_or_jid.resource:
return None
for u in self.users.values():
if nick_or_jid in (u.room_jid,u.real_jid):
return u
if create:
return MucRoomUser(nick_or_jid)
else:
return None
return self.users.get(nick_or_jid) | python | {
"resource": ""
} |
q259711 | MucRoomState.set_stream | validation | def set_stream(self,stream):
"""
Called when current stream changes.
Mark the room not joined and inform `self.handler` that it was left.
:Parameters:
- `stream`: the new stream.
:Types:
- `stream`: `pyxmpp.stream.Stream`
"""
_unused = stream
if self.joined and self.handler:
self.handler.user_left(self.me,None)
self.joined=False | python | {
"resource": ""
} |
q259712 | MucRoomState.join | validation | def join(self, password=None, history_maxchars = None,
history_maxstanzas = None, history_seconds = None, history_since = None):
"""
Send a join request for the room.
:Parameters:
- `password`: password to the room.
- `history_maxchars`: limit of the total number of characters in
history.
- `history_maxstanzas`: limit of the total number of messages in
history.
- `history_seconds`: send only messages received in the last
`history_seconds` seconds.
- `history_since`: Send only the messages received since the
dateTime specified (UTC).
:Types:
- `password`: `unicode`
- `history_maxchars`: `int`
- `history_maxstanzas`: `int`
- `history_seconds`: `int`
- `history_since`: `datetime.datetime`
"""
if self.joined:
raise RuntimeError("Room is already joined")
p=MucPresence(to_jid=self.room_jid)
p.make_join_request(password, history_maxchars, history_maxstanzas,
history_seconds, history_since)
self.manager.stream.send(p) | python | {
"resource": ""
} |
q259713 | MucRoomState.leave | validation | def leave(self):
"""
Send a leave request for the room.
"""
if self.joined:
p=MucPresence(to_jid=self.room_jid,stanza_type="unavailable")
self.manager.stream.send(p) | python | {
"resource": ""
} |
q259714 | MucRoomState.send_message | validation | def send_message(self,body):
"""
Send a message to the room.
:Parameters:
- `body`: the message body.
:Types:
- `body`: `unicode`
"""
m=Message(to_jid=self.room_jid.bare(),stanza_type="groupchat",body=body)
self.manager.stream.send(m) | python | {
"resource": ""
} |
q259715 | MucRoomState.set_subject | validation | def set_subject(self,subject):
"""
Send a subject change request to the room.
:Parameters:
- `subject`: the new subject.
:Types:
- `subject`: `unicode`
"""
m=Message(to_jid=self.room_jid.bare(),stanza_type="groupchat",subject=subject)
self.manager.stream.send(m) | python | {
"resource": ""
} |
q259716 | MucRoomState.change_nick | validation | def change_nick(self,new_nick):
"""
Send a nick change request to the room.
:Parameters:
- `new_nick`: the new nickname requested.
:Types:
- `new_nick`: `unicode`
"""
new_room_jid=JID(self.room_jid.node,self.room_jid.domain,new_nick)
p=Presence(to_jid=new_room_jid)
self.manager.stream.send(p) | python | {
"resource": ""
} |
q259717 | MucRoomState.get_room_jid | validation | def get_room_jid(self,nick=None):
"""
Get own room JID or a room JID for given `nick`.
:Parameters:
- `nick`: a nick for which the room JID is requested.
:Types:
- `nick`: `unicode`
:return: the room JID.
:returntype: `JID`
"""
if nick is None:
return self.room_jid
return JID(self.room_jid.node,self.room_jid.domain,nick) | python | {
"resource": ""
} |
q259718 | MucRoomState.process_configuration_form_success | validation | def process_configuration_form_success(self, stanza):
"""
Process successful result of a room configuration form request.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Presence`
"""
if stanza.get_query_ns() != MUC_OWNER_NS:
raise ValueError("Bad result namespace") # TODO: ProtocolError
query = stanza.get_query()
form = None
for el in xml_element_ns_iter(query.children, DATAFORM_NS):
form = Form(el)
break
if not form:
raise ValueError("No form received") # TODO: ProtocolError
self.configuration_form = form
self.handler.configuration_form_received(form) | python | {
"resource": ""
} |
q259719 | MucRoomState.request_configuration_form | validation | def request_configuration_form(self):
"""
Request a configuration form for the room.
When the form is received `self.handler.configuration_form_received` will be called.
When an error response is received then `self.handler.error` will be called.
:return: id of the request stanza.
:returntype: `unicode`
"""
iq = Iq(to_jid = self.room_jid.bare(), stanza_type = "get")
iq.new_query(MUC_OWNER_NS, "query")
self.manager.stream.set_response_handlers(
iq, self.process_configuration_form_success, self.process_configuration_form_error)
self.manager.stream.send(iq)
return iq.get_id() | python | {
"resource": ""
} |
q259720 | MucRoomState.process_configuration_success | validation | def process_configuration_success(self, stanza):
"""
Process success response for a room configuration request.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Presence`
"""
_unused = stanza
self.configured = True
self.handler.room_configured() | python | {
"resource": ""
} |
q259721 | MucRoomState.configure_room | validation | def configure_room(self, form):
"""
Configure the room using the provided data.
Do nothing if the provided form is of type 'cancel'.
:Parameters:
- `form`: the configuration parameters. Should be a 'submit' form made by filling-in
the configuration form retireved using `self.request_configuration_form` or
a 'cancel' form.
:Types:
- `form`: `Form`
:return: id of the request stanza or `None` if a 'cancel' form was provieded.
:returntype: `unicode`
"""
if form.type == "cancel":
return None
elif form.type != "submit":
raise ValueError("A 'submit' form required to configure a room")
iq = Iq(to_jid = self.room_jid.bare(), stanza_type = "set")
query = iq.new_query(MUC_OWNER_NS, "query")
form.as_xml(query)
self.manager.stream.set_response_handlers(
iq, self.process_configuration_success, self.process_configuration_error)
self.manager.stream.send(iq)
return iq.get_id() | python | {
"resource": ""
} |
q259722 | MucRoomManager.set_stream | validation | def set_stream(self,stream):
"""
Change the stream assigned to `self`.
:Parameters:
- `stream`: the new stream to be assigned to `self`.
:Types:
- `stream`: `pyxmpp.stream.Stream`
"""
self.jid=stream.me
self.stream=stream
for r in self.rooms.values():
r.set_stream(stream) | python | {
"resource": ""
} |
q259723 | MucRoomManager.set_handlers | validation | def set_handlers(self,priority=10):
"""
Assign MUC stanza handlers to the `self.stream`.
:Parameters:
- `priority`: priority for the handlers.
:Types:
- `priority`: `int`
"""
self.stream.set_message_handler("groupchat",self.__groupchat_message,None,priority)
self.stream.set_message_handler("error",self.__error_message,None,priority)
self.stream.set_presence_handler("available",self.__presence_available,None,priority)
self.stream.set_presence_handler("unavailable",self.__presence_unavailable,None,priority)
self.stream.set_presence_handler("error",self.__presence_error,None,priority) | python | {
"resource": ""
} |
q259724 | MucRoomManager.join | validation | def join(self, room, nick, handler, password = None, history_maxchars = None,
history_maxstanzas = None, history_seconds = None, history_since = None):
"""
Create and return a new room state object and request joining
to a MUC room.
:Parameters:
- `room`: the name of a room to be joined
- `nick`: the nickname to be used in the room
- `handler`: is an object to handle room events.
- `password`: password for the room, if any
- `history_maxchars`: limit of the total number of characters in
history.
- `history_maxstanzas`: limit of the total number of messages in
history.
- `history_seconds`: send only messages received in the last
`history_seconds` seconds.
- `history_since`: Send only the messages received since the
dateTime specified (UTC).
:Types:
- `room`: `JID`
- `nick`: `unicode`
- `handler`: `MucRoomHandler`
- `password`: `unicode`
- `history_maxchars`: `int`
- `history_maxstanzas`: `int`
- `history_seconds`: `int`
- `history_since`: `datetime.datetime`
:return: the room state object created.
:returntype: `MucRoomState`
"""
if not room.node or room.resource:
raise ValueError("Invalid room JID")
room_jid = JID(room.node, room.domain, nick)
cur_rs = self.rooms.get(room_jid.bare().as_unicode())
if cur_rs and cur_rs.joined:
raise RuntimeError("Room already joined")
rs=MucRoomState(self, self.stream.me, room_jid, handler)
self.rooms[room_jid.bare().as_unicode()]=rs
rs.join(password, history_maxchars, history_maxstanzas,
history_seconds, history_since)
return rs | python | {
"resource": ""
} |
q259725 | MucRoomManager.forget | validation | def forget(self,rs):
"""
Remove a room from the list of managed rooms.
:Parameters:
- `rs`: the state object of the room.
:Types:
- `rs`: `MucRoomState`
"""
try:
del self.rooms[rs.room_jid.bare().as_unicode()]
except KeyError:
pass | python | {
"resource": ""
} |
q259726 | MucRoomManager.__groupchat_message | validation | def __groupchat_message(self,stanza):
"""Process a groupchat message from a MUC room.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Message`
:return: `True` if the message was properly recognized as directed to
one of the managed rooms, `False` otherwise.
:returntype: `bool`"""
fr=stanza.get_from()
key=fr.bare().as_unicode()
rs=self.rooms.get(key)
if not rs:
self.__logger.debug("groupchat message from unknown source")
return False
rs.process_groupchat_message(stanza)
return True | python | {
"resource": ""
} |
q259727 | MucRoomManager.__error_message | validation | def __error_message(self,stanza):
"""Process an error message from a MUC room.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Message`
:return: `True` if the message was properly recognized as directed to
one of the managed rooms, `False` otherwise.
:returntype: `bool`"""
fr=stanza.get_from()
key=fr.bare().as_unicode()
rs=self.rooms.get(key)
if not rs:
return False
rs.process_error_message(stanza)
return True | python | {
"resource": ""
} |
q259728 | MucRoomManager.__presence_error | validation | def __presence_error(self,stanza):
"""Process an presence error from a MUC room.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Presence`
:return: `True` if the stanza was properly recognized as generated by
one of the managed rooms, `False` otherwise.
:returntype: `bool`"""
fr=stanza.get_from()
key=fr.bare().as_unicode()
rs=self.rooms.get(key)
if not rs:
return False
rs.process_error_presence(stanza)
return True | python | {
"resource": ""
} |
q259729 | MucRoomManager.__presence_available | validation | def __presence_available(self,stanza):
"""Process an available presence from a MUC room.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Presence`
:return: `True` if the stanza was properly recognized as generated by
one of the managed rooms, `False` otherwise.
:returntype: `bool`"""
fr=stanza.get_from()
key=fr.bare().as_unicode()
rs=self.rooms.get(key)
if not rs:
return False
rs.process_available_presence(MucPresence(stanza))
return True | python | {
"resource": ""
} |
q259730 | MucRoomManager.__presence_unavailable | validation | def __presence_unavailable(self,stanza):
"""Process an unavailable presence from a MUC room.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `Presence`
:return: `True` if the stanza was properly recognized as generated by
one of the managed rooms, `False` otherwise.
:returntype: `bool`"""
fr=stanza.get_from()
key=fr.bare().as_unicode()
rs=self.rooms.get(key)
if not rs:
return False
rs.process_unavailable_presence(MucPresence(stanza))
return True | python | {
"resource": ""
} |
q259731 | XMPPSettings.get | validation | def get(self, key, local_default = None, required = False):
"""Get a parameter value.
If parameter is not set, return `local_default` if it is not `None`
or the PyXMPP global default otherwise.
:Raise `KeyError`: if parameter has no value and no global default
:Return: parameter value
"""
# pylint: disable-msg=W0221
if key in self._settings:
return self._settings[key]
if local_default is not None:
return local_default
if key in self._defs:
setting_def = self._defs[key]
if setting_def.default is not None:
return setting_def.default
factory = setting_def.factory
if factory is None:
return None
value = factory(self)
if setting_def.cache is True:
setting_def.default = value
return value
if required:
raise KeyError(key)
return local_default | python | {
"resource": ""
} |
q259732 | XMPPSettings.add_setting | validation | def add_setting(cls, name, type = unicode, default = None, factory = None,
cache = False, default_d = None, doc = None,
cmdline_help = None, validator = None, basic = False):
"""Add a new setting definition.
:Parameters:
- `name`: setting name
- `type`: setting type object or type description
- `default`: default value
- `factory`: default value factory
- `cache`: if `True` the `factory` will be called only once
and its value stored as a constant default.
- `default_d`: description of the default value
- `doc`: setting documentation
- `cmdline_help`: command line argument description. When not
provided then the setting won't be available as a command-line
option
- `basic`: when `True` the option is considered a basic option -
one of those which should usually stay configurable in
an application.
- `validator`: function validating command-line option value string
and returning proper value for the settings objects. Defaults
to `type`.
:Types:
- `name`: `unicode`
- `type`: type or `unicode`
- `factory`: a callable
- `cache`: `bool`
- `default_d`: `unicode`
- `doc`: `unicode`
- `cmdline_help`: `unicode`
- `basic`: `bool`
- `validator`: a callable
"""
# pylint: disable-msg=W0622,R0913
setting_def = _SettingDefinition(name, type, default, factory,
cache, default_d, doc,
cmdline_help, validator, basic)
if name not in cls._defs:
cls._defs[name] = setting_def
return
duplicate = cls._defs[name]
if duplicate.type != setting_def.type:
raise ValueError("Setting duplicate, with a different type")
if duplicate.default != setting_def.default:
raise ValueError("Setting duplicate, with a different default")
if duplicate.factory != setting_def.factory:
raise ValueError("Setting duplicate, with a different factory") | python | {
"resource": ""
} |
q259733 | XMPPSettings.validate_string_list | validation | def validate_string_list(value):
"""Validator for string lists to be used with `add_setting`."""
try:
if sys.version_info.major < 3:
# pylint: disable-msg=W0404
from locale import getpreferredencoding
encoding = getpreferredencoding()
value = value.decode(encoding)
return [x.strip() for x in value.split(u",")]
except (AttributeError, TypeError, UnicodeError):
raise ValueError("Bad string list") | python | {
"resource": ""
} |
q259734 | XMPPSettings.get_int_range_validator | validation | def get_int_range_validator(start, stop):
"""Return an integer range validator to be used with `add_setting`.
:Parameters:
- `start`: minimum value for the integer
- `stop`: the upper bound (maximum value + 1)
:Types:
- `start`: `int`
- `stop`: `int`
:return: a validator function
"""
def validate_int_range(value):
"""Integer range validator."""
value = int(value)
if value >= start and value < stop:
return value
raise ValueError("Not in <{0},{1}) range".format(start, stop))
return validate_int_range | python | {
"resource": ""
} |
q259735 | XMPPSettings.list_all | validation | def list_all(cls, basic = None):
"""List known settings.
:Parameters:
- `basic`: When `True` then limit output to the basic settings,
when `False` list only the extra settings.
"""
if basic is None:
return [s for s in cls._defs]
else:
return [s.name for s in cls._defs.values() if s.basic == basic] | python | {
"resource": ""
} |
q259736 | XMPPSettings.get_arg_parser | validation | def get_arg_parser(cls, settings = None, option_prefix = u'--',
add_help = False):
"""Make a command-line option parser.
The returned parser may be used as a parent parser for application
argument parser.
:Parameters:
- `settings`: list of PyXMPP2 settings to consider. By default
all 'basic' settings are provided.
- `option_prefix`: custom prefix for PyXMPP2 options. E.g.
``'--xmpp'`` to differentiate them from not xmpp-related
application options.
- `add_help`: when `True` a '--help' option will be included
(probably already added in the application parser object)
:Types:
- `settings`: list of `unicode`
- `option_prefix`: `str`
- `add_help`:
:return: an argument parser object.
:returntype: :std:`argparse.ArgumentParser`
"""
# pylint: disable-msg=R0914,R0912
parser = argparse.ArgumentParser(add_help = add_help,
prefix_chars = option_prefix[0])
if settings is None:
settings = cls.list_all(basic = True)
if sys.version_info.major < 3:
# pylint: disable-msg=W0404
from locale import getpreferredencoding
encoding = getpreferredencoding()
def decode_string_option(value):
"""Decode a string option."""
return value.decode(encoding)
for name in settings:
if name not in cls._defs:
logger.debug("get_arg_parser: ignoring unknown option {0}"
.format(name))
return
setting = cls._defs[name]
if not setting.cmdline_help:
logger.debug("get_arg_parser: option {0} has no cmdline"
.format(name))
return
if sys.version_info.major < 3:
name = name.encode(encoding, "replace")
option = option_prefix + name.replace("_", "-")
dest = "pyxmpp2_" + name
if setting.validator:
opt_type = setting.validator
elif setting.type is unicode and sys.version_info.major < 3:
opt_type = decode_string_option
else:
opt_type = setting.type
if setting.default_d:
default_s = setting.default_d
if sys.version_info.major < 3:
default_s = default_s.encode(encoding, "replace")
elif setting.default is not None:
default_s = repr(setting.default)
else:
default_s = None
opt_help = setting.cmdline_help
if sys.version_info.major < 3:
opt_help = opt_help.encode(encoding, "replace")
if default_s:
opt_help += " (Default: {0})".format(default_s)
if opt_type is bool:
opt_action = _YesNoAction
else:
opt_action = "store"
parser.add_argument(option,
action = opt_action,
default = setting.default,
type = opt_type,
help = opt_help,
metavar = name.upper(),
dest = dest)
return parser | python | {
"resource": ""
} |
q259737 | are_domains_equal | validation | def are_domains_equal(domain1, domain2):
"""Compare two International Domain Names.
:Parameters:
- `domain1`: domains name to compare
- `domain2`: domains name to compare
:Types:
- `domain1`: `unicode`
- `domain2`: `unicode`
:return: True `domain1` and `domain2` are equal as domain names."""
domain1 = domain1.encode("idna")
domain2 = domain2.encode("idna")
return domain1.lower() == domain2.lower() | python | {
"resource": ""
} |
q259738 | _validate_ip_address | validation | def _validate_ip_address(family, address):
"""Check if `address` is valid IP address and return it, in a normalized
form.
:Parameters:
- `family`: ``socket.AF_INET`` or ``socket.AF_INET6``
- `address`: the IP address to validate
"""
try:
info = socket.getaddrinfo(address, 0, family, socket.SOCK_STREAM, 0,
socket.AI_NUMERICHOST)
except socket.gaierror, err:
logger.debug("gaierror: {0} for {1!r}".format(err, address))
raise ValueError("Bad IP address")
if not info:
logger.debug("getaddrinfo result empty")
raise ValueError("Bad IP address")
addr = info[0][4]
logger.debug(" got address: {0!r}".format(addr))
try:
return socket.getnameinfo(addr, socket.NI_NUMERICHOST)[0]
except socket.gaierror, err:
logger.debug("gaierror: {0} for {1!r}".format(err, addr))
raise ValueError("Bad IP address") | python | {
"resource": ""
} |
q259739 | JID.__from_unicode | validation | def __from_unicode(cls, data, check = True):
"""Return jid tuple from an Unicode string.
:Parameters:
- `data`: the JID string
- `check`: when `False` then the JID is not checked for
specification compliance.
:Return: (localpart, domainpart, resourcepart) tuple"""
parts1 = data.split(u"/", 1)
parts2 = parts1[0].split(u"@", 1)
if len(parts2) == 2:
local = parts2[0]
domain = parts2[1]
if check:
local = cls.__prepare_local(local)
domain = cls.__prepare_domain(domain)
else:
local = None
domain = parts2[0]
if check:
domain = cls.__prepare_domain(domain)
if len(parts1) == 2:
resource = parts1[1]
if check:
resource = cls.__prepare_resource(parts1[1])
else:
resource = None
if not domain:
raise JIDError("Domain is required in JID.")
return (local, domain, resource) | python | {
"resource": ""
} |
q259740 | JID.__prepare_local | validation | def __prepare_local(data):
"""Prepare localpart of the JID
:Parameters:
- `data`: localpart of the JID
:Types:
- `data`: `unicode`
:raise JIDError: if the local name is too long.
:raise pyxmpp.xmppstringprep.StringprepError: if the
local name fails Nodeprep preparation."""
if not data:
return None
data = unicode(data)
try:
local = NODEPREP.prepare(data)
except StringprepError, err:
raise JIDError(u"Local part invalid: {0}".format(err))
if len(local.encode("utf-8")) > 1023:
raise JIDError(u"Local part too long")
return local | python | {
"resource": ""
} |
q259741 | JID.__prepare_domain | validation | def __prepare_domain(data):
"""Prepare domainpart of the JID.
:Parameters:
- `data`: Domain part of the JID
:Types:
- `data`: `unicode`
:raise JIDError: if the domain name is too long.
"""
# pylint: disable=R0912
if not data:
raise JIDError("Domain must be given")
data = unicode(data)
if not data:
raise JIDError("Domain must be given")
if u'[' in data:
if data[0] == u'[' and data[-1] == u']':
try:
addr = _validate_ip_address(socket.AF_INET6, data[1:-1])
return "[{0}]".format(addr)
except ValueError, err:
logger.debug("ValueError: {0}".format(err))
raise JIDError(u"Invalid IPv6 literal in JID domainpart")
else:
raise JIDError(u"Invalid use of '[' or ']' in JID domainpart")
elif data[0].isdigit() and data[-1].isdigit():
try:
addr = _validate_ip_address(socket.AF_INET, data)
except ValueError, err:
logger.debug("ValueError: {0}".format(err))
data = UNICODE_DOT_RE.sub(u".", data)
data = data.rstrip(u".")
labels = data.split(u".")
try:
labels = [idna.nameprep(label) for label in labels]
except UnicodeError:
raise JIDError(u"Domain name invalid")
for label in labels:
if not STD3_LABEL_RE.match(label):
raise JIDError(u"Domain name invalid")
try:
idna.ToASCII(label)
except UnicodeError:
raise JIDError(u"Domain name invalid")
domain = u".".join(labels)
if len(domain.encode("utf-8")) > 1023:
raise JIDError(u"Domain name too long")
return domain | python | {
"resource": ""
} |
q259742 | JID.__prepare_resource | validation | def __prepare_resource(data):
"""Prepare the resourcepart of the JID.
:Parameters:
- `data`: Resourcepart of the JID
:raise JIDError: if the resource name is too long.
:raise pyxmpp.xmppstringprep.StringprepError: if the
resourcepart fails Resourceprep preparation."""
if not data:
return None
data = unicode(data)
try:
resource = RESOURCEPREP.prepare(data)
except StringprepError, err:
raise JIDError(u"Local part invalid: {0}".format(err))
if len(resource.encode("utf-8")) > 1023:
raise JIDError("Resource name too long")
return resource | python | {
"resource": ""
} |
q259743 | JID.as_unicode | validation | def as_unicode(self):
"""Unicode string JID representation.
:return: JID as Unicode string."""
result = self.domain
if self.local:
result = self.local + u'@' + result
if self.resource:
result = result + u'/' + self.resource
if not JID.cache.has_key(result):
JID.cache[result] = self
return result | python | {
"resource": ""
} |
q259744 | is_ipv6_available | validation | def is_ipv6_available():
"""Check if IPv6 is available.
:Return: `True` when an IPv6 socket can be created.
"""
try:
socket.socket(socket.AF_INET6).close()
except (socket.error, AttributeError):
return False
return True | python | {
"resource": ""
} |
q259745 | is_ipv4_available | validation | def is_ipv4_available():
"""Check if IPv4 is available.
:Return: `True` when an IPv4 socket can be created.
"""
try:
socket.socket(socket.AF_INET).close()
except socket.error:
return False
return True | python | {
"resource": ""
} |
q259746 | shuffle_srv | validation | def shuffle_srv(records):
"""Randomly reorder SRV records using their weights.
:Parameters:
- `records`: SRV records to shuffle.
:Types:
- `records`: sequence of :dns:`dns.rdtypes.IN.SRV`
:return: reordered records.
:returntype: `list` of :dns:`dns.rdtypes.IN.SRV`"""
if not records:
return []
ret = []
while len(records) > 1:
weight_sum = 0
for rrecord in records:
weight_sum += rrecord.weight + 0.1
thres = random.random() * weight_sum
weight_sum = 0
for rrecord in records:
weight_sum += rrecord.weight + 0.1
if thres < weight_sum:
records.remove(rrecord)
ret.append(rrecord)
break
ret.append(records[0])
return ret | python | {
"resource": ""
} |
q259747 | reorder_srv | validation | def reorder_srv(records):
"""Reorder SRV records using their priorities and weights.
:Parameters:
- `records`: SRV records to shuffle.
:Types:
- `records`: `list` of :dns:`dns.rdtypes.IN.SRV`
:return: reordered records.
:returntype: `list` of :dns:`dns.rdtypes.IN.SRV`"""
records = list(records)
records.sort()
ret = []
tmp = []
for rrecord in records:
if not tmp or rrecord.priority == tmp[0].priority:
tmp.append(rrecord)
continue
ret += shuffle_srv(tmp)
tmp = [rrecord]
if tmp:
ret += shuffle_srv(tmp)
return ret | python | {
"resource": ""
} |
q259748 | ThreadedResolverBase.stop | validation | def stop(self):
"""Stop the resolver threads.
"""
with self.lock:
for dummy in self.threads:
self.queue.put(None) | python | {
"resource": ""
} |
q259749 | ThreadedResolverBase._start_thread | validation | def _start_thread(self):
"""Start a new working thread unless the maximum number of threads
has been reached or the request queue is empty.
"""
with self.lock:
if self.threads and self.queue.empty():
return
if len(self.threads) >= self.max_threads:
return
thread_n = self.last_thread_n + 1
self.last_thread_n = thread_n
thread = threading.Thread(target = self._run,
name = "{0!r} #{1}".format(self, thread_n),
args = (thread_n,))
self.threads.append(thread)
thread.daemon = True
thread.start() | python | {
"resource": ""
} |
q259750 | DumbBlockingResolver.resolve_address | validation | def resolve_address(self, hostname, callback, allow_cname = True):
"""Start looking up an A or AAAA record.
`callback` will be called with a list of (family, address) tuples
on success. Family is :std:`socket.AF_INET` or :std:`socket.AF_INET6`,
the address is IPv4 or IPv6 literal. The list will be empty on error.
:Parameters:
- `hostname`: the host name to look up
- `callback`: a function to be called with a list of received
addresses
- `allow_cname`: `True` if CNAMEs should be followed
:Types:
- `hostname`: `unicode`
- `callback`: function accepting a single argument
- `allow_cname`: `bool`
"""
if self.settings["ipv6"]:
if self.settings["ipv4"]:
family = socket.AF_UNSPEC
else:
family = socket.AF_INET6
elif self.settings["ipv4"]:
family = socket.AF_INET
else:
logger.warning("Neither IPv6 or IPv4 allowed.")
callback([])
return
try:
ret = socket.getaddrinfo(hostname, 0, family, socket.SOCK_STREAM, 0)
except socket.gaierror, err:
logger.warning("Couldn't resolve {0!r}: {1}".format(hostname,
err))
callback([])
return
except IOError as err:
logger.warning("Couldn't resolve {0!r}, unexpected error: {1}"
.format(hostname,err))
callback([])
return
if family == socket.AF_UNSPEC:
tmp = ret
if self.settings["prefer_ipv6"]:
ret = [ addr for addr in tmp if addr[0] == socket.AF_INET6 ]
ret += [ addr for addr in tmp if addr[0] == socket.AF_INET ]
else:
ret = [ addr for addr in tmp if addr[0] == socket.AF_INET ]
ret += [ addr for addr in tmp if addr[0] == socket.AF_INET6 ]
callback([(addr[0], addr[4][0]) for addr in ret]) | python | {
"resource": ""
} |
q259751 | send_message | validation | def send_message(source_jid, password, target_jid, body, subject = None,
message_type = "chat", message_thread = None, settings = None):
"""Star an XMPP session and send a message, then exit.
:Parameters:
- `source_jid`: sender JID
- `password`: sender password
- `target_jid`: recipient JID
- `body`: message body
- `subject`: message subject
- `message_type`: message type
- `message_thread`: message thread id
- `settings`: other settings
:Types:
- `source_jid`: `pyxmpp2.jid.JID` or `basestring`
- `password`: `basestring`
- `target_jid`: `pyxmpp.jid.JID` or `basestring`
- `body`: `basestring`
- `subject`: `basestring`
- `message_type`: `basestring`
- `settings`: `pyxmpp2.settings.XMPPSettings`
"""
# pylint: disable=R0913,R0912
if sys.version_info.major < 3:
# pylint: disable-msg=W0404
from locale import getpreferredencoding
encoding = getpreferredencoding()
if isinstance(source_jid, str):
source_jid = source_jid.decode(encoding)
if isinstance(password, str):
password = password.decode(encoding)
if isinstance(target_jid, str):
target_jid = target_jid.decode(encoding)
if isinstance(body, str):
body = body.decode(encoding)
if isinstance(message_type, str):
message_type = message_type.decode(encoding)
if isinstance(message_thread, str):
message_thread = message_thread.decode(encoding)
if not isinstance(source_jid, JID):
source_jid = JID(source_jid)
if not isinstance(target_jid, JID):
target_jid = JID(target_jid)
msg = Message(to_jid = target_jid, body = body, subject = subject,
stanza_type = message_type)
def action(client):
"""Send a mesage `msg` via a client."""
client.stream.send(msg)
if settings is None:
settings = XMPPSettings({"starttls": True, "tls_verify_peer": False})
if password is not None:
settings["password"] = password
handler = FireAndForget(source_jid, action, settings)
try:
handler.run()
except KeyboardInterrupt:
handler.disconnect()
raise | python | {
"resource": ""
} |
q259752 | ComponentStream.connect | validation | def connect(self,server=None,port=None):
"""Establish a client connection to a server.
[component only]
:Parameters:
- `server`: name or address of the server to use. If not given
then use the one specified when creating the object.
- `port`: port number of the server to use. If not given then use
the one specified when creating the object.
:Types:
- `server`: `unicode`
- `port`: `int`"""
self.lock.acquire()
try:
self._connect(server,port)
finally:
self.lock.release() | python | {
"resource": ""
} |
q259753 | ComponentStream._connect | validation | def _connect(self,server=None,port=None):
"""Same as `ComponentStream.connect` but assume `self.lock` is acquired."""
if self.me.node or self.me.resource:
raise Value("Component JID may have only domain defined")
if not server:
server=self.server
if not port:
port=self.port
if not server or not port:
raise ValueError("Server or port not given")
Stream._connect(self,server,port,None,self.me) | python | {
"resource": ""
} |
q259754 | ComponentStream._compute_handshake | validation | def _compute_handshake(self):
"""Compute the authentication handshake value.
:return: the computed hash value.
:returntype: `str`"""
return hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.secret)).hexdigest() | python | {
"resource": ""
} |
q259755 | ComponentStream._auth | validation | def _auth(self):
"""Authenticate on the server.
[component only]"""
if self.authenticated:
self.__logger.debug("_auth: already authenticated")
return
self.__logger.debug("doing handshake...")
hash_value=self._compute_handshake()
n=common_root.newTextChild(None,"handshake",hash_value)
self._write_node(n)
n.unlinkNode()
n.freeNode()
self.__logger.debug("handshake hash sent.") | python | {
"resource": ""
} |
q259756 | TCPTransport._set_state | validation | def _set_state(self, state):
"""Set `_state` and notify any threads waiting for the change.
"""
logger.debug(" _set_state({0!r})".format(state))
self._state = state
self._state_cond.notify() | python | {
"resource": ""
} |
q259757 | TCPTransport.connect | validation | def connect(self, addr, port = None, service = None):
"""Start establishing TCP connection with given address.
One of: `port` or `service` must be provided and `addr` must be
a domain name and not an IP address if `port` is not given.
When `service` is given try an SRV lookup for that service
at domain `addr`. If `service` is not given or `addr` is an IP address,
or the SRV lookup fails, connect to `port` at host `addr` directly.
[initiating entity only]
:Parameters:
- `addr`: peer name or IP address
- `port`: port number to connect to
- `service`: service name (to be resolved using SRV DNS records)
"""
with self.lock:
self._connect(addr, port, service) | python | {
"resource": ""
} |
q259758 | TCPTransport._connect | validation | def _connect(self, addr, port, service):
"""Same as `connect`, but assumes `lock` acquired.
"""
self._dst_name = addr
self._dst_port = port
family = None
try:
res = socket.getaddrinfo(addr, port, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST)
family = res[0][0]
sockaddr = res[0][4]
except socket.gaierror:
family = None
sockaddr = None
if family is not None:
if not port:
raise ValueError("No port number given with literal IP address")
self._dst_service = None
self._family = family
self._dst_addrs = [(family, sockaddr)]
self._set_state("connect")
elif service is not None:
self._dst_service = service
self._set_state("resolve-srv")
self._dst_name = addr
elif port:
self._dst_nameports = [(self._dst_name, self._dst_port)]
self._dst_service = None
self._set_state("resolve-hostname")
else:
raise ValueError("No port number and no SRV service name given") | python | {
"resource": ""
} |
q259759 | TCPTransport._resolve_srv | validation | def _resolve_srv(self):
"""Start resolving the SRV record.
"""
resolver = self.settings["dns_resolver"] # pylint: disable=W0621
self._set_state("resolving-srv")
self.event(ResolvingSRVEvent(self._dst_name, self._dst_service))
resolver.resolve_srv(self._dst_name, self._dst_service, "tcp",
callback = self._got_srv) | python | {
"resource": ""
} |
q259760 | TCPTransport._got_srv | validation | def _got_srv(self, addrs):
"""Handle SRV lookup result.
:Parameters:
- `addrs`: properly sorted list of (hostname, port) tuples
"""
with self.lock:
if not addrs:
self._dst_service = None
if self._dst_port:
self._dst_nameports = [(self._dst_name, self._dst_port)]
else:
self._dst_nameports = []
self._set_state("aborted")
raise DNSError("Could not resolve SRV for service {0!r}"
" on host {1!r} and fallback port number not given"
.format(self._dst_service, self._dst_name))
elif addrs == [(".", 0)]:
self._dst_nameports = []
self._set_state("aborted")
raise DNSError("Service {0!r} not available on host {1!r}"
.format(self._dst_service, self._dst_name))
else:
self._dst_nameports = addrs
self._set_state("resolve-hostname") | python | {
"resource": ""
} |
q259761 | TCPTransport._resolve_hostname | validation | def _resolve_hostname(self):
"""Start hostname resolution for the next name to try.
[called with `lock` acquired]
"""
self._set_state("resolving-hostname")
resolver = self.settings["dns_resolver"] # pylint: disable=W0621
logger.debug("_dst_nameports: {0!r}".format(self._dst_nameports))
name, port = self._dst_nameports.pop(0)
self._dst_hostname = name
resolver.resolve_address(name, callback = partial(
self._got_addresses, name, port),
allow_cname = self._dst_service is None)
self.event(ResolvingAddressEvent(name)) | python | {
"resource": ""
} |
q259762 | TCPTransport._got_addresses | validation | def _got_addresses(self, name, port, addrs):
"""Handler DNS address record lookup result.
:Parameters:
- `name`: the name requested
- `port`: port number to connect to
- `addrs`: list of (family, address) tuples
"""
with self.lock:
if not addrs:
if self._dst_nameports:
self._set_state("resolve-hostname")
return
else:
self._dst_addrs = []
self._set_state("aborted")
raise DNSError("Could not resolve address record for {0!r}"
.format(name))
self._dst_addrs = [ (family, (addr, port)) for (family, addr)
in addrs ]
self._set_state("connect") | python | {
"resource": ""
} |
q259763 | TCPTransport._start_connect | validation | def _start_connect(self):
"""Start connecting to the next address on the `_dst_addrs` list.
[ called with `lock` acquired ]
"""
family, addr = self._dst_addrs.pop(0)
self._socket = socket.socket(family, socket.SOCK_STREAM)
self._socket.setblocking(False)
self._dst_addr = addr
self._family = family
try:
self._socket.connect(addr)
except socket.error, err:
logger.debug("Connect error: {0}".format(err))
if err.args[0] in BLOCKING_ERRORS:
self._set_state("connecting")
self._write_queue.append(ContinueConnect())
self._write_queue_cond.notify()
self.event(ConnectingEvent(addr))
return
elif self._dst_addrs:
self._set_state("connect")
return
elif self._dst_nameports:
self._set_state("resolve-hostname")
return
else:
self._socket.close()
self._socket = None
self._set_state("aborted")
self._write_queue.clear()
self._write_queue_cond.notify()
raise
self._connected() | python | {
"resource": ""
} |
q259764 | TCPTransport._connected | validation | def _connected(self):
"""Handle connection success."""
self._auth_properties['remote-ip'] = self._dst_addr[0]
if self._dst_service:
self._auth_properties['service-domain'] = self._dst_name
if self._dst_hostname is not None:
self._auth_properties['service-hostname'] = self._dst_hostname
else:
self._auth_properties['service-hostname'] = self._dst_addr[0]
self._auth_properties['security-layer'] = None
self.event(ConnectedEvent(self._dst_addr))
self._set_state("connected")
self._stream.transport_connected() | python | {
"resource": ""
} |
q259765 | TCPTransport._continue_connect | validation | def _continue_connect(self):
"""Continue connecting.
[called with `lock` acquired]
:Return: `True` when just connected
"""
try:
self._socket.connect(self._dst_addr)
except socket.error, err:
logger.debug("Connect error: {0}".format(err))
if err.args[0] == errno.EISCONN:
pass
elif err.args[0] in BLOCKING_ERRORS:
return None
elif self._dst_addrs:
self._set_state("connect")
return None
elif self._dst_nameports:
self._set_state("resolve-hostname")
return None
else:
self._socket.close()
self._socket = None
self._set_state("aborted")
raise
self._connected() | python | {
"resource": ""
} |
q259766 | TCPTransport._write | validation | def _write(self, data):
"""Write raw data to the socket.
:Parameters:
- `data`: data to send
:Types:
- `data`: `bytes`
"""
OUT_LOGGER.debug("OUT: %r", data)
if self._hup or not self._socket:
raise PyXMPPIOError(u"Connection closed.")
try:
while data:
try:
sent = self._socket.send(data)
except ssl.SSLError, err:
if err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
continue
else:
raise
except socket.error, err:
if err.args[0] == errno.EINTR:
continue
if err.args[0] in BLOCKING_ERRORS:
wait_for_write(self._socket)
continue
raise
data = data[sent:]
except (IOError, OSError, socket.error), err:
raise PyXMPPIOError(u"IO Error: {0}".format(err)) | python | {
"resource": ""
} |
q259767 | TCPTransport.set_target | validation | def set_target(self, stream):
"""Make the `stream` the target for this transport instance.
The 'stream_start', 'stream_end' and 'stream_element' methods
of the target will be called when appropriate content is received.
:Parameters:
- `stream`: the stream handler to receive stream content
from the transport
:Types:
- `stream`: `StreamBase`
"""
with self.lock:
if self._stream:
raise ValueError("Target stream already set")
self._stream = stream
self._reader = StreamReader(stream) | python | {
"resource": ""
} |
q259768 | TCPTransport.send_stream_head | validation | def send_stream_head(self, stanza_namespace, stream_from, stream_to,
stream_id = None, version = u'1.0', language = None):
"""
Send stream head via the transport.
:Parameters:
- `stanza_namespace`: namespace of stream stanzas (e.g.
'jabber:client')
- `stream_from`: the 'from' attribute of the stream. May be `None`.
- `stream_to`: the 'to' attribute of the stream. May be `None`.
- `version`: the 'version' of the stream.
- `language`: the 'xml:lang' of the stream
:Types:
- `stanza_namespace`: `unicode`
- `stream_from`: `unicode`
- `stream_to`: `unicode`
- `version`: `unicode`
- `language`: `unicode`
"""
# pylint: disable=R0913
with self.lock:
self._serializer = XMPPSerializer(stanza_namespace,
self.settings["extra_ns_prefixes"])
head = self._serializer.emit_head(stream_from, stream_to,
stream_id, version, language)
self._write(head.encode("utf-8")) | python | {
"resource": ""
} |
q259769 | TCPTransport.send_stream_tail | validation | def send_stream_tail(self):
"""
Send stream tail via the transport.
"""
with self.lock:
if not self._socket or self._hup:
logger.debug(u"Cannot send stream closing tag: already closed")
return
data = self._serializer.emit_tail()
try:
self._write(data.encode("utf-8"))
except (IOError, SystemError, socket.error), err:
logger.debug(u"Sending stream closing tag failed: {0}"
.format(err))
self._serializer = None
self._hup = True
if self._tls_state is None:
try:
self._socket.shutdown(socket.SHUT_WR)
except socket.error:
pass
self._set_state("closing")
self._write_queue.clear()
self._write_queue_cond.notify() | python | {
"resource": ""
} |
q259770 | TCPTransport.send_element | validation | def send_element(self, element):
"""
Send an element via the transport.
"""
with self.lock:
if self._eof or self._socket is None or not self._serializer:
logger.debug("Dropping element: {0}".format(
element_to_unicode(element)))
return
data = self._serializer.emit_stanza(element)
self._write(data.encode("utf-8")) | python | {
"resource": ""
} |
q259771 | TCPTransport.wait_for_readability | validation | def wait_for_readability(self):
"""
Stop current thread until the channel is readable.
:Return: `False` if it won't be readable (e.g. is closed)
"""
with self.lock:
while True:
if self._socket is None or self._eof:
return False
if self._state in ("connected", "closing"):
return True
if self._state == "tls-handshake" and \
self._tls_state == "want_read":
return True
self._state_cond.wait() | python | {
"resource": ""
} |
q259772 | TCPTransport.wait_for_writability | validation | def wait_for_writability(self):
"""
Stop current thread until the channel is writable.
:Return: `False` if it won't be readable (e.g. is closed)
"""
with self.lock:
while True:
if self._state in ("closing", "closed", "aborted"):
return False
if self._socket and bool(self._write_queue):
return True
self._write_queue_cond.wait()
return False | python | {
"resource": ""
} |
q259773 | TCPTransport.handle_write | validation | def handle_write(self):
"""
Handle the 'channel writable' state. E.g. send buffered data via a
socket.
"""
with self.lock:
logger.debug("handle_write: queue: {0!r}".format(self._write_queue))
try:
job = self._write_queue.popleft()
except IndexError:
return
if isinstance(job, WriteData):
self._do_write(job.data) # pylint: disable=E1101
elif isinstance(job, ContinueConnect):
self._continue_connect()
elif isinstance(job, StartTLS):
self._initiate_starttls(**job.kwargs)
elif isinstance(job, TLSHandshake):
self._continue_tls_handshake()
else:
raise ValueError("Unrecognized job in the write queue: "
"{0!r}".format(job)) | python | {
"resource": ""
} |
q259774 | TCPTransport.starttls | validation | def starttls(self, **kwargs):
"""Request a TLS handshake on the socket ans switch
to encrypted output.
The handshake will start after any currently buffered data is sent.
:Parameters:
- `kwargs`: arguments for :std:`ssl.wrap_socket`
"""
with self.lock:
self.event(TLSConnectingEvent())
self._write_queue.append(StartTLS(**kwargs))
self._write_queue_cond.notify() | python | {
"resource": ""
} |
q259775 | TCPTransport.getpeercert | validation | def getpeercert(self):
"""Return the peer certificate.
:ReturnType: `pyxmpp2.cert.Certificate`
"""
with self.lock:
if not self._socket or self._tls_state != "connected":
raise ValueError("Not TLS-connected")
return get_certificate_from_ssl_socket(self._socket) | python | {
"resource": ""
} |
q259776 | TCPTransport._initiate_starttls | validation | def _initiate_starttls(self, **kwargs):
"""Initiate starttls handshake over the socket.
"""
if self._tls_state == "connected":
raise RuntimeError("Already TLS-connected")
kwargs["do_handshake_on_connect"] = False
logger.debug("Wrapping the socket into ssl")
self._socket = ssl.wrap_socket(self._socket, **kwargs)
self._set_state("tls-handshake")
self._continue_tls_handshake() | python | {
"resource": ""
} |
q259777 | TCPTransport._continue_tls_handshake | validation | def _continue_tls_handshake(self):
"""Continue a TLS handshake."""
try:
logger.debug(" do_handshake()")
self._socket.do_handshake()
except ssl.SSLError, err:
if err.args[0] == ssl.SSL_ERROR_WANT_READ:
self._tls_state = "want_read"
logger.debug(" want_read")
self._state_cond.notify()
return
elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
self._tls_state = "want_write"
logger.debug(" want_write")
self._write_queue.appendleft(TLSHandshake)
return
else:
raise
self._tls_state = "connected"
self._set_state("connected")
self._auth_properties['security-layer'] = "TLS"
if "tls-unique" in CHANNEL_BINDING_TYPES:
try:
# pylint: disable=E1103
tls_unique = self._socket.get_channel_binding("tls-unique")
except ValueError:
pass
else:
self._auth_properties['channel-binding'] = {
"tls-unique": tls_unique}
try:
cipher = self._socket.cipher()
except AttributeError:
# SSLSocket.cipher doesn't work on PyPy
cipher = "unknown"
cert = get_certificate_from_ssl_socket(self._socket)
self.event(TLSConnectedEvent(cipher, cert)) | python | {
"resource": ""
} |
q259778 | TCPTransport.handle_read | validation | def handle_read(self):
"""
Handle the 'channel readable' state. E.g. read from a socket.
"""
with self.lock:
logger.debug("handle_read()")
if self._eof or self._socket is None:
return
if self._state == "tls-handshake":
while True:
logger.debug("tls handshake read...")
self._continue_tls_handshake()
logger.debug(" state: {0}".format(self._tls_state))
if self._tls_state != "want_read":
break
elif self._tls_state == "connected":
while self._socket and not self._eof:
logger.debug("tls socket read...")
try:
data = self._socket.read(4096)
except ssl.SSLError, err:
if err.args[0] == ssl.SSL_ERROR_WANT_READ:
break
elif err.args[0] == ssl.SSL_ERROR_WANT_WRITE:
break
else:
raise
except socket.error, err:
if err.args[0] == errno.EINTR:
continue
elif err.args[0] in BLOCKING_ERRORS:
break
elif err.args[0] == errno.ECONNRESET:
logger.warning("Connection reset by peer")
data = None
else:
raise
self._feed_reader(data)
else:
while self._socket and not self._eof:
logger.debug("raw socket read...")
try:
data = self._socket.recv(4096)
except socket.error, err:
if err.args[0] == errno.EINTR:
continue
elif err.args[0] in BLOCKING_ERRORS:
break
elif err.args[0] == errno.ECONNRESET:
logger.warning("Connection reset by peer")
data = None
else:
raise
self._feed_reader(data) | python | {
"resource": ""
} |
q259779 | TCPTransport.handle_hup | validation | def handle_hup(self):
"""
Handle the 'channel hungup' state. The handler should not be writable
after this.
"""
with self.lock:
if self._state == 'connecting' and self._dst_addrs:
self._hup = False
self._set_state("connect")
return
self._hup = True | python | {
"resource": ""
} |
q259780 | TCPTransport.handle_err | validation | def handle_err(self):
"""
Handle an error reported.
"""
with self.lock:
if self._state == 'connecting' and self._dst_addrs:
self._hup = False
self._set_state("connect")
return
self._socket.close()
self._socket = None
self._set_state("aborted")
self._write_queue.clear()
self._write_queue_cond.notify()
raise PyXMPPIOError("Unhandled error on socket") | python | {
"resource": ""
} |
q259781 | TCPTransport.disconnect | validation | def disconnect(self):
"""Disconnect the stream gracefully."""
logger.debug("TCPTransport.disconnect()")
with self.lock:
if self._socket is None:
if self._state != "closed":
self.event(DisconnectedEvent(self._dst_addr))
self._set_state("closed")
return
if self._hup or not self._serializer:
self._close()
else:
self.send_stream_tail() | python | {
"resource": ""
} |
q259782 | TCPTransport._close | validation | def _close(self):
"""Same as `_close` but expects `lock` acquired.
"""
if self._state != "closed":
self.event(DisconnectedEvent(self._dst_addr))
self._set_state("closed")
if self._socket is None:
return
try:
self._socket.shutdown(socket.SHUT_RDWR)
except socket.error:
pass
self._socket.close()
self._socket = None
self._write_queue.clear()
self._write_queue_cond.notify() | python | {
"resource": ""
} |
q259783 | TCPTransport._feed_reader | validation | def _feed_reader(self, data):
"""Feed the stream reader with data received.
[ called with `lock` acquired ]
If `data` is None or empty, then stream end (peer disconnected) is
assumed and the stream is closed.
`lock` is acquired during the operation.
:Parameters:
- `data`: data received from the stream socket.
:Types:
- `data`: `unicode`
"""
IN_LOGGER.debug("IN: %r", data)
if data:
self.lock.release() # not to deadlock with the stream
try:
self._reader.feed(data)
finally:
self.lock.acquire()
else:
self._eof = True
self.lock.release() # not to deadlock with the stream
try:
self._stream.stream_eof()
finally:
self.lock.acquire()
if not self._serializer:
if self._state != "closed":
self.event(DisconnectedEvent(self._dst_addr))
self._set_state("closed") | python | {
"resource": ""
} |
q259784 | TCPTransport.event | validation | def event(self, event):
"""Pass an event to the target stream or just log it."""
logger.debug(u"TCP transport event: {0}".format(event))
if self._stream:
event.stream = self._stream
self._event_queue.put(event) | python | {
"resource": ""
} |
q259785 | ParserTarget.start | validation | def start(self, tag, attrs):
"""Handle the start tag.
Call the handler's 'stream_start' methods with
an empty root element if it is top level.
For lower level tags use :etree:`ElementTree.TreeBuilder` to collect
them.
"""
if self._level == 0:
self._root = ElementTree.Element(tag, attrs)
self._handler.stream_start(self._root)
if self._level < 2:
self._builder = ElementTree.TreeBuilder()
self._level += 1
return self._builder.start(tag, attrs) | python | {
"resource": ""
} |
q259786 | ParserTarget.end | validation | def end(self, tag):
"""Handle an end tag.
Call the handler's 'stream_end' method with
an the root element (built by the `start` method).
On the first level below root, sent the built element tree
to the handler via the 'stanza methods'.
Any tag below will be just added to the tree builder.
"""
self._level -= 1
if self._level < 0:
self._handler.stream_parse_error(u"Unexpected end tag for: {0!r}"
.format(tag))
return
if self._level == 0:
if tag != self._root.tag:
self._handler.stream_parse_error(u"Unexpected end tag for:"
" {0!r} (stream end tag expected)".format(tag))
return
self._handler.stream_end()
return
element = self._builder.end(tag)
if self._level == 1:
self._handler.stream_element(element) | python | {
"resource": ""
} |
q259787 | StreamReader.feed | validation | def feed(self, data):
"""Feed the parser with a chunk of data. Apropriate methods
of `handler` will be called whenever something interesting is
found.
:Parameters:
- `data`: the chunk of data to parse.
:Types:
- `data`: `str`"""
with self.lock:
if self.in_use:
raise StreamParseError("StreamReader.feed() is not reentrant!")
self.in_use = True
try:
if not self._started:
# workaround for lxml bug when fed with a big chunk at once
if len(data) > 1:
self.parser.feed(data[:1])
data = data[1:]
self._started = True
if data:
self.parser.feed(data)
else:
self.parser.close()
except ElementTree.ParseError, err:
self.handler.stream_parse_error(unicode(err))
finally:
self.in_use = False | python | {
"resource": ""
} |
q259788 | ThreadPool._run_io_threads | validation | def _run_io_threads(self, handler):
"""Start threads for an IOHandler.
"""
reader = ReadingThread(self.settings, handler, daemon = self.daemon,
exc_queue = self.exc_queue)
writter = WrittingThread(self.settings, handler, daemon = self.daemon,
exc_queue = self.exc_queue)
self.io_threads += [reader, writter]
reader.start()
writter.start() | python | {
"resource": ""
} |
q259789 | ThreadPool._remove_io_handler | validation | def _remove_io_handler(self, handler):
"""Remove an IOHandler from the pool.
"""
if handler not in self.io_handlers:
return
self.io_handlers.remove(handler)
for thread in self.io_threads:
if thread.io_handler is handler:
thread.stop() | python | {
"resource": ""
} |
q259790 | ThreadPool._add_timeout_handler | validation | def _add_timeout_handler(self, handler):
"""Add a TimeoutHandler to the pool.
"""
self.timeout_handlers.append(handler)
if self.event_thread is None:
return
self._run_timeout_threads(handler) | python | {
"resource": ""
} |
q259791 | ThreadPool._run_timeout_threads | validation | def _run_timeout_threads(self, handler):
"""Start threads for a TimeoutHandler.
"""
# pylint: disable-msg=W0212
for dummy, method in inspect.getmembers(handler, callable):
if not hasattr(method, "_pyxmpp_timeout"):
continue
thread = TimeoutThread(method, daemon = self.daemon,
exc_queue = self.exc_queue)
self.timeout_threads.append(thread)
thread.start() | python | {
"resource": ""
} |
q259792 | ThreadPool._remove_timeout_handler | validation | def _remove_timeout_handler(self, handler):
"""Remove a TimeoutHandler from the pool.
"""
if handler not in self.timeout_handlers:
return
self.timeout_handlers.remove(handler)
for thread in self.timeout_threads:
if thread.method.im_self is handler:
thread.stop() | python | {
"resource": ""
} |
q259793 | ThreadPool.start | validation | def start(self, daemon = False):
"""Start the threads."""
self.daemon = daemon
self.io_threads = []
self.event_thread = EventDispatcherThread(self.event_dispatcher,
daemon = daemon, exc_queue = self.exc_queue)
self.event_thread.start()
for handler in self.io_handlers:
self._run_io_threads(handler)
for handler in self.timeout_handlers:
self._run_timeout_threads(handler) | python | {
"resource": ""
} |
q259794 | ThreadPool.stop | validation | def stop(self, join = False, timeout = None):
"""Stop the threads.
:Parameters:
- `join`: join the threads (wait until they exit)
- `timeout`: maximum time (in seconds) to wait when `join` is
`True`). No limit when `timeout` is `None`.
"""
logger.debug("Closing the io handlers...")
for handler in self.io_handlers:
handler.close()
if self.event_thread and self.event_thread.is_alive():
logger.debug("Sending the QUIT signal")
self.event_queue.put(QUIT)
logger.debug(" sent")
threads = self.io_threads + self.timeout_threads
for thread in threads:
logger.debug("Stopping thread: {0!r}".format(thread))
thread.stop()
if not join:
return
if self.event_thread:
threads.append(self.event_thread)
if timeout is None:
for thread in threads:
thread.join()
else:
timeout1 = (timeout * 0.01) / len(threads)
threads_left = []
for thread in threads:
logger.debug("Quick-joining thread {0!r}...".format(thread))
thread.join(timeout1)
if thread.is_alive():
logger.debug(" thread still alive".format(thread))
threads_left.append(thread)
if threads_left:
timeout2 = (timeout * 0.99) / len(threads_left)
for thread in threads_left:
logger.debug("Joining thread {0!r}...".format(thread))
thread.join(timeout2)
self.io_threads = []
self.event_thread = None | python | {
"resource": ""
} |
q259795 | ThreadPool.loop_iteration | validation | def loop_iteration(self, timeout = 0.1):
"""Wait up to `timeout` seconds, raise any exception from the
threads.
"""
try:
exc_info = self.exc_queue.get(True, timeout)[1]
except Queue.Empty:
return
exc_type, exc_value, ext_stack = exc_info
raise exc_type, exc_value, ext_stack | python | {
"resource": ""
} |
q259796 | LegacyClientStream._reset | validation | def _reset(self):
"""Reset the `LegacyClientStream` object state, making the object ready
to handle new connections."""
ClientStream._reset(self)
self.available_auth_methods = None
self.auth_stanza = None
self.registration_callback = None | python | {
"resource": ""
} |
q259797 | LegacyClientStream._post_connect | validation | def _post_connect(self):
"""Initialize authentication when the connection is established
and we are the initiator."""
if not self.initiator:
if "plain" in self.auth_methods or "digest" in self.auth_methods:
self.set_iq_get_handler("query","jabber:iq:auth",
self.auth_in_stage1)
self.set_iq_set_handler("query","jabber:iq:auth",
self.auth_in_stage2)
elif self.registration_callback:
iq = Iq(stanza_type = "get")
iq.set_content(Register())
self.set_response_handlers(iq, self.registration_form_received, self.registration_error)
self.send(iq)
return
ClientStream._post_connect(self) | python | {
"resource": ""
} |
q259798 | LegacyClientStream._post_auth | validation | def _post_auth(self):
"""Unregister legacy authentication handlers after successfull
authentication."""
ClientStream._post_auth(self)
if not self.initiator:
self.unset_iq_get_handler("query","jabber:iq:auth")
self.unset_iq_set_handler("query","jabber:iq:auth") | python | {
"resource": ""
} |
q259799 | LegacyClientStream._try_auth | validation | def _try_auth(self):
"""Try to authenticate using the first one of allowed authentication
methods left.
[client only]"""
if self.authenticated:
self.__logger.debug("try_auth: already authenticated")
return
self.__logger.debug("trying auth: %r" % (self._auth_methods_left,))
if not self._auth_methods_left:
raise LegacyAuthenticationError("No allowed authentication methods available")
method=self._auth_methods_left[0]
if method.startswith("sasl:"):
return ClientStream._try_auth(self)
elif method not in ("plain","digest"):
self._auth_methods_left.pop(0)
self.__logger.debug("Skipping unknown auth method: %s" % method)
return self._try_auth()
elif self.available_auth_methods is not None:
if method in self.available_auth_methods:
self._auth_methods_left.pop(0)
self.auth_method_used=method
if method=="digest":
self._digest_auth_stage2(self.auth_stanza)
else:
self._plain_auth_stage2(self.auth_stanza)
self.auth_stanza=None
return
else:
self.__logger.debug("Skipping unavailable auth method: %s" % method)
else:
self._auth_stage1() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.