partition
stringclasses 3
values | func_name
stringlengths 1
134
| docstring
stringlengths 1
46.9k
| path
stringlengths 4
223
| original_string
stringlengths 75
104k
| code
stringlengths 75
104k
| docstring_tokens
listlengths 1
1.97k
| repo
stringlengths 7
55
| language
stringclasses 1
value | url
stringlengths 87
315
| code_tokens
listlengths 19
28.4k
| sha
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|
valid
|
XMPPSettings.get_int_range_validator
|
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
|
pyxmpp2/settings.py
|
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
|
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
|
[
"Return",
"an",
"integer",
"range",
"validator",
"to",
"be",
"used",
"with",
"add_setting",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L279-L297
|
[
"def",
"get_int_range_validator",
"(",
"start",
",",
"stop",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
XMPPSettings.list_all
|
List known settings.
:Parameters:
- `basic`: When `True` then limit output to the basic settings,
when `False` list only the extra settings.
|
pyxmpp2/settings.py
|
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]
|
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]
|
[
"List",
"known",
"settings",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L300-L310
|
[
"def",
"list_all",
"(",
"cls",
",",
"basic",
"=",
"None",
")",
":",
"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",
"]"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
XMPPSettings.get_arg_parser
|
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`
|
pyxmpp2/settings.py
|
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
|
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
|
[
"Make",
"a",
"command",
"-",
"line",
"option",
"parser",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/settings.py#L313-L394
|
[
"def",
"get_arg_parser",
"(",
"cls",
",",
"settings",
"=",
"None",
",",
"option_prefix",
"=",
"u'--'",
",",
"add_help",
"=",
"False",
")",
":",
"# 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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
are_domains_equal
|
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.
|
pyxmpp2/jid.py
|
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()
|
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()
|
[
"Compare",
"two",
"International",
"Domain",
"Names",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L49-L63
|
[
"def",
"are_domains_equal",
"(",
"domain1",
",",
"domain2",
")",
":",
"domain1",
"=",
"domain1",
".",
"encode",
"(",
"\"idna\"",
")",
"domain2",
"=",
"domain2",
".",
"encode",
"(",
"\"idna\"",
")",
"return",
"domain1",
".",
"lower",
"(",
")",
"==",
"domain2",
".",
"lower",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
_validate_ip_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
|
pyxmpp2/jid.py
|
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")
|
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")
|
[
"Check",
"if",
"address",
"is",
"valid",
"IP",
"address",
"and",
"return",
"it",
"in",
"a",
"normalized",
"form",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L65-L90
|
[
"def",
"_validate_ip_address",
"(",
"family",
",",
"address",
")",
":",
"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\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
JID.__from_unicode
|
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
|
pyxmpp2/jid.py
|
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)
|
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)
|
[
"Return",
"jid",
"tuple",
"from",
"an",
"Unicode",
"string",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L156-L186
|
[
"def",
"__from_unicode",
"(",
"cls",
",",
"data",
",",
"check",
"=",
"True",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
JID.__prepare_local
|
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.
|
pyxmpp2/jid.py
|
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
|
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
|
[
"Prepare",
"localpart",
"of",
"the",
"JID"
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L189-L209
|
[
"def",
"__prepare_local",
"(",
"data",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
JID.__prepare_domain
|
Prepare domainpart of the JID.
:Parameters:
- `data`: Domain part of the JID
:Types:
- `data`: `unicode`
:raise JIDError: if the domain name is too long.
|
pyxmpp2/jid.py
|
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
|
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
|
[
"Prepare",
"domainpart",
"of",
"the",
"JID",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L212-L260
|
[
"def",
"__prepare_domain",
"(",
"data",
")",
":",
"# 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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
JID.__prepare_resource
|
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.
|
pyxmpp2/jid.py
|
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
|
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
|
[
"Prepare",
"the",
"resourcepart",
"of",
"the",
"JID",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L263-L281
|
[
"def",
"__prepare_resource",
"(",
"data",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
JID.as_unicode
|
Unicode string JID representation.
:return: JID as Unicode string.
|
pyxmpp2/jid.py
|
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
|
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
|
[
"Unicode",
"string",
"JID",
"representation",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/jid.py#L305-L316
|
[
"def",
"as_unicode",
"(",
"self",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
is_ipv6_available
|
Check if IPv6 is available.
:Return: `True` when an IPv6 socket can be created.
|
pyxmpp2/resolver.py
|
def is_ipv6_available():
"""Check if IPv6 is available.
:Return: `True` when an IPv6 socket can be created.
"""
try:
socket.socket(socket.AF_INET6).close()
except (socket.error, AttributeError):
return False
return True
|
def is_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
|
[
"Check",
"if",
"IPv6",
"is",
"available",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L49-L58
|
[
"def",
"is_ipv6_available",
"(",
")",
":",
"try",
":",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET6",
")",
".",
"close",
"(",
")",
"except",
"(",
"socket",
".",
"error",
",",
"AttributeError",
")",
":",
"return",
"False",
"return",
"True"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
is_ipv4_available
|
Check if IPv4 is available.
:Return: `True` when an IPv4 socket can be created.
|
pyxmpp2/resolver.py
|
def is_ipv4_available():
"""Check if IPv4 is available.
:Return: `True` when an IPv4 socket can be created.
"""
try:
socket.socket(socket.AF_INET).close()
except socket.error:
return False
return True
|
def 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
|
[
"Check",
"if",
"IPv4",
"is",
"available",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L60-L69
|
[
"def",
"is_ipv4_available",
"(",
")",
":",
"try",
":",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
")",
".",
"close",
"(",
")",
"except",
"socket",
".",
"error",
":",
"return",
"False",
"return",
"True"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
shuffle_srv
|
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`
|
pyxmpp2/resolver.py
|
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
|
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
|
[
"Randomly",
"reorder",
"SRV",
"records",
"using",
"their",
"weights",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L71-L97
|
[
"def",
"shuffle_srv",
"(",
"records",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
reorder_srv
|
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`
|
pyxmpp2/resolver.py
|
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
|
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
|
[
"Reorder",
"SRV",
"records",
"using",
"their",
"priorities",
"and",
"weights",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L99-L121
|
[
"def",
"reorder_srv",
"(",
"records",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadedResolverBase.stop
|
Stop the resolver threads.
|
pyxmpp2/resolver.py
|
def stop(self):
"""Stop the resolver threads.
"""
with self.lock:
for dummy in self.threads:
self.queue.put(None)
|
def stop(self):
"""Stop the resolver threads.
"""
with self.lock:
for dummy in self.threads:
self.queue.put(None)
|
[
"Stop",
"the",
"resolver",
"threads",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L146-L151
|
[
"def",
"stop",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"for",
"dummy",
"in",
"self",
".",
"threads",
":",
"self",
".",
"queue",
".",
"put",
"(",
"None",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadedResolverBase._start_thread
|
Start a new working thread unless the maximum number of threads
has been reached or the request queue is empty.
|
pyxmpp2/resolver.py
|
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()
|
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()
|
[
"Start",
"a",
"new",
"working",
"thread",
"unless",
"the",
"maximum",
"number",
"of",
"threads",
"has",
"been",
"reached",
"or",
"the",
"request",
"queue",
"is",
"empty",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L153-L169
|
[
"def",
"_start_thread",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadedResolverBase._run
|
The thread function.
|
pyxmpp2/resolver.py
|
def _run(self, thread_n):
"""The thread function."""
try:
logger.debug("{0!r}: entering thread #{1}"
.format(self, thread_n))
resolver = self._make_resolver()
while True:
request = self.queue.get()
if request is None:
break
method, args = request
logger.debug(" calling {0!r}.{1}{2!r}"
.format(resolver, method, args))
getattr(resolver, method)(*args) # pylint: disable=W0142
self.queue.task_done()
logger.debug("{0!r}: leaving thread #{1}"
.format(self, thread_n))
finally:
self.threads.remove(threading.currentThread())
|
def _run(self, thread_n):
"""The thread function."""
try:
logger.debug("{0!r}: entering thread #{1}"
.format(self, thread_n))
resolver = self._make_resolver()
while True:
request = self.queue.get()
if request is None:
break
method, args = request
logger.debug(" calling {0!r}.{1}{2!r}"
.format(resolver, method, args))
getattr(resolver, method)(*args) # pylint: disable=W0142
self.queue.task_done()
logger.debug("{0!r}: leaving thread #{1}"
.format(self, thread_n))
finally:
self.threads.remove(threading.currentThread())
|
[
"The",
"thread",
"function",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L181-L199
|
[
"def",
"_run",
"(",
"self",
",",
"thread_n",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"\"{0!r}: entering thread #{1}\"",
".",
"format",
"(",
"self",
",",
"thread_n",
")",
")",
"resolver",
"=",
"self",
".",
"_make_resolver",
"(",
")",
"while",
"True",
":",
"request",
"=",
"self",
".",
"queue",
".",
"get",
"(",
")",
"if",
"request",
"is",
"None",
":",
"break",
"method",
",",
"args",
"=",
"request",
"logger",
".",
"debug",
"(",
"\" calling {0!r}.{1}{2!r}\"",
".",
"format",
"(",
"resolver",
",",
"method",
",",
"args",
")",
")",
"getattr",
"(",
"resolver",
",",
"method",
")",
"(",
"*",
"args",
")",
"# pylint: disable=W0142",
"self",
".",
"queue",
".",
"task_done",
"(",
")",
"logger",
".",
"debug",
"(",
"\"{0!r}: leaving thread #{1}\"",
".",
"format",
"(",
"self",
",",
"thread_n",
")",
")",
"finally",
":",
"self",
".",
"threads",
".",
"remove",
"(",
"threading",
".",
"currentThread",
"(",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
DumbBlockingResolver.resolve_address
|
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`
|
pyxmpp2/resolver.py
|
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])
|
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])
|
[
"Start",
"looking",
"up",
"an",
"A",
"or",
"AAAA",
"record",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/resolver.py#L222-L270
|
[
"def",
"resolve_address",
"(",
"self",
",",
"hostname",
",",
"callback",
",",
"allow_cname",
"=",
"True",
")",
":",
"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",
"]",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
send_message
|
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`
|
pyxmpp2/simple.py
|
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
|
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
|
[
"Star",
"an",
"XMPP",
"session",
"and",
"send",
"a",
"message",
"then",
"exit",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/simple.py#L85-L147
|
[
"def",
"send_message",
"(",
"source_jid",
",",
"password",
",",
"target_jid",
",",
"body",
",",
"subject",
"=",
"None",
",",
"message_type",
"=",
"\"chat\"",
",",
"message_thread",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"# 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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ComponentStream.connect
|
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`
|
pyxmpp2/ext/component.py
|
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()
|
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()
|
[
"Establish",
"a",
"client",
"connection",
"to",
"a",
"server",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L79-L97
|
[
"def",
"connect",
"(",
"self",
",",
"server",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_connect",
"(",
"server",
",",
"port",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ComponentStream._connect
|
Same as `ComponentStream.connect` but assume `self.lock` is acquired.
|
pyxmpp2/ext/component.py
|
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)
|
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)
|
[
"Same",
"as",
"ComponentStream",
".",
"connect",
"but",
"assume",
"self",
".",
"lock",
"is",
"acquired",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L99-L109
|
[
"def",
"_connect",
"(",
"self",
",",
"server",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ComponentStream._compute_handshake
|
Compute the authentication handshake value.
:return: the computed hash value.
:returntype: `str`
|
pyxmpp2/ext/component.py
|
def _compute_handshake(self):
"""Compute the authentication handshake value.
:return: the computed hash value.
:returntype: `str`"""
return hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.secret)).hexdigest()
|
def _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()
|
[
"Compute",
"the",
"authentication",
"handshake",
"value",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L138-L143
|
[
"def",
"_compute_handshake",
"(",
"self",
")",
":",
"return",
"hashlib",
".",
"sha1",
"(",
"to_utf8",
"(",
"self",
".",
"stream_id",
")",
"+",
"to_utf8",
"(",
"self",
".",
"secret",
")",
")",
".",
"hexdigest",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ComponentStream._auth
|
Authenticate on the server.
[component only]
|
pyxmpp2/ext/component.py
|
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.")
|
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.")
|
[
"Authenticate",
"on",
"the",
"server",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L145-L158
|
[
"def",
"_auth",
"(",
"self",
")",
":",
"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.\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ComponentStream._process_node
|
Process first level element of the stream.
Handle component handshake (authentication) element, and
treat elements in "jabber:component:accept", "jabber:client"
and "jabber:server" equally (pass to `self.process_stanza`).
All other elements are passed to `Stream._process_node`.
:Parameters:
- `node`: XML node describing the element
|
pyxmpp2/ext/component.py
|
def _process_node(self,node):
"""Process first level element of the stream.
Handle component handshake (authentication) element, and
treat elements in "jabber:component:accept", "jabber:client"
and "jabber:server" equally (pass to `self.process_stanza`).
All other elements are passed to `Stream._process_node`.
:Parameters:
- `node`: XML node describing the element
"""
ns=node.ns()
if ns:
ns_uri=node.ns().getContent()
if (not ns or ns_uri=="jabber:component:accept") and node.name=="handshake":
if self.initiator and not self.authenticated:
self.authenticated=1
self.state_change("authenticated",self.me)
self._post_auth()
return
elif not self.authenticated and node.getContent()==self._compute_handshake():
self.peer=self.me
n=common_doc.newChild(None,"handshake",None)
self._write_node(n)
n.unlinkNode()
n.freeNode()
self.peer_authenticated=1
self.state_change("authenticated",self.peer)
self._post_auth()
return
else:
self._send_stream_error("not-authorized")
raise FatalComponentStreamError("Hanshake error.")
if ns_uri in ("jabber:component:accept","jabber:client","jabber:server"):
stanza=stanza_factory(node)
self.lock.release()
try:
self.process_stanza(stanza)
finally:
self.lock.acquire()
stanza.free()
return
return Stream._process_node(self,node)
|
def _process_node(self,node):
"""Process first level element of the stream.
Handle component handshake (authentication) element, and
treat elements in "jabber:component:accept", "jabber:client"
and "jabber:server" equally (pass to `self.process_stanza`).
All other elements are passed to `Stream._process_node`.
:Parameters:
- `node`: XML node describing the element
"""
ns=node.ns()
if ns:
ns_uri=node.ns().getContent()
if (not ns or ns_uri=="jabber:component:accept") and node.name=="handshake":
if self.initiator and not self.authenticated:
self.authenticated=1
self.state_change("authenticated",self.me)
self._post_auth()
return
elif not self.authenticated and node.getContent()==self._compute_handshake():
self.peer=self.me
n=common_doc.newChild(None,"handshake",None)
self._write_node(n)
n.unlinkNode()
n.freeNode()
self.peer_authenticated=1
self.state_change("authenticated",self.peer)
self._post_auth()
return
else:
self._send_stream_error("not-authorized")
raise FatalComponentStreamError("Hanshake error.")
if ns_uri in ("jabber:component:accept","jabber:client","jabber:server"):
stanza=stanza_factory(node)
self.lock.release()
try:
self.process_stanza(stanza)
finally:
self.lock.acquire()
stanza.free()
return
return Stream._process_node(self,node)
|
[
"Process",
"first",
"level",
"element",
"of",
"the",
"stream",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/component.py#L160-L203
|
[
"def",
"_process_node",
"(",
"self",
",",
"node",
")",
":",
"ns",
"=",
"node",
".",
"ns",
"(",
")",
"if",
"ns",
":",
"ns_uri",
"=",
"node",
".",
"ns",
"(",
")",
".",
"getContent",
"(",
")",
"if",
"(",
"not",
"ns",
"or",
"ns_uri",
"==",
"\"jabber:component:accept\"",
")",
"and",
"node",
".",
"name",
"==",
"\"handshake\"",
":",
"if",
"self",
".",
"initiator",
"and",
"not",
"self",
".",
"authenticated",
":",
"self",
".",
"authenticated",
"=",
"1",
"self",
".",
"state_change",
"(",
"\"authenticated\"",
",",
"self",
".",
"me",
")",
"self",
".",
"_post_auth",
"(",
")",
"return",
"elif",
"not",
"self",
".",
"authenticated",
"and",
"node",
".",
"getContent",
"(",
")",
"==",
"self",
".",
"_compute_handshake",
"(",
")",
":",
"self",
".",
"peer",
"=",
"self",
".",
"me",
"n",
"=",
"common_doc",
".",
"newChild",
"(",
"None",
",",
"\"handshake\"",
",",
"None",
")",
"self",
".",
"_write_node",
"(",
"n",
")",
"n",
".",
"unlinkNode",
"(",
")",
"n",
".",
"freeNode",
"(",
")",
"self",
".",
"peer_authenticated",
"=",
"1",
"self",
".",
"state_change",
"(",
"\"authenticated\"",
",",
"self",
".",
"peer",
")",
"self",
".",
"_post_auth",
"(",
")",
"return",
"else",
":",
"self",
".",
"_send_stream_error",
"(",
"\"not-authorized\"",
")",
"raise",
"FatalComponentStreamError",
"(",
"\"Hanshake error.\"",
")",
"if",
"ns_uri",
"in",
"(",
"\"jabber:component:accept\"",
",",
"\"jabber:client\"",
",",
"\"jabber:server\"",
")",
":",
"stanza",
"=",
"stanza_factory",
"(",
"node",
")",
"self",
".",
"lock",
".",
"release",
"(",
")",
"try",
":",
"self",
".",
"process_stanza",
"(",
"stanza",
")",
"finally",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"stanza",
".",
"free",
"(",
")",
"return",
"return",
"Stream",
".",
"_process_node",
"(",
"self",
",",
"node",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._set_state
|
Set `_state` and notify any threads waiting for the change.
|
pyxmpp2/transport.py
|
def _set_state(self, state):
"""Set `_state` and notify any threads waiting for the change.
"""
logger.debug(" _set_state({0!r})".format(state))
self._state = state
self._state_cond.notify()
|
def _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()
|
[
"Set",
"_state",
"and",
"notify",
"any",
"threads",
"waiting",
"for",
"the",
"change",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L201-L206
|
[
"def",
"_set_state",
"(",
"self",
",",
"state",
")",
":",
"logger",
".",
"debug",
"(",
"\" _set_state({0!r})\"",
".",
"format",
"(",
"state",
")",
")",
"self",
".",
"_state",
"=",
"state",
"self",
".",
"_state_cond",
".",
"notify",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.connect
|
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)
|
pyxmpp2/transport.py
|
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)
|
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)
|
[
"Start",
"establishing",
"TCP",
"connection",
"with",
"given",
"address",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L208-L226
|
[
"def",
"connect",
"(",
"self",
",",
"addr",
",",
"port",
"=",
"None",
",",
"service",
"=",
"None",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"_connect",
"(",
"addr",
",",
"port",
",",
"service",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._connect
|
Same as `connect`, but assumes `lock` acquired.
|
pyxmpp2/transport.py
|
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")
|
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")
|
[
"Same",
"as",
"connect",
"but",
"assumes",
"lock",
"acquired",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L228-L259
|
[
"def",
"_connect",
"(",
"self",
",",
"addr",
",",
"port",
",",
"service",
")",
":",
"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\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._resolve_srv
|
Start resolving the SRV record.
|
pyxmpp2/transport.py
|
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)
|
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)
|
[
"Start",
"resolving",
"the",
"SRV",
"record",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L261-L268
|
[
"def",
"_resolve_srv",
"(",
"self",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._got_srv
|
Handle SRV lookup result.
:Parameters:
- `addrs`: properly sorted list of (hostname, port) tuples
|
pyxmpp2/transport.py
|
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")
|
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")
|
[
"Handle",
"SRV",
"lookup",
"result",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L270-L294
|
[
"def",
"_got_srv",
"(",
"self",
",",
"addrs",
")",
":",
"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\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._resolve_hostname
|
Start hostname resolution for the next name to try.
[called with `lock` acquired]
|
pyxmpp2/transport.py
|
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))
|
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))
|
[
"Start",
"hostname",
"resolution",
"for",
"the",
"next",
"name",
"to",
"try",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L296-L309
|
[
"def",
"_resolve_hostname",
"(",
"self",
")",
":",
"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",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._got_addresses
|
Handler DNS address record lookup result.
:Parameters:
- `name`: the name requested
- `port`: port number to connect to
- `addrs`: list of (family, address) tuples
|
pyxmpp2/transport.py
|
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")
|
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")
|
[
"Handler",
"DNS",
"address",
"record",
"lookup",
"result",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L311-L331
|
[
"def",
"_got_addresses",
"(",
"self",
",",
"name",
",",
"port",
",",
"addrs",
")",
":",
"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\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._start_connect
|
Start connecting to the next address on the `_dst_addrs` list.
[ called with `lock` acquired ]
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Start",
"connecting",
"to",
"the",
"next",
"address",
"on",
"the",
"_dst_addrs",
"list",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L333-L367
|
[
"def",
"_start_connect",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._connected
|
Handle connection success.
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Handle",
"connection",
"success",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L369-L381
|
[
"def",
"_connected",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._continue_connect
|
Continue connecting.
[called with `lock` acquired]
:Return: `True` when just connected
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Continue",
"connecting",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L383-L409
|
[
"def",
"_continue_connect",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._write
|
Write raw data to the socket.
:Parameters:
- `data`: data to send
:Types:
- `data`: `bytes`
|
pyxmpp2/transport.py
|
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))
|
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))
|
[
"Write",
"raw",
"data",
"to",
"the",
"socket",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L411-L440
|
[
"def",
"_write",
"(",
"self",
",",
"data",
")",
":",
"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",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.set_target
|
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`
|
pyxmpp2/transport.py
|
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)
|
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)
|
[
"Make",
"the",
"stream",
"the",
"target",
"for",
"this",
"transport",
"instance",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L442-L458
|
[
"def",
"set_target",
"(",
"self",
",",
"stream",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"_stream",
":",
"raise",
"ValueError",
"(",
"\"Target stream already set\"",
")",
"self",
".",
"_stream",
"=",
"stream",
"self",
".",
"_reader",
"=",
"StreamReader",
"(",
"stream",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.send_stream_head
|
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`
|
pyxmpp2/transport.py
|
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"))
|
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"))
|
[
"Send",
"stream",
"head",
"via",
"the",
"transport",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L460-L485
|
[
"def",
"send_stream_head",
"(",
"self",
",",
"stanza_namespace",
",",
"stream_from",
",",
"stream_to",
",",
"stream_id",
"=",
"None",
",",
"version",
"=",
"u'1.0'",
",",
"language",
"=",
"None",
")",
":",
"# 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\"",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.send_stream_tail
|
Send stream tail via the transport.
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Send",
"stream",
"tail",
"via",
"the",
"transport",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L492-L515
|
[
"def",
"send_stream_tail",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.send_element
|
Send an element via the transport.
|
pyxmpp2/transport.py
|
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"))
|
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"))
|
[
"Send",
"an",
"element",
"via",
"the",
"transport",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L517-L527
|
[
"def",
"send_element",
"(",
"self",
",",
"element",
")",
":",
"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\"",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.prepare
|
When connecting start the next connection step and schedule
next `prepare` call, when connected return `HandlerReady()`
|
pyxmpp2/transport.py
|
def prepare(self):
"""When connecting start the next connection step and schedule
next `prepare` call, when connected return `HandlerReady()`
"""
result = HandlerReady()
logger.debug("TCPTransport.prepare(): state: {0!r}".format(self._state))
with self.lock:
if self._state in ("connected", "closing", "closed", "aborted"):
# no need to call prepare() .fileno() is stable
pass
elif self._state == "connect":
self._start_connect()
result = PrepareAgain(None)
elif self._state == "resolve-hostname":
self._resolve_hostname()
result = PrepareAgain(0)
elif self._state == "resolve-srv":
self._resolve_srv()
result = PrepareAgain(0)
else:
# wait for i/o, but keep calling prepare()
result = PrepareAgain(None)
logger.debug("TCPTransport.prepare(): new state: {0!r}"
.format(self._state))
return result
|
def prepare(self):
"""When connecting start the next connection step and schedule
next `prepare` call, when connected return `HandlerReady()`
"""
result = HandlerReady()
logger.debug("TCPTransport.prepare(): state: {0!r}".format(self._state))
with self.lock:
if self._state in ("connected", "closing", "closed", "aborted"):
# no need to call prepare() .fileno() is stable
pass
elif self._state == "connect":
self._start_connect()
result = PrepareAgain(None)
elif self._state == "resolve-hostname":
self._resolve_hostname()
result = PrepareAgain(0)
elif self._state == "resolve-srv":
self._resolve_srv()
result = PrepareAgain(0)
else:
# wait for i/o, but keep calling prepare()
result = PrepareAgain(None)
logger.debug("TCPTransport.prepare(): new state: {0!r}"
.format(self._state))
return result
|
[
"When",
"connecting",
"start",
"the",
"next",
"connection",
"step",
"and",
"schedule",
"next",
"prepare",
"call",
"when",
"connected",
"return",
"HandlerReady",
"()"
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L529-L553
|
[
"def",
"prepare",
"(",
"self",
")",
":",
"result",
"=",
"HandlerReady",
"(",
")",
"logger",
".",
"debug",
"(",
"\"TCPTransport.prepare(): state: {0!r}\"",
".",
"format",
"(",
"self",
".",
"_state",
")",
")",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"_state",
"in",
"(",
"\"connected\"",
",",
"\"closing\"",
",",
"\"closed\"",
",",
"\"aborted\"",
")",
":",
"# no need to call prepare() .fileno() is stable",
"pass",
"elif",
"self",
".",
"_state",
"==",
"\"connect\"",
":",
"self",
".",
"_start_connect",
"(",
")",
"result",
"=",
"PrepareAgain",
"(",
"None",
")",
"elif",
"self",
".",
"_state",
"==",
"\"resolve-hostname\"",
":",
"self",
".",
"_resolve_hostname",
"(",
")",
"result",
"=",
"PrepareAgain",
"(",
"0",
")",
"elif",
"self",
".",
"_state",
"==",
"\"resolve-srv\"",
":",
"self",
".",
"_resolve_srv",
"(",
")",
"result",
"=",
"PrepareAgain",
"(",
"0",
")",
"else",
":",
"# wait for i/o, but keep calling prepare()",
"result",
"=",
"PrepareAgain",
"(",
"None",
")",
"logger",
".",
"debug",
"(",
"\"TCPTransport.prepare(): new state: {0!r}\"",
".",
"format",
"(",
"self",
".",
"_state",
")",
")",
"return",
"result"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.is_readable
|
:Return: `True` when the I/O channel can be read
|
pyxmpp2/transport.py
|
def is_readable(self):
"""
:Return: `True` when the I/O channel can be read
"""
return self._socket is not None and not self._eof and (
self._state in ("connected", "closing")
or self._state == "tls-handshake"
and self._tls_state == "want_read")
|
def is_readable(self):
"""
:Return: `True` when the I/O channel can be read
"""
return self._socket is not None and not self._eof and (
self._state in ("connected", "closing")
or self._state == "tls-handshake"
and self._tls_state == "want_read")
|
[
":",
"Return",
":",
"True",
"when",
"the",
"I",
"/",
"O",
"channel",
"can",
"be",
"read"
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L562-L569
|
[
"def",
"is_readable",
"(",
"self",
")",
":",
"return",
"self",
".",
"_socket",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"_eof",
"and",
"(",
"self",
".",
"_state",
"in",
"(",
"\"connected\"",
",",
"\"closing\"",
")",
"or",
"self",
".",
"_state",
"==",
"\"tls-handshake\"",
"and",
"self",
".",
"_tls_state",
"==",
"\"want_read\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.wait_for_readability
|
Stop current thread until the channel is readable.
:Return: `False` if it won't be readable (e.g. is closed)
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Stop",
"current",
"thread",
"until",
"the",
"channel",
"is",
"readable",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L571-L586
|
[
"def",
"wait_for_readability",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.wait_for_writability
|
Stop current thread until the channel is writable.
:Return: `False` if it won't be readable (e.g. is closed)
|
pyxmpp2/transport.py
|
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
|
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
|
[
"Stop",
"current",
"thread",
"until",
"the",
"channel",
"is",
"writable",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L595-L608
|
[
"def",
"wait_for_writability",
"(",
"self",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.handle_write
|
Handle the 'channel writable' state. E.g. send buffered data via a
socket.
|
pyxmpp2/transport.py
|
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))
|
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))
|
[
"Handle",
"the",
"channel",
"writable",
"state",
".",
"E",
".",
"g",
".",
"send",
"buffered",
"data",
"via",
"a",
"socket",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L610-L631
|
[
"def",
"handle_write",
"(",
"self",
")",
":",
"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",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.starttls
|
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`
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Request",
"a",
"TLS",
"handshake",
"on",
"the",
"socket",
"ans",
"switch",
"to",
"encrypted",
"output",
".",
"The",
"handshake",
"will",
"start",
"after",
"any",
"currently",
"buffered",
"data",
"is",
"sent",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L633-L644
|
[
"def",
"starttls",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"event",
"(",
"TLSConnectingEvent",
"(",
")",
")",
"self",
".",
"_write_queue",
".",
"append",
"(",
"StartTLS",
"(",
"*",
"*",
"kwargs",
")",
")",
"self",
".",
"_write_queue_cond",
".",
"notify",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.getpeercert
|
Return the peer certificate.
:ReturnType: `pyxmpp2.cert.Certificate`
|
pyxmpp2/transport.py
|
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)
|
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)
|
[
"Return",
"the",
"peer",
"certificate",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L646-L654
|
[
"def",
"getpeercert",
"(",
"self",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._initiate_starttls
|
Initiate starttls handshake over the socket.
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Initiate",
"starttls",
"handshake",
"over",
"the",
"socket",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L656-L665
|
[
"def",
"_initiate_starttls",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._continue_tls_handshake
|
Continue a TLS handshake.
|
pyxmpp2/transport.py
|
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))
|
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))
|
[
"Continue",
"a",
"TLS",
"handshake",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L667-L703
|
[
"def",
"_continue_tls_handshake",
"(",
"self",
")",
":",
"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",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.handle_read
|
Handle the 'channel readable' state. E.g. read from a socket.
|
pyxmpp2/transport.py
|
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)
|
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)
|
[
"Handle",
"the",
"channel",
"readable",
"state",
".",
"E",
".",
"g",
".",
"read",
"from",
"a",
"socket",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L705-L758
|
[
"def",
"handle_read",
"(",
"self",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.handle_hup
|
Handle the 'channel hungup' state. The handler should not be writable
after this.
|
pyxmpp2/transport.py
|
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
|
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
|
[
"Handle",
"the",
"channel",
"hungup",
"state",
".",
"The",
"handler",
"should",
"not",
"be",
"writable",
"after",
"this",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L760-L770
|
[
"def",
"handle_hup",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"_state",
"==",
"'connecting'",
"and",
"self",
".",
"_dst_addrs",
":",
"self",
".",
"_hup",
"=",
"False",
"self",
".",
"_set_state",
"(",
"\"connect\"",
")",
"return",
"self",
".",
"_hup",
"=",
"True"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.handle_err
|
Handle an error reported.
|
pyxmpp2/transport.py
|
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")
|
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")
|
[
"Handle",
"an",
"error",
"reported",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L772-L786
|
[
"def",
"handle_err",
"(",
"self",
")",
":",
"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\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.disconnect
|
Disconnect the stream gracefully.
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Disconnect",
"the",
"stream",
"gracefully",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L807-L819
|
[
"def",
"disconnect",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._close
|
Same as `_close` but expects `lock` acquired.
|
pyxmpp2/transport.py
|
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()
|
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()
|
[
"Same",
"as",
"_close",
"but",
"expects",
"lock",
"acquired",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L826-L841
|
[
"def",
"_close",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport._feed_reader
|
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`
|
pyxmpp2/transport.py
|
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")
|
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")
|
[
"Feed",
"the",
"stream",
"reader",
"with",
"data",
"received",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L843-L875
|
[
"def",
"_feed_reader",
"(",
"self",
",",
"data",
")",
":",
"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\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TCPTransport.event
|
Pass an event to the target stream or just log it.
|
pyxmpp2/transport.py
|
def event(self, event):
"""Pass an event to the target stream or just log it."""
logger.debug(u"TCP transport event: {0}".format(event))
if self._stream:
event.stream = self._stream
self._event_queue.put(event)
|
def 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)
|
[
"Pass",
"an",
"event",
"to",
"the",
"target",
"stream",
"or",
"just",
"log",
"it",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/transport.py#L877-L882
|
[
"def",
"event",
"(",
"self",
",",
"event",
")",
":",
"logger",
".",
"debug",
"(",
"u\"TCP transport event: {0}\"",
".",
"format",
"(",
"event",
")",
")",
"if",
"self",
".",
"_stream",
":",
"event",
".",
"stream",
"=",
"self",
".",
"_stream",
"self",
".",
"_event_queue",
".",
"put",
"(",
"event",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ParserTarget.start
|
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.
|
pyxmpp2/xmppparser.py
|
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)
|
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)
|
[
"Handle",
"the",
"start",
"tag",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppparser.py#L112-L127
|
[
"def",
"start",
"(",
"self",
",",
"tag",
",",
"attrs",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ParserTarget.end
|
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.
|
pyxmpp2/xmppparser.py
|
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)
|
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)
|
[
"Handle",
"an",
"end",
"tag",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppparser.py#L133-L158
|
[
"def",
"end",
"(",
"self",
",",
"tag",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
StreamReader.feed
|
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`
|
pyxmpp2/xmppparser.py
|
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
|
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
|
[
"Feed",
"the",
"parser",
"with",
"a",
"chunk",
"of",
"data",
".",
"Apropriate",
"methods",
"of",
"handler",
"will",
"be",
"called",
"whenever",
"something",
"interesting",
"is",
"found",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/xmppparser.py#L191-L218
|
[
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ErrorElement._from_xml
|
Initialize an ErrorElement object from an XML element.
:Parameters:
- `element`: XML element to be decoded.
:Types:
- `element`: :etree:`ElementTree.Element`
|
pyxmpp2/error.py
|
def _from_xml(self, element):
"""Initialize an ErrorElement object from an XML element.
:Parameters:
- `element`: XML element to be decoded.
:Types:
- `element`: :etree:`ElementTree.Element`
"""
# pylint: disable-msg=R0912
if element.tag != self.error_qname:
raise ValueError(u"{0!r} is not a {1!r} element".format(
element, self.error_qname))
lang = element.get(XML_LANG_QNAME, None)
if lang:
self.language = lang
self.condition = None
for child in element:
if child.tag.startswith(self.cond_qname_prefix):
if self.condition is not None:
logger.warning("Multiple conditions in XMPP error element.")
continue
self.condition = deepcopy(child)
elif child.tag == self.text_qname:
lang = child.get(XML_LANG_QNAME, None)
if lang:
self.language = lang
self.text = child.text.strip()
else:
bad = False
for prefix in (STREAM_QNP, STANZA_CLIENT_QNP, STANZA_SERVER_QNP,
STANZA_ERROR_QNP, STREAM_ERROR_QNP):
if child.tag.startswith(prefix):
logger.warning("Unexpected stream-namespaced"
" element in error.")
bad = True
break
if not bad:
self.custom_condition.append( deepcopy(child) )
if self.condition is None:
self.condition = ElementTree.Element(self.cond_qname_prefix
+ "undefined-condition")
if self.condition.tag in OBSOLETE_CONDITIONS:
new_cond_name = OBSOLETE_CONDITIONS[self.condition.tag]
self.condition = ElementTree.Element(new_cond_name)
|
def _from_xml(self, element):
"""Initialize an ErrorElement object from an XML element.
:Parameters:
- `element`: XML element to be decoded.
:Types:
- `element`: :etree:`ElementTree.Element`
"""
# pylint: disable-msg=R0912
if element.tag != self.error_qname:
raise ValueError(u"{0!r} is not a {1!r} element".format(
element, self.error_qname))
lang = element.get(XML_LANG_QNAME, None)
if lang:
self.language = lang
self.condition = None
for child in element:
if child.tag.startswith(self.cond_qname_prefix):
if self.condition is not None:
logger.warning("Multiple conditions in XMPP error element.")
continue
self.condition = deepcopy(child)
elif child.tag == self.text_qname:
lang = child.get(XML_LANG_QNAME, None)
if lang:
self.language = lang
self.text = child.text.strip()
else:
bad = False
for prefix in (STREAM_QNP, STANZA_CLIENT_QNP, STANZA_SERVER_QNP,
STANZA_ERROR_QNP, STREAM_ERROR_QNP):
if child.tag.startswith(prefix):
logger.warning("Unexpected stream-namespaced"
" element in error.")
bad = True
break
if not bad:
self.custom_condition.append( deepcopy(child) )
if self.condition is None:
self.condition = ElementTree.Element(self.cond_qname_prefix
+ "undefined-condition")
if self.condition.tag in OBSOLETE_CONDITIONS:
new_cond_name = OBSOLETE_CONDITIONS[self.condition.tag]
self.condition = ElementTree.Element(new_cond_name)
|
[
"Initialize",
"an",
"ErrorElement",
"object",
"from",
"an",
"XML",
"element",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/error.py#L232-L275
|
[
"def",
"_from_xml",
"(",
"self",
",",
"element",
")",
":",
"# pylint: disable-msg=R0912",
"if",
"element",
".",
"tag",
"!=",
"self",
".",
"error_qname",
":",
"raise",
"ValueError",
"(",
"u\"{0!r} is not a {1!r} element\"",
".",
"format",
"(",
"element",
",",
"self",
".",
"error_qname",
")",
")",
"lang",
"=",
"element",
".",
"get",
"(",
"XML_LANG_QNAME",
",",
"None",
")",
"if",
"lang",
":",
"self",
".",
"language",
"=",
"lang",
"self",
".",
"condition",
"=",
"None",
"for",
"child",
"in",
"element",
":",
"if",
"child",
".",
"tag",
".",
"startswith",
"(",
"self",
".",
"cond_qname_prefix",
")",
":",
"if",
"self",
".",
"condition",
"is",
"not",
"None",
":",
"logger",
".",
"warning",
"(",
"\"Multiple conditions in XMPP error element.\"",
")",
"continue",
"self",
".",
"condition",
"=",
"deepcopy",
"(",
"child",
")",
"elif",
"child",
".",
"tag",
"==",
"self",
".",
"text_qname",
":",
"lang",
"=",
"child",
".",
"get",
"(",
"XML_LANG_QNAME",
",",
"None",
")",
"if",
"lang",
":",
"self",
".",
"language",
"=",
"lang",
"self",
".",
"text",
"=",
"child",
".",
"text",
".",
"strip",
"(",
")",
"else",
":",
"bad",
"=",
"False",
"for",
"prefix",
"in",
"(",
"STREAM_QNP",
",",
"STANZA_CLIENT_QNP",
",",
"STANZA_SERVER_QNP",
",",
"STANZA_ERROR_QNP",
",",
"STREAM_ERROR_QNP",
")",
":",
"if",
"child",
".",
"tag",
".",
"startswith",
"(",
"prefix",
")",
":",
"logger",
".",
"warning",
"(",
"\"Unexpected stream-namespaced\"",
"\" element in error.\"",
")",
"bad",
"=",
"True",
"break",
"if",
"not",
"bad",
":",
"self",
".",
"custom_condition",
".",
"append",
"(",
"deepcopy",
"(",
"child",
")",
")",
"if",
"self",
".",
"condition",
"is",
"None",
":",
"self",
".",
"condition",
"=",
"ElementTree",
".",
"Element",
"(",
"self",
".",
"cond_qname_prefix",
"+",
"\"undefined-condition\"",
")",
"if",
"self",
".",
"condition",
".",
"tag",
"in",
"OBSOLETE_CONDITIONS",
":",
"new_cond_name",
"=",
"OBSOLETE_CONDITIONS",
"[",
"self",
".",
"condition",
".",
"tag",
"]",
"self",
".",
"condition",
"=",
"ElementTree",
".",
"Element",
"(",
"new_cond_name",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ErrorElement.as_xml
|
Return the XML error representation.
:returntype: :etree:`ElementTree.Element`
|
pyxmpp2/error.py
|
def as_xml(self):
"""Return the XML error representation.
:returntype: :etree:`ElementTree.Element`"""
result = ElementTree.Element(self.error_qname)
result.append(deepcopy(self.condition))
if self.text:
text = ElementTree.SubElement(result, self.text_qname)
if self.language:
text.set(XML_LANG_QNAME, self.language)
text.text = self.text
return result
|
def as_xml(self):
"""Return the XML error representation.
:returntype: :etree:`ElementTree.Element`"""
result = ElementTree.Element(self.error_qname)
result.append(deepcopy(self.condition))
if self.text:
text = ElementTree.SubElement(result, self.text_qname)
if self.language:
text.set(XML_LANG_QNAME, self.language)
text.text = self.text
return result
|
[
"Return",
"the",
"XML",
"error",
"representation",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/error.py#L301-L312
|
[
"def",
"as_xml",
"(",
"self",
")",
":",
"result",
"=",
"ElementTree",
".",
"Element",
"(",
"self",
".",
"error_qname",
")",
"result",
".",
"append",
"(",
"deepcopy",
"(",
"self",
".",
"condition",
")",
")",
"if",
"self",
".",
"text",
":",
"text",
"=",
"ElementTree",
".",
"SubElement",
"(",
"result",
",",
"self",
".",
"text_qname",
")",
"if",
"self",
".",
"language",
":",
"text",
".",
"set",
"(",
"XML_LANG_QNAME",
",",
"self",
".",
"language",
")",
"text",
".",
"text",
"=",
"self",
".",
"text",
"return",
"result"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
StanzaErrorElement._from_xml
|
Initialize an ErrorElement object from an XML element.
:Parameters:
- `element`: XML element to be decoded.
:Types:
- `element`: :etree:`ElementTree.Element`
|
pyxmpp2/error.py
|
def _from_xml(self, element):
"""Initialize an ErrorElement object from an XML element.
:Parameters:
- `element`: XML element to be decoded.
:Types:
- `element`: :etree:`ElementTree.Element`
"""
ErrorElement._from_xml(self, element)
error_type = element.get(u"type")
if error_type:
self.error_type = error_type
|
def _from_xml(self, element):
"""Initialize an ErrorElement object from an XML element.
:Parameters:
- `element`: XML element to be decoded.
:Types:
- `element`: :etree:`ElementTree.Element`
"""
ErrorElement._from_xml(self, element)
error_type = element.get(u"type")
if error_type:
self.error_type = error_type
|
[
"Initialize",
"an",
"ErrorElement",
"object",
"from",
"an",
"XML",
"element",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/error.py#L399-L410
|
[
"def",
"_from_xml",
"(",
"self",
",",
"element",
")",
":",
"ErrorElement",
".",
"_from_xml",
"(",
"self",
",",
"element",
")",
"error_type",
"=",
"element",
".",
"get",
"(",
"u\"type\"",
")",
"if",
"error_type",
":",
"self",
".",
"error_type",
"=",
"error_type"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
StanzaErrorElement.as_xml
|
Return the XML error representation.
:Parameters:
- `stanza_namespace`: namespace URI of the containing stanza
:Types:
- `stanza_namespace`: `unicode`
:returntype: :etree:`ElementTree.Element`
|
pyxmpp2/error.py
|
def as_xml(self, stanza_namespace = None): # pylint: disable-msg=W0221
"""Return the XML error representation.
:Parameters:
- `stanza_namespace`: namespace URI of the containing stanza
:Types:
- `stanza_namespace`: `unicode`
:returntype: :etree:`ElementTree.Element`"""
if stanza_namespace:
self.error_qname = "{{{0}}}error".format(stanza_namespace)
self.text_qname = "{{{0}}}text".format(stanza_namespace)
result = ErrorElement.as_xml(self)
result.set("type", self.error_type)
return result
|
def as_xml(self, stanza_namespace = None): # pylint: disable-msg=W0221
"""Return the XML error representation.
:Parameters:
- `stanza_namespace`: namespace URI of the containing stanza
:Types:
- `stanza_namespace`: `unicode`
:returntype: :etree:`ElementTree.Element`"""
if stanza_namespace:
self.error_qname = "{{{0}}}error".format(stanza_namespace)
self.text_qname = "{{{0}}}text".format(stanza_namespace)
result = ErrorElement.as_xml(self)
result.set("type", self.error_type)
return result
|
[
"Return",
"the",
"XML",
"error",
"representation",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/error.py#L423-L437
|
[
"def",
"as_xml",
"(",
"self",
",",
"stanza_namespace",
"=",
"None",
")",
":",
"# pylint: disable-msg=W0221",
"if",
"stanza_namespace",
":",
"self",
".",
"error_qname",
"=",
"\"{{{0}}}error\"",
".",
"format",
"(",
"stanza_namespace",
")",
"self",
".",
"text_qname",
"=",
"\"{{{0}}}text\"",
".",
"format",
"(",
"stanza_namespace",
")",
"result",
"=",
"ErrorElement",
".",
"as_xml",
"(",
"self",
")",
"result",
".",
"set",
"(",
"\"type\"",
",",
"self",
".",
"error_type",
")",
"return",
"result"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ReadingThread.run
|
The thread function.
First, call the handler's 'prepare' method until it returns
`HandlerReady` then loop waiting for the socket input and calling
'handle_read' on the handler.
|
pyxmpp2/mainloop/threads.py
|
def run(self):
"""The thread function.
First, call the handler's 'prepare' method until it returns
`HandlerReady` then loop waiting for the socket input and calling
'handle_read' on the handler.
"""
# pylint: disable-msg=R0912
interval = self.settings["poll_interval"]
prepared = False
timeout = 0.1
while not self._quit:
if not prepared:
logger.debug("{0}: preparing handler: {1!r}".format(
self.name, self.io_handler))
ret = self.io_handler.prepare()
logger.debug("{0}: prepare result: {1!r}".format(self.name,
ret))
if isinstance(ret, HandlerReady):
prepared = True
elif isinstance(ret, PrepareAgain):
if ret.timeout is not None:
timeout = ret.timeout
else:
raise TypeError("Unexpected result type from prepare()")
if self.io_handler.is_readable():
logger.debug("{0}: readable".format(self.name))
fileno = self.io_handler.fileno()
if fileno is not None:
readable = wait_for_read(fileno, interval)
if readable:
self.io_handler.handle_read()
elif not prepared:
if timeout:
time.sleep(timeout)
else:
logger.debug("{0}: waiting for readability".format(self.name))
if not self.io_handler.wait_for_readability():
break
|
def run(self):
"""The thread function.
First, call the handler's 'prepare' method until it returns
`HandlerReady` then loop waiting for the socket input and calling
'handle_read' on the handler.
"""
# pylint: disable-msg=R0912
interval = self.settings["poll_interval"]
prepared = False
timeout = 0.1
while not self._quit:
if not prepared:
logger.debug("{0}: preparing handler: {1!r}".format(
self.name, self.io_handler))
ret = self.io_handler.prepare()
logger.debug("{0}: prepare result: {1!r}".format(self.name,
ret))
if isinstance(ret, HandlerReady):
prepared = True
elif isinstance(ret, PrepareAgain):
if ret.timeout is not None:
timeout = ret.timeout
else:
raise TypeError("Unexpected result type from prepare()")
if self.io_handler.is_readable():
logger.debug("{0}: readable".format(self.name))
fileno = self.io_handler.fileno()
if fileno is not None:
readable = wait_for_read(fileno, interval)
if readable:
self.io_handler.handle_read()
elif not prepared:
if timeout:
time.sleep(timeout)
else:
logger.debug("{0}: waiting for readability".format(self.name))
if not self.io_handler.wait_for_readability():
break
|
[
"The",
"thread",
"function",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L136-L174
|
[
"def",
"run",
"(",
"self",
")",
":",
"# pylint: disable-msg=R0912",
"interval",
"=",
"self",
".",
"settings",
"[",
"\"poll_interval\"",
"]",
"prepared",
"=",
"False",
"timeout",
"=",
"0.1",
"while",
"not",
"self",
".",
"_quit",
":",
"if",
"not",
"prepared",
":",
"logger",
".",
"debug",
"(",
"\"{0}: preparing handler: {1!r}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"self",
".",
"io_handler",
")",
")",
"ret",
"=",
"self",
".",
"io_handler",
".",
"prepare",
"(",
")",
"logger",
".",
"debug",
"(",
"\"{0}: prepare result: {1!r}\"",
".",
"format",
"(",
"self",
".",
"name",
",",
"ret",
")",
")",
"if",
"isinstance",
"(",
"ret",
",",
"HandlerReady",
")",
":",
"prepared",
"=",
"True",
"elif",
"isinstance",
"(",
"ret",
",",
"PrepareAgain",
")",
":",
"if",
"ret",
".",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"ret",
".",
"timeout",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unexpected result type from prepare()\"",
")",
"if",
"self",
".",
"io_handler",
".",
"is_readable",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"{0}: readable\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"fileno",
"=",
"self",
".",
"io_handler",
".",
"fileno",
"(",
")",
"if",
"fileno",
"is",
"not",
"None",
":",
"readable",
"=",
"wait_for_read",
"(",
"fileno",
",",
"interval",
")",
"if",
"readable",
":",
"self",
".",
"io_handler",
".",
"handle_read",
"(",
")",
"elif",
"not",
"prepared",
":",
"if",
"timeout",
":",
"time",
".",
"sleep",
"(",
"timeout",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"{0}: waiting for readability\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"not",
"self",
".",
"io_handler",
".",
"wait_for_readability",
"(",
")",
":",
"break"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
WrittingThread.run
|
The thread function.
Loop waiting for the handler and socket being writable and calling
`interfaces.IOHandler.handle_write`.
|
pyxmpp2/mainloop/threads.py
|
def run(self):
"""The thread function.
Loop waiting for the handler and socket being writable and calling
`interfaces.IOHandler.handle_write`.
"""
while not self._quit:
interval = self.settings["poll_interval"]
if self.io_handler.is_writable():
logger.debug("{0}: writable".format(self.name))
fileno = self.io_handler
if fileno:
writable = wait_for_write(fileno, interval)
if writable:
self.io_handler.handle_write()
else:
logger.debug("{0}: waiting for writaility".format(self.name))
if not self.io_handler.wait_for_writability():
break
|
def run(self):
"""The thread function.
Loop waiting for the handler and socket being writable and calling
`interfaces.IOHandler.handle_write`.
"""
while not self._quit:
interval = self.settings["poll_interval"]
if self.io_handler.is_writable():
logger.debug("{0}: writable".format(self.name))
fileno = self.io_handler
if fileno:
writable = wait_for_write(fileno, interval)
if writable:
self.io_handler.handle_write()
else:
logger.debug("{0}: waiting for writaility".format(self.name))
if not self.io_handler.wait_for_writability():
break
|
[
"The",
"thread",
"function",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L188-L206
|
[
"def",
"run",
"(",
"self",
")",
":",
"while",
"not",
"self",
".",
"_quit",
":",
"interval",
"=",
"self",
".",
"settings",
"[",
"\"poll_interval\"",
"]",
"if",
"self",
".",
"io_handler",
".",
"is_writable",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\"{0}: writable\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"fileno",
"=",
"self",
".",
"io_handler",
"if",
"fileno",
":",
"writable",
"=",
"wait_for_write",
"(",
"fileno",
",",
"interval",
")",
"if",
"writable",
":",
"self",
".",
"io_handler",
".",
"handle_write",
"(",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"{0}: waiting for writaility\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"not",
"self",
".",
"io_handler",
".",
"wait_for_writability",
"(",
")",
":",
"break"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
EventDispatcherThread.run
|
The thread function. Calls `self.run()` and if it raises
an exception, stores it in self.exc_info and exc_queue
|
pyxmpp2/mainloop/threads.py
|
def run(self):
"""The thread function. Calls `self.run()` and if it raises
an exception, stores it in self.exc_info and exc_queue
"""
logger.debug("{0}: entering thread".format(self.name))
while True:
try:
self.event_dispatcher.loop()
except Exception: # pylint: disable-msg=W0703
self.exc_info = sys.exc_info()
logger.debug(u"exception in the {0!r} thread:"
.format(self.name), exc_info = self.exc_info)
if self.exc_queue:
self.exc_queue.put( (self, self.exc_info) )
continue
else:
logger.debug("{0}: aborting thread".format(self.name))
return
except:
logger.debug("{0}: aborting thread".format(self.name))
return
break
logger.debug("{0}: exiting thread".format(self.name))
|
def run(self):
"""The thread function. Calls `self.run()` and if it raises
an exception, stores it in self.exc_info and exc_queue
"""
logger.debug("{0}: entering thread".format(self.name))
while True:
try:
self.event_dispatcher.loop()
except Exception: # pylint: disable-msg=W0703
self.exc_info = sys.exc_info()
logger.debug(u"exception in the {0!r} thread:"
.format(self.name), exc_info = self.exc_info)
if self.exc_queue:
self.exc_queue.put( (self, self.exc_info) )
continue
else:
logger.debug("{0}: aborting thread".format(self.name))
return
except:
logger.debug("{0}: aborting thread".format(self.name))
return
break
logger.debug("{0}: exiting thread".format(self.name))
|
[
"The",
"thread",
"function",
".",
"Calls",
"self",
".",
"run",
"()",
"and",
"if",
"it",
"raises",
"an",
"exception",
"stores",
"it",
"in",
"self",
".",
"exc_info",
"and",
"exc_queue"
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L247-L269
|
[
"def",
"run",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"{0}: entering thread\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"while",
"True",
":",
"try",
":",
"self",
".",
"event_dispatcher",
".",
"loop",
"(",
")",
"except",
"Exception",
":",
"# pylint: disable-msg=W0703",
"self",
".",
"exc_info",
"=",
"sys",
".",
"exc_info",
"(",
")",
"logger",
".",
"debug",
"(",
"u\"exception in the {0!r} thread:\"",
".",
"format",
"(",
"self",
".",
"name",
")",
",",
"exc_info",
"=",
"self",
".",
"exc_info",
")",
"if",
"self",
".",
"exc_queue",
":",
"self",
".",
"exc_queue",
".",
"put",
"(",
"(",
"self",
",",
"self",
".",
"exc_info",
")",
")",
"continue",
"else",
":",
"logger",
".",
"debug",
"(",
"\"{0}: aborting thread\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"return",
"except",
":",
"logger",
".",
"debug",
"(",
"\"{0}: aborting thread\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"return",
"break",
"logger",
".",
"debug",
"(",
"\"{0}: exiting thread\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TimeoutThread.run
|
The thread function.
|
pyxmpp2/mainloop/threads.py
|
def run(self):
"""The thread function."""
# pylint: disable-msg=W0212
timeout = self.method._pyxmpp_timeout
recurring = self.method._pyxmpp_recurring
while not self._quit and timeout is not None:
if timeout:
time.sleep(timeout)
if self._quit:
break
ret = self.method()
if recurring is None:
timeout = ret
elif not recurring:
break
|
def run(self):
"""The thread function."""
# pylint: disable-msg=W0212
timeout = self.method._pyxmpp_timeout
recurring = self.method._pyxmpp_recurring
while not self._quit and timeout is not None:
if timeout:
time.sleep(timeout)
if self._quit:
break
ret = self.method()
if recurring is None:
timeout = ret
elif not recurring:
break
|
[
"The",
"thread",
"function",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L341-L355
|
[
"def",
"run",
"(",
"self",
")",
":",
"# pylint: disable-msg=W0212",
"timeout",
"=",
"self",
".",
"method",
".",
"_pyxmpp_timeout",
"recurring",
"=",
"self",
".",
"method",
".",
"_pyxmpp_recurring",
"while",
"not",
"self",
".",
"_quit",
"and",
"timeout",
"is",
"not",
"None",
":",
"if",
"timeout",
":",
"time",
".",
"sleep",
"(",
"timeout",
")",
"if",
"self",
".",
"_quit",
":",
"break",
"ret",
"=",
"self",
".",
"method",
"(",
")",
"if",
"recurring",
"is",
"None",
":",
"timeout",
"=",
"ret",
"elif",
"not",
"recurring",
":",
"break"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadPool._run_io_threads
|
Start threads for an IOHandler.
|
pyxmpp2/mainloop/threads.py
|
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()
|
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()
|
[
"Start",
"threads",
"for",
"an",
"IOHandler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L398-L407
|
[
"def",
"_run_io_threads",
"(",
"self",
",",
"handler",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadPool._remove_io_handler
|
Remove an IOHandler from the pool.
|
pyxmpp2/mainloop/threads.py
|
def _remove_io_handler(self, handler):
"""Remove an IOHandler from the pool.
"""
if handler not in self.io_handlers:
return
self.io_handlers.remove(handler)
for thread in self.io_threads:
if thread.io_handler is handler:
thread.stop()
|
def _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()
|
[
"Remove",
"an",
"IOHandler",
"from",
"the",
"pool",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L409-L417
|
[
"def",
"_remove_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadPool._add_timeout_handler
|
Add a TimeoutHandler to the pool.
|
pyxmpp2/mainloop/threads.py
|
def _add_timeout_handler(self, handler):
"""Add a TimeoutHandler to the pool.
"""
self.timeout_handlers.append(handler)
if self.event_thread is None:
return
self._run_timeout_threads(handler)
|
def _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)
|
[
"Add",
"a",
"TimeoutHandler",
"to",
"the",
"pool",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L419-L425
|
[
"def",
"_add_timeout_handler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"timeout_handlers",
".",
"append",
"(",
"handler",
")",
"if",
"self",
".",
"event_thread",
"is",
"None",
":",
"return",
"self",
".",
"_run_timeout_threads",
"(",
"handler",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadPool._run_timeout_threads
|
Start threads for a TimeoutHandler.
|
pyxmpp2/mainloop/threads.py
|
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()
|
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()
|
[
"Start",
"threads",
"for",
"a",
"TimeoutHandler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L427-L437
|
[
"def",
"_run_timeout_threads",
"(",
"self",
",",
"handler",
")",
":",
"# 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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadPool._remove_timeout_handler
|
Remove a TimeoutHandler from the pool.
|
pyxmpp2/mainloop/threads.py
|
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()
|
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()
|
[
"Remove",
"a",
"TimeoutHandler",
"from",
"the",
"pool",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L439-L447
|
[
"def",
"_remove_timeout_handler",
"(",
"self",
",",
"handler",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadPool.start
|
Start the threads.
|
pyxmpp2/mainloop/threads.py
|
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)
|
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)
|
[
"Start",
"the",
"threads",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L449-L459
|
[
"def",
"start",
"(",
"self",
",",
"daemon",
"=",
"False",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadPool.stop
|
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`.
|
pyxmpp2/mainloop/threads.py
|
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
|
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
|
[
"Stop",
"the",
"threads",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L461-L502
|
[
"def",
"stop",
"(",
"self",
",",
"join",
"=",
"False",
",",
"timeout",
"=",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
ThreadPool.loop_iteration
|
Wait up to `timeout` seconds, raise any exception from the
threads.
|
pyxmpp2/mainloop/threads.py
|
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
|
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
|
[
"Wait",
"up",
"to",
"timeout",
"seconds",
"raise",
"any",
"exception",
"from",
"the",
"threads",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/threads.py#L527-L536
|
[
"def",
"loop_iteration",
"(",
"self",
",",
"timeout",
"=",
"0.1",
")",
":",
"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"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._reset
|
Reset the `LegacyClientStream` object state, making the object ready
to handle new connections.
|
pyxmpp2/ext/legacyauth.py
|
def _reset(self):
"""Reset the `LegacyClientStream` object state, making the object ready
to handle new connections."""
ClientStream._reset(self)
self.available_auth_methods = None
self.auth_stanza = None
self.registration_callback = None
|
def _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
|
[
"Reset",
"the",
"LegacyClientStream",
"object",
"state",
"making",
"the",
"object",
"ready",
"to",
"handle",
"new",
"connections",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L77-L83
|
[
"def",
"_reset",
"(",
"self",
")",
":",
"ClientStream",
".",
"_reset",
"(",
"self",
")",
"self",
".",
"available_auth_methods",
"=",
"None",
"self",
".",
"auth_stanza",
"=",
"None",
"self",
".",
"registration_callback",
"=",
"None"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._post_connect
|
Initialize authentication when the connection is established
and we are the initiator.
|
pyxmpp2/ext/legacyauth.py
|
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)
|
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)
|
[
"Initialize",
"authentication",
"when",
"the",
"connection",
"is",
"established",
"and",
"we",
"are",
"the",
"initiator",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L85-L100
|
[
"def",
"_post_connect",
"(",
"self",
")",
":",
"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",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._post_auth
|
Unregister legacy authentication handlers after successfull
authentication.
|
pyxmpp2/ext/legacyauth.py
|
def _post_auth(self):
"""Unregister legacy authentication handlers after successfull
authentication."""
ClientStream._post_auth(self)
if not self.initiator:
self.unset_iq_get_handler("query","jabber:iq:auth")
self.unset_iq_set_handler("query","jabber:iq:auth")
|
def _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")
|
[
"Unregister",
"legacy",
"authentication",
"handlers",
"after",
"successfull",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L102-L108
|
[
"def",
"_post_auth",
"(",
"self",
")",
":",
"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\"",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._try_auth
|
Try to authenticate using the first one of allowed authentication
methods left.
[client only]
|
pyxmpp2/ext/legacyauth.py
|
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()
|
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()
|
[
"Try",
"to",
"authenticate",
"using",
"the",
"first",
"one",
"of",
"allowed",
"authentication",
"methods",
"left",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L110-L141
|
[
"def",
"_try_auth",
"(",
"self",
")",
":",
"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",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.auth_in_stage1
|
Handle the first stage (<iq type='get'/>) of legacy ("plain" or
"digest") authentication.
[server only]
|
pyxmpp2/ext/legacyauth.py
|
def auth_in_stage1(self,stanza):
"""Handle the first stage (<iq type='get'/>) of legacy ("plain" or
"digest") authentication.
[server only]"""
self.lock.acquire()
try:
if "plain" not in self.auth_methods and "digest" not in self.auth_methods:
iq=stanza.make_error_response("not-allowed")
self.send(iq)
return
iq=stanza.make_result_response()
q=iq.new_query("jabber:iq:auth")
q.newChild(None,"username",None)
q.newChild(None,"resource",None)
if "plain" in self.auth_methods:
q.newChild(None,"password",None)
if "digest" in self.auth_methods:
q.newChild(None,"digest",None)
self.send(iq)
iq.free()
finally:
self.lock.release()
|
def auth_in_stage1(self,stanza):
"""Handle the first stage (<iq type='get'/>) of legacy ("plain" or
"digest") authentication.
[server only]"""
self.lock.acquire()
try:
if "plain" not in self.auth_methods and "digest" not in self.auth_methods:
iq=stanza.make_error_response("not-allowed")
self.send(iq)
return
iq=stanza.make_result_response()
q=iq.new_query("jabber:iq:auth")
q.newChild(None,"username",None)
q.newChild(None,"resource",None)
if "plain" in self.auth_methods:
q.newChild(None,"password",None)
if "digest" in self.auth_methods:
q.newChild(None,"digest",None)
self.send(iq)
iq.free()
finally:
self.lock.release()
|
[
"Handle",
"the",
"first",
"stage",
"(",
"<iq",
"type",
"=",
"get",
"/",
">",
")",
"of",
"legacy",
"(",
"plain",
"or",
"digest",
")",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L143-L166
|
[
"def",
"auth_in_stage1",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"\"plain\"",
"not",
"in",
"self",
".",
"auth_methods",
"and",
"\"digest\"",
"not",
"in",
"self",
".",
"auth_methods",
":",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"not-allowed\"",
")",
"self",
".",
"send",
"(",
"iq",
")",
"return",
"iq",
"=",
"stanza",
".",
"make_result_response",
"(",
")",
"q",
"=",
"iq",
".",
"new_query",
"(",
"\"jabber:iq:auth\"",
")",
"q",
".",
"newChild",
"(",
"None",
",",
"\"username\"",
",",
"None",
")",
"q",
".",
"newChild",
"(",
"None",
",",
"\"resource\"",
",",
"None",
")",
"if",
"\"plain\"",
"in",
"self",
".",
"auth_methods",
":",
"q",
".",
"newChild",
"(",
"None",
",",
"\"password\"",
",",
"None",
")",
"if",
"\"digest\"",
"in",
"self",
".",
"auth_methods",
":",
"q",
".",
"newChild",
"(",
"None",
",",
"\"digest\"",
",",
"None",
")",
"self",
".",
"send",
"(",
"iq",
")",
"iq",
".",
"free",
"(",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.auth_in_stage2
|
Handle the second stage (<iq type='set'/>) of legacy ("plain" or
"digest") authentication.
[server only]
|
pyxmpp2/ext/legacyauth.py
|
def auth_in_stage2(self,stanza):
"""Handle the second stage (<iq type='set'/>) of legacy ("plain" or
"digest") authentication.
[server only]"""
self.lock.acquire()
try:
if "plain" not in self.auth_methods and "digest" not in self.auth_methods:
iq=stanza.make_error_response("not-allowed")
self.send(iq)
return
username=stanza.xpath_eval("a:query/a:username",{"a":"jabber:iq:auth"})
if username:
username=from_utf8(username[0].getContent())
resource=stanza.xpath_eval("a:query/a:resource",{"a":"jabber:iq:auth"})
if resource:
resource=from_utf8(resource[0].getContent())
if not username or not resource:
self.__logger.debug("No username or resource found in auth request")
iq=stanza.make_error_response("bad-request")
self.send(iq)
return
if stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"}):
if "plain" not in self.auth_methods:
iq=stanza.make_error_response("not-allowed")
self.send(iq)
return
else:
return self._plain_auth_in_stage2(username,resource,stanza)
if stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}):
if "plain" not in self.auth_methods:
iq=stanza.make_error_response("not-allowed")
self.send(iq)
return
else:
return self._digest_auth_in_stage2(username,resource,stanza)
finally:
self.lock.release()
|
def auth_in_stage2(self,stanza):
"""Handle the second stage (<iq type='set'/>) of legacy ("plain" or
"digest") authentication.
[server only]"""
self.lock.acquire()
try:
if "plain" not in self.auth_methods and "digest" not in self.auth_methods:
iq=stanza.make_error_response("not-allowed")
self.send(iq)
return
username=stanza.xpath_eval("a:query/a:username",{"a":"jabber:iq:auth"})
if username:
username=from_utf8(username[0].getContent())
resource=stanza.xpath_eval("a:query/a:resource",{"a":"jabber:iq:auth"})
if resource:
resource=from_utf8(resource[0].getContent())
if not username or not resource:
self.__logger.debug("No username or resource found in auth request")
iq=stanza.make_error_response("bad-request")
self.send(iq)
return
if stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"}):
if "plain" not in self.auth_methods:
iq=stanza.make_error_response("not-allowed")
self.send(iq)
return
else:
return self._plain_auth_in_stage2(username,resource,stanza)
if stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}):
if "plain" not in self.auth_methods:
iq=stanza.make_error_response("not-allowed")
self.send(iq)
return
else:
return self._digest_auth_in_stage2(username,resource,stanza)
finally:
self.lock.release()
|
[
"Handle",
"the",
"second",
"stage",
"(",
"<iq",
"type",
"=",
"set",
"/",
">",
")",
"of",
"legacy",
"(",
"plain",
"or",
"digest",
")",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L168-L207
|
[
"def",
"auth_in_stage2",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"\"plain\"",
"not",
"in",
"self",
".",
"auth_methods",
"and",
"\"digest\"",
"not",
"in",
"self",
".",
"auth_methods",
":",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"not-allowed\"",
")",
"self",
".",
"send",
"(",
"iq",
")",
"return",
"username",
"=",
"stanza",
".",
"xpath_eval",
"(",
"\"a:query/a:username\"",
",",
"{",
"\"a\"",
":",
"\"jabber:iq:auth\"",
"}",
")",
"if",
"username",
":",
"username",
"=",
"from_utf8",
"(",
"username",
"[",
"0",
"]",
".",
"getContent",
"(",
")",
")",
"resource",
"=",
"stanza",
".",
"xpath_eval",
"(",
"\"a:query/a:resource\"",
",",
"{",
"\"a\"",
":",
"\"jabber:iq:auth\"",
"}",
")",
"if",
"resource",
":",
"resource",
"=",
"from_utf8",
"(",
"resource",
"[",
"0",
"]",
".",
"getContent",
"(",
")",
")",
"if",
"not",
"username",
"or",
"not",
"resource",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"No username or resource found in auth request\"",
")",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"bad-request\"",
")",
"self",
".",
"send",
"(",
"iq",
")",
"return",
"if",
"stanza",
".",
"xpath_eval",
"(",
"\"a:query/a:password\"",
",",
"{",
"\"a\"",
":",
"\"jabber:iq:auth\"",
"}",
")",
":",
"if",
"\"plain\"",
"not",
"in",
"self",
".",
"auth_methods",
":",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"not-allowed\"",
")",
"self",
".",
"send",
"(",
"iq",
")",
"return",
"else",
":",
"return",
"self",
".",
"_plain_auth_in_stage2",
"(",
"username",
",",
"resource",
",",
"stanza",
")",
"if",
"stanza",
".",
"xpath_eval",
"(",
"\"a:query/a:digest\"",
",",
"{",
"\"a\"",
":",
"\"jabber:iq:auth\"",
"}",
")",
":",
"if",
"\"plain\"",
"not",
"in",
"self",
".",
"auth_methods",
":",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"not-allowed\"",
")",
"self",
".",
"send",
"(",
"iq",
")",
"return",
"else",
":",
"return",
"self",
".",
"_digest_auth_in_stage2",
"(",
"username",
",",
"resource",
",",
"stanza",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._auth_stage1
|
Do the first stage (<iq type='get'/>) of legacy ("plain" or
"digest") authentication.
[client only]
|
pyxmpp2/ext/legacyauth.py
|
def _auth_stage1(self):
"""Do the first stage (<iq type='get'/>) of legacy ("plain" or
"digest") authentication.
[client only]"""
iq=Iq(stanza_type="get")
q=iq.new_query("jabber:iq:auth")
q.newTextChild(None,"username",to_utf8(self.my_jid.node))
q.newTextChild(None,"resource",to_utf8(self.my_jid.resource))
self.send(iq)
self.set_response_handlers(iq,self.auth_stage2,self.auth_error,
self.auth_timeout,timeout=60)
iq.free()
|
def _auth_stage1(self):
"""Do the first stage (<iq type='get'/>) of legacy ("plain" or
"digest") authentication.
[client only]"""
iq=Iq(stanza_type="get")
q=iq.new_query("jabber:iq:auth")
q.newTextChild(None,"username",to_utf8(self.my_jid.node))
q.newTextChild(None,"resource",to_utf8(self.my_jid.resource))
self.send(iq)
self.set_response_handlers(iq,self.auth_stage2,self.auth_error,
self.auth_timeout,timeout=60)
iq.free()
|
[
"Do",
"the",
"first",
"stage",
"(",
"<iq",
"type",
"=",
"get",
"/",
">",
")",
"of",
"legacy",
"(",
"plain",
"or",
"digest",
")",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L209-L221
|
[
"def",
"_auth_stage1",
"(",
"self",
")",
":",
"iq",
"=",
"Iq",
"(",
"stanza_type",
"=",
"\"get\"",
")",
"q",
"=",
"iq",
".",
"new_query",
"(",
"\"jabber:iq:auth\"",
")",
"q",
".",
"newTextChild",
"(",
"None",
",",
"\"username\"",
",",
"to_utf8",
"(",
"self",
".",
"my_jid",
".",
"node",
")",
")",
"q",
".",
"newTextChild",
"(",
"None",
",",
"\"resource\"",
",",
"to_utf8",
"(",
"self",
".",
"my_jid",
".",
"resource",
")",
")",
"self",
".",
"send",
"(",
"iq",
")",
"self",
".",
"set_response_handlers",
"(",
"iq",
",",
"self",
".",
"auth_stage2",
",",
"self",
".",
"auth_error",
",",
"self",
".",
"auth_timeout",
",",
"timeout",
"=",
"60",
")",
"iq",
".",
"free",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.auth_timeout
|
Handle legacy authentication timeout.
[client only]
|
pyxmpp2/ext/legacyauth.py
|
def auth_timeout(self):
"""Handle legacy authentication timeout.
[client only]"""
self.lock.acquire()
try:
self.__logger.debug("Timeout while waiting for jabber:iq:auth result")
if self._auth_methods_left:
self._auth_methods_left.pop(0)
finally:
self.lock.release()
|
def auth_timeout(self):
"""Handle legacy authentication timeout.
[client only]"""
self.lock.acquire()
try:
self.__logger.debug("Timeout while waiting for jabber:iq:auth result")
if self._auth_methods_left:
self._auth_methods_left.pop(0)
finally:
self.lock.release()
|
[
"Handle",
"legacy",
"authentication",
"timeout",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L223-L233
|
[
"def",
"auth_timeout",
"(",
"self",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"Timeout while waiting for jabber:iq:auth result\"",
")",
"if",
"self",
".",
"_auth_methods_left",
":",
"self",
".",
"_auth_methods_left",
".",
"pop",
"(",
"0",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.auth_error
|
Handle legacy authentication error.
[client only]
|
pyxmpp2/ext/legacyauth.py
|
def auth_error(self,stanza):
"""Handle legacy authentication error.
[client only]"""
self.lock.acquire()
try:
err=stanza.get_error()
ae=err.xpath_eval("e:*",{"e":"jabber:iq:auth:error"})
if ae:
ae=ae[0].name
else:
ae=err.get_condition().name
raise LegacyAuthenticationError("Authentication error condition: %s"
% (ae,))
finally:
self.lock.release()
|
def auth_error(self,stanza):
"""Handle legacy authentication error.
[client only]"""
self.lock.acquire()
try:
err=stanza.get_error()
ae=err.xpath_eval("e:*",{"e":"jabber:iq:auth:error"})
if ae:
ae=ae[0].name
else:
ae=err.get_condition().name
raise LegacyAuthenticationError("Authentication error condition: %s"
% (ae,))
finally:
self.lock.release()
|
[
"Handle",
"legacy",
"authentication",
"error",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L235-L250
|
[
"def",
"auth_error",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"err",
"=",
"stanza",
".",
"get_error",
"(",
")",
"ae",
"=",
"err",
".",
"xpath_eval",
"(",
"\"e:*\"",
",",
"{",
"\"e\"",
":",
"\"jabber:iq:auth:error\"",
"}",
")",
"if",
"ae",
":",
"ae",
"=",
"ae",
"[",
"0",
"]",
".",
"name",
"else",
":",
"ae",
"=",
"err",
".",
"get_condition",
"(",
")",
".",
"name",
"raise",
"LegacyAuthenticationError",
"(",
"\"Authentication error condition: %s\"",
"%",
"(",
"ae",
",",
")",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.auth_stage2
|
Handle the first stage authentication response (result of the <iq
type="get"/>).
[client only]
|
pyxmpp2/ext/legacyauth.py
|
def auth_stage2(self,stanza):
"""Handle the first stage authentication response (result of the <iq
type="get"/>).
[client only]"""
self.lock.acquire()
try:
self.__logger.debug("Procesing auth response...")
self.available_auth_methods=[]
if (stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}) and self.stream_id):
self.available_auth_methods.append("digest")
if (stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"})):
self.available_auth_methods.append("plain")
self.auth_stanza=stanza.copy()
self._try_auth()
finally:
self.lock.release()
|
def auth_stage2(self,stanza):
"""Handle the first stage authentication response (result of the <iq
type="get"/>).
[client only]"""
self.lock.acquire()
try:
self.__logger.debug("Procesing auth response...")
self.available_auth_methods=[]
if (stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"}) and self.stream_id):
self.available_auth_methods.append("digest")
if (stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"})):
self.available_auth_methods.append("plain")
self.auth_stanza=stanza.copy()
self._try_auth()
finally:
self.lock.release()
|
[
"Handle",
"the",
"first",
"stage",
"authentication",
"response",
"(",
"result",
"of",
"the",
"<iq",
"type",
"=",
"get",
"/",
">",
")",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L252-L268
|
[
"def",
"auth_stage2",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"Procesing auth response...\"",
")",
"self",
".",
"available_auth_methods",
"=",
"[",
"]",
"if",
"(",
"stanza",
".",
"xpath_eval",
"(",
"\"a:query/a:digest\"",
",",
"{",
"\"a\"",
":",
"\"jabber:iq:auth\"",
"}",
")",
"and",
"self",
".",
"stream_id",
")",
":",
"self",
".",
"available_auth_methods",
".",
"append",
"(",
"\"digest\"",
")",
"if",
"(",
"stanza",
".",
"xpath_eval",
"(",
"\"a:query/a:password\"",
",",
"{",
"\"a\"",
":",
"\"jabber:iq:auth\"",
"}",
")",
")",
":",
"self",
".",
"available_auth_methods",
".",
"append",
"(",
"\"plain\"",
")",
"self",
".",
"auth_stanza",
"=",
"stanza",
".",
"copy",
"(",
")",
"self",
".",
"_try_auth",
"(",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._plain_auth_stage2
|
Do the second stage (<iq type='set'/>) of legacy "plain"
authentication.
[client only]
|
pyxmpp2/ext/legacyauth.py
|
def _plain_auth_stage2(self, _unused):
"""Do the second stage (<iq type='set'/>) of legacy "plain"
authentication.
[client only]"""
iq=Iq(stanza_type="set")
q=iq.new_query("jabber:iq:auth")
q.newTextChild(None,"username",to_utf8(self.my_jid.node))
q.newTextChild(None,"resource",to_utf8(self.my_jid.resource))
q.newTextChild(None,"password",to_utf8(self.password))
self.send(iq)
self.set_response_handlers(iq,self.auth_finish,self.auth_error)
iq.free()
|
def _plain_auth_stage2(self, _unused):
"""Do the second stage (<iq type='set'/>) of legacy "plain"
authentication.
[client only]"""
iq=Iq(stanza_type="set")
q=iq.new_query("jabber:iq:auth")
q.newTextChild(None,"username",to_utf8(self.my_jid.node))
q.newTextChild(None,"resource",to_utf8(self.my_jid.resource))
q.newTextChild(None,"password",to_utf8(self.password))
self.send(iq)
self.set_response_handlers(iq,self.auth_finish,self.auth_error)
iq.free()
|
[
"Do",
"the",
"second",
"stage",
"(",
"<iq",
"type",
"=",
"set",
"/",
">",
")",
"of",
"legacy",
"plain",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L270-L282
|
[
"def",
"_plain_auth_stage2",
"(",
"self",
",",
"_unused",
")",
":",
"iq",
"=",
"Iq",
"(",
"stanza_type",
"=",
"\"set\"",
")",
"q",
"=",
"iq",
".",
"new_query",
"(",
"\"jabber:iq:auth\"",
")",
"q",
".",
"newTextChild",
"(",
"None",
",",
"\"username\"",
",",
"to_utf8",
"(",
"self",
".",
"my_jid",
".",
"node",
")",
")",
"q",
".",
"newTextChild",
"(",
"None",
",",
"\"resource\"",
",",
"to_utf8",
"(",
"self",
".",
"my_jid",
".",
"resource",
")",
")",
"q",
".",
"newTextChild",
"(",
"None",
",",
"\"password\"",
",",
"to_utf8",
"(",
"self",
".",
"password",
")",
")",
"self",
".",
"send",
"(",
"iq",
")",
"self",
".",
"set_response_handlers",
"(",
"iq",
",",
"self",
".",
"auth_finish",
",",
"self",
".",
"auth_error",
")",
"iq",
".",
"free",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._plain_auth_in_stage2
|
Handle the second stage (<iq type='set'/>) of legacy "plain"
authentication.
[server only]
|
pyxmpp2/ext/legacyauth.py
|
def _plain_auth_in_stage2(self, username, _unused, stanza):
"""Handle the second stage (<iq type='set'/>) of legacy "plain"
authentication.
[server only]"""
password=stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"})
if password:
password=from_utf8(password[0].getContent())
if not password:
self.__logger.debug("No password found in plain auth request")
iq=stanza.make_error_response("bad-request")
self.send(iq)
return
if self.check_password(username,password):
iq=stanza.make_result_response()
self.send(iq)
self.peer_authenticated=True
self.auth_method_used="plain"
self.state_change("authorized",self.peer)
self._post_auth()
else:
self.__logger.debug("Plain auth failed")
iq=stanza.make_error_response("bad-request")
e=iq.get_error()
e.add_custom_condition('jabber:iq:auth:error',"user-unauthorized")
self.send(iq)
|
def _plain_auth_in_stage2(self, username, _unused, stanza):
"""Handle the second stage (<iq type='set'/>) of legacy "plain"
authentication.
[server only]"""
password=stanza.xpath_eval("a:query/a:password",{"a":"jabber:iq:auth"})
if password:
password=from_utf8(password[0].getContent())
if not password:
self.__logger.debug("No password found in plain auth request")
iq=stanza.make_error_response("bad-request")
self.send(iq)
return
if self.check_password(username,password):
iq=stanza.make_result_response()
self.send(iq)
self.peer_authenticated=True
self.auth_method_used="plain"
self.state_change("authorized",self.peer)
self._post_auth()
else:
self.__logger.debug("Plain auth failed")
iq=stanza.make_error_response("bad-request")
e=iq.get_error()
e.add_custom_condition('jabber:iq:auth:error',"user-unauthorized")
self.send(iq)
|
[
"Handle",
"the",
"second",
"stage",
"(",
"<iq",
"type",
"=",
"set",
"/",
">",
")",
"of",
"legacy",
"plain",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L284-L310
|
[
"def",
"_plain_auth_in_stage2",
"(",
"self",
",",
"username",
",",
"_unused",
",",
"stanza",
")",
":",
"password",
"=",
"stanza",
".",
"xpath_eval",
"(",
"\"a:query/a:password\"",
",",
"{",
"\"a\"",
":",
"\"jabber:iq:auth\"",
"}",
")",
"if",
"password",
":",
"password",
"=",
"from_utf8",
"(",
"password",
"[",
"0",
"]",
".",
"getContent",
"(",
")",
")",
"if",
"not",
"password",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"No password found in plain auth request\"",
")",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"bad-request\"",
")",
"self",
".",
"send",
"(",
"iq",
")",
"return",
"if",
"self",
".",
"check_password",
"(",
"username",
",",
"password",
")",
":",
"iq",
"=",
"stanza",
".",
"make_result_response",
"(",
")",
"self",
".",
"send",
"(",
"iq",
")",
"self",
".",
"peer_authenticated",
"=",
"True",
"self",
".",
"auth_method_used",
"=",
"\"plain\"",
"self",
".",
"state_change",
"(",
"\"authorized\"",
",",
"self",
".",
"peer",
")",
"self",
".",
"_post_auth",
"(",
")",
"else",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"Plain auth failed\"",
")",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"bad-request\"",
")",
"e",
"=",
"iq",
".",
"get_error",
"(",
")",
"e",
".",
"add_custom_condition",
"(",
"'jabber:iq:auth:error'",
",",
"\"user-unauthorized\"",
")",
"self",
".",
"send",
"(",
"iq",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._digest_auth_stage2
|
Do the second stage (<iq type='set'/>) of legacy "digest"
authentication.
[client only]
|
pyxmpp2/ext/legacyauth.py
|
def _digest_auth_stage2(self, _unused):
"""Do the second stage (<iq type='set'/>) of legacy "digest"
authentication.
[client only]"""
iq=Iq(stanza_type="set")
q=iq.new_query("jabber:iq:auth")
q.newTextChild(None,"username",to_utf8(self.my_jid.node))
q.newTextChild(None,"resource",to_utf8(self.my_jid.resource))
digest = hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.password)).hexdigest()
q.newTextChild(None,"digest",digest)
self.send(iq)
self.set_response_handlers(iq,self.auth_finish,self.auth_error)
iq.free()
|
def _digest_auth_stage2(self, _unused):
"""Do the second stage (<iq type='set'/>) of legacy "digest"
authentication.
[client only]"""
iq=Iq(stanza_type="set")
q=iq.new_query("jabber:iq:auth")
q.newTextChild(None,"username",to_utf8(self.my_jid.node))
q.newTextChild(None,"resource",to_utf8(self.my_jid.resource))
digest = hashlib.sha1(to_utf8(self.stream_id)+to_utf8(self.password)).hexdigest()
q.newTextChild(None,"digest",digest)
self.send(iq)
self.set_response_handlers(iq,self.auth_finish,self.auth_error)
iq.free()
|
[
"Do",
"the",
"second",
"stage",
"(",
"<iq",
"type",
"=",
"set",
"/",
">",
")",
"of",
"legacy",
"digest",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L312-L327
|
[
"def",
"_digest_auth_stage2",
"(",
"self",
",",
"_unused",
")",
":",
"iq",
"=",
"Iq",
"(",
"stanza_type",
"=",
"\"set\"",
")",
"q",
"=",
"iq",
".",
"new_query",
"(",
"\"jabber:iq:auth\"",
")",
"q",
".",
"newTextChild",
"(",
"None",
",",
"\"username\"",
",",
"to_utf8",
"(",
"self",
".",
"my_jid",
".",
"node",
")",
")",
"q",
".",
"newTextChild",
"(",
"None",
",",
"\"resource\"",
",",
"to_utf8",
"(",
"self",
".",
"my_jid",
".",
"resource",
")",
")",
"digest",
"=",
"hashlib",
".",
"sha1",
"(",
"to_utf8",
"(",
"self",
".",
"stream_id",
")",
"+",
"to_utf8",
"(",
"self",
".",
"password",
")",
")",
".",
"hexdigest",
"(",
")",
"q",
".",
"newTextChild",
"(",
"None",
",",
"\"digest\"",
",",
"digest",
")",
"self",
".",
"send",
"(",
"iq",
")",
"self",
".",
"set_response_handlers",
"(",
"iq",
",",
"self",
".",
"auth_finish",
",",
"self",
".",
"auth_error",
")",
"iq",
".",
"free",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream._digest_auth_in_stage2
|
Handle the second stage (<iq type='set'/>) of legacy "digest"
authentication.
[server only]
|
pyxmpp2/ext/legacyauth.py
|
def _digest_auth_in_stage2(self, username, _unused, stanza):
"""Handle the second stage (<iq type='set'/>) of legacy "digest"
authentication.
[server only]"""
digest=stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"})
if digest:
digest=digest[0].getContent()
if not digest:
self.__logger.debug("No digest found in digest auth request")
iq=stanza.make_error_response("bad-request")
self.send(iq)
return
password,pwformat=self.get_password(username)
if not password or pwformat!="plain":
iq=stanza.make_error_response("bad-request")
e=iq.get_error()
e.add_custom_condition('jabber:iq:auth:error',"user-unauthorized")
self.send(iq)
return
mydigest = hashlib.sha1(to_utf8(self.stream_id)+to_utf8(password)).hexdigest()
if mydigest==digest:
iq=stanza.make_result_response()
self.send(iq)
self.peer_authenticated=True
self.auth_method_used="digest"
self.state_change("authorized",self.peer)
self._post_auth()
else:
self.__logger.debug("Digest auth failed: %r != %r" % (digest,mydigest))
iq=stanza.make_error_response("bad-request")
e=iq.get_error()
e.add_custom_condition('jabber:iq:auth:error',"user-unauthorized")
self.send(iq)
|
def _digest_auth_in_stage2(self, username, _unused, stanza):
"""Handle the second stage (<iq type='set'/>) of legacy "digest"
authentication.
[server only]"""
digest=stanza.xpath_eval("a:query/a:digest",{"a":"jabber:iq:auth"})
if digest:
digest=digest[0].getContent()
if not digest:
self.__logger.debug("No digest found in digest auth request")
iq=stanza.make_error_response("bad-request")
self.send(iq)
return
password,pwformat=self.get_password(username)
if not password or pwformat!="plain":
iq=stanza.make_error_response("bad-request")
e=iq.get_error()
e.add_custom_condition('jabber:iq:auth:error',"user-unauthorized")
self.send(iq)
return
mydigest = hashlib.sha1(to_utf8(self.stream_id)+to_utf8(password)).hexdigest()
if mydigest==digest:
iq=stanza.make_result_response()
self.send(iq)
self.peer_authenticated=True
self.auth_method_used="digest"
self.state_change("authorized",self.peer)
self._post_auth()
else:
self.__logger.debug("Digest auth failed: %r != %r" % (digest,mydigest))
iq=stanza.make_error_response("bad-request")
e=iq.get_error()
e.add_custom_condition('jabber:iq:auth:error',"user-unauthorized")
self.send(iq)
|
[
"Handle",
"the",
"second",
"stage",
"(",
"<iq",
"type",
"=",
"set",
"/",
">",
")",
"of",
"legacy",
"digest",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L329-L365
|
[
"def",
"_digest_auth_in_stage2",
"(",
"self",
",",
"username",
",",
"_unused",
",",
"stanza",
")",
":",
"digest",
"=",
"stanza",
".",
"xpath_eval",
"(",
"\"a:query/a:digest\"",
",",
"{",
"\"a\"",
":",
"\"jabber:iq:auth\"",
"}",
")",
"if",
"digest",
":",
"digest",
"=",
"digest",
"[",
"0",
"]",
".",
"getContent",
"(",
")",
"if",
"not",
"digest",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"No digest found in digest auth request\"",
")",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"bad-request\"",
")",
"self",
".",
"send",
"(",
"iq",
")",
"return",
"password",
",",
"pwformat",
"=",
"self",
".",
"get_password",
"(",
"username",
")",
"if",
"not",
"password",
"or",
"pwformat",
"!=",
"\"plain\"",
":",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"bad-request\"",
")",
"e",
"=",
"iq",
".",
"get_error",
"(",
")",
"e",
".",
"add_custom_condition",
"(",
"'jabber:iq:auth:error'",
",",
"\"user-unauthorized\"",
")",
"self",
".",
"send",
"(",
"iq",
")",
"return",
"mydigest",
"=",
"hashlib",
".",
"sha1",
"(",
"to_utf8",
"(",
"self",
".",
"stream_id",
")",
"+",
"to_utf8",
"(",
"password",
")",
")",
".",
"hexdigest",
"(",
")",
"if",
"mydigest",
"==",
"digest",
":",
"iq",
"=",
"stanza",
".",
"make_result_response",
"(",
")",
"self",
".",
"send",
"(",
"iq",
")",
"self",
".",
"peer_authenticated",
"=",
"True",
"self",
".",
"auth_method_used",
"=",
"\"digest\"",
"self",
".",
"state_change",
"(",
"\"authorized\"",
",",
"self",
".",
"peer",
")",
"self",
".",
"_post_auth",
"(",
")",
"else",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"Digest auth failed: %r != %r\"",
"%",
"(",
"digest",
",",
"mydigest",
")",
")",
"iq",
"=",
"stanza",
".",
"make_error_response",
"(",
"\"bad-request\"",
")",
"e",
"=",
"iq",
".",
"get_error",
"(",
")",
"e",
".",
"add_custom_condition",
"(",
"'jabber:iq:auth:error'",
",",
"\"user-unauthorized\"",
")",
"self",
".",
"send",
"(",
"iq",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.auth_finish
|
Handle success of the legacy authentication.
|
pyxmpp2/ext/legacyauth.py
|
def auth_finish(self, _unused):
"""Handle success of the legacy authentication."""
self.lock.acquire()
try:
self.__logger.debug("Authenticated")
self.authenticated=True
self.state_change("authorized",self.my_jid)
self._post_auth()
finally:
self.lock.release()
|
def auth_finish(self, _unused):
"""Handle success of the legacy authentication."""
self.lock.acquire()
try:
self.__logger.debug("Authenticated")
self.authenticated=True
self.state_change("authorized",self.my_jid)
self._post_auth()
finally:
self.lock.release()
|
[
"Handle",
"success",
"of",
"the",
"legacy",
"authentication",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L367-L376
|
[
"def",
"auth_finish",
"(",
"self",
",",
"_unused",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"__logger",
".",
"debug",
"(",
"\"Authenticated\"",
")",
"self",
".",
"authenticated",
"=",
"True",
"self",
".",
"state_change",
"(",
"\"authorized\"",
",",
"self",
".",
"my_jid",
")",
"self",
".",
"_post_auth",
"(",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.registration_error
|
Handle in-band registration error.
[client only]
:Parameters:
- `stanza`: the error stanza received or `None` on timeout.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`
|
pyxmpp2/ext/legacyauth.py
|
def registration_error(self, stanza):
"""Handle in-band registration error.
[client only]
:Parameters:
- `stanza`: the error stanza received or `None` on timeout.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
self.lock.acquire()
try:
err=stanza.get_error()
ae=err.xpath_eval("e:*",{"e":"jabber:iq:auth:error"})
if ae:
ae=ae[0].name
else:
ae=err.get_condition().name
raise RegistrationError("Authentication error condition: %s" % (ae,))
finally:
self.lock.release()
|
def registration_error(self, stanza):
"""Handle in-band registration error.
[client only]
:Parameters:
- `stanza`: the error stanza received or `None` on timeout.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
self.lock.acquire()
try:
err=stanza.get_error()
ae=err.xpath_eval("e:*",{"e":"jabber:iq:auth:error"})
if ae:
ae=ae[0].name
else:
ae=err.get_condition().name
raise RegistrationError("Authentication error condition: %s" % (ae,))
finally:
self.lock.release()
|
[
"Handle",
"in",
"-",
"band",
"registration",
"error",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L378-L397
|
[
"def",
"registration_error",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"err",
"=",
"stanza",
".",
"get_error",
"(",
")",
"ae",
"=",
"err",
".",
"xpath_eval",
"(",
"\"e:*\"",
",",
"{",
"\"e\"",
":",
"\"jabber:iq:auth:error\"",
"}",
")",
"if",
"ae",
":",
"ae",
"=",
"ae",
"[",
"0",
"]",
".",
"name",
"else",
":",
"ae",
"=",
"err",
".",
"get_condition",
"(",
")",
".",
"name",
"raise",
"RegistrationError",
"(",
"\"Authentication error condition: %s\"",
"%",
"(",
"ae",
",",
")",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.registration_form_received
|
Handle registration form received.
[client only]
Call self.registration_callback with the registration form received
as the argument. Use the value returned by the callback will be a
filled-in form.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.iq.Iq`
|
pyxmpp2/ext/legacyauth.py
|
def registration_form_received(self, stanza):
"""Handle registration form received.
[client only]
Call self.registration_callback with the registration form received
as the argument. Use the value returned by the callback will be a
filled-in form.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.iq.Iq`"""
self.lock.acquire()
try:
self.__register = Register(stanza.get_query())
self.registration_callback(stanza, self.__register.get_form())
finally:
self.lock.release()
|
def registration_form_received(self, stanza):
"""Handle registration form received.
[client only]
Call self.registration_callback with the registration form received
as the argument. Use the value returned by the callback will be a
filled-in form.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.iq.Iq`"""
self.lock.acquire()
try:
self.__register = Register(stanza.get_query())
self.registration_callback(stanza, self.__register.get_form())
finally:
self.lock.release()
|
[
"Handle",
"registration",
"form",
"received",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L399-L417
|
[
"def",
"registration_form_received",
"(",
"self",
",",
"stanza",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"__register",
"=",
"Register",
"(",
"stanza",
".",
"get_query",
"(",
")",
")",
"self",
".",
"registration_callback",
"(",
"stanza",
",",
"self",
".",
"__register",
".",
"get_form",
"(",
")",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.submit_registration_form
|
Submit a registration form.
[client only]
:Parameters:
- `form`: the filled-in form. When form is `None` or its type is
"cancel" the registration is to be canceled.
:Types:
- `form`: `pyxmpp.jabber.dataforms.Form`
|
pyxmpp2/ext/legacyauth.py
|
def submit_registration_form(self, form):
"""Submit a registration form.
[client only]
:Parameters:
- `form`: the filled-in form. When form is `None` or its type is
"cancel" the registration is to be canceled.
:Types:
- `form`: `pyxmpp.jabber.dataforms.Form`"""
self.lock.acquire()
try:
if form and form.type!="cancel":
self.registration_form = form
iq = Iq(stanza_type = "set")
iq.set_content(self.__register.submit_form(form))
self.set_response_handlers(iq, self.registration_success, self.registration_error)
self.send(iq)
else:
self.__register = None
finally:
self.lock.release()
|
def submit_registration_form(self, form):
"""Submit a registration form.
[client only]
:Parameters:
- `form`: the filled-in form. When form is `None` or its type is
"cancel" the registration is to be canceled.
:Types:
- `form`: `pyxmpp.jabber.dataforms.Form`"""
self.lock.acquire()
try:
if form and form.type!="cancel":
self.registration_form = form
iq = Iq(stanza_type = "set")
iq.set_content(self.__register.submit_form(form))
self.set_response_handlers(iq, self.registration_success, self.registration_error)
self.send(iq)
else:
self.__register = None
finally:
self.lock.release()
|
[
"Submit",
"a",
"registration",
"form",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L419-L441
|
[
"def",
"submit_registration_form",
"(",
"self",
",",
"form",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"form",
"and",
"form",
".",
"type",
"!=",
"\"cancel\"",
":",
"self",
".",
"registration_form",
"=",
"form",
"iq",
"=",
"Iq",
"(",
"stanza_type",
"=",
"\"set\"",
")",
"iq",
".",
"set_content",
"(",
"self",
".",
"__register",
".",
"submit_form",
"(",
"form",
")",
")",
"self",
".",
"set_response_handlers",
"(",
"iq",
",",
"self",
".",
"registration_success",
",",
"self",
".",
"registration_error",
")",
"self",
".",
"send",
"(",
"iq",
")",
"else",
":",
"self",
".",
"__register",
"=",
"None",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
LegacyClientStream.registration_success
|
Handle registration success.
[client only]
Clean up registration stuff, change state to "registered" and initialize
authentication.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.iq.Iq`
|
pyxmpp2/ext/legacyauth.py
|
def registration_success(self, stanza):
"""Handle registration success.
[client only]
Clean up registration stuff, change state to "registered" and initialize
authentication.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.iq.Iq`"""
_unused = stanza
self.lock.acquire()
try:
self.state_change("registered", self.registration_form)
if ('FORM_TYPE' in self.registration_form
and self.registration_form['FORM_TYPE'].value == 'jabber:iq:register'):
if 'username' in self.registration_form:
self.my_jid = JID(self.registration_form['username'].value,
self.my_jid.domain, self.my_jid.resource)
if 'password' in self.registration_form:
self.password = self.registration_form['password'].value
self.registration_callback = None
self._post_connect()
finally:
self.lock.release()
|
def registration_success(self, stanza):
"""Handle registration success.
[client only]
Clean up registration stuff, change state to "registered" and initialize
authentication.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.iq.Iq`"""
_unused = stanza
self.lock.acquire()
try:
self.state_change("registered", self.registration_form)
if ('FORM_TYPE' in self.registration_form
and self.registration_form['FORM_TYPE'].value == 'jabber:iq:register'):
if 'username' in self.registration_form:
self.my_jid = JID(self.registration_form['username'].value,
self.my_jid.domain, self.my_jid.resource)
if 'password' in self.registration_form:
self.password = self.registration_form['password'].value
self.registration_callback = None
self._post_connect()
finally:
self.lock.release()
|
[
"Handle",
"registration",
"success",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/legacyauth.py#L443-L469
|
[
"def",
"registration_success",
"(",
"self",
",",
"stanza",
")",
":",
"_unused",
"=",
"stanza",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"state_change",
"(",
"\"registered\"",
",",
"self",
".",
"registration_form",
")",
"if",
"(",
"'FORM_TYPE'",
"in",
"self",
".",
"registration_form",
"and",
"self",
".",
"registration_form",
"[",
"'FORM_TYPE'",
"]",
".",
"value",
"==",
"'jabber:iq:register'",
")",
":",
"if",
"'username'",
"in",
"self",
".",
"registration_form",
":",
"self",
".",
"my_jid",
"=",
"JID",
"(",
"self",
".",
"registration_form",
"[",
"'username'",
"]",
".",
"value",
",",
"self",
".",
"my_jid",
".",
"domain",
",",
"self",
".",
"my_jid",
".",
"resource",
")",
"if",
"'password'",
"in",
"self",
".",
"registration_form",
":",
"self",
".",
"password",
"=",
"self",
".",
"registration_form",
"[",
"'password'",
"]",
".",
"value",
"self",
".",
"registration_callback",
"=",
"None",
"self",
".",
"_post_connect",
"(",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TornadoMainLoop._add_io_handler
|
Add an I/O handler to the loop.
|
pyxmpp2/mainloop/tornado.py
|
def _add_io_handler(self, handler):
"""Add an I/O handler to the loop."""
logger.debug('adding io handler: %r', handler)
self._unprepared_handlers[handler] = None
self._configure_io_handler(handler)
|
def _add_io_handler(self, handler):
"""Add an I/O handler to the loop."""
logger.debug('adding io handler: %r', handler)
self._unprepared_handlers[handler] = None
self._configure_io_handler(handler)
|
[
"Add",
"an",
"I",
"/",
"O",
"handler",
"to",
"the",
"loop",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/tornado.py#L42-L46
|
[
"def",
"_add_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"logger",
".",
"debug",
"(",
"'adding io handler: %r'",
",",
"handler",
")",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"=",
"None",
"self",
".",
"_configure_io_handler",
"(",
"handler",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TornadoMainLoop._configure_io_handler
|
Register an io-handler at the polling object.
|
pyxmpp2/mainloop/tornado.py
|
def _configure_io_handler(self, handler):
"""Register an io-handler at the polling object."""
if self.check_events():
return
if handler in self._unprepared_handlers:
old_fileno = self._unprepared_handlers[handler]
prepared = self._prepare_io_handler(handler)
else:
old_fileno = None
prepared = True
fileno = handler.fileno()
if old_fileno is not None and fileno != old_fileno:
del self._handlers[old_fileno]
# remove_handler won't raise something like KeyError if the fd
# isn't registered; it will just print a debug log.
self.io_loop.remove_handler(old_fileno)
if not prepared:
self._unprepared_handlers[handler] = fileno
if not fileno:
return
update = fileno in self._handlers
events = ioloop.IOLoop.NONE
if handler.is_readable():
logger.debug(" {0!r} readable".format(handler))
events |= ioloop.IOLoop.READ
if handler.is_writable():
logger.debug(" {0!r} writable".format(handler))
events |= ioloop.IOLoop.WRITE
if self._handlers.get(fileno, None) == events:
return
self._handlers[fileno] = events
if events:
logger.debug(" registering {0!r} handler fileno {1} for"
" events {2}".format(handler, fileno, events))
if update:
self.io_loop.update_handler(fileno, events)
else:
self.io_loop.add_handler(
fileno, partial(self._handle_event, handler), events
)
|
def _configure_io_handler(self, handler):
"""Register an io-handler at the polling object."""
if self.check_events():
return
if handler in self._unprepared_handlers:
old_fileno = self._unprepared_handlers[handler]
prepared = self._prepare_io_handler(handler)
else:
old_fileno = None
prepared = True
fileno = handler.fileno()
if old_fileno is not None and fileno != old_fileno:
del self._handlers[old_fileno]
# remove_handler won't raise something like KeyError if the fd
# isn't registered; it will just print a debug log.
self.io_loop.remove_handler(old_fileno)
if not prepared:
self._unprepared_handlers[handler] = fileno
if not fileno:
return
update = fileno in self._handlers
events = ioloop.IOLoop.NONE
if handler.is_readable():
logger.debug(" {0!r} readable".format(handler))
events |= ioloop.IOLoop.READ
if handler.is_writable():
logger.debug(" {0!r} writable".format(handler))
events |= ioloop.IOLoop.WRITE
if self._handlers.get(fileno, None) == events:
return
self._handlers[fileno] = events
if events:
logger.debug(" registering {0!r} handler fileno {1} for"
" events {2}".format(handler, fileno, events))
if update:
self.io_loop.update_handler(fileno, events)
else:
self.io_loop.add_handler(
fileno, partial(self._handle_event, handler), events
)
|
[
"Register",
"an",
"io",
"-",
"handler",
"at",
"the",
"polling",
"object",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/tornado.py#L48-L88
|
[
"def",
"_configure_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"self",
".",
"check_events",
"(",
")",
":",
"return",
"if",
"handler",
"in",
"self",
".",
"_unprepared_handlers",
":",
"old_fileno",
"=",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"prepared",
"=",
"self",
".",
"_prepare_io_handler",
"(",
"handler",
")",
"else",
":",
"old_fileno",
"=",
"None",
"prepared",
"=",
"True",
"fileno",
"=",
"handler",
".",
"fileno",
"(",
")",
"if",
"old_fileno",
"is",
"not",
"None",
"and",
"fileno",
"!=",
"old_fileno",
":",
"del",
"self",
".",
"_handlers",
"[",
"old_fileno",
"]",
"# remove_handler won't raise something like KeyError if the fd",
"# isn't registered; it will just print a debug log.",
"self",
".",
"io_loop",
".",
"remove_handler",
"(",
"old_fileno",
")",
"if",
"not",
"prepared",
":",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"=",
"fileno",
"if",
"not",
"fileno",
":",
"return",
"update",
"=",
"fileno",
"in",
"self",
".",
"_handlers",
"events",
"=",
"ioloop",
".",
"IOLoop",
".",
"NONE",
"if",
"handler",
".",
"is_readable",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\" {0!r} readable\"",
".",
"format",
"(",
"handler",
")",
")",
"events",
"|=",
"ioloop",
".",
"IOLoop",
".",
"READ",
"if",
"handler",
".",
"is_writable",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"\" {0!r} writable\"",
".",
"format",
"(",
"handler",
")",
")",
"events",
"|=",
"ioloop",
".",
"IOLoop",
".",
"WRITE",
"if",
"self",
".",
"_handlers",
".",
"get",
"(",
"fileno",
",",
"None",
")",
"==",
"events",
":",
"return",
"self",
".",
"_handlers",
"[",
"fileno",
"]",
"=",
"events",
"if",
"events",
":",
"logger",
".",
"debug",
"(",
"\" registering {0!r} handler fileno {1} for\"",
"\" events {2}\"",
".",
"format",
"(",
"handler",
",",
"fileno",
",",
"events",
")",
")",
"if",
"update",
":",
"self",
".",
"io_loop",
".",
"update_handler",
"(",
"fileno",
",",
"events",
")",
"else",
":",
"self",
".",
"io_loop",
".",
"add_handler",
"(",
"fileno",
",",
"partial",
"(",
"self",
".",
"_handle_event",
",",
"handler",
")",
",",
"events",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TornadoMainLoop._prepare_io_handler
|
Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
|
pyxmpp2/mainloop/tornado.py
|
def _prepare_io_handler(self, handler):
"""Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
"""
logger.debug(" preparing handler: {0!r}".format(handler))
ret = handler.prepare()
logger.debug(" prepare result: {0!r}".format(ret))
if isinstance(ret, HandlerReady):
del self._unprepared_handlers[handler]
prepared = True
elif isinstance(ret, PrepareAgain):
if ret.timeout is not None:
now = time.time()
self.io_loop.add_timeout(
now + ret.timeout,
partial(self._configure_io_handler, handler)
)
else:
self.io_loop.add_callback(
partial(self._configure_io_handler, handler)
)
prepared = False
else:
raise TypeError("Unexpected result type from prepare()")
return prepared
|
def _prepare_io_handler(self, handler):
"""Call the `interfaces.IOHandler.prepare` method and
remove the handler from unprepared handler list when done.
"""
logger.debug(" preparing handler: {0!r}".format(handler))
ret = handler.prepare()
logger.debug(" prepare result: {0!r}".format(ret))
if isinstance(ret, HandlerReady):
del self._unprepared_handlers[handler]
prepared = True
elif isinstance(ret, PrepareAgain):
if ret.timeout is not None:
now = time.time()
self.io_loop.add_timeout(
now + ret.timeout,
partial(self._configure_io_handler, handler)
)
else:
self.io_loop.add_callback(
partial(self._configure_io_handler, handler)
)
prepared = False
else:
raise TypeError("Unexpected result type from prepare()")
return prepared
|
[
"Call",
"the",
"interfaces",
".",
"IOHandler",
".",
"prepare",
"method",
"and",
"remove",
"the",
"handler",
"from",
"unprepared",
"handler",
"list",
"when",
"done",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/tornado.py#L90-L114
|
[
"def",
"_prepare_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"logger",
".",
"debug",
"(",
"\" preparing handler: {0!r}\"",
".",
"format",
"(",
"handler",
")",
")",
"ret",
"=",
"handler",
".",
"prepare",
"(",
")",
"logger",
".",
"debug",
"(",
"\" prepare result: {0!r}\"",
".",
"format",
"(",
"ret",
")",
")",
"if",
"isinstance",
"(",
"ret",
",",
"HandlerReady",
")",
":",
"del",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"prepared",
"=",
"True",
"elif",
"isinstance",
"(",
"ret",
",",
"PrepareAgain",
")",
":",
"if",
"ret",
".",
"timeout",
"is",
"not",
"None",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"io_loop",
".",
"add_timeout",
"(",
"now",
"+",
"ret",
".",
"timeout",
",",
"partial",
"(",
"self",
".",
"_configure_io_handler",
",",
"handler",
")",
")",
"else",
":",
"self",
".",
"io_loop",
".",
"add_callback",
"(",
"partial",
"(",
"self",
".",
"_configure_io_handler",
",",
"handler",
")",
")",
"prepared",
"=",
"False",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unexpected result type from prepare()\"",
")",
"return",
"prepared"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TornadoMainLoop._remove_io_handler
|
Remove an i/o-handler.
|
pyxmpp2/mainloop/tornado.py
|
def _remove_io_handler(self, handler):
"""Remove an i/o-handler."""
if handler in self._unprepared_handlers:
old_fileno = self._unprepared_handlers[handler]
del self._unprepared_handlers[handler]
else:
old_fileno = handler.fileno()
if old_fileno is not None:
del self._handlers[old_fileno]
self.io_loop.remove_handler(handler.fileno())
|
def _remove_io_handler(self, handler):
"""Remove an i/o-handler."""
if handler in self._unprepared_handlers:
old_fileno = self._unprepared_handlers[handler]
del self._unprepared_handlers[handler]
else:
old_fileno = handler.fileno()
if old_fileno is not None:
del self._handlers[old_fileno]
self.io_loop.remove_handler(handler.fileno())
|
[
"Remove",
"an",
"i",
"/",
"o",
"-",
"handler",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/tornado.py#L116-L125
|
[
"def",
"_remove_io_handler",
"(",
"self",
",",
"handler",
")",
":",
"if",
"handler",
"in",
"self",
".",
"_unprepared_handlers",
":",
"old_fileno",
"=",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"del",
"self",
".",
"_unprepared_handlers",
"[",
"handler",
"]",
"else",
":",
"old_fileno",
"=",
"handler",
".",
"fileno",
"(",
")",
"if",
"old_fileno",
"is",
"not",
"None",
":",
"del",
"self",
".",
"_handlers",
"[",
"old_fileno",
"]",
"self",
".",
"io_loop",
".",
"remove_handler",
"(",
"handler",
".",
"fileno",
"(",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
TornadoMainLoop._handle_event
|
handle I/O events
|
pyxmpp2/mainloop/tornado.py
|
def _handle_event(self, handler, fd, event):
"""handle I/O events"""
# pylint: disable=C0103
logger.debug('_handle_event: %r, %r, %r', handler, fd, event)
if event & ioloop.IOLoop.ERROR:
handler.handle_hup()
if event & ioloop.IOLoop.READ:
handler.handle_read()
if event & ioloop.IOLoop.WRITE:
handler.handle_write()
self._configure_io_handler(handler)
|
def _handle_event(self, handler, fd, event):
"""handle I/O events"""
# pylint: disable=C0103
logger.debug('_handle_event: %r, %r, %r', handler, fd, event)
if event & ioloop.IOLoop.ERROR:
handler.handle_hup()
if event & ioloop.IOLoop.READ:
handler.handle_read()
if event & ioloop.IOLoop.WRITE:
handler.handle_write()
self._configure_io_handler(handler)
|
[
"handle",
"I",
"/",
"O",
"events"
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/mainloop/tornado.py#L167-L177
|
[
"def",
"_handle_event",
"(",
"self",
",",
"handler",
",",
"fd",
",",
"event",
")",
":",
"# pylint: disable=C0103",
"logger",
".",
"debug",
"(",
"'_handle_event: %r, %r, %r'",
",",
"handler",
",",
"fd",
",",
"event",
")",
"if",
"event",
"&",
"ioloop",
".",
"IOLoop",
".",
"ERROR",
":",
"handler",
".",
"handle_hup",
"(",
")",
"if",
"event",
"&",
"ioloop",
".",
"IOLoop",
".",
"READ",
":",
"handler",
".",
"handle_read",
"(",
")",
"if",
"event",
"&",
"ioloop",
".",
"IOLoop",
".",
"WRITE",
":",
"handler",
".",
"handle_write",
"(",
")",
"self",
".",
"_configure_io_handler",
"(",
"handler",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
request_software_version
|
Request software version information from a remote entity.
When a valid response is received the `callback` will be handled
with a `VersionPayload` instance as its only argument. The object will
provide the requested infromation.
In case of error stanza received or invalid response the `error_callback`
(if provided) will be called with the offending stanza (which can
be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.
The same function will be called on timeout, with the argument set to
`None`.
:Parameters:
- `stanza_processor`: a object used to send the query and handle
response. E.g. a `pyxmpp2.client.Client` instance
- `target_jid`: the JID of the entity to query
- `callback`: function to be called with a valid response
- `error_callback`: function to be called on error
:Types:
- `stanza_processor`: `StanzaProcessor`
- `target_jid`: `JID`
|
pyxmpp2/ext/version.py
|
def request_software_version(stanza_processor, target_jid, callback,
error_callback = None):
"""Request software version information from a remote entity.
When a valid response is received the `callback` will be handled
with a `VersionPayload` instance as its only argument. The object will
provide the requested infromation.
In case of error stanza received or invalid response the `error_callback`
(if provided) will be called with the offending stanza (which can
be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.
The same function will be called on timeout, with the argument set to
`None`.
:Parameters:
- `stanza_processor`: a object used to send the query and handle
response. E.g. a `pyxmpp2.client.Client` instance
- `target_jid`: the JID of the entity to query
- `callback`: function to be called with a valid response
- `error_callback`: function to be called on error
:Types:
- `stanza_processor`: `StanzaProcessor`
- `target_jid`: `JID`
"""
stanza = Iq(to_jid = target_jid, stanza_type = "get")
payload = VersionPayload()
stanza.set_payload(payload)
def wrapper(stanza):
"""Wrapper for the user-provided `callback` that extracts the payload
from stanza received."""
payload = stanza.get_payload(VersionPayload)
if payload is None:
if error_callback:
error_callback(stanza)
else:
logger.warning("Invalid version query response.")
else:
callback(payload)
stanza_processor.set_response_handlers(stanza, wrapper, error_callback)
stanza_processor.send(stanza)
|
def request_software_version(stanza_processor, target_jid, callback,
error_callback = None):
"""Request software version information from a remote entity.
When a valid response is received the `callback` will be handled
with a `VersionPayload` instance as its only argument. The object will
provide the requested infromation.
In case of error stanza received or invalid response the `error_callback`
(if provided) will be called with the offending stanza (which can
be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.
The same function will be called on timeout, with the argument set to
`None`.
:Parameters:
- `stanza_processor`: a object used to send the query and handle
response. E.g. a `pyxmpp2.client.Client` instance
- `target_jid`: the JID of the entity to query
- `callback`: function to be called with a valid response
- `error_callback`: function to be called on error
:Types:
- `stanza_processor`: `StanzaProcessor`
- `target_jid`: `JID`
"""
stanza = Iq(to_jid = target_jid, stanza_type = "get")
payload = VersionPayload()
stanza.set_payload(payload)
def wrapper(stanza):
"""Wrapper for the user-provided `callback` that extracts the payload
from stanza received."""
payload = stanza.get_payload(VersionPayload)
if payload is None:
if error_callback:
error_callback(stanza)
else:
logger.warning("Invalid version query response.")
else:
callback(payload)
stanza_processor.set_response_handlers(stanza, wrapper, error_callback)
stanza_processor.send(stanza)
|
[
"Request",
"software",
"version",
"information",
"from",
"a",
"remote",
"entity",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/version.py#L126-L166
|
[
"def",
"request_software_version",
"(",
"stanza_processor",
",",
"target_jid",
",",
"callback",
",",
"error_callback",
"=",
"None",
")",
":",
"stanza",
"=",
"Iq",
"(",
"to_jid",
"=",
"target_jid",
",",
"stanza_type",
"=",
"\"get\"",
")",
"payload",
"=",
"VersionPayload",
"(",
")",
"stanza",
".",
"set_payload",
"(",
"payload",
")",
"def",
"wrapper",
"(",
"stanza",
")",
":",
"\"\"\"Wrapper for the user-provided `callback` that extracts the payload\n from stanza received.\"\"\"",
"payload",
"=",
"stanza",
".",
"get_payload",
"(",
"VersionPayload",
")",
"if",
"payload",
"is",
"None",
":",
"if",
"error_callback",
":",
"error_callback",
"(",
"stanza",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"\"Invalid version query response.\"",
")",
"else",
":",
"callback",
"(",
"payload",
")",
"stanza_processor",
".",
"set_response_handlers",
"(",
"stanza",
",",
"wrapper",
",",
"error_callback",
")",
"stanza_processor",
".",
"send",
"(",
"stanza",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
valid
|
_os_name_factory
|
Factory for the :r:`software_os setting` default.
|
pyxmpp2/ext/version.py
|
def _os_name_factory(settings):
"""Factory for the :r:`software_os setting` default.
"""
# pylint: disable-msg=W0613,W0142
return u"{0} {1} {2}".format(platform.system(), platform.release(),
platform.machine())
|
def _os_name_factory(settings):
"""Factory for the :r:`software_os setting` default.
"""
# pylint: disable-msg=W0613,W0142
return u"{0} {1} {2}".format(platform.system(), platform.release(),
platform.machine())
|
[
"Factory",
"for",
"the",
":",
"r",
":",
"software_os",
"setting",
"default",
"."
] |
Jajcus/pyxmpp2
|
python
|
https://github.com/Jajcus/pyxmpp2/blob/14a40a3950910a9cd008b55f0d8905aa0186ce18/pyxmpp2/ext/version.py#L168-L173
|
[
"def",
"_os_name_factory",
"(",
"settings",
")",
":",
"# pylint: disable-msg=W0613,W0142",
"return",
"u\"{0} {1} {2}\"",
".",
"format",
"(",
"platform",
".",
"system",
"(",
")",
",",
"platform",
".",
"release",
"(",
")",
",",
"platform",
".",
"machine",
"(",
")",
")"
] |
14a40a3950910a9cd008b55f0d8905aa0186ce18
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.