id stringlengths 28 33 | content stringlengths 14 265k ⌀ | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-python_data_bad_742_1 | """Parse (absolute and relative) URLs.
urlparse module is based upon the following RFC specifications.
RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
and L. Masinter, January 2005.
RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
and L.Masinter, December 1999.
RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T.
Berners-Lee, R. Fielding, and L. Masinter, August 1998.
RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998.
RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
1995.
RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
McCahill, December 1994
RFC 3986 is considered the current standard and any future changes to
urlparse module should conform with it. The urlparse module is
currently not entirely compliant with this RFC due to defacto
scenarios for parsing, and for backward compatibility purposes, some
parsing quirks from older RFCs are retained. The testcases in
test_urlparse.py provides a good indicator of parsing behavior.
"""
import re
import sys
import collections
import warnings
__all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
"urlsplit", "urlunsplit", "urlencode", "parse_qs",
"parse_qsl", "quote", "quote_plus", "quote_from_bytes",
"unquote", "unquote_plus", "unquote_to_bytes",
"DefragResult", "ParseResult", "SplitResult",
"DefragResultBytes", "ParseResultBytes", "SplitResultBytes"]
# A classification of schemes.
# The empty string classifies URLs with no scheme specified,
# being the default value returned by “urlsplit” and “urlparse”.
uses_relative = ['', 'ftp', 'http', 'gopher', 'nntp', 'imap',
'wais', 'file', 'https', 'shttp', 'mms',
'prospero', 'rtsp', 'rtspu', 'sftp',
'svn', 'svn+ssh', 'ws', 'wss']
uses_netloc = ['', 'ftp', 'http', 'gopher', 'nntp', 'telnet',
'imap', 'wais', 'file', 'mms', 'https', 'shttp',
'snews', 'prospero', 'rtsp', 'rtspu', 'rsync',
'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh',
'ws', 'wss']
uses_params = ['', 'ftp', 'hdl', 'prospero', 'http', 'imap',
'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
'mms', 'sftp', 'tel']
# These are not actually used anymore, but should stay for backwards
# compatibility. (They are undocumented, but have a public-looking name.)
non_hierarchical = ['gopher', 'hdl', 'mailto', 'news',
'telnet', 'wais', 'imap', 'snews', 'sip', 'sips']
uses_query = ['', 'http', 'wais', 'imap', 'https', 'shttp', 'mms',
'gopher', 'rtsp', 'rtspu', 'sip', 'sips']
uses_fragment = ['', 'ftp', 'hdl', 'http', 'gopher', 'news',
'nntp', 'wais', 'https', 'shttp', 'snews',
'file', 'prospero']
# Characters valid in scheme names
scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789'
'+-.')
# XXX: Consider replacing with functools.lru_cache
MAX_CACHE_SIZE = 20
_parse_cache = {}
def clear_cache():
"""Clear the parse cache and the quoters cache."""
_parse_cache.clear()
_safe_quoters.clear()
# Helpers for bytes handling
# For 3.2, we deliberately require applications that
# handle improperly quoted URLs to do their own
# decoding and encoding. If valid use cases are
# presented, we may relax this by using latin-1
# decoding internally for 3.3
_implicit_encoding = 'ascii'
_implicit_errors = 'strict'
def _noop(obj):
return obj
def _encode_result(obj, encoding=_implicit_encoding,
errors=_implicit_errors):
return obj.encode(encoding, errors)
def _decode_args(args, encoding=_implicit_encoding,
errors=_implicit_errors):
return tuple(x.decode(encoding, errors) if x else '' for x in args)
def _coerce_args(*args):
# Invokes decode if necessary to create str args
# and returns the coerced inputs along with
# an appropriate result coercion function
# - noop for str inputs
# - encoding function otherwise
str_input = isinstance(args[0], str)
for arg in args[1:]:
# We special-case the empty string to support the
# "scheme=''" default argument to some functions
if arg and isinstance(arg, str) != str_input:
raise TypeError("Cannot mix str and non-str arguments")
if str_input:
return args + (_noop,)
return _decode_args(args) + (_encode_result,)
# Result objects are more helpful than simple tuples
class _ResultMixinStr(object):
"""Standard approach to encoding parsed results from str to bytes"""
__slots__ = ()
def encode(self, encoding='ascii', errors='strict'):
return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self))
class _ResultMixinBytes(object):
"""Standard approach to decoding parsed results from bytes to str"""
__slots__ = ()
def decode(self, encoding='ascii', errors='strict'):
return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))
class _NetlocResultMixinBase(object):
"""Shared methods for the parsed result objects containing a netloc element"""
__slots__ = ()
@property
def username(self):
return self._userinfo[0]
@property
def password(self):
return self._userinfo[1]
@property
def hostname(self):
hostname = self._hostinfo[0]
if not hostname:
return None
# Scoped IPv6 address may have zone info, which must not be lowercased
# like http://[fe80::822a:a8ff:fe49:470c%tESt]:1234/keys
separator = '%' if isinstance(hostname, str) else b'%'
hostname, percent, zone = hostname.partition(separator)
return hostname.lower() + percent + zone
@property
def port(self):
port = self._hostinfo[1]
if port is not None:
try:
port = int(port, 10)
except ValueError:
message = f'Port could not be cast to integer value as {port!r}'
raise ValueError(message) from None
if not ( 0 <= port <= 65535):
raise ValueError("Port out of range 0-65535")
return port
class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr):
__slots__ = ()
@property
def _userinfo(self):
netloc = self.netloc
userinfo, have_info, hostinfo = netloc.rpartition('@')
if have_info:
username, have_password, password = userinfo.partition(':')
if not have_password:
password = None
else:
username = password = None
return username, password
@property
def _hostinfo(self):
netloc = self.netloc
_, _, hostinfo = netloc.rpartition('@')
_, have_open_br, bracketed = hostinfo.partition('[')
if have_open_br:
hostname, _, port = bracketed.partition(']')
_, _, port = port.partition(':')
else:
hostname, _, port = hostinfo.partition(':')
if not port:
port = None
return hostname, port
class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):
__slots__ = ()
@property
def _userinfo(self):
netloc = self.netloc
userinfo, have_info, hostinfo = netloc.rpartition(b'@')
if have_info:
username, have_password, password = userinfo.partition(b':')
if not have_password:
password = None
else:
username = password = None
return username, password
@property
def _hostinfo(self):
netloc = self.netloc
_, _, hostinfo = netloc.rpartition(b'@')
_, have_open_br, bracketed = hostinfo.partition(b'[')
if have_open_br:
hostname, _, port = bracketed.partition(b']')
_, _, port = port.partition(b':')
else:
hostname, _, port = hostinfo.partition(b':')
if not port:
port = None
return hostname, port
from collections import namedtuple
_DefragResultBase = namedtuple('DefragResult', 'url fragment')
_SplitResultBase = namedtuple(
'SplitResult', 'scheme netloc path query fragment')
_ParseResultBase = namedtuple(
'ParseResult', 'scheme netloc path params query fragment')
_DefragResultBase.__doc__ = """
DefragResult(url, fragment)
A 2-tuple that contains the url without fragment identifier and the fragment
identifier as a separate argument.
"""
_DefragResultBase.url.__doc__ = """The URL with no fragment identifier."""
_DefragResultBase.fragment.__doc__ = """
Fragment identifier separated from URL, that allows indirect identification of a
secondary resource by reference to a primary resource and additional identifying
information.
"""
_SplitResultBase.__doc__ = """
SplitResult(scheme, netloc, path, query, fragment)
A 5-tuple that contains the different components of a URL. Similar to
ParseResult, but does not split params.
"""
_SplitResultBase.scheme.__doc__ = """Specifies URL scheme for the request."""
_SplitResultBase.netloc.__doc__ = """
Network location where the request is made to.
"""
_SplitResultBase.path.__doc__ = """
The hierarchical path, such as the path to a file to download.
"""
_SplitResultBase.query.__doc__ = """
The query component, that contains non-hierarchical data, that along with data
in path component, identifies a resource in the scope of URI's scheme and
network location.
"""
_SplitResultBase.fragment.__doc__ = """
Fragment identifier, that allows indirect identification of a secondary resource
by reference to a primary resource and additional identifying information.
"""
_ParseResultBase.__doc__ = """
ParseResult(scheme, netloc, path, params, query, fragment)
A 6-tuple that contains components of a parsed URL.
"""
_ParseResultBase.scheme.__doc__ = _SplitResultBase.scheme.__doc__
_ParseResultBase.netloc.__doc__ = _SplitResultBase.netloc.__doc__
_ParseResultBase.path.__doc__ = _SplitResultBase.path.__doc__
_ParseResultBase.params.__doc__ = """
Parameters for last path element used to dereference the URI in order to provide
access to perform some operation on the resource.
"""
_ParseResultBase.query.__doc__ = _SplitResultBase.query.__doc__
_ParseResultBase.fragment.__doc__ = _SplitResultBase.fragment.__doc__
# For backwards compatibility, alias _NetlocResultMixinStr
# ResultBase is no longer part of the documented API, but it is
# retained since deprecating it isn't worth the hassle
ResultBase = _NetlocResultMixinStr
# Structured result objects for string data
class DefragResult(_DefragResultBase, _ResultMixinStr):
__slots__ = ()
def geturl(self):
if self.fragment:
return self.url + '#' + self.fragment
else:
return self.url
class SplitResult(_SplitResultBase, _NetlocResultMixinStr):
__slots__ = ()
def geturl(self):
return urlunsplit(self)
class ParseResult(_ParseResultBase, _NetlocResultMixinStr):
__slots__ = ()
def geturl(self):
return urlunparse(self)
# Structured result objects for bytes data
class DefragResultBytes(_DefragResultBase, _ResultMixinBytes):
__slots__ = ()
def geturl(self):
if self.fragment:
return self.url + b'#' + self.fragment
else:
return self.url
class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes):
__slots__ = ()
def geturl(self):
return urlunsplit(self)
class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes):
__slots__ = ()
def geturl(self):
return urlunparse(self)
# Set up the encode/decode result pairs
def _fix_result_transcoding():
_result_pairs = (
(DefragResult, DefragResultBytes),
(SplitResult, SplitResultBytes),
(ParseResult, ParseResultBytes),
)
for _decoded, _encoded in _result_pairs:
_decoded._encoded_counterpart = _encoded
_encoded._decoded_counterpart = _decoded
_fix_result_transcoding()
del _fix_result_transcoding
def urlparse(url, scheme='', allow_fragments=True):
"""Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params>?<query>#<fragment>
Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
splitresult = urlsplit(url, scheme, allow_fragments)
scheme, netloc, url, query, fragment = splitresult
if scheme in uses_params and ';' in url:
url, params = _splitparams(url)
else:
params = ''
result = ParseResult(scheme, netloc, url, params, query, fragment)
return _coerce_result(result)
def _splitparams(url):
if '/' in url:
i = url.find(';', url.rfind('/'))
if i < 0:
return url, ''
else:
i = url.find(';')
return url[:i], url[i+1:]
def _splitnetloc(url, start=0):
delim = len(url) # position of end of domain part of url, default is end
for c in '/?#': # look for delimiters; the order is NOT important
wdelim = url.find(c, start) # find first of this delim
if wdelim >= 0: # if found
delim = min(delim, wdelim) # use earliest delim position
return url[start:delim], url[delim:] # return (domain, rest)
def _checknetloc(netloc):
if not netloc or netloc.isascii():
return
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.rpartition('@')[2] # ignore anything to the left of '@'
n = n.replace(':', '') # ignore characters already included
n = n.replace('#', '') # but not the surrounding text
n = n.replace('?', '')
netloc2 = unicodedata.normalize('NFKC', n)
if n == netloc2:
return
for c in '/?#@:':
if c in netloc2:
raise ValueError("netloc '" + netloc + "' contains invalid " +
"characters under NFKC normalization")
def urlsplit(url, scheme='', allow_fragments=True):
"""Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
Return a 5-tuple: (scheme, netloc, path, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
allow_fragments = bool(allow_fragments)
key = url, scheme, allow_fragments, type(url), type(scheme)
cached = _parse_cache.get(key, None)
if cached:
return _coerce_result(cached)
if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
clear_cache()
netloc = query = fragment = ''
i = url.find(':')
if i > 0:
if url[:i] == 'http': # optimize the common case
url = url[i+1:]
if url[:2] == '//':
netloc, url = _splitnetloc(url, 2)
if (('[' in netloc and ']' not in netloc) or
(']' in netloc and '[' not in netloc)):
raise ValueError("Invalid IPv6 URL")
if allow_fragments and '#' in url:
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
_checknetloc(netloc)
v = SplitResult('http', netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v)
for c in url[:i]:
if c not in scheme_chars:
break
else:
# make sure "url" is not actually a port number (in which case
# "scheme" is really part of the path)
rest = url[i+1:]
if not rest or any(c not in '0123456789' for c in rest):
# not a port number
scheme, url = url[:i].lower(), rest
if url[:2] == '//':
netloc, url = _splitnetloc(url, 2)
if (('[' in netloc and ']' not in netloc) or
(']' in netloc and '[' not in netloc)):
raise ValueError("Invalid IPv6 URL")
if allow_fragments and '#' in url:
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
_checknetloc(netloc)
v = SplitResult(scheme, netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v)
def urlunparse(components):
"""Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent)."""
scheme, netloc, url, params, query, fragment, _coerce_result = (
_coerce_args(*components))
if params:
url = "%s;%s" % (url, params)
return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
def urlunsplit(components):
"""Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example, a ? with an
empty query; the RFC states that these are equivalent)."""
scheme, netloc, url, query, fragment, _coerce_result = (
_coerce_args(*components))
if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
if url and url[:1] != '/': url = '/' + url
url = '//' + (netloc or '') + url
if scheme:
url = scheme + ':' + url
if query:
url = url + '?' + query
if fragment:
url = url + '#' + fragment
return _coerce_result(url)
def urljoin(base, url, allow_fragments=True):
"""Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter."""
if not base:
return url
if not url:
return base
base, url, _coerce_result = _coerce_args(base, url)
bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
urlparse(base, '', allow_fragments)
scheme, netloc, path, params, query, fragment = \
urlparse(url, bscheme, allow_fragments)
if scheme != bscheme or scheme not in uses_relative:
return _coerce_result(url)
if scheme in uses_netloc:
if netloc:
return _coerce_result(urlunparse((scheme, netloc, path,
params, query, fragment)))
netloc = bnetloc
if not path and not params:
path = bpath
params = bparams
if not query:
query = bquery
return _coerce_result(urlunparse((scheme, netloc, path,
params, query, fragment)))
base_parts = bpath.split('/')
if base_parts[-1] != '':
# the last item is not a directory, so will not be taken into account
# in resolving the relative path
del base_parts[-1]
# for rfc3986, ignore all base path should the first character be root.
if path[:1] == '/':
segments = path.split('/')
else:
segments = base_parts + path.split('/')
# filter out elements that would cause redundant slashes on re-joining
# the resolved_path
segments[1:-1] = filter(None, segments[1:-1])
resolved_path = []
for seg in segments:
if seg == '..':
try:
resolved_path.pop()
except IndexError:
# ignore any .. segments that would otherwise cause an IndexError
# when popped from resolved_path if resolving for rfc3986
pass
elif seg == '.':
continue
else:
resolved_path.append(seg)
if segments[-1] in ('.', '..'):
# do some post-processing here. if the last segment was a relative dir,
# then we need to append the trailing '/'
resolved_path.append('')
return _coerce_result(urlunparse((scheme, netloc, '/'.join(
resolved_path) or '/', params, query, fragment)))
def urldefrag(url):
"""Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
"""
url, _coerce_result = _coerce_args(url)
if '#' in url:
s, n, p, a, q, frag = urlparse(url)
defrag = urlunparse((s, n, p, a, q, ''))
else:
frag = ''
defrag = url
return _coerce_result(DefragResult(defrag, frag))
_hexdig = '0123456789ABCDEFabcdef'
_hextobyte = None
def unquote_to_bytes(string):
"""unquote_to_bytes('abc%20def') -> b'abc def'."""
# Note: strings are encoded as UTF-8. This is only an issue if it contains
# unescaped non-ASCII characters, which URIs should not.
if not string:
# Is it a string-like object?
string.split
return b''
if isinstance(string, str):
string = string.encode('utf-8')
bits = string.split(b'%')
if len(bits) == 1:
return string
res = [bits[0]]
append = res.append
# Delay the initialization of the table to not waste memory
# if the function is never called
global _hextobyte
if _hextobyte is None:
_hextobyte = {(a + b).encode(): bytes.fromhex(a + b)
for a in _hexdig for b in _hexdig}
for item in bits[1:]:
try:
append(_hextobyte[item[:2]])
append(item[2:])
except KeyError:
append(b'%')
append(item)
return b''.join(res)
_asciire = re.compile('([\x00-\x7f]+)')
def unquote(string, encoding='utf-8', errors='replace'):
"""Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters, as accepted by the bytes.decode()
method.
By default, percent-encoded sequences are decoded with UTF-8, and invalid
sequences are replaced by a placeholder character.
unquote('abc%20def') -> 'abc def'.
"""
if '%' not in string:
string.split
return string
if encoding is None:
encoding = 'utf-8'
if errors is None:
errors = 'replace'
bits = _asciire.split(string)
res = [bits[0]]
append = res.append
for i in range(1, len(bits), 2):
append(unquote_to_bytes(bits[i]).decode(encoding, errors))
append(bits[i + 1])
return ''.join(res)
def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace', max_num_fields=None):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
not included.
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
max_num_fields: int. If set, then throws a ValueError if there
are more than n fields read by parse_qsl().
Returns a dictionary.
"""
parsed_result = {}
pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
encoding=encoding, errors=errors,
max_num_fields=max_num_fields)
for name, value in pairs:
if name in parsed_result:
parsed_result[name].append(value)
else:
parsed_result[name] = [value]
return parsed_result
def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace', max_num_fields=None):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If
false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
max_num_fields: int. If set, then throws a ValueError
if there are more than n fields read by parse_qsl().
Returns a list, as G-d intended.
"""
qs, _coerce_result = _coerce_args(qs)
# If max_num_fields is defined then check that the number of fields
# is less than max_num_fields. This prevents a memory exhaustion DOS
# attack via post bodies with many fields.
if max_num_fields is not None:
num_fields = 1 + qs.count('&') + qs.count(';')
if max_num_fields < num_fields:
raise ValueError('Max number of fields exceeded')
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
r = []
for name_value in pairs:
if not name_value and not strict_parsing:
continue
nv = name_value.split('=', 1)
if len(nv) != 2:
if strict_parsing:
raise ValueError("bad query field: %r" % (name_value,))
# Handle case of a control-name with no equal sign
if keep_blank_values:
nv.append('')
else:
continue
if len(nv[1]) or keep_blank_values:
name = nv[0].replace('+', ' ')
name = unquote(name, encoding=encoding, errors=errors)
name = _coerce_result(name)
value = nv[1].replace('+', ' ')
value = unquote(value, encoding=encoding, errors=errors)
value = _coerce_result(value)
r.append((name, value))
return r
def unquote_plus(string, encoding='utf-8', errors='replace'):
"""Like unquote(), but also replace plus signs by spaces, as required for
unquoting HTML form values.
unquote_plus('%7e/abc+def') -> '~/abc def'
"""
string = string.replace('+', ' ')
return unquote(string, encoding, errors)
_ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
b'abcdefghijklmnopqrstuvwxyz'
b'0123456789'
b'_.-~')
_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
_safe_quoters = {}
class Quoter(collections.defaultdict):
"""A mapping from bytes (in range(0,256)) to strings.
String values are percent-encoded byte values, unless the key < 128, and
in the "safe" set (either the specified safe set, or default set).
"""
# Keeps a cache internally, using defaultdict, for efficiency (lookups
# of cached keys don't call Python code at all).
def __init__(self, safe):
"""safe: bytes object."""
self.safe = _ALWAYS_SAFE.union(safe)
def __repr__(self):
# Without this, will just display as a defaultdict
return "<%s %r>" % (self.__class__.__name__, dict(self))
def __missing__(self, b):
# Handle a cache miss. Store quoted string in cache and return.
res = chr(b) if b in self.safe else '%{:02X}'.format(b)
self[b] = res
return res
def quote(string, safe='/', encoding=None, errors=None):
"""quote('abc def') -> 'abc%20def'
Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted. The
quote function offers a cautious (not minimal) way to quote a
string for most of these parts.
RFC 3986 Uniform Resource Identifier (URI): Generic Syntax lists
the following (un)reserved characters.
unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
reserved = gen-delims / sub-delims
gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@"
sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
Each of the reserved characters is reserved in some component of a URL,
but not necessarily in all of them.
The quote function %-escapes all characters that are neither in the
unreserved chars ("always safe") nor the additional chars set via the
safe arg.
The default for the safe arg is '/'. The character is reserved, but in
typical usage the quote function is being called on a path where the
existing slash characters are to be preserved.
Python 3.7 updates from using RFC 2396 to RFC 3986 to quote URL strings.
Now, "~" is included in the set of unreserved characters.
string and safe may be either str or bytes objects. encoding and errors
must not be specified if string is a bytes object.
The optional encoding and errors parameters specify how to deal with
non-ASCII characters, as accepted by the str.encode method.
By default, encoding='utf-8' (characters are encoded with UTF-8), and
errors='strict' (unsupported characters raise a UnicodeEncodeError).
"""
if isinstance(string, str):
if not string:
return string
if encoding is None:
encoding = 'utf-8'
if errors is None:
errors = 'strict'
string = string.encode(encoding, errors)
else:
if encoding is not None:
raise TypeError("quote() doesn't support 'encoding' for bytes")
if errors is not None:
raise TypeError("quote() doesn't support 'errors' for bytes")
return quote_from_bytes(string, safe)
def quote_plus(string, safe='', encoding=None, errors=None):
"""Like quote(), but also replace ' ' with '+', as required for quoting
HTML form values. Plus signs in the original string are escaped unless
they are included in safe. It also does not have safe default to '/'.
"""
# Check if ' ' in string, where string may either be a str or bytes. If
# there are no spaces, the regular quote will produce the right answer.
if ((isinstance(string, str) and ' ' not in string) or
(isinstance(string, bytes) and b' ' not in string)):
return quote(string, safe, encoding, errors)
if isinstance(safe, str):
space = ' '
else:
space = b' '
string = quote(string, safe + space, encoding, errors)
return string.replace(' ', '+')
def quote_from_bytes(bs, safe='/'):
"""Like quote(), but accepts a bytes object rather than a str, and does
not perform string-to-bytes encoding. It always returns an ASCII string.
quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
"""
if not isinstance(bs, (bytes, bytearray)):
raise TypeError("quote_from_bytes() expected bytes")
if not bs:
return ''
if isinstance(safe, str):
# Normalize 'safe' by converting to bytes and removing non-ASCII chars
safe = safe.encode('ascii', 'ignore')
else:
safe = bytes([c for c in safe if c < 128])
if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
return bs.decode()
try:
quoter = _safe_quoters[safe]
except KeyError:
_safe_quoters[safe] = quoter = Quoter(safe).__getitem__
return ''.join([quoter(char) for char in bs])
def urlencode(query, doseq=False, safe='', encoding=None, errors=None,
quote_via=quote_plus):
"""Encode a dict or sequence of two-element tuples into a URL query string.
If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.
If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input.
The components of a query arg may each be either a string or a bytes type.
The safe, encoding, and errors parameters are passed down to the function
specified by quote_via (encoding and errors only if a component is a str).
"""
if hasattr(query, "items"):
query = query.items()
else:
# It's a bother at times that strings and string-like objects are
# sequences.
try:
# non-sequence items should not work with len()
# non-empty strings will fail this
if len(query) and not isinstance(query[0], tuple):
raise TypeError
# Zero-length sequences of all types will get here and succeed,
# but that's a minor nit. Since the original implementation
# allowed empty dicts that type of behavior probably should be
# preserved for consistency
except TypeError:
ty, va, tb = sys.exc_info()
raise TypeError("not a valid non-string sequence "
"or mapping object").with_traceback(tb)
l = []
if not doseq:
for k, v in query:
if isinstance(k, bytes):
k = quote_via(k, safe)
else:
k = quote_via(str(k), safe, encoding, errors)
if isinstance(v, bytes):
v = quote_via(v, safe)
else:
v = quote_via(str(v), safe, encoding, errors)
l.append(k + '=' + v)
else:
for k, v in query:
if isinstance(k, bytes):
k = quote_via(k, safe)
else:
k = quote_via(str(k), safe, encoding, errors)
if isinstance(v, bytes):
v = quote_via(v, safe)
l.append(k + '=' + v)
elif isinstance(v, str):
v = quote_via(v, safe, encoding, errors)
l.append(k + '=' + v)
else:
try:
# Is this a sufficient test for sequence-ness?
x = len(v)
except TypeError:
# not a sequence
v = quote_via(str(v), safe, encoding, errors)
l.append(k + '=' + v)
else:
# loop over the sequence
for elt in v:
if isinstance(elt, bytes):
elt = quote_via(elt, safe)
else:
elt = quote_via(str(elt), safe, encoding, errors)
l.append(k + '=' + elt)
return '&'.join(l)
def to_bytes(url):
warnings.warn("urllib.parse.to_bytes() is deprecated as of 3.8",
DeprecationWarning, stacklevel=2)
return _to_bytes(url)
def _to_bytes(url):
"""to_bytes(u"URL") --> 'URL'."""
# Most URL schemes require ASCII. If that changes, the conversion
# can be relaxed.
# XXX get rid of to_bytes()
if isinstance(url, str):
try:
url = url.encode("ASCII").decode()
except UnicodeError:
raise UnicodeError("URL " + repr(url) +
" contains non-ASCII characters")
return url
def unwrap(url):
"""Transform a string like '<URL:scheme://host/path>' into 'scheme://host/path'.
The string is returned unchanged if it's not a wrapped URL.
"""
url = str(url).strip()
if url[:1] == '<' and url[-1:] == '>':
url = url[1:-1].strip()
if url[:4] == 'URL:':
url = url[4:].strip()
return url
def splittype(url):
warnings.warn("urllib.parse.splittype() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splittype(url)
_typeprog = None
def _splittype(url):
"""splittype('type:opaquestring') --> 'type', 'opaquestring'."""
global _typeprog
if _typeprog is None:
_typeprog = re.compile('([^/:]+):(.*)', re.DOTALL)
match = _typeprog.match(url)
if match:
scheme, data = match.groups()
return scheme.lower(), data
return None, url
def splithost(url):
warnings.warn("urllib.parse.splithost() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splithost(url)
_hostprog = None
def _splithost(url):
"""splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
global _hostprog
if _hostprog is None:
_hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
match = _hostprog.match(url)
if match:
host_port, path = match.groups()
if path and path[0] != '/':
path = '/' + path
return host_port, path
return None, url
def splituser(host):
warnings.warn("urllib.parse.splituser() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splituser(host)
def _splituser(host):
"""splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
user, delim, host = host.rpartition('@')
return (user if delim else None), host
def splitpasswd(user):
warnings.warn("urllib.parse.splitpasswd() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splitpasswd(user)
def _splitpasswd(user):
"""splitpasswd('user:passwd') -> 'user', 'passwd'."""
user, delim, passwd = user.partition(':')
return user, (passwd if delim else None)
def splitport(host):
warnings.warn("urllib.parse.splitport() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splitport(host)
# splittag('/path#tag') --> '/path', 'tag'
_portprog = None
def _splitport(host):
"""splitport('host:port') --> 'host', 'port'."""
global _portprog
if _portprog is None:
_portprog = re.compile('(.*):([0-9]*)$', re.DOTALL)
match = _portprog.match(host)
if match:
host, port = match.groups()
if port:
return host, port
return host, None
def splitnport(host, defport=-1):
warnings.warn("urllib.parse.splitnport() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splitnport(host, defport)
def _splitnport(host, defport=-1):
"""Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number."""
host, delim, port = host.rpartition(':')
if not delim:
host = port
elif port:
try:
nport = int(port)
except ValueError:
nport = None
return host, nport
return host, defport
def splitquery(url):
warnings.warn("urllib.parse.splitquery() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splitquery(url)
def _splitquery(url):
"""splitquery('/path?query') --> '/path', 'query'."""
path, delim, query = url.rpartition('?')
if delim:
return path, query
return url, None
def splittag(url):
warnings.warn("urllib.parse.splittag() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splittag(url)
def _splittag(url):
"""splittag('/path#tag') --> '/path', 'tag'."""
path, delim, tag = url.rpartition('#')
if delim:
return path, tag
return url, None
def splitattr(url):
warnings.warn("urllib.parse.splitattr() is deprecated as of 3.8, "
"use urllib.parse.urlparse() instead",
DeprecationWarning, stacklevel=2)
return _splitattr(url)
def _splitattr(url):
"""splitattr('/path;attr1=value1;attr2=value2;...') ->
'/path', ['attr1=value1', 'attr2=value2', ...]."""
words = url.split(';')
return words[0], words[1:]
def splitvalue(attr):
warnings.warn("urllib.parse.splitvalue() is deprecated as of 3.8, "
"use urllib.parse.parse_qsl() instead",
DeprecationWarning, stacklevel=2)
return _splitvalue(attr)
def _splitvalue(attr):
"""splitvalue('attr=value') --> 'attr', 'value'."""
attr, delim, value = attr.partition('=')
return attr, (value if delim else None)
| ./CrossVul/dataset_final_sorted/CWE-255/py/bad_742_1 |
crossvul-python_data_good_5754_0 | # vim:set et sts=4 sw=4:
# -*- coding: utf-8 -*-
#
# ibus-anthy - The Anthy engine for IBus
#
# Copyright (c) 2007-2008 Peng Huang <shawn.p.huang@gmail.com>
# Copyright (c) 2010-2013 Takao Fujiwara <takao.fujiwara1@gmail.com>
# Copyright (c) 2007-2013 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os
from os import environ, path
import signal
import sys
from gettext import dgettext
from main import get_userhome
try:
from locale import getpreferredencoding
except:
pass
from gi.repository import GLib
from gi.repository import IBus
from gi.repository import Anthy
NTH_UNCONVERTED_CANDIDATE = Anthy.NTH_UNCONVERTED_CANDIDATE
NTH_KATAKANA_CANDIDATE = Anthy.NTH_KATAKANA_CANDIDATE
NTH_HIRAGANA_CANDIDATE = Anthy.NTH_HIRAGANA_CANDIDATE
NTH_HALFKANA_CANDIDATE = Anthy.NTH_HALFKANA_CANDIDATE
import _config as config
from tables import *
import jastring
from segment import unichar_half_to_full
sys.path.append(path.join(config.PKGDATADIR, 'setup'))
from anthyprefs import AnthyPrefs
_ = lambda a : dgettext('ibus-anthy', a)
N_ = lambda a : a
UN = lambda a : unicode(a, 'utf-8')
INPUT_MODE_HIRAGANA, \
INPUT_MODE_KATAKANA, \
INPUT_MODE_HALF_WIDTH_KATAKANA, \
INPUT_MODE_LATIN, \
INPUT_MODE_WIDE_LATIN = range(5)
CONV_MODE_OFF, \
CONV_MODE_ANTHY, \
CONV_MODE_HIRAGANA, \
CONV_MODE_KATAKANA, \
CONV_MODE_HALF_WIDTH_KATAKANA, \
CONV_MODE_LATIN_0, \
CONV_MODE_LATIN_1, \
CONV_MODE_LATIN_2, \
CONV_MODE_LATIN_3, \
CONV_MODE_WIDE_LATIN_0, \
CONV_MODE_WIDE_LATIN_1, \
CONV_MODE_WIDE_LATIN_2, \
CONV_MODE_WIDE_LATIN_3, \
CONV_MODE_PREDICTION = range(14)
SEGMENT_DEFAULT = 0
SEGMENT_SINGLE = 1 << 0
SEGMENT_IMMEDIATE = 1 << 1
CLIPBOARD_RECONVERT = range(1)
LINK_DICT_EMBEDDED, \
LINK_DICT_SINGLE = range(2)
IMPORTED_EMBEDDED_DICT_DIR = 'imported_words_default.d'
IMPORTED_EMBEDDED_DICT_PREFIX = 'ibus__'
IMPORTED_SINGLE_DICT_PREFIX = 'imported_words_ibus__'
KP_Table = {}
for s in dir(IBus):
if s.startswith('KEY_KP_'):
v = IBus.keyval_from_name(s[7:])
if v:
KP_Table[IBus.keyval_from_name(s[4:])] = v
for k, v in zip(['KEY_KP_Add', 'KEY_KP_Decimal', 'KEY_KP_Divide', 'KEY_KP_Enter',
'KEY_KP_Equal', 'KEY_KP_Multiply', 'KEY_KP_Separator',
'KEY_KP_Space', 'KEY_KP_Subtract'],
['KEY_plus', 'KEY_period', 'KEY_slash', 'KEY_Return',
'KEY_equal', 'KEY_asterisk', 'KEY_comma',
'KEY_space', 'KEY_minus']):
KP_Table[getattr(IBus, k)] = getattr(IBus, v)
class Engine(IBus.EngineSimple):
__input_mode = None
__typing_mode = None
__segment_mode = None
__dict_mode = None
__setup_pid = 0
__prefs = None
__keybind = {}
__thumb = None
__latin_with_shift = True
def __init__(self, bus, object_path):
super(Engine, self).__init__(connection=bus.get_connection(),
object_path=object_path)
# create anthy context
self.__context = Anthy.GContext()
self.__context.set_encoding(Anthy.UTF8_ENCODING)
# init state
self.__idle_id = 0
self.__prop_dict = {}
self.__input_purpose = 0
self.__has_input_purpose = False
if hasattr(IBus, 'InputPurpose'):
self.__has_input_purpose = True
try:
self.__is_utf8 = (getpreferredencoding().lower() == 'utf-8')
except:
self.__is_utf8 = False
self.__ibus_version = 0.0
# self.__lookup_table = ibus.LookupTable.new(page_size=9,
# cursor_pos=0,
# cursor_visible=True,
# round=True)
size = self.__prefs.get_value('common', 'page_size')
self.__lookup_table = IBus.LookupTable.new(page_size=size,
cursor_pos=0,
cursor_visible=True,
round=True)
self.__prop_list = self.__init_props()
self.__init_signal()
# use reset to init values
self.__reset()
ibus_config = bus.get_config()
if ibus_config != None:
ibus_config.connect('value-changed',
self.__config_value_changed_cb)
def __get_ibus_version(self):
if self.__ibus_version == 0.0:
self.__ibus_version = \
IBus.MAJOR_VERSION + IBus.MINOR_VERSION / 1000.0 + \
IBus.MICRO_VERSION / 1000000.0
return self.__ibus_version
# reset values of engine
def __reset(self):
self.__preedit_ja_string = jastring.JaString(Engine.__typing_mode,
self.__latin_with_shift)
self.__convert_chars = u''
self.__cursor_pos = 0
self.__convert_mode = CONV_MODE_OFF
self.__segments = list()
self.__lookup_table.clear()
self.__lookup_table_visible = False
self._MM = 0
self._SS = 0
self._H = 0
self._RMM = 0
self._RSS = 0
if self.__idle_id != 0:
GLib.source_remove(self.__idle_id)
self.__idle_id = 0
def __init_props(self):
anthy_props = IBus.PropList()
self.__set_input_mode_props(anthy_props)
self.__set_typing_method_props(anthy_props)
self.__set_segment_mode_props(anthy_props)
self.__set_dict_mode_props(anthy_props)
self.__set_dict_config_props(anthy_props)
if not self.__prefs.get_value('common', 'show-preferences'):
return anthy_props
anthy_props.append(IBus.Property(key=u'setup',
label=IBus.Text.new_from_string(_("Preferences - Anthy")),
icon=config.ICON_PREFERENCE,
tooltip=IBus.Text.new_from_string(_("Configure Anthy")),
sensitive=True,
visible=True))
return anthy_props
def __init_signal(self):
signal.signal(signal.SIGHUP, self.__signal_cb)
signal.signal(signal.SIGINT, self.__signal_cb)
signal.signal(signal.SIGQUIT, self.__signal_cb)
signal.signal(signal.SIGABRT, self.__signal_cb)
signal.signal(signal.SIGTERM, self.__signal_cb)
def __signal_cb(self, signum, object):
self.__remove_dict_files()
signal.signal(signum, signal.SIG_DFL)
os.kill(os.getpid(), signum)
def __set_input_mode_props(self, anthy_props):
# The class method is kept even if the engine is switched.
if Engine.__input_mode == None:
# The config value is readonly for initial engine and
# the engine keeps the class method in the memory.
Engine.__input_mode = INPUT_MODE_HIRAGANA
Engine.__input_mode = self.__prefs.get_value('common',
'input_mode')
if not self.__prefs.get_value('common', 'show-input-mode'):
return
# init input mode properties
symbol = 'あ'
'''
Need to split _() by line for intltool to detect them.
'''
# Translators: Specify the order of %s with your translation.
# It will be "Input Mode (A)" for example.
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Input mode"), 'symbol' : symbol }
input_mode_prop = IBus.Property(key=u'InputMode',
prop_type=IBus.PropType.MENU,
label=IBus.Text.new_from_string(label),
symbol=IBus.Text.new_from_string(symbol),
icon='',
tooltip=IBus.Text.new_from_string(_("Switch input mode")),
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None)
self.__prop_dict[u'InputMode'] = input_mode_prop
props = IBus.PropList()
props.append(IBus.Property(key=u'InputMode.Hiragana',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Hiragana")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'InputMode.Katakana',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Katakana")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'InputMode.HalfWidthKatakana',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Halfwidth Katakana")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'InputMode.Latin',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Latin")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'InputMode.WideLatin',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Wide Latin")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.get(Engine.__input_mode).set_state(IBus.PropState.CHECKED)
i = 0
while props.get(i) != None:
prop = props.get(i)
self.__prop_dict[prop.get_key()] = prop
i += 1
input_mode_prop.set_sub_props(props)
anthy_props.append(input_mode_prop)
mode = Engine.__input_mode
mode = 'InputMode.' + ['Hiragana', 'Katakana', 'HalfWidthKatakana',
'Latin', 'WideLatin'][mode]
self.__input_mode_activate(mode, IBus.PropState.CHECKED)
def __set_typing_method_props(self, anthy_props):
if Engine.__typing_mode == None:
Engine.__typing_mode = jastring.TYPING_MODE_ROMAJI
Engine.__typing_mode = self.__prefs.get_value('common',
'typing_method')
if not self.__prefs.get_value('common', 'show-typing-method'):
return
# typing input mode properties
symbol = 'R'
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Typing method"), 'symbol' : symbol }
typing_mode_prop = IBus.Property(key=u'TypingMode',
prop_type=IBus.PropType.MENU,
label=IBus.Text.new_from_string(label),
symbol=IBus.Text.new_from_string(symbol),
icon='',
tooltip=IBus.Text.new_from_string(_("Switch typing method")),
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None)
self.__prop_dict[u'TypingMode'] = typing_mode_prop
props = IBus.PropList()
props.append(IBus.Property(key=u'TypingMode.Romaji',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Romaji")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'TypingMode.Kana',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Kana")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'TypingMode.ThumbShift',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Thumb shift")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.get(Engine.__typing_mode).set_state(IBus.PropState.CHECKED)
i = 0
while props.get(i) != None:
prop = props.get(i)
self.__prop_dict[prop.get_key()] = prop
i += 1
typing_mode_prop.set_sub_props(props)
anthy_props.append(typing_mode_prop)
mode = Engine.__typing_mode
mode = 'TypingMode.' + ['Romaji', 'Kana', 'ThumbShift'][mode]
self.__typing_mode_activate(mode, IBus.PropState.CHECKED)
def __set_segment_mode_props(self, anthy_props):
if Engine.__segment_mode == None:
Engine.__segment_mode = SEGMENT_DEFAULT
Engine.__segment_mode = self.__prefs.get_value('common',
'conversion_segment_mode')
if not self.__prefs.get_value('common', 'show-segment-mode'):
return
symbol = '連'
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Segment mode"), 'symbol' : symbol }
segment_mode_prop = IBus.Property(key=u'SegmentMode',
prop_type=IBus.PropType.MENU,
label=IBus.Text.new_from_string(label),
symbol=IBus.Text.new_from_string(symbol),
icon=None,
tooltip=IBus.Text.new_from_string(_("Switch conversion mode")),
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None)
self.__prop_dict[u'SegmentMode'] = segment_mode_prop
props = IBus.PropList()
props.append(IBus.Property(key=u'SegmentMode.Multi',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Multiple segment")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'SegmentMode.Single',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Single segment")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'SegmentMode.ImmediateMulti',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Immediate conversion (multiple segment)")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'SegmentMode.ImmediateSingle',
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(_("Immediate conversion (single segment)")),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.get(Engine.__segment_mode).set_state(IBus.PropState.CHECKED)
i = 0
while props.get(i) != None:
prop = props.get(i)
self.__prop_dict[prop.get_key()] = prop
i += 1
segment_mode_prop.set_sub_props(props)
anthy_props.append(segment_mode_prop)
mode = Engine.__segment_mode
mode = 'SegmentMode.' + ['Multi', 'Single',
'ImmediateMulti', 'ImmediateSingle'][mode]
self.__segment_mode_activate(mode, IBus.PropState.CHECKED)
def __set_dict_mode_props(self, anthy_props, update_prop=False):
if Engine.__dict_mode == None:
Engine.__dict_mode = 0
if not self.__prefs.get_value('common', 'show-dict-mode'):
return
short_label = self.__prefs.get_value('dict/file/embedded',
'short_label')
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Dictionary mode"), 'symbol' : short_label }
dict_mode_prop = IBus.Property(key=u'DictMode',
prop_type=IBus.PropType.MENU,
label=IBus.Text.new_from_string(label),
symbol=IBus.Text.new_from_string(short_label),
icon=None,
tooltip=IBus.Text.new_from_string(_("Switch dictionary")),
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None)
self.__prop_dict[u'DictMode'] = dict_mode_prop
props = IBus.PropList()
long_label = self.__prefs.get_value('dict/file/embedded',
'long_label')
props.append(IBus.Property(key=u'DictMode.embedded',
prop_type=IBus.PropType.RADIO,
# if long_label is UTF-8
label=IBus.Text.new_from_string(UN(_(long_label))),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
for file in self.__prefs.get_value('dict', 'files'):
if not self.__link_dict_file(file):
continue
id = self.__get_dict_id_from_file(file)
section = 'dict/file/' + id
if not self.__prefs.get_value(section, 'single'):
continue
key = 'DictMode.' + id
long_label = self.__prefs.get_value(section, 'long_label')
# ibus-config 'value-changed' signal updated dict/files but
# not dict/file/new yet.
if long_label == None:
continue
# if long_label is UTF-8
if 'is_system' in self.__prefs.keys(section) and \
self.__prefs.get_value(section, 'is_system'):
uni_long_label = UN(_(long_label))
else:
uni_long_label = UN(long_label)
props.append(IBus.Property(key=UN(key),
prop_type=IBus.PropType.RADIO,
label=IBus.Text.new_from_string(uni_long_label),
icon=None,
tooltip=None,
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.get(Engine.__dict_mode).set_state(IBus.PropState.CHECKED)
i = 0
while props.get(i) != None:
prop = props.get(i)
self.__prop_dict[prop.get_key()] = prop
i += 1
dict_mode_prop.set_sub_props(props)
if update_prop:
# focus-in event will call register_properties().
# Need to switch another IME to update menus on GtkStatusIcon?
anthy_props.update_property(dict_mode_prop)
else:
anthy_props.append(dict_mode_prop)
prop_name = self.__dict_mode_get_prop_name(Engine.__dict_mode)
if prop_name == None:
return
self.__dict_mode_activate(prop_name,
IBus.PropState.CHECKED)
def __set_dict_config_props(self, anthy_props):
if not self.__prefs.get_value('common', 'show-dict-config'):
return
admin_command = self.__prefs.get_value('common', 'dict_admin_command')
icon_path = self.__prefs.get_value('common', 'dict_config_icon')
if not path.exists(admin_command[0]):
return
label = _("Dictionary - Anthy")
# if icon_path is UTF-8
if icon_path and path.exists(icon_path):
icon = UN(icon_path)
else:
# Translators: "Dic" means 'dictionary', One kanji may be good.
label = _("Dic")
icon = u''
dict_prop = IBus.Property(key=u'setup-dict-kasumi',
prop_type=IBus.PropType.MENU,
label=IBus.Text.new_from_string(label),
icon=icon,
tooltip=IBus.Text.new_from_string(_("Configure dictionaries")),
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None)
self.__prop_dict[u'setup-dict-kasumi'] = dict_prop
props = IBus.PropList()
props.append(IBus.Property(key=u'setup-dict-kasumi-admin',
prop_type=IBus.PropType.NORMAL,
label=IBus.Text.new_from_string(_("Edit dictionaries")),
icon=icon,
tooltip=IBus.Text.new_from_string(_("Launch the dictionary tool")),
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
props.append(IBus.Property(key=u'setup-dict-kasumi-word',
prop_type=IBus.PropType.NORMAL,
label=IBus.Text.new_from_string(_("Add words")),
icon=icon,
tooltip=IBus.Text.new_from_string(_("Add words to the dictionary")),
sensitive=True,
visible=True,
state=IBus.PropState.UNCHECKED,
sub_props=None))
i = 0
while props.get(i) != None:
prop = props.get(i)
self.__prop_dict[prop.get_key()] = prop
i += 1
dict_prop.set_sub_props(props)
anthy_props.append(dict_prop)
def __get_clipboard(self, clipboard, text, data):
clipboard_text = clipboard.wait_for_text ()
if data == CLIPBOARD_RECONVERT:
self.__update_reconvert(clipboard_text)
return clipboard_text
def __get_single_dict_files(self):
files = self.__prefs.get_value('dict', 'files')
single_files = []
for file in files:
id = self.__get_dict_id_from_file(file)
section = 'dict/file/' + id
if self.__prefs.get_value(section, 'single'):
single_files.append(file)
return single_files
def __remove_dict_files(self):
for file in self.__prefs.get_value('dict', 'files'):
self.__remove_dict_file(file)
def update_preedit(self, string, attrs, cursor_pos, visible):
text = IBus.Text.new_from_string(string)
i = 0
while attrs.get(i) != None:
attr = attrs.get(i)
text.append_attribute(attr.get_attr_type(),
attr.get_value(),
attr.get_start_index(),
attr.get_end_index())
i += 1
mode = self.__prefs.get_value('common', 'behavior_on_focus_out')
if self.__get_ibus_version() >= 1.003 and mode == 1:
self.update_preedit_text_with_mode(text,
cursor_pos, visible,
IBus.PreeditFocusMode.COMMIT)
else:
self.update_preedit_text(text,
cursor_pos, visible)
def update_aux_string(self, string, attrs, visible):
text = IBus.Text.new_from_string(string)
i = 0
while attrs.get(i) != None:
attr = attrs.get(i)
text.append_attribute(attr.get_attr_type(),
attr.get_value(),
attr.get_start_index(),
attr.get_end_index())
i += 1
self.update_auxiliary_text(text, visible)
def do_page_up(self):
# only process cursor down in convert mode
if self.__convert_mode != CONV_MODE_ANTHY:
return False
if not self.__lookup_table.page_up():
return False
index = self.__lookup_table.get_cursor_pos()
# if candidate is UTF-8
candidate = UN(self.__lookup_table.get_candidate(index).get_text())
self.__segments[self.__cursor_pos] = index, candidate
self.__invalidate()
return True
def do_page_down(self):
# only process cursor down in convert mode
if self.__convert_mode != CONV_MODE_ANTHY:
return False
if not self.__lookup_table.page_down():
return False
index = self.__lookup_table.get_cursor_pos()
# if candidate is UTF-8
candidate = UN(self.__lookup_table.get_candidate(index).get_text())
self.__segments[self.__cursor_pos] = index, candidate
self.__invalidate()
return True
def do_cursor_up(self):
# only process cursor down in convert mode
# if self.__convert_mode != CONV_MODE_ANTHY:
if self.__convert_mode != CONV_MODE_ANTHY and self.__convert_mode != CONV_MODE_PREDICTION:
return False
if not self.__lookup_table.cursor_up():
return False
index = self.__lookup_table.get_cursor_pos()
# if candidate is UTF-8
candidate = UN(self.__lookup_table.get_candidate(index).get_text())
self.__segments[self.__cursor_pos] = index, candidate
self.__invalidate()
return True
def do_cursor_down(self):
# only process cursor down in convert mode
# if self.__convert_mode != CONV_MODE_ANTHY:
if self.__convert_mode != CONV_MODE_ANTHY and self.__convert_mode != CONV_MODE_PREDICTION:
return False
if not self.__lookup_table.cursor_down():
return False
index = self.__lookup_table.get_cursor_pos()
# if candidate is UTF-8
candidate = UN(self.__lookup_table.get_candidate(index).get_text())
self.__segments[self.__cursor_pos] = index, candidate
self.__invalidate()
return True
def do_candidate_clicked(self, index, button, state):
if index == 9:
keyval = IBus.KEY_0
else:
keyval = IBus.KEY_1 + index
self.__on_key_number(keyval)
def __commit_string(self, text):
self.__reset()
self.commit_text(IBus.Text.new_from_string(text))
self.__invalidate()
def __shrink_segment(self, relative_size):
self.__context.resize_segment(self.__cursor_pos, relative_size)
nr_segments = self.__context.get_nr_segments()
del self.__segments[self.__cursor_pos:]
for i in xrange(self.__cursor_pos, nr_segments):
buf = self.__context.get_segment(i, 0)
text = UN(buf)
self.__segments.append((0, text))
self.__lookup_table_visible = False
self.__fill_lookup_table()
self.__invalidate()
return True
def do_process_key_event(self, keyval, keycode, state):
try:
return self.__process_key_event_internal2(keyval, keycode, state)
except:
import traceback
traceback.print_exc()
return False
def do_property_activate(self, prop_name, state):
if state == IBus.PropState.CHECKED:
if prop_name == None:
return
elif prop_name.startswith(u'InputMode.'):
self.__input_mode_activate(prop_name, state)
return
elif prop_name.startswith(u'TypingMode.'):
self.__typing_mode_activate(prop_name, state)
return
elif prop_name.startswith(u'SegmentMode.'):
self.__segment_mode_activate(prop_name, state)
return
elif prop_name.startswith(u'DictMode.'):
self.__dict_mode_activate(prop_name, state)
return
else:
if prop_name == 'setup':
self.__start_setup()
elif prop_name == 'setup-dict-kasumi-admin':
self.__start_dict_admin()
elif prop_name == 'setup-dict-kasumi-word':
self.__start_add_word()
else:
self.__prop_dict[prop_name].set_state(state)
if prop_name == 'DictMode':
sub_name = self.__dict_mode_get_prop_name(self.__dict_mode)
if sub_name == None:
return
self.__dict_mode_activate(sub_name,
IBus.PropState.CHECKED)
def __input_mode_activate(self, prop_name, state):
input_modes = {
u'InputMode.Hiragana' : (INPUT_MODE_HIRAGANA, 'あ'),
u'InputMode.Katakana' : (INPUT_MODE_KATAKANA, 'ア'),
u'InputMode.HalfWidthKatakana' : (INPUT_MODE_HALF_WIDTH_KATAKANA, '_ア'),
u'InputMode.Latin' : (INPUT_MODE_LATIN, '_A'),
u'InputMode.WideLatin' : (INPUT_MODE_WIDE_LATIN, 'A'),
}
if prop_name not in input_modes:
print >> sys.stderr, 'Unknown prop_name = %s' % prop_name
return
self.__prop_dict[prop_name].set_state(state)
self.update_property(self.__prop_dict[prop_name])
mode, symbol = input_modes[prop_name]
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Input mode"), 'symbol' : symbol }
Engine.__input_mode = mode
prop = self.__prop_dict[u'InputMode']
prop.set_symbol(IBus.Text.new_from_string(symbol))
prop.set_label(IBus.Text.new_from_string(label))
self.update_property(prop)
self.__reset()
self.__invalidate()
def __typing_mode_activate(self, prop_name, state):
typing_modes = {
u'TypingMode.Romaji' : (jastring.TYPING_MODE_ROMAJI, 'R'),
u'TypingMode.Kana' : (jastring.TYPING_MODE_KANA, 'か'),
u'TypingMode.ThumbShift' : (jastring.TYPING_MODE_THUMB_SHIFT, '親'),
}
if prop_name not in typing_modes:
print >> sys.stderr, 'Unknown prop_name = %s' % prop_name
return
self.__prop_dict[prop_name].set_state(state)
self.update_property(self.__prop_dict[prop_name])
if prop_name == u'TypingMode.ThumbShift':
self._reset_thumb()
mode, symbol = typing_modes[prop_name]
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Typing method"), 'symbol' : symbol }
Engine.__typing_mode = mode
prop = self.__prop_dict[u'TypingMode']
prop.set_symbol(IBus.Text.new_from_string(symbol))
prop.set_label(IBus.Text.new_from_string(label))
self.update_property(prop)
self.__reset()
self.__invalidate()
def __refresh_typing_mode_property(self):
if u'TypingMode' not in self.__prop_dict:
return
prop = self.__prop_dict[u'TypingMode']
modes = {
jastring.TYPING_MODE_ROMAJI : (u'TypingMode.Romaji', 'R'),
jastring.TYPING_MODE_KANA : (u'TypingMode.Kana', 'か'),
jastring.TYPING_MODE_THUMB_SHIFT : (u'TypingMode.ThumbShift', '親'),
}
prop_name, symbol = modes.get(Engine.__typing_mode, (None, None))
if prop_name == None or symbol == None:
return
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Typing method"), 'symbol' : symbol }
_prop = self.__prop_dict[prop_name]
_prop.set_state(IBus.PropState.CHECKED)
self.update_property(_prop)
prop.set_symbol(IBus.Text.new_from_string(symbol))
prop.set_label(IBus.Text.new_from_string(label))
self.update_property(prop)
def __segment_mode_activate(self, prop_name, state):
segment_modes = {
u'SegmentMode.Multi' : (SEGMENT_DEFAULT, '連'),
u'SegmentMode.Single' : (SEGMENT_SINGLE, '単'),
u'SegmentMode.ImmediateMulti' : (SEGMENT_IMMEDIATE, '逐|連'),
u'SegmentMode.ImmediateSingle' :
(SEGMENT_IMMEDIATE | SEGMENT_SINGLE, '逐|単'),
}
if prop_name not in segment_modes:
print >> sys.stderr, 'Unknown prop_name = %s' % prop_name
return
self.__prop_dict[prop_name].set_state(state)
self.update_property(self.__prop_dict[prop_name])
mode, symbol = segment_modes[prop_name]
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Segment mode"), 'symbol' : symbol }
Engine.__segment_mode = mode
prop = self.__prop_dict[u'SegmentMode']
prop.set_symbol(IBus.Text.new_from_string(symbol))
prop.set_label(IBus.Text.new_from_string(label))
self.update_property(prop)
self.__reset()
self.__invalidate()
def __dict_mode_get_prop_name(self, mode):
if mode == 0:
id = 'embedded'
else:
single_files = self.__get_single_dict_files()
file = single_files[mode - 1]
id = self.__get_dict_id_from_file(file)
return 'DictMode.' + id
def __dict_mode_activate(self, prop_name, state):
if prop_name not in self.__prop_dict.keys():
# The prop_name is added. Need to restart.
return
i = prop_name.find('.')
if i < 0:
return
# The id is already quoted.
id = prop_name[i + 1:]
file = None
single_files = self.__get_single_dict_files()
if id == 'embedded':
pass
else:
found = False
for file in single_files:
if id == self.__get_quoted_id(file):
found = True
break
if found == False:
return
if id == 'embedded':
dict_name = 'default'
Engine.__dict_mode = 0
else:
if file not in single_files:
print >> sys.stderr, "Index error ", file, single_files
return
dict_name = 'ibus__' + id
Engine.__dict_mode = single_files.index(file) + 1
self.__prop_dict[prop_name].set_state(state)
self.update_property(self.__prop_dict[prop_name])
self.__context.init_personality()
# dict_name is unicode but the argument is str.
self.__context.do_set_personality(str(dict_name))
prop = self.__prop_dict[u'DictMode']
section = 'dict/file/' + id
symbol = self.__prefs.get_value(section, 'short_label')
label = _("%(description)s (%(symbol)s)") % \
{ 'description' : _("Dictionary mode"), 'symbol' : symbol }
prop.set_symbol(IBus.Text.new_from_string(symbol))
prop.set_label(IBus.Text.new_from_string(label))
self.update_property(prop)
def __argb(self, a, r, g, b):
return ((a & 0xff)<<24) + ((r & 0xff) << 16) + ((g & 0xff) << 8) + (b & 0xff)
def __rgb(self, r, g, b):
return self.__argb(255, r, g, b)
def do_focus_in(self):
self.register_properties(self.__prop_list)
self.__refresh_typing_mode_property()
mode = self.__prefs.get_value('common', 'behavior_on_focus_out')
if mode == 2:
self.__update_input_chars()
# self.__reset()
# self.__invalidate()
size = self.__prefs.get_value('common', 'page_size')
if size != self.__lookup_table.get_page_size():
self.__lookup_table.set_page_size(size)
def do_focus_out(self):
if self.__has_input_purpose:
self.__input_purpose = 0
mode = self.__prefs.get_value('common', 'behavior_on_focus_out')
if mode == 0 or mode == 1:
self.__reset()
self.__invalidate()
def do_set_content_type(self, purpose, hints):
if self.__has_input_purpose:
self.__input_purpose = purpose
def do_disable(self):
self.__reset()
self.__invalidate()
def do_reset(self):
self.__reset()
self.__invalidate()
def do_destroy(self):
if self.__idle_id != 0:
GLib.source_remove(self.__idle_id)
self.__idle_id = 0
self.__remove_dict_files()
# It seems the parent do_destroy and destroy are different.
# The parent do_destroy calls self destroy infinitely.
super(Engine,self).destroy()
def __join_all_segments(self):
while True:
nr_segments = self.__context.get_nr_segments()
seg = nr_segments - self.__cursor_pos
if seg > 1:
self.__context.resize_segment(self.__cursor_pos, 1)
else:
break
def __normalize_preedit(self, preedit):
if not self.__is_utf8:
return preedit
for key in romaji_normalize_rule.keys():
if preedit.find(key) >= 0:
for value in romaji_normalize_rule[key]:
preedit = preedit.replace(key, value)
return preedit
# begine convert
def __begin_anthy_convert(self):
if Engine.__segment_mode & SEGMENT_IMMEDIATE:
self.__end_anthy_convert()
if self.__convert_mode == CONV_MODE_ANTHY:
return
self.__convert_mode = CONV_MODE_ANTHY
# text, cursor = self.__preedit_ja_string.get_hiragana()
text, cursor = self.__preedit_ja_string.get_hiragana(True)
text = self.__normalize_preedit(text)
self.__context.set_string(text.encode('utf8'))
if Engine.__segment_mode & SEGMENT_SINGLE:
self.__join_all_segments()
nr_segments = self.__context.get_nr_segments()
for i in xrange(0, nr_segments):
buf = self.__context.get_segment(i, 0)
text = UN(buf)
self.__segments.append((0, text))
if Engine.__segment_mode & SEGMENT_IMMEDIATE:
self.__cursor_pos = nr_segments - 1
else:
self.__cursor_pos = 0
self.__fill_lookup_table()
self.__lookup_table_visible = False
def __end_anthy_convert(self):
if self.__convert_mode == CONV_MODE_OFF:
return
self.__convert_mode = CONV_MODE_OFF
self.__convert_chars = u''
self.__segments = list()
self.__cursor_pos = 0
self.__lookup_table.clear()
self.__lookup_table_visible = False
def __end_convert(self):
self.__end_anthy_convert()
# test case 'verudhi' can show U+3046 + U+309B and U+3094
def __candidate_cb(self, candidate):
if not self.__is_utf8:
return
for key in romaji_utf8_rule.keys():
if candidate.find(key) >= 0:
for value in romaji_utf8_rule[key]:
candidate = candidate.replace(key, value)
self.__lookup_table.append_candidate(IBus.Text.new_from_string(candidate))
def __fill_lookup_table(self):
if self.__convert_mode == CONV_MODE_PREDICTION:
nr_predictions = self.__context.get_nr_predictions()
# fill lookup_table
self.__lookup_table.clear()
for i in xrange(0, seg_stat.nr_predictions):
buf = self.__context.get_prediction(i)
candidate = UN(buf)
self.__lookup_table.append_candidate(IBus.Text.new_from_string(candidate))
self.__candidate_cb(candidate)
return
# get segment stat
nr_candidates = self.__context.get_nr_candidates(self.__cursor_pos)
# fill lookup_table
self.__lookup_table.clear()
for i in xrange(0, nr_candidates):
buf = self.__context.get_segment(self.__cursor_pos, i)
candidate = UN(buf)
self.__lookup_table.append_candidate(IBus.Text.new_from_string(candidate))
self.__candidate_cb(candidate)
def __invalidate(self):
if self.__idle_id != 0:
return
self.__idle_id = GLib.idle_add(self.__update,
priority = GLib.PRIORITY_LOW)
# def __get_preedit(self):
def __get_preedit(self, commit=False):
if Engine.__input_mode == INPUT_MODE_HIRAGANA:
# text, cursor = self.__preedit_ja_string.get_hiragana()
text, cursor = self.__preedit_ja_string.get_hiragana(commit)
elif Engine.__input_mode == INPUT_MODE_KATAKANA:
# text, cursor = self.__preedit_ja_string.get_katakana()
text, cursor = self.__preedit_ja_string.get_katakana(commit)
elif Engine.__input_mode == INPUT_MODE_HALF_WIDTH_KATAKANA:
# text, cursor = self.__preedit_ja_string.get_half_width_katakana()
text, cursor = self.__preedit_ja_string.get_half_width_katakana(commit)
else:
text, cursor = u'', 0
return text, cursor
def __update_input_chars(self):
text, cursor = self.__get_preedit()
attrs = IBus.AttrList()
attrs.append(IBus.attr_underline_new(
IBus.AttrUnderline.SINGLE, 0,
len(text)))
self.update_preedit(text,
attrs, cursor, not self.__preedit_ja_string.is_empty())
self.update_aux_string(u'', IBus.AttrList(), False)
self.update_lookup_table(self.__lookup_table,
self.__lookup_table_visible)
def __update_convert_chars(self):
# if self.__convert_mode == CONV_MODE_ANTHY:
if self.__convert_mode == CONV_MODE_ANTHY or self.__convert_mode == CONV_MODE_PREDICTION:
self.__update_anthy_convert_chars()
return
if self.__convert_mode == CONV_MODE_HIRAGANA:
# text, cursor = self.__preedit_ja_string.get_hiragana()
text, cursor = self.__preedit_ja_string.get_hiragana(True)
elif self.__convert_mode == CONV_MODE_KATAKANA:
# text, cursor = self.__preedit_ja_string.get_katakana()
text, cursor = self.__preedit_ja_string.get_katakana(True)
elif self.__convert_mode == CONV_MODE_HALF_WIDTH_KATAKANA:
# text, cursor = self.__preedit_ja_string.get_half_width_katakana()
text, cursor = self.__preedit_ja_string.get_half_width_katakana(True)
elif self.__convert_mode == CONV_MODE_LATIN_0:
text, cursor = self.__preedit_ja_string.get_latin()
if text == text.lower():
self.__convert_mode = CONV_MODE_LATIN_1
elif self.__convert_mode == CONV_MODE_LATIN_1:
text, cursor = self.__preedit_ja_string.get_latin()
text = text.lower()
elif self.__convert_mode == CONV_MODE_LATIN_2:
text, cursor = self.__preedit_ja_string.get_latin()
text = text.upper()
elif self.__convert_mode == CONV_MODE_LATIN_3:
text, cursor = self.__preedit_ja_string.get_latin()
text = text.capitalize()
elif self.__convert_mode == CONV_MODE_WIDE_LATIN_0:
text, cursor = self.__preedit_ja_string.get_wide_latin()
if text == text.lower():
self.__convert_mode = CONV_MODE_WIDE_LATIN_1
elif self.__convert_mode == CONV_MODE_WIDE_LATIN_1:
text, cursor = self.__preedit_ja_string.get_wide_latin()
text = text.lower()
elif self.__convert_mode == CONV_MODE_WIDE_LATIN_2:
text, cursor = self.__preedit_ja_string.get_wide_latin()
text = text.upper()
elif self.__convert_mode == CONV_MODE_WIDE_LATIN_3:
text, cursor = self.__preedit_ja_string.get_wide_latin()
text = text.capitalize()
self.__convert_chars = text
attrs = IBus.AttrList()
attrs.append(IBus.attr_underline_new(
IBus.AttrUnderline.SINGLE, 0, len(text)))
attrs.append(IBus.attr_background_new(self.__rgb(200, 200, 240),
0, len(text)))
attrs.append(IBus.attr_foreground_new(self.__rgb(0, 0, 0),
0, len(text)))
self.update_preedit(text, attrs, len(text), True)
self.update_aux_string(u'',
IBus.AttrList(), self.__lookup_table_visible)
self.update_lookup_table(self.__lookup_table,
self.__lookup_table_visible)
def __update_anthy_convert_chars(self):
self.__convert_chars = u''
pos = 0
for i, (seg_index, text) in enumerate(self.__segments):
self.__convert_chars += text
if i < self.__cursor_pos:
pos += len(text)
attrs = IBus.AttrList()
attrs.append(IBus.attr_underline_new(
IBus.AttrUnderline.SINGLE, 0, len(self.__convert_chars)))
attrs.append(IBus.attr_background_new(self.__rgb(200, 200, 240),
pos, pos + len(self.__segments[self.__cursor_pos][1])))
attrs.append(IBus.attr_foreground_new(self.__rgb(0, 0, 0),
pos, pos + len(self.__segments[self.__cursor_pos][1])))
self.update_preedit(self.__convert_chars, attrs, pos, True)
aux_string = u'( %d / %d )' % (self.__lookup_table.get_cursor_pos() + 1, self.__lookup_table.get_number_of_candidates())
self.update_aux_string(aux_string,
IBus.AttrList(), self.__lookup_table_visible)
self.update_lookup_table(self.__lookup_table,
self.__lookup_table_visible)
def __update(self):
if self.__convert_mode == CONV_MODE_OFF:
self.__update_input_chars()
else:
self.__update_convert_chars()
self.__idle_id = 0
def __on_key_return(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__convert_mode == CONV_MODE_OFF:
# text, cursor = self.__get_preedit()
text, cursor = self.__get_preedit(True)
self.__commit_string(text)
elif self.__convert_mode == CONV_MODE_ANTHY:
for i, (seg_index, text) in enumerate(self.__segments):
self.__context.commit_segment(i, seg_index)
self.__commit_string(self.__convert_chars)
elif self.__convert_mode == CONV_MODE_PREDICTION:
self.__context.commit_prediction(self.__segments[0][0])
self.__commit_string(self.__convert_chars)
else:
self.__commit_string(self.__convert_chars)
return True
def __on_key_escape(self):
if self.__preedit_ja_string.is_empty():
return False
self.__reset()
self.__invalidate()
return True
def __on_key_back_space(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__convert_mode != CONV_MODE_OFF:
if self.__lookup_table_visible:
if self.__lookup_table.get_number_of_candidates() > 0:
self.__lookup_table.set_cursor_pos(0)
candidate = UN(self.__lookup_table.get_candidate(0).get_text())
self.__segments[self.__cursor_pos] = 0, candidate
self.__lookup_table_visible = False
elif self.__segments[self.__cursor_pos][0] != \
NTH_UNCONVERTED_CANDIDATE:
buf = self.__context.get_segment(self.__cursor_pos,
NTH_UNCONVERTED_CANDIDATE)
self.__segments[self.__cursor_pos] = \
NTH_UNCONVERTED_CANDIDATE, UN(buf)
#elif self._chk_mode('25'):
'''
# FIXME: Delete the last char in the active segment.
#
# If we are able to delete a char in the active segment,
# we also should be able to add a char in the active segment.
# Currently plain preedit, no segment mode, i.e.
# using self.__preedit_ja_string, can delete or add a char
# but anthy active segoment mode, i.e.
# using self.__segments, can not delete or add a char.
# Deleting a char could be easy here but adding a char is
# difficult because we need to update both self.__segments
# and self.__preedit_ja_string but self.__preedit_ja_string
# has no segment. To convert self.__segments to
# self.__preedit_ja_string, we may use the reconvert mode
# but no idea to convert keyvals to hiragana
# in self__on_key_common() with multiple key typings.
# Delete a char in the active segment
all_text = u''
nr_segments = self.__context.get_nr_segments()
for i in xrange(0, nr_segments):
buf = self.__context.get_segment(i,
NTH_UNCONVERTED_CANDIDATE)
text = UN(buf)
if i == self.__cursor_pos and len(text) > 0:
text = text[:len(text) - 1]
all_text += text
if all_text == u'':
return
# Set self.__preedit_ja_string by anthy context.
self.__preedit_ja_string = jastring.JaString(Engine.__typing_mode,
self.__latin_with_shift)
self.__convert_chars = self.__normalize_preedit(all_text)
for i in xrange(0, len(self.__convert_chars)):
keyval = self.__convert_chars[i]
self.__preedit_ja_string.insert(unichr(ord (keyval)))
self.__context.set_string(self.__convert_chars.encode('utf8'))
# Set self.__segments by anty context
# for editable self.__segments,
# save NTH_UNCONVERTED_CANDIDATE
nr_segments = self.__context.get_nr_segments()
if self.__cursor_pos >= nr_segments and \
nr_segments > 0:
self.__cursor_pos = nr_segments - 1
for i in xrange(self.__cursor_pos, nr_segments):
if i == self.__cursor_pos:
index = NTH_UNCONVERTED_CANDIDATE
else:
index = 0
buf = self.__context.get_segment(i,
index)
text = UN(buf)
self.__segments[i] = index, text
# Update self.__lookup_table
self.__fill_lookup_table()
'''
else:
self.__end_convert()
else:
self.__preedit_ja_string.remove_before()
self.__invalidate()
return True
def __on_key_delete(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__convert_mode != CONV_MODE_OFF:
self.__end_convert()
else:
self.__preedit_ja_string.remove_after()
self.__invalidate()
return True
'''def __on_key_hiragana_katakana(self):
if self.__convert_mode == CONV_MODE_ANTHY:
self.__end_anthy_convert()
if Engine.__input_mode >= INPUT_MODE_HIRAGANA and \
Engine.__input_mode < INPUT_MODE_HALF_WIDTH_KATAKANA:
Engine.__input_mode += 1
else:
Engine.__input_mode = INPUT_MODE_HIRAGANA
modes = { INPUT_MODE_HIRAGANA: 'あ',
INPUT_MODE_KATAKANA: 'ア',
INPUT_MODE_HALF_WIDTH_KATAKANA: '_ア' }
prop = self.__prop_dict[u'InputMode']
label = modes[Engine.__input_mode]
prop.set_label(IBus.Text.new_from_string(label))
self.update_property(prop)
self.__invalidate()
return True'''
'''def __on_key_muhenka(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__convert_mode == CONV_MODE_ANTHY:
self.__end_anthy_convert()
new_mode = CONV_MODE_HIRAGANA
if self.__convert_mode < CONV_MODE_WIDE_LATIN_3 and \
self.__convert_mode >= CONV_MODE_HIRAGANA :
self.__convert_mode += 1
else:
self.__convert_mode = CONV_MODE_HIRAGANA
self.__invalidate()
return True'''
'''def __on_key_henkan(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__convert_mode != CONV_MODE_ANTHY:
self.__begin_anthy_convert()
self.__invalidate()
elif self.__convert_mode == CONV_MODE_ANTHY:
self.__lookup_table_visible = True
self.do_cursor_down()
return True'''
'''def __on_key_space(self, wide=False):
if Engine.__input_mode == INPUT_MODE_WIDE_LATIN or wide:
# Input Wide space U+3000
wide_char = symbol_rule[unichr(IBus.KEY_space)]
self.__commit_string(wide_char)
return True
if self.__preedit_ja_string.is_empty():
if Engine.__input_mode in (INPUT_MODE_HIRAGANA, INPUT_MODE_KATAKANA):
# Input Wide space U+3000
wide_char = symbol_rule[unichr(IBus.KEY_space)]
self.__commit_string(wide_char)
return True
else:
# Input Half space U+0020
self.__commit_string(unichr(IBus.KEY_space))
return True
if self.__convert_mode != CONV_MODE_ANTHY:
self.__begin_anthy_convert()
self.__invalidate()
elif self.__convert_mode == CONV_MODE_ANTHY:
self.__lookup_table_visible = True
self.do_cursor_down()
return True'''
def __on_key_up(self):
if self.__preedit_ja_string.is_empty():
return False
self.__lookup_table_visible = True
self.do_cursor_up()
return True
def __on_key_down(self):
if self.__preedit_ja_string.is_empty():
return False
self.__lookup_table_visible = True
self.do_cursor_down()
return True
def __on_key_page_up(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__lookup_table_visible == True:
self.do_page_up()
return True
def __on_key_page_down(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__lookup_table_visible == True:
self.do_page_down()
return True
'''def __on_key_left(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__convert_mode == CONV_MODE_OFF:
self.__preedit_ja_string.move_cursor(-1)
self.__invalidate()
return True
if self.__convert_mode != CONV_MODE_ANTHY:
return True
if self.__cursor_pos == 0:
return True
self.__cursor_pos -= 1
self.__lookup_table_visible = False
self.__fill_lookup_table()
self.__invalidate()
return True'''
def __on_key_right(self):
if self.__preedit_ja_string.is_empty():
return False
if self.__convert_mode == CONV_MODE_OFF:
self.__preedit_ja_string.move_cursor(1)
self.__invalidate()
return True
if self.__convert_mode != CONV_MODE_ANTHY:
return True
if self.__cursor_pos + 1 >= len(self.__segments):
return True
self.__cursor_pos += 1
self.__lookup_table_visible = False
self.__fill_lookup_table()
self.__invalidate()
return True
def __on_key_number(self, keyval):
if self.__convert_mode != CONV_MODE_ANTHY:
return False
if not self.__lookup_table_visible:
return False
if keyval == IBus.KEY_0:
keyval = IBus.KEY_9 + 1
index = keyval - IBus.KEY_1
return self.__on_candidate_index_in_page(index)
def __on_key_conv(self, mode):
if self.__preedit_ja_string.is_empty():
return False
if self.__convert_mode == CONV_MODE_ANTHY:
self.__end_anthy_convert()
if mode == 0 or mode == 1:
if self.__convert_mode == CONV_MODE_HIRAGANA + mode:
return True
self.__convert_mode = CONV_MODE_HIRAGANA + mode
elif mode == 2:
if self.__convert_mode == CONV_MODE_HALF_WIDTH_KATAKANA:
return True
self.__convert_mode = CONV_MODE_HALF_WIDTH_KATAKANA
elif mode == 3:
if CONV_MODE_WIDE_LATIN_0 <= self.__convert_mode <= CONV_MODE_WIDE_LATIN_3:
self.__convert_mode += 1
if self.__convert_mode > CONV_MODE_WIDE_LATIN_3:
self.__convert_mode = CONV_MODE_WIDE_LATIN_1
else:
self.__convert_mode = CONV_MODE_WIDE_LATIN_0
elif mode == 4:
if CONV_MODE_LATIN_0 <= self.__convert_mode <= CONV_MODE_LATIN_3:
self.__convert_mode += 1
if self.__convert_mode > CONV_MODE_LATIN_3:
self.__convert_mode = CONV_MODE_LATIN_1
else:
self.__convert_mode = CONV_MODE_LATIN_0
else:
print >> sys.stderr, 'Unkown convert mode (%d)!' % mode
return False
self.__invalidate()
return True
def __on_key_common(self, keyval, state=0):
# If use-system-layout is FALSE in ibus 1.4.y or lower,
# ibus converts the keymap and ibus-anthy needed to use
# self.__commit_string
# ibus 1.5.y uses XKB directly so Latin mode can return FALSE.
if Engine.__input_mode == INPUT_MODE_LATIN:
return False
elif Engine.__input_mode == INPUT_MODE_WIDE_LATIN:
# Input Wide Latin chars
char = unichr(keyval)
wide_char = None#symbol_rule.get(char, None)
if wide_char == None:
wide_char = unichar_half_to_full(char)
self.__commit_string(wide_char)
return True
# Input Japanese
if Engine.__segment_mode & SEGMENT_IMMEDIATE:
# Commit nothing
pass
elif self.__convert_mode == CONV_MODE_ANTHY:
for i, (seg_index, text) in enumerate(self.__segments):
self.__context.commit_segment(i, seg_index)
self.__commit_string(self.__convert_chars)
elif self.__convert_mode != CONV_MODE_OFF:
self.__commit_string(self.__convert_chars)
# 'n' + '\'' == 'nn' in romaji
if (keyval >= ord('A') and keyval <= ord('Z')) or \
(keyval >= ord('a') and keyval <= ord('z')):
shift = (state & IBus.ModifierType.SHIFT_MASK) != 0
else:
shift = False
self.__preedit_ja_string.set_shift(shift)
self.__preedit_ja_string.insert(unichr(keyval))
if Engine.__segment_mode & SEGMENT_IMMEDIATE:
self.__begin_anthy_convert()
self.__invalidate()
return True
#=======================================================================
@classmethod
def CONFIG_RELOADED(cls, bus):
if config.DEBUG:
print 'RELOADED'
if not cls.__prefs:
cls.__prefs = AnthyPrefs(bus)
cls._init_prefs()
cls.__keybind = cls._mk_keybind()
jastring.JaString.SET_PREFS(cls.__prefs)
@classmethod
def CONFIG_VALUE_CHANGED(cls, bus, section, name, variant):
if config.DEBUG:
print 'VALUE_CHAMGED =', section, name, variant
if not section.startswith('engine/anthy'):
# This value is used for IBus.config.set_value only.
return
# The key was deleted by dconf.
# test case: update /desktop/ibus/engine/anthy/thumb/ls
# and reset the key with dconf direclty.
if variant.get_type_string() == '()':
cls.__prefs.undo_item(section, name)
return
value = cls.__prefs.variant_to_value(variant)
base_sec = section[len(cls.__prefs._prefix) + 1:]
sec = cls._get_shortcut_type()
if base_sec == sec:
cmd = '_Engine__cmd_' + name
old = cls.__prefs.get_value(sec, name)
value = value if value != [''] else []
for s in set(old).difference(value):
cls.__keybind.get(cls._s_to_key(s), []).remove(cmd)
keys = cls.__prefs.keys(sec)
for s in set(value).difference(old):
cls.__keybind.setdefault(cls._s_to_key(s), []).append(cmd)
cls.__keybind.get(cls._s_to_key(s)).sort(
lambda a, b: cmp(keys.index(a[13:]), keys.index(b[13:])))
cls.__prefs.set_value(sec, name, value)
elif base_sec == 'common':
cls.__prefs.set_value(base_sec, name, value)
if name == 'shortcut_type':
cls.__keybind = cls._mk_keybind()
if name == 'latin_with_shift':
cls.__latin_with_shift = value
jastring.JaString.RESET(cls.__prefs, base_sec, name, value)
elif base_sec.startswith('kana_typing_rule'):
jastring.JaString.RESET(cls.__prefs, base_sec, name, value)
@classmethod
def _init_prefs(cls):
prefs = cls.__prefs
value = prefs.get_value('common', 'latin_with_shift')
cls.__latin_with_shift = value
@classmethod
def _mk_keybind(cls):
keybind = {}
sec = cls._get_shortcut_type()
for k in cls.__prefs.keys(sec):
cmd = '_Engine__cmd_' + k
for s in cls.__prefs.get_value(sec, k):
keybind.setdefault(cls._s_to_key(s), []).append(cmd)
return keybind
@classmethod
def _get_shortcut_type(cls):
try:
t = 'shortcut/' + cls.__prefs.get_value('common', 'shortcut_type')
except:
t = 'shortcut/default'
return t
@classmethod
def _s_to_key(cls, s):
keyval = IBus.keyval_from_name(s.split('+')[-1])
s = s.lower()
state = ('shift+' in s and IBus.ModifierType.SHIFT_MASK or 0) | (
'ctrl+' in s and IBus.ModifierType.CONTROL_MASK or 0) | (
'alt+' in s and IBus.ModifierType.MOD1_MASK or 0)
return cls._mk_key(keyval, state)
@classmethod
def _reset_thumb(cls):
if cls.__thumb == None:
import thumb
cls.__thumb = thumb.ThumbShiftKeyboard(cls.__prefs)
else:
cls.__thumb.reset()
@staticmethod
def _mk_key(keyval, state):
if state & (IBus.ModifierType.CONTROL_MASK | IBus.ModifierType.MOD1_MASK):
if keyval < 0xff and \
unichr(keyval) in u'!"#$%^\'()*+,-./:;<=>?@[\]^_`{|}~':
state |= IBus.ModifierType.SHIFT_MASK
elif IBus.KEY_a <= keyval <= IBus.KEY_z:
keyval -= (IBus.KEY_a - IBus.KEY_A)
return repr([int(state), int(keyval)])
def process_key_event_thumb(self, keyval, keycode, state):
if self.__thumb == None:
self._reset_thumb()
def on_timeout(keyval):
if self._MM:
insert(self.__thumb.get_char(self._MM)[self._SS])
else:
cmd_exec([0, RS(), LS()][self._SS])
self._H = None
def start(t):
self._H = GLib.timeout_add(t, on_timeout, keyval)
def stop():
if self._H:
GLib.source_remove(self._H)
self._H = None
return True
return False
def insert(keyval):
try:
self._MM = self._SS = 0
ret = self.__on_key_common(ord(keyval))
if (keyval in u',.、。' and
self.__prefs.get_value('common', 'behavior_on_period')):
return self.__cmd_convert(keyval, state)
return ret
except:
pass
def cmd_exec(keyval, state=0):
key = self._mk_key(keyval, state)
for cmd in self.__keybind.get(key, []):
if config.DEBUG:
print 'cmd =', cmd
try:
if getattr(self, cmd)(keyval, state):
return True
except:
print >> sys.stderr, 'Unknown command = %s' % cmd
return False
def RS():
return self.__thumb.get_rs()
def LS():
return self.__thumb.get_ls()
def T1():
return self.__thumb.get_t1()
def T2():
return self.__thumb.get_t2()
state = state & (IBus.ModifierType.SHIFT_MASK |
IBus.ModifierType.CONTROL_MASK |
IBus.ModifierType.MOD1_MASK |
IBus.ModifierType.RELEASE_MASK)
if keyval in KP_Table and self.__prefs.get_value('common',
'ten_key_mode'):
keyval = KP_Table[keyval]
if state & IBus.ModifierType.RELEASE_MASK:
if keyval == self._MM:
if stop():
insert(self.__thumb.get_char(self._MM)[self._SS])
self._MM = 0
elif (1 if keyval == RS() else 2) == self._SS:
if stop():
cmd_exec([0, RS(), LS()][self._SS])
self._SS = 0
if keyval in [RS(), LS()]:
self._RSS = 0
elif keyval == self._RMM:
self._RMM = 0
else:
if keyval in [LS(), RS()] and state == 0:
if self._SS:
stop()
cmd_exec([0, RS(), LS()][self._SS])
self._SS = 1 if keyval == RS() else 2
start(T1())
elif self._MM:
stop()
self._RMM = self._MM
self._RSS = 1 if keyval == RS() else 2
insert(self.__thumb.get_char(self._MM)[1 if keyval == RS() else 2])
else:
if self._RSS == (1 if keyval == RS() else 2):
if self._RMM:
insert(self.__thumb.get_char(self._RMM)[self._RSS])
else:
self._SS = 1 if keyval == RS() else 2
start(T1())
elif keyval in self.__thumb.get_chars() and state == 0:
if self._MM:
stop()
insert(self.__thumb.get_char(self._MM)[self._SS])
start(T2())
self._MM = keyval
elif self._SS:
stop()
self._RMM = keyval
self._RSS = self._SS
insert(self.__thumb.get_char(keyval)[self._SS])
else:
if self._RMM == keyval:
if self._RSS:
insert(self.__thumb.get_char(self._RMM)[self._RSS])
else:
if cmd_exec(keyval, state):
return True
start(T2())
self._MM = keyval
else:
if self._MM:
stop()
insert(self.__thumb.get_char(self._MM)[self._SS])
elif self._SS:
stop()
cmd_exec([0, RS(), LS()][self._SS])
if cmd_exec(keyval, state):
return True
elif 0x21 <= keyval <= 0x7e and state & \
(IBus.ModifierType.CONTROL_MASK | IBus.ModifierType.MOD1_MASK) == 0:
if state & IBus.ModifierType.SHIFT_MASK:
insert(self.__thumb.get_shift_char(keyval, unichr(keyval)))
elif self._SS == 0:
insert(unichr(keyval))
else:
if not self.__preedit_ja_string.is_empty():
return True
return False
return True
def __process_key_event_internal2(self, keyval, keycode, state):
if self.__has_input_purpose and \
self.__input_purpose == IBus.InputPurpose.PASSWORD:
return False
if Engine.__typing_mode == jastring.TYPING_MODE_THUMB_SHIFT and \
Engine.__input_mode not in [INPUT_MODE_LATIN, INPUT_MODE_WIDE_LATIN]:
return self.process_key_event_thumb(keyval, keycode, state)
is_press = (state & IBus.ModifierType.RELEASE_MASK) == 0
state = state & (IBus.ModifierType.SHIFT_MASK |
IBus.ModifierType.CONTROL_MASK |
IBus.ModifierType.MOD1_MASK)
# ignore key release events
if not is_press:
return False
if keyval in KP_Table and self.__prefs.get_value('common',
'ten_key_mode'):
keyval = KP_Table[keyval]
key = self._mk_key(keyval, state)
for cmd in self.__keybind.get(key, []):
if config.DEBUG:
print 'cmd =', cmd
try:
if getattr(self, cmd)(keyval, state):
return True
except:
print >> sys.stderr, 'Unknown command = %s' % cmd
if state & (IBus.ModifierType.CONTROL_MASK | IBus.ModifierType.MOD1_MASK):
return False
if (IBus.KEY_exclam <= keyval <= IBus.KEY_asciitilde or
keyval == IBus.KEY_yen):
if Engine.__typing_mode == jastring.TYPING_MODE_KANA:
if keyval == IBus.KEY_0 and state == IBus.ModifierType.SHIFT_MASK:
keyval = IBus.KEY_asciitilde
elif keyval == IBus.KEY_backslash and keycode in [132-8, 133-8]:
keyval = IBus.KEY_yen
ret = self.__on_key_common(keyval, state)
if (Engine.__input_mode != INPUT_MODE_LATIN and
unichr(keyval) in u',.' and
self.__prefs.get_value('common', 'behavior_on_period')):
return self.__cmd_convert(keyval, state)
return ret
else:
if not self.__preedit_ja_string.is_empty():
return True
return False
def _chk_mode(self, mode):
if '0' in mode and self.__preedit_ja_string.is_empty():
return True
if self.__convert_mode == CONV_MODE_OFF:
if '1' in mode and not self.__preedit_ja_string.is_empty():
return True
elif self.__convert_mode == CONV_MODE_ANTHY:
if '2' in mode and not self.__lookup_table_visible:
return True
elif self.__convert_mode == CONV_MODE_PREDICTION:
if '3' in mode and not self.__lookup_table_visible:
return True
else:
if '4' in mode:
return True
if '5' in mode and self.__lookup_table_visible:
return True
return False
def __get_quoted_id(self, file):
id = file
has_mbcs = False
for i in xrange(0, len(id)):
if ord(id[i]) >= 0x7f:
has_mbcs = True
break
if has_mbcs:
id = id.encode('hex')
if id.find('/') >=0:
id = id[id.rindex('/') + 1:]
if id.find('.') >=0:
id = id[:id.rindex('.')]
if id.startswith('0x'):
id = id.encode('hex')
has_mbcs = True
if has_mbcs:
id = '0x' + id
return id
def __get_dict_id_from_file(self, file):
return self.__get_quoted_id(file)
def __link_dict_file_with_id(self, file, id, link_mode):
if id == None:
return
if link_mode == LINK_DICT_EMBEDDED:
directory = get_userhome() + '/.anthy/' + IMPORTED_EMBEDDED_DICT_DIR
name = IMPORTED_EMBEDDED_DICT_PREFIX + id
elif link_mode == LINK_DICT_SINGLE:
directory = get_userhome() + '/.anthy'
name = IMPORTED_SINGLE_DICT_PREFIX + id
else:
return
if path.exists(directory):
if not path.isdir(directory):
print >> sys.stderr, directory + ' is not a directory'
return
else:
os.makedirs(directory, 0700)
backup_dir = os.getcwd()
os.chdir(directory)
if path.lexists(directory + '/' + name):
if path.islink(directory + '/' + name):
print >> sys.stderr, 'Removing ' + name
os.unlink(directory + '/' + name)
else:
alternate = name + str(os.getpid())
print >> sys.stderr, 'Moving ' + name + ' to ' + alternate
os.rename(name, alternate)
os.symlink(file, directory + '/' + name)
if backup_dir != None:
os.chdir(backup_dir)
def __remove_dict_file_with_id(self, file, id, link_mode):
if id == None:
return
if link_mode == LINK_DICT_EMBEDDED:
directory = get_userhome() + '/.anthy/' + IMPORTED_EMBEDDED_DICT_DIR
name = IMPORTED_EMBEDDED_DICT_PREFIX + id
elif link_mode == LINK_DICT_SINGLE:
directory = get_userhome() + '/.anthy'
name = IMPORTED_SINGLE_DICT_PREFIX + id
else:
return
if path.exists(directory):
if not path.isdir(directory):
print >> sys.stderr, directory + ' is not a directory'
return
backup_dir = os.getcwd()
os.chdir(directory)
if path.lexists(directory + '/' + name):
os.unlink(directory + '/' + name)
if backup_dir != None:
os.chdir(backup_dir)
def __link_dict_file(self, file):
if not path.exists(file):
print >> sys.stderr, file + ' does not exist'
return False
id = self.__get_dict_id_from_file(file)
section = 'dict/file/' + id
if section not in self.__prefs.sections():
self.__fetch_dict_values(section)
if self.__prefs.get_value(section, 'embed'):
self.__link_dict_file_with_id(file, id, LINK_DICT_EMBEDDED)
if self.__prefs.get_value(section, 'single'):
self.__link_dict_file_with_id(file, id, LINK_DICT_SINGLE)
return True
def __remove_dict_file(self, file):
id = self.__get_dict_id_from_file(file)
section = 'dict/file/' + id
if section not in self.__prefs.sections():
self.__fetch_dict_values(section)
if self.__prefs.get_value(section, 'embed'):
self.__remove_dict_file_with_id(file, id, LINK_DICT_EMBEDDED)
if self.__prefs.get_value(section, 'single'):
self.__remove_dict_file_with_id(file, id, LINK_DICT_SINGLE)
def __set_dict_files_value(self, base_sec, name, value):
if name == 'files':
str_list = []
for file in value:
str_list.append(self.__prefs.str(file))
old_files = self.__prefs.get_value(base_sec, name)
for file in old_files:
if file in str_list:
continue
self.__remove_dict_file(file)
for file in str_list:
if file in old_files:
continue
self.__link_dict_file(file)
self.__prefs.set_value(base_sec, name, str_list)
else:
self.__prefs.set_value(base_sec, name, value)
def __fetch_dict_values(self, section):
self.__prefs.set_new_section(section)
self.__prefs.set_new_key(section, 'short_label')
self.__prefs.set_no_key_warning(True)
self.__prefs.fetch_item(section, 'short_label')
self.__prefs.set_new_key(section, 'long_label')
self.__prefs.fetch_item(section, 'long_label')
self.__prefs.set_new_key(section, 'embed')
self.__prefs.fetch_item(section, 'embed')
self.__prefs.set_new_key(section, 'single')
self.__prefs.fetch_item(section, 'single')
self.__prefs.set_new_key(section, 'reverse')
self.__prefs.fetch_item(section, 'reverse')
self.__prefs.set_no_key_warning(False)
def __config_value_changed_cb(self, ibus_config, section, name, variant):
if config.DEBUG:
print 'VALUE_CHAMGED =', section, name, variant
if not section.startswith('engine/anthy'):
# This value is used for IBus.config.set_value only.
return
# The key was deleted by dconf.
# test case: update /desktop/ibus/engine/anthy/thumb/ls
# and reset the key with dconf direclty.
if variant.get_type_string() == '()':
self.__prefs.undo_item(section, name)
return
value = self.__prefs.variant_to_value(variant)
base_sec = section[len(self.__prefs._prefix) + 1:]
sec = self._get_shortcut_type()
if base_sec == 'thumb':
self.__prefs.set_value(base_sec, name, value)
self._reset_thumb()
elif base_sec == 'dict':
self.__set_dict_files_value(base_sec, name, value)
self.__set_dict_mode_props(self.__prop_list, True)
elif base_sec.startswith('dict/file/'):
if base_sec not in self.__prefs.sections():
self.__fetch_dict_values(base_sec)
self.__prefs.set_value(base_sec, name, value)
self.__set_dict_mode_props(self.__prop_list, True)
elif base_sec:
self.__prefs.set_value(base_sec, name, value)
else:
self.__prefs.set_value(section, name, value)
#mod_keys
def __set_input_mode(self, mode):
self.__input_mode_activate(mode, IBus.PropState.CHECKED)
self.__reset()
self.__invalidate()
return True
def __unset_current_input_mode(self):
modes = {
INPUT_MODE_HIRAGANA: u'InputMode.Hiragana',
INPUT_MODE_KATAKANA: u'InputMode.Katakana',
INPUT_MODE_HALF_WIDTH_KATAKANA: u'InputMode.HalfWidthKatakana',
INPUT_MODE_LATIN: u'InputMode.Latin',
INPUT_MODE_WIDE_LATIN: u'InputMode.WideLatin'
}
self.__input_mode_activate(modes[Engine.__input_mode],
IBus.PropState.UNCHECKED)
def __cmd_on_off(self, keyval, state):
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_input_mode()
if Engine.__input_mode == INPUT_MODE_LATIN:
return self.__set_input_mode(u'InputMode.Hiragana')
else:
return self.__set_input_mode(u'InputMode.Latin')
def __cmd_circle_input_mode(self, keyval, state):
modes = {
INPUT_MODE_HIRAGANA: u'InputMode.Katakana',
INPUT_MODE_KATAKANA: u'InputMode.HalfWidthKatakana',
INPUT_MODE_HALF_WIDTH_KATAKANA: u'InputMode.Latin',
INPUT_MODE_LATIN: u'InputMode.WideLatin',
INPUT_MODE_WIDE_LATIN: u'InputMode.Hiragana'
}
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_input_mode()
return self.__set_input_mode(modes[Engine.__input_mode])
def __cmd_circle_kana_mode(self, keyval, state):
modes = {
INPUT_MODE_HIRAGANA: u'InputMode.Katakana',
INPUT_MODE_KATAKANA: u'InputMode.HalfWidthKatakana',
INPUT_MODE_HALF_WIDTH_KATAKANA: u'InputMode.Hiragana',
INPUT_MODE_LATIN: u'InputMode.Hiragana',
INPUT_MODE_WIDE_LATIN: u'InputMode.Hiragana'
}
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_input_mode()
return self.__set_input_mode(modes[Engine.__input_mode])
def __cmd_latin_mode(self, keyval, state):
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_input_mode()
return self.__set_input_mode(u'InputMode.Latin')
def __cmd_wide_latin_mode(self, keyval, state):
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_input_mode()
return self.__set_input_mode(u'InputMode.WideLatin')
def __cmd_hiragana_mode(self, keyval, state):
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_input_mode()
return self.__set_input_mode(u'InputMode.Hiragana')
def __cmd_katakana_mode(self, keyval, state):
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_input_mode()
return self.__set_input_mode(u'InputMode.Katakana')
def __cmd_half_katakana(self, keyval, state):
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_input_mode()
return self.__set_input_mode(u'InputMode.HalfWidthKatakana')
# def __cmd_cancel_pseudo_ascii_mode_key(self, keyval, state):
# pass
def __unset_current_typing_mode(self):
modes = {
jastring.TYPING_MODE_ROMAJI: u'TypingMode.Romaji',
jastring.TYPING_MODE_KANA: u'TypingMode.Kana',
jastring.TYPING_MODE_THUMB_SHIFT: u'TypingMode.ThumbShift',
}
self.__typing_mode_activate(modes[Engine.__typing_mode],
IBus.PropState.UNCHECKED)
def __cmd_circle_typing_method(self, keyval, state):
if not self._chk_mode('0'):
return False
modes = {
jastring.TYPING_MODE_THUMB_SHIFT: u'TypingMode.Romaji',
jastring.TYPING_MODE_KANA: u'TypingMode.ThumbShift',
jastring.TYPING_MODE_ROMAJI: u'TypingMode.Kana',
}
# ibus 1.5 or later needs to send UNCHECKED
self.__unset_current_typing_mode()
self.__typing_mode_activate(modes[Engine.__typing_mode],
IBus.PropState.CHECKED)
return True
def __cmd_circle_dict_method(self, keyval, state):
if not self._chk_mode('0'):
return False
# ibus 1.5 or later needs to send UNCHECKED
prop_name = self.__dict_mode_get_prop_name(Engine.__dict_mode)
if prop_name != None:
self.__dict_mode_activate(prop_name,
IBus.PropState.UNCHECKED)
single_files = self.__get_single_dict_files()
new_mode = Engine.__dict_mode + 1
if new_mode > len(single_files):
new_mode = 0
Engine.__dict_mode = new_mode
prop_name = self.__dict_mode_get_prop_name(Engine.__dict_mode)
if prop_name == None:
return False
self.__dict_mode_activate(prop_name,
IBus.PropState.CHECKED)
return True
#edit_keys
def __cmd_insert_space(self, keyval, state):
if Engine.__input_mode == INPUT_MODE_LATIN:
return False
if (self.__prefs.get_value('common', 'half_width_space') or
Engine.__input_mode == INPUT_MODE_HALF_WIDTH_KATAKANA):
return self.__cmd_insert_half_space(keyval, state)
else:
return self.__cmd_insert_wide_space(keyval, state)
def __cmd_insert_alternate_space(self, keyval, state):
if Engine.__input_mode == INPUT_MODE_LATIN:
return False
if (self.__prefs.get_value('common', 'half_width_space') or
Engine.__input_mode == INPUT_MODE_HALF_WIDTH_KATAKANA):
return self.__cmd_insert_wide_space(keyval, state)
else:
return self.__cmd_insert_half_space(keyval, state)
def __cmd_insert_half_space(self, keyval, state):
if not self._chk_mode('0'):
return False
if not self.__preedit_ja_string.is_empty():
return False
self.__commit_string(unichr(IBus.KEY_space))
return True
def __cmd_insert_wide_space(self, keyval, state):
if not self._chk_mode('0'):
return False
if not self.__preedit_ja_string.is_empty():
return False
char = unichr(IBus.KEY_space)
wide_char = symbol_rule.get(char, None)
if wide_char == None:
wide_char = unichar_half_to_full(char)
self.__commit_string(wide_char)
return True
def __cmd_backspace(self, keyval, state):
if not self._chk_mode('12345'):
return False
return self.__on_key_back_space()
def __cmd_delete(self, keyval, state):
if not self._chk_mode('12345'):
return False
return self.__on_key_delete()
def __cmd_commit(self, keyval, state):
if not self._chk_mode('12345'):
return False
return self.__on_key_return()
def __cmd_convert(self, keyval, state):
if not self._chk_mode('14'):
return False
self.__begin_anthy_convert()
self.__invalidate()
return True
def __cmd_predict(self, keyval, state):
if not self._chk_mode('14'):
return False
text, cursor = self.__preedit_ja_string.get_hiragana(True)
self.__context.set_prediction_string(text.encode('utf8'))
nr_predictions = self.__context.get_nr_predictions()
# for i in range(nr_predictions):
# print self.__context.get_prediction(i)
buf = self.__context.get_prediction(0)
if not buf:
return False
text = UN(buf)
self.__segments.append((0, text))
self.__convert_mode = CONV_MODE_PREDICTION
self.__cursor_pos = 0
self.__fill_lookup_table()
self.__lookup_table_visible = False
self.__invalidate()
return True
def __cmd_cancel(self, keyval, state):
return self.__cmd_cancel_all(keyval, state)
def __cmd_cancel_all(self, keyval, state):
if not self._chk_mode('12345'):
return False
if self.__convert_mode == CONV_MODE_OFF:
return self.__on_key_escape()
else:
self.__end_convert()
self.__invalidate()
return True
def __cmd_reconvert(self, keyval, state):
if not self.__preedit_ja_string.is_empty():
# if user has inputed some chars
return False
# Move importing Gtk into Engine from the header
# because ibus-engine-anthy --xml does not requre to open X.
try:
from gi.repository import Gtk
clipboard_get = Gtk.Clipboard.get
except ImportError:
clipboard_get = lambda a : None
except RuntimeError:
# Do we support the engine without display?
print >> sys.stderr, "Gtk couldn't be initialized"
print >> sys.stderr, 'Could not open display'
clipboard_get = lambda a : None
# Use Gtk.Clipboard.request_text() instead of
# Gtk.Clipboard.wait_for_text() because DBus is timed out.
clipboard = clipboard_get ('PRIMARY')
if clipboard:
clipboard.request_text (self.__get_clipboard, CLIPBOARD_RECONVERT)
return True
def __update_reconvert(self, clipboard_text):
if clipboard_text == None:
return False
self.__convert_chars = UN(clipboard_text)
for i in xrange(0, len(self.__convert_chars)):
keyval = self.__convert_chars[i]
self.__preedit_ja_string.insert(unichr(ord (keyval)))
self.__context.set_string(self.__convert_chars.encode('utf-8'))
nr_segments = self.__context.get_nr_segments()
for i in xrange(0, nr_segments):
buf = self.__context.get_segment(i, 0)
text = UN(buf)
self.__segments.append((0, text))
self.__convert_mode = CONV_MODE_ANTHY
self.__cursor_pos = 0
self.__fill_lookup_table()
self.__lookup_table_visible = False
self.__invalidate()
return True
# def __cmd_do_nothing(self, keyval, state):
# return True
#caret_keys
def __move_caret(self, i):
if not self._chk_mode('1'):
return False
if self.__convert_mode == CONV_MODE_OFF:
self.__preedit_ja_string.move_cursor(
-len(self.__preedit_ja_string.get_latin()[0]) if i == 0 else
i if i in [-1, 1] else
len(self.__preedit_ja_string.get_latin()[0]))
self.__invalidate()
return True
return False
def __cmd_move_caret_first(self, keyval, state):
return self.__move_caret(0)
def __cmd_move_caret_last(self, keyval, state):
return self.__move_caret(2)
def __cmd_move_caret_forward(self, keyval, state):
return self.__move_caret(1)
def __cmd_move_caret_backward(self, keyval, state):
return self.__move_caret(-1)
#segments_keys
def __select_segment(self, i):
if not self._chk_mode('25'):
return False
pos = 0 if i == 0 else \
self.__cursor_pos + i if i in [-1, 1] else \
len(self.__segments) - 1
if 0 <= pos < len(self.__segments) and pos != self.__cursor_pos:
self.__cursor_pos = pos
self.__lookup_table_visible = False
self.__fill_lookup_table()
self.__invalidate()
return True
def __cmd_select_first_segment(self, keyval, state):
return self.__select_segment(0)
def __cmd_select_last_segment(self, keyval, state):
return self.__select_segment(2)
def __cmd_select_next_segment(self, keyval, state):
return self.__select_segment(1)
def __cmd_select_prev_segment(self, keyval, state):
return self.__select_segment(-1)
def __cmd_shrink_segment(self, keyval, state):
if not self._chk_mode('25'):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
self.__shrink_segment(-1)
return True
def __cmd_expand_segment(self, keyval, state):
if not self._chk_mode('25'):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
self.__shrink_segment(1)
return True
def __move_cursor_char_length(self, length):
if Engine.__input_mode == INPUT_MODE_HIRAGANA:
self.__preedit_ja_string.move_cursor_hiragana_length(length)
elif Engine.__input_mode == INPUT_MODE_KATAKANA:
self.__preedit_ja_string.move_cursor_katakana_length(length)
elif Engine.__input_mode == INPUT_MODE_HALF_WIDTH_KATAKANA:
self.__preedit_ja_string.move_cursor_half_with_katakana_length(length)
else:
self.__preedit_ja_string.move_cursor(length)
def __commit_nth_segment(self, commit_index, keyval, state):
if commit_index >= len(self.__segments):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
for i in xrange(0, commit_index + 1):
(seg_index, text) = self.__segments[i]
self.commit_text(IBus.Text.new_from_string(text))
text, cursor = self.__get_preedit()
commit_length = 0
for i in xrange(0, commit_index + 1):
buf = self.__context.get_segment(i, NTH_UNCONVERTED_CANDIDATE)
commit_length += len(UN(buf))
self.__move_cursor_char_length(commit_length - cursor)
for i in xrange(0, commit_length):
self.__preedit_ja_string.remove_before()
self.__move_cursor_char_length(cursor - commit_length)
del self.__segments[0:commit_index + 1]
if len(self.__segments) == 0:
self.__reset()
else:
if self.__cursor_pos > commit_index:
self.__cursor_pos -= (commit_index + 1)
else:
self.__cursor_pos = 0
text, cursor = self.__get_preedit()
self.__convert_chars = text
self.__context.set_string(text.encode ('utf-8'))
self.__lookup_table.clear()
self.__lookup_table.set_cursor_visible(False)
self.__lookup_table_visible = False
self.update_aux_string(u'', IBus.AttrList(),
self.__lookup_table_visible)
self.__fill_lookup_table()
self.__invalidate()
self.__update_input_chars()
return True
def __cmd_commit_first_segment(self, keyval, state):
return self.__commit_nth_segment(0, keyval, state)
def __cmd_commit_selected_segment(self, keyval, state):
return self.__commit_nth_segment(self.__cursor_pos, keyval, state)
#candidates_keys
def __on_candidate_index_in_page(self, index):
if not self._chk_mode('5'):
return False
if index >= self.__lookup_table.get_page_size():
return False
cursor_pos = self.__lookup_table.get_cursor_pos()
cursor_in_page = self.__lookup_table.get_cursor_in_page()
real_index = cursor_pos - cursor_in_page + index
if real_index >= self.__lookup_table.get_number_of_candidates():
return False
self.__lookup_table.set_cursor_pos(real_index)
index = self.__lookup_table.get_cursor_pos()
candidate = UN(self.__lookup_table.get_candidate(index).get_text())
self.__segments[self.__cursor_pos] = index, candidate
self.__lookup_table_visible = False
self.__on_key_right()
self.__invalidate()
return True
def __cmd_select_first_candidate(self, keyval, state):
return self.__on_candidate_index_in_page(0)
def __cmd_select_last_candidate(self, keyval, state):
return self.__on_candidate_index_in_page(
self.__lookup_table.get_page_size() - 1)
def __cmd_select_next_candidate(self, keyval, state):
if not self._chk_mode('235'):
return False
return self.__on_key_down()
def __cmd_select_prev_candidate(self, keyval, state):
if not self._chk_mode('235'):
return False
return self.__on_key_up()
def __cmd_candidates_page_up(self, keyval, state):
if not self._chk_mode('5'):
return False
return self.__on_key_page_up()
def __cmd_candidates_page_down(self, keyval, state):
if not self._chk_mode('5'):
return False
return self.__on_key_page_down()
#direct_select_keys
def __select_keyval(self, keyval):
if not self._chk_mode('5'):
return False
return self.__on_key_number(keyval)
def __cmd_select_candidates_1(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_2(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_3(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_4(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_5(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_6(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_7(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_8(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_9(self, keyval, state):
return self.__select_keyval(keyval)
def __cmd_select_candidates_0(self, keyval, state):
return self.__select_keyval(keyval)
#convert_keys
def __cmd_convert_to_char_type_forward(self, keyval, state):
if self.__convert_mode == CONV_MODE_ANTHY:
n = self.__segments[self.__cursor_pos][0]
if n == NTH_HIRAGANA_CANDIDATE:
return self.__convert_segment_to_kana(NTH_KATAKANA_CANDIDATE)
elif n == NTH_KATAKANA_CANDIDATE:
return self.__convert_segment_to_kana(NTH_HALFKANA_CANDIDATE)
elif n == NTH_HALFKANA_CANDIDATE:
return self.__convert_segment_to_latin(-100)
elif n == -100:
return self.__convert_segment_to_latin(-101)
else:
return self.__convert_segment_to_kana(NTH_HIRAGANA_CANDIDATE)
if self.__convert_mode == CONV_MODE_KATAKANA:
return self.__cmd_convert_to_half_katakana(keyval, state)
elif self.__convert_mode == CONV_MODE_HALF_WIDTH_KATAKANA:
return self.__cmd_convert_to_latin(keyval, state)
elif CONV_MODE_LATIN_0 <= self.__convert_mode <= CONV_MODE_LATIN_3:
return self.__cmd_convert_to_wide_latin(keyval, state)
elif (CONV_MODE_WIDE_LATIN_0 <= self.__convert_mode
<= CONV_MODE_WIDE_LATIN_3):
return self.__cmd_convert_to_hiragana(keyval, state)
else:
return self.__cmd_convert_to_katakana(keyval, state)
def __cmd_convert_to_char_type_backward(self, keyval, state):
if self.__convert_mode == CONV_MODE_ANTHY:
n = self.__segments[self.__cursor_pos][0]
if n == NTH_KATAKANA_CANDIDATE:
return self.__convert_segment_to_kana(NTH_HIRAGANA_CANDIDATE)
elif n == NTH_HALFKANA_CANDIDATE:
return self.__convert_segment_to_kana(NTH_KATAKANA_CANDIDATE)
elif n == -100:
return self.__convert_segment_to_kana(NTH_HALFKANA_CANDIDATE)
elif n == -101:
return self.__convert_segment_to_latin(-100)
else:
return self.__convert_segment_to_latin(-101)
if self.__convert_mode == CONV_MODE_KATAKANA:
return self.__cmd_convert_to_hiragana(keyval, state)
elif self.__convert_mode == CONV_MODE_HALF_WIDTH_KATAKANA:
return self.__cmd_convert_to_katakana(keyval, state)
elif CONV_MODE_LATIN_0 <= self.__convert_mode <= CONV_MODE_LATIN_3:
return self.__cmd_convert_to_half_katakana(keyval, state)
elif (CONV_MODE_WIDE_LATIN_0 <= self.__convert_mode
<= CONV_MODE_WIDE_LATIN_3):
return self.__cmd_convert_to_latin(keyval, state)
else:
return self.__cmd_convert_to_wide_latin(keyval, state)
def __convert_segment_to_kana(self, n):
if self.__convert_mode == CONV_MODE_ANTHY and -4 <= n <= -2:
buf = self.__context.get_segment(self.__cursor_pos, n)
self.__segments[self.__cursor_pos] = n, UN(buf)
self.__lookup_table_visible = False
self.__invalidate()
return True
return False
def __cmd_convert_to_hiragana(self, keyval, state):
if not self._chk_mode('12345'):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
return self.__convert_segment_to_kana(NTH_HIRAGANA_CANDIDATE)
return self.__on_key_conv(0)
def __cmd_convert_to_katakana(self, keyval, state):
if not self._chk_mode('12345'):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
return self.__convert_segment_to_kana(NTH_KATAKANA_CANDIDATE)
return self.__on_key_conv(1)
def __cmd_convert_to_half(self, keyval, state):
if not self._chk_mode('12345'):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
i, s = self.__segments[self.__cursor_pos]
if i == -101:
return self.__convert_segment_to_latin(-100)
elif i == -100:
return self.__convert_segment_to_latin(-100)
return self.__convert_segment_to_kana(NTH_HALFKANA_CANDIDATE)
elif CONV_MODE_WIDE_LATIN_0 <= self.__convert_mode <= CONV_MODE_WIDE_LATIN_3:
return self.__on_key_conv(4)
elif CONV_MODE_LATIN_0 <= self.__convert_mode <= CONV_MODE_LATIN_3:
return self.__on_key_conv(4)
return self.__on_key_conv(2)
def __cmd_convert_to_half_katakana(self, keyval, state):
if not self._chk_mode('12345'):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
return self.__convert_segment_to_kana(NTH_HALFKANA_CANDIDATE)
return self.__on_key_conv(2)
def __convert_segment_to_latin(self, n):
if self.__convert_mode == CONV_MODE_ANTHY and n in [-100, -101]:
start = 0
for i in range(self.__cursor_pos):
start += len(UN(self.__context.get_segment(i, NTH_UNCONVERTED_CANDIDATE)))
end = start + len(UN(self.__context.get_segment(self.__cursor_pos, NTH_UNCONVERTED_CANDIDATE)))
i, s = self.__segments[self.__cursor_pos]
s2 = self.__preedit_ja_string.get_raw(start, end)
if n == -101:
s2 = u''.join([unichar_half_to_full(c) for c in s2])
if i == n:
if s == s2.lower():
s2 = s2.upper()
elif s == s2.upper():
s2 = s2.capitalize()
elif s == s2 or s == s2.capitalize():
s2 = s2.lower()
self.__segments[self.__cursor_pos] = n, s2
self.__lookup_table_visible = False
self.__invalidate()
return True
return False
def __cmd_convert_to_wide_latin(self, keyval, state):
if not self._chk_mode('12345'):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
return self.__convert_segment_to_latin(-101)
return self.__on_key_conv(3)
def __cmd_convert_to_latin(self, keyval, state):
if not self._chk_mode('12345'):
return False
if self.__convert_mode == CONV_MODE_ANTHY:
return self.__convert_segment_to_latin(-100)
return self.__on_key_conv(4)
#dictonary_keys
def __cmd_dict_admin(self, keyval, state):
if not self._chk_mode('0'):
return False
self.__start_dict_admin()
return True
def __cmd_add_word(self, keyval, state):
if not self._chk_mode('0'):
return False
self.__start_add_word()
return True
def __cmd_start_setup(self, keyval, state):
if not self._chk_mode('0'):
return False
self.__start_setup()
return True
def __start_dict_admin(self):
command = self.__prefs.get_value('common', 'dict_admin_command')
os.spawnl(os.P_NOWAIT, *command)
def __start_add_word(self):
command = self.__prefs.get_value('common', 'add_word_command')
os.spawnl(os.P_NOWAIT, *command)
def __start_setup(self):
if Engine.__setup_pid != 0:
pid, state = os.waitpid(Engine.__setup_pid, os.P_NOWAIT)
if pid != Engine.__setup_pid:
return
Engine.__setup_pid = 0
setup_cmd = path.join(config.LIBEXECDIR, 'ibus-setup-anthy')
Engine.__setup_pid = os.spawnl(os.P_NOWAIT, setup_cmd, 'ibus-setup-anthy')
def __cmd_hiragana_for_latin_with_shift(self, keyval, state):
self.__preedit_ja_string.set_hiragana_katakana(True)
| ./CrossVul/dataset_final_sorted/CWE-255/py/good_5754_0 |
crossvul-python_data_bad_5024_0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
| This file is part of the web2py Web Framework
| Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
| License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Contains the classes for the global used variables:
- Request
- Response
- Session
"""
from gluon.storage import Storage, List
from gluon.streamer import streamer, stream_file_or_304_or_206, DEFAULT_CHUNK_SIZE
from gluon.xmlrpc import handler
from gluon.contenttype import contenttype
from gluon.html import xmlescape, TABLE, TR, PRE, URL
from gluon.http import HTTP, redirect
from gluon.fileutils import up
from gluon.serializers import json, custom_json
import gluon.settings as settings
from gluon.utils import web2py_uuid, secure_dumps, secure_loads
from gluon.settings import global_settings
from gluon import recfile
from gluon.cache import CacheInRam
from gluon.fileutils import copystream
import hashlib
import portalocker
try:
import cPickle as pickle
except:
import pickle
from pickle import Pickler, MARK, DICT, EMPTY_DICT
from types import DictionaryType
import cStringIO
import datetime
import re
import copy_reg
import Cookie
import os
import sys
import traceback
import threading
import cgi
import urlparse
import copy
import tempfile
FMT = '%a, %d-%b-%Y %H:%M:%S PST'
PAST = 'Sat, 1-Jan-1971 00:00:00'
FUTURE = 'Tue, 1-Dec-2999 23:59:59'
try:
from gluon.contrib.minify import minify
have_minify = True
except ImportError:
have_minify = False
try:
import simplejson as sj # external installed library
except:
try:
import json as sj # standard installed library
except:
import gluon.contrib.simplejson as sj # pure python library
regex_session_id = re.compile('^([\w\-]+/)?[\w\-\.]+$')
__all__ = ['Request', 'Response', 'Session']
current = threading.local() # thread-local storage for request-scope globals
css_template = '<link href="%s" rel="stylesheet" type="text/css" />'
js_template = '<script src="%s" type="text/javascript"></script>'
coffee_template = '<script src="%s" type="text/coffee"></script>'
typescript_template = '<script src="%s" type="text/typescript"></script>'
less_template = '<link href="%s" rel="stylesheet/less" type="text/css" />'
css_inline = '<style type="text/css">\n%s\n</style>'
js_inline = '<script type="text/javascript">\n%s\n</script>'
template_mapping = {
'css': css_template,
'js': js_template,
'coffee': coffee_template,
'ts': typescript_template,
'less': less_template,
'css:inline': css_inline,
'js:inline': js_inline
}
# IMPORTANT:
# this is required so that pickled dict(s) and class.__dict__
# are sorted and web2py can detect without ambiguity when a session changes
class SortingPickler(Pickler):
def save_dict(self, obj):
self.write(EMPTY_DICT if self.bin else MARK + DICT)
self.memoize(obj)
self._batch_setitems([(key, obj[key]) for key in sorted(obj)])
SortingPickler.dispatch = copy.copy(Pickler.dispatch)
SortingPickler.dispatch[DictionaryType] = SortingPickler.save_dict
def sorting_dumps(obj, protocol=None):
file = cStringIO.StringIO()
SortingPickler(file, protocol).dump(obj)
return file.getvalue()
# END #####################################################################
def copystream_progress(request, chunk_size=10 ** 5):
"""
Copies request.env.wsgi_input into request.body
and stores progress upload status in cache_ram
X-Progress-ID:length and X-Progress-ID:uploaded
"""
env = request.env
if not env.get('CONTENT_LENGTH', None):
return cStringIO.StringIO()
source = env['wsgi.input']
try:
size = int(env['CONTENT_LENGTH'])
except ValueError:
raise HTTP(400, "Invalid Content-Length header")
try: # Android requires this
dest = tempfile.NamedTemporaryFile()
except NotImplementedError: # and GAE this
dest = tempfile.TemporaryFile()
if not 'X-Progress-ID' in request.get_vars:
copystream(source, dest, size, chunk_size)
return dest
cache_key = 'X-Progress-ID:' + request.get_vars['X-Progress-ID']
cache_ram = CacheInRam(request) # same as cache.ram because meta_storage
cache_ram(cache_key + ':length', lambda: size, 0)
cache_ram(cache_key + ':uploaded', lambda: 0, 0)
while size > 0:
if size < chunk_size:
data = source.read(size)
cache_ram.increment(cache_key + ':uploaded', size)
else:
data = source.read(chunk_size)
cache_ram.increment(cache_key + ':uploaded', chunk_size)
length = len(data)
if length > size:
(data, length) = (data[:size], size)
size -= length
if length == 0:
break
dest.write(data)
if length < chunk_size:
break
dest.seek(0)
cache_ram(cache_key + ':length', None)
cache_ram(cache_key + ':uploaded', None)
return dest
class Request(Storage):
"""
Defines the request object and the default values of its members
- env: environment variables, by gluon.main.wsgibase()
- cookies
- get_vars
- post_vars
- vars
- folder
- application
- function
- args
- extension
- now: datetime.datetime.now()
- utcnow : datetime.datetime.utcnow()
- is_local
- is_https
- restful()
"""
def __init__(self, env):
Storage.__init__(self)
self.env = Storage(env)
self.env.web2py_path = global_settings.applications_parent
self.env.update(global_settings)
self.cookies = Cookie.SimpleCookie()
self._get_vars = None
self._post_vars = None
self._vars = None
self._body = None
self.folder = None
self.application = None
self.function = None
self.args = List()
self.extension = 'html'
self.now = datetime.datetime.now()
self.utcnow = datetime.datetime.utcnow()
self.is_restful = False
self.is_https = False
self.is_local = False
self.global_settings = settings.global_settings
self._uuid = None
def parse_get_vars(self):
"""Takes the QUERY_STRING and unpacks it to get_vars
"""
query_string = self.env.get('query_string', '')
dget = urlparse.parse_qs(query_string, keep_blank_values=1) # Ref: https://docs.python.org/2/library/cgi.html#cgi.parse_qs
get_vars = self._get_vars = Storage(dget)
for (key, value) in get_vars.iteritems():
if isinstance(value, list) and len(value) == 1:
get_vars[key] = value[0]
def parse_post_vars(self):
"""Takes the body of the request and unpacks it into
post_vars. application/json is also automatically parsed
"""
env = self.env
post_vars = self._post_vars = Storage()
body = self.body
# if content-type is application/json, we must read the body
is_json = env.get('content_type', '')[:16] == 'application/json'
if is_json:
try:
json_vars = sj.load(body)
except:
# incoherent request bodies can still be parsed "ad-hoc"
json_vars = {}
pass
# update vars and get_vars with what was posted as json
if isinstance(json_vars, dict):
post_vars.update(json_vars)
body.seek(0)
# parse POST variables on POST, PUT, BOTH only in post_vars
if (body and not is_json
and env.request_method in ('POST', 'PUT', 'DELETE', 'BOTH')):
query_string = env.pop('QUERY_STRING', None)
dpost = cgi.FieldStorage(fp=body, environ=env, keep_blank_values=1)
try:
post_vars.update(dpost)
except:
pass
if query_string is not None:
env['QUERY_STRING'] = query_string
# The same detection used by FieldStorage to detect multipart POSTs
body.seek(0)
def listify(a):
return (not isinstance(a, list) and [a]) or a
try:
keys = sorted(dpost)
except TypeError:
keys = []
for key in keys:
if key is None:
continue # not sure why cgi.FieldStorage returns None key
dpk = dpost[key]
# if an element is not a file replace it with
# its value else leave it alone
pvalue = listify([(_dpk if _dpk.filename else _dpk.value)
for _dpk in dpk]
if isinstance(dpk, list) else
(dpk if dpk.filename else dpk.value))
if len(pvalue):
post_vars[key] = (len(pvalue) > 1 and pvalue) or pvalue[0]
@property
def body(self):
if self._body is None:
try:
self._body = copystream_progress(self)
except IOError:
raise HTTP(400, "Bad Request - HTTP body is incomplete")
return self._body
def parse_all_vars(self):
"""Merges get_vars and post_vars to vars
"""
self._vars = copy.copy(self.get_vars)
for key, value in self.post_vars.iteritems():
if key not in self._vars:
self._vars[key] = value
else:
if not isinstance(self._vars[key], list):
self._vars[key] = [self._vars[key]]
self._vars[key] += value if isinstance(value, list) else [value]
@property
def get_vars(self):
"""Lazily parses the query string into get_vars
"""
if self._get_vars is None:
self.parse_get_vars()
return self._get_vars
@property
def post_vars(self):
"""Lazily parse the body into post_vars
"""
if self._post_vars is None:
self.parse_post_vars()
return self._post_vars
@property
def vars(self):
"""Lazily parses all get_vars and post_vars to fill vars
"""
if self._vars is None:
self.parse_all_vars()
return self._vars
@property
def uuid(self):
"""Lazily uuid
"""
if self._uuid is None:
self.compute_uuid()
return self._uuid
def compute_uuid(self):
self._uuid = '%s/%s.%s.%s' % (
self.application,
self.client.replace(':', '_'),
self.now.strftime('%Y-%m-%d.%H-%M-%S'),
web2py_uuid())
return self._uuid
def user_agent(self):
from gluon.contrib import user_agent_parser
session = current.session
user_agent = session._user_agent
if user_agent:
return user_agent
user_agent = user_agent_parser.detect(self.env.http_user_agent)
for key, value in user_agent.items():
if isinstance(value, dict):
user_agent[key] = Storage(value)
user_agent = session._user_agent = Storage(user_agent)
return user_agent
def requires_https(self):
"""
If request comes in over HTTP, redirects it to HTTPS
and secures the session.
"""
cmd_opts = global_settings.cmd_options
# checking if this is called within the scheduler or within the shell
# in addition to checking if it's not a cronjob
if ((cmd_opts and (cmd_opts.shell or cmd_opts.scheduler))
or global_settings.cronjob or self.is_https):
current.session.secure()
else:
current.session.forget()
redirect(URL(scheme='https', args=self.args, vars=self.vars))
def restful(self):
def wrapper(action, request=self):
def f(_action=action, *a, **b):
request.is_restful = True
env = request.env
is_json = env.content_type=='application/json'
method = env.request_method
if len(request.args) and '.' in request.args[-1]:
request.args[-1], _, request.extension = request.args[-1].rpartition('.')
current.response.headers['Content-Type'] = \
contenttype('.' + request.extension.lower())
rest_action = _action().get(method, None)
if not (rest_action and method == method.upper()
and callable(rest_action)):
raise HTTP(405, "method not allowed")
try:
vars = request.vars
if method == 'POST' and is_json:
body = request.body.read()
if len(body):
vars = sj.loads(body)
res = rest_action(*request.args, **vars)
if is_json and not isinstance(res, str):
res = json(res)
return res
except TypeError, e:
exc_type, exc_value, exc_traceback = sys.exc_info()
if len(traceback.extract_tb(exc_traceback)) == 1:
raise HTTP(400, "invalid arguments")
else:
raise
f.__doc__ = action.__doc__
f.__name__ = action.__name__
return f
return wrapper
class Response(Storage):
"""
Defines the response object and the default values of its members
response.write( ) can be used to write in the output html
"""
def __init__(self):
Storage.__init__(self)
self.status = 200
self.headers = dict()
self.headers['X-Powered-By'] = 'web2py'
self.body = cStringIO.StringIO()
self.session_id = None
self.cookies = Cookie.SimpleCookie()
self.postprocessing = []
self.flash = '' # used by the default view layout
self.meta = Storage() # used by web2py_ajax.html
self.menu = [] # used by the default view layout
self.files = [] # used by web2py_ajax.html
self._vars = None
self._caller = lambda f: f()
self._view_environment = None
self._custom_commit = None
self._custom_rollback = None
self.generic_patterns = ['*']
self.delimiters = ('{{', '}}')
self.formstyle = 'table3cols'
self.form_label_separator = ': '
def write(self, data, escape=True):
if not escape:
self.body.write(str(data))
else:
self.body.write(xmlescape(data))
def render(self, *a, **b):
from compileapp import run_view_in
if len(a) > 2:
raise SyntaxError(
'Response.render can be called with two arguments, at most')
elif len(a) == 2:
(view, self._vars) = (a[0], a[1])
elif len(a) == 1 and isinstance(a[0], str):
(view, self._vars) = (a[0], {})
elif len(a) == 1 and hasattr(a[0], 'read') and callable(a[0].read):
(view, self._vars) = (a[0], {})
elif len(a) == 1 and isinstance(a[0], dict):
(view, self._vars) = (None, a[0])
else:
(view, self._vars) = (None, {})
self._vars.update(b)
self._view_environment.update(self._vars)
if view:
import cStringIO
(obody, oview) = (self.body, self.view)
(self.body, self.view) = (cStringIO.StringIO(), view)
run_view_in(self._view_environment)
page = self.body.getvalue()
self.body.close()
(self.body, self.view) = (obody, oview)
else:
run_view_in(self._view_environment)
page = self.body.getvalue()
return page
def include_meta(self):
s = "\n"
for meta in (self.meta or {}).iteritems():
k, v = meta
if isinstance(v, dict):
s += '<meta' + ''.join(' %s="%s"' % (xmlescape(key), xmlescape(v[key])) for key in v) +' />\n'
else:
s += '<meta name="%s" content="%s" />\n' % (k, xmlescape(v))
self.write(s, escape=False)
def include_files(self, extensions=None):
"""
Includes files (usually in the head).
Can minify and cache local files
By default, caches in ram for 5 minutes. To change,
response.cache_includes = (cache_method, time_expire).
Example: (cache.disk, 60) # caches to disk for 1 minute.
"""
files = []
ext_files = []
has_js = has_css = False
for item in self.files:
if isinstance(item, (list, tuple)):
ext_files.append(item)
continue
if extensions and not item.rpartition('.')[2] in extensions:
continue
if item in files:
continue
if item.endswith('.js'):
has_js = True
if item.endswith('.css'):
has_css = True
files.append(item)
if have_minify and ((self.optimize_css and has_css) or (self.optimize_js and has_js)):
# cache for 5 minutes by default
key = hashlib.md5(repr(files)).hexdigest()
cache = self.cache_includes or (current.cache.ram, 60 * 5)
def call_minify(files=files):
return minify.minify(files,
URL('static', 'temp'),
current.request.folder,
self.optimize_css,
self.optimize_js)
if cache:
cache_model, time_expire = cache
files = cache_model('response.files.minified/' + key,
call_minify,
time_expire)
else:
files = call_minify()
files.extend(ext_files)
s = []
for item in files:
if isinstance(item, str):
f = item.lower().split('?')[0]
ext = f.rpartition('.')[2]
# if static_version we need also to check for
# static_version_urls. In that case, the _.x.x.x
# bit would have already been added by the URL()
# function
if self.static_version and not self.static_version_urls:
item = item.replace(
'/static/', '/static/_%s/' % self.static_version, 1)
tmpl = template_mapping.get(ext)
if tmpl:
s.append(tmpl % item)
elif isinstance(item, (list, tuple)):
f = item[0]
tmpl = template_mapping.get(f)
if tmpl:
s.append(tmpl % item[1])
self.write(''.join(s), escape=False)
def stream(self,
stream,
chunk_size=DEFAULT_CHUNK_SIZE,
request=None,
attachment=False,
filename=None
):
"""
If in a controller function::
return response.stream(file, 100)
the file content will be streamed at 100 bytes at the time
Args:
stream: filename or read()able content
chunk_size(int): Buffer size
request: the request object
attachment(bool): prepares the correct headers to download the file
as an attachment. Usually creates a pop-up download window
on browsers
filename(str): the name for the attachment
Note:
for using the stream name (filename) with attachments
the option must be explicitly set as function parameter (will
default to the last request argument otherwise)
"""
headers = self.headers
# for attachment settings and backward compatibility
keys = [item.lower() for item in headers]
if attachment:
if filename is None:
attname = ""
else:
attname = filename
headers["Content-Disposition"] = \
'attachment;filename="%s"' % attname
if not request:
request = current.request
if isinstance(stream, (str, unicode)):
stream_file_or_304_or_206(stream,
chunk_size=chunk_size,
request=request,
headers=headers,
status=self.status)
# ## the following is for backward compatibility
if hasattr(stream, 'name'):
filename = stream.name
if filename and not 'content-type' in keys:
headers['Content-Type'] = contenttype(filename)
if filename and not 'content-length' in keys:
try:
headers['Content-Length'] = \
os.path.getsize(filename)
except OSError:
pass
env = request.env
# Internet Explorer < 9.0 will not allow downloads over SSL unless caching is enabled
if request.is_https and isinstance(env.http_user_agent, str) and \
not re.search(r'Opera', env.http_user_agent) and \
re.search(r'MSIE [5-8][^0-9]', env.http_user_agent):
headers['Pragma'] = 'cache'
headers['Cache-Control'] = 'private'
if request and env.web2py_use_wsgi_file_wrapper:
wrapped = env.wsgi_file_wrapper(stream, chunk_size)
else:
wrapped = streamer(stream, chunk_size=chunk_size)
return wrapped
def download(self, request, db, chunk_size=DEFAULT_CHUNK_SIZE, attachment=True, download_filename=None):
"""
Example of usage in controller::
def download():
return response.download(request, db)
Downloads from http://..../download/filename
"""
from pydal.exceptions import NotAuthorizedException, NotFoundException
current.session.forget(current.response)
if not request.args:
raise HTTP(404)
name = request.args[-1]
items = re.compile('(?P<table>.*?)\.(?P<field>.*?)\..*').match(name)
if not items:
raise HTTP(404)
(t, f) = (items.group('table'), items.group('field'))
try:
field = db[t][f]
except AttributeError:
raise HTTP(404)
try:
(filename, stream) = field.retrieve(name, nameonly=True)
except NotAuthorizedException:
raise HTTP(403)
except NotFoundException:
raise HTTP(404)
except IOError:
raise HTTP(404)
headers = self.headers
headers['Content-Type'] = contenttype(name)
if download_filename is None:
download_filename = filename
if attachment:
headers['Content-Disposition'] = \
'attachment; filename="%s"' % download_filename.replace('"', '\"')
return self.stream(stream, chunk_size=chunk_size, request=request)
def json(self, data, default=None):
if 'Content-Type' not in self.headers:
self.headers['Content-Type'] = 'application/json'
return json(data, default=default or custom_json)
def xmlrpc(self, request, methods):
"""
assuming::
def add(a, b):
return a+b
if a controller function \"func\"::
return response.xmlrpc(request, [add])
the controller will be able to handle xmlrpc requests for
the add function. Example::
import xmlrpclib
connection = xmlrpclib.ServerProxy(
'http://hostname/app/contr/func')
print connection.add(3, 4)
"""
return handler(request, self, methods)
def toolbar(self):
from gluon.html import DIV, SCRIPT, BEAUTIFY, TAG, A
BUTTON = TAG.button
admin = URL("admin", "default", "design", extension='html',
args=current.request.application)
from gluon.dal import DAL
dbstats = []
dbtables = {}
infos = DAL.get_instances()
for k, v in infos.iteritems():
dbstats.append(TABLE(*[TR(PRE(row[0]), '%.2fms' % (row[1]*1000))
for row in v['dbstats']]))
dbtables[k] = dict(defined=v['dbtables']['defined'] or '[no defined tables]',
lazy=v['dbtables']['lazy'] or '[no lazy tables]')
u = web2py_uuid()
backtotop = A('Back to top', _href="#totop-%s" % u)
# Convert lazy request.vars from property to Storage so they
# will be displayed in the toolbar.
request = copy.copy(current.request)
request.update(vars=current.request.vars,
get_vars=current.request.get_vars,
post_vars=current.request.post_vars)
return DIV(
BUTTON('design', _onclick="document.location='%s'" % admin),
BUTTON('request',
_onclick="jQuery('#request-%s').slideToggle()" % u),
BUTTON('response',
_onclick="jQuery('#response-%s').slideToggle()" % u),
BUTTON('session',
_onclick="jQuery('#session-%s').slideToggle()" % u),
BUTTON('db tables',
_onclick="jQuery('#db-tables-%s').slideToggle()" % u),
BUTTON('db stats',
_onclick="jQuery('#db-stats-%s').slideToggle()" % u),
DIV(BEAUTIFY(request), backtotop,
_class="w2p-toolbar-hidden", _id="request-%s" % u),
DIV(BEAUTIFY(current.session), backtotop,
_class="w2p-toolbar-hidden", _id="session-%s" % u),
DIV(BEAUTIFY(current.response), backtotop,
_class="w2p-toolbar-hidden", _id="response-%s" % u),
DIV(BEAUTIFY(dbtables), backtotop,
_class="w2p-toolbar-hidden", _id="db-tables-%s" % u),
DIV(BEAUTIFY(dbstats), backtotop,
_class="w2p-toolbar-hidden", _id="db-stats-%s" % u),
SCRIPT("jQuery('.w2p-toolbar-hidden').hide()"),
_id="totop-%s" % u
)
class Session(Storage):
"""
Defines the session object and the default values of its members (None)
- session_storage_type : 'file', 'db', or 'cookie'
- session_cookie_compression_level :
- session_cookie_expires : cookie expiration
- session_cookie_key : for encrypted sessions in cookies
- session_id : a number or None if no session
- session_id_name :
- session_locked :
- session_masterapp :
- session_new : a new session obj is being created
- session_hash : hash of the pickled loaded session
- session_pickled : picked session
if session in cookie:
- session_data_name : name of the cookie for session data
if session in db:
- session_db_record_id
- session_db_table
- session_db_unique_key
if session in file:
- session_file
- session_filename
"""
def connect(self,
request=None,
response=None,
db=None,
tablename='web2py_session',
masterapp=None,
migrate=True,
separate=None,
check_client=False,
cookie_key=None,
cookie_expires=None,
compression_level=None
):
"""
Used in models, allows to customize Session handling
Args:
request: the request object
response: the response object
db: to store/retrieve sessions in db (a table is created)
tablename(str): table name
masterapp(str): points to another's app sessions. This enables a
"SSO" environment among apps
migrate: passed to the underlying db
separate: with True, creates a folder with the 2 initials of the
session id. Can also be a function, e.g. ::
separate=lambda(session_name): session_name[-2:]
check_client: if True, sessions can only come from the same ip
cookie_key(str): secret for cookie encryption
cookie_expires: sets the expiration of the cookie
compression_level(int): 0-9, sets zlib compression on the data
before the encryption
"""
from gluon.dal import Field
request = request or current.request
response = response or current.response
masterapp = masterapp or request.application
cookies = request.cookies
self._unlock(response)
response.session_masterapp = masterapp
response.session_id_name = 'session_id_%s' % masterapp.lower()
response.session_data_name = 'session_data_%s' % masterapp.lower()
response.session_cookie_expires = cookie_expires
response.session_client = str(request.client).replace(':', '.')
response.session_cookie_key = cookie_key
response.session_cookie_compression_level = compression_level
# check if there is a session_id in cookies
try:
old_session_id = cookies[response.session_id_name].value
except KeyError:
old_session_id = None
response.session_id = old_session_id
# if we are supposed to use cookie based session data
if cookie_key:
response.session_storage_type = 'cookie'
elif db:
response.session_storage_type = 'db'
else:
response.session_storage_type = 'file'
# why do we do this?
# because connect may be called twice, by web2py and in models.
# the first time there is no db yet so it should do nothing
if (global_settings.db_sessions is True
or masterapp in global_settings.db_sessions):
return
if response.session_storage_type == 'cookie':
# check if there is session data in cookies
if response.session_data_name in cookies:
session_cookie_data = cookies[response.session_data_name].value
else:
session_cookie_data = None
if session_cookie_data:
data = secure_loads(session_cookie_data, cookie_key,
compression_level=compression_level)
if data:
self.update(data)
response.session_id = True
# else if we are supposed to use file based sessions
elif response.session_storage_type == 'file':
response.session_new = False
response.session_file = None
# check if the session_id points to a valid sesion filename
if response.session_id:
if not regex_session_id.match(response.session_id):
response.session_id = None
else:
response.session_filename = \
os.path.join(up(request.folder), masterapp,
'sessions', response.session_id)
try:
response.session_file = \
recfile.open(response.session_filename, 'rb+')
portalocker.lock(response.session_file,
portalocker.LOCK_EX)
response.session_locked = True
self.update(pickle.load(response.session_file))
response.session_file.seek(0)
oc = response.session_filename.split('/')[-1].split('-')[0]
if check_client and response.session_client != oc:
raise Exception("cookie attack")
except:
response.session_id = None
if not response.session_id:
uuid = web2py_uuid()
response.session_id = '%s-%s' % (response.session_client, uuid)
separate = separate and (lambda session_name: session_name[-2:])
if separate:
prefix = separate(response.session_id)
response.session_id = '%s/%s' % (prefix, response.session_id)
response.session_filename = \
os.path.join(up(request.folder), masterapp,
'sessions', response.session_id)
response.session_new = True
# else the session goes in db
elif response.session_storage_type == 'db':
if global_settings.db_sessions is not True:
global_settings.db_sessions.add(masterapp)
# if had a session on file alreday, close it (yes, can happen)
if response.session_file:
self._close(response)
# if on GAE tickets go also in DB
if settings.global_settings.web2py_runtime_gae:
request.tickets_db = db
if masterapp == request.application:
table_migrate = migrate
else:
table_migrate = False
tname = tablename + '_' + masterapp
table = db.get(tname, None)
# Field = db.Field
if table is None:
db.define_table(
tname,
Field('locked', 'boolean', default=False),
Field('client_ip', length=64),
Field('created_datetime', 'datetime',
default=request.now),
Field('modified_datetime', 'datetime'),
Field('unique_key', length=64),
Field('session_data', 'blob'),
migrate=table_migrate,
)
table = db[tname] # to allow for lazy table
response.session_db_table = table
if response.session_id:
# Get session data out of the database
try:
(record_id, unique_key) = response.session_id.split(':')
record_id = long(record_id)
except (TypeError, ValueError):
record_id = None
# Select from database
if record_id:
row = table(record_id, unique_key=unique_key)
# Make sure the session data exists in the database
if row:
# rows[0].update_record(locked=True)
# Unpickle the data
session_data = pickle.loads(row.session_data)
self.update(session_data)
response.session_new = False
else:
record_id = None
if record_id:
response.session_id = '%s:%s' % (record_id, unique_key)
response.session_db_unique_key = unique_key
response.session_db_record_id = record_id
else:
response.session_id = None
response.session_new = True
# if there is no session id yet, we'll need to create a
# new session
else:
response.session_new = True
# set the cookie now if you know the session_id so user can set
# cookie attributes in controllers/models
# cookie will be reset later
# yet cookie may be reset later
# Removed comparison between old and new session ids - should send
# the cookie all the time
if isinstance(response.session_id, str):
response.cookies[response.session_id_name] = response.session_id
response.cookies[response.session_id_name]['path'] = '/'
if cookie_expires:
response.cookies[response.session_id_name]['expires'] = \
cookie_expires.strftime(FMT)
session_pickled = pickle.dumps(self, pickle.HIGHEST_PROTOCOL)
response.session_hash = hashlib.md5(session_pickled).hexdigest()
if self.flash:
(response.flash, self.flash) = (self.flash, None)
def renew(self, clear_session=False):
if clear_session:
self.clear()
request = current.request
response = current.response
session = response.session
masterapp = response.session_masterapp
cookies = request.cookies
if response.session_storage_type == 'cookie':
return
# if the session goes in file
if response.session_storage_type == 'file':
self._close(response)
uuid = web2py_uuid()
response.session_id = '%s-%s' % (response.session_client, uuid)
separate = (lambda s: s[-2:]) if session and response.session_id[2:3] == "/" else None
if separate:
prefix = separate(response.session_id)
response.session_id = '%s/%s' % \
(prefix, response.session_id)
response.session_filename = \
os.path.join(up(request.folder), masterapp,
'sessions', response.session_id)
response.session_new = True
# else the session goes in db
elif response.session_storage_type == 'db':
table = response.session_db_table
# verify that session_id exists
if response.session_file:
self._close(response)
if response.session_new:
return
# Get session data out of the database
if response.session_id is None:
return
(record_id, sep, unique_key) = response.session_id.partition(':')
if record_id.isdigit() and long(record_id) > 0:
new_unique_key = web2py_uuid()
row = table(record_id)
if row and row.unique_key == unique_key:
table._db(table.id == record_id).update(unique_key=new_unique_key)
else:
record_id = None
if record_id:
response.session_id = '%s:%s' % (record_id, new_unique_key)
response.session_db_record_id = record_id
response.session_db_unique_key = new_unique_key
else:
response.session_new = True
def _fixup_before_save(self):
response = current.response
rcookies = response.cookies
scookies = rcookies.get(response.session_id_name)
if not scookies:
return
if self._forget:
del rcookies[response.session_id_name]
return
if self.get('httponly_cookies',True):
scookies['HttpOnly'] = True
if self._secure:
scookies['secure'] = True
def clear_session_cookies(self):
request = current.request
response = current.response
session = response.session
masterapp = response.session_masterapp
cookies = request.cookies
rcookies = response.cookies
# if not cookie_key, but session_data_name in cookies
# expire session_data_name from cookies
if response.session_data_name in cookies:
rcookies[response.session_data_name] = 'expired'
rcookies[response.session_data_name]['path'] = '/'
rcookies[response.session_data_name]['expires'] = PAST
if response.session_id_name in rcookies:
del rcookies[response.session_id_name]
def save_session_id_cookie(self):
request = current.request
response = current.response
session = response.session
masterapp = response.session_masterapp
cookies = request.cookies
rcookies = response.cookies
# if not cookie_key, but session_data_name in cookies
# expire session_data_name from cookies
if not response.session_cookie_key:
if response.session_data_name in cookies:
rcookies[response.session_data_name] = 'expired'
rcookies[response.session_data_name]['path'] = '/'
rcookies[response.session_data_name]['expires'] = PAST
if response.session_id:
rcookies[response.session_id_name] = response.session_id
rcookies[response.session_id_name]['path'] = '/'
expires = response.session_cookie_expires
if isinstance(expires, datetime.datetime):
expires = expires.strftime(FMT)
if expires:
rcookies[response.session_id_name]['expires'] = expires
def clear(self):
# see https://github.com/web2py/web2py/issues/735
response = current.response
if response.session_storage_type == 'file':
target = recfile.generate(response.session_filename)
try:
self._close(response)
os.unlink(target)
except:
pass
elif response.session_storage_type == 'db':
table = response.session_db_table
if response.session_id:
(record_id, sep, unique_key) = response.session_id.partition(':')
if record_id.isdigit() and long(record_id) > 0:
table._db(table.id == record_id).delete()
Storage.clear(self)
def is_new(self):
if self._start_timestamp:
return False
else:
self._start_timestamp = datetime.datetime.today()
return True
def is_expired(self, seconds=3600):
now = datetime.datetime.today()
if not self._last_timestamp or \
self._last_timestamp + datetime.timedelta(seconds=seconds) > now:
self._last_timestamp = now
return False
else:
return True
def secure(self):
self._secure = True
def forget(self, response=None):
self._close(response)
self._forget = True
def _try_store_in_cookie(self, request, response):
if self._forget or self._unchanged(response):
# self.clear_session_cookies()
self.save_session_id_cookie()
return False
name = response.session_data_name
compression_level = response.session_cookie_compression_level
value = secure_dumps(dict(self),
response.session_cookie_key,
compression_level=compression_level)
rcookies = response.cookies
rcookies.pop(name, None)
rcookies[name] = value
rcookies[name]['path'] = '/'
expires = response.session_cookie_expires
if isinstance(expires, datetime.datetime):
expires = expires.strftime(FMT)
if expires:
rcookies[name]['expires'] = expires
return True
def _unchanged(self, response):
session_pickled = pickle.dumps(self, pickle.HIGHEST_PROTOCOL)
response.session_pickled = session_pickled
session_hash = hashlib.md5(session_pickled).hexdigest()
return response.session_hash == session_hash
def _try_store_in_db(self, request, response):
# don't save if file-based sessions,
# no session id, or session being forgotten
# or no changes to session (Unless the session is new)
if (not response.session_db_table
or self._forget
or (self._unchanged(response) and not response.session_new)):
if (not response.session_db_table
and global_settings.db_sessions is not True
and response.session_masterapp in global_settings.db_sessions):
global_settings.db_sessions.remove(response.session_masterapp)
# self.clear_session_cookies()
self.save_session_id_cookie()
return False
table = response.session_db_table
record_id = response.session_db_record_id
if response.session_new:
unique_key = web2py_uuid()
else:
unique_key = response.session_db_unique_key
session_pickled = response.session_pickled or pickle.dumps(self, pickle.HIGHEST_PROTOCOL)
dd = dict(locked=False,
client_ip=response.session_client,
modified_datetime=request.now,
session_data=session_pickled,
unique_key=unique_key)
if record_id:
if not table._db(table.id == record_id).update(**dd):
record_id = None
if not record_id:
record_id = table.insert(**dd)
response.session_id = '%s:%s' % (record_id, unique_key)
response.session_db_unique_key = unique_key
response.session_db_record_id = record_id
self.save_session_id_cookie()
return True
def _try_store_in_cookie_or_file(self, request, response):
if response.session_storage_type == 'file':
return self._try_store_in_file(request, response)
if response.session_storage_type == 'cookie':
return self._try_store_in_cookie(request, response)
def _try_store_in_file(self, request, response):
try:
if (not response.session_id or self._forget
or self._unchanged(response)):
# self.clear_session_cookies()
self.save_session_id_cookie()
return False
if response.session_new or not response.session_file:
# Tests if the session sub-folder exists, if not, create it
session_folder = os.path.dirname(response.session_filename)
if not os.path.exists(session_folder):
os.mkdir(session_folder)
response.session_file = recfile.open(response.session_filename, 'wb')
portalocker.lock(response.session_file, portalocker.LOCK_EX)
response.session_locked = True
if response.session_file:
session_pickled = response.session_pickled or pickle.dumps(self, pickle.HIGHEST_PROTOCOL)
response.session_file.write(session_pickled)
response.session_file.truncate()
finally:
self._close(response)
self.save_session_id_cookie()
return True
def _unlock(self, response):
if response and response.session_file and response.session_locked:
try:
portalocker.unlock(response.session_file)
response.session_locked = False
except: # this should never happen but happens in Windows
pass
def _close(self, response):
if response and response.session_file:
self._unlock(response)
try:
response.session_file.close()
del response.session_file
except:
pass
def pickle_session(s):
return Session, (dict(s),)
copy_reg.pickle(Session, pickle_session)
| ./CrossVul/dataset_final_sorted/CWE-255/py/bad_5024_0 |
crossvul-python_data_good_744_1 | """Parse (absolute and relative) URLs.
urlparse module is based upon the following RFC specifications.
RFC 3986 (STD66): "Uniform Resource Identifiers" by T. Berners-Lee, R. Fielding
and L. Masinter, January 2005.
RFC 2732 : "Format for Literal IPv6 Addresses in URL's by R.Hinden, B.Carpenter
and L.Masinter, December 1999.
RFC 2396: "Uniform Resource Identifiers (URI)": Generic Syntax by T.
Berners-Lee, R. Fielding, and L. Masinter, August 1998.
RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998.
RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
1995.
RFC 1738: "Uniform Resource Locators (URL)" by T. Berners-Lee, L. Masinter, M.
McCahill, December 1994
RFC 3986 is considered the current standard and any future changes to
urlparse module should conform with it. The urlparse module is
currently not entirely compliant with this RFC due to defacto
scenarios for parsing, and for backward compatibility purposes, some
parsing quirks from older RFCs are retained. The testcases in
test_urlparse.py provides a good indicator of parsing behavior.
"""
import re
import sys
import collections
__all__ = ["urlparse", "urlunparse", "urljoin", "urldefrag",
"urlsplit", "urlunsplit", "urlencode", "parse_qs",
"parse_qsl", "quote", "quote_plus", "quote_from_bytes",
"unquote", "unquote_plus", "unquote_to_bytes",
"DefragResult", "ParseResult", "SplitResult",
"DefragResultBytes", "ParseResultBytes", "SplitResultBytes"]
# A classification of schemes.
# The empty string classifies URLs with no scheme specified,
# being the default value returned by “urlsplit” and “urlparse”.
uses_relative = ['', 'ftp', 'http', 'gopher', 'nntp', 'imap',
'wais', 'file', 'https', 'shttp', 'mms',
'prospero', 'rtsp', 'rtspu', 'sftp',
'svn', 'svn+ssh', 'ws', 'wss']
uses_netloc = ['', 'ftp', 'http', 'gopher', 'nntp', 'telnet',
'imap', 'wais', 'file', 'mms', 'https', 'shttp',
'snews', 'prospero', 'rtsp', 'rtspu', 'rsync',
'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh',
'ws', 'wss']
uses_params = ['', 'ftp', 'hdl', 'prospero', 'http', 'imap',
'https', 'shttp', 'rtsp', 'rtspu', 'sip', 'sips',
'mms', 'sftp', 'tel']
# These are not actually used anymore, but should stay for backwards
# compatibility. (They are undocumented, but have a public-looking name.)
non_hierarchical = ['gopher', 'hdl', 'mailto', 'news',
'telnet', 'wais', 'imap', 'snews', 'sip', 'sips']
uses_query = ['', 'http', 'wais', 'imap', 'https', 'shttp', 'mms',
'gopher', 'rtsp', 'rtspu', 'sip', 'sips']
uses_fragment = ['', 'ftp', 'hdl', 'http', 'gopher', 'news',
'nntp', 'wais', 'https', 'shttp', 'snews',
'file', 'prospero']
# Characters valid in scheme names
scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'0123456789'
'+-.')
# XXX: Consider replacing with functools.lru_cache
MAX_CACHE_SIZE = 20
_parse_cache = {}
def clear_cache():
"""Clear the parse cache and the quoters cache."""
_parse_cache.clear()
_safe_quoters.clear()
# Helpers for bytes handling
# For 3.2, we deliberately require applications that
# handle improperly quoted URLs to do their own
# decoding and encoding. If valid use cases are
# presented, we may relax this by using latin-1
# decoding internally for 3.3
_implicit_encoding = 'ascii'
_implicit_errors = 'strict'
def _noop(obj):
return obj
def _encode_result(obj, encoding=_implicit_encoding,
errors=_implicit_errors):
return obj.encode(encoding, errors)
def _decode_args(args, encoding=_implicit_encoding,
errors=_implicit_errors):
return tuple(x.decode(encoding, errors) if x else '' for x in args)
def _coerce_args(*args):
# Invokes decode if necessary to create str args
# and returns the coerced inputs along with
# an appropriate result coercion function
# - noop for str inputs
# - encoding function otherwise
str_input = isinstance(args[0], str)
for arg in args[1:]:
# We special-case the empty string to support the
# "scheme=''" default argument to some functions
if arg and isinstance(arg, str) != str_input:
raise TypeError("Cannot mix str and non-str arguments")
if str_input:
return args + (_noop,)
return _decode_args(args) + (_encode_result,)
# Result objects are more helpful than simple tuples
class _ResultMixinStr(object):
"""Standard approach to encoding parsed results from str to bytes"""
__slots__ = ()
def encode(self, encoding='ascii', errors='strict'):
return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self))
class _ResultMixinBytes(object):
"""Standard approach to decoding parsed results from bytes to str"""
__slots__ = ()
def decode(self, encoding='ascii', errors='strict'):
return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))
class _NetlocResultMixinBase(object):
"""Shared methods for the parsed result objects containing a netloc element"""
__slots__ = ()
@property
def username(self):
return self._userinfo[0]
@property
def password(self):
return self._userinfo[1]
@property
def hostname(self):
hostname = self._hostinfo[0]
if not hostname:
return None
# Scoped IPv6 address may have zone info, which must not be lowercased
# like http://[fe80::822a:a8ff:fe49:470c%tESt]:1234/keys
separator = '%' if isinstance(hostname, str) else b'%'
hostname, percent, zone = hostname.partition(separator)
return hostname.lower() + percent + zone
@property
def port(self):
port = self._hostinfo[1]
if port is not None:
port = int(port, 10)
if not ( 0 <= port <= 65535):
raise ValueError("Port out of range 0-65535")
return port
class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr):
__slots__ = ()
@property
def _userinfo(self):
netloc = self.netloc
userinfo, have_info, hostinfo = netloc.rpartition('@')
if have_info:
username, have_password, password = userinfo.partition(':')
if not have_password:
password = None
else:
username = password = None
return username, password
@property
def _hostinfo(self):
netloc = self.netloc
_, _, hostinfo = netloc.rpartition('@')
_, have_open_br, bracketed = hostinfo.partition('[')
if have_open_br:
hostname, _, port = bracketed.partition(']')
_, _, port = port.partition(':')
else:
hostname, _, port = hostinfo.partition(':')
if not port:
port = None
return hostname, port
class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):
__slots__ = ()
@property
def _userinfo(self):
netloc = self.netloc
userinfo, have_info, hostinfo = netloc.rpartition(b'@')
if have_info:
username, have_password, password = userinfo.partition(b':')
if not have_password:
password = None
else:
username = password = None
return username, password
@property
def _hostinfo(self):
netloc = self.netloc
_, _, hostinfo = netloc.rpartition(b'@')
_, have_open_br, bracketed = hostinfo.partition(b'[')
if have_open_br:
hostname, _, port = bracketed.partition(b']')
_, _, port = port.partition(b':')
else:
hostname, _, port = hostinfo.partition(b':')
if not port:
port = None
return hostname, port
from collections import namedtuple
_DefragResultBase = namedtuple('DefragResult', 'url fragment')
_SplitResultBase = namedtuple(
'SplitResult', 'scheme netloc path query fragment')
_ParseResultBase = namedtuple(
'ParseResult', 'scheme netloc path params query fragment')
_DefragResultBase.__doc__ = """
DefragResult(url, fragment)
A 2-tuple that contains the url without fragment identifier and the fragment
identifier as a separate argument.
"""
_DefragResultBase.url.__doc__ = """The URL with no fragment identifier."""
_DefragResultBase.fragment.__doc__ = """
Fragment identifier separated from URL, that allows indirect identification of a
secondary resource by reference to a primary resource and additional identifying
information.
"""
_SplitResultBase.__doc__ = """
SplitResult(scheme, netloc, path, query, fragment)
A 5-tuple that contains the different components of a URL. Similar to
ParseResult, but does not split params.
"""
_SplitResultBase.scheme.__doc__ = """Specifies URL scheme for the request."""
_SplitResultBase.netloc.__doc__ = """
Network location where the request is made to.
"""
_SplitResultBase.path.__doc__ = """
The hierarchical path, such as the path to a file to download.
"""
_SplitResultBase.query.__doc__ = """
The query component, that contains non-hierarchical data, that along with data
in path component, identifies a resource in the scope of URI's scheme and
network location.
"""
_SplitResultBase.fragment.__doc__ = """
Fragment identifier, that allows indirect identification of a secondary resource
by reference to a primary resource and additional identifying information.
"""
_ParseResultBase.__doc__ = """
ParseResult(scheme, netloc, path, params, query, fragment)
A 6-tuple that contains components of a parsed URL.
"""
_ParseResultBase.scheme.__doc__ = _SplitResultBase.scheme.__doc__
_ParseResultBase.netloc.__doc__ = _SplitResultBase.netloc.__doc__
_ParseResultBase.path.__doc__ = _SplitResultBase.path.__doc__
_ParseResultBase.params.__doc__ = """
Parameters for last path element used to dereference the URI in order to provide
access to perform some operation on the resource.
"""
_ParseResultBase.query.__doc__ = _SplitResultBase.query.__doc__
_ParseResultBase.fragment.__doc__ = _SplitResultBase.fragment.__doc__
# For backwards compatibility, alias _NetlocResultMixinStr
# ResultBase is no longer part of the documented API, but it is
# retained since deprecating it isn't worth the hassle
ResultBase = _NetlocResultMixinStr
# Structured result objects for string data
class DefragResult(_DefragResultBase, _ResultMixinStr):
__slots__ = ()
def geturl(self):
if self.fragment:
return self.url + '#' + self.fragment
else:
return self.url
class SplitResult(_SplitResultBase, _NetlocResultMixinStr):
__slots__ = ()
def geturl(self):
return urlunsplit(self)
class ParseResult(_ParseResultBase, _NetlocResultMixinStr):
__slots__ = ()
def geturl(self):
return urlunparse(self)
# Structured result objects for bytes data
class DefragResultBytes(_DefragResultBase, _ResultMixinBytes):
__slots__ = ()
def geturl(self):
if self.fragment:
return self.url + b'#' + self.fragment
else:
return self.url
class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes):
__slots__ = ()
def geturl(self):
return urlunsplit(self)
class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes):
__slots__ = ()
def geturl(self):
return urlunparse(self)
# Set up the encode/decode result pairs
def _fix_result_transcoding():
_result_pairs = (
(DefragResult, DefragResultBytes),
(SplitResult, SplitResultBytes),
(ParseResult, ParseResultBytes),
)
for _decoded, _encoded in _result_pairs:
_decoded._encoded_counterpart = _encoded
_encoded._decoded_counterpart = _decoded
_fix_result_transcoding()
del _fix_result_transcoding
def urlparse(url, scheme='', allow_fragments=True):
"""Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params>?<query>#<fragment>
Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
splitresult = urlsplit(url, scheme, allow_fragments)
scheme, netloc, url, query, fragment = splitresult
if scheme in uses_params and ';' in url:
url, params = _splitparams(url)
else:
params = ''
result = ParseResult(scheme, netloc, url, params, query, fragment)
return _coerce_result(result)
def _splitparams(url):
if '/' in url:
i = url.find(';', url.rfind('/'))
if i < 0:
return url, ''
else:
i = url.find(';')
return url[:i], url[i+1:]
def _splitnetloc(url, start=0):
delim = len(url) # position of end of domain part of url, default is end
for c in '/?#': # look for delimiters; the order is NOT important
wdelim = url.find(c, start) # find first of this delim
if wdelim >= 0: # if found
delim = min(delim, wdelim) # use earliest delim position
return url[start:delim], url[delim:] # return (domain, rest)
def _checknetloc(netloc):
if not netloc or not any(ord(c) > 127 for c in netloc):
return
# looking for characters like \u2100 that expand to 'a/c'
# IDNA uses NFKC equivalence, so normalize for this check
import unicodedata
n = netloc.replace('@', '') # ignore characters already included
n = n.replace(':', '') # but not the surrounding text
n = n.replace('#', '')
n = n.replace('?', '')
netloc2 = unicodedata.normalize('NFKC', n)
if n == netloc2:
return
for c in '/?#@:':
if c in netloc2:
raise ValueError("netloc '" + netloc + "' contains invalid " +
"characters under NFKC normalization")
def urlsplit(url, scheme='', allow_fragments=True):
"""Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment>
Return a 5-tuple: (scheme, netloc, path, query, fragment).
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
allow_fragments = bool(allow_fragments)
key = url, scheme, allow_fragments, type(url), type(scheme)
cached = _parse_cache.get(key, None)
if cached:
return _coerce_result(cached)
if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
clear_cache()
netloc = query = fragment = ''
i = url.find(':')
if i > 0:
if url[:i] == 'http': # optimize the common case
scheme = url[:i].lower()
url = url[i+1:]
if url[:2] == '//':
netloc, url = _splitnetloc(url, 2)
if (('[' in netloc and ']' not in netloc) or
(']' in netloc and '[' not in netloc)):
raise ValueError("Invalid IPv6 URL")
if allow_fragments and '#' in url:
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
_checknetloc(netloc)
v = SplitResult(scheme, netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v)
for c in url[:i]:
if c not in scheme_chars:
break
else:
# make sure "url" is not actually a port number (in which case
# "scheme" is really part of the path)
rest = url[i+1:]
if not rest or any(c not in '0123456789' for c in rest):
# not a port number
scheme, url = url[:i].lower(), rest
if url[:2] == '//':
netloc, url = _splitnetloc(url, 2)
if (('[' in netloc and ']' not in netloc) or
(']' in netloc and '[' not in netloc)):
raise ValueError("Invalid IPv6 URL")
if allow_fragments and '#' in url:
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
_checknetloc(netloc)
v = SplitResult(scheme, netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v)
def urlunparse(components):
"""Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent)."""
scheme, netloc, url, params, query, fragment, _coerce_result = (
_coerce_args(*components))
if params:
url = "%s;%s" % (url, params)
return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
def urlunsplit(components):
"""Combine the elements of a tuple as returned by urlsplit() into a
complete URL as a string. The data argument can be any five-item iterable.
This may result in a slightly different, but equivalent URL, if the URL that
was parsed originally had unnecessary delimiters (for example, a ? with an
empty query; the RFC states that these are equivalent)."""
scheme, netloc, url, query, fragment, _coerce_result = (
_coerce_args(*components))
if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
if url and url[:1] != '/': url = '/' + url
url = '//' + (netloc or '') + url
if scheme:
url = scheme + ':' + url
if query:
url = url + '?' + query
if fragment:
url = url + '#' + fragment
return _coerce_result(url)
def urljoin(base, url, allow_fragments=True):
"""Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter."""
if not base:
return url
if not url:
return base
base, url, _coerce_result = _coerce_args(base, url)
bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
urlparse(base, '', allow_fragments)
scheme, netloc, path, params, query, fragment = \
urlparse(url, bscheme, allow_fragments)
if scheme != bscheme or scheme not in uses_relative:
return _coerce_result(url)
if scheme in uses_netloc:
if netloc:
return _coerce_result(urlunparse((scheme, netloc, path,
params, query, fragment)))
netloc = bnetloc
if not path and not params:
path = bpath
params = bparams
if not query:
query = bquery
return _coerce_result(urlunparse((scheme, netloc, path,
params, query, fragment)))
base_parts = bpath.split('/')
if base_parts[-1] != '':
# the last item is not a directory, so will not be taken into account
# in resolving the relative path
del base_parts[-1]
# for rfc3986, ignore all base path should the first character be root.
if path[:1] == '/':
segments = path.split('/')
else:
segments = base_parts + path.split('/')
# filter out elements that would cause redundant slashes on re-joining
# the resolved_path
segments[1:-1] = filter(None, segments[1:-1])
resolved_path = []
for seg in segments:
if seg == '..':
try:
resolved_path.pop()
except IndexError:
# ignore any .. segments that would otherwise cause an IndexError
# when popped from resolved_path if resolving for rfc3986
pass
elif seg == '.':
continue
else:
resolved_path.append(seg)
if segments[-1] in ('.', '..'):
# do some post-processing here. if the last segment was a relative dir,
# then we need to append the trailing '/'
resolved_path.append('')
return _coerce_result(urlunparse((scheme, netloc, '/'.join(
resolved_path) or '/', params, query, fragment)))
def urldefrag(url):
"""Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
"""
url, _coerce_result = _coerce_args(url)
if '#' in url:
s, n, p, a, q, frag = urlparse(url)
defrag = urlunparse((s, n, p, a, q, ''))
else:
frag = ''
defrag = url
return _coerce_result(DefragResult(defrag, frag))
_hexdig = '0123456789ABCDEFabcdef'
_hextobyte = None
def unquote_to_bytes(string):
"""unquote_to_bytes('abc%20def') -> b'abc def'."""
# Note: strings are encoded as UTF-8. This is only an issue if it contains
# unescaped non-ASCII characters, which URIs should not.
if not string:
# Is it a string-like object?
string.split
return b''
if isinstance(string, str):
string = string.encode('utf-8')
bits = string.split(b'%')
if len(bits) == 1:
return string
res = [bits[0]]
append = res.append
# Delay the initialization of the table to not waste memory
# if the function is never called
global _hextobyte
if _hextobyte is None:
_hextobyte = {(a + b).encode(): bytes([int(a + b, 16)])
for a in _hexdig for b in _hexdig}
for item in bits[1:]:
try:
append(_hextobyte[item[:2]])
append(item[2:])
except KeyError:
append(b'%')
append(item)
return b''.join(res)
_asciire = re.compile('([\x00-\x7f]+)')
def unquote(string, encoding='utf-8', errors='replace'):
"""Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters, as accepted by the bytes.decode()
method.
By default, percent-encoded sequences are decoded with UTF-8, and invalid
sequences are replaced by a placeholder character.
unquote('abc%20def') -> 'abc def'.
"""
if '%' not in string:
string.split
return string
if encoding is None:
encoding = 'utf-8'
if errors is None:
errors = 'replace'
bits = _asciire.split(string)
res = [bits[0]]
append = res.append
for i in range(1, len(bits), 2):
append(unquote_to_bytes(bits[i]).decode(encoding, errors))
append(bits[i + 1])
return ''.join(res)
def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace', max_num_fields=None):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as
blank strings. The default false value indicates that
blank values are to be ignored and treated as if they were
not included.
strict_parsing: flag indicating what to do with parsing errors.
If false (the default), errors are silently ignored.
If true, errors raise a ValueError exception.
encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
max_num_fields: int. If set, then throws a ValueError if there
are more than n fields read by parse_qsl().
Returns a dictionary.
"""
parsed_result = {}
pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
encoding=encoding, errors=errors,
max_num_fields=max_num_fields)
for name, value in pairs:
if name in parsed_result:
parsed_result[name].append(value)
else:
parsed_result[name] = [value]
return parsed_result
def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace', max_num_fields=None):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encoded query string to be parsed
keep_blank_values: flag indicating whether blank values in
percent-encoded queries should be treated as blank strings.
A true value indicates that blanks should be retained as blank
strings. The default false value indicates that blank values
are to be ignored and treated as if they were not included.
strict_parsing: flag indicating what to do with parsing errors. If
false (the default), errors are silently ignored. If true,
errors raise a ValueError exception.
encoding and errors: specify how to decode percent-encoded sequences
into Unicode characters, as accepted by the bytes.decode() method.
max_num_fields: int. If set, then throws a ValueError
if there are more than n fields read by parse_qsl().
Returns a list, as G-d intended.
"""
qs, _coerce_result = _coerce_args(qs)
# If max_num_fields is defined then check that the number of fields
# is less than max_num_fields. This prevents a memory exhaustion DOS
# attack via post bodies with many fields.
if max_num_fields is not None:
num_fields = 1 + qs.count('&') + qs.count(';')
if max_num_fields < num_fields:
raise ValueError('Max number of fields exceeded')
pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
r = []
for name_value in pairs:
if not name_value and not strict_parsing:
continue
nv = name_value.split('=', 1)
if len(nv) != 2:
if strict_parsing:
raise ValueError("bad query field: %r" % (name_value,))
# Handle case of a control-name with no equal sign
if keep_blank_values:
nv.append('')
else:
continue
if len(nv[1]) or keep_blank_values:
name = nv[0].replace('+', ' ')
name = unquote(name, encoding=encoding, errors=errors)
name = _coerce_result(name)
value = nv[1].replace('+', ' ')
value = unquote(value, encoding=encoding, errors=errors)
value = _coerce_result(value)
r.append((name, value))
return r
def unquote_plus(string, encoding='utf-8', errors='replace'):
"""Like unquote(), but also replace plus signs by spaces, as required for
unquoting HTML form values.
unquote_plus('%7e/abc+def') -> '~/abc def'
"""
string = string.replace('+', ' ')
return unquote(string, encoding, errors)
_ALWAYS_SAFE = frozenset(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
b'abcdefghijklmnopqrstuvwxyz'
b'0123456789'
b'_.-')
_ALWAYS_SAFE_BYTES = bytes(_ALWAYS_SAFE)
_safe_quoters = {}
class Quoter(collections.defaultdict):
"""A mapping from bytes (in range(0,256)) to strings.
String values are percent-encoded byte values, unless the key < 128, and
in the "safe" set (either the specified safe set, or default set).
"""
# Keeps a cache internally, using defaultdict, for efficiency (lookups
# of cached keys don't call Python code at all).
def __init__(self, safe):
"""safe: bytes object."""
self.safe = _ALWAYS_SAFE.union(safe)
def __repr__(self):
# Without this, will just display as a defaultdict
return "<%s %r>" % (self.__class__.__name__, dict(self))
def __missing__(self, b):
# Handle a cache miss. Store quoted string in cache and return.
res = chr(b) if b in self.safe else '%{:02X}'.format(b)
self[b] = res
return res
def quote(string, safe='/', encoding=None, errors=None):
"""quote('abc def') -> 'abc%20def'
Each part of a URL, e.g. the path info, the query, etc., has a
different set of reserved characters that must be quoted.
RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists
the following reserved characters.
reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" |
"$" | ","
Each of these characters is reserved in some component of a URL,
but not necessarily in all of them.
By default, the quote function is intended for quoting the path
section of a URL. Thus, it will not encode '/'. This character
is reserved, but in typical usage the quote function is being
called on a path where the existing slash characters are used as
reserved characters.
string and safe may be either str or bytes objects. encoding and errors
must not be specified if string is a bytes object.
The optional encoding and errors parameters specify how to deal with
non-ASCII characters, as accepted by the str.encode method.
By default, encoding='utf-8' (characters are encoded with UTF-8), and
errors='strict' (unsupported characters raise a UnicodeEncodeError).
"""
if isinstance(string, str):
if not string:
return string
if encoding is None:
encoding = 'utf-8'
if errors is None:
errors = 'strict'
string = string.encode(encoding, errors)
else:
if encoding is not None:
raise TypeError("quote() doesn't support 'encoding' for bytes")
if errors is not None:
raise TypeError("quote() doesn't support 'errors' for bytes")
return quote_from_bytes(string, safe)
def quote_plus(string, safe='', encoding=None, errors=None):
"""Like quote(), but also replace ' ' with '+', as required for quoting
HTML form values. Plus signs in the original string are escaped unless
they are included in safe. It also does not have safe default to '/'.
"""
# Check if ' ' in string, where string may either be a str or bytes. If
# there are no spaces, the regular quote will produce the right answer.
if ((isinstance(string, str) and ' ' not in string) or
(isinstance(string, bytes) and b' ' not in string)):
return quote(string, safe, encoding, errors)
if isinstance(safe, str):
space = ' '
else:
space = b' '
string = quote(string, safe + space, encoding, errors)
return string.replace(' ', '+')
def quote_from_bytes(bs, safe='/'):
"""Like quote(), but accepts a bytes object rather than a str, and does
not perform string-to-bytes encoding. It always returns an ASCII string.
quote_from_bytes(b'abc def\x3f') -> 'abc%20def%3f'
"""
if not isinstance(bs, (bytes, bytearray)):
raise TypeError("quote_from_bytes() expected bytes")
if not bs:
return ''
if isinstance(safe, str):
# Normalize 'safe' by converting to bytes and removing non-ASCII chars
safe = safe.encode('ascii', 'ignore')
else:
safe = bytes([c for c in safe if c < 128])
if not bs.rstrip(_ALWAYS_SAFE_BYTES + safe):
return bs.decode()
try:
quoter = _safe_quoters[safe]
except KeyError:
_safe_quoters[safe] = quoter = Quoter(safe).__getitem__
return ''.join([quoter(char) for char in bs])
def urlencode(query, doseq=False, safe='', encoding=None, errors=None,
quote_via=quote_plus):
"""Encode a dict or sequence of two-element tuples into a URL query string.
If any values in the query arg are sequences and doseq is true, each
sequence element is converted to a separate parameter.
If the query arg is a sequence of two-element tuples, the order of the
parameters in the output will match the order of parameters in the
input.
The components of a query arg may each be either a string or a bytes type.
The safe, encoding, and errors parameters are passed down to the function
specified by quote_via (encoding and errors only if a component is a str).
"""
if hasattr(query, "items"):
query = query.items()
else:
# It's a bother at times that strings and string-like objects are
# sequences.
try:
# non-sequence items should not work with len()
# non-empty strings will fail this
if len(query) and not isinstance(query[0], tuple):
raise TypeError
# Zero-length sequences of all types will get here and succeed,
# but that's a minor nit. Since the original implementation
# allowed empty dicts that type of behavior probably should be
# preserved for consistency
except TypeError:
ty, va, tb = sys.exc_info()
raise TypeError("not a valid non-string sequence "
"or mapping object").with_traceback(tb)
l = []
if not doseq:
for k, v in query:
if isinstance(k, bytes):
k = quote_via(k, safe)
else:
k = quote_via(str(k), safe, encoding, errors)
if isinstance(v, bytes):
v = quote_via(v, safe)
else:
v = quote_via(str(v), safe, encoding, errors)
l.append(k + '=' + v)
else:
for k, v in query:
if isinstance(k, bytes):
k = quote_via(k, safe)
else:
k = quote_via(str(k), safe, encoding, errors)
if isinstance(v, bytes):
v = quote_via(v, safe)
l.append(k + '=' + v)
elif isinstance(v, str):
v = quote_via(v, safe, encoding, errors)
l.append(k + '=' + v)
else:
try:
# Is this a sufficient test for sequence-ness?
x = len(v)
except TypeError:
# not a sequence
v = quote_via(str(v), safe, encoding, errors)
l.append(k + '=' + v)
else:
# loop over the sequence
for elt in v:
if isinstance(elt, bytes):
elt = quote_via(elt, safe)
else:
elt = quote_via(str(elt), safe, encoding, errors)
l.append(k + '=' + elt)
return '&'.join(l)
def to_bytes(url):
"""to_bytes(u"URL") --> 'URL'."""
# Most URL schemes require ASCII. If that changes, the conversion
# can be relaxed.
# XXX get rid of to_bytes()
if isinstance(url, str):
try:
url = url.encode("ASCII").decode()
except UnicodeError:
raise UnicodeError("URL " + repr(url) +
" contains non-ASCII characters")
return url
def unwrap(url):
"""unwrap('<URL:type://host/path>') --> 'type://host/path'."""
url = str(url).strip()
if url[:1] == '<' and url[-1:] == '>':
url = url[1:-1].strip()
if url[:4] == 'URL:': url = url[4:].strip()
return url
_typeprog = None
def splittype(url):
"""splittype('type:opaquestring') --> 'type', 'opaquestring'."""
global _typeprog
if _typeprog is None:
_typeprog = re.compile('([^/:]+):(.*)', re.DOTALL)
match = _typeprog.match(url)
if match:
scheme, data = match.groups()
return scheme.lower(), data
return None, url
_hostprog = None
def splithost(url):
"""splithost('//host[:port]/path') --> 'host[:port]', '/path'."""
global _hostprog
if _hostprog is None:
_hostprog = re.compile('//([^/#?]*)(.*)', re.DOTALL)
match = _hostprog.match(url)
if match:
host_port, path = match.groups()
if path and path[0] != '/':
path = '/' + path
return host_port, path
return None, url
def splituser(host):
"""splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'."""
user, delim, host = host.rpartition('@')
return (user if delim else None), host
def splitpasswd(user):
"""splitpasswd('user:passwd') -> 'user', 'passwd'."""
user, delim, passwd = user.partition(':')
return user, (passwd if delim else None)
# splittag('/path#tag') --> '/path', 'tag'
_portprog = None
def splitport(host):
"""splitport('host:port') --> 'host', 'port'."""
global _portprog
if _portprog is None:
_portprog = re.compile('(.*):([0-9]*)$', re.DOTALL)
match = _portprog.match(host)
if match:
host, port = match.groups()
if port:
return host, port
return host, None
def splitnport(host, defport=-1):
"""Split host and port, returning numeric port.
Return given default port if no ':' found; defaults to -1.
Return numerical port if a valid number are found after ':'.
Return None if ':' but not a valid number."""
host, delim, port = host.rpartition(':')
if not delim:
host = port
elif port:
try:
nport = int(port)
except ValueError:
nport = None
return host, nport
return host, defport
def splitquery(url):
"""splitquery('/path?query') --> '/path', 'query'."""
path, delim, query = url.rpartition('?')
if delim:
return path, query
return url, None
def splittag(url):
"""splittag('/path#tag') --> '/path', 'tag'."""
path, delim, tag = url.rpartition('#')
if delim:
return path, tag
return url, None
def splitattr(url):
"""splitattr('/path;attr1=value1;attr2=value2;...') ->
'/path', ['attr1=value1', 'attr2=value2', ...]."""
words = url.split(';')
return words[0], words[1:]
def splitvalue(attr):
"""splitvalue('attr=value') --> 'attr', 'value'."""
attr, delim, value = attr.partition('=')
return attr, (value if delim else None)
| ./CrossVul/dataset_final_sorted/CWE-255/py/good_744_1 |
crossvul-python_data_good_3792_0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Main entry point into the EC2 Credentials service.
This service allows the creation of access/secret credentials used for
the ec2 interop layer of OpenStack.
A user can create as many access/secret pairs, each of which map to a
specific tenant. This is required because OpenStack supports a user
belonging to multiple tenants, whereas the signatures created on ec2-style
requests don't allow specification of which tenant the user wishs to act
upon.
To complete the cycle, we provide a method that OpenStack services can
use to validate a signature and get a corresponding openstack token. This
token allows method calls to other services within the context the
access/secret was created. As an example, nova requests keystone to validate
the signature of a request, receives a token, and then makes a request to
glance to list images needed to perform the requested task.
"""
import uuid
from keystone import catalog
from keystone import config
from keystone import exception
from keystone import identity
from keystone import policy
from keystone import service
from keystone import token
from keystone.common import manager
from keystone.common import utils
from keystone.common import wsgi
CONF = config.CONF
class Manager(manager.Manager):
"""Default pivot point for the EC2 Credentials backend.
See :mod:`keystone.common.manager.Manager` for more details on how this
dynamically calls the backend.
"""
def __init__(self):
super(Manager, self).__init__(CONF.ec2.driver)
class Ec2Extension(wsgi.ExtensionRouter):
def add_routes(self, mapper):
ec2_controller = Ec2Controller()
# validation
mapper.connect('/ec2tokens',
controller=ec2_controller,
action='authenticate',
conditions=dict(method=['POST']))
# crud
mapper.connect('/users/{user_id}/credentials/OS-EC2',
controller=ec2_controller,
action='create_credential',
conditions=dict(method=['POST']))
mapper.connect('/users/{user_id}/credentials/OS-EC2',
controller=ec2_controller,
action='get_credentials',
conditions=dict(method=['GET']))
mapper.connect('/users/{user_id}/credentials/OS-EC2/{credential_id}',
controller=ec2_controller,
action='get_credential',
conditions=dict(method=['GET']))
mapper.connect('/users/{user_id}/credentials/OS-EC2/{credential_id}',
controller=ec2_controller,
action='delete_credential',
conditions=dict(method=['DELETE']))
class Ec2Controller(wsgi.Application):
def __init__(self):
self.catalog_api = catalog.Manager()
self.identity_api = identity.Manager()
self.token_api = token.Manager()
self.policy_api = policy.Manager()
self.ec2_api = Manager()
super(Ec2Controller, self).__init__()
def check_signature(self, creds_ref, credentials):
signer = utils.Ec2Signer(creds_ref['secret'])
signature = signer.generate(credentials)
if utils.auth_str_equal(credentials['signature'], signature):
return
# NOTE(vish): Some libraries don't use the port when signing
# requests, so try again without port.
elif ':' in credentials['signature']:
hostname, _port = credentials['host'].split(':')
credentials['host'] = hostname
signature = signer.generate(credentials)
if not utils.auth_str_equal(credentials.signature, signature):
raise exception.Unauthorized(message='Invalid EC2 signature.')
else:
raise exception.Unauthorized(message='EC2 signature not supplied.')
def authenticate(self, context, credentials=None,
ec2Credentials=None):
"""Validate a signed EC2 request and provide a token.
Other services (such as Nova) use this **admin** call to determine
if a request they signed received is from a valid user.
If it is a valid signature, an openstack token that maps
to the user/tenant is returned to the caller, along with
all the other details returned from a normal token validation
call.
The returned token is useful for making calls to other
OpenStack services within the context of the request.
:param context: standard context
:param credentials: dict of ec2 signature
:param ec2Credentials: DEPRECATED dict of ec2 signature
:returns: token: openstack token equivalent to access key along
with the corresponding service catalog and roles
"""
# FIXME(ja): validate that a service token was used!
# NOTE(termie): backwards compat hack
if not credentials and ec2Credentials:
credentials = ec2Credentials
if not 'access' in credentials:
raise exception.Unauthorized(message='EC2 signature not supplied.')
creds_ref = self._get_credentials(context,
credentials['access'])
self.check_signature(creds_ref, credentials)
# TODO(termie): don't create new tokens every time
# TODO(termie): this is copied from TokenController.authenticate
token_id = uuid.uuid4().hex
tenant_ref = self.identity_api.get_tenant(
context=context,
tenant_id=creds_ref['tenant_id'])
user_ref = self.identity_api.get_user(
context=context,
user_id=creds_ref['user_id'])
metadata_ref = self.identity_api.get_metadata(
context=context,
user_id=user_ref['id'],
tenant_id=tenant_ref['id'])
# TODO(termie): optimize this call at some point and put it into the
# the return for metadata
# fill out the roles in the metadata
roles = metadata_ref.get('roles', [])
if not roles:
raise exception.Unauthorized(message='User not valid for tenant.')
roles_ref = [self.identity_api.get_role(context, role_id)
for role_id in roles]
catalog_ref = self.catalog_api.get_catalog(
context=context,
user_id=user_ref['id'],
tenant_id=tenant_ref['id'],
metadata=metadata_ref)
token_ref = self.token_api.create_token(
context, token_id, dict(id=token_id,
user=user_ref,
tenant=tenant_ref,
metadata=metadata_ref))
# TODO(termie): make this a util function or something
# TODO(termie): i don't think the ec2 middleware currently expects a
# full return, but it contains a note saying that it
# would be better to expect a full return
token_controller = service.TokenController()
return token_controller._format_authenticate(
token_ref, roles_ref, catalog_ref)
def create_credential(self, context, user_id, tenant_id):
"""Create a secret/access pair for use with ec2 style auth.
Generates a new set of credentials that map the the user/tenant
pair.
:param context: standard context
:param user_id: id of user
:param tenant_id: id of tenant
:returns: credential: dict of ec2 credential
"""
if not self._is_admin(context):
self._assert_identity(context, user_id)
self._assert_valid_user_id(context, user_id)
self._assert_valid_tenant_id(context, tenant_id)
cred_ref = {'user_id': user_id,
'tenant_id': tenant_id,
'access': uuid.uuid4().hex,
'secret': uuid.uuid4().hex}
self.ec2_api.create_credential(context, cred_ref['access'], cred_ref)
return {'credential': cred_ref}
def get_credentials(self, context, user_id):
"""List all credentials for a user.
:param context: standard context
:param user_id: id of user
:returns: credentials: list of ec2 credential dicts
"""
if not self._is_admin(context):
self._assert_identity(context, user_id)
self._assert_valid_user_id(context, user_id)
return {'credentials': self.ec2_api.list_credentials(context, user_id)}
def get_credential(self, context, user_id, credential_id):
"""Retreive a user's access/secret pair by the access key.
Grab the full access/secret pair for a given access key.
:param context: standard context
:param user_id: id of user
:param credential_id: access key for credentials
:returns: credential: dict of ec2 credential
"""
if not self._is_admin(context):
self._assert_identity(context, user_id)
self._assert_valid_user_id(context, user_id)
creds = self._get_credentials(context, credential_id)
return {'credential': creds}
def delete_credential(self, context, user_id, credential_id):
"""Delete a user's access/secret pair.
Used to revoke a user's access/secret pair
:param context: standard context
:param user_id: id of user
:param credential_id: access key for credentials
:returns: bool: success
"""
if not self._is_admin(context):
self._assert_identity(context, user_id)
self._assert_owner(context, user_id, credential_id)
self._assert_valid_user_id(context, user_id)
self._get_credentials(context, credential_id)
return self.ec2_api.delete_credential(context, credential_id)
def _get_credentials(self, context, credential_id):
"""Return credentials from an ID.
:param context: standard context
:param credential_id: id of credential
:raises exception.Unauthorized: when credential id is invalid
:returns: credential: dict of ec2 credential.
"""
creds = self.ec2_api.get_credential(context,
credential_id)
if not creds:
raise exception.Unauthorized(message='EC2 access key not found.')
return creds
def _assert_identity(self, context, user_id):
"""Check that the provided token belongs to the user.
:param context: standard context
:param user_id: id of user
:raises exception.Forbidden: when token is invalid
"""
try:
token_ref = self.token_api.get_token(context=context,
token_id=context['token_id'])
except exception.TokenNotFound:
raise exception.Unauthorized()
token_user_id = token_ref['user'].get('id')
if not token_user_id == user_id:
raise exception.Forbidden()
def _is_admin(self, context):
"""Wrap admin assertion error return statement.
:param context: standard context
:returns: bool: success
"""
try:
self.assert_admin(context)
return True
except exception.Forbidden:
return False
def _assert_owner(self, context, user_id, credential_id):
"""Ensure the provided user owns the credential.
:param context: standard context
:param user_id: expected credential owner
:param credential_id: id of credential object
:raises exception.Forbidden: on failure
"""
cred_ref = self.ec2_api.get_credential(context, credential_id)
if not user_id == cred_ref['user_id']:
raise exception.Forbidden()
def _assert_valid_user_id(self, context, user_id):
"""Ensure a valid user id.
:param context: standard context
:param user_id: expected credential owner
:raises exception.UserNotFound: on failure
"""
user_ref = self.identity_api.get_user(
context=context,
user_id=user_id)
if not user_ref:
raise exception.UserNotFound(user_id=user_id)
def _assert_valid_tenant_id(self, context, tenant_id):
"""Ensure a valid tenant id.
:param context: standard context
:param user_id: expected credential owner
:raises exception.UserNotFound: on failure
"""
tenant_ref = self.identity_api.get_tenant(
context=context,
tenant_id=tenant_id)
if not tenant_ref:
raise exception.TenantNotFound(tenant_id=tenant_id)
| ./CrossVul/dataset_final_sorted/CWE-255/py/good_3792_0 |
crossvul-python_data_good_3788_0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import uuid
import routes
import json
from keystone import config
from keystone import catalog
from keystone.common import cms
from keystone.common import logging
from keystone.common import wsgi
from keystone import exception
from keystone import identity
from keystone.openstack.common import timeutils
from keystone import policy
from keystone import token
LOG = logging.getLogger(__name__)
class V3Router(wsgi.ComposingRouter):
def crud_routes(self, mapper, controller, collection_key, key):
collection_path = '/%(collection_key)s' % {
'collection_key': collection_key}
entity_path = '/%(collection_key)s/{%(key)s_id}' % {
'collection_key': collection_key,
'key': key}
mapper.connect(
collection_path,
controller=controller,
action='create_%s' % key,
conditions=dict(method=['POST']))
mapper.connect(
collection_path,
controller=controller,
action='list_%s' % collection_key,
conditions=dict(method=['GET']))
mapper.connect(
entity_path,
controller=controller,
action='get_%s' % key,
conditions=dict(method=['GET']))
mapper.connect(
entity_path,
controller=controller,
action='update_%s' % key,
conditions=dict(method=['PATCH']))
mapper.connect(
entity_path,
controller=controller,
action='delete_%s' % key,
conditions=dict(method=['DELETE']))
def __init__(self):
mapper = routes.Mapper()
apis = dict(
catalog_api=catalog.Manager(),
identity_api=identity.Manager(),
policy_api=policy.Manager(),
token_api=token.Manager())
# Catalog
self.crud_routes(
mapper,
catalog.ServiceControllerV3(**apis),
'services',
'service')
self.crud_routes(
mapper,
catalog.EndpointControllerV3(**apis),
'endpoints',
'endpoint')
# Identity
self.crud_routes(
mapper,
identity.DomainControllerV3(**apis),
'domains',
'domain')
project_controller = identity.ProjectControllerV3(**apis)
self.crud_routes(
mapper,
project_controller,
'projects',
'project')
mapper.connect(
'/users/{user_id}/projects',
controller=project_controller,
action='list_user_projects',
conditions=dict(method=['GET']))
self.crud_routes(
mapper,
identity.UserControllerV3(**apis),
'users',
'user')
self.crud_routes(
mapper,
identity.CredentialControllerV3(**apis),
'credentials',
'credential')
role_controller = identity.RoleControllerV3(**apis)
self.crud_routes(
mapper,
role_controller,
'roles',
'role')
mapper.connect(
'/projects/{project_id}/users/{user_id}/roles/{role_id}',
controller=role_controller,
action='create_grant',
conditions=dict(method=['PUT']))
mapper.connect(
'/projects/{project_id}/users/{user_id}/roles/{role_id}',
controller=role_controller,
action='check_grant',
conditions=dict(method=['HEAD']))
mapper.connect(
'/projects/{project_id}/users/{user_id}/roles',
controller=role_controller,
action='list_grants',
conditions=dict(method=['GET']))
mapper.connect(
'/projects/{project_id}/users/{user_id}/roles/{role_id}',
controller=role_controller,
action='revoke_grant',
conditions=dict(method=['DELETE']))
mapper.connect(
'/domains/{domain_id}/users/{user_id}/roles/{role_id}',
controller=role_controller,
action='create_grant',
conditions=dict(method=['PUT']))
mapper.connect(
'/domains/{domain_id}/users/{user_id}/roles/{role_id}',
controller=role_controller,
action='check_grant',
conditions=dict(method=['HEAD']))
mapper.connect(
'/domains/{domain_id}/users/{user_id}/roles',
controller=role_controller,
action='list_grants',
conditions=dict(method=['GET']))
mapper.connect(
'/domains/{domain_id}/users/{user_id}/roles/{role_id}',
controller=role_controller,
action='revoke_grant',
conditions=dict(method=['DELETE']))
# Policy
policy_controller = policy.PolicyControllerV3(**apis)
self.crud_routes(
mapper,
policy_controller,
'policies',
'policy')
# Token
"""
# v2.0 LEGACY
mapper.connect('/tokens/{token_id}',
controller=auth_controller,
action='validate_token',
conditions=dict(method=['GET']))
mapper.connect('/tokens/{token_id}',
controller=auth_controller,
action='validate_token_head',
conditions=dict(method=['HEAD']))
mapper.connect('/tokens/{token_id}',
controller=auth_controller,
action='delete_token',
conditions=dict(method=['DELETE']))
mapper.connect('/tokens/{token_id}/endpoints',
controller=auth_controller,
action='endpoints',
conditions=dict(method=['GET']))
"""
super(V3Router, self).__init__(mapper, [])
class AdminRouter(wsgi.ComposingRouter):
def __init__(self):
mapper = routes.Mapper()
version_controller = VersionController('admin')
mapper.connect('/',
controller=version_controller,
action='get_version')
# Token Operations
auth_controller = TokenController()
mapper.connect('/tokens',
controller=auth_controller,
action='authenticate',
conditions=dict(method=['POST']))
mapper.connect('/tokens/revoked',
controller=auth_controller,
action='revocation_list',
conditions=dict(method=['GET']))
mapper.connect('/tokens/{token_id}',
controller=auth_controller,
action='validate_token',
conditions=dict(method=['GET']))
mapper.connect('/tokens/{token_id}',
controller=auth_controller,
action='validate_token_head',
conditions=dict(method=['HEAD']))
mapper.connect('/tokens/{token_id}',
controller=auth_controller,
action='delete_token',
conditions=dict(method=['DELETE']))
mapper.connect('/tokens/{token_id}/endpoints',
controller=auth_controller,
action='endpoints',
conditions=dict(method=['GET']))
# Certificates used to verify auth tokens
mapper.connect('/certificates/ca',
controller=auth_controller,
action='ca_cert',
conditions=dict(method=['GET']))
mapper.connect('/certificates/signing',
controller=auth_controller,
action='signing_cert',
conditions=dict(method=['GET']))
# Miscellaneous Operations
extensions_controller = AdminExtensionsController()
mapper.connect('/extensions',
controller=extensions_controller,
action='get_extensions_info',
conditions=dict(method=['GET']))
mapper.connect('/extensions/{extension_alias}',
controller=extensions_controller,
action='get_extension_info',
conditions=dict(method=['GET']))
identity_router = identity.AdminRouter()
routers = [identity_router]
super(AdminRouter, self).__init__(mapper, routers)
class PublicRouter(wsgi.ComposingRouter):
def __init__(self):
mapper = routes.Mapper()
version_controller = VersionController('public')
mapper.connect('/',
controller=version_controller,
action='get_version')
# Token Operations
auth_controller = TokenController()
mapper.connect('/tokens',
controller=auth_controller,
action='authenticate',
conditions=dict(method=['POST']))
mapper.connect('/certificates/ca',
controller=auth_controller,
action='ca_cert',
conditions=dict(method=['GET']))
mapper.connect('/certificates/signing',
controller=auth_controller,
action='signing_cert',
conditions=dict(method=['GET']))
# Miscellaneous
extensions_controller = PublicExtensionsController()
mapper.connect('/extensions',
controller=extensions_controller,
action='get_extensions_info',
conditions=dict(method=['GET']))
mapper.connect('/extensions/{extension_alias}',
controller=extensions_controller,
action='get_extension_info',
conditions=dict(method=['GET']))
identity_router = identity.PublicRouter()
routers = [identity_router]
super(PublicRouter, self).__init__(mapper, routers)
class PublicVersionRouter(wsgi.ComposingRouter):
def __init__(self):
mapper = routes.Mapper()
version_controller = VersionController('public')
mapper.connect('/',
controller=version_controller,
action='get_versions')
routers = []
super(PublicVersionRouter, self).__init__(mapper, routers)
class AdminVersionRouter(wsgi.ComposingRouter):
def __init__(self):
mapper = routes.Mapper()
version_controller = VersionController('admin')
mapper.connect('/',
controller=version_controller,
action='get_versions')
routers = []
super(AdminVersionRouter, self).__init__(mapper, routers)
class VersionController(wsgi.Application):
def __init__(self, version_type):
self.catalog_api = catalog.Manager()
self.url_key = '%sURL' % version_type
super(VersionController, self).__init__()
def _get_identity_url(self, context):
catalog_ref = self.catalog_api.get_catalog(context=context,
user_id=None,
tenant_id=None)
for region, region_ref in catalog_ref.iteritems():
for service, service_ref in region_ref.iteritems():
if service == 'identity':
return service_ref[self.url_key]
raise exception.NotImplemented()
def _get_versions_list(self, context):
"""The list of versions is dependent on the context."""
identity_url = self._get_identity_url(context)
if not identity_url.endswith('/'):
identity_url = identity_url + '/'
versions = {}
versions['v2.0'] = {
'id': 'v2.0',
'status': 'beta',
'updated': '2011-11-19T00:00:00Z',
'links': [
{
'rel': 'self',
'href': identity_url,
}, {
'rel': 'describedby',
'type': 'text/html',
'href': 'http://docs.openstack.org/api/openstack-'
'identity-service/2.0/content/'
}, {
'rel': 'describedby',
'type': 'application/pdf',
'href': 'http://docs.openstack.org/api/openstack-'
'identity-service/2.0/identity-dev-guide-'
'2.0.pdf'
}
],
'media-types': [
{
'base': 'application/json',
'type': 'application/vnd.openstack.identity-v2.0'
'+json'
}, {
'base': 'application/xml',
'type': 'application/vnd.openstack.identity-v2.0'
'+xml'
}
]
}
return versions
def get_versions(self, context):
versions = self._get_versions_list(context)
return wsgi.render_response(status=(300, 'Multiple Choices'), body={
'versions': {
'values': versions.values()
}
})
def get_version(self, context):
versions = self._get_versions_list(context)
return wsgi.render_response(body={
'version': versions['v2.0']
})
class NoopController(wsgi.Application):
def __init__(self):
super(NoopController, self).__init__()
def noop(self, context):
return {}
class ExternalAuthNotApplicable(Exception):
"""External authentication is not applicable"""
class TokenController(wsgi.Application):
def __init__(self):
self.catalog_api = catalog.Manager()
self.identity_api = identity.Manager()
self.token_api = token.Manager()
self.policy_api = policy.Manager()
super(TokenController, self).__init__()
def ca_cert(self, context, auth=None):
ca_file = open(config.CONF.signing.ca_certs, 'r')
data = ca_file.read()
ca_file.close()
return data
def signing_cert(self, context, auth=None):
cert_file = open(config.CONF.signing.certfile, 'r')
data = cert_file.read()
cert_file.close()
return data
def authenticate(self, context, auth=None):
"""Authenticate credentials and return a token.
Accept auth as a dict that looks like::
{
"auth":{
"passwordCredentials":{
"username":"test_user",
"password":"mypass"
},
"tenantName":"customer-x"
}
}
In this case, tenant is optional, if not provided the token will be
considered "unscoped" and can later be used to get a scoped token.
Alternatively, this call accepts auth with only a token and tenant
that will return a token that is scoped to that tenant.
"""
if auth is None:
raise exception.ValidationError(attribute='auth',
target='request body')
auth_token_data = None
if "token" in auth:
# Try to authenticate using a token
auth_token_data, auth_info = self._authenticate_token(
context, auth)
else:
# Try external authentication
try:
auth_token_data, auth_info = self._authenticate_external(
context, auth)
except ExternalAuthNotApplicable:
# Try local authentication
auth_token_data, auth_info = self._authenticate_local(
context, auth)
user_ref, tenant_ref, metadata_ref = auth_info
# If the user is disabled don't allow them to authenticate
if not user_ref.get('enabled', True):
msg = 'User is disabled: %s' % user_ref['id']
LOG.warning(msg)
raise exception.Unauthorized(msg)
# If the tenant is disabled don't allow them to authenticate
if tenant_ref and not tenant_ref.get('enabled', True):
msg = 'Tenant is disabled: %s' % tenant_ref['id']
LOG.warning(msg)
raise exception.Unauthorized(msg)
if tenant_ref:
catalog_ref = self.catalog_api.get_catalog(
context=context,
user_id=user_ref['id'],
tenant_id=tenant_ref['id'],
metadata=metadata_ref)
else:
catalog_ref = {}
auth_token_data['id'] = 'placeholder'
roles_ref = []
for role_id in metadata_ref.get('roles', []):
role_ref = self.identity_api.get_role(context, role_id)
roles_ref.append(dict(name=role_ref['name']))
token_data = self._format_token(auth_token_data, roles_ref)
service_catalog = self._format_catalog(catalog_ref)
token_data['access']['serviceCatalog'] = service_catalog
if config.CONF.signing.token_format == 'UUID':
token_id = uuid.uuid4().hex
elif config.CONF.signing.token_format == 'PKI':
token_id = cms.cms_sign_token(json.dumps(token_data),
config.CONF.signing.certfile,
config.CONF.signing.keyfile)
else:
raise exception.UnexpectedError(
'Invalid value for token_format: %s.'
' Allowed values are PKI or UUID.' %
config.CONF.signing.token_format)
try:
self.token_api.create_token(
context, token_id, dict(key=token_id,
id=token_id,
expires=auth_token_data['expires'],
user=user_ref,
tenant=tenant_ref,
metadata=metadata_ref))
except Exception as e:
# an identical token may have been created already.
# if so, return the token_data as it is also identical
try:
self.token_api.get_token(context=context,
token_id=token_id)
except exception.TokenNotFound:
raise e
token_data['access']['token']['id'] = token_id
return token_data
def _authenticate_token(self, context, auth):
"""Try to authenticate using an already existing token.
Returns auth_token_data, (user_ref, tenant_ref, metadata_ref)
"""
if 'token' not in auth:
raise exception.ValidationError(
attribute='token', target='auth')
if "id" not in auth['token']:
raise exception.ValidationError(
attribute="id", target="token")
old_token = auth['token']['id']
try:
old_token_ref = self.token_api.get_token(context=context,
token_id=old_token)
except exception.NotFound as e:
raise exception.Unauthorized(e)
user_ref = old_token_ref['user']
user_id = user_ref['id']
current_user_ref = self.identity_api.get_user(context=context,
user_id=user_id)
tenant_id = self._get_tenant_id_from_auth(context, auth)
tenant_ref = self._get_tenant_ref(context, user_id, tenant_id)
metadata_ref = self._get_metadata_ref(context, user_id, tenant_id)
expiry = old_token_ref['expires']
auth_token_data = self._get_auth_token_data(current_user_ref,
tenant_ref,
metadata_ref,
expiry)
return auth_token_data, (current_user_ref, tenant_ref, metadata_ref)
def _authenticate_local(self, context, auth):
"""Try to authenticate against the identity backend.
Returns auth_token_data, (user_ref, tenant_ref, metadata_ref)
"""
if 'passwordCredentials' not in auth:
raise exception.ValidationError(
attribute='passwordCredentials', target='auth')
if "password" not in auth['passwordCredentials']:
raise exception.ValidationError(
attribute='password', target='passwordCredentials')
password = auth['passwordCredentials']['password']
if ("userId" not in auth['passwordCredentials'] and
"username" not in auth['passwordCredentials']):
raise exception.ValidationError(
attribute='username or userId',
target='passwordCredentials')
user_id = auth['passwordCredentials'].get('userId', None)
username = auth['passwordCredentials'].get('username', '')
if username:
try:
user_ref = self.identity_api.get_user_by_name(
context=context, user_name=username)
user_id = user_ref['id']
except exception.UserNotFound as e:
raise exception.Unauthorized(e)
tenant_id = self._get_tenant_id_from_auth(context, auth)
try:
auth_info = self.identity_api.authenticate(
context=context,
user_id=user_id,
password=password,
tenant_id=tenant_id)
except AssertionError as e:
raise exception.Unauthorized(e)
(user_ref, tenant_ref, metadata_ref) = auth_info
expiry = self.token_api._get_default_expire_time(context=context)
auth_token_data = self._get_auth_token_data(user_ref,
tenant_ref,
metadata_ref,
expiry)
return auth_token_data, (user_ref, tenant_ref, metadata_ref)
def _authenticate_external(self, context, auth):
"""Try to authenticate an external user via REMOTE_USER variable.
Returns auth_token_data, (user_ref, tenant_ref, metadata_ref)
"""
if 'REMOTE_USER' not in context:
raise ExternalAuthNotApplicable()
username = context['REMOTE_USER']
try:
user_ref = self.identity_api.get_user_by_name(
context=context, user_name=username)
user_id = user_ref['id']
except exception.UserNotFound as e:
raise exception.Unauthorized(e)
tenant_id = self._get_tenant_id_from_auth(context, auth)
tenant_ref = self._get_tenant_ref(context, user_id, tenant_id)
metadata_ref = self._get_metadata_ref(context, user_id, tenant_id)
expiry = self.token_api._get_default_expire_time(context=context)
auth_token_data = self._get_auth_token_data(user_ref,
tenant_ref,
metadata_ref,
expiry)
return auth_token_data, (user_ref, tenant_ref, metadata_ref)
def _get_auth_token_data(self, user, tenant, metadata, expiry):
return dict(dict(user=user,
tenant=tenant,
metadata=metadata,
expires=expiry))
def _get_tenant_id_from_auth(self, context, auth):
"""Extract tenant information from auth dict.
Returns a valid tenant_id if it exists, or None if not specified.
"""
tenant_id = auth.get('tenantId', None)
tenant_name = auth.get('tenantName', None)
if tenant_name:
try:
tenant_ref = self.identity_api.get_tenant_by_name(
context=context, tenant_name=tenant_name)
tenant_id = tenant_ref['id']
except exception.TenantNotFound as e:
raise exception.Unauthorized(e)
return tenant_id
def _get_tenant_ref(self, context, user_id, tenant_id):
"""Returns the tenant_ref for the user's tenant"""
tenant_ref = None
if tenant_id:
tenants = self.identity_api.get_tenants_for_user(context, user_id)
if tenant_id not in tenants:
msg = 'User %s is unauthorized for tenant %s' % (
user_id, tenant_id)
LOG.warning(msg)
raise exception.Unauthorized(msg)
try:
tenant_ref = self.identity_api.get_tenant(context=context,
tenant_id=tenant_id)
except exception.TenantNotFound as e:
exception.Unauthorized(e)
return tenant_ref
def _get_metadata_ref(self, context, user_id, tenant_id):
"""Returns the metadata_ref for a user in a tenant"""
metadata_ref = {}
if tenant_id:
try:
metadata_ref = self.identity_api.get_metadata(
context=context,
user_id=user_id,
tenant_id=tenant_id)
except exception.MetadataNotFound:
metadata_ref = {}
return metadata_ref
def _get_token_ref(self, context, token_id, belongs_to=None):
"""Returns a token if a valid one exists.
Optionally, limited to a token owned by a specific tenant.
"""
# TODO(termie): this stuff should probably be moved to middleware
self.assert_admin(context)
if cms.is_ans1_token(token_id):
data = json.loads(cms.cms_verify(cms.token_to_cms(token_id),
config.CONF.signing.certfile,
config.CONF.signing.ca_certs))
data['access']['token']['user'] = data['access']['user']
data['access']['token']['metadata'] = data['access']['metadata']
if belongs_to:
assert data['access']['token']['tenant']['id'] == belongs_to
token_ref = data['access']['token']
else:
token_ref = self.token_api.get_token(context=context,
token_id=token_id)
return token_ref
# admin only
def validate_token_head(self, context, token_id):
"""Check that a token is valid.
Optionally, also ensure that it is owned by a specific tenant.
Identical to ``validate_token``, except does not return a response.
"""
belongs_to = context['query_string'].get('belongsTo')
assert self._get_token_ref(context, token_id, belongs_to)
# admin only
def validate_token(self, context, token_id):
"""Check that a token is valid.
Optionally, also ensure that it is owned by a specific tenant.
Returns metadata about the token along any associated roles.
"""
belongs_to = context['query_string'].get('belongsTo')
token_ref = self._get_token_ref(context, token_id, belongs_to)
# TODO(termie): optimize this call at some point and put it into the
# the return for metadata
# fill out the roles in the metadata
metadata_ref = token_ref['metadata']
roles_ref = []
for role_id in metadata_ref.get('roles', []):
roles_ref.append(self.identity_api.get_role(context, role_id))
# Get a service catalog if possible
# This is needed for on-behalf-of requests
catalog_ref = None
if token_ref.get('tenant'):
catalog_ref = self.catalog_api.get_catalog(
context=context,
user_id=token_ref['user']['id'],
tenant_id=token_ref['tenant']['id'],
metadata=metadata_ref)
return self._format_token(token_ref, roles_ref, catalog_ref)
def delete_token(self, context, token_id):
"""Delete a token, effectively invalidating it for authz."""
# TODO(termie): this stuff should probably be moved to middleware
self.assert_admin(context)
self.token_api.delete_token(context=context, token_id=token_id)
def revocation_list(self, context, auth=None):
self.assert_admin(context)
tokens = self.token_api.list_revoked_tokens(context)
for t in tokens:
expires = t['expires']
if not (expires and isinstance(expires, unicode)):
t['expires'] = timeutils.isotime(expires)
data = {'revoked': tokens}
json_data = json.dumps(data)
signed_text = cms.cms_sign_text(json_data,
config.CONF.signing.certfile,
config.CONF.signing.keyfile)
return {'signed': signed_text}
def endpoints(self, context, token_id):
"""Return a list of endpoints available to the token."""
self.assert_admin(context)
token_ref = self._get_token_ref(context, token_id)
catalog_ref = None
if token_ref.get('tenant'):
catalog_ref = self.catalog_api.get_catalog(
context=context,
user_id=token_ref['user']['id'],
tenant_id=token_ref['tenant']['id'],
metadata=token_ref['metadata'])
return self._format_endpoint_list(catalog_ref)
def _format_authenticate(self, token_ref, roles_ref, catalog_ref):
o = self._format_token(token_ref, roles_ref)
o['access']['serviceCatalog'] = self._format_catalog(catalog_ref)
return o
def _format_token(self, token_ref, roles_ref, catalog_ref=None):
user_ref = token_ref['user']
metadata_ref = token_ref['metadata']
expires = token_ref['expires']
if expires is not None:
if not isinstance(expires, unicode):
expires = timeutils.isotime(expires)
o = {'access': {'token': {'id': token_ref['id'],
'expires': expires,
'issued_at': timeutils.strtime()
},
'user': {'id': user_ref['id'],
'name': user_ref['name'],
'username': user_ref['name'],
'roles': roles_ref,
'roles_links': metadata_ref.get('roles_links',
[])
}
}
}
if 'tenant' in token_ref and token_ref['tenant']:
token_ref['tenant']['enabled'] = True
o['access']['token']['tenant'] = token_ref['tenant']
if catalog_ref is not None:
o['access']['serviceCatalog'] = self._format_catalog(catalog_ref)
if metadata_ref:
if 'is_admin' in metadata_ref:
o['access']['metadata'] = {'is_admin':
metadata_ref['is_admin']}
else:
o['access']['metadata'] = {'is_admin': 0}
if 'roles' in metadata_ref:
o['access']['metadata']['roles'] = metadata_ref['roles']
return o
def _format_catalog(self, catalog_ref):
"""Munge catalogs from internal to output format
Internal catalogs look like:
{$REGION: {
{$SERVICE: {
$key1: $value1,
...
}
}
}
The legacy api wants them to look like
[{'name': $SERVICE[name],
'type': $SERVICE,
'endpoints': [{
'tenantId': $tenant_id,
...
'region': $REGION,
}],
'endpoints_links': [],
}]
"""
if not catalog_ref:
return {}
services = {}
for region, region_ref in catalog_ref.iteritems():
for service, service_ref in region_ref.iteritems():
new_service_ref = services.get(service, {})
new_service_ref['name'] = service_ref.pop('name')
new_service_ref['type'] = service
new_service_ref['endpoints_links'] = []
service_ref['region'] = region
endpoints_ref = new_service_ref.get('endpoints', [])
endpoints_ref.append(service_ref)
new_service_ref['endpoints'] = endpoints_ref
services[service] = new_service_ref
return services.values()
def _format_endpoint_list(self, catalog_ref):
"""Formats a list of endpoints according to Identity API v2.
The v2.0 API wants an endpoint list to look like::
{
'endpoints': [
{
'id': $endpoint_id,
'name': $SERVICE[name],
'type': $SERVICE,
'tenantId': $tenant_id,
'region': $REGION,
}
],
'endpoints_links': [],
}
"""
if not catalog_ref:
return {}
endpoints = []
for region_name, region_ref in catalog_ref.iteritems():
for service_type, service_ref in region_ref.iteritems():
endpoints.append({
'id': service_ref.get('id'),
'name': service_ref.get('name'),
'type': service_type,
'region': region_name,
'publicURL': service_ref.get('publicURL'),
'internalURL': service_ref.get('internalURL'),
'adminURL': service_ref.get('adminURL'),
})
return {'endpoints': endpoints, 'endpoints_links': []}
class ExtensionsController(wsgi.Application):
"""Base extensions controller to be extended by public and admin API's."""
def __init__(self, extensions=None):
super(ExtensionsController, self).__init__()
self.extensions = extensions or {}
def get_extensions_info(self, context):
return {'extensions': {'values': self.extensions.values()}}
def get_extension_info(self, context, extension_alias):
try:
return {'extension': self.extensions[extension_alias]}
except KeyError:
raise exception.NotFound(target=extension_alias)
class PublicExtensionsController(ExtensionsController):
pass
class AdminExtensionsController(ExtensionsController):
def __init__(self, *args, **kwargs):
super(AdminExtensionsController, self).__init__(*args, **kwargs)
# TODO(dolph): Extensions should obviously provide this information
# themselves, but hardcoding it here allows us to match
# the API spec in the short term with minimal complexity.
self.extensions['OS-KSADM'] = {
'name': 'Openstack Keystone Admin',
'namespace': 'http://docs.openstack.org/identity/api/ext/'
'OS-KSADM/v1.0',
'alias': 'OS-KSADM',
'updated': '2011-08-19T13:25:27-06:00',
'description': 'Openstack extensions to Keystone v2.0 API '
'enabling Admin Operations.',
'links': [
{
'rel': 'describedby',
# TODO(dolph): link needs to be revised after
# bug 928059 merges
'type': 'text/html',
'href': 'https://github.com/openstack/identity-api',
}
]
}
@logging.fail_gracefully
def public_app_factory(global_conf, **local_conf):
conf = global_conf.copy()
conf.update(local_conf)
return PublicRouter()
@logging.fail_gracefully
def admin_app_factory(global_conf, **local_conf):
conf = global_conf.copy()
conf.update(local_conf)
return AdminRouter()
@logging.fail_gracefully
def public_version_app_factory(global_conf, **local_conf):
conf = global_conf.copy()
conf.update(local_conf)
return PublicVersionRouter()
@logging.fail_gracefully
def admin_version_app_factory(global_conf, **local_conf):
conf = global_conf.copy()
conf.update(local_conf)
return AdminVersionRouter()
@logging.fail_gracefully
def v3_app_factory(global_conf, **local_conf):
conf = global_conf.copy()
conf.update(local_conf)
return V3Router()
| ./CrossVul/dataset_final_sorted/CWE-255/py/good_3788_0 |
crossvul-python_data_bad_2084_1 | #
# The Python Imaging Library.
# $Id$
#
# the Image class wrapper
#
# partial release history:
# 1995-09-09 fl Created
# 1996-03-11 fl PIL release 0.0 (proof of concept)
# 1996-04-30 fl PIL release 0.1b1
# 1999-07-28 fl PIL release 1.0 final
# 2000-06-07 fl PIL release 1.1
# 2000-10-20 fl PIL release 1.1.1
# 2001-05-07 fl PIL release 1.1.2
# 2002-03-15 fl PIL release 1.1.3
# 2003-05-10 fl PIL release 1.1.4
# 2005-03-28 fl PIL release 1.1.5
# 2006-12-02 fl PIL release 1.1.6
# 2009-11-15 fl PIL release 1.1.7
#
# Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
# Copyright (c) 1995-2009 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
from PIL import VERSION, PILLOW_VERSION, _plugins
import warnings
class _imaging_not_installed:
# module placeholder
def __getattr__(self, id):
raise ImportError("The _imaging C module is not installed")
try:
# give Tk a chance to set up the environment, in case we're
# using an _imaging module linked against libtcl/libtk (use
# __import__ to hide this from naive packagers; we don't really
# depend on Tk unless ImageTk is used, and that module already
# imports Tkinter)
__import__("FixTk")
except ImportError:
pass
try:
# If the _imaging C module is not present, you can still use
# the "open" function to identify files, but you cannot load
# them. Note that other modules should not refer to _imaging
# directly; import Image and use the Image.core variable instead.
from PIL import _imaging as core
if PILLOW_VERSION != getattr(core, 'PILLOW_VERSION', None):
raise ImportError("The _imaging extension was built for another "
" version of Pillow or PIL")
except ImportError as v:
core = _imaging_not_installed()
# Explanations for ways that we know we might have an import error
if str(v).startswith("Module use of python"):
# The _imaging C module is present, but not compiled for
# the right version (windows only). Print a warning, if
# possible.
warnings.warn(
"The _imaging extension was built for another version "
"of Python.",
RuntimeWarning
)
elif str(v).startswith("The _imaging extension"):
warnings.warn(str(v), RuntimeWarning)
elif "Symbol not found: _PyUnicodeUCS2_FromString" in str(v):
warnings.warn(
"The _imaging extension was built for Python with UCS2 support; "
"recompile PIL or build Python --without-wide-unicode. ",
RuntimeWarning
)
elif "Symbol not found: _PyUnicodeUCS4_FromString" in str(v):
warnings.warn(
"The _imaging extension was built for Python with UCS4 support; "
"recompile PIL or build Python --with-wide-unicode. ",
RuntimeWarning
)
# Fail here anyway. Don't let people run with a mostly broken Pillow.
raise
try:
import builtins
except ImportError:
import __builtin__
builtins = __builtin__
from PIL import ImageMode
from PIL._binary import i8, o8
from PIL._util import isPath, isStringType
import os, sys
# type stuff
import collections
import numbers
def isImageType(t):
"""
Checks if an object is an image object.
.. warning::
This function is for internal use only.
:param t: object to check if it's an image
:returns: True if the object is an image
"""
return hasattr(t, "im")
#
# Debug level
DEBUG = 0
#
# Constants (also defined in _imagingmodule.c!)
NONE = 0
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
ROTATE_90 = 2
ROTATE_180 = 3
ROTATE_270 = 4
# transforms
AFFINE = 0
EXTENT = 1
PERSPECTIVE = 2
QUAD = 3
MESH = 4
# resampling filters
NONE = 0
NEAREST = 0
ANTIALIAS = 1 # 3-lobed lanczos
LINEAR = BILINEAR = 2
CUBIC = BICUBIC = 3
# dithers
NONE = 0
NEAREST = 0
ORDERED = 1 # Not yet implemented
RASTERIZE = 2 # Not yet implemented
FLOYDSTEINBERG = 3 # default
# palettes/quantizers
WEB = 0
ADAPTIVE = 1
MEDIANCUT = 0
MAXCOVERAGE = 1
FASTOCTREE = 2
# categories
NORMAL = 0
SEQUENCE = 1
CONTAINER = 2
if hasattr(core, 'DEFAULT_STRATEGY'):
DEFAULT_STRATEGY = core.DEFAULT_STRATEGY
FILTERED = core.FILTERED
HUFFMAN_ONLY = core.HUFFMAN_ONLY
RLE = core.RLE
FIXED = core.FIXED
# --------------------------------------------------------------------
# Registries
ID = []
OPEN = {}
MIME = {}
SAVE = {}
EXTENSION = {}
# --------------------------------------------------------------------
# Modes supported by this version
_MODEINFO = {
# NOTE: this table will be removed in future versions. use
# getmode* functions or ImageMode descriptors instead.
# official modes
"1": ("L", "L", ("1",)),
"L": ("L", "L", ("L",)),
"I": ("L", "I", ("I",)),
"F": ("L", "F", ("F",)),
"P": ("RGB", "L", ("P",)),
"RGB": ("RGB", "L", ("R", "G", "B")),
"RGBX": ("RGB", "L", ("R", "G", "B", "X")),
"RGBA": ("RGB", "L", ("R", "G", "B", "A")),
"CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
"YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
"LAB": ("RGB", "L", ("L", "A", "B")),
# Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and
# BGR;24. Use these modes only if you know exactly what you're
# doing...
}
if sys.byteorder == 'little':
_ENDIAN = '<'
else:
_ENDIAN = '>'
_MODE_CONV = {
# official modes
"1": ('|b1', None), # broken
"L": ('|u1', None),
"I": (_ENDIAN + 'i4', None),
"F": (_ENDIAN + 'f4', None),
"P": ('|u1', None),
"RGB": ('|u1', 3),
"RGBX": ('|u1', 4),
"RGBA": ('|u1', 4),
"CMYK": ('|u1', 4),
"YCbCr": ('|u1', 3),
"LAB": ('|u1', 3), # UNDONE - unsigned |u1i1i1
# I;16 == I;16L, and I;32 == I;32L
"I;16": ('<u2', None),
"I;16B": ('>u2', None),
"I;16L": ('<u2', None),
"I;16S": ('<i2', None),
"I;16BS": ('>i2', None),
"I;16LS": ('<i2', None),
"I;32": ('<u4', None),
"I;32B": ('>u4', None),
"I;32L": ('<u4', None),
"I;32S": ('<i4', None),
"I;32BS": ('>i4', None),
"I;32LS": ('<i4', None),
}
def _conv_type_shape(im):
shape = im.size[1], im.size[0]
typ, extra = _MODE_CONV[im.mode]
if extra is None:
return shape, typ
else:
return shape+(extra,), typ
MODES = sorted(_MODEINFO.keys())
# raw modes that may be memory mapped. NOTE: if you change this, you
# may have to modify the stride calculation in map.c too!
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")
def getmodebase(mode):
"""
Gets the "base" mode for given mode. This function returns "L" for
images that contain grayscale data, and "RGB" for images that
contain color data.
:param mode: Input mode.
:returns: "L" or "RGB".
:exception KeyError: If the input mode was not a standard mode.
"""
return ImageMode.getmode(mode).basemode
def getmodetype(mode):
"""
Gets the storage type mode. Given a mode, this function returns a
single-layer mode suitable for storing individual bands.
:param mode: Input mode.
:returns: "L", "I", or "F".
:exception KeyError: If the input mode was not a standard mode.
"""
return ImageMode.getmode(mode).basetype
def getmodebandnames(mode):
"""
Gets a list of individual band names. Given a mode, this function returns
a tuple containing the names of individual bands (use
:py:method:`~PIL.Image.getmodetype` to get the mode used to store each
individual band.
:param mode: Input mode.
:returns: A tuple containing band names. The length of the tuple
gives the number of bands in an image of the given mode.
:exception KeyError: If the input mode was not a standard mode.
"""
return ImageMode.getmode(mode).bands
def getmodebands(mode):
"""
Gets the number of individual bands for this mode.
:param mode: Input mode.
:returns: The number of bands in this mode.
:exception KeyError: If the input mode was not a standard mode.
"""
return len(ImageMode.getmode(mode).bands)
# --------------------------------------------------------------------
# Helpers
_initialized = 0
def preinit():
"Explicitly load standard file format drivers."
global _initialized
if _initialized >= 1:
return
try:
from PIL import BmpImagePlugin
except ImportError:
pass
try:
from PIL import GifImagePlugin
except ImportError:
pass
try:
from PIL import JpegImagePlugin
except ImportError:
pass
try:
from PIL import PpmImagePlugin
except ImportError:
pass
try:
from PIL import PngImagePlugin
except ImportError:
pass
# try:
# import TiffImagePlugin
# except ImportError:
# pass
_initialized = 1
def init():
"""
Explicitly initializes the Python Imaging Library. This function
loads all available file format drivers.
"""
global _initialized
if _initialized >= 2:
return 0
for plugin in _plugins:
try:
if DEBUG:
print ("Importing %s"%plugin)
__import__("PIL.%s"%plugin, globals(), locals(), [])
except ImportError:
if DEBUG:
print("Image: failed to import", end=' ')
print(plugin, ":", sys.exc_info()[1])
if OPEN or SAVE:
_initialized = 2
return 1
# --------------------------------------------------------------------
# Codec factories (used by tobytes/frombytes and ImageFile.load)
def _getdecoder(mode, decoder_name, args, extra=()):
# tweak arguments
if args is None:
args = ()
elif not isinstance(args, tuple):
args = (args,)
try:
# get decoder
decoder = getattr(core, decoder_name + "_decoder")
# print(decoder, mode, args + extra)
return decoder(mode, *args + extra)
except AttributeError:
raise IOError("decoder %s not available" % decoder_name)
def _getencoder(mode, encoder_name, args, extra=()):
# tweak arguments
if args is None:
args = ()
elif not isinstance(args, tuple):
args = (args,)
try:
# get encoder
encoder = getattr(core, encoder_name + "_encoder")
# print(encoder, mode, args + extra)
return encoder(mode, *args + extra)
except AttributeError:
raise IOError("encoder %s not available" % encoder_name)
# --------------------------------------------------------------------
# Simple expression analyzer
def coerce_e(value):
return value if isinstance(value, _E) else _E(value)
class _E:
def __init__(self, data):
self.data = data
def __add__(self, other):
return _E((self.data, "__add__", coerce_e(other).data))
def __mul__(self, other):
return _E((self.data, "__mul__", coerce_e(other).data))
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number)):
return c, 0.0
if (a is stub and b == "__add__" and isinstance(c, numbers.Number)):
return 1.0, c
except TypeError: pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number) and
d == "__add__" and isinstance(e, numbers.Number)):
return c, e
except TypeError: pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
class Image:
"""
This class represents an image object. To create
:py:class:`~PIL.Image.Image` objects, use the appropriate factory
functions. There's hardly ever any reason to call the Image constructor
directly.
* :py:func:`~PIL.Image.open`
* :py:func:`~PIL.Image.new`
* :py:func:`~PIL.Image.frombytes`
"""
format = None
format_description = None
def __init__(self):
# FIXME: take "new" parameters / other image?
# FIXME: turn mode and size into delegating properties?
self.im = None
self.mode = ""
self.size = (0, 0)
self.palette = None
self.info = {}
self.category = NORMAL
self.readonly = 0
def _new(self, im):
new = Image()
new.im = im
new.mode = im.mode
new.size = im.size
new.palette = self.palette
if im.mode == "P" and not new.palette:
from PIL import ImagePalette
new.palette = ImagePalette.ImagePalette()
try:
new.info = self.info.copy()
except AttributeError:
# fallback (pre-1.5.2)
new.info = {}
for k, v in self.info:
new.info[k] = v
return new
_makeself = _new # compatibility
def _copy(self):
self.load()
self.im = self.im.copy()
self.readonly = 0
def _dump(self, file=None, format=None):
import tempfile
if not file:
file = tempfile.mktemp()
self.load()
if not format or format == "PPM":
self.im.save_ppm(file)
else:
file = file + "." + format
self.save(file, format)
return file
def __repr__(self):
return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
self.__class__.__module__, self.__class__.__name__,
self.mode, self.size[0], self.size[1],
id(self)
)
def __getattr__(self, name):
if name == "__array_interface__":
# numpy array interface support
new = {}
shape, typestr = _conv_type_shape(self)
new['shape'] = shape
new['typestr'] = typestr
new['data'] = self.tobytes()
return new
raise AttributeError(name)
def tobytes(self, encoder_name="raw", *args):
"""
Return image as a bytes object
:param encoder_name: What encoder to use. The default is to
use the standard "raw" encoder.
:param args: Extra arguments to the encoder.
:rtype: A bytes object.
"""
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0]
if encoder_name == "raw" and args == ():
args = self.mode
self.load()
# unpack data
e = _getencoder(self.mode, encoder_name, args)
e.setimage(self.im)
bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
data = []
while True:
l, s, d = e.encode(bufsize)
data.append(d)
if s:
break
if s < 0:
raise RuntimeError("encoder error %d in tobytes" % s)
return b"".join(data)
# Declare tostring as alias to tobytes
def tostring(self, *args, **kw):
warnings.warn(
'tostring() is deprecated. Please call tobytes() instead.',
DeprecationWarning,
stacklevel=2,
)
return self.tobytes(*args, **kw)
def tobitmap(self, name="image"):
"""
Returns the image converted to an X11 bitmap.
.. note:: This method only works for mode "1" images.
:param name: The name prefix to use for the bitmap variables.
:returns: A string containing an X11 bitmap.
:raises ValueError: If the mode is not "1"
"""
self.load()
if self.mode != "1":
raise ValueError("not a bitmap")
data = self.tobytes("xbm")
return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'),
("#define %s_height %d\n"% (name, self.size[1])).encode('ascii'),
("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"])
def frombytes(self, data, decoder_name="raw", *args):
"""
Loads this image with pixel data from a bytes object.
This method is similar to the :py:func:`~PIL.Image.frombytes` function,
but loads data into this image instead of creating a new image object.
"""
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0]
# default format
if decoder_name == "raw" and args == ():
args = self.mode
# unpack data
d = _getdecoder(self.mode, decoder_name, args)
d.setimage(self.im)
s = d.decode(data)
if s[0] >= 0:
raise ValueError("not enough image data")
if s[1] != 0:
raise ValueError("cannot decode image data")
def fromstring(self, *args, **kw):
"""Deprecated alias to frombytes.
.. deprecated:: 2.0
"""
warnings.warn('fromstring() is deprecated. Please call frombytes() instead.', DeprecationWarning)
return self.frombytes(*args, **kw)
def load(self):
"""
Allocates storage for the image and loads the pixel data. In
normal cases, you don't need to call this method, since the
Image class automatically loads an opened image when it is
accessed for the first time.
:returns: An image access object.
"""
if self.im and self.palette and self.palette.dirty:
# realize palette
self.im.putpalette(*self.palette.getdata())
self.palette.dirty = 0
self.palette.mode = "RGB"
self.palette.rawmode = None
if "transparency" in self.info:
if isinstance(self.info["transparency"], int):
self.im.putpalettealpha(self.info["transparency"], 0)
else:
self.im.putpalettealphas(self.info["transparency"])
self.palette.mode = "RGBA"
if self.im:
return self.im.pixel_access(self.readonly)
def verify(self):
"""
Verifies the contents of a file. For data read from a file, this
method attempts to determine if the file is broken, without
actually decoding the image data. If this method finds any
problems, it raises suitable exceptions. If you need to load
the image after using this method, you must reopen the image
file.
"""
pass
def convert(self, mode=None, matrix=None, dither=None,
palette=WEB, colors=256):
"""
Returns a converted copy of this image. For the "P" mode, this
method translates pixels through the palette. If mode is
omitted, a mode is chosen so that all information in the image
and the palette can be represented without a palette.
The current version supports all possible conversions between
"L", "RGB" and "CMYK." The **matrix** argument only supports "L"
and "RGB".
When translating a color image to black and white (mode "L"),
the library uses the ITU-R 601-2 luma transform::
L = R * 299/1000 + G * 587/1000 + B * 114/1000
The default method of converting a greyscale ("L") or "RGB"
image into a bilevel (mode "1") image uses Floyd-Steinberg
dither to approximate the original image luminosity levels. If
dither is NONE, all non-zero values are set to 255 (white). To
use other thresholds, use the :py:meth:`~PIL.Image.Image.point`
method.
:param mode: The requested mode.
:param matrix: An optional conversion matrix. If given, this
should be 4- or 16-tuple containing floating point values.
:param dither: Dithering method, used when converting from
mode "RGB" to "P" or from "RGB" or "L" to "1".
Available methods are NONE or FLOYDSTEINBERG (default).
:param palette: Palette to use when converting from mode "RGB"
to "P". Available palettes are WEB or ADAPTIVE.
:param colors: Number of colors to use for the ADAPTIVE palette.
Defaults to 256.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if not mode:
# determine default mode
if self.mode == "P":
self.load()
if self.palette:
mode = self.palette.mode
else:
mode = "RGB"
else:
return self.copy()
self.load()
if matrix:
# matrix conversion
if mode not in ("L", "RGB"):
raise ValueError("illegal conversion")
im = self.im.convert_matrix(mode, matrix)
return self._new(im)
if mode == "P" and palette == ADAPTIVE:
im = self.im.quantize(colors)
return self._new(im)
# colorspace conversion
if dither is None:
dither = FLOYDSTEINBERG
# Use transparent conversion to promote from transparent color to an alpha channel.
if self.mode in ("L", "RGB") and mode == "RGBA" and "transparency" in self.info:
return self._new(self.im.convert_transparent(mode, self.info['transparency']))
try:
im = self.im.convert(mode, dither)
except ValueError:
try:
# normalize source image and try again
im = self.im.convert(getmodebase(self.mode))
im = im.convert(mode, dither)
except KeyError:
raise ValueError("illegal conversion")
return self._new(im)
def quantize(self, colors=256, method=0, kmeans=0, palette=None):
# methods:
# 0 = median cut
# 1 = maximum coverage
# 2 = fast octree
# NOTE: this functionality will be moved to the extended
# quantizer interface in a later version of PIL.
self.load()
if palette:
# use palette from reference image
palette.load()
if palette.mode != "P":
raise ValueError("bad mode for palette image")
if self.mode != "RGB" and self.mode != "L":
raise ValueError(
"only RGB or L mode images can be quantized to a palette"
)
im = self.im.convert("P", 1, palette.im)
return self._makeself(im)
im = self.im.quantize(colors, method, kmeans)
return self._new(im)
def copy(self):
"""
Copies this image. Use this method if you wish to paste things
into an image, but still retain the original.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object.
"""
self.load()
im = self.im.copy()
return self._new(im)
def crop(self, box=None):
"""
Returns a rectangular region from this image. The box is a
4-tuple defining the left, upper, right, and lower pixel
coordinate.
This is a lazy operation. Changes to the source image may or
may not be reflected in the cropped image. To break the
connection, call the :py:meth:`~PIL.Image.Image.load` method on
the cropped copy.
:param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object.
"""
self.load()
if box is None:
return self.copy()
# lazy operation
return _ImageCrop(self, box)
def draft(self, mode, size):
"""
Configures the image file loader so it returns a version of the
image that as closely as possible matches the given mode and
size. For example, you can use this method to convert a color
JPEG to greyscale while loading it, or to extract a 128x192
version from a PCD file.
Note that this method modifies the :py:class:`~PIL.Image.Image` object
in place. If the image has already been loaded, this method has no
effect.
:param mode: The requested mode.
:param size: The requested size.
"""
pass
def _expand(self, xmargin, ymargin=None):
if ymargin is None:
ymargin = xmargin
self.load()
return self._new(self.im.expand(xmargin, ymargin, 0))
def filter(self, filter):
"""
Filters this image using the given filter. For a list of
available filters, see the :py:mod:`~PIL.ImageFilter` module.
:param filter: Filter kernel.
:returns: An :py:class:`~PIL.Image.Image` object. """
self.load()
if isinstance(filter, collections.Callable):
filter = filter()
if not hasattr(filter, "filter"):
raise TypeError("filter argument should be ImageFilter.Filter instance or class")
if self.im.bands == 1:
return self._new(filter.filter(self.im))
# fix to handle multiband images since _imaging doesn't
ims = []
for c in range(self.im.bands):
ims.append(self._new(filter.filter(self.im.getband(c))))
return merge(self.mode, ims)
def getbands(self):
"""
Returns a tuple containing the name of each band in this image.
For example, **getbands** on an RGB image returns ("R", "G", "B").
:returns: A tuple containing band names.
:rtype: tuple
"""
return ImageMode.getmode(self.mode).bands
def getbbox(self):
"""
Calculates the bounding box of the non-zero regions in the
image.
:returns: The bounding box is returned as a 4-tuple defining the
left, upper, right, and lower pixel coordinate. If the image
is completely empty, this method returns None.
"""
self.load()
return self.im.getbbox()
def getcolors(self, maxcolors=256):
"""
Returns a list of colors used in this image.
:param maxcolors: Maximum number of colors. If this number is
exceeded, this method returns None. The default limit is
256 colors.
:returns: An unsorted list of (count, pixel) values.
"""
self.load()
if self.mode in ("1", "L", "P"):
h = self.im.histogram()
out = []
for i in range(256):
if h[i]:
out.append((h[i], i))
if len(out) > maxcolors:
return None
return out
return self.im.getcolors(maxcolors)
def getdata(self, band = None):
"""
Returns the contents of this image as a sequence object
containing pixel values. The sequence object is flattened, so
that values for line one follow directly after the values of
line zero, and so on.
Note that the sequence object returned by this method is an
internal PIL data type, which only supports certain sequence
operations. To convert it to an ordinary sequence (e.g. for
printing), use **list(im.getdata())**.
:param band: What band to return. The default is to return
all bands. To return a single band, pass in the index
value (e.g. 0 to get the "R" band from an "RGB" image).
:returns: A sequence-like object.
"""
self.load()
if band is not None:
return self.im.getband(band)
return self.im # could be abused
def getextrema(self):
"""
Gets the the minimum and maximum pixel values for each band in
the image.
:returns: For a single-band image, a 2-tuple containing the
minimum and maximum pixel value. For a multi-band image,
a tuple containing one 2-tuple for each band.
"""
self.load()
if self.im.bands > 1:
extrema = []
for i in range(self.im.bands):
extrema.append(self.im.getband(i).getextrema())
return tuple(extrema)
return self.im.getextrema()
def getim(self):
"""
Returns a capsule that points to the internal image memory.
:returns: A capsule object.
"""
self.load()
return self.im.ptr
def getpalette(self):
"""
Returns the image palette as a list.
:returns: A list of color values [r, g, b, ...], or None if the
image has no palette.
"""
self.load()
try:
if bytes is str:
return [i8(c) for c in self.im.getpalette()]
else:
return list(self.im.getpalette())
except ValueError:
return None # no palette
def getpixel(self, xy):
"""
Returns the pixel value at a given position.
:param xy: The coordinate, given as (x, y).
:returns: The pixel value. If the image is a multi-layer image,
this method returns a tuple.
"""
self.load()
return self.im.getpixel(xy)
def getprojection(self):
"""
Get projection to x and y axes
:returns: Two sequences, indicating where there are non-zero
pixels along the X-axis and the Y-axis, respectively.
"""
self.load()
x, y = self.im.getprojection()
return [i8(c) for c in x], [i8(c) for c in y]
def histogram(self, mask=None, extrema=None):
"""
Returns a histogram for the image. The histogram is returned as
a list of pixel counts, one for each pixel value in the source
image. If the image has more than one band, the histograms for
all bands are concatenated (for example, the histogram for an
"RGB" image contains 768 values).
A bilevel image (mode "1") is treated as a greyscale ("L") image
by this method.
If a mask is provided, the method returns a histogram for those
parts of the image where the mask image is non-zero. The mask
image must have the same size as the image, and be either a
bi-level image (mode "1") or a greyscale image ("L").
:param mask: An optional mask.
:returns: A list containing pixel counts.
"""
self.load()
if mask:
mask.load()
return self.im.histogram((0, 0), mask.im)
if self.mode in ("I", "F"):
if extrema is None:
extrema = self.getextrema()
return self.im.histogram(extrema)
return self.im.histogram()
def offset(self, xoffset, yoffset=None):
"""
.. deprecated:: 2.0
.. note:: New code should use :py:func:`PIL.ImageChops.offset`.
Returns a copy of the image where the data has been offset by the given
distances. Data wraps around the edges. If **yoffset** is omitted, it
is assumed to be equal to **xoffset**.
:param xoffset: The horizontal distance.
:param yoffset: The vertical distance. If omitted, both
distances are set to the same value.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if warnings:
warnings.warn(
"'offset' is deprecated; use 'ImageChops.offset' instead",
DeprecationWarning, stacklevel=2
)
from PIL import ImageChops
return ImageChops.offset(self, xoffset, yoffset)
def paste(self, im, box=None, mask=None):
"""
Pastes another image into this image. The box argument is either
a 2-tuple giving the upper left corner, a 4-tuple defining the
left, upper, right, and lower pixel coordinate, or None (same as
(0, 0)). If a 4-tuple is given, the size of the pasted image
must match the size of the region.
If the modes don't match, the pasted image is converted to the mode of
this image (see the :py:meth:`~PIL.Image.Image.convert` method for
details).
Instead of an image, the source can be a integer or tuple
containing pixel values. The method then fills the region
with the given color. When creating RGB images, you can
also use color strings as supported by the ImageColor module.
If a mask is given, this method updates only the regions
indicated by the mask. You can use either "1", "L" or "RGBA"
images (in the latter case, the alpha band is used as mask).
Where the mask is 255, the given image is copied as is. Where
the mask is 0, the current value is preserved. Intermediate
values can be used for transparency effects.
Note that if you paste an "RGBA" image, the alpha band is
ignored. You can work around this by using the same image as
both source image and mask.
:param im: Source image or pixel value (integer or tuple).
:param box: An optional 4-tuple giving the region to paste into.
If a 2-tuple is used instead, it's treated as the upper left
corner. If omitted or None, the source is pasted into the
upper left corner.
If an image is given as the second argument and there is no
third, the box defaults to (0, 0), and the second argument
is interpreted as a mask image.
:param mask: An optional mask image.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if isImageType(box) and mask is None:
# abbreviated paste(im, mask) syntax
mask = box; box = None
if box is None:
# cover all of self
box = (0, 0) + self.size
if len(box) == 2:
# lower left corner given; get size from image or mask
if isImageType(im):
size = im.size
elif isImageType(mask):
size = mask.size
else:
# FIXME: use self.size here?
raise ValueError(
"cannot determine region size; use 4-item box"
)
box = box + (box[0]+size[0], box[1]+size[1])
if isStringType(im):
from PIL import ImageColor
im = ImageColor.getcolor(im, self.mode)
elif isImageType(im):
im.load()
if self.mode != im.mode:
if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
# should use an adapter for this!
im = im.convert(self.mode)
im = im.im
self.load()
if self.readonly:
self._copy()
if mask:
mask.load()
self.im.paste(im, box, mask.im)
else:
self.im.paste(im, box)
def point(self, lut, mode=None):
"""
Maps this image through a lookup table or function.
:param lut: A lookup table, containing 256 (or 65336 if
self.mode=="I" and mode == "L") values per band in the
image. A function can be used instead, it should take a
single argument. The function is called once for each
possible pixel value, and the resulting table is applied to
all bands of the image.
:param mode: Output mode (default is same as input). In the
current version, this can only be used if the source image
has mode "L" or "P", and the output has mode "1" or the
source image mode is "I" and the output mode is "L".
:returns: An :py:class:`~PIL.Image.Image` object.
"""
self.load()
if isinstance(lut, ImagePointHandler):
return lut.point(self)
if callable(lut):
# if it isn't a list, it should be a function
if self.mode in ("I", "I;16", "F"):
# check if the function can be used with point_transform
# UNDONE wiredfool -- I think this prevents us from ever doing
# a gamma function point transform on > 8bit images.
scale, offset = _getscaleoffset(lut)
return self._new(self.im.point_transform(scale, offset))
# for other modes, convert the function to a table
lut = [lut(i) for i in range(256)] * self.im.bands
if self.mode == "F":
# FIXME: _imaging returns a confusing error message for this case
raise ValueError("point operation not supported for this mode")
return self._new(self.im.point(lut, mode))
def putalpha(self, alpha):
"""
Adds or replaces the alpha layer in this image. If the image
does not have an alpha layer, it's converted to "LA" or "RGBA".
The new layer must be either "L" or "1".
:param alpha: The new alpha layer. This can either be an "L" or "1"
image having the same size as this image, or an integer or
other color value.
"""
self.load()
if self.readonly:
self._copy()
if self.mode not in ("LA", "RGBA"):
# attempt to promote self to a matching alpha mode
try:
mode = getmodebase(self.mode) + "A"
try:
self.im.setmode(mode)
except (AttributeError, ValueError):
# do things the hard way
im = self.im.convert(mode)
if im.mode not in ("LA", "RGBA"):
raise ValueError # sanity check
self.im = im
self.mode = self.im.mode
except (KeyError, ValueError):
raise ValueError("illegal image mode")
if self.mode == "LA":
band = 1
else:
band = 3
if isImageType(alpha):
# alpha layer
if alpha.mode not in ("1", "L"):
raise ValueError("illegal image mode")
alpha.load()
if alpha.mode == "1":
alpha = alpha.convert("L")
else:
# constant alpha
try:
self.im.fillband(band, alpha)
except (AttributeError, ValueError):
# do things the hard way
alpha = new("L", self.size, alpha)
else:
return
self.im.putband(alpha.im, band)
def putdata(self, data, scale=1.0, offset=0.0):
"""
Copies pixel data to this image. This method copies data from a
sequence object into the image, starting at the upper left
corner (0, 0), and continuing until either the image or the
sequence ends. The scale and offset values are used to adjust
the sequence values: **pixel = value*scale + offset**.
:param data: A sequence object.
:param scale: An optional scale value. The default is 1.0.
:param offset: An optional offset value. The default is 0.0.
"""
self.load()
if self.readonly:
self._copy()
self.im.putdata(data, scale, offset)
def putpalette(self, data, rawmode="RGB"):
"""
Attaches a palette to this image. The image must be a "P" or
"L" image, and the palette sequence must contain 768 integer
values, where each group of three values represent the red,
green, and blue values for the corresponding pixel
index. Instead of an integer sequence, you can use an 8-bit
string.
:param data: A palette sequence (either a list or a string).
"""
from PIL import ImagePalette
if self.mode not in ("L", "P"):
raise ValueError("illegal image mode")
self.load()
if isinstance(data, ImagePalette.ImagePalette):
palette = ImagePalette.raw(data.rawmode, data.palette)
else:
if not isinstance(data, bytes):
if bytes is str:
data = "".join(chr(x) for x in data)
else:
data = bytes(data)
palette = ImagePalette.raw(rawmode, data)
self.mode = "P"
self.palette = palette
self.palette.mode = "RGB"
self.load() # install new palette
def putpixel(self, xy, value):
"""
Modifies the pixel at the given position. The color is given as
a single numerical value for single-band images, and a tuple for
multi-band images.
Note that this method is relatively slow. For more extensive changes,
use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
module instead.
See:
* :py:meth:`~PIL.Image.Image.paste`
* :py:meth:`~PIL.Image.Image.putdata`
* :py:mod:`~PIL.ImageDraw`
:param xy: The pixel coordinate, given as (x, y).
:param value: The pixel value.
"""
self.load()
if self.readonly:
self._copy()
return self.im.putpixel(xy, value)
def resize(self, size, resample=NEAREST):
"""
Returns a resized copy of this image.
:param size: The requested size in pixels, as a 2-tuple:
(width, height).
:param filter: An optional resampling filter. This can be
one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), :py:attr:`PIL.Image.BICUBIC` (cubic spline
interpolation in a 4x4 environment), or
:py:attr:`PIL.Image.ANTIALIAS` (a high-quality downsampling filter).
If omitted, or if the image has mode "1" or "P", it is
set :py:attr:`PIL.Image.NEAREST`.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"):
resample = NEAREST
if self.mode == 'RGBA':
return self.convert('RGBa').resize(size, resample).convert('RGBA')
if resample == ANTIALIAS:
# requires stretch support (imToolkit & PIL 1.1.3)
try:
im = self.im.stretch(size, resample)
except AttributeError:
raise ValueError("unsupported resampling filter")
else:
im = self.im.resize(size, resample)
return self._new(im)
def rotate(self, angle, resample=NEAREST, expand=0):
"""
Returns a rotated copy of this image. This method returns a
copy of this image, rotated the given number of degrees counter
clockwise around its centre.
:param angle: In degrees counter clockwise.
:param filter: An optional resampling filter. This can be
one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), or :py:attr:`PIL.Image.BICUBIC`
(cubic spline interpolation in a 4x4 environment).
If omitted, or if the image has mode "1" or "P", it is
set :py:attr:`PIL.Image.NEAREST`.
:param expand: Optional expansion flag. If true, expands the output
image to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the
input image.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if expand:
import math
angle = -angle * math.pi / 180
matrix = [
math.cos(angle), math.sin(angle), 0.0,
-math.sin(angle), math.cos(angle), 0.0
]
def transform(x, y, matrix=matrix):
(a, b, c, d, e, f) = matrix
return a*x + b*y + c, d*x + e*y + f
# calculate output size
w, h = self.size
xx = []
yy = []
for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
x, y = transform(x, y)
xx.append(x)
yy.append(y)
w = int(math.ceil(max(xx)) - math.floor(min(xx)))
h = int(math.ceil(max(yy)) - math.floor(min(yy)))
# adjust center
x, y = transform(w / 2.0, h / 2.0)
matrix[2] = self.size[0] / 2.0 - x
matrix[5] = self.size[1] / 2.0 - y
return self.transform((w, h), AFFINE, matrix, resample)
if resample not in (NEAREST, BILINEAR, BICUBIC):
raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"):
resample = NEAREST
return self._new(self.im.rotate(angle, resample))
def save(self, fp, format=None, **params):
"""
Saves this image under the given filename. If no format is
specified, the format to use is determined from the filename
extension, if possible.
Keyword options can be used to provide additional instructions
to the writer. If a writer doesn't recognise an option, it is
silently ignored. The available options are described later in
this handbook.
You can use a file object instead of a filename. In this case,
you must always specify the format. The file object must
implement the **seek**, **tell**, and **write**
methods, and be opened in binary mode.
:param file: File name or file object.
:param format: Optional format override. If omitted, the
format to use is determined from the filename extension.
If a file object was used instead of a filename, this
parameter should always be used.
:param options: Extra parameters to the image writer.
:returns: None
:exception KeyError: If the output format could not be determined
from the file name. Use the format option to solve this.
:exception IOError: If the file could not be written. The file
may have been created, and may contain partial data.
"""
if isPath(fp):
filename = fp
else:
if hasattr(fp, "name") and isPath(fp.name):
filename = fp.name
else:
filename = ""
# may mutate self!
self.load()
self.encoderinfo = params
self.encoderconfig = ()
preinit()
ext = os.path.splitext(filename)[1].lower()
if not format:
try:
format = EXTENSION[ext]
except KeyError:
init()
try:
format = EXTENSION[ext]
except KeyError:
raise KeyError(ext) # unknown extension
try:
save_handler = SAVE[format.upper()]
except KeyError:
init()
save_handler = SAVE[format.upper()] # unknown format
if isPath(fp):
fp = builtins.open(fp, "wb")
close = 1
else:
close = 0
try:
save_handler(self, fp, filename)
finally:
# do what we can to clean up
if close:
fp.close()
def seek(self, frame):
"""
Seeks to the given frame in this sequence file. If you seek
beyond the end of the sequence, the method raises an
**EOFError** exception. When a sequence file is opened, the
library automatically seeks to frame 0.
Note that in the current version of the library, most sequence
formats only allows you to seek to the next frame.
See :py:meth:`~PIL.Image.Image.tell`.
:param frame: Frame number, starting at 0.
:exception EOFError: If the call attempts to seek beyond the end
of the sequence.
"""
# overridden by file handlers
if frame != 0:
raise EOFError
def show(self, title=None, command=None):
"""
Displays this image. This method is mainly intended for
debugging purposes.
On Unix platforms, this method saves the image to a temporary
PPM file, and calls the **xv** utility.
On Windows, it saves the image to a temporary BMP file, and uses
the standard BMP display utility to show it (usually Paint).
:param title: Optional title to use for the image window,
where possible.
:param command: command used to show the image
"""
_show(self, title=title, command=command)
def split(self):
"""
Split this image into individual bands. This method returns a
tuple of individual image bands from an image. For example,
splitting an "RGB" image creates three new images each
containing a copy of one of the original bands (red, green,
blue).
:returns: A tuple containing bands.
"""
self.load()
if self.im.bands == 1:
ims = [self.copy()]
else:
ims = []
for i in range(self.im.bands):
ims.append(self._new(self.im.getband(i)))
return tuple(ims)
def tell(self):
"""
Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
:returns: Frame number, starting with 0.
"""
return 0
def thumbnail(self, size, resample=NEAREST):
"""
Make this image into a thumbnail. This method modifies the
image to contain a thumbnail version of itself, no larger than
the given size. This method calculates an appropriate thumbnail
size to preserve the aspect of the image, calls the
:py:meth:`~PIL.Image.Image.draft` method to configure the file reader
(where applicable), and finally resizes the image.
Note that the bilinear and bicubic filters in the current
version of PIL are not well-suited for thumbnail generation.
You should use :py:attr:`PIL.Image.ANTIALIAS` unless speed is much more
important than quality.
Also note that this function modifies the :py:class:`~PIL.Image.Image`
object in place. If you need to use the full resolution image as well, apply
this method to a :py:meth:`~PIL.Image.Image.copy` of the original image.
:param size: Requested size.
:param resample: Optional resampling filter. This can be one
of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,
:py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.ANTIALIAS`
(best quality). If omitted, it defaults to
:py:attr:`PIL.Image.NEAREST` (this will be changed to ANTIALIAS in a
future version).
:returns: None
"""
# FIXME: the default resampling filter will be changed
# to ANTIALIAS in future versions
# preserve aspect ratio
x, y = self.size
if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0])
if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1])
size = x, y
if size == self.size:
return
self.draft(None, size)
self.load()
try:
im = self.resize(size, resample)
except ValueError:
if resample != ANTIALIAS:
raise
im = self.resize(size, NEAREST) # fallback
self.im = im.im
self.mode = im.mode
self.size = size
self.readonly = 0
# FIXME: the different tranform methods need further explanation
# instead of bloating the method docs, add a separate chapter.
def transform(self, size, method, data=None, resample=NEAREST, fill=1):
"""
Transforms this image. This method creates a new image with the
given size, and the same mode as the original, and copies data
to the new image using the given transform.
:param size: The output size.
:param method: The transformation method. This is one of
:py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),
:py:attr:`PIL.Image.AFFINE` (affine transform),
:py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),
:py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
:py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals
in one operation).
:param data: Extra data to the transformation method.
:param resample: Optional resampling filter. It can be one of
:py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
interpolation in a 4x4 environment). If omitted, or if the image
has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if self.mode == 'RGBA':
return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA')
if isinstance(method, ImageTransformHandler):
return method.transform(size, self, resample=resample, fill=fill)
if hasattr(method, "getdata"):
# compatibility w. old-style transform objects
method, data = method.getdata()
if data is None:
raise ValueError("missing method data")
im = new(self.mode, size, None)
if method == MESH:
# list of quads
for box, quad in data:
im.__transformer(box, self, QUAD, quad, resample, fill)
else:
im.__transformer((0, 0)+size, self, method, data, resample, fill)
return im
def __transformer(self, box, image, method, data,
resample=NEAREST, fill=1):
# FIXME: this should be turned into a lazy operation (?)
w = box[2]-box[0]
h = box[3]-box[1]
if method == AFFINE:
# change argument order to match implementation
data = (data[2], data[0], data[1],
data[5], data[3], data[4])
elif method == EXTENT:
# convert extent to an affine transform
x0, y0, x1, y1 = data
xs = float(x1 - x0) / w
ys = float(y1 - y0) / h
method = AFFINE
data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys)
elif method == PERSPECTIVE:
# change argument order to match implementation
data = (data[2], data[0], data[1],
data[5], data[3], data[4],
data[6], data[7])
elif method == QUAD:
# quadrilateral warp. data specifies the four corners
# given as NW, SW, SE, and NE.
nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8]
x0, y0 = nw; As = 1.0 / w; At = 1.0 / h
data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At,
(se[0]-sw[0]-ne[0]+x0)*As*At,
y0, (ne[1]-y0)*As, (sw[1]-y0)*At,
(se[1]-sw[1]-ne[1]+y0)*As*At)
else:
raise ValueError("unknown transformation method")
if resample not in (NEAREST, BILINEAR, BICUBIC):
raise ValueError("unknown resampling filter")
image.load()
self.load()
if image.mode in ("1", "P"):
resample = NEAREST
self.im.transform2(box, image.im, method, data, resample, fill)
def transpose(self, method):
"""
Transpose image (flip or rotate in 90 degree steps)
:param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
:py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
:py:attr:`PIL.Image.ROTATE_180`, or :py:attr:`PIL.Image.ROTATE_270`.
:returns: Returns a flipped or rotated copy of this image.
"""
self.load()
im = self.im.transpose(method)
return self._new(im)
# --------------------------------------------------------------------
# Lazy operations
class _ImageCrop(Image):
def __init__(self, im, box):
Image.__init__(self)
x0, y0, x1, y1 = box
if x1 < x0:
x1 = x0
if y1 < y0:
y1 = y0
self.mode = im.mode
self.size = x1-x0, y1-y0
self.__crop = x0, y0, x1, y1
self.im = im.im
def load(self):
# lazy evaluation!
if self.__crop:
self.im = self.im.crop(self.__crop)
self.__crop = None
if self.im:
return self.im.pixel_access(self.readonly)
# FIXME: future versions should optimize crop/paste
# sequences!
# --------------------------------------------------------------------
# Abstract handlers.
class ImagePointHandler:
# used as a mixin by point transforms (for use with im.point)
pass
class ImageTransformHandler:
# used as a mixin by geometry transforms (for use with im.transform)
pass
# --------------------------------------------------------------------
# Factories
#
# Debugging
def _wedge():
"Create greyscale wedge (for debugging only)"
return Image()._new(core.wedge("L"))
def new(mode, size, color=0):
"""
Creates a new image with the given mode and size.
:param mode: The mode to use for the new image.
:param size: A 2-tuple, containing (width, height) in pixels.
:param color: What color to use for the image. Default is black.
If given, this should be a single integer or floating point value
for single-band modes, and a tuple for multi-band modes (one value
per band). When creating RGB images, you can also use color
strings as supported by the ImageColor module. If the color is
None, the image is not initialised.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if color is None:
# don't initialize
return Image()._new(core.new(mode, size))
if isStringType(color):
# css3-style specifier
from PIL import ImageColor
color = ImageColor.getcolor(color, mode)
return Image()._new(core.fill(mode, size, color))
def frombytes(mode, size, data, decoder_name="raw", *args):
"""
Creates a copy of an image memory from pixel data in a buffer.
In its simplest form, this function takes three arguments
(mode, size, and unpacked pixel data).
You can also use any pixel decoder supported by PIL. For more
information on available decoders, see the section
**Writing Your Own File Decoder**.
Note that this function decodes pixel data only, not entire images.
If you have an entire image in a string, wrap it in a
:py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load
it.
:param mode: The image mode.
:param size: The image size.
:param data: A byte buffer containing raw data for the given mode.
:param decoder_name: What decoder to use.
:param args: Additional parameters for the given decoder.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0]
if decoder_name == "raw" and args == ():
args = mode
im = new(mode, size)
im.frombytes(data, decoder_name, args)
return im
def fromstring(*args, **kw):
"""Deprecated alias to frombytes.
.. deprecated:: 2.0
"""
warnings.warn(
'fromstring() is deprecated. Please call frombytes() instead.',
DeprecationWarning,
stacklevel=2
)
return frombytes(*args, **kw)
def frombuffer(mode, size, data, decoder_name="raw", *args):
"""
Creates an image memory referencing pixel data in a byte buffer.
This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data
in the byte buffer, where possible. This means that changes to the
original buffer object are reflected in this image). Not all modes can
share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK".
Note that this function decodes pixel data only, not entire images.
If you have an entire image file in a string, wrap it in a
**BytesIO** object, and use :py:func:`~PIL.Image.open` to load it.
In the current version, the default parameters used for the "raw" decoder
differs from that used for :py:func:`~PIL.Image.fromstring`. This is a
bug, and will probably be fixed in a future release. The current release
issues a warning if you do this; to disable the warning, you should provide
the full set of parameters. See below for details.
:param mode: The image mode.
:param size: The image size.
:param data: A bytes or other buffer object containing raw
data for the given mode.
:param decoder_name: What decoder to use.
:param args: Additional parameters for the given decoder. For the
default encoder ("raw"), it's recommended that you provide the
full set of parameters::
frombuffer(mode, size, data, "raw", mode, 0, 1)
:returns: An :py:class:`~PIL.Image.Image` object.
.. versionadded:: 1.1.4
"""
"Load image from bytes or buffer"
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0]
if decoder_name == "raw":
if args == ():
if warnings:
warnings.warn(
"the frombuffer defaults may change in a future release; "
"for portability, change the call to read:\n"
" frombuffer(mode, size, data, 'raw', mode, 0, 1)",
RuntimeWarning, stacklevel=2
)
args = mode, 0, -1 # may change to (mode, 0, 1) post-1.1.6
if args[0] in _MAPMODES:
im = new(mode, (1,1))
im = im._new(
core.map_buffer(data, size, decoder_name, None, 0, args)
)
im.readonly = 1
return im
return frombytes(mode, size, data, decoder_name, args)
def fromarray(obj, mode=None):
"""
Creates an image memory from an object exporting the array interface
(using the buffer protocol).
If obj is not contiguous, then the tobytes method is called
and :py:func:`~PIL.Image.frombuffer` is used.
:param obj: Object with array interface
:param mode: Mode to use (will be determined from type if None)
:returns: An image memory.
.. versionadded:: 1.1.6
"""
arr = obj.__array_interface__
shape = arr['shape']
ndim = len(shape)
try:
strides = arr['strides']
except KeyError:
strides = None
if mode is None:
try:
typekey = (1, 1) + shape[2:], arr['typestr']
mode, rawmode = _fromarray_typemap[typekey]
except KeyError:
# print typekey
raise TypeError("Cannot handle this data type")
else:
rawmode = mode
if mode in ["1", "L", "I", "P", "F"]:
ndmax = 2
elif mode == "RGB":
ndmax = 3
else:
ndmax = 4
if ndim > ndmax:
raise ValueError("Too many dimensions.")
size = shape[1], shape[0]
if strides is not None:
if hasattr(obj, 'tobytes'):
obj = obj.tobytes()
else:
obj = obj.tostring()
return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
_fromarray_typemap = {
# (shape, typestr) => mode, rawmode
# first two members of shape are set to one
# ((1, 1), "|b1"): ("1", "1"), # broken
((1, 1), "|u1"): ("L", "L"),
((1, 1), "|i1"): ("I", "I;8"),
((1, 1), "<i2"): ("I", "I;16"),
((1, 1), ">i2"): ("I", "I;16B"),
((1, 1), "<i4"): ("I", "I;32"),
((1, 1), ">i4"): ("I", "I;32B"),
((1, 1), "<f4"): ("F", "F;32F"),
((1, 1), ">f4"): ("F", "F;32BF"),
((1, 1), "<f8"): ("F", "F;64F"),
((1, 1), ">f8"): ("F", "F;64BF"),
((1, 1, 3), "|u1"): ("RGB", "RGB"),
((1, 1, 4), "|u1"): ("RGBA", "RGBA"),
}
# shortcuts
_fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")
_fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")
def open(fp, mode="r"):
"""
Opens and identifies the given image file.
This is a lazy operation; this function identifies the file, but the
actual image data is not read from the file until you try to process
the data (or call the :py:meth:`~PIL.Image.Image.load` method).
See :py:func:`~PIL.Image.new`.
:param file: A filename (string) or a file object. The file object
must implement :py:meth:`~file.read`, :py:meth:`~file.seek`, and
:py:meth:`~file.tell` methods, and be opened in binary mode.
:param mode: The mode. If given, this argument must be "r".
:returns: An :py:class:`~PIL.Image.Image` object.
:exception IOError: If the file cannot be found, or the image cannot be
opened and identified.
"""
if mode != "r":
raise ValueError("bad mode")
if isPath(fp):
filename = fp
fp = builtins.open(fp, "rb")
else:
filename = ""
prefix = fp.read(16)
preinit()
for i in ID:
try:
factory, accept = OPEN[i]
if not accept or accept(prefix):
fp.seek(0)
return factory(fp, filename)
except (SyntaxError, IndexError, TypeError):
#import traceback
#traceback.print_exc()
pass
if init():
for i in ID:
try:
factory, accept = OPEN[i]
if not accept or accept(prefix):
fp.seek(0)
return factory(fp, filename)
except (SyntaxError, IndexError, TypeError):
#import traceback
#traceback.print_exc()
pass
raise IOError("cannot identify image file")
#
# Image processing.
def alpha_composite(im1, im2):
"""
Alpha composite im2 over im1.
:param im1: The first image.
:param im2: The second image. Must have the same mode and size as
the first image.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
im1.load()
im2.load()
return im1._new(core.alpha_composite(im1.im, im2.im))
def blend(im1, im2, alpha):
"""
Creates a new image by interpolating between two input images, using
a constant alpha.::
out = image1 * (1.0 - alpha) + image2 * alpha
:param im1: The first image.
:param im2: The second image. Must have the same mode and size as
the first image.
:param alpha: The interpolation alpha factor. If alpha is 0.0, a
copy of the first image is returned. If alpha is 1.0, a copy of
the second image is returned. There are no restrictions on the
alpha value. If necessary, the result is clipped to fit into
the allowed output range.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
im1.load()
im2.load()
return im1._new(core.blend(im1.im, im2.im, alpha))
def composite(image1, image2, mask):
"""
Create composite image by blending images using a transparency mask.
:param image1: The first image.
:param image2: The second image. Must have the same mode and
size as the first image.
:param mask: A mask image. This image can can have mode
"1", "L", or "RGBA", and must have the same size as the
other two images.
"""
image = image2.copy()
image.paste(image1, None, mask)
return image
def eval(image, *args):
"""
Applies the function (which should take one argument) to each pixel
in the given image. If the image has more than one band, the same
function is applied to each band. Note that the function is
evaluated once for each possible pixel value, so you cannot use
random components or other generators.
:param image: The input image.
:param function: A function object, taking one integer argument.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
return image.point(args[0])
def merge(mode, bands):
"""
Merge a set of single band images into a new multiband image.
:param mode: The mode to use for the output image.
:param bands: A sequence containing one single-band image for
each band in the output image. All bands must have the
same size.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if getmodebands(mode) != len(bands) or "*" in mode:
raise ValueError("wrong number of bands")
for im in bands[1:]:
if im.mode != getmodetype(mode):
raise ValueError("mode mismatch")
if im.size != bands[0].size:
raise ValueError("size mismatch")
im = core.new(mode, bands[0].size)
for i in range(getmodebands(mode)):
bands[i].load()
im.putband(bands[i].im, i)
return bands[0]._new(im)
# --------------------------------------------------------------------
# Plugin registry
def register_open(id, factory, accept=None):
"""
Register an image file plugin. This function should not be used
in application code.
:param id: An image format identifier.
:param factory: An image file factory method.
:param accept: An optional function that can be used to quickly
reject images having another format.
"""
id = id.upper()
ID.append(id)
OPEN[id] = factory, accept
def register_mime(id, mimetype):
"""
Registers an image MIME type. This function should not be used
in application code.
:param id: An image format identifier.
:param mimetype: The image MIME type for this format.
"""
MIME[id.upper()] = mimetype
def register_save(id, driver):
"""
Registers an image save function. This function should not be
used in application code.
:param id: An image format identifier.
:param driver: A function to save images in this format.
"""
SAVE[id.upper()] = driver
def register_extension(id, extension):
"""
Registers an image extension. This function should not be
used in application code.
:param id: An image format identifier.
:param extension: An extension used for this format.
"""
EXTENSION[extension.lower()] = id.upper()
# --------------------------------------------------------------------
# Simple display support. User code may override this.
def _show(image, **options):
# override me, as necessary
_showxv(image, **options)
def _showxv(image, title=None, **options):
from PIL import ImageShow
ImageShow.show(image, title, **options)
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_2084_1 |
crossvul-python_data_bad_2084_3 | #
# The Python Imaging Library.
# $Id$
#
# JPEG (JFIF) file handling
#
# See "Digital Compression and Coding of Continous-Tone Still Images,
# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1)
#
# History:
# 1995-09-09 fl Created
# 1995-09-13 fl Added full parser
# 1996-03-25 fl Added hack to use the IJG command line utilities
# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug
# 1996-05-28 fl Added draft support, JFIF version (0.1)
# 1996-12-30 fl Added encoder options, added progression property (0.2)
# 1997-08-27 fl Save mode 1 images as BW (0.3)
# 1998-07-12 fl Added YCbCr to draft and save methods (0.4)
# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1)
# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2)
# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3)
# 2003-04-25 fl Added experimental EXIF decoder (0.5)
# 2003-06-06 fl Added experimental EXIF GPSinfo decoder
# 2003-09-13 fl Extract COM markers
# 2009-09-06 fl Added icc_profile support (from Florian Hoech)
# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6)
# 2009-03-08 fl Added subsampling support (from Justin Huff).
#
# Copyright (c) 1997-2003 by Secret Labs AB.
# Copyright (c) 1995-1996 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#
__version__ = "0.6"
import array, struct
from PIL import Image, ImageFile, _binary
from PIL.JpegPresets import presets
from PIL._util import isStringType
i8 = _binary.i8
o8 = _binary.o8
i16 = _binary.i16be
i32 = _binary.i32be
#
# Parser
def Skip(self, marker):
n = i16(self.fp.read(2))-2
ImageFile._safe_read(self.fp, n)
def APP(self, marker):
#
# Application marker. Store these in the APP dictionary.
# Also look for well-known application markers.
n = i16(self.fp.read(2))-2
s = ImageFile._safe_read(self.fp, n)
app = "APP%d" % (marker&15)
self.app[app] = s # compatibility
self.applist.append((app, s))
if marker == 0xFFE0 and s[:4] == b"JFIF":
# extract JFIF information
self.info["jfif"] = version = i16(s, 5) # version
self.info["jfif_version"] = divmod(version, 256)
# extract JFIF properties
try:
jfif_unit = i8(s[7])
jfif_density = i16(s, 8), i16(s, 10)
except:
pass
else:
if jfif_unit == 1:
self.info["dpi"] = jfif_density
self.info["jfif_unit"] = jfif_unit
self.info["jfif_density"] = jfif_density
elif marker == 0xFFE1 and s[:5] == b"Exif\0":
# extract Exif information (incomplete)
self.info["exif"] = s # FIXME: value will change
elif marker == 0xFFE2 and s[:5] == b"FPXR\0":
# extract FlashPix information (incomplete)
self.info["flashpix"] = s # FIXME: value will change
elif marker == 0xFFE2 and s[:12] == b"ICC_PROFILE\0":
# Since an ICC profile can be larger than the maximum size of
# a JPEG marker (64K), we need provisions to split it into
# multiple markers. The format defined by the ICC specifies
# one or more APP2 markers containing the following data:
# Identifying string ASCII "ICC_PROFILE\0" (12 bytes)
# Marker sequence number 1, 2, etc (1 byte)
# Number of markers Total of APP2's used (1 byte)
# Profile data (remainder of APP2 data)
# Decoders should use the marker sequence numbers to
# reassemble the profile, rather than assuming that the APP2
# markers appear in the correct sequence.
self.icclist.append(s)
elif marker == 0xFFEE and s[:5] == b"Adobe":
self.info["adobe"] = i16(s, 5)
# extract Adobe custom properties
try:
adobe_transform = i8(s[1])
except:
pass
else:
self.info["adobe_transform"] = adobe_transform
def COM(self, marker):
#
# Comment marker. Store these in the APP dictionary.
n = i16(self.fp.read(2))-2
s = ImageFile._safe_read(self.fp, n)
self.app["COM"] = s # compatibility
self.applist.append(("COM", s))
def SOF(self, marker):
#
# Start of frame marker. Defines the size and mode of the
# image. JPEG is colour blind, so we use some simple
# heuristics to map the number of layers to an appropriate
# mode. Note that this could be made a bit brighter, by
# looking for JFIF and Adobe APP markers.
n = i16(self.fp.read(2))-2
s = ImageFile._safe_read(self.fp, n)
self.size = i16(s[3:]), i16(s[1:])
self.bits = i8(s[0])
if self.bits != 8:
raise SyntaxError("cannot handle %d-bit layers" % self.bits)
self.layers = i8(s[5])
if self.layers == 1:
self.mode = "L"
elif self.layers == 3:
self.mode = "RGB"
elif self.layers == 4:
self.mode = "CMYK"
else:
raise SyntaxError("cannot handle %d-layer images" % self.layers)
if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
self.info["progressive"] = self.info["progression"] = 1
if self.icclist:
# fixup icc profile
self.icclist.sort() # sort by sequence number
if i8(self.icclist[0][13]) == len(self.icclist):
profile = []
for p in self.icclist:
profile.append(p[14:])
icc_profile = b"".join(profile)
else:
icc_profile = None # wrong number of fragments
self.info["icc_profile"] = icc_profile
self.icclist = None
for i in range(6, len(s), 3):
t = s[i:i+3]
# 4-tuples: id, vsamp, hsamp, qtable
self.layer.append((t[0], i8(t[1])//16, i8(t[1])&15, i8(t[2])))
def DQT(self, marker):
#
# Define quantization table. Support baseline 8-bit tables
# only. Note that there might be more than one table in
# each marker.
# FIXME: The quantization tables can be used to estimate the
# compression quality.
n = i16(self.fp.read(2))-2
s = ImageFile._safe_read(self.fp, n)
while len(s):
if len(s) < 65:
raise SyntaxError("bad quantization table marker")
v = i8(s[0])
if v//16 == 0:
self.quantization[v&15] = array.array("b", s[1:65])
s = s[65:]
else:
return # FIXME: add code to read 16-bit tables!
# raise SyntaxError, "bad quantization table element size"
#
# JPEG marker table
MARKER = {
0xFFC0: ("SOF0", "Baseline DCT", SOF),
0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
0xFFC2: ("SOF2", "Progressive DCT", SOF),
0xFFC3: ("SOF3", "Spatial lossless", SOF),
0xFFC4: ("DHT", "Define Huffman table", Skip),
0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
0xFFC7: ("SOF7", "Differential spatial", SOF),
0xFFC8: ("JPG", "Extension", None),
0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
0xFFD0: ("RST0", "Restart 0", None),
0xFFD1: ("RST1", "Restart 1", None),
0xFFD2: ("RST2", "Restart 2", None),
0xFFD3: ("RST3", "Restart 3", None),
0xFFD4: ("RST4", "Restart 4", None),
0xFFD5: ("RST5", "Restart 5", None),
0xFFD6: ("RST6", "Restart 6", None),
0xFFD7: ("RST7", "Restart 7", None),
0xFFD8: ("SOI", "Start of image", None),
0xFFD9: ("EOI", "End of image", None),
0xFFDA: ("SOS", "Start of scan", Skip),
0xFFDB: ("DQT", "Define quantization table", DQT),
0xFFDC: ("DNL", "Define number of lines", Skip),
0xFFDD: ("DRI", "Define restart interval", Skip),
0xFFDE: ("DHP", "Define hierarchical progression", SOF),
0xFFDF: ("EXP", "Expand reference component", Skip),
0xFFE0: ("APP0", "Application segment 0", APP),
0xFFE1: ("APP1", "Application segment 1", APP),
0xFFE2: ("APP2", "Application segment 2", APP),
0xFFE3: ("APP3", "Application segment 3", APP),
0xFFE4: ("APP4", "Application segment 4", APP),
0xFFE5: ("APP5", "Application segment 5", APP),
0xFFE6: ("APP6", "Application segment 6", APP),
0xFFE7: ("APP7", "Application segment 7", APP),
0xFFE8: ("APP8", "Application segment 8", APP),
0xFFE9: ("APP9", "Application segment 9", APP),
0xFFEA: ("APP10", "Application segment 10", APP),
0xFFEB: ("APP11", "Application segment 11", APP),
0xFFEC: ("APP12", "Application segment 12", APP),
0xFFED: ("APP13", "Application segment 13", APP),
0xFFEE: ("APP14", "Application segment 14", APP),
0xFFEF: ("APP15", "Application segment 15", APP),
0xFFF0: ("JPG0", "Extension 0", None),
0xFFF1: ("JPG1", "Extension 1", None),
0xFFF2: ("JPG2", "Extension 2", None),
0xFFF3: ("JPG3", "Extension 3", None),
0xFFF4: ("JPG4", "Extension 4", None),
0xFFF5: ("JPG5", "Extension 5", None),
0xFFF6: ("JPG6", "Extension 6", None),
0xFFF7: ("JPG7", "Extension 7", None),
0xFFF8: ("JPG8", "Extension 8", None),
0xFFF9: ("JPG9", "Extension 9", None),
0xFFFA: ("JPG10", "Extension 10", None),
0xFFFB: ("JPG11", "Extension 11", None),
0xFFFC: ("JPG12", "Extension 12", None),
0xFFFD: ("JPG13", "Extension 13", None),
0xFFFE: ("COM", "Comment", COM)
}
def _accept(prefix):
return prefix[0:1] == b"\377"
##
# Image plugin for JPEG and JFIF images.
class JpegImageFile(ImageFile.ImageFile):
format = "JPEG"
format_description = "JPEG (ISO 10918)"
def _open(self):
s = self.fp.read(1)
if i8(s[0]) != 255:
raise SyntaxError("not a JPEG file")
# Create attributes
self.bits = self.layers = 0
# JPEG specifics (internal)
self.layer = []
self.huffman_dc = {}
self.huffman_ac = {}
self.quantization = {}
self.app = {} # compatibility
self.applist = []
self.icclist = []
while True:
s = s + self.fp.read(1)
i = i16(s)
if i in MARKER:
name, description, handler = MARKER[i]
# print hex(i), name, description
if handler is not None:
handler(self, i)
if i == 0xFFDA: # start of scan
rawmode = self.mode
if self.mode == "CMYK":
rawmode = "CMYK;I" # assume adobe conventions
self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))]
# self.__offset = self.fp.tell()
break
s = self.fp.read(1)
elif i == 0 or i == 65535:
# padded marker or junk; move on
s = "\xff"
else:
raise SyntaxError("no marker found")
def draft(self, mode, size):
if len(self.tile) != 1:
return
d, e, o, a = self.tile[0]
scale = 0
if a[0] == "RGB" and mode in ["L", "YCbCr"]:
self.mode = mode
a = mode, ""
if size:
scale = max(self.size[0] // size[0], self.size[1] // size[1])
for s in [8, 4, 2, 1]:
if scale >= s:
break
e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1]
self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s)
scale = s
self.tile = [(d, e, o, a)]
self.decoderconfig = (scale, 1)
return self
def load_djpeg(self):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
file = tempfile.mktemp()
os.system("djpeg %s >%s" % (self.filename, file))
try:
self.im = Image.core.open_ppm(file)
finally:
try: os.unlink(file)
except: pass
self.mode = self.im.mode
self.size = self.im.size
self.tile = []
def _getexif(self):
return _getexif(self)
def _getexif(self):
# Extract EXIF information. This method is highly experimental,
# and is likely to be replaced with something better in a future
# version.
from PIL import TiffImagePlugin
import io
def fixup(value):
if len(value) == 1:
return value[0]
return value
# The EXIF record consists of a TIFF file embedded in a JPEG
# application marker (!).
try:
data = self.info["exif"]
except KeyError:
return None
file = io.BytesIO(data[6:])
head = file.read(8)
exif = {}
# process dictionary
info = TiffImagePlugin.ImageFileDirectory(head)
info.load(file)
for key, value in info.items():
exif[key] = fixup(value)
# get exif extension
try:
file.seek(exif[0x8769])
except KeyError:
pass
else:
info = TiffImagePlugin.ImageFileDirectory(head)
info.load(file)
for key, value in info.items():
exif[key] = fixup(value)
# get gpsinfo extension
try:
file.seek(exif[0x8825])
except KeyError:
pass
else:
info = TiffImagePlugin.ImageFileDirectory(head)
info.load(file)
exif[0x8825] = gps = {}
for key, value in info.items():
gps[key] = fixup(value)
return exif
# --------------------------------------------------------------------
# stuff to save JPEG files
RAWMODE = {
"1": "L",
"L": "L",
"RGB": "RGB",
"RGBA": "RGB",
"RGBX": "RGB",
"CMYK": "CMYK;I", # assume adobe conventions
"YCbCr": "YCbCr",
}
zigzag_index = ( 0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63)
samplings = {
(1, 1, 1, 1, 1, 1): 0,
(2, 1, 1, 1, 1, 1): 1,
(2, 2, 1, 1, 1, 1): 2,
}
def convert_dict_qtables(qtables):
qtables = [qtables[key] for key in xrange(len(qtables)) if qtables.has_key(key)]
for idx, table in enumerate(qtables):
qtables[idx] = [table[i] for i in zigzag_index]
return qtables
def get_sampling(im):
sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]
return samplings.get(sampling, -1)
def _save(im, fp, filename):
try:
rawmode = RAWMODE[im.mode]
except KeyError:
raise IOError("cannot write mode %s as JPEG" % im.mode)
info = im.encoderinfo
dpi = info.get("dpi", (0, 0))
quality = info.get("quality", 0)
subsampling = info.get("subsampling", -1)
qtables = info.get("qtables")
if quality == "keep":
quality = 0
subsampling = "keep"
qtables = "keep"
elif quality in presets:
preset = presets[quality]
quality = 0
subsampling = preset.get('subsampling', -1)
qtables = preset.get('quantization')
elif not isinstance(quality, int):
raise ValueError("Invalid quality setting")
else:
if subsampling in presets:
subsampling = presets[subsampling].get('subsampling', -1)
if qtables in presets:
qtables = presets[qtables].get('quantization')
if subsampling == "4:4:4":
subsampling = 0
elif subsampling == "4:2:2":
subsampling = 1
elif subsampling == "4:1:1":
subsampling = 2
elif subsampling == "keep":
if im.format != "JPEG":
raise ValueError("Cannot use 'keep' when original image is not a JPEG")
subsampling = get_sampling(im)
def validate_qtables(qtables):
if qtables is None:
return qtables
if isStringType(qtables):
try:
lines = [int(num) for line in qtables.splitlines()
for num in line.split('#', 1)[0].split()]
except ValueError:
raise ValueError("Invalid quantization table")
else:
qtables = [lines[s:s+64] for s in xrange(0, len(lines), 64)]
if isinstance(qtables, (tuple, list, dict)):
if isinstance(qtables, dict):
qtables = convert_dict_qtables(qtables)
elif isinstance(qtables, tuple):
qtables = list(qtables)
if not (0 < len(qtables) < 5):
raise ValueError("None or too many quantization tables")
for idx, table in enumerate(qtables):
try:
if len(table) != 64:
raise
table = array.array('b', table)
except TypeError:
raise ValueError("Invalid quantization table")
else:
qtables[idx] = list(table)
return qtables
if qtables == "keep":
if im.format != "JPEG":
raise ValueError("Cannot use 'keep' when original image is not a JPEG")
qtables = getattr(im, "quantization", None)
qtables = validate_qtables(qtables)
extra = b""
icc_profile = info.get("icc_profile")
if icc_profile:
ICC_OVERHEAD_LEN = 14
MAX_BYTES_IN_MARKER = 65533
MAX_DATA_BYTES_IN_MARKER = MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN
markers = []
while icc_profile:
markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:]
i = 1
for marker in markers:
size = struct.pack(">H", 2 + ICC_OVERHEAD_LEN + len(marker))
extra = extra + (b"\xFF\xE2" + size + b"ICC_PROFILE\0" + o8(i) + o8(len(markers)) + marker)
i = i + 1
# get keyword arguments
im.encoderconfig = (
quality,
# "progressive" is the official name, but older documentation
# says "progression"
# FIXME: issue a warning if the wrong form is used (post-1.1.7)
"progressive" in info or "progression" in info,
info.get("smooth", 0),
"optimize" in info,
info.get("streamtype", 0),
dpi[0], dpi[1],
subsampling,
qtables,
extra,
info.get("exif", b"")
)
# if we optimize, libjpeg needs a buffer big enough to hold the whole image in a shot.
# Guessing on the size, at im.size bytes. (raw pizel size is channels*size, this
# is a value that's been used in a django patch.
# https://github.com/jdriscoll/django-imagekit/issues/50
bufsize=0
if "optimize" in info or "progressive" in info or "progression" in info:
bufsize = im.size[0]*im.size[1]
# The exif info needs to be written as one block, + APP1, + one spare byte.
# Ensure that our buffer is big enough
bufsize = max(ImageFile.MAXBLOCK, bufsize, len(info.get("exif",b"")) + 5 )
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)], bufsize)
def _save_cjpeg(im, fp, filename):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities.
import os
file = im._dump()
os.system("cjpeg %s >%s" % (file, filename))
try: os.unlink(file)
except: pass
# -------------------------------------------------------------------q-
# Registry stuff
Image.register_open("JPEG", JpegImageFile, _accept)
Image.register_save("JPEG", _save)
Image.register_extension("JPEG", ".jfif")
Image.register_extension("JPEG", ".jpe")
Image.register_extension("JPEG", ".jpg")
Image.register_extension("JPEG", ".jpeg")
Image.register_mime("JPEG", "image/jpeg")
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_2084_3 |
crossvul-python_data_bad_3481_0 | #!/usr/bin/env python
#############################################################################
#
# Run Pyro servers as daemon processes on Unix/Linux.
# This won't work on other operating systems such as Windows.
# Author: Jeff Bauer (jbauer@rubic.com)
# This software is released under the MIT software license.
# Based on an earlier daemonize module by Jeffery Kunce
# Updated by Luis Camaano to double-fork-detach.
#
# DEPRECATED. Don't use this in new code.
#
# This is part of "Pyro" - Python Remote Objects
# which is (c) Irmen de Jong - irmen@razorvine.net
#
#############################################################################
import sys, os, time
from signal import SIGINT
class DaemonizerException:
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Daemonizer:
"""
Daemonizer is a class wrapper to run a Pyro server program
in the background as daemon process. The only requirement
is for the derived class to implement a main_loop() method.
See Test class below for an example.
The following command line operations are provided to support
typical /etc/init.d startup/shutdown on Unix systems:
start | stop | restart
In addition, a daemonized program can be called with arguments:
status - check if process is still running
debug - run the program in non-daemon mode for testing
Note: Since Daemonizer uses fork(), it will not work on non-Unix
systems.
"""
def __init__(self, pidfile=None):
if not pidfile:
self.pidfile = "/tmp/%s.pid" % self.__class__.__name__.lower()
else:
self.pidfile = pidfile
def become_daemon(self, root_dir='/'):
if os.fork() != 0: # launch child and ...
os._exit(0) # kill off parent
os.setsid()
os.chdir(root_dir)
os.umask(0)
if os.fork() != 0: # fork again so we are not a session leader
os._exit(0)
sys.stdin.close()
sys.__stdin__ = sys.stdin
sys.stdout.close()
sys.stdout = sys.__stdout__ = _NullDevice()
sys.stderr.close()
sys.stderr = sys.__stderr__ = _NullDevice()
for fd in range(1024):
try:
os.close(fd)
except OSError:
pass
def daemon_start(self, start_as_daemon=1):
if start_as_daemon:
self.become_daemon()
if self.is_process_running():
msg = "Unable to start server. Process is already running."
raise DaemonizerException(msg)
f = open(self.pidfile, 'w')
f.write("%s" % os.getpid())
f.close()
self.main_loop()
def daemon_stop(self):
pid = self.get_pid()
try:
os.kill(pid, SIGINT) # SIGTERM is too harsh...
time.sleep(1)
try:
os.unlink(self.pidfile)
except OSError:
pass
except IOError:
pass
def get_pid(self):
try:
f = open(self.pidfile)
pid = int(f.readline().strip())
f.close()
except IOError:
pid = None
return pid
def is_process_running(self):
pid = self.get_pid()
if pid:
try:
os.kill(pid, 0)
return 1
except OSError:
pass
return 0
def main_loop(self):
"""NOTE: This method must be implemented in the derived class."""
msg = "main_loop method not implemented in derived class: %s" % \
self.__class__.__name__
raise DaemonizerException(msg)
def process_command_line(self, argv, verbose=1):
usage = "usage: %s start | stop | restart | status | debug " \
"(run as non-daemon)" % os.path.basename(argv[0])
if len(argv) < 2:
print usage
raise SystemExit
else:
operation = argv[1]
pid = self.get_pid()
if operation == 'status':
if self.is_process_running():
print "Server process %s is running." % pid
else:
print "Server is not running."
elif operation == 'start':
if self.is_process_running():
print "Server process %s is already running." % pid
raise SystemExit
else:
if verbose:
print "Starting server process."
self.daemon_start()
elif operation == 'stop':
if self.is_process_running():
self.daemon_stop()
if verbose:
print "Server process %s stopped." % pid
else:
print "Server process %s is not running." % pid
raise SystemExit
elif operation == 'restart':
self.daemon_stop()
if verbose:
print "Restarting server process."
self.daemon_start()
elif operation == 'debug':
self.daemon_start(0)
else:
print "Unknown operation:", operation
raise SystemExit
class _NullDevice:
"""A substitute for stdout/stderr that writes to nowhere."""
def write(self, s):
pass
class Test(Daemonizer):
def __init__(self):
Daemonizer.__init__(self)
def main_loop(self):
while 1:
time.sleep(1)
if __name__ == "__main__":
test = Test()
test.process_command_line(sys.argv)
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_3481_0 |
crossvul-python_data_good_2836_0 | from __future__ import print_function
import argparse
import json
from oauthlib.oauth2 import LegacyApplicationClient
import logging
import logging.handlers
from requests_oauthlib import OAuth2Session
import os
import requests
import six
import sys
import traceback
from six.moves.urllib.parse import quote as urlquote
from six.moves.urllib.parse import urlparse
# ------------------------------------------------------------------------------
logger = None
prog_name = os.path.basename(sys.argv[0])
AUTH_ROLES = ['root-admin', 'realm-admin', 'anonymous']
LOG_FILE_ROTATION_COUNT = 3
TOKEN_URL_TEMPLATE = (
'{server}/auth/realms/{realm}/protocol/openid-connect/token')
GET_SERVER_INFO_TEMPLATE = (
'{server}/auth/admin/serverinfo/')
GET_REALMS_URL_TEMPLATE = (
'{server}/auth/admin/realms')
CREATE_REALM_URL_TEMPLATE = (
'{server}/auth/admin/realms')
DELETE_REALM_URL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}')
GET_REALM_METADATA_TEMPLATE = (
'{server}/auth/realms/{realm}/protocol/saml/descriptor')
CLIENT_REPRESENTATION_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients/{id}')
GET_CLIENTS_URL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients')
CLIENT_DESCRIPTOR_URL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/client-description-converter')
CREATE_CLIENT_URL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients')
GET_INITIAL_ACCESS_TOKEN_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients-initial-access')
SAML2_CLIENT_REGISTRATION_TEMPLATE = (
'{server}/auth/realms/{realm}/clients-registrations/saml2-entity-descriptor')
GET_CLIENT_PROTOCOL_MAPPERS_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients/{id}/protocol-mappers/models')
GET_CLIENT_PROTOCOL_MAPPERS_BY_PROTOCOL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients/{id}/protocol-mappers/protocol/{protocol}')
POST_CLIENT_PROTOCOL_MAPPER_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients/{id}/protocol-mappers/models')
ADMIN_CLIENT_ID = 'admin-cli'
# ------------------------------------------------------------------------------
class RESTError(Exception):
def __init__(self, status_code, status_reason,
response_json, response_text, cmd):
self.status_code = status_code
self.status_reason = status_reason
self.error_description = None
self.error = None
self.response_json = response_json
self.response_text = response_text
self.cmd = cmd
self.message = '{status_reason}({status_code}): '.format(
status_reason=self.status_reason,
status_code=self.status_code)
if response_json:
self.error_description = response_json.get('error_description')
if self.error_description is None:
self.error_description = response_json.get('errorMessage')
self.error = response_json.get('error')
self.message += '"{error_description}" [{error}]'.format(
error_description=self.error_description,
error=self.error)
else:
self.message += '"{response_text}"'.format(
response_text=self.response_text)
self.args = (self.message,)
def __str__(self):
return self.message
# ------------------------------------------------------------------------------
def configure_logging(options):
global logger # pylint: disable=W0603
log_dir = os.path.dirname(options.log_file)
if os.path.exists(log_dir):
if not os.path.isdir(log_dir):
raise ValueError('logging directory "{log_dir}" exists but is not '
'directory'.format(log_dir=log_dir))
else:
os.makedirs(log_dir)
log_level = logging.ERROR
if options.verbose:
log_level = logging.INFO
if options.debug:
log_level = logging.DEBUG
# These two lines enable debugging at httplib level
# (requests->urllib3->http.client) You will see the REQUEST,
# including HEADERS and DATA, and RESPONSE with HEADERS but
# without DATA. The only thing missing will be the
# response.body which is not logged.
try:
import http.client as http_client # Python 3
except ImportError:
import httplib as http_client # Python 2
http_client.HTTPConnection.debuglevel = 1
# Turn on cookielib debugging
if False:
try:
import http.cookiejar as cookiejar
except ImportError:
import cookielib as cookiejar # Python 2
cookiejar.debug = True
logger = logging.getLogger(prog_name)
try:
file_handler = logging.handlers.RotatingFileHandler(
options.log_file, backupCount=LOG_FILE_ROTATION_COUNT)
except IOError as e:
print('Unable to open log file %s (%s)' % (options.log_file, e),
file=sys.stderr)
else:
formatter = logging.Formatter(
'%(asctime)s %(name)s %(levelname)s: %(message)s')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
console_handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(message)s')
console_handler.setFormatter(formatter)
console_handler.setLevel(log_level)
logger.addHandler(console_handler)
# Set the log level on the logger to the lowest level
# possible. This allows the message to be emitted from the logger
# to it's handlers where the level will be filtered on a per
# handler basis.
logger.setLevel(1)
# ------------------------------------------------------------------------------
def json_pretty(text):
return json.dumps(json.loads(text),
indent=4, sort_keys=True)
def py_json_pretty(py_json):
return json_pretty(json.dumps(py_json))
def server_name_from_url(url):
return urlparse(url).netloc
def get_realm_names_from_realms(realms):
return [x['realm'] for x in realms]
def get_client_client_ids_from_clients(clients):
return [x['clientId'] for x in clients]
def find_client_by_name(clients, client_id):
for client in clients:
if client.get('clientId') == client_id:
return client
raise KeyError('{item} not found'.format(item=client_id))
# ------------------------------------------------------------------------------
class KeycloakREST(object):
def __init__(self, server, auth_role=None, session=None):
self.server = server
self.auth_role = auth_role
self.session = session
def get_initial_access_token(self, realm_name):
cmd_name = "get initial access token for realm '{realm}'".format(
realm=realm_name)
url = GET_INITIAL_ACCESS_TOKEN_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
params = {"expiration": 60, # seconds
"count": 1}
response = self.session.post(url, json=params)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json # ClientInitialAccessPresentation
def get_server_info(self):
cmd_name = "get server info"
url = GET_SERVER_INFO_TEMPLATE.format(server=self.server)
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def get_realms(self):
cmd_name = "get realms"
url = GET_REALMS_URL_TEMPLATE.format(server=self.server)
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def create_realm(self, realm_name):
cmd_name = "create realm '{realm}'".format(realm=realm_name)
url = CREATE_REALM_URL_TEMPLATE.format(server=self.server)
logger.debug("%s on server %s", cmd_name, self.server)
params = {"enabled": True,
"id": realm_name,
"realm": realm_name,
}
response = self.session.post(url, json=params)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.created:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def delete_realm(self, realm_name):
cmd_name = "delete realm '{realm}'".format(realm=realm_name)
url = DELETE_REALM_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.delete(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.no_content:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def get_realm_metadata(self, realm_name):
cmd_name = "get metadata for realm '{realm}'".format(realm=realm_name)
url = GET_REALM_METADATA_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.ok:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
return response.text
def get_clients(self, realm_name):
cmd_name = "get clients in realm '{realm}'".format(realm=realm_name)
url = GET_CLIENTS_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def get_client_by_id(self, realm_name, id):
cmd_name = "get client id {id} in realm '{realm}'".format(
id=id, realm=realm_name)
url = GET_CLIENTS_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
params = {'clientID': id}
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url, params=params)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def get_client_by_name(self, realm_name, client_name):
clients = self.get_clients(realm_name)
client = find_client_by_name(clients, client_name)
id = client.get('id')
logger.debug("client name '%s' mapped to id '%s'",
client_name, id)
logger.debug("client %s\n%s", client_name, py_json_pretty(client))
return client
def get_client_id_by_name(self, realm_name, client_name):
client = self.get_client_by_name(realm_name, client_name)
id = client.get('id')
return id
def get_client_descriptor(self, realm_name, metadata):
cmd_name = "get client descriptor realm '{realm}'".format(
realm=realm_name)
url = CLIENT_DESCRIPTOR_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
headers = {'Content-Type': 'application/xml;charset=utf-8'}
response = self.session.post(url, headers=headers, data=metadata)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def create_client_from_descriptor(self, realm_name, descriptor):
cmd_name = "create client from descriptor "
"'{client_id}'in realm '{realm}'".format(
client_id=descriptor['clientId'], realm=realm_name)
url = CREATE_CLIENT_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.post(url, json=descriptor)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.created:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def create_client(self, realm_name, metadata):
logger.debug("create client in realm %s on server %s",
realm_name, self.server)
descriptor = self.get_client_descriptor(realm_name, metadata)
self.create_client_from_descriptor(realm_name, descriptor)
return descriptor
def register_client(self, initial_access_token, realm_name, metadata):
cmd_name = "register_client realm '{realm}'".format(
realm=realm_name)
url = SAML2_CLIENT_REGISTRATION_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
headers = {'Content-Type': 'application/xml;charset=utf-8'}
if initial_access_token:
headers['Authorization'] = 'Bearer {token}'.format(
token=initial_access_token)
response = self.session.post(url, headers=headers, data=metadata)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.created):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json # ClientRepresentation
def delete_client_by_name(self, realm_name, client_name):
id = self.get_client_id_by_name(realm_name, client_name)
self.delete_client_by_id(realm_name, id)
def delete_client_by_id(self, realm_name, id):
cmd_name = "delete client id '{id}'in realm '{realm}'".format(
id=id, realm=realm_name)
url = CLIENT_REPRESENTATION_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name),
id=urlquote(id))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.delete(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.no_content:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def update_client(self, realm_name, client):
id = client['id']
cmd_name = "update client {id} in realm '{realm}'".format(
id=client['clientId'], realm=realm_name)
url = CLIENT_REPRESENTATION_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name),
id=urlquote(id))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.put(url, json=client)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.no_content:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def update_client_attributes(self, realm_name, client, update_attrs):
client_id = client['clientId']
logger.debug("update client attrs: client_id=%s "
"current attrs=%s update=%s" % (client_id, client['attributes'],
update_attrs))
client['attributes'].update(update_attrs)
logger.debug("update client attrs: client_id=%s "
"new attrs=%s" % (client_id, client['attributes']))
self.update_client(realm_name, client);
def update_client_by_name_attributes(self, realm_name, client_name,
update_attrs):
client = self.get_client_by_name(realm_name, client_name)
self.update_client_attributes(realm_name, client, update_attrs)
def new_saml_group_protocol_mapper(self, mapper_name, attribute_name,
friendly_name=None,
single_attribute=True):
mapper = {
'protocol': 'saml',
'name': mapper_name,
'protocolMapper': 'saml-group-membership-mapper',
'config': {
'attribute.name': attribute_name,
'attribute.nameformat': 'Basic',
'single': single_attribute,
'full.path': False,
},
}
if friendly_name:
mapper['config']['friendly.name'] = friendly_name
return mapper
def create_client_protocol_mapper(self, realm_name, client, mapper):
id = client['id']
cmd_name = ("create protocol-mapper '{mapper_name}' for client {id} "
"in realm '{realm}'".format(
mapper_name=mapper['name'],id=client['clientId'], realm=realm_name))
url = POST_CLIENT_PROTOCOL_MAPPER_TEMPLATE.format(
server=self.server,
realm=urlquote(realm_name),
id=urlquote(id))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.post(url, json=mapper)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.created:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def create_client_by_name_protocol_mapper(self, realm_name, client_name,
mapper):
client = self.get_client_by_name(realm_name, client_name)
self.create_client_protocol_mapper(realm_name, client, mapper)
def add_client_by_name_redirect_uris(self, realm_name, client_name, uris):
client = self.get_client_by_name(realm_name, client_name)
uris = set(uris)
redirect_uris = set(client['redirectUris'])
redirect_uris |= uris
client['redirectUris'] = list(redirect_uris)
self.update_client(realm_name, client);
def remove_client_by_name_redirect_uris(self, realm_name, client_name, uris):
client = self.get_client_by_name(realm_name, client_name)
uris = set(uris)
redirect_uris = set(client['redirectUris'])
redirect_uris -= uris
client['redirectUris'] = list(redirect_uris)
self.update_client(realm_name, client);
# ------------------------------------------------------------------------------
class KeycloakAdminConnection(KeycloakREST):
def __init__(self, server, auth_role, realm, client_id,
username, password, tls_verify):
super(KeycloakAdminConnection, self).__init__(server, auth_role)
self.realm = realm
self.client_id = client_id
self.username = username
self.password = password
self.session = self._create_session(tls_verify)
def _create_session(self, tls_verify):
token_url = TOKEN_URL_TEMPLATE.format(
server=self.server, realm=urlquote(self.realm))
refresh_url = token_url
client = LegacyApplicationClient(client_id=self.client_id)
session = OAuth2Session(client=client,
auto_refresh_url=refresh_url,
auto_refresh_kwargs={
'client_id': self.client_id})
session.verify = tls_verify
token = session.fetch_token(token_url=token_url,
username=self.username,
password=self.password,
client_id=self.client_id,
verify=session.verify)
return session
class KeycloakAnonymousConnection(KeycloakREST):
def __init__(self, server, tls_verify):
super(KeycloakAnonymousConnection, self).__init__(server, 'anonymous')
self.session = self._create_session(tls_verify)
def _create_session(self, tls_verify):
session = requests.Session()
session.verify = tls_verify
return session
# ------------------------------------------------------------------------------
def do_server_info(options, conn):
server_info = conn.get_server_info()
print(json_pretty(server_info))
def do_list_realms(options, conn):
realms = conn.get_realms()
realm_names = get_realm_names_from_realms(realms)
print('\n'.join(sorted(realm_names)))
def do_create_realm(options, conn):
conn.create_realm(options.realm_name)
def do_delete_realm(options, conn):
conn.delete_realm(options.realm_name)
def do_get_realm_metadata(options, conn):
metadata = conn.get_realm_metadata(options.realm_name)
print(metadata)
def do_list_clients(options, conn):
clients = conn.get_clients(options.realm_name)
client_ids = get_client_client_ids_from_clients(clients)
print('\n'.join(sorted(client_ids)))
def do_create_client(options, conn):
metadata = options.metadata.read()
descriptor = conn.create_client(options.realm_name, metadata)
def do_register_client(options, conn):
metadata = options.metadata.read()
client_representation = conn.register_client(
options.initial_access_token,
options.realm_name, metadata)
def do_delete_client(options, conn):
conn.delete_client_by_name(options.realm_name, options.client_name)
def do_client_test(options, conn):
'experimental test code used during development'
uri = 'https://openstack.jdennis.oslab.test:5000/v3/mellon/fooResponse'
conn.remove_client_by_name_redirect_uri(options.realm_name,
options.client_name,
uri)
# ------------------------------------------------------------------------------
verbose_help = '''
The structure of the command line arguments is "noun verb" where noun
is one of Keycloak's data items (e.g. realm, client, etc.) and the
verb is an action to perform on the item. Each of the nouns and verbs
may have their own set of arguments which must follow the noun or
verb.
For example to delete the client XYZ in the realm ABC:
echo password | {prog_name} -s http://example.com:8080 -P - client delete -r ABC -c XYZ
where 'client' is the noun, 'delete' is the verb and -r ABC -c XYZ are
arguments to the delete action.
If the command completes successfully the exit status is 0. The exit
status is 1 if an authenticated connection with the server cannont be
successfully established. The exit status is 2 if the REST operation
fails.
The server should be a scheme://hostname:port URL.
'''
class TlsVerifyAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super(TlsVerifyAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
if values.lower() in ['true', 'yes', 'on']:
verify = True
elif values.lower() in ['false', 'no', 'off']:
verify = False
else:
verify = values
setattr(namespace, self.dest, verify)
def main():
global logger
result = 0
parser = argparse.ArgumentParser(description='Keycloak REST client',
prog=prog_name,
epilog=verbose_help.format(prog_name=prog_name),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--verbose', action='store_true',
help='be chatty')
parser.add_argument('-d', '--debug', action='store_true',
help='turn on debug info')
parser.add_argument('--show-traceback', action='store_true',
help='exceptions print traceback in addition to '
'error message')
parser.add_argument('--log-file',
default='{prog_name}.log'.format(
prog_name=prog_name),
help='log file pathname')
parser.add_argument('--permit-insecure-transport', action='store_true',
help='Normally secure transport such as TLS '
'is required, defeat this check')
parser.add_argument('--tls-verify', action=TlsVerifyAction,
default=True,
help='TLS certificate verification for requests to'
' the server. May be one of case insenstive '
'[true, yes, on] to enable,'
'[false, no, off] to disable.'
'Or the pathname to a OpenSSL CA bundle to use.'
' Default is True.')
group = parser.add_argument_group('Server')
group.add_argument('-s', '--server',
required=True,
help='DNS name or IP address of Keycloak server')
group.add_argument('-a', '--auth-role',
choices=AUTH_ROLES,
default='root-admin',
help='authenticating as what type of user (default: root-admin)')
group.add_argument('-u', '--admin-username',
default='admin',
help='admin user name (default: admin)')
group.add_argument('-P', '--admin-password-file',
type=argparse.FileType('rb'),
help=('file containing admin password '
'(or use a hyphen "-" to read the password '
'from stdin)'))
group.add_argument('--admin-realm',
default='master',
help='realm admin belongs to')
cmd_parsers = parser.add_subparsers(help='available commands')
# --- realm commands ---
realm_parser = cmd_parsers.add_parser('realm',
help='realm operations')
sub_parser = realm_parser.add_subparsers(help='realm commands')
cmd_parser = sub_parser.add_parser('server_info',
help='dump server info')
cmd_parser.set_defaults(func=do_server_info)
cmd_parser = sub_parser.add_parser('list',
help='list realm names')
cmd_parser.set_defaults(func=do_list_realms)
cmd_parser = sub_parser.add_parser('create',
help='create new realm')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.set_defaults(func=do_create_realm)
cmd_parser = sub_parser.add_parser('delete',
help='delete existing realm')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.set_defaults(func=do_delete_realm)
cmd_parser = sub_parser.add_parser('metadata',
help='retrieve realm metadata')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.set_defaults(func=do_get_realm_metadata)
# --- client commands ---
client_parser = cmd_parsers.add_parser('client',
help='client operations')
sub_parser = client_parser.add_subparsers(help='client commands')
cmd_parser = sub_parser.add_parser('list',
help='list client names')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.set_defaults(func=do_list_clients)
cmd_parser = sub_parser.add_parser('create',
help='create new client')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.add_argument('-m', '--metadata', type=argparse.FileType('rb'),
required=True,
help='SP metadata file or stdin')
cmd_parser.set_defaults(func=do_create_client)
cmd_parser = sub_parser.add_parser('register',
help='register new client')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.add_argument('-m', '--metadata', type=argparse.FileType('rb'),
required=True,
help='SP metadata file or stdin')
cmd_parser.add_argument('--initial-access-token', required=True,
help='realm initial access token for '
'client registeration')
cmd_parser.set_defaults(func=do_register_client)
cmd_parser = sub_parser.add_parser('delete',
help='delete existing client')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.add_argument('-c', '--client-name', required=True,
help='client name')
cmd_parser.set_defaults(func=do_delete_client)
cmd_parser = sub_parser.add_parser('test',
help='experimental test used during '
'development')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.add_argument('-c', '--client-name', required=True,
help='client name')
cmd_parser.set_defaults(func=do_client_test)
# Process command line arguments
options = parser.parse_args()
configure_logging(options)
if options.permit_insecure_transport:
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Get admin password
options.admin_password = None
# 1. Try password file
if options.admin_password_file is not None:
options.admin_password = options.keycloak_admin_password_file.readline().strip()
options.keycloak_admin_password_file.close()
# 2. Try KEYCLOAK_ADMIN_PASSWORD environment variable
if options.admin_password is None:
if (('KEYCLOAK_ADMIN_PASSWORD' in os.environ) and
(os.environ['KEYCLOAK_ADMIN_PASSWORD'])):
options.admin_password = os.environ['KEYCLOAK_ADMIN_PASSWORD']
try:
anonymous_conn = KeycloakAnonymousConnection(options.server,
options.tls_verify)
admin_conn = KeycloakAdminConnection(options.server,
options.auth_role,
options.admin_realm,
ADMIN_CLIENT_ID,
options.admin_username,
options.admin_password,
options.tls_verify)
except Exception as e:
if options.show_traceback:
traceback.print_exc()
print(six.text_type(e), file=sys.stderr)
result = 1
return result
try:
if options.func == do_register_client:
conn = admin_conn
else:
conn = admin_conn
result = options.func(options, conn)
except Exception as e:
if options.show_traceback:
traceback.print_exc()
print(six.text_type(e), file=sys.stderr)
result = 2
return result
return result
# ------------------------------------------------------------------------------
if __name__ == '__main__':
sys.exit(main())
else:
logger = logging.getLogger('keycloak-cli')
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_2836_0 |
crossvul-python_data_bad_2084_2 | #
# The Python Imaging Library.
# $Id$
#
# IPTC/NAA file handling
#
# history:
# 1995-10-01 fl Created
# 1998-03-09 fl Cleaned up and added to PIL
# 2002-06-18 fl Added getiptcinfo helper
#
# Copyright (c) Secret Labs AB 1997-2002.
# Copyright (c) Fredrik Lundh 1995.
#
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
__version__ = "0.3"
from PIL import Image, ImageFile, _binary
import os, tempfile
i8 = _binary.i8
i16 = _binary.i16be
i32 = _binary.i32be
o8 = _binary.o8
COMPRESSION = {
1: "raw",
5: "jpeg"
}
PAD = o8(0) * 4
#
# Helpers
def i(c):
return i32((PAD + c)[-4:])
def dump(c):
for i in c:
print("%02x" % i8(i), end=' ')
print()
##
# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields
# from TIFF and JPEG files, use the <b>getiptcinfo</b> function.
class IptcImageFile(ImageFile.ImageFile):
format = "IPTC"
format_description = "IPTC/NAA"
def getint(self, key):
return i(self.info[key])
def field(self):
#
# get a IPTC field header
s = self.fp.read(5)
if not len(s):
return None, 0
tag = i8(s[1]), i8(s[2])
# syntax
if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9:
raise SyntaxError("invalid IPTC/NAA file")
# field size
size = i8(s[3])
if size > 132:
raise IOError("illegal field length in IPTC/NAA file")
elif size == 128:
size = 0
elif size > 128:
size = i(self.fp.read(size-128))
else:
size = i16(s[3:])
return tag, size
def _is_raw(self, offset, size):
#
# check if the file can be mapped
# DISABLED: the following only slows things down...
return 0
self.fp.seek(offset)
t, sz = self.field()
if sz != size[0]:
return 0
y = 1
while True:
self.fp.seek(sz, 1)
t, s = self.field()
if t != (8, 10):
break
if s != sz:
return 0
y = y + 1
return y == size[1]
def _open(self):
# load descriptive fields
while True:
offset = self.fp.tell()
tag, size = self.field()
if not tag or tag == (8,10):
break
if size:
tagdata = self.fp.read(size)
else:
tagdata = None
if tag in list(self.info.keys()):
if isinstance(self.info[tag], list):
self.info[tag].append(tagdata)
else:
self.info[tag] = [self.info[tag], tagdata]
else:
self.info[tag] = tagdata
# print tag, self.info[tag]
# mode
layers = i8(self.info[(3,60)][0])
component = i8(self.info[(3,60)][1])
if (3,65) in self.info:
id = i8(self.info[(3,65)][0])-1
else:
id = 0
if layers == 1 and not component:
self.mode = "L"
elif layers == 3 and component:
self.mode = "RGB"[id]
elif layers == 4 and component:
self.mode = "CMYK"[id]
# size
self.size = self.getint((3,20)), self.getint((3,30))
# compression
try:
compression = COMPRESSION[self.getint((3,120))]
except KeyError:
raise IOError("Unknown IPTC image compression")
# tile
if tag == (8,10):
if compression == "raw" and self._is_raw(offset, self.size):
self.tile = [(compression, (offset, size + 5, -1),
(0, 0, self.size[0], self.size[1]))]
else:
self.tile = [("iptc", (compression, offset),
(0, 0, self.size[0], self.size[1]))]
def load(self):
if len(self.tile) != 1 or self.tile[0][0] != "iptc":
return ImageFile.ImageFile.load(self)
type, tile, box = self.tile[0]
encoding, offset = tile
self.fp.seek(offset)
# Copy image data to temporary file
outfile = tempfile.mktemp()
o = open(outfile, "wb")
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header
o.write("P5\n%d %d\n255\n" % self.size)
while True:
type, size = self.field()
if type != (8, 10):
break
while size > 0:
s = self.fp.read(min(size, 8192))
if not s:
break
o.write(s)
size = size - len(s)
o.close()
try:
try:
# fast
self.im = Image.core.open_ppm(outfile)
except:
# slightly slower
im = Image.open(outfile)
im.load()
self.im = im.im
finally:
try: os.unlink(outfile)
except: pass
Image.register_open("IPTC", IptcImageFile)
Image.register_extension("IPTC", ".iim")
##
# Get IPTC information from TIFF, JPEG, or IPTC file.
#
# @param im An image containing IPTC data.
# @return A dictionary containing IPTC information, or None if
# no IPTC information block was found.
def getiptcinfo(im):
from PIL import TiffImagePlugin, JpegImagePlugin
import io
data = None
if isinstance(im, IptcImageFile):
# return info dictionary right away
return im.info
elif isinstance(im, JpegImagePlugin.JpegImageFile):
# extract the IPTC/NAA resource
try:
app = im.app["APP13"]
if app[:14] == "Photoshop 3.0\x00":
app = app[14:]
# parse the image resource block
offset = 0
while app[offset:offset+4] == "8BIM":
offset = offset + 4
# resource code
code = JpegImagePlugin.i16(app, offset)
offset = offset + 2
# resource name (usually empty)
name_len = i8(app[offset])
name = app[offset+1:offset+1+name_len]
offset = 1 + offset + name_len
if offset & 1:
offset = offset + 1
# resource data block
size = JpegImagePlugin.i32(app, offset)
offset = offset + 4
if code == 0x0404:
# 0x0404 contains IPTC/NAA data
data = app[offset:offset+size]
break
offset = offset + size
if offset & 1:
offset = offset + 1
except (AttributeError, KeyError):
pass
elif isinstance(im, TiffImagePlugin.TiffImageFile):
# get raw data from the IPTC/NAA tag (PhotoShop tags the data
# as 4-byte integers, so we cannot use the get method...)
try:
data = im.tag.tagdata[TiffImagePlugin.IPTC_NAA_CHUNK]
except (AttributeError, KeyError):
pass
if data is None:
return None # no properties
# create an IptcImagePlugin object without initializing it
class FakeImage:
pass
im = FakeImage()
im.__class__ = IptcImageFile
# parse the IPTC information chunk
im.info = {}
im.fp = io.BytesIO(data)
try:
im._open()
except (IndexError, KeyError):
pass # expected failure
return im.info
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_2084_2 |
crossvul-python_data_good_2084_0 | #
# The Python Imaging Library.
# $Id$
#
# EPS file handling
#
# History:
# 1995-09-01 fl Created (0.1)
# 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
# 1996-08-22 fl Don't choke on floating point BoundingBox values
# 1996-08-23 fl Handle files from Macintosh (0.3)
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
# 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
#
# Copyright (c) 1997-2003 by Secret Labs AB.
# Copyright (c) 1995-2003 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
__version__ = "0.5"
import re
import io
from PIL import Image, ImageFile, _binary
#
# --------------------------------------------------------------------
i32 = _binary.i32le
o32 = _binary.o32le
split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
gs_windows_binary = None
import sys
if sys.platform.startswith('win'):
import shutil
if hasattr(shutil, 'which'):
which = shutil.which
else:
# Python < 3.3
import distutils.spawn
which = distutils.spawn.find_executable
for binary in ('gswin32c', 'gswin64c', 'gs'):
if which(binary) is not None:
gs_windows_binary = binary
break
else:
gs_windows_binary = False
def Ghostscript(tile, size, fp, scale=1):
"""Render an image using Ghostscript"""
# Unpack decoder tile
decoder, tile, offset, data = tile[0]
length, bbox = data
#Hack to support hi-res rendering
scale = int(scale) or 1
orig_size = size
orig_bbox = bbox
size = (size[0] * scale, size[1] * scale)
bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]
#print("Ghostscript", scale, size, orig_size, bbox, orig_bbox)
import tempfile, os, subprocess
out_fd, file = tempfile.mkstemp()
os.close(out_fd)
# Build ghostscript command
command = ["gs",
"-q", # quite mode
"-g%dx%d" % size, # set output geometry (pixels)
"-r%d" % (72*scale), # set input DPI (dots per inch)
"-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
"-sDEVICE=ppmraw", # ppm driver
"-sOutputFile=%s" % file,# output file
]
if gs_windows_binary is not None:
if gs_windows_binary is False:
raise WindowsError('Unable to locate Ghostscript on paths')
command[0] = gs_windows_binary
# push data through ghostscript
try:
gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# adjust for image origin
if bbox[0] != 0 or bbox[1] != 0:
gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii'))
fp.seek(offset)
while length > 0:
s = fp.read(8192)
if not s:
break
length = length - len(s)
gs.stdin.write(s)
gs.stdin.close()
status = gs.wait()
if status:
raise IOError("gs failed (status %d)" % status)
im = Image.core.open_ppm(file)
finally:
try: os.unlink(file)
except: pass
return im
class PSFile:
"""Wrapper that treats either CR or LF as end of line."""
def __init__(self, fp):
self.fp = fp
self.char = None
def __getattr__(self, id):
v = getattr(self.fp, id)
setattr(self, id, v)
return v
def seek(self, offset, whence=0):
self.char = None
self.fp.seek(offset, whence)
def read(self, count):
return self.fp.read(count).decode('latin-1')
def tell(self):
pos = self.fp.tell()
if self.char:
pos = pos - 1
return pos
def readline(self):
s = b""
if self.char:
c = self.char
self.char = None
else:
c = self.fp.read(1)
while c not in b"\r\n":
s = s + c
c = self.fp.read(1)
if c == b"\r":
self.char = self.fp.read(1)
if self.char == b"\n":
self.char = None
return s.decode('latin-1') + "\n"
def _accept(prefix):
return prefix[:4] == b"%!PS" or i32(prefix) == 0xC6D3D0C5
##
# Image plugin for Encapsulated Postscript. This plugin supports only
# a few variants of this format.
class EpsImageFile(ImageFile.ImageFile):
"""EPS File Parser for the Python Imaging Library"""
format = "EPS"
format_description = "Encapsulated Postscript"
def _open(self):
# FIXME: should check the first 512 bytes to see if this
# really is necessary (platform-dependent, though...)
fp = PSFile(self.fp)
# HEAD
s = fp.read(512)
if s[:4] == "%!PS":
offset = 0
fp.seek(0, 2)
length = fp.tell()
elif i32(s) == 0xC6D3D0C5:
offset = i32(s[4:])
length = i32(s[8:])
fp.seek(offset)
else:
raise SyntaxError("not an EPS file")
fp.seek(offset)
box = None
self.mode = "RGB"
self.size = 1, 1 # FIXME: huh?
#
# Load EPS header
s = fp.readline()
while s:
if len(s) > 255:
raise SyntaxError("not an EPS file")
if s[-2:] == '\r\n':
s = s[:-2]
elif s[-1:] == '\n':
s = s[:-1]
try:
m = split.match(s)
except re.error as v:
raise SyntaxError("not an EPS file")
if m:
k, v = m.group(1, 2)
self.info[k] = v
if k == "BoundingBox":
try:
# Note: The DSC spec says that BoundingBox
# fields should be integers, but some drivers
# put floating point values there anyway.
box = [int(float(s)) for s in v.split()]
self.size = box[2] - box[0], box[3] - box[1]
self.tile = [("eps", (0,0) + self.size, offset,
(length, box))]
except:
pass
else:
m = field.match(s)
if m:
k = m.group(1)
if k == "EndComments":
break
if k[:8] == "PS-Adobe":
self.info[k[:8]] = k[9:]
else:
self.info[k] = ""
elif s[0:1] == '%':
# handle non-DSC Postscript comments that some
# tools mistakenly put in the Comments section
pass
else:
raise IOError("bad EPS header")
s = fp.readline()
if s[:1] != "%":
break
#
# Scan for an "ImageData" descriptor
while s[0] == "%":
if len(s) > 255:
raise SyntaxError("not an EPS file")
if s[-2:] == '\r\n':
s = s[:-2]
elif s[-1:] == '\n':
s = s[:-1]
if s[:11] == "%ImageData:":
[x, y, bi, mo, z3, z4, en, id] =\
s[11:].split(None, 7)
x = int(x); y = int(y)
bi = int(bi)
mo = int(mo)
en = int(en)
if en == 1:
decoder = "eps_binary"
elif en == 2:
decoder = "eps_hex"
else:
break
if bi != 8:
break
if mo == 1:
self.mode = "L"
elif mo == 2:
self.mode = "LAB"
elif mo == 3:
self.mode = "RGB"
else:
break
if id[:1] == id[-1:] == '"':
id = id[1:-1]
# Scan forward to the actual image data
while True:
s = fp.readline()
if not s:
break
if s[:len(id)] == id:
self.size = x, y
self.tile2 = [(decoder,
(0, 0, x, y),
fp.tell(),
0)]
return
s = fp.readline()
if not s:
break
if not box:
raise IOError("cannot determine EPS bounding box")
def load(self, scale=1):
# Load EPS via Ghostscript
if not self.tile:
return
self.im = Ghostscript(self.tile, self.size, self.fp, scale)
self.mode = self.im.mode
self.size = self.im.size
self.tile = []
#
# --------------------------------------------------------------------
def _save(im, fp, filename, eps=1):
"""EPS Writer for the Python Imaging Library."""
#
# make sure image data is available
im.load()
#
# determine postscript image mode
if im.mode == "L":
operator = (8, 1, "image")
elif im.mode == "RGB":
operator = (8, 3, "false 3 colorimage")
elif im.mode == "CMYK":
operator = (8, 4, "false 4 colorimage")
else:
raise ValueError("image mode is not supported")
class NoCloseStream:
def __init__(self, fp):
self.fp = fp
def __getattr__(self, name):
return getattr(self.fp, name)
def close(self):
pass
base_fp = fp
fp = io.TextIOWrapper(NoCloseStream(fp), encoding='latin-1')
if eps:
#
# write EPS header
fp.write("%!PS-Adobe-3.0 EPSF-3.0\n")
fp.write("%%Creator: PIL 0.1 EpsEncode\n")
#fp.write("%%CreationDate: %s"...)
fp.write("%%%%BoundingBox: 0 0 %d %d\n" % im.size)
fp.write("%%Pages: 1\n")
fp.write("%%EndComments\n")
fp.write("%%Page: 1 1\n")
fp.write("%%ImageData: %d %d " % im.size)
fp.write("%d %d 0 1 1 \"%s\"\n" % operator)
#
# image header
fp.write("gsave\n")
fp.write("10 dict begin\n")
fp.write("/buf %d string def\n" % (im.size[0] * operator[1]))
fp.write("%d %d scale\n" % im.size)
fp.write("%d %d 8\n" % im.size) # <= bits
fp.write("[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
fp.write("{ currentfile buf readhexstring pop } bind\n")
fp.write(operator[2] + "\n")
fp.flush()
ImageFile._save(im, base_fp, [("eps", (0,0)+im.size, 0, None)])
fp.write("\n%%%%EndBinary\n")
fp.write("grestore end\n")
fp.flush()
#
# --------------------------------------------------------------------
Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
Image.register_save(EpsImageFile.format, _save)
Image.register_extension(EpsImageFile.format, ".ps")
Image.register_extension(EpsImageFile.format, ".eps")
Image.register_mime(EpsImageFile.format, "application/postscript")
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_2084_0 |
crossvul-python_data_bad_2836_0 | from __future__ import print_function
import argparse
import json
from oauthlib.oauth2 import LegacyApplicationClient
import logging
import logging.handlers
from requests_oauthlib import OAuth2Session
import os
import requests
import six
import sys
import traceback
from six.moves.urllib.parse import quote as urlquote
from six.moves.urllib.parse import urlparse
# ------------------------------------------------------------------------------
logger = None
prog_name = os.path.basename(sys.argv[0])
AUTH_ROLES = ['root-admin', 'realm-admin', 'anonymous']
LOG_FILE_ROTATION_COUNT = 3
TOKEN_URL_TEMPLATE = (
'{server}/auth/realms/{realm}/protocol/openid-connect/token')
GET_SERVER_INFO_TEMPLATE = (
'{server}/auth/admin/serverinfo/')
GET_REALMS_URL_TEMPLATE = (
'{server}/auth/admin/realms')
CREATE_REALM_URL_TEMPLATE = (
'{server}/auth/admin/realms')
DELETE_REALM_URL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}')
GET_REALM_METADATA_TEMPLATE = (
'{server}/auth/realms/{realm}/protocol/saml/descriptor')
CLIENT_REPRESENTATION_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients/{id}')
GET_CLIENTS_URL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients')
CLIENT_DESCRIPTOR_URL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/client-description-converter')
CREATE_CLIENT_URL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients')
GET_INITIAL_ACCESS_TOKEN_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients-initial-access')
SAML2_CLIENT_REGISTRATION_TEMPLATE = (
'{server}/auth/realms/{realm}/clients-registrations/saml2-entity-descriptor')
GET_CLIENT_PROTOCOL_MAPPERS_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients/{id}/protocol-mappers/models')
GET_CLIENT_PROTOCOL_MAPPERS_BY_PROTOCOL_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients/{id}/protocol-mappers/protocol/{protocol}')
POST_CLIENT_PROTOCOL_MAPPER_TEMPLATE = (
'{server}/auth/admin/realms/{realm}/clients/{id}/protocol-mappers/models')
ADMIN_CLIENT_ID = 'admin-cli'
# ------------------------------------------------------------------------------
class RESTError(Exception):
def __init__(self, status_code, status_reason,
response_json, response_text, cmd):
self.status_code = status_code
self.status_reason = status_reason
self.error_description = None
self.error = None
self.response_json = response_json
self.response_text = response_text
self.cmd = cmd
self.message = '{status_reason}({status_code}): '.format(
status_reason=self.status_reason,
status_code=self.status_code)
if response_json:
self.error_description = response_json.get('error_description')
if self.error_description is None:
self.error_description = response_json.get('errorMessage')
self.error = response_json.get('error')
self.message += '"{error_description}" [{error}]'.format(
error_description=self.error_description,
error=self.error)
else:
self.message += '"{response_text}"'.format(
response_text=self.response_text)
self.args = (self.message,)
def __str__(self):
return self.message
# ------------------------------------------------------------------------------
def configure_logging(options):
global logger # pylint: disable=W0603
log_dir = os.path.dirname(options.log_file)
if os.path.exists(log_dir):
if not os.path.isdir(log_dir):
raise ValueError('logging directory "{log_dir}" exists but is not '
'directory'.format(log_dir=log_dir))
else:
os.makedirs(log_dir)
log_level = logging.ERROR
if options.verbose:
log_level = logging.INFO
if options.debug:
log_level = logging.DEBUG
# These two lines enable debugging at httplib level
# (requests->urllib3->http.client) You will see the REQUEST,
# including HEADERS and DATA, and RESPONSE with HEADERS but
# without DATA. The only thing missing will be the
# response.body which is not logged.
try:
import http.client as http_client # Python 3
except ImportError:
import httplib as http_client # Python 2
http_client.HTTPConnection.debuglevel = 1
# Turn on cookielib debugging
if False:
try:
import http.cookiejar as cookiejar
except ImportError:
import cookielib as cookiejar # Python 2
cookiejar.debug = True
logger = logging.getLogger(prog_name)
try:
file_handler = logging.handlers.RotatingFileHandler(
options.log_file, backupCount=LOG_FILE_ROTATION_COUNT)
except IOError as e:
print('Unable to open log file %s (%s)' % (options.log_file, e),
file=sys.stderr)
else:
formatter = logging.Formatter(
'%(asctime)s %(name)s %(levelname)s: %(message)s')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
console_handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(message)s')
console_handler.setFormatter(formatter)
console_handler.setLevel(log_level)
logger.addHandler(console_handler)
# Set the log level on the logger to the lowest level
# possible. This allows the message to be emitted from the logger
# to it's handlers where the level will be filtered on a per
# handler basis.
logger.setLevel(1)
# ------------------------------------------------------------------------------
def json_pretty(text):
return json.dumps(json.loads(text),
indent=4, sort_keys=True)
def py_json_pretty(py_json):
return json_pretty(json.dumps(py_json))
def server_name_from_url(url):
return urlparse(url).netloc
def get_realm_names_from_realms(realms):
return [x['realm'] for x in realms]
def get_client_client_ids_from_clients(clients):
return [x['clientId'] for x in clients]
def find_client_by_name(clients, client_id):
for client in clients:
if client.get('clientId') == client_id:
return client
raise KeyError('{item} not found'.format(item=client_id))
# ------------------------------------------------------------------------------
class KeycloakREST(object):
def __init__(self, server, auth_role=None, session=None):
self.server = server
self.auth_role = auth_role
self.session = session
def get_initial_access_token(self, realm_name):
cmd_name = "get initial access token for realm '{realm}'".format(
realm=realm_name)
url = GET_INITIAL_ACCESS_TOKEN_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
params = {"expiration": 60, # seconds
"count": 1}
response = self.session.post(url, json=params)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json # ClientInitialAccessPresentation
def get_server_info(self):
cmd_name = "get server info"
url = GET_SERVER_INFO_TEMPLATE.format(server=self.server)
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def get_realms(self):
cmd_name = "get realms"
url = GET_REALMS_URL_TEMPLATE.format(server=self.server)
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def create_realm(self, realm_name):
cmd_name = "create realm '{realm}'".format(realm=realm_name)
url = CREATE_REALM_URL_TEMPLATE.format(server=self.server)
logger.debug("%s on server %s", cmd_name, self.server)
params = {"enabled": True,
"id": realm_name,
"realm": realm_name,
}
response = self.session.post(url, json=params)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.created:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def delete_realm(self, realm_name):
cmd_name = "delete realm '{realm}'".format(realm=realm_name)
url = DELETE_REALM_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.delete(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.no_content:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def get_realm_metadata(self, realm_name):
cmd_name = "get metadata for realm '{realm}'".format(realm=realm_name)
url = GET_REALM_METADATA_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.ok:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
return response.text
def get_clients(self, realm_name):
cmd_name = "get clients in realm '{realm}'".format(realm=realm_name)
url = GET_CLIENTS_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def get_client_by_id(self, realm_name, id):
cmd_name = "get client id {id} in realm '{realm}'".format(
id=id, realm=realm_name)
url = GET_CLIENTS_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
params = {'clientID': id}
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.get(url, params=params)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def get_client_by_name(self, realm_name, client_name):
clients = self.get_clients(realm_name)
client = find_client_by_name(clients, client_name)
id = client.get('id')
logger.debug("client name '%s' mapped to id '%s'",
client_name, id)
logger.debug("client %s\n%s", client_name, py_json_pretty(client))
return client
def get_client_id_by_name(self, realm_name, client_name):
client = self.get_client_by_name(realm_name, client_name)
id = client.get('id')
return id
def get_client_descriptor(self, realm_name, metadata):
cmd_name = "get client descriptor realm '{realm}'".format(
realm=realm_name)
url = CLIENT_DESCRIPTOR_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
headers = {'Content-Type': 'application/xml;charset=utf-8'}
response = self.session.post(url, headers=headers, data=metadata)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.ok):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json
def create_client_from_descriptor(self, realm_name, descriptor):
cmd_name = "create client from descriptor "
"'{client_id}'in realm '{realm}'".format(
client_id=descriptor['clientId'], realm=realm_name)
url = CREATE_CLIENT_URL_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.post(url, json=descriptor)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.created:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def create_client(self, realm_name, metadata):
logger.debug("create client in realm %s on server %s",
realm_name, self.server)
descriptor = self.get_client_descriptor(realm_name, metadata)
self.create_client_from_descriptor(realm_name, descriptor)
return descriptor
def register_client(self, initial_access_token, realm_name, metadata):
cmd_name = "register_client realm '{realm}'".format(
realm=realm_name)
url = SAML2_CLIENT_REGISTRATION_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name))
logger.debug("%s on server %s", cmd_name, self.server)
headers = {'Content-Type': 'application/xml;charset=utf-8'}
if initial_access_token:
headers['Authorization'] = 'Bearer {token}'.format(
token=initial_access_token)
response = self.session.post(url, headers=headers, data=metadata)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if (not response_json or
response.status_code != requests.codes.created):
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, json_pretty(response.text))
return response_json # ClientRepresentation
def delete_client_by_name(self, realm_name, client_name):
id = self.get_client_id_by_name(realm_name, client_name)
self.delete_client_by_id(realm_name, id)
def delete_client_by_id(self, realm_name, id):
cmd_name = "delete client id '{id}'in realm '{realm}'".format(
id=id, realm=realm_name)
url = CLIENT_REPRESENTATION_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name),
id=urlquote(id))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.delete(url)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.no_content:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def update_client(self, realm_name, client):
id = client['id']
cmd_name = "update client {id} in realm '{realm}'".format(
id=client['clientId'], realm=realm_name)
url = CLIENT_REPRESENTATION_TEMPLATE.format(
server=self.server, realm=urlquote(realm_name),
id=urlquote(id))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.put(url, json=client)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.no_content:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def update_client_attributes(self, realm_name, client, update_attrs):
client_id = client['clientId']
logger.debug("update client attrs: client_id=%s "
"current attrs=%s update=%s" % (client_id, client['attributes'],
update_attrs))
client['attributes'].update(update_attrs)
logger.debug("update client attrs: client_id=%s "
"new attrs=%s" % (client_id, client['attributes']))
self.update_client(realm_name, client);
def update_client_by_name_attributes(self, realm_name, client_name,
update_attrs):
client = self.get_client_by_name(realm_name, client_name)
self.update_client_attributes(realm_name, client, update_attrs)
def new_saml_group_protocol_mapper(self, mapper_name, attribute_name,
friendly_name=None,
single_attribute=True):
mapper = {
'protocol': 'saml',
'name': mapper_name,
'protocolMapper': 'saml-group-membership-mapper',
'config': {
'attribute.name': attribute_name,
'attribute.nameformat': 'Basic',
'single': single_attribute,
'full.path': False,
},
}
if friendly_name:
mapper['config']['friendly.name'] = friendly_name
return mapper
def create_client_protocol_mapper(self, realm_name, client, mapper):
id = client['id']
cmd_name = ("create protocol-mapper '{mapper_name}' for client {id} "
"in realm '{realm}'".format(
mapper_name=mapper['name'],id=client['clientId'], realm=realm_name))
url = POST_CLIENT_PROTOCOL_MAPPER_TEMPLATE.format(
server=self.server,
realm=urlquote(realm_name),
id=urlquote(id))
logger.debug("%s on server %s", cmd_name, self.server)
response = self.session.post(url, json=mapper)
logger.debug("%s response code: %s %s",
cmd_name, response.status_code, response.reason)
try:
response_json = response.json()
except ValueError as e:
response_json = None
if response.status_code != requests.codes.created:
logger.error("%s error: status=%s (%s) text=%s",
cmd_name, response.status_code, response.reason,
response.text)
raise RESTError(response.status_code, response.reason,
response_json, response.text, cmd_name)
logger.debug("%s response = %s", cmd_name, response.text)
def create_client_by_name_protocol_mapper(self, realm_name, client_name,
mapper):
client = self.get_client_by_name(realm_name, client_name)
self.create_client_protocol_mapper(realm_name, client, mapper)
def add_client_by_name_redirect_uris(self, realm_name, client_name, uris):
client = self.get_client_by_name(realm_name, client_name)
uris = set(uris)
redirect_uris = set(client['redirectUris'])
redirect_uris |= uris
client['redirectUris'] = list(redirect_uris)
self.update_client(realm_name, client);
def remove_client_by_name_redirect_uris(self, realm_name, client_name, uris):
client = self.get_client_by_name(realm_name, client_name)
uris = set(uris)
redirect_uris = set(client['redirectUris'])
redirect_uris -= uris
client['redirectUris'] = list(redirect_uris)
self.update_client(realm_name, client);
# ------------------------------------------------------------------------------
class KeycloakAdminConnection(KeycloakREST):
def __init__(self, server, auth_role, realm, client_id,
username, password, tls_verify):
super(KeycloakAdminConnection, self).__init__(server, auth_role)
self.realm = realm
self.client_id = client_id
self.username = username
self.password = password
self.session = self._create_session(tls_verify)
def _create_session(self, tls_verify):
token_url = TOKEN_URL_TEMPLATE.format(
server=self.server, realm=urlquote(self.realm))
refresh_url = token_url
client = LegacyApplicationClient(client_id=self.client_id)
session = OAuth2Session(client=client,
auto_refresh_url=refresh_url,
auto_refresh_kwargs={
'client_id': self.client_id})
session.verify = tls_verify
token = session.fetch_token(token_url=token_url,
username=self.username,
password=self.password,
client_id=self.client_id,
verify=session.verify)
return session
class KeycloakAnonymousConnection(KeycloakREST):
def __init__(self, server, tls_verify):
super(KeycloakAnonymousConnection, self).__init__(server, 'anonymous')
self.session = self._create_session(tls_verify)
def _create_session(self, tls_verify):
session = requests.Session()
session.verify = tls_verify
return session
# ------------------------------------------------------------------------------
def do_server_info(options, conn):
server_info = conn.get_server_info()
print(json_pretty(server_info))
def do_list_realms(options, conn):
realms = conn.get_realms()
realm_names = get_realm_names_from_realms(realms)
print('\n'.join(sorted(realm_names)))
def do_create_realm(options, conn):
conn.create_realm(options.realm_name)
def do_delete_realm(options, conn):
conn.delete_realm(options.realm_name)
def do_get_realm_metadata(options, conn):
metadata = conn.get_realm_metadata(options.realm_name)
print(metadata)
def do_list_clients(options, conn):
clients = conn.get_clients(options.realm_name)
client_ids = get_client_client_ids_from_clients(clients)
print('\n'.join(sorted(client_ids)))
def do_create_client(options, conn):
metadata = options.metadata.read()
descriptor = conn.create_client(options.realm_name, metadata)
def do_register_client(options, conn):
metadata = options.metadata.read()
client_representation = conn.register_client(
options.initial_access_token,
options.realm_name, metadata)
def do_delete_client(options, conn):
conn.delete_client_by_name(options.realm_name, options.client_name)
def do_client_test(options, conn):
'experimental test code used during development'
uri = 'https://openstack.jdennis.oslab.test:5000/v3/mellon/fooResponse'
conn.remove_client_by_name_redirect_uri(options.realm_name,
options.client_name,
uri)
# ------------------------------------------------------------------------------
verbose_help = '''
The structure of the command line arguments is "noun verb" where noun
is one of Keycloak's data items (e.g. realm, client, etc.) and the
verb is an action to perform on the item. Each of the nouns and verbs
may have their own set of arguments which must follow the noun or
verb.
For example to delete the client XYZ in the realm ABC:
echo password | {prog_name} -s http://example.com:8080 -P - client delete -r ABC -c XYZ
where 'client' is the noun, 'delete' is the verb and -r ABC -c XYZ are
arguments to the delete action.
If the command completes successfully the exit status is 0. The exit
status is 1 if an authenticated connection with the server cannont be
successfully established. The exit status is 2 if the REST operation
fails.
The server should be a scheme://hostname:port URL.
'''
class TlsVerifyAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
if nargs is not None:
raise ValueError("nargs not allowed")
super(TlsVerifyAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
if values.lower() in ['true', 'yes', 'on']:
verify = True
elif values.lower() in ['false', 'no', 'off']:
verify = False
else:
verify = values
setattr(namespace, self.dest, verify)
def main():
global logger
result = 0
parser = argparse.ArgumentParser(description='Keycloak REST client',
prog=prog_name,
epilog=verbose_help.format(prog_name=prog_name),
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--verbose', action='store_true',
help='be chatty')
parser.add_argument('-d', '--debug', action='store_true',
help='turn on debug info')
parser.add_argument('--show-traceback', action='store_true',
help='exceptions print traceback in addition to '
'error message')
parser.add_argument('--log-file',
default='/tmp/{prog_name}.log'.format(
prog_name=prog_name),
help='log file pathname')
parser.add_argument('--permit-insecure-transport', action='store_true',
help='Normally secure transport such as TLS '
'is required, defeat this check')
parser.add_argument('--tls-verify', action=TlsVerifyAction,
default=True,
help='TLS certificate verification for requests to'
' the server. May be one of case insenstive '
'[true, yes, on] to enable,'
'[false, no, off] to disable.'
'Or the pathname to a OpenSSL CA bundle to use.'
' Default is True.')
group = parser.add_argument_group('Server')
group.add_argument('-s', '--server',
required=True,
help='DNS name or IP address of Keycloak server')
group.add_argument('-a', '--auth-role',
choices=AUTH_ROLES,
default='root-admin',
help='authenticating as what type of user (default: root-admin)')
group.add_argument('-u', '--admin-username',
default='admin',
help='admin user name (default: admin)')
group.add_argument('-P', '--admin-password-file',
type=argparse.FileType('rb'),
help=('file containing admin password '
'(or use a hyphen "-" to read the password '
'from stdin)'))
group.add_argument('--admin-realm',
default='master',
help='realm admin belongs to')
cmd_parsers = parser.add_subparsers(help='available commands')
# --- realm commands ---
realm_parser = cmd_parsers.add_parser('realm',
help='realm operations')
sub_parser = realm_parser.add_subparsers(help='realm commands')
cmd_parser = sub_parser.add_parser('server_info',
help='dump server info')
cmd_parser.set_defaults(func=do_server_info)
cmd_parser = sub_parser.add_parser('list',
help='list realm names')
cmd_parser.set_defaults(func=do_list_realms)
cmd_parser = sub_parser.add_parser('create',
help='create new realm')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.set_defaults(func=do_create_realm)
cmd_parser = sub_parser.add_parser('delete',
help='delete existing realm')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.set_defaults(func=do_delete_realm)
cmd_parser = sub_parser.add_parser('metadata',
help='retrieve realm metadata')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.set_defaults(func=do_get_realm_metadata)
# --- client commands ---
client_parser = cmd_parsers.add_parser('client',
help='client operations')
sub_parser = client_parser.add_subparsers(help='client commands')
cmd_parser = sub_parser.add_parser('list',
help='list client names')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.set_defaults(func=do_list_clients)
cmd_parser = sub_parser.add_parser('create',
help='create new client')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.add_argument('-m', '--metadata', type=argparse.FileType('rb'),
required=True,
help='SP metadata file or stdin')
cmd_parser.set_defaults(func=do_create_client)
cmd_parser = sub_parser.add_parser('register',
help='register new client')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.add_argument('-m', '--metadata', type=argparse.FileType('rb'),
required=True,
help='SP metadata file or stdin')
cmd_parser.add_argument('--initial-access-token', required=True,
help='realm initial access token for '
'client registeration')
cmd_parser.set_defaults(func=do_register_client)
cmd_parser = sub_parser.add_parser('delete',
help='delete existing client')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.add_argument('-c', '--client-name', required=True,
help='client name')
cmd_parser.set_defaults(func=do_delete_client)
cmd_parser = sub_parser.add_parser('test',
help='experimental test used during '
'development')
cmd_parser.add_argument('-r', '--realm-name', required=True,
help='realm name')
cmd_parser.add_argument('-c', '--client-name', required=True,
help='client name')
cmd_parser.set_defaults(func=do_client_test)
# Process command line arguments
options = parser.parse_args()
configure_logging(options)
if options.permit_insecure_transport:
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'
# Get admin password
options.admin_password = None
# 1. Try password file
if options.admin_password_file is not None:
options.admin_password = options.keycloak_admin_password_file.readline().strip()
options.keycloak_admin_password_file.close()
# 2. Try KEYCLOAK_ADMIN_PASSWORD environment variable
if options.admin_password is None:
if (('KEYCLOAK_ADMIN_PASSWORD' in os.environ) and
(os.environ['KEYCLOAK_ADMIN_PASSWORD'])):
options.admin_password = os.environ['KEYCLOAK_ADMIN_PASSWORD']
try:
anonymous_conn = KeycloakAnonymousConnection(options.server,
options.tls_verify)
admin_conn = KeycloakAdminConnection(options.server,
options.auth_role,
options.admin_realm,
ADMIN_CLIENT_ID,
options.admin_username,
options.admin_password,
options.tls_verify)
except Exception as e:
if options.show_traceback:
traceback.print_exc()
print(six.text_type(e), file=sys.stderr)
result = 1
return result
try:
if options.func == do_register_client:
conn = admin_conn
else:
conn = admin_conn
result = options.func(options, conn)
except Exception as e:
if options.show_traceback:
traceback.print_exc()
print(six.text_type(e), file=sys.stderr)
result = 2
return result
return result
# ------------------------------------------------------------------------------
if __name__ == '__main__':
sys.exit(main())
else:
logger = logging.getLogger('keycloak-cli')
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_2836_0 |
crossvul-python_data_bad_1711_0 | # Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# and chroot.py (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# (c) 2013, Michael Scherer <misc@zarb.org>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import traceback
import os
import shutil
import subprocess
from ansible import errors
from ansible.callbacks import vvv
import ansible.constants as C
class Connection(object):
''' Local chroot based connections '''
def _search_executable(self, executable):
cmd = distutils.spawn.find_executable(executable)
if not cmd:
raise errors.AnsibleError("%s command not found in PATH") % executable
return cmd
def list_jails(self):
p = subprocess.Popen([self.jls_cmd, '-q', 'name'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.split()
def get_jail_path(self):
p = subprocess.Popen([self.jls_cmd, '-j', self.jail, '-q', 'path'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
# remove \n
return stdout[:-1]
def __init__(self, runner, host, port, *args, **kwargs):
self.jail = host
self.runner = runner
self.host = host
self.has_pipelining = False
self.become_methods_supported=C.BECOME_METHODS
if os.geteuid() != 0:
raise errors.AnsibleError("jail connection requires running as root")
self.jls_cmd = self._search_executable('jls')
self.jexec_cmd = self._search_executable('jexec')
if not self.jail in self.list_jails():
raise errors.AnsibleError("incorrect jail name %s" % self.jail)
self.host = host
# port is unused, since this is local
self.port = port
def connect(self, port=None):
''' connect to the chroot; nothing to do here '''
vvv("THIS IS A LOCAL CHROOT DIR", host=self.jail)
return self
# a modifier
def _generate_cmd(self, executable, cmd):
if executable:
local_cmd = [self.jexec_cmd, self.jail, executable, '-c', cmd]
else:
local_cmd = '%s "%s" %s' % (self.jexec_cmd, self.jail, cmd)
return local_cmd
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the chroot '''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
# Ignores privilege escalation
local_cmd = self._generate_cmd(executable, cmd)
vvv("EXEC %s" % (local_cmd), host=self.jail)
p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
return (p.returncode, '', stdout, stderr)
def _normalize_path(self, path, prefix):
if not path.startswith(os.path.sep):
path = os.path.join(os.path.sep, path)
normpath = os.path.normpath(path)
return os.path.join(prefix, normpath[1:])
def _copy_file(self, in_path, out_path):
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
shutil.copyfile(in_path, out_path)
except shutil.Error:
traceback.print_exc()
raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
except IOError:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path)
def put_file(self, in_path, out_path):
''' transfer a file from local to chroot '''
out_path = self._normalize_path(out_path, self.get_jail_path())
vvv("PUT %s TO %s" % (in_path, out_path), host=self.jail)
self._copy_file(in_path, out_path)
def fetch_file(self, in_path, out_path):
''' fetch a file from chroot to local '''
in_path = self._normalize_path(in_path, self.get_jail_path())
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.jail)
self._copy_file(in_path, out_path)
def close(self):
''' terminate the connection; nothing to do here '''
pass
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_1711_0 |
crossvul-python_data_bad_4994_0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Kevin Carter <kevin.carter@rackspace.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = """
---
module: lxc_container
short_description: Manage LXC Containers
version_added: 1.8.0
description:
- Management of LXC containers
author: "Kevin Carter (@cloudnull)"
options:
name:
description:
- Name of a container.
required: true
backing_store:
choices:
- dir
- lvm
- loop
- btrfs
- overlayfs
- zfs
description:
- Backend storage type for the container.
required: false
default: dir
template:
description:
- Name of the template to use within an LXC create.
required: false
default: ubuntu
template_options:
description:
- Template options when building the container.
required: false
config:
description:
- Path to the LXC configuration file.
required: false
default: null
lv_name:
description:
- Name of the logical volume, defaults to the container name.
default: $CONTAINER_NAME
required: false
vg_name:
description:
- If Backend store is lvm, specify the name of the volume group.
default: lxc
required: false
thinpool:
description:
- Use LVM thin pool called TP.
required: false
fs_type:
description:
- Create fstype TYPE.
default: ext4
required: false
fs_size:
description:
- File system Size.
default: 5G
required: false
directory:
description:
- Place rootfs directory under DIR.
required: false
zfs_root:
description:
- Create zfs under given zfsroot.
required: false
container_command:
description:
- Run a command within a container.
required: false
lxc_path:
description:
- Place container under PATH
required: false
container_log:
choices:
- true
- false
description:
- Enable a container log for host actions to the container.
default: false
container_log_level:
choices:
- INFO
- ERROR
- DEBUG
description:
- Set the log level for a container where *container_log* was set.
required: false
default: INFO
clone_name:
version_added: "2.0"
description:
- Name of the new cloned server. This is only used when state is
clone.
required: false
default: false
clone_snapshot:
version_added: "2.0"
required: false
choices:
- true
- false
description:
- Create a snapshot a container when cloning. This is not supported
by all container storage backends. Enabling this may fail if the
backing store does not support snapshots.
default: false
archive:
choices:
- true
- false
description:
- Create an archive of a container. This will create a tarball of the
running container.
default: false
archive_path:
description:
- Path the save the archived container. If the path does not exist
the archive method will attempt to create it.
default: /tmp
archive_compression:
choices:
- gzip
- bzip2
- none
description:
- Type of compression to use when creating an archive of a running
container.
default: gzip
state:
choices:
- started
- stopped
- restarted
- absent
- frozen
description:
- Define the state of a container. If you clone a container using
`clone_name` the newly cloned container created in a stopped state.
The running container will be stopped while the clone operation is
happening and upon completion of the clone the original container
state will be restored.
required: false
default: started
container_config:
description:
- list of 'key=value' options to use when configuring a container.
required: false
requirements:
- 'lxc >= 1.0 # OS package'
- 'python >= 2.6 # OS Package'
- 'lxc-python2 >= 0.1 # PIP Package from https://github.com/lxc/python2-lxc'
notes:
- Containers must have a unique name. If you attempt to create a container
with a name that already exists in the users namespace the module will
simply return as "unchanged".
- The "container_command" can be used with any state except "absent". If
used with state "stopped" the container will be "started", the command
executed, and then the container "stopped" again. Likewise if the state
is "stopped" and the container does not exist it will be first created,
"started", the command executed, and then "stopped". If you use a "|"
in the variable you can use common script formatting within the variable
iteself The "container_command" option will always execute as BASH.
When using "container_command" a log file is created in the /tmp/ directory
which contains both stdout and stderr of any command executed.
- If "archive" is **true** the system will attempt to create a compressed
tarball of the running container. The "archive" option supports LVM backed
containers and will create a snapshot of the running container when
creating the archive.
- If your distro does not have a package for "python2-lxc", which is a
requirement for this module, it can be installed from source at
"https://github.com/lxc/python2-lxc" or installed via pip using the package
name lxc-python2.
"""
EXAMPLES = """
- name: Create a started container
lxc_container:
name: test-container-started
container_log: true
template: ubuntu
state: started
template_options: --release trusty
- name: Create a stopped container
lxc_container:
name: test-container-stopped
container_log: true
template: ubuntu
state: stopped
template_options: --release trusty
- name: Create a frozen container
lxc_container:
name: test-container-frozen
container_log: true
template: ubuntu
state: frozen
template_options: --release trusty
container_command: |
echo 'hello world.' | tee /opt/started-frozen
# Create filesystem container, configure it, and archive it, and start it.
- name: Create filesystem container
lxc_container:
name: test-container-config
backing_store: dir
container_log: true
template: ubuntu
state: started
archive: true
archive_compression: none
container_config:
- "lxc.aa_profile=unconfined"
- "lxc.cgroup.devices.allow=a *:* rmw"
template_options: --release trusty
# Create an lvm container, run a complex command in it, add additional
# configuration to it, create an archive of it, and finally leave the container
# in a frozen state. The container archive will be compressed using bzip2
- name: Create a frozen lvm container
lxc_container:
name: test-container-lvm
container_log: true
template: ubuntu
state: frozen
backing_store: lvm
template_options: --release trusty
container_command: |
apt-get update
apt-get install -y vim lxc-dev
echo 'hello world.' | tee /opt/started
if [[ -f "/opt/started" ]]; then
echo 'hello world.' | tee /opt/found-started
fi
container_config:
- "lxc.aa_profile=unconfined"
- "lxc.cgroup.devices.allow=a *:* rmw"
archive: true
archive_compression: bzip2
register: lvm_container_info
- name: Debug info on container "test-container-lvm"
debug: var=lvm_container_info
- name: Run a command in a container and ensure its in a "stopped" state.
lxc_container:
name: test-container-started
state: stopped
container_command: |
echo 'hello world.' | tee /opt/stopped
- name: Run a command in a container and ensure its it in a "frozen" state.
lxc_container:
name: test-container-stopped
state: frozen
container_command: |
echo 'hello world.' | tee /opt/frozen
- name: Start a container
lxc_container:
name: test-container-stopped
state: started
- name: Run a command in a container and then restart it
lxc_container:
name: test-container-started
state: restarted
container_command: |
echo 'hello world.' | tee /opt/restarted
- name: Run a complex command within a "running" container
lxc_container:
name: test-container-started
container_command: |
apt-get update
apt-get install -y curl wget vim apache2
echo 'hello world.' | tee /opt/started
if [[ -f "/opt/started" ]]; then
echo 'hello world.' | tee /opt/found-started
fi
# Create an archive of an existing container, save the archive to a defined
# path and then destroy it.
- name: Archive container
lxc_container:
name: test-container-started
state: absent
archive: true
archive_path: /opt/archives
# Create a container using overlayfs, create an archive of it, create a
# snapshot clone of the container and and finally leave the container
# in a frozen state. The container archive will be compressed using gzip.
- name: Create an overlayfs container archive and clone it
lxc_container:
name: test-container-overlayfs
container_log: true
template: ubuntu
state: started
backing_store: overlayfs
template_options: --release trusty
clone_snapshot: true
clone_name: test-container-overlayfs-clone-snapshot
archive: true
archive_compression: gzip
register: clone_container_info
- name: debug info on container "test-container"
debug: var=clone_container_info
- name: Clone a container using snapshot
lxc_container:
name: test-container-overlayfs-clone-snapshot
backing_store: overlayfs
clone_name: test-container-overlayfs-clone-snapshot2
clone_snapshot: true
- name: Create a new container and clone it
lxc_container:
name: test-container-new-archive
backing_store: dir
clone_name: test-container-new-archive-clone
- name: Archive and clone a container then destroy it
lxc_container:
name: test-container-new-archive
state: absent
clone_name: test-container-new-archive-destroyed-clone
archive: true
archive_compression: gzip
- name: Start a cloned container.
lxc_container:
name: test-container-new-archive-destroyed-clone
state: started
- name: Destroy a container
lxc_container:
name: "{{ item }}"
state: absent
with_items:
- test-container-stopped
- test-container-started
- test-container-frozen
- test-container-lvm
- test-container-config
- test-container-overlayfs
- test-container-overlayfs-clone
- test-container-overlayfs-clone-snapshot
- test-container-overlayfs-clone-snapshot2
- test-container-new-archive
- test-container-new-archive-clone
- test-container-new-archive-destroyed-clone
"""
RETURN="""
lxc_container:
description: container information
returned: success
type: list
contains:
name:
description: name of the lxc container
returned: success
type: string
sample: test_host
init_pid:
description: pid of the lxc init process
returned: success
type: int
sample: 19786
interfaces:
description: list of the container's network interfaces
returned: success
type: list
sample: [ "eth0", "lo" ]
ips:
description: list of ips
returned: success
type: list
sample: [ "10.0.3.3" ]
state:
description: resulting state of the container
returned: success
type: string
sample: "running"
archive:
description: resulting state of the container
returned: success, when archive is true
type: string
sample: "/tmp/test-container-config.tar"
clone:
description: if the container was cloned
returned: success, when clone_name is specified
type: boolean
sample: True
"""
try:
import lxc
except ImportError:
HAS_LXC = False
else:
HAS_LXC = True
# LXC_COMPRESSION_MAP is a map of available compression types when creating
# an archive of a container.
LXC_COMPRESSION_MAP = {
'gzip': {
'extension': 'tar.tgz',
'argument': '-czf'
},
'bzip2': {
'extension': 'tar.bz2',
'argument': '-cjf'
},
'none': {
'extension': 'tar',
'argument': '-cf'
}
}
# LXC_COMMAND_MAP is a map of variables that are available to a method based
# on the state the container is in.
LXC_COMMAND_MAP = {
'create': {
'variables': {
'config': '--config',
'template': '--template',
'backing_store': '--bdev',
'lxc_path': '--lxcpath',
'lv_name': '--lvname',
'vg_name': '--vgname',
'thinpool': '--thinpool',
'fs_type': '--fstype',
'fs_size': '--fssize',
'directory': '--dir',
'zfs_root': '--zfsroot'
}
},
'clone': {
'variables': {
'backing_store': '--backingstore',
'lxc_path': '--lxcpath',
'fs_size': '--fssize',
'name': '--orig',
'clone_name': '--new'
}
}
}
# LXC_BACKING_STORE is a map of available storage backends and options that
# are incompatible with the given storage backend.
LXC_BACKING_STORE = {
'dir': [
'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool'
],
'lvm': [
'zfs_root'
],
'btrfs': [
'lv_name', 'vg_name', 'thinpool', 'zfs_root', 'fs_type', 'fs_size'
],
'loop': [
'lv_name', 'vg_name', 'thinpool', 'zfs_root'
],
'overlayfs': [
'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool', 'zfs_root'
],
'zfs': [
'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool'
]
}
# LXC_LOGGING_LEVELS is a map of available log levels
LXC_LOGGING_LEVELS = {
'INFO': ['info', 'INFO', 'Info'],
'ERROR': ['error', 'ERROR', 'Error'],
'DEBUG': ['debug', 'DEBUG', 'Debug']
}
# LXC_ANSIBLE_STATES is a map of states that contain values of methods used
# when a particular state is evoked.
LXC_ANSIBLE_STATES = {
'started': '_started',
'stopped': '_stopped',
'restarted': '_restarted',
'absent': '_destroyed',
'frozen': '_frozen',
'clone': '_clone'
}
# This is used to attach to a running container and execute commands from
# within the container on the host. This will provide local access to a
# container without using SSH. The template will attempt to work within the
# home directory of the user that was attached to the container and source
# that users environment variables by default.
ATTACH_TEMPLATE = """#!/usr/bin/env bash
pushd "$(getent passwd $(whoami)|cut -f6 -d':')"
if [[ -f ".bashrc" ]];then
source .bashrc
fi
popd
# User defined command
%(container_command)s
"""
def create_script(command):
"""Write out a script onto a target.
This method should be backward compatible with Python 2.4+ when executing
from within the container.
:param command: command to run, this can be a script and can use spacing
with newlines as separation.
:type command: ``str``
"""
import os
import os.path as path
import subprocess
import tempfile
# Ensure that the directory /opt exists.
if not path.isdir('/opt'):
os.mkdir('/opt')
# Create the script.
script_file = path.join('/opt', '.lxc-attach-script')
f = open(script_file, 'wb')
try:
f.write(ATTACH_TEMPLATE % {'container_command': command})
f.flush()
finally:
f.close()
# Ensure the script is executable.
os.chmod(script_file, 0700)
# Get temporary directory.
tempdir = tempfile.gettempdir()
# Output log file.
stdout_file = open(path.join(tempdir, 'lxc-attach-script.log'), 'ab')
# Error log file.
stderr_file = open(path.join(tempdir, 'lxc-attach-script.err'), 'ab')
# Execute the script command.
try:
subprocess.Popen(
[script_file],
stdout=stdout_file,
stderr=stderr_file
).communicate()
finally:
# Close the log files.
stderr_file.close()
stdout_file.close()
# Remove the script file upon completion of execution.
os.remove(script_file)
class LxcContainerManagement(object):
def __init__(self, module):
"""Management of LXC containers via Ansible.
:param module: Processed Ansible Module.
:type module: ``object``
"""
self.module = module
self.state = self.module.params.get('state', None)
self.state_change = False
self.lxc_vg = None
self.container_name = self.module.params['name']
self.container = self.get_container_bind()
self.archive_info = None
self.clone_info = None
def get_container_bind(self):
return lxc.Container(name=self.container_name)
@staticmethod
def _roundup(num):
"""Return a rounded floating point number.
:param num: Number to round up.
:type: ``float``
:returns: Rounded up number.
:rtype: ``int``
"""
num, part = str(num).split('.')
num = int(num)
if int(part) != 0:
num += 1
return num
@staticmethod
def _container_exists(container_name):
"""Check if a container exists.
:param container_name: Name of the container.
:type: ``str``
:returns: True or False if the container is found.
:rtype: ``bol``
"""
if [i for i in lxc.list_containers() if i == container_name]:
return True
else:
return False
@staticmethod
def _add_variables(variables_dict, build_command):
"""Return a command list with all found options.
:param variables_dict: Pre-parsed optional variables used from a
seed command.
:type variables_dict: ``dict``
:param build_command: Command to run.
:type build_command: ``list``
:returns: list of command options.
:rtype: ``list``
"""
for key, value in variables_dict.items():
build_command.append(
'%s %s' % (key, value)
)
else:
return build_command
def _get_vars(self, variables):
"""Return a dict of all variables as found within the module.
:param variables: Hash of all variables to find.
:type variables: ``dict``
"""
# Remove incompatible storage backend options.
variables = variables.copy()
for v in LXC_BACKING_STORE[self.module.params['backing_store']]:
variables.pop(v, None)
return_dict = dict()
false_values = [None, ''] + BOOLEANS_FALSE
for k, v in variables.items():
_var = self.module.params.get(k)
if _var not in false_values:
return_dict[v] = _var
else:
return return_dict
def _run_command(self, build_command, unsafe_shell=False, timeout=600):
"""Return information from running an Ansible Command.
This will squash the build command list into a string and then
execute the command via Ansible. The output is returned to the method.
This output is returned as `return_code`, `stdout`, `stderr`.
Prior to running the command the method will look to see if the LXC
lockfile is present. If the lockfile "/var/lock/subsys/lxc" the method
will wait upto 10 minutes for it to be gone; polling every 5 seconds.
:param build_command: Used for the command and all options.
:type build_command: ``list``
:param unsafe_shell: Enable or Disable unsafe sell commands.
:type unsafe_shell: ``bol``
:param timeout: Time before the container create process quites.
:type timeout: ``int``
"""
lockfile = '/var/lock/subsys/lxc'
for _ in xrange(timeout):
if os.path.exists(lockfile):
time.sleep(1)
else:
return self.module.run_command(
' '.join(build_command),
use_unsafe_shell=unsafe_shell
)
else:
message = (
'The LXC subsystem is locked and after 5 minutes it never'
' became unlocked. Lockfile [ %s ]' % lockfile
)
self.failure(
error='LXC subsystem locked',
rc=0,
msg=message
)
def _config(self):
"""Configure an LXC container.
Write new configuration values to the lxc config file. This will
stop the container if it's running write the new options and then
restart the container upon completion.
"""
_container_config = self.module.params.get('container_config')
if not _container_config:
return False
container_config_file = self.container.config_file_name
with open(container_config_file, 'rb') as f:
container_config = f.readlines()
# Note used ast literal_eval because AnsibleModule does not provide for
# adequate dictionary parsing.
# Issue: https://github.com/ansible/ansible/issues/7679
# TODO(cloudnull) adjust import when issue has been resolved.
import ast
options_dict = ast.literal_eval(_container_config)
parsed_options = [i.split('=', 1) for i in options_dict]
config_change = False
for key, value in parsed_options:
new_entry = '%s = %s\n' % (key, value)
for option_line in container_config:
# Look for key in config
if option_line.startswith(key):
_, _value = option_line.split('=', 1)
config_value = ' '.join(_value.split())
line_index = container_config.index(option_line)
# If the sanitized values don't match replace them
if value != config_value:
line_index += 1
if new_entry not in container_config:
config_change = True
container_config.insert(line_index, new_entry)
# Break the flow as values are written or not at this point
break
else:
config_change = True
container_config.append(new_entry)
# If the config changed restart the container.
if config_change:
container_state = self._get_state()
if container_state != 'stopped':
self.container.stop()
with open(container_config_file, 'wb') as f:
f.writelines(container_config)
self.state_change = True
if container_state == 'running':
self._container_startup()
elif container_state == 'frozen':
self._container_startup()
self.container.freeze()
def _container_create_clone(self):
"""Clone a new LXC container from an existing container.
This method will clone an existing container to a new container using
the `clone_name` variable as the new container name. The method will
create a container if the container `name` does not exist.
Note that cloning a container will ensure that the original container
is "stopped" before the clone can be done. Because this operation can
require a state change the method will return the original container
to its prior state upon completion of the clone.
Once the clone is complete the new container will be left in a stopped
state.
"""
# Ensure that the state of the original container is stopped
container_state = self._get_state()
if container_state != 'stopped':
self.state_change = True
self.container.stop()
build_command = [
self.module.get_bin_path('lxc-clone', True),
]
build_command = self._add_variables(
variables_dict=self._get_vars(
variables=LXC_COMMAND_MAP['clone']['variables']
),
build_command=build_command
)
# Load logging for the instance when creating it.
if self.module.params.get('clone_snapshot') in BOOLEANS_TRUE:
build_command.append('--snapshot')
# Check for backing_store == overlayfs if so force the use of snapshot
# If overlay fs is used and snapshot is unset the clone command will
# fail with an unsupported type.
elif self.module.params.get('backing_store') == 'overlayfs':
build_command.append('--snapshot')
rc, return_data, err = self._run_command(build_command)
if rc != 0:
message = "Failed executing lxc-clone."
self.failure(
err=err, rc=rc, msg=message, command=' '.join(
build_command
)
)
else:
self.state_change = True
# Restore the original state of the origin container if it was
# not in a stopped state.
if container_state == 'running':
self.container.start()
elif container_state == 'frozen':
self.container.start()
self.container.freeze()
return True
def _create(self):
"""Create a new LXC container.
This method will build and execute a shell command to build the
container. It would have been nice to simply use the lxc python library
however at the time this was written the python library, in both py2
and py3 didn't support some of the more advanced container create
processes. These missing processes mainly revolve around backing
LXC containers with block devices.
"""
build_command = [
self.module.get_bin_path('lxc-create', True),
'--name %s' % self.container_name,
'--quiet'
]
build_command = self._add_variables(
variables_dict=self._get_vars(
variables=LXC_COMMAND_MAP['create']['variables']
),
build_command=build_command
)
# Load logging for the instance when creating it.
if self.module.params.get('container_log') in BOOLEANS_TRUE:
# Set the logging path to the /var/log/lxc if uid is root. else
# set it to the home folder of the user executing.
try:
if os.getuid() != 0:
log_path = os.getenv('HOME')
else:
if not os.path.isdir('/var/log/lxc/'):
os.makedirs('/var/log/lxc/')
log_path = '/var/log/lxc/'
except OSError:
log_path = os.getenv('HOME')
build_command.extend([
'--logfile %s' % os.path.join(
log_path, 'lxc-%s.log' % self.container_name
),
'--logpriority %s' % self.module.params.get(
'container_log_level'
).upper()
])
# Add the template commands to the end of the command if there are any
template_options = self.module.params.get('template_options', None)
if template_options:
build_command.append('-- %s' % template_options)
rc, return_data, err = self._run_command(build_command)
if rc != 0:
message = "Failed executing lxc-create."
self.failure(
err=err, rc=rc, msg=message, command=' '.join(build_command)
)
else:
self.state_change = True
def _container_data(self):
"""Returns a dict of container information.
:returns: container data
:rtype: ``dict``
"""
return {
'interfaces': self.container.get_interfaces(),
'ips': self.container.get_ips(),
'state': self._get_state(),
'init_pid': int(self.container.init_pid),
'name' : self.container_name,
}
def _unfreeze(self):
"""Unfreeze a container.
:returns: True or False based on if the container was unfrozen.
:rtype: ``bol``
"""
unfreeze = self.container.unfreeze()
if unfreeze:
self.state_change = True
return unfreeze
def _get_state(self):
"""Return the state of a container.
If the container is not found the state returned is "absent"
:returns: state of a container as a lower case string.
:rtype: ``str``
"""
if self._container_exists(container_name=self.container_name):
return str(self.container.state).lower()
else:
return str('absent')
def _execute_command(self):
"""Execute a shell command."""
container_command = self.module.params.get('container_command')
if container_command:
container_state = self._get_state()
if container_state == 'frozen':
self._unfreeze()
elif container_state == 'stopped':
self._container_startup()
self.container.attach_wait(create_script, container_command)
self.state_change = True
def _container_startup(self, timeout=60):
"""Ensure a container is started.
:param timeout: Time before the destroy operation is abandoned.
:type timeout: ``int``
"""
self.container = self.get_container_bind()
for _ in xrange(timeout):
if self._get_state() != 'running':
self.container.start()
self.state_change = True
# post startup sleep for 1 second.
time.sleep(1)
else:
return True
else:
self.failure(
lxc_container=self._container_data(),
error='Failed to start container'
' [ %s ]' % self.container_name,
rc=1,
msg='The container [ %s ] failed to start. Check to lxc is'
' available and that the container is in a functional'
' state.' % self.container_name
)
def _check_archive(self):
"""Create a compressed archive of a container.
This will store archive_info in as self.archive_info
"""
if self.module.params.get('archive') in BOOLEANS_TRUE:
self.archive_info = {
'archive': self._container_create_tar()
}
def _check_clone(self):
"""Create a compressed archive of a container.
This will store archive_info in as self.archive_info
"""
clone_name = self.module.params.get('clone_name')
if clone_name:
if not self._container_exists(container_name=clone_name):
self.clone_info = {
'cloned': self._container_create_clone()
}
else:
self.clone_info = {
'cloned': False
}
def _destroyed(self, timeout=60):
"""Ensure a container is destroyed.
:param timeout: Time before the destroy operation is abandoned.
:type timeout: ``int``
"""
for _ in xrange(timeout):
if not self._container_exists(container_name=self.container_name):
break
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
if self._get_state() != 'stopped':
self.state_change = True
self.container.stop()
if self.container.destroy():
self.state_change = True
# post destroy attempt sleep for 1 second.
time.sleep(1)
else:
self.failure(
lxc_container=self._container_data(),
error='Failed to destroy container'
' [ %s ]' % self.container_name,
rc=1,
msg='The container [ %s ] failed to be destroyed. Check'
' that lxc is available and that the container is in a'
' functional state.' % self.container_name
)
def _frozen(self, count=0):
"""Ensure a container is frozen.
If the container does not exist the container will be created.
:param count: number of times this command has been called by itself.
:type count: ``int``
"""
self.check_count(count=count, method='frozen')
if self._container_exists(container_name=self.container_name):
self._execute_command()
# Perform any configuration updates
self._config()
container_state = self._get_state()
if container_state == 'frozen':
pass
elif container_state == 'running':
self.container.freeze()
self.state_change = True
else:
self._container_startup()
self.container.freeze()
self.state_change = True
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
else:
self._create()
count += 1
self._frozen(count)
def _restarted(self, count=0):
"""Ensure a container is restarted.
If the container does not exist the container will be created.
:param count: number of times this command has been called by itself.
:type count: ``int``
"""
self.check_count(count=count, method='restart')
if self._container_exists(container_name=self.container_name):
self._execute_command()
# Perform any configuration updates
self._config()
if self._get_state() != 'stopped':
self.container.stop()
self.state_change = True
# Run container startup
self._container_startup()
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
else:
self._create()
count += 1
self._restarted(count)
def _stopped(self, count=0):
"""Ensure a container is stopped.
If the container does not exist the container will be created.
:param count: number of times this command has been called by itself.
:type count: ``int``
"""
self.check_count(count=count, method='stop')
if self._container_exists(container_name=self.container_name):
self._execute_command()
# Perform any configuration updates
self._config()
if self._get_state() != 'stopped':
self.container.stop()
self.state_change = True
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
else:
self._create()
count += 1
self._stopped(count)
def _started(self, count=0):
"""Ensure a container is started.
If the container does not exist the container will be created.
:param count: number of times this command has been called by itself.
:type count: ``int``
"""
self.check_count(count=count, method='start')
if self._container_exists(container_name=self.container_name):
container_state = self._get_state()
if container_state == 'running':
pass
elif container_state == 'frozen':
self._unfreeze()
elif not self._container_startup():
self.failure(
lxc_container=self._container_data(),
error='Failed to start container'
' [ %s ]' % self.container_name,
rc=1,
msg='The container [ %s ] failed to start. Check to lxc is'
' available and that the container is in a functional'
' state.' % self.container_name
)
# Return data
self._execute_command()
# Perform any configuration updates
self._config()
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
else:
self._create()
count += 1
self._started(count)
def _get_lxc_vg(self):
"""Return the name of the Volume Group used in LXC."""
build_command = [
self.module.get_bin_path('lxc-config', True),
"lxc.bdev.lvm.vg"
]
rc, vg, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='Failed to read LVM VG from LXC config',
command=' '.join(build_command)
)
else:
return str(vg.strip())
def _lvm_lv_list(self):
"""Return a list of all lv in a current vg."""
vg = self._get_lxc_vg()
build_command = [
self.module.get_bin_path('lvs', True)
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='Failed to get list of LVs',
command=' '.join(build_command)
)
all_lvms = [i.split() for i in stdout.splitlines()][1:]
return [lv_entry[0] for lv_entry in all_lvms if lv_entry[1] == vg]
def _get_vg_free_pe(self, vg_name):
"""Return the available size of a given VG.
:param vg_name: Name of volume.
:type vg_name: ``str``
:returns: size and measurement of an LV
:type: ``tuple``
"""
build_command = [
'vgdisplay',
vg_name,
'--units',
'g'
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to read vg %s' % vg_name,
command=' '.join(build_command)
)
vg_info = [i.strip() for i in stdout.splitlines()][1:]
free_pe = [i for i in vg_info if i.startswith('Free')]
_free_pe = free_pe[0].split()
return float(_free_pe[-2]), _free_pe[-1]
def _get_lv_size(self, lv_name):
"""Return the available size of a given LV.
:param lv_name: Name of volume.
:type lv_name: ``str``
:returns: size and measurement of an LV
:type: ``tuple``
"""
vg = self._get_lxc_vg()
lv = os.path.join(vg, lv_name)
build_command = [
'lvdisplay',
lv,
'--units',
'g'
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to read lv %s' % lv,
command=' '.join(build_command)
)
lv_info = [i.strip() for i in stdout.splitlines()][1:]
_free_pe = [i for i in lv_info if i.startswith('LV Size')]
free_pe = _free_pe[0].split()
return self._roundup(float(free_pe[-2])), free_pe[-1]
def _lvm_snapshot_create(self, source_lv, snapshot_name,
snapshot_size_gb=5):
"""Create an LVM snapshot.
:param source_lv: Name of lv to snapshot
:type source_lv: ``str``
:param snapshot_name: Name of lv snapshot
:type snapshot_name: ``str``
:param snapshot_size_gb: Size of snapshot to create
:type snapshot_size_gb: ``int``
"""
vg = self._get_lxc_vg()
free_space, messurement = self._get_vg_free_pe(vg_name=vg)
if free_space < float(snapshot_size_gb):
message = (
'Snapshot size [ %s ] is > greater than [ %s ] on volume group'
' [ %s ]' % (snapshot_size_gb, free_space, vg)
)
self.failure(
error='Not enough space to create snapshot',
rc=2,
msg=message
)
# Create LVM Snapshot
build_command = [
self.module.get_bin_path('lvcreate', True),
"-n",
snapshot_name,
"-s",
os.path.join(vg, source_lv),
"-L%sg" % snapshot_size_gb
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='Failed to Create LVM snapshot %s/%s --> %s'
% (vg, source_lv, snapshot_name)
)
def _lvm_lv_mount(self, lv_name, mount_point):
"""mount an lv.
:param lv_name: name of the logical volume to mount
:type lv_name: ``str``
:param mount_point: path on the file system that is mounted.
:type mount_point: ``str``
"""
vg = self._get_lxc_vg()
build_command = [
self.module.get_bin_path('mount', True),
"/dev/%s/%s" % (vg, lv_name),
mount_point,
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to mountlvm lv %s/%s to %s'
% (vg, lv_name, mount_point)
)
def _create_tar(self, source_dir):
"""Create an archive of a given ``source_dir`` to ``output_path``.
:param source_dir: Path to the directory to be archived.
:type source_dir: ``str``
"""
archive_path = self.module.params.get('archive_path')
if not os.path.isdir(archive_path):
os.makedirs(archive_path)
archive_compression = self.module.params.get('archive_compression')
compression_type = LXC_COMPRESSION_MAP[archive_compression]
# remove trailing / if present.
archive_name = '%s.%s' % (
os.path.join(
archive_path,
self.container_name
),
compression_type['extension']
)
build_command = [
self.module.get_bin_path('tar', True),
'--directory=%s' % os.path.realpath(
os.path.expanduser(source_dir)
),
compression_type['argument'],
archive_name,
'.'
]
rc, stdout, err = self._run_command(
build_command=build_command,
unsafe_shell=True
)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to create tar archive',
command=' '.join(build_command)
)
return archive_name
def _lvm_lv_remove(self, lv_name):
"""Remove an LV.
:param lv_name: The name of the logical volume
:type lv_name: ``str``
"""
vg = self._get_lxc_vg()
build_command = [
self.module.get_bin_path('lvremove', True),
"-f",
"%s/%s" % (vg, lv_name),
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='Failed to remove LVM LV %s/%s' % (vg, lv_name),
command=' '.join(build_command)
)
def _rsync_data(self, container_path, temp_dir):
"""Sync the container directory to the temp directory.
:param container_path: path to the container container
:type container_path: ``str``
:param temp_dir: path to the temporary local working directory
:type temp_dir: ``str``
"""
# This loop is created to support overlayfs archives. This should
# squash all of the layers into a single archive.
fs_paths = container_path.split(':')
if 'overlayfs' in fs_paths:
fs_paths.pop(fs_paths.index('overlayfs'))
for fs_path in fs_paths:
# Set the path to the container data
fs_path = os.path.dirname(fs_path)
# Run the sync command
build_command = [
self.module.get_bin_path('rsync', True),
'-aHAX',
fs_path,
temp_dir
]
rc, stdout, err = self._run_command(
build_command,
unsafe_shell=True
)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to perform archive',
command=' '.join(build_command)
)
def _unmount(self, mount_point):
"""Unmount a file system.
:param mount_point: path on the file system that is mounted.
:type mount_point: ``str``
"""
build_command = [
self.module.get_bin_path('umount', True),
mount_point,
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to unmount [ %s ]' % mount_point,
command=' '.join(build_command)
)
def _overlayfs_mount(self, lowerdir, upperdir, mount_point):
"""mount an lv.
:param lowerdir: name/path of the lower directory
:type lowerdir: ``str``
:param upperdir: name/path of the upper directory
:type upperdir: ``str``
:param mount_point: path on the file system that is mounted.
:type mount_point: ``str``
"""
build_command = [
self.module.get_bin_path('mount', True),
'-t overlayfs',
'-o lowerdir=%s,upperdir=%s' % (lowerdir, upperdir),
'overlayfs',
mount_point,
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to mount overlayfs:%s:%s to %s -- Command: %s'
% (lowerdir, upperdir, mount_point, build_command)
)
def _container_create_tar(self):
"""Create a tar archive from an LXC container.
The process is as follows:
* Stop or Freeze the container
* Create temporary dir
* Copy container and config to temporary directory
* If LVM backed:
* Create LVM snapshot of LV backing the container
* Mount the snapshot to tmpdir/rootfs
* Restore the state of the container
* Create tar of tmpdir
* Clean up
"""
# Create a temp dir
temp_dir = tempfile.mkdtemp()
# Set the name of the working dir, temp + container_name
work_dir = os.path.join(temp_dir, self.container_name)
# LXC container rootfs
lxc_rootfs = self.container.get_config_item('lxc.rootfs')
# Test if the containers rootfs is a block device
block_backed = lxc_rootfs.startswith(os.path.join(os.sep, 'dev'))
# Test if the container is using overlayfs
overlayfs_backed = lxc_rootfs.startswith('overlayfs')
mount_point = os.path.join(work_dir, 'rootfs')
# Set the snapshot name if needed
snapshot_name = '%s_lxc_snapshot' % self.container_name
container_state = self._get_state()
try:
# Ensure the original container is stopped or frozen
if container_state not in ['stopped', 'frozen']:
if container_state == 'running':
self.container.freeze()
else:
self.container.stop()
# Sync the container data from the container_path to work_dir
self._rsync_data(lxc_rootfs, temp_dir)
if block_backed:
if snapshot_name not in self._lvm_lv_list():
if not os.path.exists(mount_point):
os.makedirs(mount_point)
# Take snapshot
size, measurement = self._get_lv_size(
lv_name=self.container_name
)
self._lvm_snapshot_create(
source_lv=self.container_name,
snapshot_name=snapshot_name,
snapshot_size_gb=size
)
# Mount snapshot
self._lvm_lv_mount(
lv_name=snapshot_name,
mount_point=mount_point
)
else:
self.failure(
err='snapshot [ %s ] already exists' % snapshot_name,
rc=1,
msg='The snapshot [ %s ] already exists. Please clean'
' up old snapshot of containers before continuing.'
% snapshot_name
)
elif overlayfs_backed:
lowerdir, upperdir = lxc_rootfs.split(':')[1:]
self._overlayfs_mount(
lowerdir=lowerdir,
upperdir=upperdir,
mount_point=mount_point
)
# Set the state as changed and set a new fact
self.state_change = True
return self._create_tar(source_dir=work_dir)
finally:
if block_backed or overlayfs_backed:
# unmount snapshot
self._unmount(mount_point)
if block_backed:
# Remove snapshot
self._lvm_lv_remove(snapshot_name)
# Restore original state of container
if container_state == 'running':
if self._get_state() == 'frozen':
self.container.unfreeze()
else:
self.container.start()
# Remove tmpdir
shutil.rmtree(temp_dir)
def check_count(self, count, method):
if count > 1:
self.failure(
error='Failed to %s container' % method,
rc=1,
msg='The container [ %s ] failed to %s. Check to lxc is'
' available and that the container is in a functional'
' state.' % (self.container_name, method)
)
def failure(self, **kwargs):
"""Return a Failure when running an Ansible command.
:param error: ``str`` Error that occurred.
:param rc: ``int`` Return code while executing an Ansible command.
:param msg: ``str`` Message to report.
"""
self.module.fail_json(**kwargs)
def run(self):
"""Run the main method."""
action = getattr(self, LXC_ANSIBLE_STATES[self.state])
action()
outcome = self._container_data()
if self.archive_info:
outcome.update(self.archive_info)
if self.clone_info:
outcome.update(self.clone_info)
self.module.exit_json(
changed=self.state_change,
lxc_container=outcome
)
def main():
"""Ansible Main module."""
module = AnsibleModule(
argument_spec=dict(
name=dict(
type='str',
required=True
),
template=dict(
type='str',
default='ubuntu'
),
backing_store=dict(
type='str',
choices=LXC_BACKING_STORE.keys(),
default='dir'
),
template_options=dict(
type='str'
),
config=dict(
type='str',
),
vg_name=dict(
type='str',
default='lxc'
),
thinpool=dict(
type='str'
),
fs_type=dict(
type='str',
default='ext4'
),
fs_size=dict(
type='str',
default='5G'
),
directory=dict(
type='str'
),
zfs_root=dict(
type='str'
),
lv_name=dict(
type='str'
),
lxc_path=dict(
type='str'
),
state=dict(
choices=LXC_ANSIBLE_STATES.keys(),
default='started'
),
container_command=dict(
type='str'
),
container_config=dict(
type='str'
),
container_log=dict(
type='bool',
default='false'
),
container_log_level=dict(
choices=[n for i in LXC_LOGGING_LEVELS.values() for n in i],
default='INFO'
),
clone_name=dict(
type='str',
required=False
),
clone_snapshot=dict(
type='bool',
default='false'
),
archive=dict(
type='bool',
default='false'
),
archive_path=dict(
type='str',
default='/tmp'
),
archive_compression=dict(
choices=LXC_COMPRESSION_MAP.keys(),
default='gzip'
)
),
supports_check_mode=False,
)
if not HAS_LXC:
module.fail_json(
msg='The `lxc` module is not importable. Check the requirements.'
)
lv_name = module.params.get('lv_name')
if not lv_name:
module.params['lv_name'] = module.params.get('name')
lxc_manage = LxcContainerManagement(module=module)
lxc_manage.run()
# import module bits
from ansible.module_utils.basic import *
main()
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_4994_0 |
crossvul-python_data_good_4994_0 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Kevin Carter <kevin.carter@rackspace.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = """
---
module: lxc_container
short_description: Manage LXC Containers
version_added: 1.8.0
description:
- Management of LXC containers
author: "Kevin Carter (@cloudnull)"
options:
name:
description:
- Name of a container.
required: true
backing_store:
choices:
- dir
- lvm
- loop
- btrfs
- overlayfs
- zfs
description:
- Backend storage type for the container.
required: false
default: dir
template:
description:
- Name of the template to use within an LXC create.
required: false
default: ubuntu
template_options:
description:
- Template options when building the container.
required: false
config:
description:
- Path to the LXC configuration file.
required: false
default: null
lv_name:
description:
- Name of the logical volume, defaults to the container name.
default: $CONTAINER_NAME
required: false
vg_name:
description:
- If Backend store is lvm, specify the name of the volume group.
default: lxc
required: false
thinpool:
description:
- Use LVM thin pool called TP.
required: false
fs_type:
description:
- Create fstype TYPE.
default: ext4
required: false
fs_size:
description:
- File system Size.
default: 5G
required: false
directory:
description:
- Place rootfs directory under DIR.
required: false
zfs_root:
description:
- Create zfs under given zfsroot.
required: false
container_command:
description:
- Run a command within a container.
required: false
lxc_path:
description:
- Place container under PATH
required: false
container_log:
choices:
- true
- false
description:
- Enable a container log for host actions to the container.
default: false
container_log_level:
choices:
- INFO
- ERROR
- DEBUG
description:
- Set the log level for a container where *container_log* was set.
required: false
default: INFO
clone_name:
version_added: "2.0"
description:
- Name of the new cloned server. This is only used when state is
clone.
required: false
default: false
clone_snapshot:
version_added: "2.0"
required: false
choices:
- true
- false
description:
- Create a snapshot a container when cloning. This is not supported
by all container storage backends. Enabling this may fail if the
backing store does not support snapshots.
default: false
archive:
choices:
- true
- false
description:
- Create an archive of a container. This will create a tarball of the
running container.
default: false
archive_path:
description:
- Path the save the archived container. If the path does not exist
the archive method will attempt to create it.
default: null
archive_compression:
choices:
- gzip
- bzip2
- none
description:
- Type of compression to use when creating an archive of a running
container.
default: gzip
state:
choices:
- started
- stopped
- restarted
- absent
- frozen
description:
- Define the state of a container. If you clone a container using
`clone_name` the newly cloned container created in a stopped state.
The running container will be stopped while the clone operation is
happening and upon completion of the clone the original container
state will be restored.
required: false
default: started
container_config:
description:
- list of 'key=value' options to use when configuring a container.
required: false
requirements:
- 'lxc >= 1.0 # OS package'
- 'python >= 2.6 # OS Package'
- 'lxc-python2 >= 0.1 # PIP Package from https://github.com/lxc/python2-lxc'
notes:
- Containers must have a unique name. If you attempt to create a container
with a name that already exists in the users namespace the module will
simply return as "unchanged".
- The "container_command" can be used with any state except "absent". If
used with state "stopped" the container will be "started", the command
executed, and then the container "stopped" again. Likewise if the state
is "stopped" and the container does not exist it will be first created,
"started", the command executed, and then "stopped". If you use a "|"
in the variable you can use common script formatting within the variable
iteself The "container_command" option will always execute as BASH.
When using "container_command" a log file is created in the /tmp/ directory
which contains both stdout and stderr of any command executed.
- If "archive" is **true** the system will attempt to create a compressed
tarball of the running container. The "archive" option supports LVM backed
containers and will create a snapshot of the running container when
creating the archive.
- If your distro does not have a package for "python2-lxc", which is a
requirement for this module, it can be installed from source at
"https://github.com/lxc/python2-lxc" or installed via pip using the package
name lxc-python2.
"""
EXAMPLES = """
- name: Create a started container
lxc_container:
name: test-container-started
container_log: true
template: ubuntu
state: started
template_options: --release trusty
- name: Create a stopped container
lxc_container:
name: test-container-stopped
container_log: true
template: ubuntu
state: stopped
template_options: --release trusty
- name: Create a frozen container
lxc_container:
name: test-container-frozen
container_log: true
template: ubuntu
state: frozen
template_options: --release trusty
container_command: |
echo 'hello world.' | tee /opt/started-frozen
# Create filesystem container, configure it, and archive it, and start it.
- name: Create filesystem container
lxc_container:
name: test-container-config
backing_store: dir
container_log: true
template: ubuntu
state: started
archive: true
archive_compression: none
container_config:
- "lxc.aa_profile=unconfined"
- "lxc.cgroup.devices.allow=a *:* rmw"
template_options: --release trusty
# Create an lvm container, run a complex command in it, add additional
# configuration to it, create an archive of it, and finally leave the container
# in a frozen state. The container archive will be compressed using bzip2
- name: Create a frozen lvm container
lxc_container:
name: test-container-lvm
container_log: true
template: ubuntu
state: frozen
backing_store: lvm
template_options: --release trusty
container_command: |
apt-get update
apt-get install -y vim lxc-dev
echo 'hello world.' | tee /opt/started
if [[ -f "/opt/started" ]]; then
echo 'hello world.' | tee /opt/found-started
fi
container_config:
- "lxc.aa_profile=unconfined"
- "lxc.cgroup.devices.allow=a *:* rmw"
archive: true
archive_compression: bzip2
register: lvm_container_info
- name: Debug info on container "test-container-lvm"
debug: var=lvm_container_info
- name: Run a command in a container and ensure its in a "stopped" state.
lxc_container:
name: test-container-started
state: stopped
container_command: |
echo 'hello world.' | tee /opt/stopped
- name: Run a command in a container and ensure its it in a "frozen" state.
lxc_container:
name: test-container-stopped
state: frozen
container_command: |
echo 'hello world.' | tee /opt/frozen
- name: Start a container
lxc_container:
name: test-container-stopped
state: started
- name: Run a command in a container and then restart it
lxc_container:
name: test-container-started
state: restarted
container_command: |
echo 'hello world.' | tee /opt/restarted
- name: Run a complex command within a "running" container
lxc_container:
name: test-container-started
container_command: |
apt-get update
apt-get install -y curl wget vim apache2
echo 'hello world.' | tee /opt/started
if [[ -f "/opt/started" ]]; then
echo 'hello world.' | tee /opt/found-started
fi
# Create an archive of an existing container, save the archive to a defined
# path and then destroy it.
- name: Archive container
lxc_container:
name: test-container-started
state: absent
archive: true
archive_path: /opt/archives
# Create a container using overlayfs, create an archive of it, create a
# snapshot clone of the container and and finally leave the container
# in a frozen state. The container archive will be compressed using gzip.
- name: Create an overlayfs container archive and clone it
lxc_container:
name: test-container-overlayfs
container_log: true
template: ubuntu
state: started
backing_store: overlayfs
template_options: --release trusty
clone_snapshot: true
clone_name: test-container-overlayfs-clone-snapshot
archive: true
archive_compression: gzip
register: clone_container_info
- name: debug info on container "test-container"
debug: var=clone_container_info
- name: Clone a container using snapshot
lxc_container:
name: test-container-overlayfs-clone-snapshot
backing_store: overlayfs
clone_name: test-container-overlayfs-clone-snapshot2
clone_snapshot: true
- name: Create a new container and clone it
lxc_container:
name: test-container-new-archive
backing_store: dir
clone_name: test-container-new-archive-clone
- name: Archive and clone a container then destroy it
lxc_container:
name: test-container-new-archive
state: absent
clone_name: test-container-new-archive-destroyed-clone
archive: true
archive_compression: gzip
- name: Start a cloned container.
lxc_container:
name: test-container-new-archive-destroyed-clone
state: started
- name: Destroy a container
lxc_container:
name: "{{ item }}"
state: absent
with_items:
- test-container-stopped
- test-container-started
- test-container-frozen
- test-container-lvm
- test-container-config
- test-container-overlayfs
- test-container-overlayfs-clone
- test-container-overlayfs-clone-snapshot
- test-container-overlayfs-clone-snapshot2
- test-container-new-archive
- test-container-new-archive-clone
- test-container-new-archive-destroyed-clone
"""
RETURN="""
lxc_container:
description: container information
returned: success
type: list
contains:
name:
description: name of the lxc container
returned: success
type: string
sample: test_host
init_pid:
description: pid of the lxc init process
returned: success
type: int
sample: 19786
interfaces:
description: list of the container's network interfaces
returned: success
type: list
sample: [ "eth0", "lo" ]
ips:
description: list of ips
returned: success
type: list
sample: [ "10.0.3.3" ]
state:
description: resulting state of the container
returned: success
type: string
sample: "running"
archive:
description: resulting state of the container
returned: success, when archive is true
type: string
sample: "/tmp/test-container-config.tar"
clone:
description: if the container was cloned
returned: success, when clone_name is specified
type: boolean
sample: True
"""
try:
import lxc
except ImportError:
HAS_LXC = False
else:
HAS_LXC = True
# LXC_COMPRESSION_MAP is a map of available compression types when creating
# an archive of a container.
LXC_COMPRESSION_MAP = {
'gzip': {
'extension': 'tar.tgz',
'argument': '-czf'
},
'bzip2': {
'extension': 'tar.bz2',
'argument': '-cjf'
},
'none': {
'extension': 'tar',
'argument': '-cf'
}
}
# LXC_COMMAND_MAP is a map of variables that are available to a method based
# on the state the container is in.
LXC_COMMAND_MAP = {
'create': {
'variables': {
'config': '--config',
'template': '--template',
'backing_store': '--bdev',
'lxc_path': '--lxcpath',
'lv_name': '--lvname',
'vg_name': '--vgname',
'thinpool': '--thinpool',
'fs_type': '--fstype',
'fs_size': '--fssize',
'directory': '--dir',
'zfs_root': '--zfsroot'
}
},
'clone': {
'variables': {
'backing_store': '--backingstore',
'lxc_path': '--lxcpath',
'fs_size': '--fssize',
'name': '--orig',
'clone_name': '--new'
}
}
}
# LXC_BACKING_STORE is a map of available storage backends and options that
# are incompatible with the given storage backend.
LXC_BACKING_STORE = {
'dir': [
'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool'
],
'lvm': [
'zfs_root'
],
'btrfs': [
'lv_name', 'vg_name', 'thinpool', 'zfs_root', 'fs_type', 'fs_size'
],
'loop': [
'lv_name', 'vg_name', 'thinpool', 'zfs_root'
],
'overlayfs': [
'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool', 'zfs_root'
],
'zfs': [
'lv_name', 'vg_name', 'fs_type', 'fs_size', 'thinpool'
]
}
# LXC_LOGGING_LEVELS is a map of available log levels
LXC_LOGGING_LEVELS = {
'INFO': ['info', 'INFO', 'Info'],
'ERROR': ['error', 'ERROR', 'Error'],
'DEBUG': ['debug', 'DEBUG', 'Debug']
}
# LXC_ANSIBLE_STATES is a map of states that contain values of methods used
# when a particular state is evoked.
LXC_ANSIBLE_STATES = {
'started': '_started',
'stopped': '_stopped',
'restarted': '_restarted',
'absent': '_destroyed',
'frozen': '_frozen',
'clone': '_clone'
}
# This is used to attach to a running container and execute commands from
# within the container on the host. This will provide local access to a
# container without using SSH. The template will attempt to work within the
# home directory of the user that was attached to the container and source
# that users environment variables by default.
ATTACH_TEMPLATE = """#!/usr/bin/env bash
pushd "$(getent passwd $(whoami)|cut -f6 -d':')"
if [[ -f ".bashrc" ]];then
source .bashrc
fi
popd
# User defined command
%(container_command)s
"""
def create_script(command):
"""Write out a script onto a target.
This method should be backward compatible with Python 2.4+ when executing
from within the container.
:param command: command to run, this can be a script and can use spacing
with newlines as separation.
:type command: ``str``
"""
import os
import os.path as path
import subprocess
import tempfile
(fd, script_file) = tempfile.mkstemp(prefix='lxc-attach-script')
f = os.fdopen(fd, 'wb')
try:
f.write(ATTACH_TEMPLATE % {'container_command': command})
f.flush()
finally:
f.close()
# Ensure the script is executable.
os.chmod(script_file, 0700)
# Output log file.
stdout_file = os.fdopen(tempfile.mkstemp(prefix='lxc-attach-script-log')[0], 'ab')
# Error log file.
stderr_file = os.fdopen(tempfile.mkstemp(prefix='lxc-attach-script-err')[0], 'ab')
# Execute the script command.
try:
subprocess.Popen(
[script_file],
stdout=stdout_file,
stderr=stderr_file
).communicate()
finally:
# Close the log files.
stderr_file.close()
stdout_file.close()
# Remove the script file upon completion of execution.
os.remove(script_file)
class LxcContainerManagement(object):
def __init__(self, module):
"""Management of LXC containers via Ansible.
:param module: Processed Ansible Module.
:type module: ``object``
"""
self.module = module
self.state = self.module.params.get('state', None)
self.state_change = False
self.lxc_vg = None
self.container_name = self.module.params['name']
self.container = self.get_container_bind()
self.archive_info = None
self.clone_info = None
def get_container_bind(self):
return lxc.Container(name=self.container_name)
@staticmethod
def _roundup(num):
"""Return a rounded floating point number.
:param num: Number to round up.
:type: ``float``
:returns: Rounded up number.
:rtype: ``int``
"""
num, part = str(num).split('.')
num = int(num)
if int(part) != 0:
num += 1
return num
@staticmethod
def _container_exists(container_name):
"""Check if a container exists.
:param container_name: Name of the container.
:type: ``str``
:returns: True or False if the container is found.
:rtype: ``bol``
"""
if [i for i in lxc.list_containers() if i == container_name]:
return True
else:
return False
@staticmethod
def _add_variables(variables_dict, build_command):
"""Return a command list with all found options.
:param variables_dict: Pre-parsed optional variables used from a
seed command.
:type variables_dict: ``dict``
:param build_command: Command to run.
:type build_command: ``list``
:returns: list of command options.
:rtype: ``list``
"""
for key, value in variables_dict.items():
build_command.append(
'%s %s' % (key, value)
)
else:
return build_command
def _get_vars(self, variables):
"""Return a dict of all variables as found within the module.
:param variables: Hash of all variables to find.
:type variables: ``dict``
"""
# Remove incompatible storage backend options.
variables = variables.copy()
for v in LXC_BACKING_STORE[self.module.params['backing_store']]:
variables.pop(v, None)
return_dict = dict()
false_values = [None, ''] + BOOLEANS_FALSE
for k, v in variables.items():
_var = self.module.params.get(k)
if _var not in false_values:
return_dict[v] = _var
else:
return return_dict
def _run_command(self, build_command, unsafe_shell=False, timeout=600):
"""Return information from running an Ansible Command.
This will squash the build command list into a string and then
execute the command via Ansible. The output is returned to the method.
This output is returned as `return_code`, `stdout`, `stderr`.
Prior to running the command the method will look to see if the LXC
lockfile is present. If the lockfile "/var/lock/subsys/lxc" the method
will wait upto 10 minutes for it to be gone; polling every 5 seconds.
:param build_command: Used for the command and all options.
:type build_command: ``list``
:param unsafe_shell: Enable or Disable unsafe sell commands.
:type unsafe_shell: ``bol``
:param timeout: Time before the container create process quites.
:type timeout: ``int``
"""
lockfile = '/var/lock/subsys/lxc'
for _ in xrange(timeout):
if os.path.exists(lockfile):
time.sleep(1)
else:
return self.module.run_command(
' '.join(build_command),
use_unsafe_shell=unsafe_shell
)
else:
message = (
'The LXC subsystem is locked and after 5 minutes it never'
' became unlocked. Lockfile [ %s ]' % lockfile
)
self.failure(
error='LXC subsystem locked',
rc=0,
msg=message
)
def _config(self):
"""Configure an LXC container.
Write new configuration values to the lxc config file. This will
stop the container if it's running write the new options and then
restart the container upon completion.
"""
_container_config = self.module.params.get('container_config')
if not _container_config:
return False
container_config_file = self.container.config_file_name
with open(container_config_file, 'rb') as f:
container_config = f.readlines()
# Note used ast literal_eval because AnsibleModule does not provide for
# adequate dictionary parsing.
# Issue: https://github.com/ansible/ansible/issues/7679
# TODO(cloudnull) adjust import when issue has been resolved.
import ast
options_dict = ast.literal_eval(_container_config)
parsed_options = [i.split('=', 1) for i in options_dict]
config_change = False
for key, value in parsed_options:
new_entry = '%s = %s\n' % (key, value)
for option_line in container_config:
# Look for key in config
if option_line.startswith(key):
_, _value = option_line.split('=', 1)
config_value = ' '.join(_value.split())
line_index = container_config.index(option_line)
# If the sanitized values don't match replace them
if value != config_value:
line_index += 1
if new_entry not in container_config:
config_change = True
container_config.insert(line_index, new_entry)
# Break the flow as values are written or not at this point
break
else:
config_change = True
container_config.append(new_entry)
# If the config changed restart the container.
if config_change:
container_state = self._get_state()
if container_state != 'stopped':
self.container.stop()
with open(container_config_file, 'wb') as f:
f.writelines(container_config)
self.state_change = True
if container_state == 'running':
self._container_startup()
elif container_state == 'frozen':
self._container_startup()
self.container.freeze()
def _container_create_clone(self):
"""Clone a new LXC container from an existing container.
This method will clone an existing container to a new container using
the `clone_name` variable as the new container name. The method will
create a container if the container `name` does not exist.
Note that cloning a container will ensure that the original container
is "stopped" before the clone can be done. Because this operation can
require a state change the method will return the original container
to its prior state upon completion of the clone.
Once the clone is complete the new container will be left in a stopped
state.
"""
# Ensure that the state of the original container is stopped
container_state = self._get_state()
if container_state != 'stopped':
self.state_change = True
self.container.stop()
build_command = [
self.module.get_bin_path('lxc-clone', True),
]
build_command = self._add_variables(
variables_dict=self._get_vars(
variables=LXC_COMMAND_MAP['clone']['variables']
),
build_command=build_command
)
# Load logging for the instance when creating it.
if self.module.params.get('clone_snapshot') in BOOLEANS_TRUE:
build_command.append('--snapshot')
# Check for backing_store == overlayfs if so force the use of snapshot
# If overlay fs is used and snapshot is unset the clone command will
# fail with an unsupported type.
elif self.module.params.get('backing_store') == 'overlayfs':
build_command.append('--snapshot')
rc, return_data, err = self._run_command(build_command)
if rc != 0:
message = "Failed executing lxc-clone."
self.failure(
err=err, rc=rc, msg=message, command=' '.join(
build_command
)
)
else:
self.state_change = True
# Restore the original state of the origin container if it was
# not in a stopped state.
if container_state == 'running':
self.container.start()
elif container_state == 'frozen':
self.container.start()
self.container.freeze()
return True
def _create(self):
"""Create a new LXC container.
This method will build and execute a shell command to build the
container. It would have been nice to simply use the lxc python library
however at the time this was written the python library, in both py2
and py3 didn't support some of the more advanced container create
processes. These missing processes mainly revolve around backing
LXC containers with block devices.
"""
build_command = [
self.module.get_bin_path('lxc-create', True),
'--name %s' % self.container_name,
'--quiet'
]
build_command = self._add_variables(
variables_dict=self._get_vars(
variables=LXC_COMMAND_MAP['create']['variables']
),
build_command=build_command
)
# Load logging for the instance when creating it.
if self.module.params.get('container_log') in BOOLEANS_TRUE:
# Set the logging path to the /var/log/lxc if uid is root. else
# set it to the home folder of the user executing.
try:
if os.getuid() != 0:
log_path = os.getenv('HOME')
else:
if not os.path.isdir('/var/log/lxc/'):
os.makedirs('/var/log/lxc/')
log_path = '/var/log/lxc/'
except OSError:
log_path = os.getenv('HOME')
build_command.extend([
'--logfile %s' % os.path.join(
log_path, 'lxc-%s.log' % self.container_name
),
'--logpriority %s' % self.module.params.get(
'container_log_level'
).upper()
])
# Add the template commands to the end of the command if there are any
template_options = self.module.params.get('template_options', None)
if template_options:
build_command.append('-- %s' % template_options)
rc, return_data, err = self._run_command(build_command)
if rc != 0:
message = "Failed executing lxc-create."
self.failure(
err=err, rc=rc, msg=message, command=' '.join(build_command)
)
else:
self.state_change = True
def _container_data(self):
"""Returns a dict of container information.
:returns: container data
:rtype: ``dict``
"""
return {
'interfaces': self.container.get_interfaces(),
'ips': self.container.get_ips(),
'state': self._get_state(),
'init_pid': int(self.container.init_pid),
'name' : self.container_name,
}
def _unfreeze(self):
"""Unfreeze a container.
:returns: True or False based on if the container was unfrozen.
:rtype: ``bol``
"""
unfreeze = self.container.unfreeze()
if unfreeze:
self.state_change = True
return unfreeze
def _get_state(self):
"""Return the state of a container.
If the container is not found the state returned is "absent"
:returns: state of a container as a lower case string.
:rtype: ``str``
"""
if self._container_exists(container_name=self.container_name):
return str(self.container.state).lower()
else:
return str('absent')
def _execute_command(self):
"""Execute a shell command."""
container_command = self.module.params.get('container_command')
if container_command:
container_state = self._get_state()
if container_state == 'frozen':
self._unfreeze()
elif container_state == 'stopped':
self._container_startup()
self.container.attach_wait(create_script, container_command)
self.state_change = True
def _container_startup(self, timeout=60):
"""Ensure a container is started.
:param timeout: Time before the destroy operation is abandoned.
:type timeout: ``int``
"""
self.container = self.get_container_bind()
for _ in xrange(timeout):
if self._get_state() != 'running':
self.container.start()
self.state_change = True
# post startup sleep for 1 second.
time.sleep(1)
else:
return True
else:
self.failure(
lxc_container=self._container_data(),
error='Failed to start container'
' [ %s ]' % self.container_name,
rc=1,
msg='The container [ %s ] failed to start. Check to lxc is'
' available and that the container is in a functional'
' state.' % self.container_name
)
def _check_archive(self):
"""Create a compressed archive of a container.
This will store archive_info in as self.archive_info
"""
if self.module.params.get('archive') in BOOLEANS_TRUE:
self.archive_info = {
'archive': self._container_create_tar()
}
def _check_clone(self):
"""Create a compressed archive of a container.
This will store archive_info in as self.archive_info
"""
clone_name = self.module.params.get('clone_name')
if clone_name:
if not self._container_exists(container_name=clone_name):
self.clone_info = {
'cloned': self._container_create_clone()
}
else:
self.clone_info = {
'cloned': False
}
def _destroyed(self, timeout=60):
"""Ensure a container is destroyed.
:param timeout: Time before the destroy operation is abandoned.
:type timeout: ``int``
"""
for _ in xrange(timeout):
if not self._container_exists(container_name=self.container_name):
break
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
if self._get_state() != 'stopped':
self.state_change = True
self.container.stop()
if self.container.destroy():
self.state_change = True
# post destroy attempt sleep for 1 second.
time.sleep(1)
else:
self.failure(
lxc_container=self._container_data(),
error='Failed to destroy container'
' [ %s ]' % self.container_name,
rc=1,
msg='The container [ %s ] failed to be destroyed. Check'
' that lxc is available and that the container is in a'
' functional state.' % self.container_name
)
def _frozen(self, count=0):
"""Ensure a container is frozen.
If the container does not exist the container will be created.
:param count: number of times this command has been called by itself.
:type count: ``int``
"""
self.check_count(count=count, method='frozen')
if self._container_exists(container_name=self.container_name):
self._execute_command()
# Perform any configuration updates
self._config()
container_state = self._get_state()
if container_state == 'frozen':
pass
elif container_state == 'running':
self.container.freeze()
self.state_change = True
else:
self._container_startup()
self.container.freeze()
self.state_change = True
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
else:
self._create()
count += 1
self._frozen(count)
def _restarted(self, count=0):
"""Ensure a container is restarted.
If the container does not exist the container will be created.
:param count: number of times this command has been called by itself.
:type count: ``int``
"""
self.check_count(count=count, method='restart')
if self._container_exists(container_name=self.container_name):
self._execute_command()
# Perform any configuration updates
self._config()
if self._get_state() != 'stopped':
self.container.stop()
self.state_change = True
# Run container startup
self._container_startup()
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
else:
self._create()
count += 1
self._restarted(count)
def _stopped(self, count=0):
"""Ensure a container is stopped.
If the container does not exist the container will be created.
:param count: number of times this command has been called by itself.
:type count: ``int``
"""
self.check_count(count=count, method='stop')
if self._container_exists(container_name=self.container_name):
self._execute_command()
# Perform any configuration updates
self._config()
if self._get_state() != 'stopped':
self.container.stop()
self.state_change = True
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
else:
self._create()
count += 1
self._stopped(count)
def _started(self, count=0):
"""Ensure a container is started.
If the container does not exist the container will be created.
:param count: number of times this command has been called by itself.
:type count: ``int``
"""
self.check_count(count=count, method='start')
if self._container_exists(container_name=self.container_name):
container_state = self._get_state()
if container_state == 'running':
pass
elif container_state == 'frozen':
self._unfreeze()
elif not self._container_startup():
self.failure(
lxc_container=self._container_data(),
error='Failed to start container'
' [ %s ]' % self.container_name,
rc=1,
msg='The container [ %s ] failed to start. Check to lxc is'
' available and that the container is in a functional'
' state.' % self.container_name
)
# Return data
self._execute_command()
# Perform any configuration updates
self._config()
# Check if the container needs to have an archive created.
self._check_archive()
# Check if the container is to be cloned
self._check_clone()
else:
self._create()
count += 1
self._started(count)
def _get_lxc_vg(self):
"""Return the name of the Volume Group used in LXC."""
build_command = [
self.module.get_bin_path('lxc-config', True),
"lxc.bdev.lvm.vg"
]
rc, vg, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='Failed to read LVM VG from LXC config',
command=' '.join(build_command)
)
else:
return str(vg.strip())
def _lvm_lv_list(self):
"""Return a list of all lv in a current vg."""
vg = self._get_lxc_vg()
build_command = [
self.module.get_bin_path('lvs', True)
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='Failed to get list of LVs',
command=' '.join(build_command)
)
all_lvms = [i.split() for i in stdout.splitlines()][1:]
return [lv_entry[0] for lv_entry in all_lvms if lv_entry[1] == vg]
def _get_vg_free_pe(self, vg_name):
"""Return the available size of a given VG.
:param vg_name: Name of volume.
:type vg_name: ``str``
:returns: size and measurement of an LV
:type: ``tuple``
"""
build_command = [
'vgdisplay',
vg_name,
'--units',
'g'
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to read vg %s' % vg_name,
command=' '.join(build_command)
)
vg_info = [i.strip() for i in stdout.splitlines()][1:]
free_pe = [i for i in vg_info if i.startswith('Free')]
_free_pe = free_pe[0].split()
return float(_free_pe[-2]), _free_pe[-1]
def _get_lv_size(self, lv_name):
"""Return the available size of a given LV.
:param lv_name: Name of volume.
:type lv_name: ``str``
:returns: size and measurement of an LV
:type: ``tuple``
"""
vg = self._get_lxc_vg()
lv = os.path.join(vg, lv_name)
build_command = [
'lvdisplay',
lv,
'--units',
'g'
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to read lv %s' % lv,
command=' '.join(build_command)
)
lv_info = [i.strip() for i in stdout.splitlines()][1:]
_free_pe = [i for i in lv_info if i.startswith('LV Size')]
free_pe = _free_pe[0].split()
return self._roundup(float(free_pe[-2])), free_pe[-1]
def _lvm_snapshot_create(self, source_lv, snapshot_name,
snapshot_size_gb=5):
"""Create an LVM snapshot.
:param source_lv: Name of lv to snapshot
:type source_lv: ``str``
:param snapshot_name: Name of lv snapshot
:type snapshot_name: ``str``
:param snapshot_size_gb: Size of snapshot to create
:type snapshot_size_gb: ``int``
"""
vg = self._get_lxc_vg()
free_space, messurement = self._get_vg_free_pe(vg_name=vg)
if free_space < float(snapshot_size_gb):
message = (
'Snapshot size [ %s ] is > greater than [ %s ] on volume group'
' [ %s ]' % (snapshot_size_gb, free_space, vg)
)
self.failure(
error='Not enough space to create snapshot',
rc=2,
msg=message
)
# Create LVM Snapshot
build_command = [
self.module.get_bin_path('lvcreate', True),
"-n",
snapshot_name,
"-s",
os.path.join(vg, source_lv),
"-L%sg" % snapshot_size_gb
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='Failed to Create LVM snapshot %s/%s --> %s'
% (vg, source_lv, snapshot_name)
)
def _lvm_lv_mount(self, lv_name, mount_point):
"""mount an lv.
:param lv_name: name of the logical volume to mount
:type lv_name: ``str``
:param mount_point: path on the file system that is mounted.
:type mount_point: ``str``
"""
vg = self._get_lxc_vg()
build_command = [
self.module.get_bin_path('mount', True),
"/dev/%s/%s" % (vg, lv_name),
mount_point,
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to mountlvm lv %s/%s to %s'
% (vg, lv_name, mount_point)
)
def _create_tar(self, source_dir):
"""Create an archive of a given ``source_dir`` to ``output_path``.
:param source_dir: Path to the directory to be archived.
:type source_dir: ``str``
"""
archive_path = self.module.params.get('archive_path')
if not os.path.isdir(archive_path):
os.makedirs(archive_path)
archive_compression = self.module.params.get('archive_compression')
compression_type = LXC_COMPRESSION_MAP[archive_compression]
# remove trailing / if present.
archive_name = '%s.%s' % (
os.path.join(
archive_path,
self.container_name
),
compression_type['extension']
)
build_command = [
self.module.get_bin_path('tar', True),
'--directory=%s' % os.path.realpath(
os.path.expanduser(source_dir)
),
compression_type['argument'],
archive_name,
'.'
]
rc, stdout, err = self._run_command(
build_command=build_command,
unsafe_shell=True
)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to create tar archive',
command=' '.join(build_command)
)
return archive_name
def _lvm_lv_remove(self, lv_name):
"""Remove an LV.
:param lv_name: The name of the logical volume
:type lv_name: ``str``
"""
vg = self._get_lxc_vg()
build_command = [
self.module.get_bin_path('lvremove', True),
"-f",
"%s/%s" % (vg, lv_name),
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='Failed to remove LVM LV %s/%s' % (vg, lv_name),
command=' '.join(build_command)
)
def _rsync_data(self, container_path, temp_dir):
"""Sync the container directory to the temp directory.
:param container_path: path to the container container
:type container_path: ``str``
:param temp_dir: path to the temporary local working directory
:type temp_dir: ``str``
"""
# This loop is created to support overlayfs archives. This should
# squash all of the layers into a single archive.
fs_paths = container_path.split(':')
if 'overlayfs' in fs_paths:
fs_paths.pop(fs_paths.index('overlayfs'))
for fs_path in fs_paths:
# Set the path to the container data
fs_path = os.path.dirname(fs_path)
# Run the sync command
build_command = [
self.module.get_bin_path('rsync', True),
'-aHAX',
fs_path,
temp_dir
]
rc, stdout, err = self._run_command(
build_command,
unsafe_shell=True
)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to perform archive',
command=' '.join(build_command)
)
def _unmount(self, mount_point):
"""Unmount a file system.
:param mount_point: path on the file system that is mounted.
:type mount_point: ``str``
"""
build_command = [
self.module.get_bin_path('umount', True),
mount_point,
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to unmount [ %s ]' % mount_point,
command=' '.join(build_command)
)
def _overlayfs_mount(self, lowerdir, upperdir, mount_point):
"""mount an lv.
:param lowerdir: name/path of the lower directory
:type lowerdir: ``str``
:param upperdir: name/path of the upper directory
:type upperdir: ``str``
:param mount_point: path on the file system that is mounted.
:type mount_point: ``str``
"""
build_command = [
self.module.get_bin_path('mount', True),
'-t overlayfs',
'-o lowerdir=%s,upperdir=%s' % (lowerdir, upperdir),
'overlayfs',
mount_point,
]
rc, stdout, err = self._run_command(build_command)
if rc != 0:
self.failure(
err=err,
rc=rc,
msg='failed to mount overlayfs:%s:%s to %s -- Command: %s'
% (lowerdir, upperdir, mount_point, build_command)
)
def _container_create_tar(self):
"""Create a tar archive from an LXC container.
The process is as follows:
* Stop or Freeze the container
* Create temporary dir
* Copy container and config to temporary directory
* If LVM backed:
* Create LVM snapshot of LV backing the container
* Mount the snapshot to tmpdir/rootfs
* Restore the state of the container
* Create tar of tmpdir
* Clean up
"""
# Create a temp dir
temp_dir = tempfile.mkdtemp()
# Set the name of the working dir, temp + container_name
work_dir = os.path.join(temp_dir, self.container_name)
# LXC container rootfs
lxc_rootfs = self.container.get_config_item('lxc.rootfs')
# Test if the containers rootfs is a block device
block_backed = lxc_rootfs.startswith(os.path.join(os.sep, 'dev'))
# Test if the container is using overlayfs
overlayfs_backed = lxc_rootfs.startswith('overlayfs')
mount_point = os.path.join(work_dir, 'rootfs')
# Set the snapshot name if needed
snapshot_name = '%s_lxc_snapshot' % self.container_name
container_state = self._get_state()
try:
# Ensure the original container is stopped or frozen
if container_state not in ['stopped', 'frozen']:
if container_state == 'running':
self.container.freeze()
else:
self.container.stop()
# Sync the container data from the container_path to work_dir
self._rsync_data(lxc_rootfs, temp_dir)
if block_backed:
if snapshot_name not in self._lvm_lv_list():
if not os.path.exists(mount_point):
os.makedirs(mount_point)
# Take snapshot
size, measurement = self._get_lv_size(
lv_name=self.container_name
)
self._lvm_snapshot_create(
source_lv=self.container_name,
snapshot_name=snapshot_name,
snapshot_size_gb=size
)
# Mount snapshot
self._lvm_lv_mount(
lv_name=snapshot_name,
mount_point=mount_point
)
else:
self.failure(
err='snapshot [ %s ] already exists' % snapshot_name,
rc=1,
msg='The snapshot [ %s ] already exists. Please clean'
' up old snapshot of containers before continuing.'
% snapshot_name
)
elif overlayfs_backed:
lowerdir, upperdir = lxc_rootfs.split(':')[1:]
self._overlayfs_mount(
lowerdir=lowerdir,
upperdir=upperdir,
mount_point=mount_point
)
# Set the state as changed and set a new fact
self.state_change = True
return self._create_tar(source_dir=work_dir)
finally:
if block_backed or overlayfs_backed:
# unmount snapshot
self._unmount(mount_point)
if block_backed:
# Remove snapshot
self._lvm_lv_remove(snapshot_name)
# Restore original state of container
if container_state == 'running':
if self._get_state() == 'frozen':
self.container.unfreeze()
else:
self.container.start()
# Remove tmpdir
shutil.rmtree(temp_dir)
def check_count(self, count, method):
if count > 1:
self.failure(
error='Failed to %s container' % method,
rc=1,
msg='The container [ %s ] failed to %s. Check to lxc is'
' available and that the container is in a functional'
' state.' % (self.container_name, method)
)
def failure(self, **kwargs):
"""Return a Failure when running an Ansible command.
:param error: ``str`` Error that occurred.
:param rc: ``int`` Return code while executing an Ansible command.
:param msg: ``str`` Message to report.
"""
self.module.fail_json(**kwargs)
def run(self):
"""Run the main method."""
action = getattr(self, LXC_ANSIBLE_STATES[self.state])
action()
outcome = self._container_data()
if self.archive_info:
outcome.update(self.archive_info)
if self.clone_info:
outcome.update(self.clone_info)
self.module.exit_json(
changed=self.state_change,
lxc_container=outcome
)
def main():
"""Ansible Main module."""
module = AnsibleModule(
argument_spec=dict(
name=dict(
type='str',
required=True
),
template=dict(
type='str',
default='ubuntu'
),
backing_store=dict(
type='str',
choices=LXC_BACKING_STORE.keys(),
default='dir'
),
template_options=dict(
type='str'
),
config=dict(
type='str',
),
vg_name=dict(
type='str',
default='lxc'
),
thinpool=dict(
type='str'
),
fs_type=dict(
type='str',
default='ext4'
),
fs_size=dict(
type='str',
default='5G'
),
directory=dict(
type='str'
),
zfs_root=dict(
type='str'
),
lv_name=dict(
type='str'
),
lxc_path=dict(
type='str'
),
state=dict(
choices=LXC_ANSIBLE_STATES.keys(),
default='started'
),
container_command=dict(
type='str'
),
container_config=dict(
type='str'
),
container_log=dict(
type='bool',
default='false'
),
container_log_level=dict(
choices=[n for i in LXC_LOGGING_LEVELS.values() for n in i],
default='INFO'
),
clone_name=dict(
type='str',
required=False
),
clone_snapshot=dict(
type='bool',
default='false'
),
archive=dict(
type='bool',
default='false'
),
archive_path=dict(
type='str',
),
archive_compression=dict(
choices=LXC_COMPRESSION_MAP.keys(),
default='gzip'
)
),
supports_check_mode=False,
required_if = ([
('archive', True, ['archive_path'])
]),
)
if not HAS_LXC:
module.fail_json(
msg='The `lxc` module is not importable. Check the requirements.'
)
lv_name = module.params.get('lv_name')
if not lv_name:
module.params['lv_name'] = module.params.get('name')
lxc_manage = LxcContainerManagement(module=module)
lxc_manage.run()
# import module bits
from ansible.module_utils.basic import *
main()
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_4994_0 |
crossvul-python_data_bad_2084_0 | #
# The Python Imaging Library.
# $Id$
#
# EPS file handling
#
# History:
# 1995-09-01 fl Created (0.1)
# 1996-05-18 fl Don't choke on "atend" fields, Ghostscript interface (0.2)
# 1996-08-22 fl Don't choke on floating point BoundingBox values
# 1996-08-23 fl Handle files from Macintosh (0.3)
# 2001-02-17 fl Use 're' instead of 'regex' (Python 2.1) (0.4)
# 2003-09-07 fl Check gs.close status (from Federico Di Gregorio) (0.5)
#
# Copyright (c) 1997-2003 by Secret Labs AB.
# Copyright (c) 1995-2003 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
__version__ = "0.5"
import re
import io
from PIL import Image, ImageFile, _binary
#
# --------------------------------------------------------------------
i32 = _binary.i32le
o32 = _binary.o32le
split = re.compile(r"^%%([^:]*):[ \t]*(.*)[ \t]*$")
field = re.compile(r"^%[%!\w]([^:]*)[ \t]*$")
gs_windows_binary = None
import sys
if sys.platform.startswith('win'):
import shutil
if hasattr(shutil, 'which'):
which = shutil.which
else:
# Python < 3.3
import distutils.spawn
which = distutils.spawn.find_executable
for binary in ('gswin32c', 'gswin64c', 'gs'):
if which(binary) is not None:
gs_windows_binary = binary
break
else:
gs_windows_binary = False
def Ghostscript(tile, size, fp, scale=1):
"""Render an image using Ghostscript"""
# Unpack decoder tile
decoder, tile, offset, data = tile[0]
length, bbox = data
#Hack to support hi-res rendering
scale = int(scale) or 1
orig_size = size
orig_bbox = bbox
size = (size[0] * scale, size[1] * scale)
bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]
#print("Ghostscript", scale, size, orig_size, bbox, orig_bbox)
import tempfile, os, subprocess
file = tempfile.mktemp()
# Build ghostscript command
command = ["gs",
"-q", # quite mode
"-g%dx%d" % size, # set output geometry (pixels)
"-r%d" % (72*scale), # set input DPI (dots per inch)
"-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
"-sDEVICE=ppmraw", # ppm driver
"-sOutputFile=%s" % file,# output file
]
if gs_windows_binary is not None:
if gs_windows_binary is False:
raise WindowsError('Unable to locate Ghostscript on paths')
command[0] = gs_windows_binary
# push data through ghostscript
try:
gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# adjust for image origin
if bbox[0] != 0 or bbox[1] != 0:
gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii'))
fp.seek(offset)
while length > 0:
s = fp.read(8192)
if not s:
break
length = length - len(s)
gs.stdin.write(s)
gs.stdin.close()
status = gs.wait()
if status:
raise IOError("gs failed (status %d)" % status)
im = Image.core.open_ppm(file)
finally:
try: os.unlink(file)
except: pass
return im
class PSFile:
"""Wrapper that treats either CR or LF as end of line."""
def __init__(self, fp):
self.fp = fp
self.char = None
def __getattr__(self, id):
v = getattr(self.fp, id)
setattr(self, id, v)
return v
def seek(self, offset, whence=0):
self.char = None
self.fp.seek(offset, whence)
def read(self, count):
return self.fp.read(count).decode('latin-1')
def tell(self):
pos = self.fp.tell()
if self.char:
pos = pos - 1
return pos
def readline(self):
s = b""
if self.char:
c = self.char
self.char = None
else:
c = self.fp.read(1)
while c not in b"\r\n":
s = s + c
c = self.fp.read(1)
if c == b"\r":
self.char = self.fp.read(1)
if self.char == b"\n":
self.char = None
return s.decode('latin-1') + "\n"
def _accept(prefix):
return prefix[:4] == b"%!PS" or i32(prefix) == 0xC6D3D0C5
##
# Image plugin for Encapsulated Postscript. This plugin supports only
# a few variants of this format.
class EpsImageFile(ImageFile.ImageFile):
"""EPS File Parser for the Python Imaging Library"""
format = "EPS"
format_description = "Encapsulated Postscript"
def _open(self):
# FIXME: should check the first 512 bytes to see if this
# really is necessary (platform-dependent, though...)
fp = PSFile(self.fp)
# HEAD
s = fp.read(512)
if s[:4] == "%!PS":
offset = 0
fp.seek(0, 2)
length = fp.tell()
elif i32(s) == 0xC6D3D0C5:
offset = i32(s[4:])
length = i32(s[8:])
fp.seek(offset)
else:
raise SyntaxError("not an EPS file")
fp.seek(offset)
box = None
self.mode = "RGB"
self.size = 1, 1 # FIXME: huh?
#
# Load EPS header
s = fp.readline()
while s:
if len(s) > 255:
raise SyntaxError("not an EPS file")
if s[-2:] == '\r\n':
s = s[:-2]
elif s[-1:] == '\n':
s = s[:-1]
try:
m = split.match(s)
except re.error as v:
raise SyntaxError("not an EPS file")
if m:
k, v = m.group(1, 2)
self.info[k] = v
if k == "BoundingBox":
try:
# Note: The DSC spec says that BoundingBox
# fields should be integers, but some drivers
# put floating point values there anyway.
box = [int(float(s)) for s in v.split()]
self.size = box[2] - box[0], box[3] - box[1]
self.tile = [("eps", (0,0) + self.size, offset,
(length, box))]
except:
pass
else:
m = field.match(s)
if m:
k = m.group(1)
if k == "EndComments":
break
if k[:8] == "PS-Adobe":
self.info[k[:8]] = k[9:]
else:
self.info[k] = ""
elif s[0:1] == '%':
# handle non-DSC Postscript comments that some
# tools mistakenly put in the Comments section
pass
else:
raise IOError("bad EPS header")
s = fp.readline()
if s[:1] != "%":
break
#
# Scan for an "ImageData" descriptor
while s[0] == "%":
if len(s) > 255:
raise SyntaxError("not an EPS file")
if s[-2:] == '\r\n':
s = s[:-2]
elif s[-1:] == '\n':
s = s[:-1]
if s[:11] == "%ImageData:":
[x, y, bi, mo, z3, z4, en, id] =\
s[11:].split(None, 7)
x = int(x); y = int(y)
bi = int(bi)
mo = int(mo)
en = int(en)
if en == 1:
decoder = "eps_binary"
elif en == 2:
decoder = "eps_hex"
else:
break
if bi != 8:
break
if mo == 1:
self.mode = "L"
elif mo == 2:
self.mode = "LAB"
elif mo == 3:
self.mode = "RGB"
else:
break
if id[:1] == id[-1:] == '"':
id = id[1:-1]
# Scan forward to the actual image data
while True:
s = fp.readline()
if not s:
break
if s[:len(id)] == id:
self.size = x, y
self.tile2 = [(decoder,
(0, 0, x, y),
fp.tell(),
0)]
return
s = fp.readline()
if not s:
break
if not box:
raise IOError("cannot determine EPS bounding box")
def load(self, scale=1):
# Load EPS via Ghostscript
if not self.tile:
return
self.im = Ghostscript(self.tile, self.size, self.fp, scale)
self.mode = self.im.mode
self.size = self.im.size
self.tile = []
#
# --------------------------------------------------------------------
def _save(im, fp, filename, eps=1):
"""EPS Writer for the Python Imaging Library."""
#
# make sure image data is available
im.load()
#
# determine postscript image mode
if im.mode == "L":
operator = (8, 1, "image")
elif im.mode == "RGB":
operator = (8, 3, "false 3 colorimage")
elif im.mode == "CMYK":
operator = (8, 4, "false 4 colorimage")
else:
raise ValueError("image mode is not supported")
class NoCloseStream:
def __init__(self, fp):
self.fp = fp
def __getattr__(self, name):
return getattr(self.fp, name)
def close(self):
pass
base_fp = fp
fp = io.TextIOWrapper(NoCloseStream(fp), encoding='latin-1')
if eps:
#
# write EPS header
fp.write("%!PS-Adobe-3.0 EPSF-3.0\n")
fp.write("%%Creator: PIL 0.1 EpsEncode\n")
#fp.write("%%CreationDate: %s"...)
fp.write("%%%%BoundingBox: 0 0 %d %d\n" % im.size)
fp.write("%%Pages: 1\n")
fp.write("%%EndComments\n")
fp.write("%%Page: 1 1\n")
fp.write("%%ImageData: %d %d " % im.size)
fp.write("%d %d 0 1 1 \"%s\"\n" % operator)
#
# image header
fp.write("gsave\n")
fp.write("10 dict begin\n")
fp.write("/buf %d string def\n" % (im.size[0] * operator[1]))
fp.write("%d %d scale\n" % im.size)
fp.write("%d %d 8\n" % im.size) # <= bits
fp.write("[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]))
fp.write("{ currentfile buf readhexstring pop } bind\n")
fp.write(operator[2] + "\n")
fp.flush()
ImageFile._save(im, base_fp, [("eps", (0,0)+im.size, 0, None)])
fp.write("\n%%%%EndBinary\n")
fp.write("grestore end\n")
fp.flush()
#
# --------------------------------------------------------------------
Image.register_open(EpsImageFile.format, EpsImageFile, _accept)
Image.register_save(EpsImageFile.format, _save)
Image.register_extension(EpsImageFile.format, ".ps")
Image.register_extension(EpsImageFile.format, ".eps")
Image.register_mime(EpsImageFile.format, "application/postscript")
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_2084_0 |
crossvul-python_data_good_1710_0 | # Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import traceback
import os
import subprocess
from ansible import errors
from ansible import utils
from ansible.callbacks import vvv
import ansible.constants as C
BUFSIZE = 65536
class Connection(object):
''' Local chroot based connections '''
def __init__(self, runner, host, port, *args, **kwargs):
self.chroot = host
self.has_pipelining = False
self.become_methods_supported=C.BECOME_METHODS
if os.geteuid() != 0:
raise errors.AnsibleError("chroot connection requires running as root")
# we're running as root on the local system so do some
# trivial checks for ensuring 'host' is actually a chroot'able dir
if not os.path.isdir(self.chroot):
raise errors.AnsibleError("%s is not a directory" % self.chroot)
chrootsh = os.path.join(self.chroot, 'bin/sh')
if not utils.is_executable(chrootsh):
raise errors.AnsibleError("%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot)
self.chroot_cmd = distutils.spawn.find_executable('chroot')
if not self.chroot_cmd:
raise errors.AnsibleError("chroot command not found in PATH")
self.runner = runner
self.host = host
# port is unused, since this is local
self.port = port
def connect(self, port=None):
''' connect to the chroot; nothing to do here '''
vvv("THIS IS A LOCAL CHROOT DIR", host=self.chroot)
return self
def _generate_cmd(self, executable, cmd):
if executable:
local_cmd = [self.chroot_cmd, self.chroot, executable, '-c', cmd]
else:
local_cmd = '%s "%s" %s' % (self.chroot_cmd, self.chroot, cmd)
return local_cmd
def _buffered_exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None, stdin=subprocess.PIPE):
''' run a command on the chroot. This is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
'''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
# We enter chroot as root so we ignore privlege escalation?
local_cmd = self._generate_cmd(executable, cmd)
vvv("EXEC %s" % (local_cmd), host=self.chroot)
p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
cwd=self.runner.basedir,
stdin=stdin,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the chroot '''
p = self._buffered_exec_command(cmd, tmp_path, become_user, sudoable, executable, in_data)
stdout, stderr = p.communicate()
return (p.returncode, '', stdout, stderr)
def put_file(self, in_path, out_path):
''' transfer a file from local to chroot '''
vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)
try:
with open(in_path, 'rb') as in_file:
try:
p = self._buffered_exec_command('dd of=%s' % out_path, None, stdin=in_file)
except OSError:
raise errors.AnsibleError("chroot connection requires dd command in the chroot")
try:
stdout, stderr = p.communicate()
except:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
except IOError:
raise errors.AnsibleError("file or module does not exist at: %s" % in_path)
def fetch_file(self, in_path, out_path):
''' fetch a file from chroot to local '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot)
try:
p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE), None)
except OSError:
raise errors.AnsibleError("chroot connection requires dd command in the jail")
with open(out_path, 'wb+') as out_file:
try:
for chunk in p.stdout.read(BUFSIZE):
out_file.write(chunk)
except:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file %s to %s" % (in_path, out_path))
stdout, stderr = p.communicate()
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
def close(self):
''' terminate the connection; nothing to do here '''
pass
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_1710_0 |
crossvul-python_data_bad_1710_0 | # Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2013, Maykel Moya <mmoya@speedyrails.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import traceback
import os
import shutil
import subprocess
from ansible import errors
from ansible import utils
from ansible.callbacks import vvv
import ansible.constants as C
class Connection(object):
''' Local chroot based connections '''
def __init__(self, runner, host, port, *args, **kwargs):
self.chroot = host
self.has_pipelining = False
self.become_methods_supported=C.BECOME_METHODS
if os.geteuid() != 0:
raise errors.AnsibleError("chroot connection requires running as root")
# we're running as root on the local system so do some
# trivial checks for ensuring 'host' is actually a chroot'able dir
if not os.path.isdir(self.chroot):
raise errors.AnsibleError("%s is not a directory" % self.chroot)
chrootsh = os.path.join(self.chroot, 'bin/sh')
if not utils.is_executable(chrootsh):
raise errors.AnsibleError("%s does not look like a chrootable dir (/bin/sh missing)" % self.chroot)
self.chroot_cmd = distutils.spawn.find_executable('chroot')
if not self.chroot_cmd:
raise errors.AnsibleError("chroot command not found in PATH")
self.runner = runner
self.host = host
# port is unused, since this is local
self.port = port
def connect(self, port=None):
''' connect to the chroot; nothing to do here '''
vvv("THIS IS A LOCAL CHROOT DIR", host=self.chroot)
return self
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the chroot '''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
# We enter chroot as root so we ignore privlege escalation?
if executable:
local_cmd = [self.chroot_cmd, self.chroot, executable, '-c', cmd]
else:
local_cmd = '%s "%s" %s' % (self.chroot_cmd, self.chroot, cmd)
vvv("EXEC %s" % (local_cmd), host=self.chroot)
p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
return (p.returncode, '', stdout, stderr)
def put_file(self, in_path, out_path):
''' transfer a file from local to chroot '''
if not out_path.startswith(os.path.sep):
out_path = os.path.join(os.path.sep, out_path)
normpath = os.path.normpath(out_path)
out_path = os.path.join(self.chroot, normpath[1:])
vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
shutil.copyfile(in_path, out_path)
except shutil.Error:
traceback.print_exc()
raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
except IOError:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path)
def fetch_file(self, in_path, out_path):
''' fetch a file from chroot to local '''
if not in_path.startswith(os.path.sep):
in_path = os.path.join(os.path.sep, in_path)
normpath = os.path.normpath(in_path)
in_path = os.path.join(self.chroot, normpath[1:])
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
shutil.copyfile(in_path, out_path)
except shutil.Error:
traceback.print_exc()
raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
except IOError:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path)
def close(self):
''' terminate the connection; nothing to do here '''
pass
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_1710_0 |
crossvul-python_data_bad_1711_1 | # Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# and chroot.py (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# and jail.py (c) 2013, Michael Scherer <misc@zarb.org>
# (c) 2015, Dagobert Michelsen <dam@baltic-online.de>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import traceback
import os
import shutil
import subprocess
from subprocess import Popen,PIPE
from ansible import errors
from ansible.callbacks import vvv
import ansible.constants as C
class Connection(object):
''' Local zone based connections '''
def _search_executable(self, executable):
cmd = distutils.spawn.find_executable(executable)
if not cmd:
raise errors.AnsibleError("%s command not found in PATH") % executable
return cmd
def list_zones(self):
pipe = subprocess.Popen([self.zoneadm_cmd, 'list', '-ip'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#stdout, stderr = p.communicate()
zones = []
for l in pipe.stdout.readlines():
# 1:work:running:/zones/work:3126dc59-9a07-4829-cde9-a816e4c5040e:native:shared
s = l.split(':')
if s[1] != 'global':
zones.append(s[1])
return zones
def get_zone_path(self):
#solaris10vm# zoneadm -z cswbuild list -p
#-:cswbuild:installed:/zones/cswbuild:479f3c4b-d0c6-e97b-cd04-fd58f2c0238e:native:shared
pipe = subprocess.Popen([self.zoneadm_cmd, '-z', self.zone, 'list', '-p'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#stdout, stderr = p.communicate()
path = pipe.stdout.readlines()[0].split(':')[3]
return path + '/root'
def __init__(self, runner, host, port, *args, **kwargs):
self.zone = host
self.runner = runner
self.host = host
self.has_pipelining = False
self.become_methods_supported=C.BECOME_METHODS
if os.geteuid() != 0:
raise errors.AnsibleError("zone connection requires running as root")
self.zoneadm_cmd = self._search_executable('zoneadm')
self.zlogin_cmd = self._search_executable('zlogin')
if not self.zone in self.list_zones():
raise errors.AnsibleError("incorrect zone name %s" % self.zone)
self.host = host
# port is unused, since this is local
self.port = port
def connect(self, port=None):
''' connect to the zone; nothing to do here '''
vvv("THIS IS A LOCAL ZONE DIR", host=self.zone)
return self
# a modifier
def _generate_cmd(self, executable, cmd):
if executable:
local_cmd = [self.zlogin_cmd, self.zone, executable, cmd]
else:
local_cmd = '%s "%s" %s' % (self.zlogin_cmd, self.zone, cmd)
return local_cmd
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable=None, in_data=None):
''' run a command on the zone '''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
# We happily ignore privilege escalation
if executable == '/bin/sh':
executable = None
local_cmd = self._generate_cmd(executable, cmd)
vvv("EXEC %s" % (local_cmd), host=self.zone)
p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
return (p.returncode, '', stdout, stderr)
def _normalize_path(self, path, prefix):
if not path.startswith(os.path.sep):
path = os.path.join(os.path.sep, path)
normpath = os.path.normpath(path)
return os.path.join(prefix, normpath[1:])
def _copy_file(self, in_path, out_path):
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
shutil.copyfile(in_path, out_path)
except shutil.Error:
traceback.print_exc()
raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
except IOError:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path)
def put_file(self, in_path, out_path):
''' transfer a file from local to zone '''
out_path = self._normalize_path(out_path, self.get_zone_path())
vvv("PUT %s TO %s" % (in_path, out_path), host=self.zone)
self._copy_file(in_path, out_path)
def fetch_file(self, in_path, out_path):
''' fetch a file from zone to local '''
in_path = self._normalize_path(in_path, self.get_zone_path())
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.zone)
self._copy_file(in_path, out_path)
def close(self):
''' terminate the connection; nothing to do here '''
pass
| ./CrossVul/dataset_final_sorted/CWE-59/py/bad_1711_1 |
crossvul-python_data_good_1711_1 | # Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# and chroot.py (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# and jail.py (c) 2013, Michael Scherer <misc@zarb.org>
# (c) 2015, Dagobert Michelsen <dam@baltic-online.de>
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import traceback
import os
import subprocess
from ansible import errors
from ansible.callbacks import vvv
import ansible.constants as C
BUFSIZE = 4096
class Connection(object):
''' Local zone based connections '''
def _search_executable(self, executable):
cmd = distutils.spawn.find_executable(executable)
if not cmd:
raise errors.AnsibleError("%s command not found in PATH") % executable
return cmd
def list_zones(self):
pipe = subprocess.Popen([self.zoneadm_cmd, 'list', '-ip'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
zones = []
for l in pipe.stdout.readlines():
# 1:work:running:/zones/work:3126dc59-9a07-4829-cde9-a816e4c5040e:native:shared
s = l.split(':')
if s[1] != 'global':
zones.append(s[1])
return zones
def get_zone_path(self):
#solaris10vm# zoneadm -z cswbuild list -p
#-:cswbuild:installed:/zones/cswbuild:479f3c4b-d0c6-e97b-cd04-fd58f2c0238e:native:shared
pipe = subprocess.Popen([self.zoneadm_cmd, '-z', self.zone, 'list', '-p'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#stdout, stderr = p.communicate()
path = pipe.stdout.readlines()[0].split(':')[3]
return path + '/root'
def __init__(self, runner, host, port, *args, **kwargs):
self.zone = host
self.runner = runner
self.host = host
self.has_pipelining = False
self.become_methods_supported=C.BECOME_METHODS
if os.geteuid() != 0:
raise errors.AnsibleError("zone connection requires running as root")
self.zoneadm_cmd = self._search_executable('zoneadm')
self.zlogin_cmd = self._search_executable('zlogin')
if not self.zone in self.list_zones():
raise errors.AnsibleError("incorrect zone name %s" % self.zone)
self.host = host
# port is unused, since this is local
self.port = port
def connect(self, port=None):
''' connect to the zone; nothing to do here '''
vvv("THIS IS A LOCAL ZONE DIR", host=self.zone)
return self
# a modifier
def _generate_cmd(self, executable, cmd):
if executable:
### TODO: Why was "-c" removed from here? (vs jail.py)
local_cmd = [self.zlogin_cmd, self.zone, executable, cmd]
else:
local_cmd = '%s "%s" %s' % (self.zlogin_cmd, self.zone, cmd)
return local_cmd
def _buffered_exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable=None, in_data=None, stdin=subprocess.PIPE):
''' run a command on the zone. This is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
'''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
# We happily ignore privilege escalation
local_cmd = self._generate_cmd(executable, cmd)
vvv("EXEC %s" % (local_cmd), host=self.zone)
p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
cwd=self.runner.basedir,
stdin=stdin,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable=None, in_data=None):
''' run a command on the zone '''
### TODO: Why all the precautions not to specify /bin/sh? (vs jail.py)
if executable == '/bin/sh':
executable = None
p = self._buffered_exec_command(cmd, tmp_path, become_user, sudoable, executable, in_data)
stdout, stderr = p.communicate()
return (p.returncode, '', stdout, stderr)
def put_file(self, in_path, out_path):
''' transfer a file from local to zone '''
vvv("PUT %s TO %s" % (in_path, out_path), host=self.zone)
with open(in_path, 'rb') as in_file:
p = self._buffered_exec_command('dd of=%s' % out_path, None, stdin=in_file)
try:
stdout, stderr = p.communicate()
except:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path)
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file to %s:\n%s\n%s" % (out_path, stdout, stderr))
def fetch_file(self, in_path, out_path):
''' fetch a file from zone to local '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.zone)
p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE), None)
with open(out_path, 'wb+') as out_file:
try:
for chunk in p.stdout.read(BUFSIZE):
out_file.write(chunk)
except:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path)
stdout, stderr = p.communicate()
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file to %s:\n%s\n%s" % (out_path, stdout, stderr))
def close(self):
''' terminate the connection; nothing to do here '''
pass
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_1711_1 |
crossvul-python_data_good_2084_3 | #
# The Python Imaging Library.
# $Id$
#
# JPEG (JFIF) file handling
#
# See "Digital Compression and Coding of Continous-Tone Still Images,
# Part 1, Requirements and Guidelines" (CCITT T.81 / ISO 10918-1)
#
# History:
# 1995-09-09 fl Created
# 1995-09-13 fl Added full parser
# 1996-03-25 fl Added hack to use the IJG command line utilities
# 1996-05-05 fl Workaround Photoshop 2.5 CMYK polarity bug
# 1996-05-28 fl Added draft support, JFIF version (0.1)
# 1996-12-30 fl Added encoder options, added progression property (0.2)
# 1997-08-27 fl Save mode 1 images as BW (0.3)
# 1998-07-12 fl Added YCbCr to draft and save methods (0.4)
# 1998-10-19 fl Don't hang on files using 16-bit DQT's (0.4.1)
# 2001-04-16 fl Extract DPI settings from JFIF files (0.4.2)
# 2002-07-01 fl Skip pad bytes before markers; identify Exif files (0.4.3)
# 2003-04-25 fl Added experimental EXIF decoder (0.5)
# 2003-06-06 fl Added experimental EXIF GPSinfo decoder
# 2003-09-13 fl Extract COM markers
# 2009-09-06 fl Added icc_profile support (from Florian Hoech)
# 2009-03-06 fl Changed CMYK handling; always use Adobe polarity (0.6)
# 2009-03-08 fl Added subsampling support (from Justin Huff).
#
# Copyright (c) 1997-2003 by Secret Labs AB.
# Copyright (c) 1995-1996 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#
__version__ = "0.6"
import array, struct
from PIL import Image, ImageFile, _binary
from PIL.JpegPresets import presets
from PIL._util import isStringType
i8 = _binary.i8
o8 = _binary.o8
i16 = _binary.i16be
i32 = _binary.i32be
#
# Parser
def Skip(self, marker):
n = i16(self.fp.read(2))-2
ImageFile._safe_read(self.fp, n)
def APP(self, marker):
#
# Application marker. Store these in the APP dictionary.
# Also look for well-known application markers.
n = i16(self.fp.read(2))-2
s = ImageFile._safe_read(self.fp, n)
app = "APP%d" % (marker&15)
self.app[app] = s # compatibility
self.applist.append((app, s))
if marker == 0xFFE0 and s[:4] == b"JFIF":
# extract JFIF information
self.info["jfif"] = version = i16(s, 5) # version
self.info["jfif_version"] = divmod(version, 256)
# extract JFIF properties
try:
jfif_unit = i8(s[7])
jfif_density = i16(s, 8), i16(s, 10)
except:
pass
else:
if jfif_unit == 1:
self.info["dpi"] = jfif_density
self.info["jfif_unit"] = jfif_unit
self.info["jfif_density"] = jfif_density
elif marker == 0xFFE1 and s[:5] == b"Exif\0":
# extract Exif information (incomplete)
self.info["exif"] = s # FIXME: value will change
elif marker == 0xFFE2 and s[:5] == b"FPXR\0":
# extract FlashPix information (incomplete)
self.info["flashpix"] = s # FIXME: value will change
elif marker == 0xFFE2 and s[:12] == b"ICC_PROFILE\0":
# Since an ICC profile can be larger than the maximum size of
# a JPEG marker (64K), we need provisions to split it into
# multiple markers. The format defined by the ICC specifies
# one or more APP2 markers containing the following data:
# Identifying string ASCII "ICC_PROFILE\0" (12 bytes)
# Marker sequence number 1, 2, etc (1 byte)
# Number of markers Total of APP2's used (1 byte)
# Profile data (remainder of APP2 data)
# Decoders should use the marker sequence numbers to
# reassemble the profile, rather than assuming that the APP2
# markers appear in the correct sequence.
self.icclist.append(s)
elif marker == 0xFFEE and s[:5] == b"Adobe":
self.info["adobe"] = i16(s, 5)
# extract Adobe custom properties
try:
adobe_transform = i8(s[1])
except:
pass
else:
self.info["adobe_transform"] = adobe_transform
def COM(self, marker):
#
# Comment marker. Store these in the APP dictionary.
n = i16(self.fp.read(2))-2
s = ImageFile._safe_read(self.fp, n)
self.app["COM"] = s # compatibility
self.applist.append(("COM", s))
def SOF(self, marker):
#
# Start of frame marker. Defines the size and mode of the
# image. JPEG is colour blind, so we use some simple
# heuristics to map the number of layers to an appropriate
# mode. Note that this could be made a bit brighter, by
# looking for JFIF and Adobe APP markers.
n = i16(self.fp.read(2))-2
s = ImageFile._safe_read(self.fp, n)
self.size = i16(s[3:]), i16(s[1:])
self.bits = i8(s[0])
if self.bits != 8:
raise SyntaxError("cannot handle %d-bit layers" % self.bits)
self.layers = i8(s[5])
if self.layers == 1:
self.mode = "L"
elif self.layers == 3:
self.mode = "RGB"
elif self.layers == 4:
self.mode = "CMYK"
else:
raise SyntaxError("cannot handle %d-layer images" % self.layers)
if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
self.info["progressive"] = self.info["progression"] = 1
if self.icclist:
# fixup icc profile
self.icclist.sort() # sort by sequence number
if i8(self.icclist[0][13]) == len(self.icclist):
profile = []
for p in self.icclist:
profile.append(p[14:])
icc_profile = b"".join(profile)
else:
icc_profile = None # wrong number of fragments
self.info["icc_profile"] = icc_profile
self.icclist = None
for i in range(6, len(s), 3):
t = s[i:i+3]
# 4-tuples: id, vsamp, hsamp, qtable
self.layer.append((t[0], i8(t[1])//16, i8(t[1])&15, i8(t[2])))
def DQT(self, marker):
#
# Define quantization table. Support baseline 8-bit tables
# only. Note that there might be more than one table in
# each marker.
# FIXME: The quantization tables can be used to estimate the
# compression quality.
n = i16(self.fp.read(2))-2
s = ImageFile._safe_read(self.fp, n)
while len(s):
if len(s) < 65:
raise SyntaxError("bad quantization table marker")
v = i8(s[0])
if v//16 == 0:
self.quantization[v&15] = array.array("b", s[1:65])
s = s[65:]
else:
return # FIXME: add code to read 16-bit tables!
# raise SyntaxError, "bad quantization table element size"
#
# JPEG marker table
MARKER = {
0xFFC0: ("SOF0", "Baseline DCT", SOF),
0xFFC1: ("SOF1", "Extended Sequential DCT", SOF),
0xFFC2: ("SOF2", "Progressive DCT", SOF),
0xFFC3: ("SOF3", "Spatial lossless", SOF),
0xFFC4: ("DHT", "Define Huffman table", Skip),
0xFFC5: ("SOF5", "Differential sequential DCT", SOF),
0xFFC6: ("SOF6", "Differential progressive DCT", SOF),
0xFFC7: ("SOF7", "Differential spatial", SOF),
0xFFC8: ("JPG", "Extension", None),
0xFFC9: ("SOF9", "Extended sequential DCT (AC)", SOF),
0xFFCA: ("SOF10", "Progressive DCT (AC)", SOF),
0xFFCB: ("SOF11", "Spatial lossless DCT (AC)", SOF),
0xFFCC: ("DAC", "Define arithmetic coding conditioning", Skip),
0xFFCD: ("SOF13", "Differential sequential DCT (AC)", SOF),
0xFFCE: ("SOF14", "Differential progressive DCT (AC)", SOF),
0xFFCF: ("SOF15", "Differential spatial (AC)", SOF),
0xFFD0: ("RST0", "Restart 0", None),
0xFFD1: ("RST1", "Restart 1", None),
0xFFD2: ("RST2", "Restart 2", None),
0xFFD3: ("RST3", "Restart 3", None),
0xFFD4: ("RST4", "Restart 4", None),
0xFFD5: ("RST5", "Restart 5", None),
0xFFD6: ("RST6", "Restart 6", None),
0xFFD7: ("RST7", "Restart 7", None),
0xFFD8: ("SOI", "Start of image", None),
0xFFD9: ("EOI", "End of image", None),
0xFFDA: ("SOS", "Start of scan", Skip),
0xFFDB: ("DQT", "Define quantization table", DQT),
0xFFDC: ("DNL", "Define number of lines", Skip),
0xFFDD: ("DRI", "Define restart interval", Skip),
0xFFDE: ("DHP", "Define hierarchical progression", SOF),
0xFFDF: ("EXP", "Expand reference component", Skip),
0xFFE0: ("APP0", "Application segment 0", APP),
0xFFE1: ("APP1", "Application segment 1", APP),
0xFFE2: ("APP2", "Application segment 2", APP),
0xFFE3: ("APP3", "Application segment 3", APP),
0xFFE4: ("APP4", "Application segment 4", APP),
0xFFE5: ("APP5", "Application segment 5", APP),
0xFFE6: ("APP6", "Application segment 6", APP),
0xFFE7: ("APP7", "Application segment 7", APP),
0xFFE8: ("APP8", "Application segment 8", APP),
0xFFE9: ("APP9", "Application segment 9", APP),
0xFFEA: ("APP10", "Application segment 10", APP),
0xFFEB: ("APP11", "Application segment 11", APP),
0xFFEC: ("APP12", "Application segment 12", APP),
0xFFED: ("APP13", "Application segment 13", APP),
0xFFEE: ("APP14", "Application segment 14", APP),
0xFFEF: ("APP15", "Application segment 15", APP),
0xFFF0: ("JPG0", "Extension 0", None),
0xFFF1: ("JPG1", "Extension 1", None),
0xFFF2: ("JPG2", "Extension 2", None),
0xFFF3: ("JPG3", "Extension 3", None),
0xFFF4: ("JPG4", "Extension 4", None),
0xFFF5: ("JPG5", "Extension 5", None),
0xFFF6: ("JPG6", "Extension 6", None),
0xFFF7: ("JPG7", "Extension 7", None),
0xFFF8: ("JPG8", "Extension 8", None),
0xFFF9: ("JPG9", "Extension 9", None),
0xFFFA: ("JPG10", "Extension 10", None),
0xFFFB: ("JPG11", "Extension 11", None),
0xFFFC: ("JPG12", "Extension 12", None),
0xFFFD: ("JPG13", "Extension 13", None),
0xFFFE: ("COM", "Comment", COM)
}
def _accept(prefix):
return prefix[0:1] == b"\377"
##
# Image plugin for JPEG and JFIF images.
class JpegImageFile(ImageFile.ImageFile):
format = "JPEG"
format_description = "JPEG (ISO 10918)"
def _open(self):
s = self.fp.read(1)
if i8(s[0]) != 255:
raise SyntaxError("not a JPEG file")
# Create attributes
self.bits = self.layers = 0
# JPEG specifics (internal)
self.layer = []
self.huffman_dc = {}
self.huffman_ac = {}
self.quantization = {}
self.app = {} # compatibility
self.applist = []
self.icclist = []
while True:
s = s + self.fp.read(1)
i = i16(s)
if i in MARKER:
name, description, handler = MARKER[i]
# print hex(i), name, description
if handler is not None:
handler(self, i)
if i == 0xFFDA: # start of scan
rawmode = self.mode
if self.mode == "CMYK":
rawmode = "CMYK;I" # assume adobe conventions
self.tile = [("jpeg", (0,0) + self.size, 0, (rawmode, ""))]
# self.__offset = self.fp.tell()
break
s = self.fp.read(1)
elif i == 0 or i == 65535:
# padded marker or junk; move on
s = "\xff"
else:
raise SyntaxError("no marker found")
def draft(self, mode, size):
if len(self.tile) != 1:
return
d, e, o, a = self.tile[0]
scale = 0
if a[0] == "RGB" and mode in ["L", "YCbCr"]:
self.mode = mode
a = mode, ""
if size:
scale = max(self.size[0] // size[0], self.size[1] // size[1])
for s in [8, 4, 2, 1]:
if scale >= s:
break
e = e[0], e[1], (e[2]-e[0]+s-1)//s+e[0], (e[3]-e[1]+s-1)//s+e[1]
self.size = ((self.size[0]+s-1)//s, (self.size[1]+s-1)//s)
scale = s
self.tile = [(d, e, o, a)]
self.decoderconfig = (scale, 1)
return self
def load_djpeg(self):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities
import tempfile, os
f, path = tempfile.mkstemp()
os.close(f)
if os.path.exists(self.filename):
os.system("djpeg '%s' >'%s'" % (self.filename, path))
else:
raise ValueError("Invalid Filename")
try:
self.im = Image.core.open_ppm(path)
finally:
try: os.unlink(path)
except: pass
self.mode = self.im.mode
self.size = self.im.size
self.tile = []
def _getexif(self):
return _getexif(self)
def _getexif(self):
# Extract EXIF information. This method is highly experimental,
# and is likely to be replaced with something better in a future
# version.
from PIL import TiffImagePlugin
import io
def fixup(value):
if len(value) == 1:
return value[0]
return value
# The EXIF record consists of a TIFF file embedded in a JPEG
# application marker (!).
try:
data = self.info["exif"]
except KeyError:
return None
file = io.BytesIO(data[6:])
head = file.read(8)
exif = {}
# process dictionary
info = TiffImagePlugin.ImageFileDirectory(head)
info.load(file)
for key, value in info.items():
exif[key] = fixup(value)
# get exif extension
try:
file.seek(exif[0x8769])
except KeyError:
pass
else:
info = TiffImagePlugin.ImageFileDirectory(head)
info.load(file)
for key, value in info.items():
exif[key] = fixup(value)
# get gpsinfo extension
try:
file.seek(exif[0x8825])
except KeyError:
pass
else:
info = TiffImagePlugin.ImageFileDirectory(head)
info.load(file)
exif[0x8825] = gps = {}
for key, value in info.items():
gps[key] = fixup(value)
return exif
# --------------------------------------------------------------------
# stuff to save JPEG files
RAWMODE = {
"1": "L",
"L": "L",
"RGB": "RGB",
"RGBA": "RGB",
"RGBX": "RGB",
"CMYK": "CMYK;I", # assume adobe conventions
"YCbCr": "YCbCr",
}
zigzag_index = ( 0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63)
samplings = {
(1, 1, 1, 1, 1, 1): 0,
(2, 1, 1, 1, 1, 1): 1,
(2, 2, 1, 1, 1, 1): 2,
}
def convert_dict_qtables(qtables):
qtables = [qtables[key] for key in xrange(len(qtables)) if qtables.has_key(key)]
for idx, table in enumerate(qtables):
qtables[idx] = [table[i] for i in zigzag_index]
return qtables
def get_sampling(im):
sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3]
return samplings.get(sampling, -1)
def _save(im, fp, filename):
try:
rawmode = RAWMODE[im.mode]
except KeyError:
raise IOError("cannot write mode %s as JPEG" % im.mode)
info = im.encoderinfo
dpi = info.get("dpi", (0, 0))
quality = info.get("quality", 0)
subsampling = info.get("subsampling", -1)
qtables = info.get("qtables")
if quality == "keep":
quality = 0
subsampling = "keep"
qtables = "keep"
elif quality in presets:
preset = presets[quality]
quality = 0
subsampling = preset.get('subsampling', -1)
qtables = preset.get('quantization')
elif not isinstance(quality, int):
raise ValueError("Invalid quality setting")
else:
if subsampling in presets:
subsampling = presets[subsampling].get('subsampling', -1)
if qtables in presets:
qtables = presets[qtables].get('quantization')
if subsampling == "4:4:4":
subsampling = 0
elif subsampling == "4:2:2":
subsampling = 1
elif subsampling == "4:1:1":
subsampling = 2
elif subsampling == "keep":
if im.format != "JPEG":
raise ValueError("Cannot use 'keep' when original image is not a JPEG")
subsampling = get_sampling(im)
def validate_qtables(qtables):
if qtables is None:
return qtables
if isStringType(qtables):
try:
lines = [int(num) for line in qtables.splitlines()
for num in line.split('#', 1)[0].split()]
except ValueError:
raise ValueError("Invalid quantization table")
else:
qtables = [lines[s:s+64] for s in xrange(0, len(lines), 64)]
if isinstance(qtables, (tuple, list, dict)):
if isinstance(qtables, dict):
qtables = convert_dict_qtables(qtables)
elif isinstance(qtables, tuple):
qtables = list(qtables)
if not (0 < len(qtables) < 5):
raise ValueError("None or too many quantization tables")
for idx, table in enumerate(qtables):
try:
if len(table) != 64:
raise
table = array.array('b', table)
except TypeError:
raise ValueError("Invalid quantization table")
else:
qtables[idx] = list(table)
return qtables
if qtables == "keep":
if im.format != "JPEG":
raise ValueError("Cannot use 'keep' when original image is not a JPEG")
qtables = getattr(im, "quantization", None)
qtables = validate_qtables(qtables)
extra = b""
icc_profile = info.get("icc_profile")
if icc_profile:
ICC_OVERHEAD_LEN = 14
MAX_BYTES_IN_MARKER = 65533
MAX_DATA_BYTES_IN_MARKER = MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN
markers = []
while icc_profile:
markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:]
i = 1
for marker in markers:
size = struct.pack(">H", 2 + ICC_OVERHEAD_LEN + len(marker))
extra = extra + (b"\xFF\xE2" + size + b"ICC_PROFILE\0" + o8(i) + o8(len(markers)) + marker)
i = i + 1
# get keyword arguments
im.encoderconfig = (
quality,
# "progressive" is the official name, but older documentation
# says "progression"
# FIXME: issue a warning if the wrong form is used (post-1.1.7)
"progressive" in info or "progression" in info,
info.get("smooth", 0),
"optimize" in info,
info.get("streamtype", 0),
dpi[0], dpi[1],
subsampling,
qtables,
extra,
info.get("exif", b"")
)
# if we optimize, libjpeg needs a buffer big enough to hold the whole image in a shot.
# Guessing on the size, at im.size bytes. (raw pizel size is channels*size, this
# is a value that's been used in a django patch.
# https://github.com/jdriscoll/django-imagekit/issues/50
bufsize=0
if "optimize" in info or "progressive" in info or "progression" in info:
bufsize = im.size[0]*im.size[1]
# The exif info needs to be written as one block, + APP1, + one spare byte.
# Ensure that our buffer is big enough
bufsize = max(ImageFile.MAXBLOCK, bufsize, len(info.get("exif",b"")) + 5 )
ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)], bufsize)
def _save_cjpeg(im, fp, filename):
# ALTERNATIVE: handle JPEGs via the IJG command line utilities.
import os
file = im._dump()
os.system("cjpeg %s >%s" % (file, filename))
try: os.unlink(file)
except: pass
# -------------------------------------------------------------------q-
# Registry stuff
Image.register_open("JPEG", JpegImageFile, _accept)
Image.register_save("JPEG", _save)
Image.register_extension("JPEG", ".jfif")
Image.register_extension("JPEG", ".jpe")
Image.register_extension("JPEG", ".jpg")
Image.register_extension("JPEG", ".jpeg")
Image.register_mime("JPEG", "image/jpeg")
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_2084_3 |
crossvul-python_data_good_1711_0 | # Based on local.py (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# and chroot.py (c) 2013, Maykel Moya <mmoya@speedyrails.com>
# (c) 2013, Michael Scherer <misc@zarb.org>
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import traceback
import os
import subprocess
from ansible import errors
from ansible.callbacks import vvv
import ansible.constants as C
BUFSIZE = 4096
class Connection(object):
''' Local BSD Jail based connections '''
def _search_executable(self, executable):
cmd = distutils.spawn.find_executable(executable)
if not cmd:
raise errors.AnsibleError("%s command not found in PATH") % executable
return cmd
def list_jails(self):
p = subprocess.Popen([self.jls_cmd, '-q', 'name'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.split()
def get_jail_path(self):
p = subprocess.Popen([self.jls_cmd, '-j', self.jail, '-q', 'path'],
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
# remove \n
return stdout[:-1]
def __init__(self, runner, host, port, *args, **kwargs):
self.jail = host
self.runner = runner
self.host = host
self.has_pipelining = False
self.become_methods_supported=C.BECOME_METHODS
if os.geteuid() != 0:
raise errors.AnsibleError("jail connection requires running as root")
self.jls_cmd = self._search_executable('jls')
self.jexec_cmd = self._search_executable('jexec')
if not self.jail in self.list_jails():
raise errors.AnsibleError("incorrect jail name %s" % self.jail)
self.host = host
# port is unused, since this is local
self.port = port
def connect(self, port=None):
''' connect to the jail; nothing to do here '''
vvv("THIS IS A LOCAL JAIL DIR", host=self.jail)
return self
# a modifier
def _generate_cmd(self, executable, cmd):
if executable:
local_cmd = [self.jexec_cmd, self.jail, executable, '-c', cmd]
else:
local_cmd = '%s "%s" %s' % (self.jexec_cmd, self.jail, cmd)
return local_cmd
def _buffered_exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None, stdin=subprocess.PIPE):
''' run a command on the jail. This is only needed for implementing
put_file() get_file() so that we don't have to read the whole file
into memory.
compared to exec_command() it looses some niceties like being able to
return the process's exit code immediately.
'''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
# Ignores privilege escalation
local_cmd = self._generate_cmd(executable, cmd)
vvv("EXEC %s" % (local_cmd), host=self.jail)
p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
cwd=self.runner.basedir,
stdin=stdin,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return p
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the jail '''
p = self._buffered_exec_command(cmd, tmp_path, become_user, sudoable, executable, in_data)
stdout, stderr = p.communicate()
return (p.returncode, '', stdout, stderr)
def put_file(self, in_path, out_path):
''' transfer a file from local to jail '''
vvv("PUT %s TO %s" % (in_path, out_path), host=self.jail)
with open(in_path, 'rb') as in_file:
p = self._buffered_exec_command('dd of=%s' % out_path, None, stdin=in_file)
try:
stdout, stderr = p.communicate()
except:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path)
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file to %s:\n%s\n%s" % (out_path, stdout, stderr))
def fetch_file(self, in_path, out_path):
''' fetch a file from jail to local '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.jail)
p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE), None)
with open(out_path, 'wb+') as out_file:
try:
for chunk in p.stdout.read(BUFSIZE):
out_file.write(chunk)
except:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path)
stdout, stderr = p.communicate()
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file to %s:\n%s\n%s" % (out_path, stdout, stderr))
def close(self):
''' terminate the connection; nothing to do here '''
pass
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_1711_0 |
crossvul-python_data_good_2084_2 | #
# The Python Imaging Library.
# $Id$
#
# IPTC/NAA file handling
#
# history:
# 1995-10-01 fl Created
# 1998-03-09 fl Cleaned up and added to PIL
# 2002-06-18 fl Added getiptcinfo helper
#
# Copyright (c) Secret Labs AB 1997-2002.
# Copyright (c) Fredrik Lundh 1995.
#
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
__version__ = "0.3"
from PIL import Image, ImageFile, _binary
import os, tempfile
i8 = _binary.i8
i16 = _binary.i16be
i32 = _binary.i32be
o8 = _binary.o8
COMPRESSION = {
1: "raw",
5: "jpeg"
}
PAD = o8(0) * 4
#
# Helpers
def i(c):
return i32((PAD + c)[-4:])
def dump(c):
for i in c:
print("%02x" % i8(i), end=' ')
print()
##
# Image plugin for IPTC/NAA datastreams. To read IPTC/NAA fields
# from TIFF and JPEG files, use the <b>getiptcinfo</b> function.
class IptcImageFile(ImageFile.ImageFile):
format = "IPTC"
format_description = "IPTC/NAA"
def getint(self, key):
return i(self.info[key])
def field(self):
#
# get a IPTC field header
s = self.fp.read(5)
if not len(s):
return None, 0
tag = i8(s[1]), i8(s[2])
# syntax
if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9:
raise SyntaxError("invalid IPTC/NAA file")
# field size
size = i8(s[3])
if size > 132:
raise IOError("illegal field length in IPTC/NAA file")
elif size == 128:
size = 0
elif size > 128:
size = i(self.fp.read(size-128))
else:
size = i16(s[3:])
return tag, size
def _is_raw(self, offset, size):
#
# check if the file can be mapped
# DISABLED: the following only slows things down...
return 0
self.fp.seek(offset)
t, sz = self.field()
if sz != size[0]:
return 0
y = 1
while True:
self.fp.seek(sz, 1)
t, s = self.field()
if t != (8, 10):
break
if s != sz:
return 0
y = y + 1
return y == size[1]
def _open(self):
# load descriptive fields
while True:
offset = self.fp.tell()
tag, size = self.field()
if not tag or tag == (8,10):
break
if size:
tagdata = self.fp.read(size)
else:
tagdata = None
if tag in list(self.info.keys()):
if isinstance(self.info[tag], list):
self.info[tag].append(tagdata)
else:
self.info[tag] = [self.info[tag], tagdata]
else:
self.info[tag] = tagdata
# print tag, self.info[tag]
# mode
layers = i8(self.info[(3,60)][0])
component = i8(self.info[(3,60)][1])
if (3,65) in self.info:
id = i8(self.info[(3,65)][0])-1
else:
id = 0
if layers == 1 and not component:
self.mode = "L"
elif layers == 3 and component:
self.mode = "RGB"[id]
elif layers == 4 and component:
self.mode = "CMYK"[id]
# size
self.size = self.getint((3,20)), self.getint((3,30))
# compression
try:
compression = COMPRESSION[self.getint((3,120))]
except KeyError:
raise IOError("Unknown IPTC image compression")
# tile
if tag == (8,10):
if compression == "raw" and self._is_raw(offset, self.size):
self.tile = [(compression, (offset, size + 5, -1),
(0, 0, self.size[0], self.size[1]))]
else:
self.tile = [("iptc", (compression, offset),
(0, 0, self.size[0], self.size[1]))]
def load(self):
if len(self.tile) != 1 or self.tile[0][0] != "iptc":
return ImageFile.ImageFile.load(self)
type, tile, box = self.tile[0]
encoding, offset = tile
self.fp.seek(offset)
# Copy image data to temporary file
o_fd, outfile = tempfile.mkstemp(text=False)
o = os.fdopen(o_fd)
if encoding == "raw":
# To simplify access to the extracted file,
# prepend a PPM header
o.write("P5\n%d %d\n255\n" % self.size)
while True:
type, size = self.field()
if type != (8, 10):
break
while size > 0:
s = self.fp.read(min(size, 8192))
if not s:
break
o.write(s)
size = size - len(s)
o.close()
try:
try:
# fast
self.im = Image.core.open_ppm(outfile)
except:
# slightly slower
im = Image.open(outfile)
im.load()
self.im = im.im
finally:
try: os.unlink(outfile)
except: pass
Image.register_open("IPTC", IptcImageFile)
Image.register_extension("IPTC", ".iim")
##
# Get IPTC information from TIFF, JPEG, or IPTC file.
#
# @param im An image containing IPTC data.
# @return A dictionary containing IPTC information, or None if
# no IPTC information block was found.
def getiptcinfo(im):
from PIL import TiffImagePlugin, JpegImagePlugin
import io
data = None
if isinstance(im, IptcImageFile):
# return info dictionary right away
return im.info
elif isinstance(im, JpegImagePlugin.JpegImageFile):
# extract the IPTC/NAA resource
try:
app = im.app["APP13"]
if app[:14] == "Photoshop 3.0\x00":
app = app[14:]
# parse the image resource block
offset = 0
while app[offset:offset+4] == "8BIM":
offset = offset + 4
# resource code
code = JpegImagePlugin.i16(app, offset)
offset = offset + 2
# resource name (usually empty)
name_len = i8(app[offset])
name = app[offset+1:offset+1+name_len]
offset = 1 + offset + name_len
if offset & 1:
offset = offset + 1
# resource data block
size = JpegImagePlugin.i32(app, offset)
offset = offset + 4
if code == 0x0404:
# 0x0404 contains IPTC/NAA data
data = app[offset:offset+size]
break
offset = offset + size
if offset & 1:
offset = offset + 1
except (AttributeError, KeyError):
pass
elif isinstance(im, TiffImagePlugin.TiffImageFile):
# get raw data from the IPTC/NAA tag (PhotoShop tags the data
# as 4-byte integers, so we cannot use the get method...)
try:
data = im.tag.tagdata[TiffImagePlugin.IPTC_NAA_CHUNK]
except (AttributeError, KeyError):
pass
if data is None:
return None # no properties
# create an IptcImagePlugin object without initializing it
class FakeImage:
pass
im = FakeImage()
im.__class__ = IptcImageFile
# parse the IPTC information chunk
im.info = {}
im.fp = io.BytesIO(data)
try:
im._open()
except (IndexError, KeyError):
pass # expected failure
return im.info
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_2084_2 |
crossvul-python_data_good_3481_0 | #!/usr/bin/env python
#############################################################################
#
# Run Pyro servers as daemon processes on Unix/Linux.
# This won't work on other operating systems such as Windows.
# Author: Jeff Bauer (jbauer@rubic.com)
# This software is released under the MIT software license.
# Based on an earlier daemonize module by Jeffery Kunce
# Updated by Luis Camaano to double-fork-detach.
#
# DEPRECATED. Don't use this in new code.
#
# This is part of "Pyro" - Python Remote Objects
# which is (c) Irmen de Jong - irmen@razorvine.net
#
#############################################################################
import sys, os, time
from signal import SIGINT
class DaemonizerException:
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Daemonizer:
"""
Daemonizer is a class wrapper to run a Pyro server program
in the background as daemon process. The only requirement
is for the derived class to implement a main_loop() method.
See Test class below for an example.
The following command line operations are provided to support
typical /etc/init.d startup/shutdown on Unix systems:
start | stop | restart
In addition, a daemonized program can be called with arguments:
status - check if process is still running
debug - run the program in non-daemon mode for testing
Note: Since Daemonizer uses fork(), it will not work on non-Unix
systems.
"""
def __init__(self, pidfile=None):
if not pidfile:
# PID file moved out of /tmp to avoid security vulnerability
# changed by Debian maintainer per Debian bug #631912
self.pidfile = "/var/run/pyro-%s.pid" % self.__class__.__name__.lower()
else:
self.pidfile = pidfile
def become_daemon(self, root_dir='/'):
if os.fork() != 0: # launch child and ...
os._exit(0) # kill off parent
os.setsid()
os.chdir(root_dir)
os.umask(0)
if os.fork() != 0: # fork again so we are not a session leader
os._exit(0)
sys.stdin.close()
sys.__stdin__ = sys.stdin
sys.stdout.close()
sys.stdout = sys.__stdout__ = _NullDevice()
sys.stderr.close()
sys.stderr = sys.__stderr__ = _NullDevice()
for fd in range(1024):
try:
os.close(fd)
except OSError:
pass
def daemon_start(self, start_as_daemon=1):
if start_as_daemon:
self.become_daemon()
if self.is_process_running():
msg = "Unable to start server. Process is already running."
raise DaemonizerException(msg)
f = open(self.pidfile, 'w')
f.write("%s" % os.getpid())
f.close()
self.main_loop()
def daemon_stop(self):
pid = self.get_pid()
try:
os.kill(pid, SIGINT) # SIGTERM is too harsh...
time.sleep(1)
try:
os.unlink(self.pidfile)
except OSError:
pass
except IOError:
pass
def get_pid(self):
try:
f = open(self.pidfile)
pid = int(f.readline().strip())
f.close()
except IOError:
pid = None
return pid
def is_process_running(self):
pid = self.get_pid()
if pid:
try:
os.kill(pid, 0)
return 1
except OSError:
pass
return 0
def main_loop(self):
"""NOTE: This method must be implemented in the derived class."""
msg = "main_loop method not implemented in derived class: %s" % \
self.__class__.__name__
raise DaemonizerException(msg)
def process_command_line(self, argv, verbose=1):
usage = "usage: %s start | stop | restart | status | debug " \
"[--pidfile=...] " \
"(run as non-daemon)" % os.path.basename(argv[0])
if len(argv) < 2:
print usage
raise SystemExit
else:
operation = argv[1]
if len(argv) > 2 and argv[2].startswith('--pidfile=') and \
len(argv[2]) > len('--pidfile='):
self.pidfile = argv[2][len('--pidfile='):]
pid = self.get_pid()
if operation == 'status':
if self.is_process_running():
print "Server process %s is running." % pid
else:
print "Server is not running."
elif operation == 'start':
if self.is_process_running():
print "Server process %s is already running." % pid
raise SystemExit
else:
if verbose:
print "Starting server process."
self.daemon_start()
elif operation == 'stop':
if self.is_process_running():
self.daemon_stop()
if verbose:
print "Server process %s stopped." % pid
else:
print "Server process %s is not running." % pid
raise SystemExit
elif operation == 'restart':
self.daemon_stop()
if verbose:
print "Restarting server process."
self.daemon_start()
elif operation == 'debug':
self.daemon_start(0)
else:
print "Unknown operation:", operation
raise SystemExit
class _NullDevice:
"""A substitute for stdout/stderr that writes to nowhere."""
def write(self, s):
pass
class Test(Daemonizer):
def __init__(self):
Daemonizer.__init__(self)
def main_loop(self):
while 1:
time.sleep(1)
if __name__ == "__main__":
test = Test()
test.process_command_line(sys.argv)
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_3481_0 |
crossvul-python_data_good_2084_1 | #
# The Python Imaging Library.
# $Id$
#
# the Image class wrapper
#
# partial release history:
# 1995-09-09 fl Created
# 1996-03-11 fl PIL release 0.0 (proof of concept)
# 1996-04-30 fl PIL release 0.1b1
# 1999-07-28 fl PIL release 1.0 final
# 2000-06-07 fl PIL release 1.1
# 2000-10-20 fl PIL release 1.1.1
# 2001-05-07 fl PIL release 1.1.2
# 2002-03-15 fl PIL release 1.1.3
# 2003-05-10 fl PIL release 1.1.4
# 2005-03-28 fl PIL release 1.1.5
# 2006-12-02 fl PIL release 1.1.6
# 2009-11-15 fl PIL release 1.1.7
#
# Copyright (c) 1997-2009 by Secret Labs AB. All rights reserved.
# Copyright (c) 1995-2009 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
from PIL import VERSION, PILLOW_VERSION, _plugins
import warnings
class _imaging_not_installed:
# module placeholder
def __getattr__(self, id):
raise ImportError("The _imaging C module is not installed")
try:
# give Tk a chance to set up the environment, in case we're
# using an _imaging module linked against libtcl/libtk (use
# __import__ to hide this from naive packagers; we don't really
# depend on Tk unless ImageTk is used, and that module already
# imports Tkinter)
__import__("FixTk")
except ImportError:
pass
try:
# If the _imaging C module is not present, you can still use
# the "open" function to identify files, but you cannot load
# them. Note that other modules should not refer to _imaging
# directly; import Image and use the Image.core variable instead.
from PIL import _imaging as core
if PILLOW_VERSION != getattr(core, 'PILLOW_VERSION', None):
raise ImportError("The _imaging extension was built for another "
" version of Pillow or PIL")
except ImportError as v:
core = _imaging_not_installed()
# Explanations for ways that we know we might have an import error
if str(v).startswith("Module use of python"):
# The _imaging C module is present, but not compiled for
# the right version (windows only). Print a warning, if
# possible.
warnings.warn(
"The _imaging extension was built for another version "
"of Python.",
RuntimeWarning
)
elif str(v).startswith("The _imaging extension"):
warnings.warn(str(v), RuntimeWarning)
elif "Symbol not found: _PyUnicodeUCS2_FromString" in str(v):
warnings.warn(
"The _imaging extension was built for Python with UCS2 support; "
"recompile PIL or build Python --without-wide-unicode. ",
RuntimeWarning
)
elif "Symbol not found: _PyUnicodeUCS4_FromString" in str(v):
warnings.warn(
"The _imaging extension was built for Python with UCS4 support; "
"recompile PIL or build Python --with-wide-unicode. ",
RuntimeWarning
)
# Fail here anyway. Don't let people run with a mostly broken Pillow.
raise
try:
import builtins
except ImportError:
import __builtin__
builtins = __builtin__
from PIL import ImageMode
from PIL._binary import i8, o8
from PIL._util import isPath, isStringType
import os, sys
# type stuff
import collections
import numbers
def isImageType(t):
"""
Checks if an object is an image object.
.. warning::
This function is for internal use only.
:param t: object to check if it's an image
:returns: True if the object is an image
"""
return hasattr(t, "im")
#
# Debug level
DEBUG = 0
#
# Constants (also defined in _imagingmodule.c!)
NONE = 0
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
ROTATE_90 = 2
ROTATE_180 = 3
ROTATE_270 = 4
# transforms
AFFINE = 0
EXTENT = 1
PERSPECTIVE = 2
QUAD = 3
MESH = 4
# resampling filters
NONE = 0
NEAREST = 0
ANTIALIAS = 1 # 3-lobed lanczos
LINEAR = BILINEAR = 2
CUBIC = BICUBIC = 3
# dithers
NONE = 0
NEAREST = 0
ORDERED = 1 # Not yet implemented
RASTERIZE = 2 # Not yet implemented
FLOYDSTEINBERG = 3 # default
# palettes/quantizers
WEB = 0
ADAPTIVE = 1
MEDIANCUT = 0
MAXCOVERAGE = 1
FASTOCTREE = 2
# categories
NORMAL = 0
SEQUENCE = 1
CONTAINER = 2
if hasattr(core, 'DEFAULT_STRATEGY'):
DEFAULT_STRATEGY = core.DEFAULT_STRATEGY
FILTERED = core.FILTERED
HUFFMAN_ONLY = core.HUFFMAN_ONLY
RLE = core.RLE
FIXED = core.FIXED
# --------------------------------------------------------------------
# Registries
ID = []
OPEN = {}
MIME = {}
SAVE = {}
EXTENSION = {}
# --------------------------------------------------------------------
# Modes supported by this version
_MODEINFO = {
# NOTE: this table will be removed in future versions. use
# getmode* functions or ImageMode descriptors instead.
# official modes
"1": ("L", "L", ("1",)),
"L": ("L", "L", ("L",)),
"I": ("L", "I", ("I",)),
"F": ("L", "F", ("F",)),
"P": ("RGB", "L", ("P",)),
"RGB": ("RGB", "L", ("R", "G", "B")),
"RGBX": ("RGB", "L", ("R", "G", "B", "X")),
"RGBA": ("RGB", "L", ("R", "G", "B", "A")),
"CMYK": ("RGB", "L", ("C", "M", "Y", "K")),
"YCbCr": ("RGB", "L", ("Y", "Cb", "Cr")),
"LAB": ("RGB", "L", ("L", "A", "B")),
# Experimental modes include I;16, I;16L, I;16B, RGBa, BGR;15, and
# BGR;24. Use these modes only if you know exactly what you're
# doing...
}
if sys.byteorder == 'little':
_ENDIAN = '<'
else:
_ENDIAN = '>'
_MODE_CONV = {
# official modes
"1": ('|b1', None), # broken
"L": ('|u1', None),
"I": (_ENDIAN + 'i4', None),
"F": (_ENDIAN + 'f4', None),
"P": ('|u1', None),
"RGB": ('|u1', 3),
"RGBX": ('|u1', 4),
"RGBA": ('|u1', 4),
"CMYK": ('|u1', 4),
"YCbCr": ('|u1', 3),
"LAB": ('|u1', 3), # UNDONE - unsigned |u1i1i1
# I;16 == I;16L, and I;32 == I;32L
"I;16": ('<u2', None),
"I;16B": ('>u2', None),
"I;16L": ('<u2', None),
"I;16S": ('<i2', None),
"I;16BS": ('>i2', None),
"I;16LS": ('<i2', None),
"I;32": ('<u4', None),
"I;32B": ('>u4', None),
"I;32L": ('<u4', None),
"I;32S": ('<i4', None),
"I;32BS": ('>i4', None),
"I;32LS": ('<i4', None),
}
def _conv_type_shape(im):
shape = im.size[1], im.size[0]
typ, extra = _MODE_CONV[im.mode]
if extra is None:
return shape, typ
else:
return shape+(extra,), typ
MODES = sorted(_MODEINFO.keys())
# raw modes that may be memory mapped. NOTE: if you change this, you
# may have to modify the stride calculation in map.c too!
_MAPMODES = ("L", "P", "RGBX", "RGBA", "CMYK", "I;16", "I;16L", "I;16B")
def getmodebase(mode):
"""
Gets the "base" mode for given mode. This function returns "L" for
images that contain grayscale data, and "RGB" for images that
contain color data.
:param mode: Input mode.
:returns: "L" or "RGB".
:exception KeyError: If the input mode was not a standard mode.
"""
return ImageMode.getmode(mode).basemode
def getmodetype(mode):
"""
Gets the storage type mode. Given a mode, this function returns a
single-layer mode suitable for storing individual bands.
:param mode: Input mode.
:returns: "L", "I", or "F".
:exception KeyError: If the input mode was not a standard mode.
"""
return ImageMode.getmode(mode).basetype
def getmodebandnames(mode):
"""
Gets a list of individual band names. Given a mode, this function returns
a tuple containing the names of individual bands (use
:py:method:`~PIL.Image.getmodetype` to get the mode used to store each
individual band.
:param mode: Input mode.
:returns: A tuple containing band names. The length of the tuple
gives the number of bands in an image of the given mode.
:exception KeyError: If the input mode was not a standard mode.
"""
return ImageMode.getmode(mode).bands
def getmodebands(mode):
"""
Gets the number of individual bands for this mode.
:param mode: Input mode.
:returns: The number of bands in this mode.
:exception KeyError: If the input mode was not a standard mode.
"""
return len(ImageMode.getmode(mode).bands)
# --------------------------------------------------------------------
# Helpers
_initialized = 0
def preinit():
"Explicitly load standard file format drivers."
global _initialized
if _initialized >= 1:
return
try:
from PIL import BmpImagePlugin
except ImportError:
pass
try:
from PIL import GifImagePlugin
except ImportError:
pass
try:
from PIL import JpegImagePlugin
except ImportError:
pass
try:
from PIL import PpmImagePlugin
except ImportError:
pass
try:
from PIL import PngImagePlugin
except ImportError:
pass
# try:
# import TiffImagePlugin
# except ImportError:
# pass
_initialized = 1
def init():
"""
Explicitly initializes the Python Imaging Library. This function
loads all available file format drivers.
"""
global _initialized
if _initialized >= 2:
return 0
for plugin in _plugins:
try:
if DEBUG:
print ("Importing %s"%plugin)
__import__("PIL.%s"%plugin, globals(), locals(), [])
except ImportError:
if DEBUG:
print("Image: failed to import", end=' ')
print(plugin, ":", sys.exc_info()[1])
if OPEN or SAVE:
_initialized = 2
return 1
# --------------------------------------------------------------------
# Codec factories (used by tobytes/frombytes and ImageFile.load)
def _getdecoder(mode, decoder_name, args, extra=()):
# tweak arguments
if args is None:
args = ()
elif not isinstance(args, tuple):
args = (args,)
try:
# get decoder
decoder = getattr(core, decoder_name + "_decoder")
# print(decoder, mode, args + extra)
return decoder(mode, *args + extra)
except AttributeError:
raise IOError("decoder %s not available" % decoder_name)
def _getencoder(mode, encoder_name, args, extra=()):
# tweak arguments
if args is None:
args = ()
elif not isinstance(args, tuple):
args = (args,)
try:
# get encoder
encoder = getattr(core, encoder_name + "_encoder")
# print(encoder, mode, args + extra)
return encoder(mode, *args + extra)
except AttributeError:
raise IOError("encoder %s not available" % encoder_name)
# --------------------------------------------------------------------
# Simple expression analyzer
def coerce_e(value):
return value if isinstance(value, _E) else _E(value)
class _E:
def __init__(self, data):
self.data = data
def __add__(self, other):
return _E((self.data, "__add__", coerce_e(other).data))
def __mul__(self, other):
return _E((self.data, "__mul__", coerce_e(other).data))
def _getscaleoffset(expr):
stub = ["stub"]
data = expr(_E(stub)).data
try:
(a, b, c) = data # simplified syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number)):
return c, 0.0
if (a is stub and b == "__add__" and isinstance(c, numbers.Number)):
return 1.0, c
except TypeError: pass
try:
((a, b, c), d, e) = data # full syntax
if (a is stub and b == "__mul__" and isinstance(c, numbers.Number) and
d == "__add__" and isinstance(e, numbers.Number)):
return c, e
except TypeError: pass
raise ValueError("illegal expression")
# --------------------------------------------------------------------
# Implementation wrapper
class Image:
"""
This class represents an image object. To create
:py:class:`~PIL.Image.Image` objects, use the appropriate factory
functions. There's hardly ever any reason to call the Image constructor
directly.
* :py:func:`~PIL.Image.open`
* :py:func:`~PIL.Image.new`
* :py:func:`~PIL.Image.frombytes`
"""
format = None
format_description = None
def __init__(self):
# FIXME: take "new" parameters / other image?
# FIXME: turn mode and size into delegating properties?
self.im = None
self.mode = ""
self.size = (0, 0)
self.palette = None
self.info = {}
self.category = NORMAL
self.readonly = 0
def _new(self, im):
new = Image()
new.im = im
new.mode = im.mode
new.size = im.size
new.palette = self.palette
if im.mode == "P" and not new.palette:
from PIL import ImagePalette
new.palette = ImagePalette.ImagePalette()
try:
new.info = self.info.copy()
except AttributeError:
# fallback (pre-1.5.2)
new.info = {}
for k, v in self.info:
new.info[k] = v
return new
_makeself = _new # compatibility
def _copy(self):
self.load()
self.im = self.im.copy()
self.readonly = 0
def _dump(self, file=None, format=None):
import tempfile, os
if not file:
f, file = tempfile.mkstemp(format or '')
os.close(f)
self.load()
if not format or format == "PPM":
self.im.save_ppm(file)
else:
if file.endswith(format):
file = file + "." + format
self.save(file, format)
return file
def __repr__(self):
return "<%s.%s image mode=%s size=%dx%d at 0x%X>" % (
self.__class__.__module__, self.__class__.__name__,
self.mode, self.size[0], self.size[1],
id(self)
)
def __getattr__(self, name):
if name == "__array_interface__":
# numpy array interface support
new = {}
shape, typestr = _conv_type_shape(self)
new['shape'] = shape
new['typestr'] = typestr
new['data'] = self.tobytes()
return new
raise AttributeError(name)
def tobytes(self, encoder_name="raw", *args):
"""
Return image as a bytes object
:param encoder_name: What encoder to use. The default is to
use the standard "raw" encoder.
:param args: Extra arguments to the encoder.
:rtype: A bytes object.
"""
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0]
if encoder_name == "raw" and args == ():
args = self.mode
self.load()
# unpack data
e = _getencoder(self.mode, encoder_name, args)
e.setimage(self.im)
bufsize = max(65536, self.size[0] * 4) # see RawEncode.c
data = []
while True:
l, s, d = e.encode(bufsize)
data.append(d)
if s:
break
if s < 0:
raise RuntimeError("encoder error %d in tobytes" % s)
return b"".join(data)
# Declare tostring as alias to tobytes
def tostring(self, *args, **kw):
warnings.warn(
'tostring() is deprecated. Please call tobytes() instead.',
DeprecationWarning,
stacklevel=2,
)
return self.tobytes(*args, **kw)
def tobitmap(self, name="image"):
"""
Returns the image converted to an X11 bitmap.
.. note:: This method only works for mode "1" images.
:param name: The name prefix to use for the bitmap variables.
:returns: A string containing an X11 bitmap.
:raises ValueError: If the mode is not "1"
"""
self.load()
if self.mode != "1":
raise ValueError("not a bitmap")
data = self.tobytes("xbm")
return b"".join([("#define %s_width %d\n" % (name, self.size[0])).encode('ascii'),
("#define %s_height %d\n"% (name, self.size[1])).encode('ascii'),
("static char %s_bits[] = {\n" % name).encode('ascii'), data, b"};"])
def frombytes(self, data, decoder_name="raw", *args):
"""
Loads this image with pixel data from a bytes object.
This method is similar to the :py:func:`~PIL.Image.frombytes` function,
but loads data into this image instead of creating a new image object.
"""
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0]
# default format
if decoder_name == "raw" and args == ():
args = self.mode
# unpack data
d = _getdecoder(self.mode, decoder_name, args)
d.setimage(self.im)
s = d.decode(data)
if s[0] >= 0:
raise ValueError("not enough image data")
if s[1] != 0:
raise ValueError("cannot decode image data")
def fromstring(self, *args, **kw):
"""Deprecated alias to frombytes.
.. deprecated:: 2.0
"""
warnings.warn('fromstring() is deprecated. Please call frombytes() instead.', DeprecationWarning)
return self.frombytes(*args, **kw)
def load(self):
"""
Allocates storage for the image and loads the pixel data. In
normal cases, you don't need to call this method, since the
Image class automatically loads an opened image when it is
accessed for the first time.
:returns: An image access object.
"""
if self.im and self.palette and self.palette.dirty:
# realize palette
self.im.putpalette(*self.palette.getdata())
self.palette.dirty = 0
self.palette.mode = "RGB"
self.palette.rawmode = None
if "transparency" in self.info:
if isinstance(self.info["transparency"], int):
self.im.putpalettealpha(self.info["transparency"], 0)
else:
self.im.putpalettealphas(self.info["transparency"])
self.palette.mode = "RGBA"
if self.im:
return self.im.pixel_access(self.readonly)
def verify(self):
"""
Verifies the contents of a file. For data read from a file, this
method attempts to determine if the file is broken, without
actually decoding the image data. If this method finds any
problems, it raises suitable exceptions. If you need to load
the image after using this method, you must reopen the image
file.
"""
pass
def convert(self, mode=None, matrix=None, dither=None,
palette=WEB, colors=256):
"""
Returns a converted copy of this image. For the "P" mode, this
method translates pixels through the palette. If mode is
omitted, a mode is chosen so that all information in the image
and the palette can be represented without a palette.
The current version supports all possible conversions between
"L", "RGB" and "CMYK." The **matrix** argument only supports "L"
and "RGB".
When translating a color image to black and white (mode "L"),
the library uses the ITU-R 601-2 luma transform::
L = R * 299/1000 + G * 587/1000 + B * 114/1000
The default method of converting a greyscale ("L") or "RGB"
image into a bilevel (mode "1") image uses Floyd-Steinberg
dither to approximate the original image luminosity levels. If
dither is NONE, all non-zero values are set to 255 (white). To
use other thresholds, use the :py:meth:`~PIL.Image.Image.point`
method.
:param mode: The requested mode.
:param matrix: An optional conversion matrix. If given, this
should be 4- or 16-tuple containing floating point values.
:param dither: Dithering method, used when converting from
mode "RGB" to "P" or from "RGB" or "L" to "1".
Available methods are NONE or FLOYDSTEINBERG (default).
:param palette: Palette to use when converting from mode "RGB"
to "P". Available palettes are WEB or ADAPTIVE.
:param colors: Number of colors to use for the ADAPTIVE palette.
Defaults to 256.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if not mode:
# determine default mode
if self.mode == "P":
self.load()
if self.palette:
mode = self.palette.mode
else:
mode = "RGB"
else:
return self.copy()
self.load()
if matrix:
# matrix conversion
if mode not in ("L", "RGB"):
raise ValueError("illegal conversion")
im = self.im.convert_matrix(mode, matrix)
return self._new(im)
if mode == "P" and palette == ADAPTIVE:
im = self.im.quantize(colors)
return self._new(im)
# colorspace conversion
if dither is None:
dither = FLOYDSTEINBERG
# Use transparent conversion to promote from transparent color to an alpha channel.
if self.mode in ("L", "RGB") and mode == "RGBA" and "transparency" in self.info:
return self._new(self.im.convert_transparent(mode, self.info['transparency']))
try:
im = self.im.convert(mode, dither)
except ValueError:
try:
# normalize source image and try again
im = self.im.convert(getmodebase(self.mode))
im = im.convert(mode, dither)
except KeyError:
raise ValueError("illegal conversion")
return self._new(im)
def quantize(self, colors=256, method=0, kmeans=0, palette=None):
# methods:
# 0 = median cut
# 1 = maximum coverage
# 2 = fast octree
# NOTE: this functionality will be moved to the extended
# quantizer interface in a later version of PIL.
self.load()
if palette:
# use palette from reference image
palette.load()
if palette.mode != "P":
raise ValueError("bad mode for palette image")
if self.mode != "RGB" and self.mode != "L":
raise ValueError(
"only RGB or L mode images can be quantized to a palette"
)
im = self.im.convert("P", 1, palette.im)
return self._makeself(im)
im = self.im.quantize(colors, method, kmeans)
return self._new(im)
def copy(self):
"""
Copies this image. Use this method if you wish to paste things
into an image, but still retain the original.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object.
"""
self.load()
im = self.im.copy()
return self._new(im)
def crop(self, box=None):
"""
Returns a rectangular region from this image. The box is a
4-tuple defining the left, upper, right, and lower pixel
coordinate.
This is a lazy operation. Changes to the source image may or
may not be reflected in the cropped image. To break the
connection, call the :py:meth:`~PIL.Image.Image.load` method on
the cropped copy.
:param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
:rtype: :py:class:`~PIL.Image.Image`
:returns: An :py:class:`~PIL.Image.Image` object.
"""
self.load()
if box is None:
return self.copy()
# lazy operation
return _ImageCrop(self, box)
def draft(self, mode, size):
"""
Configures the image file loader so it returns a version of the
image that as closely as possible matches the given mode and
size. For example, you can use this method to convert a color
JPEG to greyscale while loading it, or to extract a 128x192
version from a PCD file.
Note that this method modifies the :py:class:`~PIL.Image.Image` object
in place. If the image has already been loaded, this method has no
effect.
:param mode: The requested mode.
:param size: The requested size.
"""
pass
def _expand(self, xmargin, ymargin=None):
if ymargin is None:
ymargin = xmargin
self.load()
return self._new(self.im.expand(xmargin, ymargin, 0))
def filter(self, filter):
"""
Filters this image using the given filter. For a list of
available filters, see the :py:mod:`~PIL.ImageFilter` module.
:param filter: Filter kernel.
:returns: An :py:class:`~PIL.Image.Image` object. """
self.load()
if isinstance(filter, collections.Callable):
filter = filter()
if not hasattr(filter, "filter"):
raise TypeError("filter argument should be ImageFilter.Filter instance or class")
if self.im.bands == 1:
return self._new(filter.filter(self.im))
# fix to handle multiband images since _imaging doesn't
ims = []
for c in range(self.im.bands):
ims.append(self._new(filter.filter(self.im.getband(c))))
return merge(self.mode, ims)
def getbands(self):
"""
Returns a tuple containing the name of each band in this image.
For example, **getbands** on an RGB image returns ("R", "G", "B").
:returns: A tuple containing band names.
:rtype: tuple
"""
return ImageMode.getmode(self.mode).bands
def getbbox(self):
"""
Calculates the bounding box of the non-zero regions in the
image.
:returns: The bounding box is returned as a 4-tuple defining the
left, upper, right, and lower pixel coordinate. If the image
is completely empty, this method returns None.
"""
self.load()
return self.im.getbbox()
def getcolors(self, maxcolors=256):
"""
Returns a list of colors used in this image.
:param maxcolors: Maximum number of colors. If this number is
exceeded, this method returns None. The default limit is
256 colors.
:returns: An unsorted list of (count, pixel) values.
"""
self.load()
if self.mode in ("1", "L", "P"):
h = self.im.histogram()
out = []
for i in range(256):
if h[i]:
out.append((h[i], i))
if len(out) > maxcolors:
return None
return out
return self.im.getcolors(maxcolors)
def getdata(self, band = None):
"""
Returns the contents of this image as a sequence object
containing pixel values. The sequence object is flattened, so
that values for line one follow directly after the values of
line zero, and so on.
Note that the sequence object returned by this method is an
internal PIL data type, which only supports certain sequence
operations. To convert it to an ordinary sequence (e.g. for
printing), use **list(im.getdata())**.
:param band: What band to return. The default is to return
all bands. To return a single band, pass in the index
value (e.g. 0 to get the "R" band from an "RGB" image).
:returns: A sequence-like object.
"""
self.load()
if band is not None:
return self.im.getband(band)
return self.im # could be abused
def getextrema(self):
"""
Gets the the minimum and maximum pixel values for each band in
the image.
:returns: For a single-band image, a 2-tuple containing the
minimum and maximum pixel value. For a multi-band image,
a tuple containing one 2-tuple for each band.
"""
self.load()
if self.im.bands > 1:
extrema = []
for i in range(self.im.bands):
extrema.append(self.im.getband(i).getextrema())
return tuple(extrema)
return self.im.getextrema()
def getim(self):
"""
Returns a capsule that points to the internal image memory.
:returns: A capsule object.
"""
self.load()
return self.im.ptr
def getpalette(self):
"""
Returns the image palette as a list.
:returns: A list of color values [r, g, b, ...], or None if the
image has no palette.
"""
self.load()
try:
if bytes is str:
return [i8(c) for c in self.im.getpalette()]
else:
return list(self.im.getpalette())
except ValueError:
return None # no palette
def getpixel(self, xy):
"""
Returns the pixel value at a given position.
:param xy: The coordinate, given as (x, y).
:returns: The pixel value. If the image is a multi-layer image,
this method returns a tuple.
"""
self.load()
return self.im.getpixel(xy)
def getprojection(self):
"""
Get projection to x and y axes
:returns: Two sequences, indicating where there are non-zero
pixels along the X-axis and the Y-axis, respectively.
"""
self.load()
x, y = self.im.getprojection()
return [i8(c) for c in x], [i8(c) for c in y]
def histogram(self, mask=None, extrema=None):
"""
Returns a histogram for the image. The histogram is returned as
a list of pixel counts, one for each pixel value in the source
image. If the image has more than one band, the histograms for
all bands are concatenated (for example, the histogram for an
"RGB" image contains 768 values).
A bilevel image (mode "1") is treated as a greyscale ("L") image
by this method.
If a mask is provided, the method returns a histogram for those
parts of the image where the mask image is non-zero. The mask
image must have the same size as the image, and be either a
bi-level image (mode "1") or a greyscale image ("L").
:param mask: An optional mask.
:returns: A list containing pixel counts.
"""
self.load()
if mask:
mask.load()
return self.im.histogram((0, 0), mask.im)
if self.mode in ("I", "F"):
if extrema is None:
extrema = self.getextrema()
return self.im.histogram(extrema)
return self.im.histogram()
def offset(self, xoffset, yoffset=None):
"""
.. deprecated:: 2.0
.. note:: New code should use :py:func:`PIL.ImageChops.offset`.
Returns a copy of the image where the data has been offset by the given
distances. Data wraps around the edges. If **yoffset** is omitted, it
is assumed to be equal to **xoffset**.
:param xoffset: The horizontal distance.
:param yoffset: The vertical distance. If omitted, both
distances are set to the same value.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if warnings:
warnings.warn(
"'offset' is deprecated; use 'ImageChops.offset' instead",
DeprecationWarning, stacklevel=2
)
from PIL import ImageChops
return ImageChops.offset(self, xoffset, yoffset)
def paste(self, im, box=None, mask=None):
"""
Pastes another image into this image. The box argument is either
a 2-tuple giving the upper left corner, a 4-tuple defining the
left, upper, right, and lower pixel coordinate, or None (same as
(0, 0)). If a 4-tuple is given, the size of the pasted image
must match the size of the region.
If the modes don't match, the pasted image is converted to the mode of
this image (see the :py:meth:`~PIL.Image.Image.convert` method for
details).
Instead of an image, the source can be a integer or tuple
containing pixel values. The method then fills the region
with the given color. When creating RGB images, you can
also use color strings as supported by the ImageColor module.
If a mask is given, this method updates only the regions
indicated by the mask. You can use either "1", "L" or "RGBA"
images (in the latter case, the alpha band is used as mask).
Where the mask is 255, the given image is copied as is. Where
the mask is 0, the current value is preserved. Intermediate
values can be used for transparency effects.
Note that if you paste an "RGBA" image, the alpha band is
ignored. You can work around this by using the same image as
both source image and mask.
:param im: Source image or pixel value (integer or tuple).
:param box: An optional 4-tuple giving the region to paste into.
If a 2-tuple is used instead, it's treated as the upper left
corner. If omitted or None, the source is pasted into the
upper left corner.
If an image is given as the second argument and there is no
third, the box defaults to (0, 0), and the second argument
is interpreted as a mask image.
:param mask: An optional mask image.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if isImageType(box) and mask is None:
# abbreviated paste(im, mask) syntax
mask = box; box = None
if box is None:
# cover all of self
box = (0, 0) + self.size
if len(box) == 2:
# lower left corner given; get size from image or mask
if isImageType(im):
size = im.size
elif isImageType(mask):
size = mask.size
else:
# FIXME: use self.size here?
raise ValueError(
"cannot determine region size; use 4-item box"
)
box = box + (box[0]+size[0], box[1]+size[1])
if isStringType(im):
from PIL import ImageColor
im = ImageColor.getcolor(im, self.mode)
elif isImageType(im):
im.load()
if self.mode != im.mode:
if self.mode != "RGB" or im.mode not in ("RGBA", "RGBa"):
# should use an adapter for this!
im = im.convert(self.mode)
im = im.im
self.load()
if self.readonly:
self._copy()
if mask:
mask.load()
self.im.paste(im, box, mask.im)
else:
self.im.paste(im, box)
def point(self, lut, mode=None):
"""
Maps this image through a lookup table or function.
:param lut: A lookup table, containing 256 (or 65336 if
self.mode=="I" and mode == "L") values per band in the
image. A function can be used instead, it should take a
single argument. The function is called once for each
possible pixel value, and the resulting table is applied to
all bands of the image.
:param mode: Output mode (default is same as input). In the
current version, this can only be used if the source image
has mode "L" or "P", and the output has mode "1" or the
source image mode is "I" and the output mode is "L".
:returns: An :py:class:`~PIL.Image.Image` object.
"""
self.load()
if isinstance(lut, ImagePointHandler):
return lut.point(self)
if callable(lut):
# if it isn't a list, it should be a function
if self.mode in ("I", "I;16", "F"):
# check if the function can be used with point_transform
# UNDONE wiredfool -- I think this prevents us from ever doing
# a gamma function point transform on > 8bit images.
scale, offset = _getscaleoffset(lut)
return self._new(self.im.point_transform(scale, offset))
# for other modes, convert the function to a table
lut = [lut(i) for i in range(256)] * self.im.bands
if self.mode == "F":
# FIXME: _imaging returns a confusing error message for this case
raise ValueError("point operation not supported for this mode")
return self._new(self.im.point(lut, mode))
def putalpha(self, alpha):
"""
Adds or replaces the alpha layer in this image. If the image
does not have an alpha layer, it's converted to "LA" or "RGBA".
The new layer must be either "L" or "1".
:param alpha: The new alpha layer. This can either be an "L" or "1"
image having the same size as this image, or an integer or
other color value.
"""
self.load()
if self.readonly:
self._copy()
if self.mode not in ("LA", "RGBA"):
# attempt to promote self to a matching alpha mode
try:
mode = getmodebase(self.mode) + "A"
try:
self.im.setmode(mode)
except (AttributeError, ValueError):
# do things the hard way
im = self.im.convert(mode)
if im.mode not in ("LA", "RGBA"):
raise ValueError # sanity check
self.im = im
self.mode = self.im.mode
except (KeyError, ValueError):
raise ValueError("illegal image mode")
if self.mode == "LA":
band = 1
else:
band = 3
if isImageType(alpha):
# alpha layer
if alpha.mode not in ("1", "L"):
raise ValueError("illegal image mode")
alpha.load()
if alpha.mode == "1":
alpha = alpha.convert("L")
else:
# constant alpha
try:
self.im.fillband(band, alpha)
except (AttributeError, ValueError):
# do things the hard way
alpha = new("L", self.size, alpha)
else:
return
self.im.putband(alpha.im, band)
def putdata(self, data, scale=1.0, offset=0.0):
"""
Copies pixel data to this image. This method copies data from a
sequence object into the image, starting at the upper left
corner (0, 0), and continuing until either the image or the
sequence ends. The scale and offset values are used to adjust
the sequence values: **pixel = value*scale + offset**.
:param data: A sequence object.
:param scale: An optional scale value. The default is 1.0.
:param offset: An optional offset value. The default is 0.0.
"""
self.load()
if self.readonly:
self._copy()
self.im.putdata(data, scale, offset)
def putpalette(self, data, rawmode="RGB"):
"""
Attaches a palette to this image. The image must be a "P" or
"L" image, and the palette sequence must contain 768 integer
values, where each group of three values represent the red,
green, and blue values for the corresponding pixel
index. Instead of an integer sequence, you can use an 8-bit
string.
:param data: A palette sequence (either a list or a string).
"""
from PIL import ImagePalette
if self.mode not in ("L", "P"):
raise ValueError("illegal image mode")
self.load()
if isinstance(data, ImagePalette.ImagePalette):
palette = ImagePalette.raw(data.rawmode, data.palette)
else:
if not isinstance(data, bytes):
if bytes is str:
data = "".join(chr(x) for x in data)
else:
data = bytes(data)
palette = ImagePalette.raw(rawmode, data)
self.mode = "P"
self.palette = palette
self.palette.mode = "RGB"
self.load() # install new palette
def putpixel(self, xy, value):
"""
Modifies the pixel at the given position. The color is given as
a single numerical value for single-band images, and a tuple for
multi-band images.
Note that this method is relatively slow. For more extensive changes,
use :py:meth:`~PIL.Image.Image.paste` or the :py:mod:`~PIL.ImageDraw`
module instead.
See:
* :py:meth:`~PIL.Image.Image.paste`
* :py:meth:`~PIL.Image.Image.putdata`
* :py:mod:`~PIL.ImageDraw`
:param xy: The pixel coordinate, given as (x, y).
:param value: The pixel value.
"""
self.load()
if self.readonly:
self._copy()
return self.im.putpixel(xy, value)
def resize(self, size, resample=NEAREST):
"""
Returns a resized copy of this image.
:param size: The requested size in pixels, as a 2-tuple:
(width, height).
:param filter: An optional resampling filter. This can be
one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), :py:attr:`PIL.Image.BICUBIC` (cubic spline
interpolation in a 4x4 environment), or
:py:attr:`PIL.Image.ANTIALIAS` (a high-quality downsampling filter).
If omitted, or if the image has mode "1" or "P", it is
set :py:attr:`PIL.Image.NEAREST`.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if resample not in (NEAREST, BILINEAR, BICUBIC, ANTIALIAS):
raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"):
resample = NEAREST
if self.mode == 'RGBA':
return self.convert('RGBa').resize(size, resample).convert('RGBA')
if resample == ANTIALIAS:
# requires stretch support (imToolkit & PIL 1.1.3)
try:
im = self.im.stretch(size, resample)
except AttributeError:
raise ValueError("unsupported resampling filter")
else:
im = self.im.resize(size, resample)
return self._new(im)
def rotate(self, angle, resample=NEAREST, expand=0):
"""
Returns a rotated copy of this image. This method returns a
copy of this image, rotated the given number of degrees counter
clockwise around its centre.
:param angle: In degrees counter clockwise.
:param filter: An optional resampling filter. This can be
one of :py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), or :py:attr:`PIL.Image.BICUBIC`
(cubic spline interpolation in a 4x4 environment).
If omitted, or if the image has mode "1" or "P", it is
set :py:attr:`PIL.Image.NEAREST`.
:param expand: Optional expansion flag. If true, expands the output
image to make it large enough to hold the entire rotated image.
If false or omitted, make the output image the same size as the
input image.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if expand:
import math
angle = -angle * math.pi / 180
matrix = [
math.cos(angle), math.sin(angle), 0.0,
-math.sin(angle), math.cos(angle), 0.0
]
def transform(x, y, matrix=matrix):
(a, b, c, d, e, f) = matrix
return a*x + b*y + c, d*x + e*y + f
# calculate output size
w, h = self.size
xx = []
yy = []
for x, y in ((0, 0), (w, 0), (w, h), (0, h)):
x, y = transform(x, y)
xx.append(x)
yy.append(y)
w = int(math.ceil(max(xx)) - math.floor(min(xx)))
h = int(math.ceil(max(yy)) - math.floor(min(yy)))
# adjust center
x, y = transform(w / 2.0, h / 2.0)
matrix[2] = self.size[0] / 2.0 - x
matrix[5] = self.size[1] / 2.0 - y
return self.transform((w, h), AFFINE, matrix, resample)
if resample not in (NEAREST, BILINEAR, BICUBIC):
raise ValueError("unknown resampling filter")
self.load()
if self.mode in ("1", "P"):
resample = NEAREST
return self._new(self.im.rotate(angle, resample))
def save(self, fp, format=None, **params):
"""
Saves this image under the given filename. If no format is
specified, the format to use is determined from the filename
extension, if possible.
Keyword options can be used to provide additional instructions
to the writer. If a writer doesn't recognise an option, it is
silently ignored. The available options are described later in
this handbook.
You can use a file object instead of a filename. In this case,
you must always specify the format. The file object must
implement the **seek**, **tell**, and **write**
methods, and be opened in binary mode.
:param file: File name or file object.
:param format: Optional format override. If omitted, the
format to use is determined from the filename extension.
If a file object was used instead of a filename, this
parameter should always be used.
:param options: Extra parameters to the image writer.
:returns: None
:exception KeyError: If the output format could not be determined
from the file name. Use the format option to solve this.
:exception IOError: If the file could not be written. The file
may have been created, and may contain partial data.
"""
if isPath(fp):
filename = fp
else:
if hasattr(fp, "name") and isPath(fp.name):
filename = fp.name
else:
filename = ""
# may mutate self!
self.load()
self.encoderinfo = params
self.encoderconfig = ()
preinit()
ext = os.path.splitext(filename)[1].lower()
if not format:
try:
format = EXTENSION[ext]
except KeyError:
init()
try:
format = EXTENSION[ext]
except KeyError:
raise KeyError(ext) # unknown extension
try:
save_handler = SAVE[format.upper()]
except KeyError:
init()
save_handler = SAVE[format.upper()] # unknown format
if isPath(fp):
fp = builtins.open(fp, "wb")
close = 1
else:
close = 0
try:
save_handler(self, fp, filename)
finally:
# do what we can to clean up
if close:
fp.close()
def seek(self, frame):
"""
Seeks to the given frame in this sequence file. If you seek
beyond the end of the sequence, the method raises an
**EOFError** exception. When a sequence file is opened, the
library automatically seeks to frame 0.
Note that in the current version of the library, most sequence
formats only allows you to seek to the next frame.
See :py:meth:`~PIL.Image.Image.tell`.
:param frame: Frame number, starting at 0.
:exception EOFError: If the call attempts to seek beyond the end
of the sequence.
"""
# overridden by file handlers
if frame != 0:
raise EOFError
def show(self, title=None, command=None):
"""
Displays this image. This method is mainly intended for
debugging purposes.
On Unix platforms, this method saves the image to a temporary
PPM file, and calls the **xv** utility.
On Windows, it saves the image to a temporary BMP file, and uses
the standard BMP display utility to show it (usually Paint).
:param title: Optional title to use for the image window,
where possible.
:param command: command used to show the image
"""
_show(self, title=title, command=command)
def split(self):
"""
Split this image into individual bands. This method returns a
tuple of individual image bands from an image. For example,
splitting an "RGB" image creates three new images each
containing a copy of one of the original bands (red, green,
blue).
:returns: A tuple containing bands.
"""
self.load()
if self.im.bands == 1:
ims = [self.copy()]
else:
ims = []
for i in range(self.im.bands):
ims.append(self._new(self.im.getband(i)))
return tuple(ims)
def tell(self):
"""
Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`.
:returns: Frame number, starting with 0.
"""
return 0
def thumbnail(self, size, resample=NEAREST):
"""
Make this image into a thumbnail. This method modifies the
image to contain a thumbnail version of itself, no larger than
the given size. This method calculates an appropriate thumbnail
size to preserve the aspect of the image, calls the
:py:meth:`~PIL.Image.Image.draft` method to configure the file reader
(where applicable), and finally resizes the image.
Note that the bilinear and bicubic filters in the current
version of PIL are not well-suited for thumbnail generation.
You should use :py:attr:`PIL.Image.ANTIALIAS` unless speed is much more
important than quality.
Also note that this function modifies the :py:class:`~PIL.Image.Image`
object in place. If you need to use the full resolution image as well, apply
this method to a :py:meth:`~PIL.Image.Image.copy` of the original image.
:param size: Requested size.
:param resample: Optional resampling filter. This can be one
of :py:attr:`PIL.Image.NEAREST`, :py:attr:`PIL.Image.BILINEAR`,
:py:attr:`PIL.Image.BICUBIC`, or :py:attr:`PIL.Image.ANTIALIAS`
(best quality). If omitted, it defaults to
:py:attr:`PIL.Image.NEAREST` (this will be changed to ANTIALIAS in a
future version).
:returns: None
"""
# FIXME: the default resampling filter will be changed
# to ANTIALIAS in future versions
# preserve aspect ratio
x, y = self.size
if x > size[0]: y = int(max(y * size[0] / x, 1)); x = int(size[0])
if y > size[1]: x = int(max(x * size[1] / y, 1)); y = int(size[1])
size = x, y
if size == self.size:
return
self.draft(None, size)
self.load()
try:
im = self.resize(size, resample)
except ValueError:
if resample != ANTIALIAS:
raise
im = self.resize(size, NEAREST) # fallback
self.im = im.im
self.mode = im.mode
self.size = size
self.readonly = 0
# FIXME: the different tranform methods need further explanation
# instead of bloating the method docs, add a separate chapter.
def transform(self, size, method, data=None, resample=NEAREST, fill=1):
"""
Transforms this image. This method creates a new image with the
given size, and the same mode as the original, and copies data
to the new image using the given transform.
:param size: The output size.
:param method: The transformation method. This is one of
:py:attr:`PIL.Image.EXTENT` (cut out a rectangular subregion),
:py:attr:`PIL.Image.AFFINE` (affine transform),
:py:attr:`PIL.Image.PERSPECTIVE` (perspective transform),
:py:attr:`PIL.Image.QUAD` (map a quadrilateral to a rectangle), or
:py:attr:`PIL.Image.MESH` (map a number of source quadrilaterals
in one operation).
:param data: Extra data to the transformation method.
:param resample: Optional resampling filter. It can be one of
:py:attr:`PIL.Image.NEAREST` (use nearest neighbour),
:py:attr:`PIL.Image.BILINEAR` (linear interpolation in a 2x2
environment), or :py:attr:`PIL.Image.BICUBIC` (cubic spline
interpolation in a 4x4 environment). If omitted, or if the image
has mode "1" or "P", it is set to :py:attr:`PIL.Image.NEAREST`.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if self.mode == 'RGBA':
return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA')
if isinstance(method, ImageTransformHandler):
return method.transform(size, self, resample=resample, fill=fill)
if hasattr(method, "getdata"):
# compatibility w. old-style transform objects
method, data = method.getdata()
if data is None:
raise ValueError("missing method data")
im = new(self.mode, size, None)
if method == MESH:
# list of quads
for box, quad in data:
im.__transformer(box, self, QUAD, quad, resample, fill)
else:
im.__transformer((0, 0)+size, self, method, data, resample, fill)
return im
def __transformer(self, box, image, method, data,
resample=NEAREST, fill=1):
# FIXME: this should be turned into a lazy operation (?)
w = box[2]-box[0]
h = box[3]-box[1]
if method == AFFINE:
# change argument order to match implementation
data = (data[2], data[0], data[1],
data[5], data[3], data[4])
elif method == EXTENT:
# convert extent to an affine transform
x0, y0, x1, y1 = data
xs = float(x1 - x0) / w
ys = float(y1 - y0) / h
method = AFFINE
data = (x0 + xs/2, xs, 0, y0 + ys/2, 0, ys)
elif method == PERSPECTIVE:
# change argument order to match implementation
data = (data[2], data[0], data[1],
data[5], data[3], data[4],
data[6], data[7])
elif method == QUAD:
# quadrilateral warp. data specifies the four corners
# given as NW, SW, SE, and NE.
nw = data[0:2]; sw = data[2:4]; se = data[4:6]; ne = data[6:8]
x0, y0 = nw; As = 1.0 / w; At = 1.0 / h
data = (x0, (ne[0]-x0)*As, (sw[0]-x0)*At,
(se[0]-sw[0]-ne[0]+x0)*As*At,
y0, (ne[1]-y0)*As, (sw[1]-y0)*At,
(se[1]-sw[1]-ne[1]+y0)*As*At)
else:
raise ValueError("unknown transformation method")
if resample not in (NEAREST, BILINEAR, BICUBIC):
raise ValueError("unknown resampling filter")
image.load()
self.load()
if image.mode in ("1", "P"):
resample = NEAREST
self.im.transform2(box, image.im, method, data, resample, fill)
def transpose(self, method):
"""
Transpose image (flip or rotate in 90 degree steps)
:param method: One of :py:attr:`PIL.Image.FLIP_LEFT_RIGHT`,
:py:attr:`PIL.Image.FLIP_TOP_BOTTOM`, :py:attr:`PIL.Image.ROTATE_90`,
:py:attr:`PIL.Image.ROTATE_180`, or :py:attr:`PIL.Image.ROTATE_270`.
:returns: Returns a flipped or rotated copy of this image.
"""
self.load()
im = self.im.transpose(method)
return self._new(im)
# --------------------------------------------------------------------
# Lazy operations
class _ImageCrop(Image):
def __init__(self, im, box):
Image.__init__(self)
x0, y0, x1, y1 = box
if x1 < x0:
x1 = x0
if y1 < y0:
y1 = y0
self.mode = im.mode
self.size = x1-x0, y1-y0
self.__crop = x0, y0, x1, y1
self.im = im.im
def load(self):
# lazy evaluation!
if self.__crop:
self.im = self.im.crop(self.__crop)
self.__crop = None
if self.im:
return self.im.pixel_access(self.readonly)
# FIXME: future versions should optimize crop/paste
# sequences!
# --------------------------------------------------------------------
# Abstract handlers.
class ImagePointHandler:
# used as a mixin by point transforms (for use with im.point)
pass
class ImageTransformHandler:
# used as a mixin by geometry transforms (for use with im.transform)
pass
# --------------------------------------------------------------------
# Factories
#
# Debugging
def _wedge():
"Create greyscale wedge (for debugging only)"
return Image()._new(core.wedge("L"))
def new(mode, size, color=0):
"""
Creates a new image with the given mode and size.
:param mode: The mode to use for the new image.
:param size: A 2-tuple, containing (width, height) in pixels.
:param color: What color to use for the image. Default is black.
If given, this should be a single integer or floating point value
for single-band modes, and a tuple for multi-band modes (one value
per band). When creating RGB images, you can also use color
strings as supported by the ImageColor module. If the color is
None, the image is not initialised.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if color is None:
# don't initialize
return Image()._new(core.new(mode, size))
if isStringType(color):
# css3-style specifier
from PIL import ImageColor
color = ImageColor.getcolor(color, mode)
return Image()._new(core.fill(mode, size, color))
def frombytes(mode, size, data, decoder_name="raw", *args):
"""
Creates a copy of an image memory from pixel data in a buffer.
In its simplest form, this function takes three arguments
(mode, size, and unpacked pixel data).
You can also use any pixel decoder supported by PIL. For more
information on available decoders, see the section
**Writing Your Own File Decoder**.
Note that this function decodes pixel data only, not entire images.
If you have an entire image in a string, wrap it in a
:py:class:`~io.BytesIO` object, and use :py:func:`~PIL.Image.open` to load
it.
:param mode: The image mode.
:param size: The image size.
:param data: A byte buffer containing raw data for the given mode.
:param decoder_name: What decoder to use.
:param args: Additional parameters for the given decoder.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0]
if decoder_name == "raw" and args == ():
args = mode
im = new(mode, size)
im.frombytes(data, decoder_name, args)
return im
def fromstring(*args, **kw):
"""Deprecated alias to frombytes.
.. deprecated:: 2.0
"""
warnings.warn(
'fromstring() is deprecated. Please call frombytes() instead.',
DeprecationWarning,
stacklevel=2
)
return frombytes(*args, **kw)
def frombuffer(mode, size, data, decoder_name="raw", *args):
"""
Creates an image memory referencing pixel data in a byte buffer.
This function is similar to :py:func:`~PIL.Image.frombytes`, but uses data
in the byte buffer, where possible. This means that changes to the
original buffer object are reflected in this image). Not all modes can
share memory; supported modes include "L", "RGBX", "RGBA", and "CMYK".
Note that this function decodes pixel data only, not entire images.
If you have an entire image file in a string, wrap it in a
**BytesIO** object, and use :py:func:`~PIL.Image.open` to load it.
In the current version, the default parameters used for the "raw" decoder
differs from that used for :py:func:`~PIL.Image.fromstring`. This is a
bug, and will probably be fixed in a future release. The current release
issues a warning if you do this; to disable the warning, you should provide
the full set of parameters. See below for details.
:param mode: The image mode.
:param size: The image size.
:param data: A bytes or other buffer object containing raw
data for the given mode.
:param decoder_name: What decoder to use.
:param args: Additional parameters for the given decoder. For the
default encoder ("raw"), it's recommended that you provide the
full set of parameters::
frombuffer(mode, size, data, "raw", mode, 0, 1)
:returns: An :py:class:`~PIL.Image.Image` object.
.. versionadded:: 1.1.4
"""
"Load image from bytes or buffer"
# may pass tuple instead of argument list
if len(args) == 1 and isinstance(args[0], tuple):
args = args[0]
if decoder_name == "raw":
if args == ():
if warnings:
warnings.warn(
"the frombuffer defaults may change in a future release; "
"for portability, change the call to read:\n"
" frombuffer(mode, size, data, 'raw', mode, 0, 1)",
RuntimeWarning, stacklevel=2
)
args = mode, 0, -1 # may change to (mode, 0, 1) post-1.1.6
if args[0] in _MAPMODES:
im = new(mode, (1,1))
im = im._new(
core.map_buffer(data, size, decoder_name, None, 0, args)
)
im.readonly = 1
return im
return frombytes(mode, size, data, decoder_name, args)
def fromarray(obj, mode=None):
"""
Creates an image memory from an object exporting the array interface
(using the buffer protocol).
If obj is not contiguous, then the tobytes method is called
and :py:func:`~PIL.Image.frombuffer` is used.
:param obj: Object with array interface
:param mode: Mode to use (will be determined from type if None)
:returns: An image memory.
.. versionadded:: 1.1.6
"""
arr = obj.__array_interface__
shape = arr['shape']
ndim = len(shape)
try:
strides = arr['strides']
except KeyError:
strides = None
if mode is None:
try:
typekey = (1, 1) + shape[2:], arr['typestr']
mode, rawmode = _fromarray_typemap[typekey]
except KeyError:
# print typekey
raise TypeError("Cannot handle this data type")
else:
rawmode = mode
if mode in ["1", "L", "I", "P", "F"]:
ndmax = 2
elif mode == "RGB":
ndmax = 3
else:
ndmax = 4
if ndim > ndmax:
raise ValueError("Too many dimensions.")
size = shape[1], shape[0]
if strides is not None:
if hasattr(obj, 'tobytes'):
obj = obj.tobytes()
else:
obj = obj.tostring()
return frombuffer(mode, size, obj, "raw", rawmode, 0, 1)
_fromarray_typemap = {
# (shape, typestr) => mode, rawmode
# first two members of shape are set to one
# ((1, 1), "|b1"): ("1", "1"), # broken
((1, 1), "|u1"): ("L", "L"),
((1, 1), "|i1"): ("I", "I;8"),
((1, 1), "<i2"): ("I", "I;16"),
((1, 1), ">i2"): ("I", "I;16B"),
((1, 1), "<i4"): ("I", "I;32"),
((1, 1), ">i4"): ("I", "I;32B"),
((1, 1), "<f4"): ("F", "F;32F"),
((1, 1), ">f4"): ("F", "F;32BF"),
((1, 1), "<f8"): ("F", "F;64F"),
((1, 1), ">f8"): ("F", "F;64BF"),
((1, 1, 3), "|u1"): ("RGB", "RGB"),
((1, 1, 4), "|u1"): ("RGBA", "RGBA"),
}
# shortcuts
_fromarray_typemap[((1, 1), _ENDIAN + "i4")] = ("I", "I")
_fromarray_typemap[((1, 1), _ENDIAN + "f4")] = ("F", "F")
def open(fp, mode="r"):
"""
Opens and identifies the given image file.
This is a lazy operation; this function identifies the file, but the
actual image data is not read from the file until you try to process
the data (or call the :py:meth:`~PIL.Image.Image.load` method).
See :py:func:`~PIL.Image.new`.
:param file: A filename (string) or a file object. The file object
must implement :py:meth:`~file.read`, :py:meth:`~file.seek`, and
:py:meth:`~file.tell` methods, and be opened in binary mode.
:param mode: The mode. If given, this argument must be "r".
:returns: An :py:class:`~PIL.Image.Image` object.
:exception IOError: If the file cannot be found, or the image cannot be
opened and identified.
"""
if mode != "r":
raise ValueError("bad mode")
if isPath(fp):
filename = fp
fp = builtins.open(fp, "rb")
else:
filename = ""
prefix = fp.read(16)
preinit()
for i in ID:
try:
factory, accept = OPEN[i]
if not accept or accept(prefix):
fp.seek(0)
return factory(fp, filename)
except (SyntaxError, IndexError, TypeError):
#import traceback
#traceback.print_exc()
pass
if init():
for i in ID:
try:
factory, accept = OPEN[i]
if not accept or accept(prefix):
fp.seek(0)
return factory(fp, filename)
except (SyntaxError, IndexError, TypeError):
#import traceback
#traceback.print_exc()
pass
raise IOError("cannot identify image file")
#
# Image processing.
def alpha_composite(im1, im2):
"""
Alpha composite im2 over im1.
:param im1: The first image.
:param im2: The second image. Must have the same mode and size as
the first image.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
im1.load()
im2.load()
return im1._new(core.alpha_composite(im1.im, im2.im))
def blend(im1, im2, alpha):
"""
Creates a new image by interpolating between two input images, using
a constant alpha.::
out = image1 * (1.0 - alpha) + image2 * alpha
:param im1: The first image.
:param im2: The second image. Must have the same mode and size as
the first image.
:param alpha: The interpolation alpha factor. If alpha is 0.0, a
copy of the first image is returned. If alpha is 1.0, a copy of
the second image is returned. There are no restrictions on the
alpha value. If necessary, the result is clipped to fit into
the allowed output range.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
im1.load()
im2.load()
return im1._new(core.blend(im1.im, im2.im, alpha))
def composite(image1, image2, mask):
"""
Create composite image by blending images using a transparency mask.
:param image1: The first image.
:param image2: The second image. Must have the same mode and
size as the first image.
:param mask: A mask image. This image can can have mode
"1", "L", or "RGBA", and must have the same size as the
other two images.
"""
image = image2.copy()
image.paste(image1, None, mask)
return image
def eval(image, *args):
"""
Applies the function (which should take one argument) to each pixel
in the given image. If the image has more than one band, the same
function is applied to each band. Note that the function is
evaluated once for each possible pixel value, so you cannot use
random components or other generators.
:param image: The input image.
:param function: A function object, taking one integer argument.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
return image.point(args[0])
def merge(mode, bands):
"""
Merge a set of single band images into a new multiband image.
:param mode: The mode to use for the output image.
:param bands: A sequence containing one single-band image for
each band in the output image. All bands must have the
same size.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if getmodebands(mode) != len(bands) or "*" in mode:
raise ValueError("wrong number of bands")
for im in bands[1:]:
if im.mode != getmodetype(mode):
raise ValueError("mode mismatch")
if im.size != bands[0].size:
raise ValueError("size mismatch")
im = core.new(mode, bands[0].size)
for i in range(getmodebands(mode)):
bands[i].load()
im.putband(bands[i].im, i)
return bands[0]._new(im)
# --------------------------------------------------------------------
# Plugin registry
def register_open(id, factory, accept=None):
"""
Register an image file plugin. This function should not be used
in application code.
:param id: An image format identifier.
:param factory: An image file factory method.
:param accept: An optional function that can be used to quickly
reject images having another format.
"""
id = id.upper()
ID.append(id)
OPEN[id] = factory, accept
def register_mime(id, mimetype):
"""
Registers an image MIME type. This function should not be used
in application code.
:param id: An image format identifier.
:param mimetype: The image MIME type for this format.
"""
MIME[id.upper()] = mimetype
def register_save(id, driver):
"""
Registers an image save function. This function should not be
used in application code.
:param id: An image format identifier.
:param driver: A function to save images in this format.
"""
SAVE[id.upper()] = driver
def register_extension(id, extension):
"""
Registers an image extension. This function should not be
used in application code.
:param id: An image format identifier.
:param extension: An extension used for this format.
"""
EXTENSION[extension.lower()] = id.upper()
# --------------------------------------------------------------------
# Simple display support. User code may override this.
def _show(image, **options):
# override me, as necessary
_showxv(image, **options)
def _showxv(image, title=None, **options):
from PIL import ImageShow
ImageShow.show(image, title, **options)
| ./CrossVul/dataset_final_sorted/CWE-59/py/good_2084_1 |
crossvul-python_data_bad_2234_5 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import sys
import re
import os
import shlex
import yaml
import copy
import optparse
import operator
from ansible import errors
from ansible import __version__
from ansible.utils import template
from ansible.utils.display_functions import *
from ansible.utils.plugins import *
from ansible.callbacks import display
import ansible.constants as C
import ast
import time
import StringIO
import stat
import termios
import tty
import pipes
import random
import difflib
import warnings
import traceback
import getpass
import sys
import json
from vault import VaultLib
VERBOSITY=0
MAX_FILE_SIZE_FOR_DIFF=1*1024*1024
try:
import json
except ImportError:
import simplejson as json
try:
from hashlib import md5 as _md5
except ImportError:
from md5 import md5 as _md5
PASSLIB_AVAILABLE = False
try:
import passlib.hash
PASSLIB_AVAILABLE = True
except:
pass
try:
import builtin
except ImportError:
import __builtin__ as builtin
KEYCZAR_AVAILABLE=False
try:
try:
# some versions of pycrypto may not have this?
from Crypto.pct_warnings import PowmInsecureWarning
except ImportError:
PowmInsecureWarning = RuntimeWarning
with warnings.catch_warnings(record=True) as warning_handler:
warnings.simplefilter("error", PowmInsecureWarning)
try:
import keyczar.errors as key_errors
from keyczar.keys import AesKey
except PowmInsecureWarning:
system_warning(
"The version of gmp you have installed has a known issue regarding " + \
"timing vulnerabilities when used with pycrypto. " + \
"If possible, you should update it (ie. yum update gmp)."
)
warnings.resetwarnings()
warnings.simplefilter("ignore")
import keyczar.errors as key_errors
from keyczar.keys import AesKey
KEYCZAR_AVAILABLE=True
except ImportError:
pass
###############################################################
# Abstractions around keyczar
###############################################################
def key_for_hostname(hostname):
# fireball mode is an implementation of ansible firing up zeromq via SSH
# to use no persistent daemons or key management
if not KEYCZAR_AVAILABLE:
raise errors.AnsibleError("python-keyczar must be installed on the control machine to use accelerated modes")
key_path = os.path.expanduser(C.ACCELERATE_KEYS_DIR)
if not os.path.exists(key_path):
os.makedirs(key_path, mode=0700)
os.chmod(key_path, int(C.ACCELERATE_KEYS_DIR_PERMS, 8))
elif not os.path.isdir(key_path):
raise errors.AnsibleError('ACCELERATE_KEYS_DIR is not a directory.')
if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_DIR_PERMS, 8):
raise errors.AnsibleError('Incorrect permissions on the private key directory. Use `chmod 0%o %s` to correct this issue, and make sure any of the keys files contained within that directory are set to 0%o' % (int(C.ACCELERATE_KEYS_DIR_PERMS, 8), C.ACCELERATE_KEYS_DIR, int(C.ACCELERATE_KEYS_FILE_PERMS, 8)))
key_path = os.path.join(key_path, hostname)
# use new AES keys every 2 hours, which means fireball must not allow running for longer either
if not os.path.exists(key_path) or (time.time() - os.path.getmtime(key_path) > 60*60*2):
key = AesKey.Generate()
fd = os.open(key_path, os.O_WRONLY | os.O_CREAT, int(C.ACCELERATE_KEYS_FILE_PERMS, 8))
fh = os.fdopen(fd, 'w')
fh.write(str(key))
fh.close()
return key
else:
if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_FILE_PERMS, 8):
raise errors.AnsibleError('Incorrect permissions on the key file for this host. Use `chmod 0%o %s` to correct this issue.' % (int(C.ACCELERATE_KEYS_FILE_PERMS, 8), key_path))
fh = open(key_path)
key = AesKey.Read(fh.read())
fh.close()
return key
def encrypt(key, msg):
return key.Encrypt(msg)
def decrypt(key, msg):
try:
return key.Decrypt(msg)
except key_errors.InvalidSignatureError:
raise errors.AnsibleError("decryption failed")
###############################################################
# UTILITY FUNCTIONS FOR COMMAND LINE TOOLS
###############################################################
def err(msg):
''' print an error message to stderr '''
print >> sys.stderr, msg
def exit(msg, rc=1):
''' quit with an error to stdout and a failure code '''
err(msg)
sys.exit(rc)
def jsonify(result, format=False):
''' format JSON output (uncompressed or uncompressed) '''
if result is None:
return "{}"
result2 = result.copy()
for key, value in result2.items():
if type(value) is str:
result2[key] = value.decode('utf-8', 'ignore')
if format:
return json.dumps(result2, sort_keys=True, indent=4)
else:
return json.dumps(result2, sort_keys=True)
def write_tree_file(tree, hostname, buf):
''' write something into treedir/hostname '''
# TODO: might be nice to append playbook runs per host in a similar way
# in which case, we'd want append mode.
path = os.path.join(tree, hostname)
fd = open(path, "w+")
fd.write(buf)
fd.close()
def is_failed(result):
''' is a given JSON result a failed result? '''
return ((result.get('rc', 0) != 0) or (result.get('failed', False) in [ True, 'True', 'true']))
def is_changed(result):
''' is a given JSON result a changed result? '''
return (result.get('changed', False) in [ True, 'True', 'true'])
def check_conditional(conditional, basedir, inject, fail_on_undefined=False):
if conditional is None or conditional == '':
return True
if isinstance(conditional, list):
for x in conditional:
if not check_conditional(x, basedir, inject, fail_on_undefined=fail_on_undefined):
return False
return True
if not isinstance(conditional, basestring):
return conditional
conditional = conditional.replace("jinja2_compare ","")
# allow variable names
if conditional in inject and '-' not in str(inject[conditional]):
conditional = inject[conditional]
conditional = template.template(basedir, conditional, inject, fail_on_undefined=fail_on_undefined)
original = str(conditional).replace("jinja2_compare ","")
# a Jinja2 evaluation that results in something Python can eval!
presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional
conditional = template.template(basedir, presented, inject)
val = conditional.strip()
if val == presented:
# the templating failed, meaning most likely a
# variable was undefined. If we happened to be
# looking for an undefined variable, return True,
# otherwise fail
if "is undefined" in conditional:
return True
elif "is defined" in conditional:
return False
else:
raise errors.AnsibleError("error while evaluating conditional: %s" % original)
elif val == "True":
return True
elif val == "False":
return False
else:
raise errors.AnsibleError("unable to evaluate conditional: %s" % original)
def is_executable(path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def unfrackpath(path):
'''
returns a path that is free of symlinks, environment
variables, relative path traversals and symbols (~)
example:
'$HOME/../../var/mail' becomes '/var/spool/mail'
'''
return os.path.normpath(os.path.realpath(os.path.expandvars(os.path.expanduser(path))))
def prepare_writeable_dir(tree,mode=0777):
''' make sure a directory exists and is writeable '''
# modify the mode to ensure the owner at least
# has read/write access to this directory
mode |= 0700
# make sure the tree path is always expanded
# and normalized and free of symlinks
tree = unfrackpath(tree)
if not os.path.exists(tree):
try:
os.makedirs(tree, mode)
except (IOError, OSError), e:
raise errors.AnsibleError("Could not make dir %s: %s" % (tree, e))
if not os.access(tree, os.W_OK):
raise errors.AnsibleError("Cannot write to path %s" % tree)
return tree
def path_dwim(basedir, given):
'''
make relative paths work like folks expect.
'''
if given.startswith("/"):
return os.path.abspath(given)
elif given.startswith("~"):
return os.path.abspath(os.path.expanduser(given))
else:
if basedir is None:
basedir = "."
return os.path.abspath(os.path.join(basedir, given))
def path_dwim_relative(original, dirname, source, playbook_base, check=True):
''' find one file in a directory one level up in a dir named dirname relative to current '''
# (used by roles code)
basedir = os.path.dirname(original)
if os.path.islink(basedir):
basedir = unfrackpath(basedir)
template2 = os.path.join(basedir, dirname, source)
else:
template2 = os.path.join(basedir, '..', dirname, source)
source2 = path_dwim(basedir, template2)
if os.path.exists(source2):
return source2
obvious_local_path = path_dwim(playbook_base, source)
if os.path.exists(obvious_local_path):
return obvious_local_path
if check:
raise errors.AnsibleError("input file not found at %s or %s" % (source2, obvious_local_path))
return source2 # which does not exist
def json_loads(data):
''' parse a JSON string and return a data structure '''
return json.loads(data)
def _clean_data(orig_data):
''' remove template tags from a string '''
data = orig_data
if isinstance(orig_data, basestring):
for pattern,replacement in (('{{','{#'), ('}}','#}'), ('{%','{#'), ('%}','#}')):
data = data.replace(pattern, replacement)
return data
def _clean_data_struct(orig_data):
'''
walk a complex data structure, and use _clean_data() to
remove any template tags that may exist
'''
if isinstance(orig_data, dict):
data = orig_data.copy()
for key in data:
new_key = _clean_data_struct(key)
new_val = _clean_data_struct(data[key])
if key != new_key:
del data[key]
data[new_key] = new_val
elif isinstance(orig_data, list):
data = orig_data[:]
for i in range(0, len(data)):
data[i] = _clean_data_struct(data[i])
elif isinstance(orig_data, basestring):
data = _clean_data(orig_data)
else:
data = orig_data
return data
def parse_json(raw_data, from_remote=False):
''' this version for module return data only '''
orig_data = raw_data
# ignore stuff like tcgetattr spewage or other warnings
data = filter_leading_non_json_lines(raw_data)
try:
results = json.loads(data)
except:
# not JSON, but try "Baby JSON" which allows many of our modules to not
# require JSON and makes writing modules in bash much simpler
results = {}
try:
tokens = shlex.split(data)
except:
print "failed to parse json: "+ data
raise
for t in tokens:
if "=" not in t:
raise errors.AnsibleError("failed to parse: %s" % orig_data)
(key,value) = t.split("=", 1)
if key == 'changed' or 'failed':
if value.lower() in [ 'true', '1' ]:
value = True
elif value.lower() in [ 'false', '0' ]:
value = False
if key == 'rc':
value = int(value)
results[key] = value
if len(results.keys()) == 0:
return { "failed" : True, "parsed" : False, "msg" : orig_data }
if from_remote:
results = _clean_data_struct(results)
return results
def smush_braces(data):
''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed weird by key=value code '''
while '{{ ' in data:
data = data.replace('{{ ', '{{')
while ' }}' in data:
data = data.replace(' }}', '}}')
return data
def smush_ds(data):
# things like key={{ foo }} are not handled by shlex.split well, so preprocess any YAML we load
# so we do not have to call smush elsewhere
if type(data) == list:
return [ smush_ds(x) for x in data ]
elif type(data) == dict:
for (k,v) in data.items():
data[k] = smush_ds(v)
return data
elif isinstance(data, basestring):
return smush_braces(data)
else:
return data
def parse_yaml(data, path_hint=None):
''' convert a yaml string to a data structure. Also supports JSON, ssssssh!!!'''
stripped_data = data.lstrip()
loaded = None
if stripped_data.startswith("{") or stripped_data.startswith("["):
# since the line starts with { or [ we can infer this is a JSON document.
try:
loaded = json.loads(data)
except ValueError, ve:
if path_hint:
raise errors.AnsibleError(path_hint + ": " + str(ve))
else:
raise errors.AnsibleError(str(ve))
else:
# else this is pretty sure to be a YAML document
loaded = yaml.safe_load(data)
return smush_ds(loaded)
def process_common_errors(msg, probline, column):
replaced = probline.replace(" ","")
if ":{{" in replaced and "}}" in replaced:
msg = msg + """
This one looks easy to fix. YAML thought it was looking for the start of a
hash/dictionary and was confused to see a second "{". Most likely this was
meant to be an ansible template evaluation instead, so we have to give the
parser a small hint that we wanted a string instead. The solution here is to
just quote the entire value.
For instance, if the original line was:
app_path: {{ base_path }}/foo
It should be written as:
app_path: "{{ base_path }}/foo"
"""
return msg
elif len(probline) and len(probline) > 1 and len(probline) > column and probline[column] == ":" and probline.count(':') > 1:
msg = msg + """
This one looks easy to fix. There seems to be an extra unquoted colon in the line
and this is confusing the parser. It was only expecting to find one free
colon. The solution is just add some quotes around the colon, or quote the
entire line after the first colon.
For instance, if the original line was:
copy: src=file.txt dest=/path/filename:with_colon.txt
It can be written as:
copy: src=file.txt dest='/path/filename:with_colon.txt'
Or:
copy: 'src=file.txt dest=/path/filename:with_colon.txt'
"""
return msg
else:
parts = probline.split(":")
if len(parts) > 1:
middle = parts[1].strip()
match = False
unbalanced = False
if middle.startswith("'") and not middle.endswith("'"):
match = True
elif middle.startswith('"') and not middle.endswith('"'):
match = True
if len(middle) > 0 and middle[0] in [ '"', "'" ] and middle[-1] in [ '"', "'" ] and probline.count("'") > 2 or probline.count('"') > 2:
unbalanced = True
if match:
msg = msg + """
This one looks easy to fix. It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote. For instance:
when: "ok" in result.stdout
Could be written as:
when: '"ok" in result.stdout'
or equivalently:
when: "'ok' in result.stdout"
"""
return msg
if unbalanced:
msg = msg + """
We could be wrong, but this one looks like it might be an issue with
unbalanced quotes. If starting a value with a quote, make sure the
line ends with the same set of quotes. For instance this arbitrary
example:
foo: "bad" "wolf"
Could be written as:
foo: '"bad" "wolf"'
"""
return msg
return msg
def process_yaml_error(exc, data, path=None, show_content=True):
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
if show_content:
if mark.line -1 >= 0:
before_probline = data.split("\n")[mark.line-1]
else:
before_probline = ''
probline = data.split("\n")[mark.line]
arrow = " " * mark.column + "^"
msg = """Syntax Error while loading YAML script, %s
Note: The error may actually appear before this position: line %s, column %s
%s
%s
%s""" % (path, mark.line + 1, mark.column + 1, before_probline, probline, arrow)
unquoted_var = None
if '{{' in probline and '}}' in probline:
if '"{{' not in probline or "'{{" not in probline:
unquoted_var = True
msg = process_common_errors(msg, probline, mark.column)
if not unquoted_var:
msg = process_common_errors(msg, probline, mark.column)
else:
msg = msg + """
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
"""
msg = process_common_errors(msg, probline, mark.column)
else:
# most likely displaying a file with sensitive content,
# so don't show any of the actual lines of yaml just the
# line number itself
msg = """Syntax error while loading YAML script, %s
The error appears to have been on line %s, column %s, but may actually
be before there depending on the exact syntax problem.
""" % (path, mark.line + 1, mark.column + 1)
else:
# No problem markers means we have to throw a generic
# "stuff messed up" type message. Sry bud.
if path:
msg = "Could not parse YAML. Check over %s again." % path
else:
msg = "Could not parse YAML."
raise errors.AnsibleYAMLValidationFailed(msg)
def parse_yaml_from_file(path, vault_password=None):
''' convert a yaml file to a data structure '''
data = None
show_content = True
try:
data = open(path).read()
except IOError:
raise errors.AnsibleError("file could not read: %s" % path)
vault = VaultLib(password=vault_password)
if vault.is_encrypted(data):
data = vault.decrypt(data)
show_content = False
try:
return parse_yaml(data, path_hint=path)
except yaml.YAMLError, exc:
process_yaml_error(exc, data, path, show_content)
def parse_kv(args):
''' convert a string of key/value items to a dict '''
options = {}
if args is not None:
# attempting to split a unicode here does bad things
args = args.encode('utf-8')
try:
vargs = shlex.split(args, posix=True)
except ValueError, ve:
if 'no closing quotation' in str(ve).lower():
raise errors.AnsibleError("error parsing argument string, try quoting the entire line.")
else:
raise
vargs = [x.decode('utf-8') for x in vargs]
for x in vargs:
if "=" in x:
k, v = x.split("=",1)
options[k]=v
return options
def merge_hash(a, b):
''' recursively merges hash b into a
keys from b take precedence over keys from a '''
result = copy.deepcopy(a)
# next, iterate over b keys and values
for k, v in b.iteritems():
# if there's already such key in a
# and that key contains dict
if k in result and isinstance(result[k], dict):
# merge those dicts recursively
result[k] = merge_hash(a[k], v)
else:
# otherwise, just copy a value from b to a
result[k] = v
return result
def md5s(data):
''' Return MD5 hex digest of data. '''
digest = _md5()
try:
digest.update(data)
except UnicodeEncodeError:
digest.update(data.encode('utf-8'))
return digest.hexdigest()
def md5(filename):
''' Return MD5 hex digest of local file, or None if file is not present. '''
if not os.path.exists(filename):
return None
digest = _md5()
blocksize = 64 * 1024
try:
infile = open(filename, 'rb')
block = infile.read(blocksize)
while block:
digest.update(block)
block = infile.read(blocksize)
infile.close()
except IOError, e:
raise errors.AnsibleError("error while accessing the file %s, error was: %s" % (filename, e))
return digest.hexdigest()
def default(value, function):
''' syntactic sugar around lazy evaluation of defaults '''
if value is None:
return function()
return value
def _gitinfo():
''' returns a string containing git branch, commit id and commit date '''
result = None
repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git')
if os.path.exists(repo_path):
# Check if the .git is a file. If it is a file, it means that we are in a submodule structure.
if os.path.isfile(repo_path):
try:
gitdir = yaml.safe_load(open(repo_path)).get('gitdir')
# There is a posibility the .git file to have an absolute path.
if os.path.isabs(gitdir):
repo_path = gitdir
else:
repo_path = os.path.join(repo_path.split('.git')[0], gitdir)
except (IOError, AttributeError):
return ''
f = open(os.path.join(repo_path, "HEAD"))
branch = f.readline().split('/')[-1].rstrip("\n")
f.close()
branch_path = os.path.join(repo_path, "refs", "heads", branch)
if os.path.exists(branch_path):
f = open(branch_path)
commit = f.readline()[:10]
f.close()
date = time.localtime(os.stat(branch_path).st_mtime)
if time.daylight == 0:
offset = time.timezone
else:
offset = time.altzone
result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit,
time.strftime("%Y/%m/%d %H:%M:%S", date), offset / -36)
else:
result = ''
return result
def version(prog):
result = "{0} {1}".format(prog, __version__)
gitinfo = _gitinfo()
if gitinfo:
result = result + " {0}".format(gitinfo)
return result
def getch():
''' read in a single character '''
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def sanitize_output(str):
''' strips private info out of a string '''
private_keys = ['password', 'login_password']
filter_re = [
# filter out things like user:pass@foo/whatever
# and http://username:pass@wherever/foo
re.compile('^(?P<before>.*:)(?P<password>.*)(?P<after>\@.*)$'),
]
parts = str.split()
output = ''
for part in parts:
try:
(k,v) = part.split('=', 1)
if k in private_keys:
output += " %s=VALUE_HIDDEN" % k
else:
found = False
for filter in filter_re:
m = filter.match(v)
if m:
d = m.groupdict()
output += " %s=%s" % (k, d['before'] + "********" + d['after'])
found = True
break
if not found:
output += " %s" % part
except:
output += " %s" % part
return output.strip()
####################################################################
# option handling code for /usr/bin/ansible and ansible-playbook
# below this line
class SortedOptParser(optparse.OptionParser):
'''Optparser which sorts the options by opt before outputting --help'''
def format_help(self, formatter=None):
self.option_list.sort(key=operator.methodcaller('get_opt_string'))
return optparse.OptionParser.format_help(self, formatter=None)
def increment_debug(option, opt, value, parser):
global VERBOSITY
VERBOSITY += 1
def base_parser(constants=C, usage="", output_opts=False, runas_opts=False,
async_opts=False, connect_opts=False, subset_opts=False, check_opts=False, diff_opts=False):
''' create an options parser for any ansible script '''
parser = SortedOptParser(usage, version=version("%prog"))
parser.add_option('-v','--verbose', default=False, action="callback",
callback=increment_debug, help="verbose mode (-vvv for more, -vvvv to enable connection debugging)")
parser.add_option('-f','--forks', dest='forks', default=constants.DEFAULT_FORKS, type='int',
help="specify number of parallel processes to use (default=%s)" % constants.DEFAULT_FORKS)
parser.add_option('-i', '--inventory-file', dest='inventory',
help="specify inventory host file (default=%s)" % constants.DEFAULT_HOST_LIST,
default=constants.DEFAULT_HOST_LIST)
parser.add_option('-k', '--ask-pass', default=False, dest='ask_pass', action='store_true',
help='ask for SSH password')
parser.add_option('--private-key', default=C.DEFAULT_PRIVATE_KEY_FILE, dest='private_key_file',
help='use this file to authenticate the connection')
parser.add_option('-K', '--ask-sudo-pass', default=False, dest='ask_sudo_pass', action='store_true',
help='ask for sudo password')
parser.add_option('--ask-su-pass', default=False, dest='ask_su_pass', action='store_true',
help='ask for su password')
parser.add_option('--ask-vault-pass', default=False, dest='ask_vault_pass', action='store_true',
help='ask for vault password')
parser.add_option('--vault-password-file', default=None, dest='vault_password_file',
help="vault password file")
parser.add_option('--list-hosts', dest='listhosts', action='store_true',
help='outputs a list of matching hosts; does not execute anything else')
parser.add_option('-M', '--module-path', dest='module_path',
help="specify path(s) to module library (default=%s)" % constants.DEFAULT_MODULE_PATH,
default=None)
if subset_opts:
parser.add_option('-l', '--limit', default=constants.DEFAULT_SUBSET, dest='subset',
help='further limit selected hosts to an additional pattern')
parser.add_option('-T', '--timeout', default=constants.DEFAULT_TIMEOUT, type='int',
dest='timeout',
help="override the SSH timeout in seconds (default=%s)" % constants.DEFAULT_TIMEOUT)
if output_opts:
parser.add_option('-o', '--one-line', dest='one_line', action='store_true',
help='condense output')
parser.add_option('-t', '--tree', dest='tree', default=None,
help='log output to this directory')
if runas_opts:
parser.add_option("-s", "--sudo", default=constants.DEFAULT_SUDO, action="store_true",
dest='sudo', help="run operations with sudo (nopasswd)")
parser.add_option('-U', '--sudo-user', dest='sudo_user', default=None,
help='desired sudo user (default=root)') # Can't default to root because we need to detect when this option was given
parser.add_option('-u', '--user', default=constants.DEFAULT_REMOTE_USER,
dest='remote_user', help='connect as this user (default=%s)' % constants.DEFAULT_REMOTE_USER)
parser.add_option('-S', '--su', default=constants.DEFAULT_SU,
action='store_true', help='run operations with su')
parser.add_option('-R', '--su-user', help='run operations with su as this '
'user (default=%s)' % constants.DEFAULT_SU_USER)
if connect_opts:
parser.add_option('-c', '--connection', dest='connection',
default=C.DEFAULT_TRANSPORT,
help="connection type to use (default=%s)" % C.DEFAULT_TRANSPORT)
if async_opts:
parser.add_option('-P', '--poll', default=constants.DEFAULT_POLL_INTERVAL, type='int',
dest='poll_interval',
help="set the poll interval if using -B (default=%s)" % constants.DEFAULT_POLL_INTERVAL)
parser.add_option('-B', '--background', dest='seconds', type='int', default=0,
help='run asynchronously, failing after X seconds (default=N/A)')
if check_opts:
parser.add_option("-C", "--check", default=False, dest='check', action='store_true',
help="don't make any changes; instead, try to predict some of the changes that may occur"
)
if diff_opts:
parser.add_option("-D", "--diff", default=False, dest='diff', action='store_true',
help="when changing (small) files and templates, show the differences in those files; works great with --check"
)
return parser
def ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=False, confirm_vault=False, confirm_new=False):
vault_pass = None
new_vault_pass = None
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
if ask_vault_pass and confirm_vault:
vault_pass2 = getpass.getpass(prompt="Confirm Vault password: ")
if vault_pass != vault_pass2:
raise errors.AnsibleError("Passwords do not match")
if ask_new_vault_pass:
new_vault_pass = getpass.getpass(prompt="New Vault password: ")
if ask_new_vault_pass and confirm_new:
new_vault_pass2 = getpass.getpass(prompt="Confirm New Vault password: ")
if new_vault_pass != new_vault_pass2:
raise errors.AnsibleError("Passwords do not match")
# enforce no newline chars at the end of passwords
if vault_pass:
vault_pass = vault_pass.strip()
if new_vault_pass:
new_vault_pass = new_vault_pass.strip()
return vault_pass, new_vault_pass
def ask_passwords(ask_pass=False, ask_sudo_pass=False, ask_su_pass=False, ask_vault_pass=False):
sshpass = None
sudopass = None
su_pass = None
vault_pass = None
sudo_prompt = "sudo password: "
su_prompt = "su password: "
if ask_pass:
sshpass = getpass.getpass(prompt="SSH password: ")
sudo_prompt = "sudo password [defaults to SSH password]: "
if ask_sudo_pass:
sudopass = getpass.getpass(prompt=sudo_prompt)
if ask_pass and sudopass == '':
sudopass = sshpass
if ask_su_pass:
su_pass = getpass.getpass(prompt=su_prompt)
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
return (sshpass, sudopass, su_pass, vault_pass)
def do_encrypt(result, encrypt, salt_size=None, salt=None):
if PASSLIB_AVAILABLE:
try:
crypt = getattr(passlib.hash, encrypt)
except:
raise errors.AnsibleError("passlib does not support '%s' algorithm" % encrypt)
if salt_size:
result = crypt.encrypt(result, salt_size=salt_size)
elif salt:
result = crypt.encrypt(result, salt=salt)
else:
result = crypt.encrypt(result)
else:
raise errors.AnsibleError("passlib must be installed to encrypt vars_prompt values")
return result
def last_non_blank_line(buf):
all_lines = buf.splitlines()
all_lines.reverse()
for line in all_lines:
if (len(line) > 0):
return line
# shouldn't occur unless there's no output
return ""
def filter_leading_non_json_lines(buf):
'''
used to avoid random output from SSH at the top of JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
need to filter anything which starts not with '{', '[', ', '=' or is an empty line.
filter only leading lines since multiline JSON is valid.
'''
kv_regex = re.compile(r'.*\w+=\w+.*')
filtered_lines = StringIO.StringIO()
stop_filtering = False
for line in buf.splitlines():
if stop_filtering or kv_regex.match(line) or line.startswith('{') or line.startswith('['):
stop_filtering = True
filtered_lines.write(line + '\n')
return filtered_lines.getvalue()
def boolean(value):
val = str(value)
if val.lower() in [ "true", "t", "y", "1", "yes" ]:
return True
else:
return False
def make_sudo_cmd(sudo_user, executable, cmd):
"""
helper function for connection plugins to create sudo commands
"""
# Rather than detect if sudo wants a password this time, -k makes
# sudo always ask for a password if one is required.
# Passing a quoted compound command to sudo (or sudo -s)
# directly doesn't work, so we shellquote it with pipes.quote()
# and pass the quoted string to the user's shell. We loop reading
# output until we see the randomly-generated sudo prompt set with
# the -p option.
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = '[sudo via ansible, key=%s] password: ' % randbits
success_key = 'SUDO-SUCCESS-%s' % randbits
sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % (
C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_FLAGS,
prompt, sudo_user, executable or '$SHELL', pipes.quote('echo %s; %s' % (success_key, cmd)))
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
def make_su_cmd(su_user, executable, cmd):
"""
Helper function for connection plugins to create direct su commands
"""
# TODO: work on this function
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = 'assword: '
success_key = 'SUDO-SUCCESS-%s' % randbits
sudocmd = '%s %s %s %s -c %s' % (
C.DEFAULT_SU_EXE, C.DEFAULT_SU_FLAGS, su_user, executable or '$SHELL',
pipes.quote('echo %s; %s' % (success_key, cmd))
)
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
_TO_UNICODE_TYPES = (unicode, type(None))
def to_unicode(value):
if isinstance(value, _TO_UNICODE_TYPES):
return value
return value.decode("utf-8")
def get_diff(diff):
# called by --diff usage in playbook and runner via callbacks
# include names in diffs 'before' and 'after' and do diff -U 10
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ret = []
if 'dst_binary' in diff:
ret.append("diff skipped: destination file appears to be binary\n")
if 'src_binary' in diff:
ret.append("diff skipped: source file appears to be binary\n")
if 'dst_larger' in diff:
ret.append("diff skipped: destination file size is greater than %d\n" % diff['dst_larger'])
if 'src_larger' in diff:
ret.append("diff skipped: source file size is greater than %d\n" % diff['src_larger'])
if 'before' in diff and 'after' in diff:
if 'before_header' in diff:
before_header = "before: %s" % diff['before_header']
else:
before_header = 'before'
if 'after_header' in diff:
after_header = "after: %s" % diff['after_header']
else:
after_header = 'after'
differ = difflib.unified_diff(to_unicode(diff['before']).splitlines(True), to_unicode(diff['after']).splitlines(True), before_header, after_header, '', '', 10)
for line in list(differ):
ret.append(line)
return u"".join(ret)
except UnicodeDecodeError:
return ">> the files are different, but the diff library cannot compare unicode strings"
def is_list_of_strings(items):
for x in items:
if not isinstance(x, basestring):
return False
return True
def list_union(a, b):
result = []
for x in a:
if x not in result:
result.append(x)
for x in b:
if x not in result:
result.append(x)
return result
def list_intersection(a, b):
result = []
for x in a:
if x in b and x not in result:
result.append(x)
return result
def safe_eval(expr, locals={}, include_exceptions=False):
'''
this is intended for allowing things like:
with_items: a_list_variable
where Jinja2 would return a string
but we do not want to allow it to call functions (outside of Jinja2, where
the env is constrained)
Based on:
http://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe
'''
# this is the whitelist of AST nodes we are going to
# allow in the evaluation. Any node type other than
# those listed here will raise an exception in our custom
# visitor class defined below.
SAFE_NODES = set(
(
ast.Add,
ast.BinOp,
ast.Call,
ast.Compare,
ast.Dict,
ast.Div,
ast.Expression,
ast.List,
ast.Load,
ast.Mult,
ast.Num,
ast.Name,
ast.Str,
ast.Sub,
ast.Tuple,
ast.UnaryOp,
)
)
# AST node types were expanded after 2.6
if not sys.version.startswith('2.6'):
SAFE_NODES.union(
set(
(ast.Set,)
)
)
filter_list = []
for filter in filter_loader.all():
filter_list.extend(filter.filters().keys())
CALL_WHITELIST = C.DEFAULT_CALLABLE_WHITELIST + filter_list
class CleansingNodeVisitor(ast.NodeVisitor):
def generic_visit(self, node, inside_call=False):
if type(node) not in SAFE_NODES:
raise Exception("invalid expression (%s)" % expr)
elif isinstance(node, ast.Call):
inside_call = True
elif isinstance(node, ast.Name) and inside_call:
if hasattr(builtin, node.id) and node.id not in CALL_WHITELIST:
raise Exception("invalid function: %s" % node.id)
# iterate over all child nodes
for child_node in ast.iter_child_nodes(node):
self.generic_visit(child_node, inside_call)
if not isinstance(expr, basestring):
# already templated to a datastructure, perhaps?
if include_exceptions:
return (expr, None)
return expr
cnv = CleansingNodeVisitor()
try:
parsed_tree = ast.parse(expr, mode='eval')
cnv.visit(parsed_tree)
compiled = compile(parsed_tree, expr, 'eval')
result = eval(compiled, {}, locals)
if include_exceptions:
return (result, None)
else:
return result
except SyntaxError, e:
# special handling for syntax errors, we just return
# the expression string back as-is
if include_exceptions:
return (expr, None)
return expr
except Exception, e:
if include_exceptions:
return (expr, e)
return expr
def listify_lookup_plugin_terms(terms, basedir, inject):
if isinstance(terms, basestring):
# someone did:
# with_items: alist
# OR
# with_items: {{ alist }}
stripped = terms.strip()
if not (stripped.startswith('{') or stripped.startswith('[')) and not stripped.startswith("/") and not stripped.startswith('set(['):
# if not already a list, get ready to evaluate with Jinja2
# not sure why the "/" is in above code :)
try:
new_terms = template.template(basedir, "{{ %s }}" % terms, inject)
if isinstance(new_terms, basestring) and "{{" in new_terms:
pass
else:
terms = new_terms
except:
pass
if '{' in terms or '[' in terms:
# Jinja2 already evaluated a variable to a list.
# Jinja2-ified list needs to be converted back to a real type
# TODO: something a bit less heavy than eval
return safe_eval(terms)
if isinstance(terms, basestring):
terms = [ terms ]
return terms
def combine_vars(a, b):
if C.DEFAULT_HASH_BEHAVIOUR == "merge":
return merge_hash(a, b)
else:
return dict(a.items() + b.items())
def random_password(length=20, chars=C.DEFAULT_PASSWORD_CHARS):
'''Return a random password string of length containing only chars.'''
password = []
while len(password) < length:
new_char = os.urandom(1)
if new_char in chars:
password.append(new_char)
return ''.join(password)
def before_comment(msg):
''' what's the part of a string before a comment? '''
msg = msg.replace("\#","**NOT_A_COMMENT**")
msg = msg.split("#")[0]
msg = msg.replace("**NOT_A_COMMENT**","#")
return msg
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_2234_5 |
crossvul-python_data_bad_2234_1 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import multiprocessing
import signal
import os
import pwd
import Queue
import random
import traceback
import tempfile
import time
import collections
import socket
import base64
import sys
import pipes
import jinja2
import subprocess
import getpass
import ansible.constants as C
import ansible.inventory
from ansible import utils
from ansible.utils import template
from ansible.utils import check_conditional
from ansible.utils import string_functions
from ansible import errors
from ansible import module_common
import poller
import connection
from return_data import ReturnData
from ansible.callbacks import DefaultRunnerCallbacks, vv
from ansible.module_common import ModuleReplacer
module_replacer = ModuleReplacer(strip_comments=False)
HAS_ATFORK=True
try:
from Crypto.Random import atfork
except ImportError:
HAS_ATFORK=False
multiprocessing_runner = None
OUTPUT_LOCKFILE = tempfile.TemporaryFile()
PROCESS_LOCKFILE = tempfile.TemporaryFile()
################################################
def _executor_hook(job_queue, result_queue, new_stdin):
# attempt workaround of https://github.com/newsapps/beeswithmachineguns/issues/17
# this function also not present in CentOS 6
if HAS_ATFORK:
atfork()
signal.signal(signal.SIGINT, signal.SIG_IGN)
while not job_queue.empty():
try:
host = job_queue.get(block=False)
return_data = multiprocessing_runner._executor(host, new_stdin)
result_queue.put(return_data)
except Queue.Empty:
pass
except:
traceback.print_exc()
class HostVars(dict):
''' A special view of vars_cache that adds values from the inventory when needed. '''
def __init__(self, vars_cache, inventory, vault_password=None):
self.vars_cache = vars_cache
self.inventory = inventory
self.lookup = dict()
self.update(vars_cache)
self.vault_password = vault_password
def __getitem__(self, host):
if host not in self.lookup:
result = self.inventory.get_variables(host, vault_password=self.vault_password).copy()
result.update(self.vars_cache.get(host, {}))
self.lookup[host] = result
return self.lookup[host]
class Runner(object):
''' core API interface to ansible '''
# see bin/ansible for how this is used...
def __init__(self,
host_list=C.DEFAULT_HOST_LIST, # ex: /etc/ansible/hosts, legacy usage
module_path=None, # ex: /usr/share/ansible
module_name=C.DEFAULT_MODULE_NAME, # ex: copy
module_args=C.DEFAULT_MODULE_ARGS, # ex: "src=/tmp/a dest=/tmp/b"
forks=C.DEFAULT_FORKS, # parallelism level
timeout=C.DEFAULT_TIMEOUT, # SSH timeout
pattern=C.DEFAULT_PATTERN, # which hosts? ex: 'all', 'acme.example.org'
remote_user=C.DEFAULT_REMOTE_USER, # ex: 'username'
remote_pass=C.DEFAULT_REMOTE_PASS, # ex: 'password123' or None if using key
remote_port=None, # if SSH on different ports
private_key_file=C.DEFAULT_PRIVATE_KEY_FILE, # if not using keys/passwords
sudo_pass=C.DEFAULT_SUDO_PASS, # ex: 'password123' or None
background=0, # async poll every X seconds, else 0 for non-async
basedir=None, # directory of playbook, if applicable
setup_cache=None, # used to share fact data w/ other tasks
vars_cache=None, # used to store variables about hosts
transport=C.DEFAULT_TRANSPORT, # 'ssh', 'paramiko', 'local'
conditional='True', # run only if this fact expression evals to true
callbacks=None, # used for output
sudo=False, # whether to run sudo or not
sudo_user=C.DEFAULT_SUDO_USER, # ex: 'root'
module_vars=None, # a playbooks internals thing
default_vars=None, # ditto
is_playbook=False, # running from playbook or not?
inventory=None, # reference to Inventory object
subset=None, # subset pattern
check=False, # don't make any changes, just try to probe for potential changes
diff=False, # whether to show diffs for template files that change
environment=None, # environment variables (as dict) to use inside the command
complex_args=None, # structured data in addition to module_args, must be a dict
error_on_undefined_vars=C.DEFAULT_UNDEFINED_VAR_BEHAVIOR, # ex. False
accelerate=False, # use accelerated connection
accelerate_ipv6=False, # accelerated connection w/ IPv6
accelerate_port=None, # port to use with accelerated connection
su=False, # Are we running our command via su?
su_user=None, # User to su to when running command, ex: 'root'
su_pass=C.DEFAULT_SU_PASS,
vault_pass=None,
run_hosts=None, # an optional list of pre-calculated hosts to run on
no_log=False, # option to enable/disable logging for a given task
):
# used to lock multiprocess inputs and outputs at various levels
self.output_lockfile = OUTPUT_LOCKFILE
self.process_lockfile = PROCESS_LOCKFILE
if not complex_args:
complex_args = {}
# storage & defaults
self.check = check
self.diff = diff
self.setup_cache = utils.default(setup_cache, lambda: collections.defaultdict(dict))
self.vars_cache = utils.default(vars_cache, lambda: collections.defaultdict(dict))
self.basedir = utils.default(basedir, lambda: os.getcwd())
self.callbacks = utils.default(callbacks, lambda: DefaultRunnerCallbacks())
self.generated_jid = str(random.randint(0, 999999999999))
self.transport = transport
self.inventory = utils.default(inventory, lambda: ansible.inventory.Inventory(host_list))
self.module_vars = utils.default(module_vars, lambda: {})
self.default_vars = utils.default(default_vars, lambda: {})
self.always_run = None
self.connector = connection.Connection(self)
self.conditional = conditional
self.module_name = module_name
self.forks = int(forks)
self.pattern = pattern
self.module_args = module_args
self.timeout = timeout
self.remote_user = remote_user
self.remote_pass = remote_pass
self.remote_port = remote_port
self.private_key_file = private_key_file
self.background = background
self.sudo = sudo
self.sudo_user_var = sudo_user
self.sudo_user = None
self.sudo_pass = sudo_pass
self.is_playbook = is_playbook
self.environment = environment
self.complex_args = complex_args
self.error_on_undefined_vars = error_on_undefined_vars
self.accelerate = accelerate
self.accelerate_port = accelerate_port
self.accelerate_ipv6 = accelerate_ipv6
self.callbacks.runner = self
self.su = su
self.su_user_var = su_user
self.su_user = None
self.su_pass = su_pass
self.vault_pass = vault_pass
self.no_log = no_log
if self.transport == 'smart':
# if the transport is 'smart' see if SSH can support ControlPersist if not use paramiko
# 'smart' is the default since 1.2.1/1.3
cmd = subprocess.Popen(['ssh','-o','ControlPersist'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = cmd.communicate()
if "Bad configuration option" in err:
self.transport = "paramiko"
else:
self.transport = "ssh"
# save the original transport, in case it gets
# changed later via options like accelerate
self.original_transport = self.transport
# misc housekeeping
if subset and self.inventory._subset is None:
# don't override subset when passed from playbook
self.inventory.subset(subset)
# If we get a pre-built list of hosts to run on, from say a playbook, use them.
# Also where we will store the hosts to run on once discovered
self.run_hosts = run_hosts
if self.transport == 'local':
self.remote_user = pwd.getpwuid(os.geteuid())[0]
if module_path is not None:
for i in module_path.split(os.pathsep):
utils.plugins.module_finder.add_directory(i)
utils.plugins.push_basedir(self.basedir)
# ensure we are using unique tmp paths
random.seed()
# *****************************************************
def _complex_args_hack(self, complex_args, module_args):
"""
ansible-playbook both allows specifying key=value string arguments and complex arguments
however not all modules use our python common module system and cannot
access these. An example might be a Bash module. This hack allows users to still pass "args"
as a hash of simple scalars to those arguments and is short term. We could technically
just feed JSON to the module, but that makes it hard on Bash consumers. The way this is implemented
it does mean values in 'args' have LOWER priority than those on the key=value line, allowing
args to provide yet another way to have pluggable defaults.
"""
if complex_args is None:
return module_args
if not isinstance(complex_args, dict):
raise errors.AnsibleError("complex arguments are not a dictionary: %s" % complex_args)
for (k,v) in complex_args.iteritems():
if isinstance(v, basestring):
module_args = "%s=%s %s" % (k, pipes.quote(v), module_args)
return module_args
# *****************************************************
def _transfer_str(self, conn, tmp, name, data):
''' transfer string to remote file '''
if type(data) == dict:
data = utils.jsonify(data)
afd, afile = tempfile.mkstemp()
afo = os.fdopen(afd, 'w')
try:
if not isinstance(data, unicode):
#ensure the data is valid UTF-8
data.decode('utf-8')
else:
data = data.encode('utf-8')
afo.write(data)
except:
raise errors.AnsibleError("failure encoding into utf-8")
afo.flush()
afo.close()
remote = os.path.join(tmp, name)
try:
conn.put_file(afile, remote)
finally:
os.unlink(afile)
return remote
# *****************************************************
def _compute_environment_string(self, inject=None):
''' what environment variables to use when running the command? '''
default_environment = dict(
LANG = C.DEFAULT_MODULE_LANG,
LC_CTYPE = C.DEFAULT_MODULE_LANG,
)
if self.environment:
enviro = template.template(self.basedir, self.environment, inject, convert_bare=True)
enviro = utils.safe_eval(enviro)
if type(enviro) != dict:
raise errors.AnsibleError("environment must be a dictionary, received %s" % enviro)
default_environment.update(enviro)
result = ""
for (k,v) in default_environment.iteritems():
result = "%s=%s %s" % (k, pipes.quote(unicode(v)), result)
return result
# *****************************************************
def _compute_delegate(self, host, password, remote_inject):
""" Build a dictionary of all attributes for the delegate host """
delegate = {}
# allow delegated host to be templated
delegate['host'] = template.template(self.basedir, host,
remote_inject, fail_on_undefined=True)
delegate['inject'] = remote_inject.copy()
# set any interpreters
interpreters = []
for i in delegate['inject']:
if i.startswith("ansible_") and i.endswith("_interpreter"):
interpreters.append(i)
for i in interpreters:
del delegate['inject'][i]
port = C.DEFAULT_REMOTE_PORT
this_host = delegate['host']
# get the vars for the delegate by it's name
try:
this_info = delegate['inject']['hostvars'][this_host]
except:
# make sure the inject is empty for non-inventory hosts
this_info = {}
# get the real ssh_address for the delegate
# and allow ansible_ssh_host to be templated
delegate['ssh_host'] = template.template(self.basedir,
this_info.get('ansible_ssh_host', this_host),
this_info, fail_on_undefined=True)
delegate['port'] = this_info.get('ansible_ssh_port', port)
delegate['user'] = self._compute_delegate_user(this_host, delegate['inject'])
delegate['pass'] = this_info.get('ansible_ssh_pass', password)
delegate['private_key_file'] = this_info.get('ansible_ssh_private_key_file',
self.private_key_file)
delegate['transport'] = this_info.get('ansible_connection', self.transport)
delegate['sudo_pass'] = this_info.get('ansible_sudo_pass', self.sudo_pass)
# Last chance to get private_key_file from global variables.
# this is usefull if delegated host is not defined in the inventory
if delegate['private_key_file'] is None:
delegate['private_key_file'] = remote_inject.get(
'ansible_ssh_private_key_file', None)
if delegate['private_key_file'] is not None:
delegate['private_key_file'] = os.path.expanduser(delegate['private_key_file'])
for i in this_info:
if i.startswith("ansible_") and i.endswith("_interpreter"):
delegate['inject'][i] = this_info[i]
return delegate
def _compute_delegate_user(self, host, inject):
""" Caculate the remote user based on an order of preference """
# inventory > playbook > original_host
actual_user = inject.get('ansible_ssh_user', self.remote_user)
thisuser = None
if host in inject['hostvars']:
if inject['hostvars'][host].get('ansible_ssh_user'):
# user for delegate host in inventory
thisuser = inject['hostvars'][host].get('ansible_ssh_user')
if thisuser is None and self.remote_user:
# user defined by play/runner
thisuser = self.remote_user
if thisuser is not None:
actual_user = thisuser
else:
# fallback to the inventory user of the play host
#actual_user = inject.get('ansible_ssh_user', actual_user)
actual_user = inject.get('ansible_ssh_user', self.remote_user)
return actual_user
# *****************************************************
def _execute_module(self, conn, tmp, module_name, args,
async_jid=None, async_module=None, async_limit=None, inject=None, persist_files=False, complex_args=None, delete_remote_tmp=True):
''' transfer and run a module along with its arguments on the remote side'''
# hack to support fireball mode
if module_name == 'fireball':
args = "%s password=%s" % (args, base64.b64encode(str(utils.key_for_hostname(conn.host))))
if 'port' not in args:
args += " port=%s" % C.ZEROMQ_PORT
(
module_style,
shebang,
module_data
) = self._configure_module(conn, module_name, args, inject, complex_args)
# a remote tmp path may be necessary and not already created
if self._late_needs_tmp_path(conn, tmp, module_style):
tmp = self._make_tmp_path(conn)
remote_module_path = os.path.join(tmp, module_name)
if (module_style != 'new'
or async_jid is not None
or not conn.has_pipelining
or not C.ANSIBLE_SSH_PIPELINING
or C.DEFAULT_KEEP_REMOTE_FILES
or self.su):
self._transfer_str(conn, tmp, module_name, module_data)
environment_string = self._compute_environment_string(inject)
if "tmp" in tmp and ((self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root')):
# deal with possible umask issues once sudo'ed to other user
cmd_chmod = "chmod a+r %s" % remote_module_path
self._low_level_exec_command(conn, cmd_chmod, tmp, sudoable=False)
cmd = ""
in_data = None
if module_style != 'new':
if 'CHECKMODE=True' in args:
# if module isn't using AnsibleModuleCommon infrastructure we can't be certain it knows how to
# do --check mode, so to be safe we will not run it.
return ReturnData(conn=conn, result=dict(skipped=True, msg="cannot yet run check mode against old-style modules"))
elif 'NO_LOG' in args:
return ReturnData(conn=conn, result=dict(skipped=True, msg="cannot use no_log: with old-style modules"))
args = template.template(self.basedir, args, inject)
# decide whether we need to transfer JSON or key=value
argsfile = None
if module_style == 'non_native_want_json':
if complex_args:
complex_args.update(utils.parse_kv(args))
argsfile = self._transfer_str(conn, tmp, 'arguments', utils.jsonify(complex_args))
else:
argsfile = self._transfer_str(conn, tmp, 'arguments', utils.jsonify(utils.parse_kv(args)))
else:
argsfile = self._transfer_str(conn, tmp, 'arguments', args)
if (self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root'):
# deal with possible umask issues once sudo'ed to other user
cmd_args_chmod = "chmod a+r %s" % argsfile
self._low_level_exec_command(conn, cmd_args_chmod, tmp, sudoable=False)
if async_jid is None:
cmd = "%s %s" % (remote_module_path, argsfile)
else:
cmd = " ".join([str(x) for x in [remote_module_path, async_jid, async_limit, async_module, argsfile]])
else:
if async_jid is None:
if conn.has_pipelining and C.ANSIBLE_SSH_PIPELINING and not C.DEFAULT_KEEP_REMOTE_FILES and not self.su:
in_data = module_data
else:
cmd = "%s" % (remote_module_path)
else:
cmd = " ".join([str(x) for x in [remote_module_path, async_jid, async_limit, async_module]])
if not shebang:
raise errors.AnsibleError("module is missing interpreter line")
cmd = " ".join([environment_string.strip(), shebang.replace("#!","").strip(), cmd])
cmd = cmd.strip()
if "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if not self.sudo or self.su or self.sudo_user == 'root' or self.su_user == 'root':
# not sudoing or sudoing to root, so can cleanup files in the same step
cmd = cmd + "; rm -rf %s >/dev/null 2>&1" % tmp
sudoable = True
if module_name == "accelerate":
# always run the accelerate module as the user
# specified in the play, not the sudo_user
sudoable = False
if self.su:
res = self._low_level_exec_command(conn, cmd, tmp, su=True, in_data=in_data)
else:
res = self._low_level_exec_command(conn, cmd, tmp, sudoable=sudoable, in_data=in_data)
if "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if (self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root'):
# not sudoing to root, so maybe can't delete files as that other user
# have to clean up temp files as original user in a second step
cmd2 = "rm -rf %s >/dev/null 2>&1" % tmp
self._low_level_exec_command(conn, cmd2, tmp, sudoable=False)
data = utils.parse_json(res['stdout'], from_remote=True)
if 'parsed' in data and data['parsed'] == False:
data['msg'] += res['stderr']
return ReturnData(conn=conn, result=data)
# *****************************************************
def _executor(self, host, new_stdin):
''' handler for multiprocessing library '''
try:
fileno = sys.stdin.fileno()
except ValueError:
fileno = None
try:
self._new_stdin = new_stdin
if not new_stdin and fileno is not None:
try:
self._new_stdin = os.fdopen(os.dup(fileno))
except OSError, e:
# couldn't dupe stdin, most likely because it's
# not a valid file descriptor, so we just rely on
# using the one that was passed in
pass
exec_rc = self._executor_internal(host, new_stdin)
if type(exec_rc) != ReturnData:
raise Exception("unexpected return type: %s" % type(exec_rc))
# redundant, right?
if not exec_rc.comm_ok:
self.callbacks.on_unreachable(host, exec_rc.result)
return exec_rc
except errors.AnsibleError, ae:
msg = str(ae)
self.callbacks.on_unreachable(host, msg)
return ReturnData(host=host, comm_ok=False, result=dict(failed=True, msg=msg))
except Exception:
msg = traceback.format_exc()
self.callbacks.on_unreachable(host, msg)
return ReturnData(host=host, comm_ok=False, result=dict(failed=True, msg=msg))
# *****************************************************
def _executor_internal(self, host, new_stdin):
''' executes any module one or more times '''
host_variables = self.inventory.get_variables(host, vault_password=self.vault_pass)
host_connection = host_variables.get('ansible_connection', self.transport)
if host_connection in [ 'paramiko', 'ssh', 'accelerate' ]:
port = host_variables.get('ansible_ssh_port', self.remote_port)
if port is None:
port = C.DEFAULT_REMOTE_PORT
else:
# fireball, local, etc
port = self.remote_port
# merge the VARS and SETUP caches for this host
combined_cache = self.setup_cache.copy()
combined_cache.setdefault(host, {}).update(self.vars_cache.get(host, {}))
hostvars = HostVars(combined_cache, self.inventory, vault_password=self.vault_pass)
# use combined_cache and host_variables to template the module_vars
# we update the inject variables with the data we're about to template
# since some of the variables we'll be replacing may be contained there too
module_vars_inject = utils.combine_vars(host_variables, combined_cache.get(host, {}))
module_vars_inject = utils.combine_vars(self.module_vars, module_vars_inject)
module_vars = template.template(self.basedir, self.module_vars, module_vars_inject)
inject = {}
inject = utils.combine_vars(inject, self.default_vars)
inject = utils.combine_vars(inject, host_variables)
inject = utils.combine_vars(inject, module_vars)
inject = utils.combine_vars(inject, combined_cache.get(host, {}))
inject.setdefault('ansible_ssh_user', self.remote_user)
inject['hostvars'] = hostvars
inject['group_names'] = host_variables.get('group_names', [])
inject['groups'] = self.inventory.groups_list()
inject['vars'] = self.module_vars
inject['defaults'] = self.default_vars
inject['environment'] = self.environment
inject['playbook_dir'] = self.basedir
if self.inventory.basedir() is not None:
inject['inventory_dir'] = self.inventory.basedir()
if self.inventory.src() is not None:
inject['inventory_file'] = self.inventory.src()
# allow with_foo to work in playbooks...
items = None
items_plugin = self.module_vars.get('items_lookup_plugin', None)
if items_plugin is not None and items_plugin in utils.plugins.lookup_loader:
basedir = self.basedir
if '_original_file' in inject:
basedir = os.path.dirname(inject['_original_file'])
filesdir = os.path.join(basedir, '..', 'files')
if os.path.exists(filesdir):
basedir = filesdir
items_terms = self.module_vars.get('items_lookup_terms', '')
items_terms = template.template(basedir, items_terms, inject)
items = utils.plugins.lookup_loader.get(items_plugin, runner=self, basedir=basedir).run(items_terms, inject=inject)
if type(items) != list:
raise errors.AnsibleError("lookup plugins have to return a list: %r" % items)
if len(items) and utils.is_list_of_strings(items) and self.module_name in [ 'apt', 'yum', 'pkgng' ]:
# hack for apt, yum, and pkgng so that with_items maps back into a single module call
use_these_items = []
for x in items:
inject['item'] = x
if not self.conditional or utils.check_conditional(self.conditional, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
use_these_items.append(x)
inject['item'] = ",".join(use_these_items)
items = None
# logic to replace complex args if possible
complex_args = self.complex_args
# logic to decide how to run things depends on whether with_items is used
if items is None:
if isinstance(complex_args, basestring):
complex_args = template.template(self.basedir, complex_args, inject, convert_bare=True)
complex_args = utils.safe_eval(complex_args)
if type(complex_args) != dict:
raise errors.AnsibleError("args must be a dictionary, received %s" % complex_args)
return self._executor_internal_inner(host, self.module_name, self.module_args, inject, port, complex_args=complex_args)
elif len(items) > 0:
# executing using with_items, so make multiple calls
# TODO: refactor
if self.background > 0:
raise errors.AnsibleError("lookup plugins (with_*) cannot be used with async tasks")
all_comm_ok = True
all_changed = False
all_failed = False
results = []
for x in items:
# use a fresh inject for each item
this_inject = inject.copy()
this_inject['item'] = x
# TODO: this idiom should be replaced with an up-conversion to a Jinja2 template evaluation
if isinstance(self.complex_args, basestring):
complex_args = template.template(self.basedir, self.complex_args, this_inject, convert_bare=True)
complex_args = utils.safe_eval(complex_args)
if type(complex_args) != dict:
raise errors.AnsibleError("args must be a dictionary, received %s" % complex_args)
result = self._executor_internal_inner(
host,
self.module_name,
self.module_args,
this_inject,
port,
complex_args=complex_args
)
results.append(result.result)
if result.comm_ok == False:
all_comm_ok = False
all_failed = True
break
for x in results:
if x.get('changed') == True:
all_changed = True
if (x.get('failed') == True) or ('failed_when_result' in x and [x['failed_when_result']] or [('rc' in x) and (x['rc'] != 0)])[0]:
all_failed = True
break
msg = 'All items completed'
if all_failed:
msg = "One or more items failed."
rd_result = dict(failed=all_failed, changed=all_changed, results=results, msg=msg)
if not all_failed:
del rd_result['failed']
return ReturnData(host=host, comm_ok=all_comm_ok, result=rd_result)
else:
self.callbacks.on_skipped(host, None)
return ReturnData(host=host, comm_ok=True, result=dict(changed=False, skipped=True))
# *****************************************************
def _executor_internal_inner(self, host, module_name, module_args, inject, port, is_chained=False, complex_args=None):
''' decides how to invoke a module '''
# late processing of parameterized sudo_user (with_items,..)
if self.sudo_user_var is not None:
self.sudo_user = template.template(self.basedir, self.sudo_user_var, inject)
if self.su_user_var is not None:
self.su_user = template.template(self.basedir, self.su_user_var, inject)
# allow module args to work as a dictionary
# though it is usually a string
new_args = ""
if type(module_args) == dict:
for (k,v) in module_args.iteritems():
new_args = new_args + "%s='%s' " % (k,v)
module_args = new_args
# module_name may be dynamic (but cannot contain {{ ansible_ssh_user }})
module_name = template.template(self.basedir, module_name, inject)
if module_name in utils.plugins.action_loader:
if self.background != 0:
raise errors.AnsibleError("async mode is not supported with the %s module" % module_name)
handler = utils.plugins.action_loader.get(module_name, self)
elif self.background == 0:
handler = utils.plugins.action_loader.get('normal', self)
else:
handler = utils.plugins.action_loader.get('async', self)
if type(self.conditional) != list:
self.conditional = [ self.conditional ]
for cond in self.conditional:
if not utils.check_conditional(cond, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
result = utils.jsonify(dict(changed=False, skipped=True))
self.callbacks.on_skipped(host, inject.get('item',None))
return ReturnData(host=host, result=result)
if getattr(handler, 'setup', None) is not None:
handler.setup(module_name, inject)
conn = None
actual_host = inject.get('ansible_ssh_host', host)
# allow ansible_ssh_host to be templated
actual_host = template.template(self.basedir, actual_host, inject, fail_on_undefined=True)
actual_port = port
actual_user = inject.get('ansible_ssh_user', self.remote_user)
actual_pass = inject.get('ansible_ssh_pass', self.remote_pass)
actual_transport = inject.get('ansible_connection', self.transport)
actual_private_key_file = inject.get('ansible_ssh_private_key_file', self.private_key_file)
actual_private_key_file = template.template(self.basedir, actual_private_key_file, inject, fail_on_undefined=True)
self.sudo = utils.boolean(inject.get('ansible_sudo', self.sudo))
self.sudo_user = inject.get('ansible_sudo_user', self.sudo_user)
self.sudo_pass = inject.get('ansible_sudo_pass', self.sudo_pass)
self.su = inject.get('ansible_su', self.su)
self.su_pass = inject.get('ansible_su_pass', self.su_pass)
# select default root user in case self.sudo requested
# but no user specified; happens e.g. in host vars when
# just ansible_sudo=True is specified
if self.sudo and self.sudo_user is None:
self.sudo_user = 'root'
if actual_private_key_file is not None:
actual_private_key_file = os.path.expanduser(actual_private_key_file)
if self.accelerate and actual_transport != 'local':
#Fix to get the inventory name of the host to accelerate plugin
if inject.get('ansible_ssh_host', None):
self.accelerate_inventory_host = host
else:
self.accelerate_inventory_host = None
# if we're using accelerated mode, force the
# transport to accelerate
actual_transport = "accelerate"
if not self.accelerate_port:
self.accelerate_port = C.ACCELERATE_PORT
if actual_transport in [ 'paramiko', 'ssh', 'accelerate' ]:
actual_port = inject.get('ansible_ssh_port', port)
# the delegated host may have different SSH port configured, etc
# and we need to transfer those, and only those, variables
delegate_to = inject.get('delegate_to', None)
if delegate_to is not None:
delegate = self._compute_delegate(delegate_to, actual_pass, inject)
actual_transport = delegate['transport']
actual_host = delegate['ssh_host']
actual_port = delegate['port']
actual_user = delegate['user']
actual_pass = delegate['pass']
actual_private_key_file = delegate['private_key_file']
self.sudo_pass = delegate['sudo_pass']
inject = delegate['inject']
# user/pass may still contain variables at this stage
actual_user = template.template(self.basedir, actual_user, inject)
actual_pass = template.template(self.basedir, actual_pass, inject)
self.sudo_pass = template.template(self.basedir, self.sudo_pass, inject)
# make actual_user available as __magic__ ansible_ssh_user variable
inject['ansible_ssh_user'] = actual_user
try:
if actual_transport == 'accelerate':
# for accelerate, we stuff both ports into a single
# variable so that we don't have to mangle other function
# calls just to accomodate this one case
actual_port = [actual_port, self.accelerate_port]
elif actual_port is not None:
actual_port = int(template.template(self.basedir, actual_port, inject))
except ValueError, e:
result = dict(failed=True, msg="FAILED: Configured port \"%s\" is not a valid port, expected integer" % actual_port)
return ReturnData(host=host, comm_ok=False, result=result)
try:
conn = self.connector.connect(actual_host, actual_port, actual_user, actual_pass, actual_transport, actual_private_key_file)
if delegate_to or host != actual_host:
conn.delegate = host
except errors.AnsibleConnectionFailed, e:
result = dict(failed=True, msg="FAILED: %s" % str(e))
return ReturnData(host=host, comm_ok=False, result=result)
tmp = ''
# action plugins may DECLARE via TRANSFERS_FILES = True that they need a remote tmp path working dir
if self._early_needs_tmp_path(module_name, handler):
tmp = self._make_tmp_path(conn)
# render module_args and complex_args templates
try:
module_args = template.template(self.basedir, module_args, inject, fail_on_undefined=self.error_on_undefined_vars)
complex_args = template.template(self.basedir, complex_args, inject, fail_on_undefined=self.error_on_undefined_vars)
except jinja2.exceptions.UndefinedError, e:
raise errors.AnsibleUndefinedVariable("One or more undefined variables: %s" % str(e))
result = handler.run(conn, tmp, module_name, module_args, inject, complex_args)
# Code for do until feature
until = self.module_vars.get('until', None)
if until is not None and result.comm_ok:
inject[self.module_vars.get('register')] = result.result
cond = template.template(self.basedir, until, inject, expand_lists=False)
if not utils.check_conditional(cond, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
retries = self.module_vars.get('retries')
delay = self.module_vars.get('delay')
for x in range(1, int(retries) + 1):
# template the delay, cast to float and sleep
delay = template.template(self.basedir, delay, inject, expand_lists=False)
delay = float(delay)
time.sleep(delay)
tmp = ''
if self._early_needs_tmp_path(module_name, handler):
tmp = self._make_tmp_path(conn)
result = handler.run(conn, tmp, module_name, module_args, inject, complex_args)
result.result['attempts'] = x
vv("Result from run %i is: %s" % (x, result.result))
inject[self.module_vars.get('register')] = result.result
cond = template.template(self.basedir, until, inject, expand_lists=False)
if utils.check_conditional(cond, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
break
if result.result['attempts'] == retries and not utils.check_conditional(cond, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
result.result['failed'] = True
result.result['msg'] = "Task failed as maximum retries was encountered"
else:
result.result['attempts'] = 0
conn.close()
if not result.comm_ok:
# connection or parsing errors...
self.callbacks.on_unreachable(host, result.result)
else:
data = result.result
# https://github.com/ansible/ansible/issues/4958
if hasattr(sys.stdout, "isatty"):
if "stdout" in data and sys.stdout.isatty():
if not string_functions.isprintable(data['stdout']):
data['stdout'] = ''
if 'item' in inject:
result.result['item'] = inject['item']
result.result['invocation'] = dict(
module_args=module_args,
module_name=module_name
)
changed_when = self.module_vars.get('changed_when')
failed_when = self.module_vars.get('failed_when')
if (changed_when is not None or failed_when is not None) and self.background == 0:
register = self.module_vars.get('register')
if register is not None:
if 'stdout' in data:
data['stdout_lines'] = data['stdout'].splitlines()
inject[register] = data
# only run the final checks if the async_status has finished,
# or if we're not running an async_status check at all
if (module_name == 'async_status' and "finished" in data) or module_name != 'async_status':
if changed_when is not None and 'skipped' not in data:
data['changed'] = utils.check_conditional(changed_when, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars)
if failed_when is not None and 'skipped' not in data:
data['failed_when_result'] = data['failed'] = utils.check_conditional(failed_when, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars)
if is_chained:
# no callbacks
return result
if 'skipped' in data:
self.callbacks.on_skipped(host, inject.get('item',None))
elif not result.is_successful():
ignore_errors = self.module_vars.get('ignore_errors', False)
self.callbacks.on_failed(host, data, ignore_errors)
else:
if self.diff:
self.callbacks.on_file_diff(conn.host, result.diff)
self.callbacks.on_ok(host, data)
return result
def _early_needs_tmp_path(self, module_name, handler):
''' detect if a tmp path should be created before the handler is called '''
if module_name in utils.plugins.action_loader:
return getattr(handler, 'TRANSFERS_FILES', False)
# other modules never need tmp path at early stage
return False
def _late_needs_tmp_path(self, conn, tmp, module_style):
if "tmp" in tmp:
# tmp has already been created
return False
if not conn.has_pipelining or not C.ANSIBLE_SSH_PIPELINING or C.DEFAULT_KEEP_REMOTE_FILES or self.su:
# tmp is necessary to store module source code
return True
if not conn.has_pipelining:
# tmp is necessary to store the module source code
# or we want to keep the files on the target system
return True
if module_style != "new":
# even when conn has pipelining, old style modules need tmp to store arguments
return True
return False
# *****************************************************
def _low_level_exec_command(self, conn, cmd, tmp, sudoable=False,
executable=None, su=False, in_data=None):
''' execute a command string over SSH, return the output '''
if executable is None:
executable = C.DEFAULT_EXECUTABLE
sudo_user = self.sudo_user
su_user = self.su_user
# compare connection user to (su|sudo)_user and disable if the same
if hasattr(conn, 'user'):
if (not su and conn.user == sudo_user) or (su and conn.user == su_user):
sudoable = False
su = False
else:
# assume connection type is local if no user attribute
this_user = getpass.getuser()
if (not su and this_user == sudo_user) or (su and this_user == su_user):
sudoable = False
su = False
if su:
rc, stdin, stdout, stderr = conn.exec_command(cmd,
tmp,
su=su,
su_user=su_user,
executable=executable,
in_data=in_data)
else:
rc, stdin, stdout, stderr = conn.exec_command(cmd,
tmp,
sudo_user,
sudoable=sudoable,
executable=executable,
in_data=in_data)
if type(stdout) not in [ str, unicode ]:
out = ''.join(stdout.readlines())
else:
out = stdout
if type(stderr) not in [ str, unicode ]:
err = ''.join(stderr.readlines())
else:
err = stderr
if rc is not None:
return dict(rc=rc, stdout=out, stderr=err)
else:
return dict(stdout=out, stderr=err)
# *****************************************************
def _remote_md5(self, conn, tmp, path):
''' takes a remote md5sum without requiring python, and returns 1 if no file '''
path = pipes.quote(path)
# The following test needs to be SH-compliant. BASH-isms will
# not work if /bin/sh points to a non-BASH shell.
test = "rc=0; [ -r \"%s\" ] || rc=2; [ -f \"%s\" ] || rc=1; [ -d \"%s\" ] && echo 3 && exit 0" % ((path,) * 3)
md5s = [
"(/usr/bin/md5sum %s 2>/dev/null)" % path, # Linux
"(/sbin/md5sum -q %s 2>/dev/null)" % path, # ?
"(/usr/bin/digest -a md5 %s 2>/dev/null)" % path, # Solaris 10+
"(/sbin/md5 -q %s 2>/dev/null)" % path, # Freebsd
"(/usr/bin/md5 -n %s 2>/dev/null)" % path, # Netbsd
"(/bin/md5 -q %s 2>/dev/null)" % path, # Openbsd
"(/usr/bin/csum -h MD5 %s 2>/dev/null)" % path, # AIX
"(/bin/csum -h MD5 %s 2>/dev/null)" % path # AIX also
]
cmd = " || ".join(md5s)
cmd = "%s; %s || (echo \"${rc} %s\")" % (test, cmd, path)
data = self._low_level_exec_command(conn, cmd, tmp, sudoable=True)
data2 = utils.last_non_blank_line(data['stdout'])
try:
if data2 == '':
# this may happen if the connection to the remote server
# failed, so just return "INVALIDMD5SUM" to avoid errors
return "INVALIDMD5SUM"
else:
return data2.split()[0]
except IndexError:
sys.stderr.write("warning: md5sum command failed unusually, please report this to the list so it can be fixed\n")
sys.stderr.write("command: %s\n" % md5s)
sys.stderr.write("----\n")
sys.stderr.write("output: %s\n" % data)
sys.stderr.write("----\n")
# this will signal that it changed and allow things to keep going
return "INVALIDMD5SUM"
# *****************************************************
def _make_tmp_path(self, conn):
''' make and return a temporary path on a remote box '''
basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48))
basetmp = os.path.join(C.DEFAULT_REMOTE_TMP, basefile)
if (self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root') and basetmp.startswith('$HOME'):
basetmp = os.path.join('/tmp', basefile)
cmd = 'mkdir -p %s' % basetmp
if self.remote_user != 'root' or ((self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root')):
cmd += ' && chmod a+rx %s' % basetmp
cmd += ' && echo %s' % basetmp
result = self._low_level_exec_command(conn, cmd, None, sudoable=False)
# error handling on this seems a little aggressive?
if result['rc'] != 0:
if result['rc'] == 5:
output = 'Authentication failure.'
elif result['rc'] == 255 and self.transport in ['ssh']:
if utils.VERBOSITY > 3:
output = 'SSH encountered an unknown error. The output was:\n%s' % (result['stdout']+result['stderr'])
else:
output = 'SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue'
else:
output = 'Authentication or permission failure. In some cases, you may have been able to authenticate and did not have permissions on the remote directory. Consider changing the remote temp path in ansible.cfg to a path rooted in "/tmp". Failed command was: %s, exited with result %d' % (cmd, result['rc'])
if 'stdout' in result and result['stdout'] != '':
output = output + ": %s" % result['stdout']
raise errors.AnsibleError(output)
rc = utils.last_non_blank_line(result['stdout']).strip() + '/'
# Catch failure conditions, files should never be
# written to locations in /.
if rc == '/':
raise errors.AnsibleError('failed to resolve remote temporary directory from %s: `%s` returned empty string' % (basetmp, cmd))
return rc
# *****************************************************
def _remove_tmp_path(self, conn, tmp_path):
''' Remove a tmp_path. '''
if "-tmp-" in tmp_path:
cmd = "rm -rf %s >/dev/null 2>&1" % tmp_path
self._low_level_exec_command(conn, cmd, None, sudoable=False)
# If we have gotten here we have a working ssh configuration.
# If ssh breaks we could leave tmp directories out on the remote system.
# *****************************************************
def _copy_module(self, conn, tmp, module_name, module_args, inject, complex_args=None):
''' transfer a module over SFTP, does not run it '''
(
module_style,
module_shebang,
module_data
) = self._configure_module(conn, module_name, module_args, inject, complex_args)
module_remote_path = os.path.join(tmp, module_name)
self._transfer_str(conn, tmp, module_name, module_data)
return (module_remote_path, module_style, module_shebang)
# *****************************************************
def _configure_module(self, conn, module_name, module_args, inject, complex_args=None):
''' find module and configure it '''
# Search module path(s) for named module.
module_path = utils.plugins.module_finder.find_plugin(module_name)
if module_path is None:
raise errors.AnsibleFileNotFound("module %s not found in %s" % (module_name, utils.plugins.module_finder.print_paths()))
# insert shared code and arguments into the module
(module_data, module_style, module_shebang) = module_replacer.modify_module(
module_path, complex_args, module_args, inject
)
return (module_style, module_shebang, module_data)
# *****************************************************
def _parallel_exec(self, hosts):
''' handles mulitprocessing when more than 1 fork is required '''
manager = multiprocessing.Manager()
job_queue = manager.Queue()
for host in hosts:
job_queue.put(host)
result_queue = manager.Queue()
try:
fileno = sys.stdin.fileno()
except ValueError:
fileno = None
workers = []
for i in range(self.forks):
new_stdin = None
if fileno is not None:
try:
new_stdin = os.fdopen(os.dup(fileno))
except OSError, e:
# couldn't dupe stdin, most likely because it's
# not a valid file descriptor, so we just rely on
# using the one that was passed in
pass
prc = multiprocessing.Process(target=_executor_hook,
args=(job_queue, result_queue, new_stdin))
prc.start()
workers.append(prc)
try:
for worker in workers:
worker.join()
except KeyboardInterrupt:
for worker in workers:
worker.terminate()
worker.join()
results = []
try:
while not result_queue.empty():
results.append(result_queue.get(block=False))
except socket.error:
raise errors.AnsibleError("<interrupted>")
return results
# *****************************************************
def _partition_results(self, results):
''' separate results by ones we contacted & ones we didn't '''
if results is None:
return None
results2 = dict(contacted={}, dark={})
for result in results:
host = result.host
if host is None:
raise Exception("internal error, host not set")
if result.communicated_ok():
results2["contacted"][host] = result.result
else:
results2["dark"][host] = result.result
# hosts which were contacted but never got a chance to return
for host in self.run_hosts:
if not (host in results2['dark'] or host in results2['contacted']):
results2["dark"][host] = {}
return results2
# *****************************************************
def run(self):
''' xfer & run module on all matched hosts '''
# find hosts that match the pattern
if not self.run_hosts:
self.run_hosts = self.inventory.list_hosts(self.pattern)
hosts = self.run_hosts
if len(hosts) == 0:
self.callbacks.on_no_hosts()
return dict(contacted={}, dark={})
global multiprocessing_runner
multiprocessing_runner = self
results = None
# Check if this is an action plugin. Some of them are designed
# to be ran once per group of hosts. Example module: pause,
# run once per hostgroup, rather than pausing once per each
# host.
p = utils.plugins.action_loader.get(self.module_name, self)
if self.forks == 0 or self.forks > len(hosts):
self.forks = len(hosts)
if p and getattr(p, 'BYPASS_HOST_LOOP', None):
# Expose the current hostgroup to the bypassing plugins
self.host_set = hosts
# We aren't iterating over all the hosts in this
# group. So, just pick the first host in our group to
# construct the conn object with.
result_data = self._executor(hosts[0], None).result
# Create a ResultData item for each host in this group
# using the returned result. If we didn't do this we would
# get false reports of dark hosts.
results = [ ReturnData(host=h, result=result_data, comm_ok=True) \
for h in hosts ]
del self.host_set
elif self.forks > 1:
try:
results = self._parallel_exec(hosts)
except IOError, ie:
print ie.errno
if ie.errno == 32:
# broken pipe from Ctrl+C
raise errors.AnsibleError("interrupted")
raise
else:
results = [ self._executor(h, None) for h in hosts ]
return self._partition_results(results)
# *****************************************************
def run_async(self, time_limit):
''' Run this module asynchronously and return a poller. '''
self.background = time_limit
results = self.run()
return results, poller.AsyncPoller(results, self)
# *****************************************************
def noop_on_check(self, inject):
''' Should the runner run in check mode or not ? '''
# initialize self.always_run on first call
if self.always_run is None:
self.always_run = self.module_vars.get('always_run', False)
self.always_run = check_conditional(
self.always_run, self.basedir, inject, fail_on_undefined=True)
return (self.check and not self.always_run)
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_2234_1 |
crossvul-python_data_bad_4316_1 | from __future__ import absolute_import
import datetime
import logging
import os
import socket
from socket import error as SocketError, timeout as SocketTimeout
import warnings
from .packages import six
from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection
from .packages.six.moves.http_client import HTTPException # noqa: F401
try: # Compiled with SSL?
import ssl
BaseSSLError = ssl.SSLError
except (ImportError, AttributeError): # Platform-specific: No SSL.
ssl = None
class BaseSSLError(BaseException):
pass
try:
# Python 3: not a no-op, we're adding this to the namespace so it can be imported.
ConnectionError = ConnectionError
except NameError:
# Python 2
class ConnectionError(Exception):
pass
from .exceptions import (
NewConnectionError,
ConnectTimeoutError,
SubjectAltNameWarning,
SystemTimeWarning,
)
from .packages.ssl_match_hostname import match_hostname, CertificateError
from .util.ssl_ import (
resolve_cert_reqs,
resolve_ssl_version,
assert_fingerprint,
create_urllib3_context,
ssl_wrap_socket,
)
from .util import connection
from ._collections import HTTPHeaderDict
log = logging.getLogger(__name__)
port_by_scheme = {"http": 80, "https": 443}
# When it comes time to update this value as a part of regular maintenance
# (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2019, 1, 1)
class DummyConnection(object):
"""Used to detect a failed ConnectionCls import."""
pass
class HTTPConnection(_HTTPConnection, object):
"""
Based on httplib.HTTPConnection but provides an extra constructor
backwards-compatibility layer between older and newer Pythons.
Additional keyword parameters are used to configure attributes of the connection.
Accepted parameters include:
- ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`
- ``source_address``: Set the source address for the current connection.
- ``socket_options``: Set specific options on the underlying socket. If not specified, then
defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
For example, if you wish to enable TCP Keep Alive in addition to the defaults,
you might pass::
HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
]
Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
"""
default_port = port_by_scheme["http"]
#: Disable Nagle's algorithm by default.
#: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
#: Whether this connection verifies the host's certificate.
is_verified = False
def __init__(self, *args, **kw):
if not six.PY2:
kw.pop("strict", None)
# Pre-set source_address.
self.source_address = kw.get("source_address")
#: The socket options provided by the user. If no options are
#: provided, we use the default options.
self.socket_options = kw.pop("socket_options", self.default_socket_options)
_HTTPConnection.__init__(self, *args, **kw)
@property
def host(self):
"""
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name that includes the dot. In addition, some
servers may not expect to receive the trailing dot when provided.
However, the hostname with trailing dot is critical to DNS resolution; doing a
lookup with the trailing dot will properly only resolve the appropriate FQDN,
whereas a lookup without a trailing dot will search the system's search domain
list. Thus, it's important to keep the original host around for use only in
those cases where it's appropriate (i.e., when doing DNS lookup to establish the
actual TCP connection across which we're going to send HTTP requests).
"""
return self._dns_host.rstrip(".")
@host.setter
def host(self, value):
"""
Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit.
"""
self._dns_host = value
def _new_conn(self):
""" Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
"""
extra_kw = {}
if self.source_address:
extra_kw["source_address"] = self.source_address
if self.socket_options:
extra_kw["socket_options"] = self.socket_options
try:
conn = connection.create_connection(
(self._dns_host, self.port), self.timeout, **extra_kw
)
except SocketTimeout:
raise ConnectTimeoutError(
self,
"Connection to %s timed out. (connect timeout=%s)"
% (self.host, self.timeout),
)
except SocketError as e:
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % e
)
return conn
def _prepare_conn(self, conn):
self.sock = conn
# Google App Engine's httplib does not define _tunnel_host
if getattr(self, "_tunnel_host", None):
# TODO: Fix tunnel so it doesn't depend on self.sock state.
self._tunnel()
# Mark this connection as not reusable
self.auto_open = 0
def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
"""
headers = HTTPHeaderDict(headers if headers is not None else {})
skip_accept_encoding = "accept-encoding" in headers
skip_host = "host" in headers
self.putrequest(
method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
)
for header, value in headers.items():
self.putheader(header, value)
if "transfer-encoding" not in headers:
self.putheader("Transfer-Encoding", "chunked")
self.endheaders()
if body is not None:
stringish_types = six.string_types + (bytes,)
if isinstance(body, stringish_types):
body = (body,)
for chunk in body:
if not chunk:
continue
if not isinstance(chunk, bytes):
chunk = chunk.encode("utf8")
len_str = hex(len(chunk))[2:]
self.send(len_str.encode("utf-8"))
self.send(b"\r\n")
self.send(chunk)
self.send(b"\r\n")
# After the if clause, to always have a closed body
self.send(b"0\r\n\r\n")
class HTTPSConnection(HTTPConnection):
default_port = port_by_scheme["https"]
ssl_version = None
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
key_password=None,
strict=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
ssl_context=None,
server_hostname=None,
**kw
):
HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw)
self.key_file = key_file
self.cert_file = cert_file
self.key_password = key_password
self.ssl_context = ssl_context
self.server_hostname = server_hostname
# Required property for Google AppEngine 1.9.0 which otherwise causes
# HTTPS requests to go out as HTTP. (See Issue #356)
self._protocol = "https"
class VerifiedHTTPSConnection(HTTPSConnection):
"""
Based on httplib.HTTPSConnection but wraps the socket with
SSL certification.
"""
cert_reqs = None
ca_certs = None
ca_cert_dir = None
ssl_version = None
assert_fingerprint = None
def set_cert(
self,
key_file=None,
cert_file=None,
cert_reqs=None,
key_password=None,
ca_certs=None,
assert_hostname=None,
assert_fingerprint=None,
ca_cert_dir=None,
):
"""
This method should only be called once, before the connection is used.
"""
# If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also
# have an SSLContext object in which case we'll use its verify_mode.
if cert_reqs is None:
if self.ssl_context is not None:
cert_reqs = self.ssl_context.verify_mode
else:
cert_reqs = resolve_cert_reqs(None)
self.key_file = key_file
self.cert_file = cert_file
self.cert_reqs = cert_reqs
self.key_password = key_password
self.assert_hostname = assert_hostname
self.assert_fingerprint = assert_fingerprint
self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
def connect(self):
# Add certificate verification
conn = self._new_conn()
hostname = self.host
# Google App Engine's httplib does not define _tunnel_host
if getattr(self, "_tunnel_host", None):
self.sock = conn
# Calls self._set_hostport(), so self.host is
# self._tunnel_host below.
self._tunnel()
# Mark this connection as not reusable
self.auto_open = 0
# Override the host with the one we're requesting data from.
hostname = self._tunnel_host
server_hostname = hostname
if self.server_hostname is not None:
server_hostname = self.server_hostname
is_time_off = datetime.date.today() < RECENT_DATE
if is_time_off:
warnings.warn(
(
"System time is way off (before {0}). This will probably "
"lead to SSL verification errors"
).format(RECENT_DATE),
SystemTimeWarning,
)
# Wrap socket using verification with the root certs in
# trusted_root_certs
default_ssl_context = False
if self.ssl_context is None:
default_ssl_context = True
self.ssl_context = create_urllib3_context(
ssl_version=resolve_ssl_version(self.ssl_version),
cert_reqs=resolve_cert_reqs(self.cert_reqs),
)
context = self.ssl_context
context.verify_mode = resolve_cert_reqs(self.cert_reqs)
# Try to load OS default certs if none are given.
# Works well on Windows (requires Python3.4+)
if (
not self.ca_certs
and not self.ca_cert_dir
and default_ssl_context
and hasattr(context, "load_default_certs")
):
context.load_default_certs()
self.sock = ssl_wrap_socket(
sock=conn,
keyfile=self.key_file,
certfile=self.cert_file,
key_password=self.key_password,
ca_certs=self.ca_certs,
ca_cert_dir=self.ca_cert_dir,
server_hostname=server_hostname,
ssl_context=context,
)
if self.assert_fingerprint:
assert_fingerprint(
self.sock.getpeercert(binary_form=True), self.assert_fingerprint
)
elif (
context.verify_mode != ssl.CERT_NONE
and not getattr(context, "check_hostname", False)
and self.assert_hostname is not False
):
# While urllib3 attempts to always turn off hostname matching from
# the TLS library, this cannot always be done. So we check whether
# the TLS Library still thinks it's matching hostnames.
cert = self.sock.getpeercert()
if not cert.get("subjectAltName", ()):
warnings.warn(
(
"Certificate for {0} has no `subjectAltName`, falling back to check for a "
"`commonName` for now. This feature is being removed by major browsers and "
"deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "
"for details.)".format(hostname)
),
SubjectAltNameWarning,
)
_match_hostname(cert, self.assert_hostname or server_hostname)
self.is_verified = (
context.verify_mode == ssl.CERT_REQUIRED
or self.assert_fingerprint is not None
)
def _match_hostname(cert, asserted_hostname):
try:
match_hostname(cert, asserted_hostname)
except CertificateError as e:
log.warning(
"Certificate did not match expected hostname: %s. Certificate: %s",
asserted_hostname,
cert,
)
# Add cert to exception and reraise so client code can inspect
# the cert when catching the exception, if they want to
e._peer_cert = cert
raise
if ssl:
# Make a copy for testing.
UnverifiedHTTPSConnection = HTTPSConnection
HTTPSConnection = VerifiedHTTPSConnection
else:
HTTPSConnection = DummyConnection
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_4316_1 |
crossvul-python_data_good_4316_1 | from __future__ import absolute_import
import re
import datetime
import logging
import os
import socket
from socket import error as SocketError, timeout as SocketTimeout
import warnings
from .packages import six
from .packages.six.moves.http_client import HTTPConnection as _HTTPConnection
from .packages.six.moves.http_client import HTTPException # noqa: F401
try: # Compiled with SSL?
import ssl
BaseSSLError = ssl.SSLError
except (ImportError, AttributeError): # Platform-specific: No SSL.
ssl = None
class BaseSSLError(BaseException):
pass
try:
# Python 3: not a no-op, we're adding this to the namespace so it can be imported.
ConnectionError = ConnectionError
except NameError:
# Python 2
class ConnectionError(Exception):
pass
from .exceptions import (
NewConnectionError,
ConnectTimeoutError,
SubjectAltNameWarning,
SystemTimeWarning,
)
from .packages.ssl_match_hostname import match_hostname, CertificateError
from .util.ssl_ import (
resolve_cert_reqs,
resolve_ssl_version,
assert_fingerprint,
create_urllib3_context,
ssl_wrap_socket,
)
from .util import connection
from ._collections import HTTPHeaderDict
log = logging.getLogger(__name__)
port_by_scheme = {"http": 80, "https": 443}
# When it comes time to update this value as a part of regular maintenance
# (ie test_recent_date is failing) update it to ~6 months before the current date.
RECENT_DATE = datetime.date(2019, 1, 1)
_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]")
class DummyConnection(object):
"""Used to detect a failed ConnectionCls import."""
pass
class HTTPConnection(_HTTPConnection, object):
"""
Based on httplib.HTTPConnection but provides an extra constructor
backwards-compatibility layer between older and newer Pythons.
Additional keyword parameters are used to configure attributes of the connection.
Accepted parameters include:
- ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`
- ``source_address``: Set the source address for the current connection.
- ``socket_options``: Set specific options on the underlying socket. If not specified, then
defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling
Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.
For example, if you wish to enable TCP Keep Alive in addition to the defaults,
you might pass::
HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
]
Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).
"""
default_port = port_by_scheme["http"]
#: Disable Nagle's algorithm by default.
#: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``
default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
#: Whether this connection verifies the host's certificate.
is_verified = False
def __init__(self, *args, **kw):
if not six.PY2:
kw.pop("strict", None)
# Pre-set source_address.
self.source_address = kw.get("source_address")
#: The socket options provided by the user. If no options are
#: provided, we use the default options.
self.socket_options = kw.pop("socket_options", self.default_socket_options)
_HTTPConnection.__init__(self, *args, **kw)
@property
def host(self):
"""
Getter method to remove any trailing dots that indicate the hostname is an FQDN.
In general, SSL certificates don't include the trailing dot indicating a
fully-qualified domain name, and thus, they don't validate properly when
checked against a domain name that includes the dot. In addition, some
servers may not expect to receive the trailing dot when provided.
However, the hostname with trailing dot is critical to DNS resolution; doing a
lookup with the trailing dot will properly only resolve the appropriate FQDN,
whereas a lookup without a trailing dot will search the system's search domain
list. Thus, it's important to keep the original host around for use only in
those cases where it's appropriate (i.e., when doing DNS lookup to establish the
actual TCP connection across which we're going to send HTTP requests).
"""
return self._dns_host.rstrip(".")
@host.setter
def host(self, value):
"""
Setter for the `host` property.
We assume that only urllib3 uses the _dns_host attribute; httplib itself
only uses `host`, and it seems reasonable that other libraries follow suit.
"""
self._dns_host = value
def _new_conn(self):
""" Establish a socket connection and set nodelay settings on it.
:return: New socket connection.
"""
extra_kw = {}
if self.source_address:
extra_kw["source_address"] = self.source_address
if self.socket_options:
extra_kw["socket_options"] = self.socket_options
try:
conn = connection.create_connection(
(self._dns_host, self.port), self.timeout, **extra_kw
)
except SocketTimeout:
raise ConnectTimeoutError(
self,
"Connection to %s timed out. (connect timeout=%s)"
% (self.host, self.timeout),
)
except SocketError as e:
raise NewConnectionError(
self, "Failed to establish a new connection: %s" % e
)
return conn
def _prepare_conn(self, conn):
self.sock = conn
# Google App Engine's httplib does not define _tunnel_host
if getattr(self, "_tunnel_host", None):
# TODO: Fix tunnel so it doesn't depend on self.sock state.
self._tunnel()
# Mark this connection as not reusable
self.auto_open = 0
def connect(self):
conn = self._new_conn()
self._prepare_conn(conn)
def putrequest(self, method, url, *args, **kwargs):
"""Send a request to the server"""
match = _CONTAINS_CONTROL_CHAR_RE.search(method)
if match:
raise ValueError(
"Method cannot contain non-token characters %r (found at least %r)"
% (method, match.group())
)
return _HTTPConnection.putrequest(self, method, url, *args, **kwargs)
def request_chunked(self, method, url, body=None, headers=None):
"""
Alternative to the common request method, which sends the
body with chunked encoding and not as one block
"""
headers = HTTPHeaderDict(headers if headers is not None else {})
skip_accept_encoding = "accept-encoding" in headers
skip_host = "host" in headers
self.putrequest(
method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host
)
for header, value in headers.items():
self.putheader(header, value)
if "transfer-encoding" not in headers:
self.putheader("Transfer-Encoding", "chunked")
self.endheaders()
if body is not None:
stringish_types = six.string_types + (bytes,)
if isinstance(body, stringish_types):
body = (body,)
for chunk in body:
if not chunk:
continue
if not isinstance(chunk, bytes):
chunk = chunk.encode("utf8")
len_str = hex(len(chunk))[2:]
self.send(len_str.encode("utf-8"))
self.send(b"\r\n")
self.send(chunk)
self.send(b"\r\n")
# After the if clause, to always have a closed body
self.send(b"0\r\n\r\n")
class HTTPSConnection(HTTPConnection):
default_port = port_by_scheme["https"]
ssl_version = None
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
key_password=None,
strict=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
ssl_context=None,
server_hostname=None,
**kw
):
HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw)
self.key_file = key_file
self.cert_file = cert_file
self.key_password = key_password
self.ssl_context = ssl_context
self.server_hostname = server_hostname
# Required property for Google AppEngine 1.9.0 which otherwise causes
# HTTPS requests to go out as HTTP. (See Issue #356)
self._protocol = "https"
class VerifiedHTTPSConnection(HTTPSConnection):
"""
Based on httplib.HTTPSConnection but wraps the socket with
SSL certification.
"""
cert_reqs = None
ca_certs = None
ca_cert_dir = None
ssl_version = None
assert_fingerprint = None
def set_cert(
self,
key_file=None,
cert_file=None,
cert_reqs=None,
key_password=None,
ca_certs=None,
assert_hostname=None,
assert_fingerprint=None,
ca_cert_dir=None,
):
"""
This method should only be called once, before the connection is used.
"""
# If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also
# have an SSLContext object in which case we'll use its verify_mode.
if cert_reqs is None:
if self.ssl_context is not None:
cert_reqs = self.ssl_context.verify_mode
else:
cert_reqs = resolve_cert_reqs(None)
self.key_file = key_file
self.cert_file = cert_file
self.cert_reqs = cert_reqs
self.key_password = key_password
self.assert_hostname = assert_hostname
self.assert_fingerprint = assert_fingerprint
self.ca_certs = ca_certs and os.path.expanduser(ca_certs)
self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)
def connect(self):
# Add certificate verification
conn = self._new_conn()
hostname = self.host
# Google App Engine's httplib does not define _tunnel_host
if getattr(self, "_tunnel_host", None):
self.sock = conn
# Calls self._set_hostport(), so self.host is
# self._tunnel_host below.
self._tunnel()
# Mark this connection as not reusable
self.auto_open = 0
# Override the host with the one we're requesting data from.
hostname = self._tunnel_host
server_hostname = hostname
if self.server_hostname is not None:
server_hostname = self.server_hostname
is_time_off = datetime.date.today() < RECENT_DATE
if is_time_off:
warnings.warn(
(
"System time is way off (before {0}). This will probably "
"lead to SSL verification errors"
).format(RECENT_DATE),
SystemTimeWarning,
)
# Wrap socket using verification with the root certs in
# trusted_root_certs
default_ssl_context = False
if self.ssl_context is None:
default_ssl_context = True
self.ssl_context = create_urllib3_context(
ssl_version=resolve_ssl_version(self.ssl_version),
cert_reqs=resolve_cert_reqs(self.cert_reqs),
)
context = self.ssl_context
context.verify_mode = resolve_cert_reqs(self.cert_reqs)
# Try to load OS default certs if none are given.
# Works well on Windows (requires Python3.4+)
if (
not self.ca_certs
and not self.ca_cert_dir
and default_ssl_context
and hasattr(context, "load_default_certs")
):
context.load_default_certs()
self.sock = ssl_wrap_socket(
sock=conn,
keyfile=self.key_file,
certfile=self.cert_file,
key_password=self.key_password,
ca_certs=self.ca_certs,
ca_cert_dir=self.ca_cert_dir,
server_hostname=server_hostname,
ssl_context=context,
)
if self.assert_fingerprint:
assert_fingerprint(
self.sock.getpeercert(binary_form=True), self.assert_fingerprint
)
elif (
context.verify_mode != ssl.CERT_NONE
and not getattr(context, "check_hostname", False)
and self.assert_hostname is not False
):
# While urllib3 attempts to always turn off hostname matching from
# the TLS library, this cannot always be done. So we check whether
# the TLS Library still thinks it's matching hostnames.
cert = self.sock.getpeercert()
if not cert.get("subjectAltName", ()):
warnings.warn(
(
"Certificate for {0} has no `subjectAltName`, falling back to check for a "
"`commonName` for now. This feature is being removed by major browsers and "
"deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 "
"for details.)".format(hostname)
),
SubjectAltNameWarning,
)
_match_hostname(cert, self.assert_hostname or server_hostname)
self.is_verified = (
context.verify_mode == ssl.CERT_REQUIRED
or self.assert_fingerprint is not None
)
def _match_hostname(cert, asserted_hostname):
try:
match_hostname(cert, asserted_hostname)
except CertificateError as e:
log.warning(
"Certificate did not match expected hostname: %s. Certificate: %s",
asserted_hostname,
cert,
)
# Add cert to exception and reraise so client code can inspect
# the cert when catching the exception, if they want to
e._peer_cert = cert
raise
if ssl:
# Make a copy for testing.
UnverifiedHTTPSConnection = HTTPSConnection
HTTPSConnection = VerifiedHTTPSConnection
else:
HTTPSConnection = DummyConnection
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_4316_1 |
crossvul-python_data_good_3934_0 | """Small, fast HTTP client library for Python.
Features persistent connections, cache, and Google App Engine Standard
Environment support.
"""
from __future__ import print_function
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = [
"Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger",
"Alex Yu",
]
__license__ = "MIT"
__version__ = '0.17.4'
import base64
import calendar
import copy
import email
import email.FeedParser
import email.Message
import email.Utils
import errno
import gzip
import httplib
import os
import random
import re
import StringIO
import sys
import time
import urllib
import urlparse
import zlib
try:
from hashlib import sha1 as _sha, md5 as _md5
except ImportError:
# prior to Python 2.5, these were separate modules
import sha
import md5
_sha = sha.new
_md5 = md5.new
import hmac
from gettext import gettext as _
import socket
try:
from httplib2 import socks
except ImportError:
try:
import socks
except (ImportError, AttributeError):
socks = None
# Build the appropriate socket wrapper for ssl
ssl = None
ssl_SSLError = None
ssl_CertificateError = None
try:
import ssl # python 2.6
except ImportError:
pass
if ssl is not None:
ssl_SSLError = getattr(ssl, "SSLError", None)
ssl_CertificateError = getattr(ssl, "CertificateError", None)
def _ssl_wrap_socket(
sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password
):
if disable_validation:
cert_reqs = ssl.CERT_NONE
else:
cert_reqs = ssl.CERT_REQUIRED
if ssl_version is None:
ssl_version = ssl.PROTOCOL_SSLv23
if hasattr(ssl, "SSLContext"): # Python 2.7.9
context = ssl.SSLContext(ssl_version)
context.verify_mode = cert_reqs
context.check_hostname = cert_reqs != ssl.CERT_NONE
if cert_file:
if key_password:
context.load_cert_chain(cert_file, key_file, key_password)
else:
context.load_cert_chain(cert_file, key_file)
if ca_certs:
context.load_verify_locations(ca_certs)
return context.wrap_socket(sock, server_hostname=hostname)
else:
if key_password:
raise NotSupportedOnThisPlatform("Certificate with password is not supported.")
return ssl.wrap_socket(
sock,
keyfile=key_file,
certfile=cert_file,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
ssl_version=ssl_version,
)
def _ssl_wrap_socket_unsupported(
sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password
):
if not disable_validation:
raise CertificateValidationUnsupported(
"SSL certificate validation is not supported without "
"the ssl module installed. To avoid this error, install "
"the ssl module, or explicity disable validation."
)
if key_password:
raise NotSupportedOnThisPlatform("Certificate with password is not supported.")
ssl_sock = socket.ssl(sock, key_file, cert_file)
return httplib.FakeSocket(sock, ssl_sock)
if ssl is None:
_ssl_wrap_socket = _ssl_wrap_socket_unsupported
if sys.version_info >= (2, 3):
from .iri2uri import iri2uri
else:
def iri2uri(uri):
return uri
def has_timeout(timeout): # python 2.6
if hasattr(socket, "_GLOBAL_DEFAULT_TIMEOUT"):
return timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT
return timeout is not None
__all__ = [
"Http",
"Response",
"ProxyInfo",
"HttpLib2Error",
"RedirectMissingLocation",
"RedirectLimit",
"FailedToDecompressContent",
"UnimplementedDigestAuthOptionError",
"UnimplementedHmacDigestAuthOptionError",
"debuglevel",
"ProxiesUnavailableError",
]
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# A request will be tried 'RETRIES' times if it fails at the socket/connection level.
RETRIES = 2
# Python 2.3 support
if sys.version_info < (2, 4):
def sorted(seq):
seq.sort()
return seq
# Python 2.3 support
def HTTPResponse__getheaders(self):
"""Return list of (header, value) tuples."""
if self.msg is None:
raise httplib.ResponseNotReady()
return self.msg.items()
if not hasattr(httplib.HTTPResponse, "getheaders"):
httplib.HTTPResponse.getheaders = HTTPResponse__getheaders
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception):
pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse):
pass
class RedirectLimit(HttpLib2ErrorWithResponse):
pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse):
pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class MalformedHeader(HttpLib2Error):
pass
class RelativeURIError(HttpLib2Error):
pass
class ServerNotFoundError(HttpLib2Error):
pass
class ProxiesUnavailableError(HttpLib2Error):
pass
class CertificateValidationUnsupported(HttpLib2Error):
pass
class SSLHandshakeError(HttpLib2Error):
pass
class NotSupportedOnThisPlatform(HttpLib2Error):
pass
class CertificateHostnameMismatch(SSLHandshakeError):
def __init__(self, desc, host, cert):
HttpLib2Error.__init__(self, desc)
self.host = host
self.cert = cert
class NotRunningAppEngineEnvironment(HttpLib2Error):
pass
# Open Items:
# -----------
# Proxy support
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
from httplib2 import certs
CA_CERTS = certs.where()
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
]
# https://tools.ietf.org/html/rfc7231#section-8.1.3
SAFE_METHODS = ("GET", "HEAD") # TODO add "OPTIONS", "TRACE"
# To change, assign to `Http().redirect_codes`
REDIRECT_CODES = frozenset((300, 301, 302, 303, 307, 308))
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get("connection", "").split(",")])
return [header for header in response.keys() if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r"^\w+://")
re_unsafe = re.compile(r"[^\w\-_.()=!]+")
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
if isinstance(filename, str):
filename_bytes = filename
filename = filename.decode("utf-8")
else:
filename_bytes = filename.encode("utf-8")
filemd5 = _md5(filename_bytes).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_unsafe.sub("", filename)
# limit length of filename (vital for Windows)
# https://github.com/httplib2/httplib2/pull/74
# C:\Users\ <username> \AppData\Local\Temp\ <safe_filename> , <md5>
# 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars
# Thus max safe filename x = 93 chars. Let it be 90 to make a round sum:
filename = filename[:90]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r"(?:\r\n)?[ \t]+")
def _normalize_headers(headers):
return dict(
[
(key.lower(), NORMALIZE_SPACE.sub(value, " ").strip())
for (key, value) in headers.iteritems()
]
)
def _parse_cache_control(headers):
retval = {}
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)])
for part in parts
if -1 != part.find("=")
]
parts_wo_args = [
(name.strip().lower(), 1) for name in parts if -1 == name.find("=")
]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, usefull for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(
r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$"
)
WWW_AUTH_RELAXED = re.compile(
r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$"
)
UNQUOTE_PAIRS = re.compile(r"\\(.)")
def _parse_www_authenticate(headers, headername="www-authenticate"):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headername in headers:
try:
authenticate = headers[headername].strip()
www_auth = (
USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
)
while authenticate:
# Break off the scheme at the beginning of the line
if headername == "authentication-info":
(auth_scheme, the_rest) = ("digest", authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(
r"\1", value
) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
# TODO: add current time as _entry_disposition argument to avoid sleep in tests
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if (
"pragma" in request_headers
and request_headers["pragma"].lower().find("no-cache") != -1
):
retval = "TRANSPARENT"
if "cache-control" not in request_headers:
request_headers["cache-control"] = "no-cache"
elif "no-cache" in cc:
retval = "TRANSPARENT"
elif "no-cache" in cc_response:
retval = "STALE"
elif "only-if-cached" in cc:
retval = "FRESH"
elif "date" in response_headers:
date = calendar.timegm(email.Utils.parsedate_tz(response_headers["date"]))
now = time.time()
current_age = max(0, now - date)
if "max-age" in cc_response:
try:
freshness_lifetime = int(cc_response["max-age"])
except ValueError:
freshness_lifetime = 0
elif "expires" in response_headers:
expires = email.Utils.parsedate_tz(response_headers["expires"])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if "max-age" in cc:
try:
freshness_lifetime = int(cc["max-age"])
except ValueError:
freshness_lifetime = 0
if "min-fresh" in cc:
try:
min_fresh = int(cc["min-fresh"])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get("content-encoding", None)
if encoding in ["gzip", "deflate"]:
if encoding == "gzip":
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == "deflate":
content = zlib.decompress(content, -zlib.MAX_WBITS)
response["content-length"] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response["-content-encoding"] = response["content-encoding"]
del response["content-encoding"]
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
)
return content
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if "no-store" in cc or "no-store" in cc_response:
cache.delete(cachekey)
else:
info = email.Message.Message()
for key, value in response_headers.iteritems():
if key not in ["status", "content-encoding", "transfer-encoding"]:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get("vary", None)
if vary:
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = "status: %d\r\n" % status
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = "".join([status_header, header_str, content])
cache.set(cachekey, text)
def _cnonce():
dig = _md5(
"%s:%s"
% (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])
).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(
_sha("%s%s%s" % (cnonce, iso_now, password)).digest()
).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path) :].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-ride this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
class BasicAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = (
"Basic " + base64.b64encode("%s:%s" % self.credentials).strip()
)
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["digest"]
qop = self.challenge.get("qop", "auth")
self.challenge["qop"] = (
("auth" in [x.strip() for x in qop.split()]) and "auth" or None
)
if self.challenge["qop"] is None:
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for qop: %s." % qop)
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "MD5").upper()
if self.challenge["algorithm"] != "MD5":
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.A1 = "".join(
[
self.credentials[0],
":",
self.challenge["realm"],
":",
self.credentials[1],
]
)
self.challenge["nc"] = 1
def request(self, method, request_uri, headers, content, cnonce=None):
"""Modify the request headers"""
H = lambda x: _md5(x).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge["cnonce"] = cnonce or _cnonce()
request_digest = '"%s"' % KD(
H(self.A1),
"%s:%s:%s:%s:%s"
% (
self.challenge["nonce"],
"%08x" % self.challenge["nc"],
self.challenge["cnonce"],
self.challenge["qop"],
H(A2),
),
)
headers["authorization"] = (
'Digest username="%s", realm="%s", nonce="%s", '
'uri="%s", algorithm=%s, response=%s, qop=%s, '
'nc=%08x, cnonce="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["nonce"],
request_uri,
self.challenge["algorithm"],
request_digest,
self.challenge["qop"],
self.challenge["nc"],
self.challenge["cnonce"],
)
if self.challenge.get("opaque"):
headers["authorization"] += ', opaque="%s"' % self.challenge["opaque"]
self.challenge["nc"] += 1
def response(self, response, content):
if "authentication-info" not in response:
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"digest", {}
)
if "true" == challenge.get("stale"):
self.challenge["nonce"] = challenge["nonce"]
self.challenge["nc"] = 1
return True
else:
updated_challenge = _parse_www_authenticate(
response, "authentication-info"
).get("digest", {})
if "nextnonce" in updated_challenge:
self.challenge["nonce"] = updated_challenge["nextnonce"]
self.challenge["nc"] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["hmacdigest"]
# TODO: self.challenge['domain']
self.challenge["reason"] = self.challenge.get("reason", "unauthorized")
if self.challenge["reason"] not in ["unauthorized", "integrity"]:
self.challenge["reason"] = "unauthorized"
self.challenge["salt"] = self.challenge.get("salt", "")
if not self.challenge.get("snonce"):
raise UnimplementedHmacDigestAuthOptionError(
_("The challenge doesn't contain a server nonce, or this one is empty.")
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "HMAC-SHA-1")
if self.challenge["algorithm"] not in ["HMAC-SHA-1", "HMAC-MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1")
if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_(
"Unsupported value for pw-algorithm: %s."
% self.challenge["pw-algorithm"]
)
)
if self.challenge["algorithm"] == "HMAC-MD5":
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge["pw-algorithm"] == "MD5":
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join(
[
self.credentials[0],
":",
self.pwhashmod.new(
"".join([self.credentials[1], self.challenge["salt"]])
)
.hexdigest()
.lower(),
":",
self.challenge["realm"],
]
)
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (
method,
request_uri,
cnonce,
self.challenge["snonce"],
headers_val,
)
request_digest = (
hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
)
headers["authorization"] = (
'HMACDigest username="%s", realm="%s", snonce="%s",'
' cnonce="%s", uri="%s", created="%s", '
'response="%s", headers="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["snonce"],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"hmacdigest", {}
)
if challenge.get("reason") in ["integrity", "stale"]:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = (
'UsernameToken Username="%s", PasswordDigest="%s", '
'Nonce="%s", Created="%s"'
) % (self.credentials[0], password_digest, cnonce, iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
from urllib import urlencode
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
service = challenge["googlelogin"].get("service", "xapi")
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == "xapi" and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(
Email=credentials[0],
Passwd=credentials[1],
service=service,
source=headers["user-agent"],
)
resp, content = self.http.request(
"https://www.google.com/accounts/ClientLogin",
method="POST",
body=urlencode(auth),
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
lines = content.split("\n")
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d["Auth"]
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = "GoogleLogin Auth=" + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication,
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(
self, cache, safe=safename
): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = file(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = file(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
def iter(self, domain):
for (cdomain, key, cert, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (key, cert, password)
class AllHosts(object):
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
bypass_hosts = ()
def __init__(
self,
proxy_type,
proxy_host,
proxy_port,
proxy_rdns=True,
proxy_user=None,
proxy_pass=None,
proxy_headers=None,
):
"""Args:
proxy_type: The type of proxy server. This must be set to one of
socks.PROXY_TYPE_XXX constants. For example: p =
ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost',
proxy_port=8000)
proxy_host: The hostname or IP address of the proxy server.
proxy_port: The port that the proxy server is running on.
proxy_rdns: If True (default), DNS queries will not be performed
locally, and instead, handed to the proxy to resolve. This is useful
if the network does not allow resolution of non-local names. In
httplib2 0.9 and earlier, this defaulted to False.
proxy_user: The username used to authenticate with the proxy server.
proxy_pass: The password used to authenticate with the proxy server.
proxy_headers: Additional or modified headers for the proxy connect
request.
"""
self.proxy_type = proxy_type
self.proxy_host = proxy_host
self.proxy_port = proxy_port
self.proxy_rdns = proxy_rdns
self.proxy_user = proxy_user
self.proxy_pass = proxy_pass
self.proxy_headers = proxy_headers
def astuple(self):
return (
self.proxy_type,
self.proxy_host,
self.proxy_port,
self.proxy_rdns,
self.proxy_user,
self.proxy_pass,
self.proxy_headers,
)
def isgood(self):
return (self.proxy_host != None) and (self.proxy_port != None)
def applies_to(self, hostname):
return not self.bypass_host(hostname)
def bypass_host(self, hostname):
"""Has this host been excluded from the proxy config"""
if self.bypass_hosts is AllHosts:
return True
hostname = "." + hostname.lstrip(".")
for skip_name in self.bypass_hosts:
# *.suffix
if skip_name.startswith(".") and hostname.endswith(skip_name):
return True
# exact match
if hostname == "." + skip_name:
return True
return False
def __repr__(self):
return (
"<ProxyInfo type={p.proxy_type} "
"host:port={p.proxy_host}:{p.proxy_port} rdns={p.proxy_rdns}"
+ " user={p.proxy_user} headers={p.proxy_headers}>"
).format(p=self)
def proxy_info_from_environment(method="http"):
"""Read proxy info from the environment variables.
"""
if method not in ["http", "https"]:
return
env_var = method + "_proxy"
url = os.environ.get(env_var, os.environ.get(env_var.upper()))
if not url:
return
return proxy_info_from_url(url, method, None)
def proxy_info_from_url(url, method="http", noproxy=None):
"""Construct a ProxyInfo from a URL (such as http_proxy env var)
"""
url = urlparse.urlparse(url)
username = None
password = None
port = None
if "@" in url[1]:
ident, host_port = url[1].split("@", 1)
if ":" in ident:
username, password = ident.split(":", 1)
else:
password = ident
else:
host_port = url[1]
if ":" in host_port:
host, port = host_port.split(":", 1)
else:
host = host_port
if port:
port = int(port)
else:
port = dict(https=443, http=80)[method]
proxy_type = 3 # socks.PROXY_TYPE_HTTP
pi = ProxyInfo(
proxy_type=proxy_type,
proxy_host=host,
proxy_port=port,
proxy_user=username or None,
proxy_pass=password or None,
proxy_headers=None,
)
bypass_hosts = []
# If not given an explicit noproxy value, respect values in env vars.
if noproxy is None:
noproxy = os.environ.get("no_proxy", os.environ.get("NO_PROXY", ""))
# Special case: A single '*' character means all hosts should be bypassed.
if noproxy == "*":
bypass_hosts = AllHosts
elif noproxy.strip():
bypass_hosts = noproxy.split(",")
bypass_hosts = filter(bool, bypass_hosts) # To exclude empty string.
pi.bypass_hosts = bypass_hosts
return pi
class HTTPConnectionWithTimeout(httplib.HTTPConnection):
"""HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
httplib.HTTPConnection.__init__(self, host, port, strict)
self.timeout = timeout
self.proxy_info = proxy_info
def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
"Proxy support missing but proxy use was requested!"
)
if self.proxy_info and self.proxy_info.isgood():
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_port
else:
use_proxy = False
host = self.host
port = self.port
socket_err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# Different from httplib: support timeouts.
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
# End of difference from httplib.
if self.debuglevel > 0:
print("connect: (%s, %s) ************" % (self.host, self.port))
if use_proxy:
print(
"proxy: %s ************"
% str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
if use_proxy:
self.sock.connect((self.host, self.port) + sa[2:])
else:
self.sock.connect(sa)
except socket.error as e:
socket_err = e
if self.debuglevel > 0:
print("connect fail: (%s, %s)" % (self.host, self.port))
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket_err or socket.error("getaddrinfo returns an empty list")
class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
"""This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
ca_certs=None,
disable_ssl_certificate_validation=False,
ssl_version=None,
key_password=None,
):
if key_password:
httplib.HTTPSConnection.__init__(self, host, port=port, strict=strict)
self._context.load_cert_chain(cert_file, key_file, key_password)
self.key_file = key_file
self.cert_file = cert_file
self.key_password = key_password
else:
httplib.HTTPSConnection.__init__(
self, host, port=port, key_file=key_file, cert_file=cert_file, strict=strict
)
self.key_password = None
self.timeout = timeout
self.proxy_info = proxy_info
if ca_certs is None:
ca_certs = CA_CERTS
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.ssl_version = ssl_version
# The following two methods were adapted from https_wrapper.py, released
# with the Google Appengine SDK at
# http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
# under the following license:
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def _GetValidHostsForCert(self, cert):
"""Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.
"""
if "subjectAltName" in cert:
return [x[1] for x in cert["subjectAltName"] if x[0].lower() == "dns"]
else:
return [x[0][1] for x in cert["subject"] if x[0][0].lower() == "commonname"]
def _ValidateCertificateHostname(self, cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.
"""
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace(".", "\.").replace("*", "[^.]*")
if re.search("^%s$" % (host_re,), hostname, re.I):
return True
return False
def connect(self):
"Connect to a host on a given (SSL) port."
if self.proxy_info and self.proxy_info.isgood():
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_port
else:
use_proxy = False
host = self.host
port = self.port
socket_err = None
address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
for family, socktype, proto, canonname, sockaddr in address_info:
try:
if use_proxy:
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
if use_proxy:
sock.connect((self.host, self.port) + sockaddr[:2])
else:
sock.connect(sockaddr)
self.sock = _ssl_wrap_socket(
sock,
self.key_file,
self.cert_file,
self.disable_ssl_certificate_validation,
self.ca_certs,
self.ssl_version,
self.host,
self.key_password,
)
if self.debuglevel > 0:
print("connect: (%s, %s)" % (self.host, self.port))
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
if not self.disable_ssl_certificate_validation:
cert = self.sock.getpeercert()
hostname = self.host.split(":", 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise CertificateHostnameMismatch(
"Server presented certificate that does not match "
"host %s: %s" % (hostname, cert),
hostname,
cert,
)
except (
ssl_SSLError,
ssl_CertificateError,
CertificateHostnameMismatch,
) as e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
# Unfortunately the ssl module doesn't seem to provide any way
# to get at more detailed error information, in particular
# whether the error is due to certificate validation or
# something else (such as SSL protocol mismatch).
if getattr(e, "errno", None) == ssl.SSL_ERROR_SSL:
raise SSLHandshakeError(e)
else:
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error as e:
socket_err = e
if self.debuglevel > 0:
print("connect fail: (%s, %s)" % (self.host, self.port))
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket_err or socket.error("getaddrinfo returns an empty list")
SCHEME_TO_CONNECTION = {
"http": HTTPConnectionWithTimeout,
"https": HTTPSConnectionWithTimeout,
}
def _new_fixed_fetch(validate_certificate):
def fixed_fetch(
url,
payload=None,
method="GET",
headers={},
allow_truncated=False,
follow_redirects=True,
deadline=None,
):
return fetch(
url,
payload=payload,
method=method,
headers=headers,
allow_truncated=allow_truncated,
follow_redirects=follow_redirects,
deadline=deadline,
validate_certificate=validate_certificate,
)
return fixed_fetch
class AppEngineHttpConnection(httplib.HTTPConnection):
"""Use httplib on App Engine, but compensate for its weirdness.
The parameters key_file, cert_file, proxy_info, ca_certs,
disable_ssl_certificate_validation, and ssl_version are all dropped on
the ground.
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
ca_certs=None,
disable_ssl_certificate_validation=False,
ssl_version=None,
):
httplib.HTTPConnection.__init__(
self, host, port=port, strict=strict, timeout=timeout
)
class AppEngineHttpsConnection(httplib.HTTPSConnection):
"""Same as AppEngineHttpConnection, but for HTTPS URIs.
The parameters proxy_info, ca_certs, disable_ssl_certificate_validation,
and ssl_version are all dropped on the ground.
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
ca_certs=None,
disable_ssl_certificate_validation=False,
ssl_version=None,
key_password=None,
):
if key_password:
raise NotSupportedOnThisPlatform("Certificate with password is not supported.")
httplib.HTTPSConnection.__init__(
self,
host,
port=port,
key_file=key_file,
cert_file=cert_file,
strict=strict,
timeout=timeout,
)
self._fetch = _new_fixed_fetch(not disable_ssl_certificate_validation)
# Use a different connection object for Google App Engine Standard Environment.
def is_gae_instance():
server_software = os.environ.get('SERVER_SOFTWARE', '')
if (server_software.startswith('Google App Engine/') or
server_software.startswith('Development/') or
server_software.startswith('testutil/')):
return True
return False
try:
if not is_gae_instance():
raise NotRunningAppEngineEnvironment()
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub("urlfetch") is None:
raise ImportError
from google.appengine.api.urlfetch import fetch
# Update the connection classes to use the Googel App Engine specific ones.
SCHEME_TO_CONNECTION = {
"http": AppEngineHttpConnection,
"https": AppEngineHttpsConnection,
}
except (ImportError, NotRunningAppEngineEnvironment):
pass
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(
self,
cache=None,
timeout=None,
proxy_info=proxy_info_from_environment,
ca_certs=None,
disable_ssl_certificate_validation=False,
ssl_version=None,
):
"""If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
`proxy_info` may be:
- a callable that takes the http scheme ('http' or 'https') and
returns a ProxyInfo instance per request. By default, uses
proxy_nfo_from_environment.
- a ProxyInfo instance (static proxy config).
- None (proxy disabled).
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
By default, ssl.PROTOCOL_SSLv23 will be used for the ssl version.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.ssl_version = ssl_version
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, basestring):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
self.redirect_codes = REDIRECT_CODES
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
self.safe_methods = list(SAFE_METHODS)
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
# Keep Authorization: headers on a redirect.
self.forward_authorization_headers = False
def close(self):
"""Close persistent connections, clear sensitive data.
Not thread-safe, requires external synchronization against concurrent requests.
"""
existing, self.connections = self.connections, {}
for _, c in existing.iteritems():
c.close()
self.certificates.clear()
self.clear_credentials()
def __getstate__(self):
state_dict = copy.copy(self.__dict__)
# In case request is augmented by some foreign object such as
# credentials which handle auth
if "request" in state_dict:
del state_dict["request"]
if "connections" in state_dict:
del state_dict["connections"]
return state_dict
def __setstate__(self, state):
self.__dict__.update(state)
self.connections = {}
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if scheme in challenges:
yield AUTH_SCHEME_CLASSES[scheme](
cred, host, request_uri, headers, response, content, self
)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain, password=None):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain, password)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
i = 0
seen_bad_status_line = False
while i < RETRIES:
i += 1
try:
if hasattr(conn, "sock") and conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except ssl_SSLError:
conn.close()
raise
except socket.error as e:
err = 0
if hasattr(e, "args"):
err = getattr(e, "args")[0]
else:
err = e.errno
if err == errno.ECONNREFUSED: # Connection refused
raise
if err in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
continue # retry on potentially transient socket errors
except httplib.HTTPException:
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
if hasattr(conn, "sock") and conn.sock is None:
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
try:
response = conn.getresponse()
except httplib.BadStatusLine:
# If we get a BadStatusLine on the first try then that means
# the connection just went stale, so retry regardless of the
# number of RETRIES set.
if not seen_bad_status_line and i == 1:
i = 0
seen_bad_status_line = True
conn.close()
conn.connect()
continue
else:
conn.close()
raise
except (socket.error, httplib.HTTPException):
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
else:
content = ""
if method == "HEAD":
conn.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(
self,
conn,
host,
absolute_uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [
(auth.depth(request_uri), auth)
for auth in self.authorizations
if auth.inscope(host, request_uri)
]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(
host, request_uri, headers, response, content
):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (
self.follow_all_redirects
or method in self.safe_methods
or response.status in (303, 308)
):
if self.follow_redirects and response.status in self.redirect_codes:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if "location" not in response and response.status != 300:
raise RedirectMissingLocation(
_(
"Redirected but the response is missing a Location: header."
),
response,
content,
)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if "location" in response:
location = response["location"]
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response["location"] = urlparse.urljoin(
absolute_uri, location
)
if response.status == 308 or (response.status == 301 and method in self.safe_methods):
response["-x-permanent-redirect-url"] = response["location"]
if "content-location" not in response:
response["content-location"] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if "if-none-match" in headers:
del headers["if-none-match"]
if "if-modified-since" in headers:
del headers["if-modified-since"]
if (
"authorization" in headers
and not self.forward_authorization_headers
):
del headers["authorization"]
if "location" in response:
location = response["location"]
old_response = copy.deepcopy(response)
if "content-location" not in old_response:
old_response["content-location"] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(
location,
method=redirect_method,
body=body,
headers=headers,
redirections=redirections - 1,
)
response.previous = old_response
else:
raise RedirectLimit(
"Redirected more times than rediection_limit allows.",
response,
content,
)
elif response.status in [200, 203] and method in self.safe_methods:
# Don't cache 206's since we aren't going to handle byte range requests
if "content-location" not in response:
response["content-location"] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(
self,
uri,
method="GET",
body=None,
headers=None,
redirections=DEFAULT_MAX_REDIRECTS,
connection_type=None,
):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin with either
'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE,
etc. There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a
string object.
Any extra headers that are to be sent with the request should be
provided in the 'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ''
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if "user-agent" not in headers:
headers["user-agent"] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
# Prevent CWE-75 space injection to manipulate request via part of uri.
# Prevent CWE-93 CRLF injection to modify headers via part of uri.
uri = uri.replace(" ", "%20").replace("\r", "%0D").replace("\n", "%0A")
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
proxy_info = self._get_proxy_info(scheme, authority)
conn_key = scheme + ":" + authority
conn = self.connections.get(conn_key)
if conn is None:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if scheme == "https":
if certs:
conn = self.connections[conn_key] = connection_type(
authority,
key_file=certs[0][0],
cert_file=certs[0][1],
timeout=self.timeout,
proxy_info=proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
ssl_version=self.ssl_version,
key_password=certs[0][2],
)
else:
conn = self.connections[conn_key] = connection_type(
authority,
timeout=self.timeout,
proxy_info=proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
ssl_version=self.ssl_version,
)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout, proxy_info=proxy_info
)
conn.set_debuglevel(debuglevel)
if "range" not in headers and "accept-encoding" not in headers:
headers["accept-encoding"] = "gzip, deflate"
info = email.Message.Message()
cachekey = None
cached_value = None
if self.cache:
cachekey = defrag_uri.encode("utf-8")
cached_value = self.cache.get(cachekey)
if cached_value:
# info = email.message_from_string(cached_value)
#
# Need to replace the line above with the kludge below
# to fix the non-existent bug not fixed in this
# bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html
try:
info, content = cached_value.split("\r\n\r\n", 1)
feedparser = email.FeedParser.FeedParser()
feedparser.feed(info)
info = feedparser.close()
feedparser._parse = None
except (IndexError, ValueError):
self.cache.delete(cachekey)
cachekey = None
cached_value = None
if (
method in self.optimistic_concurrency_methods
and self.cache
and "etag" in info
and not self.ignore_etag
and "if-match" not in headers
):
# http://www.w3.org/1999/04/Editing/
headers["if-match"] = info["etag"]
# https://tools.ietf.org/html/rfc7234
# A cache MUST invalidate the effective Request URI as well as [...] Location and Content-Location
# when a non-error status code is received in response to an unsafe request method.
if self.cache and cachekey and method not in self.safe_methods:
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in self.safe_methods and "vary" in info:
vary = info["vary"]
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if (
self.cache
and cached_value
and (method in self.safe_methods or info["status"] == "308")
and "range" not in headers
):
redirect_method = method
if info["status"] not in ("307", "308"):
redirect_method = "GET"
if "-x-permanent-redirect-url" in info:
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit(
"Redirected more times than rediection_limit allows.",
{},
"",
)
(response, new_content) = self.request(
info["-x-permanent-redirect-url"],
method=redirect_method,
headers=headers,
redirections=redirections - 1,
)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info["status"] = "504"
content = ""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if (
"etag" in info
and not self.ignore_etag
and not "if-none-match" in headers
):
headers["if-none-match"] = info["etag"]
if "last-modified" in info and not "last-modified" in headers:
headers["if-modified-since"] = info["last-modified"]
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(
headers, merged_response, content, self.cache, cachekey
)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if "only-if-cached" in cc:
info["status"] = "504"
response = Response(info)
content = ""
else:
(response, content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
)
except Exception as e:
is_timeout = isinstance(e, socket.timeout)
if is_timeout:
conn = self.connections.pop(conn_key, None)
if conn:
conn.close()
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif is_timeout:
content = "Request Timeout"
response = Response(
{
"content-type": "text/plain",
"status": "408",
"content-length": len(content),
}
)
response.reason = "Request Timeout"
else:
content = str(e)
response = Response(
{
"content-type": "text/plain",
"status": "400",
"content-length": len(content),
}
)
response.reason = "Bad Request"
else:
raise
return (response, content)
def _get_proxy_info(self, scheme, authority):
"""Return a ProxyInfo instance (or None) based on the scheme
and authority.
"""
hostname, port = urllib.splitport(authority)
proxy_info = self.proxy_info
if callable(proxy_info):
proxy_info = proxy_info(scheme)
if hasattr(proxy_info, "applies_to") and not proxy_info.applies_to(hostname):
proxy_info = None
return proxy_info
class Response(dict):
"""An object more like email.Message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server.
10 for HTTP/1.0, 11 for HTTP/1.1.
"""
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.Message or
# an httplib.HTTPResponse object.
if isinstance(info, httplib.HTTPResponse):
for key, value in info.getheaders():
self[key.lower()] = value
self.status = info.status
self["status"] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.Message.Message):
for key, value in info.items():
self[key.lower()] = value
self.status = int(self["status"])
else:
for key, value in info.iteritems():
self[key.lower()] = value
self.status = int(self.get("status", self.status))
self.reason = self.get("reason", self.reason)
def __getattr__(self, name):
if name == "dict":
return self
else:
raise AttributeError(name)
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_3934_0 |
crossvul-python_data_good_4109_0 | """Module for Trivia cog."""
import asyncio
import math
import pathlib
from collections import Counter
from typing import List, Literal
import io
import yaml
import discord
from redbot.core import Config, commands, checks
from redbot.cogs.bank import is_owner_if_bank_global
from redbot.core.data_manager import cog_data_path
from redbot.core.i18n import Translator, cog_i18n
from redbot.core.utils import AsyncIter
from redbot.core.utils.chat_formatting import box, pagify, bold
from redbot.core.utils.menus import start_adding_reactions
from redbot.core.utils.predicates import MessagePredicate, ReactionPredicate
from .checks import trivia_stop_check
from .converters import finite_float
from .log import LOG
from .session import TriviaSession
__all__ = ["Trivia", "UNIQUE_ID", "get_core_lists"]
UNIQUE_ID = 0xB3C0E453
_ = Translator("Trivia", __file__)
class InvalidListError(Exception):
"""A Trivia list file is in invalid format."""
pass
@cog_i18n(_)
class Trivia(commands.Cog):
"""Play trivia with friends!"""
def __init__(self):
super().__init__()
self.trivia_sessions = []
self.config = Config.get_conf(self, identifier=UNIQUE_ID, force_registration=True)
self.config.register_guild(
max_score=10,
timeout=120.0,
delay=15.0,
bot_plays=False,
reveal_answer=True,
payout_multiplier=0.0,
allow_override=True,
)
self.config.register_member(wins=0, games=0, total_score=0)
async def red_delete_data_for_user(
self,
*,
requester: Literal["discord_deleted_user", "owner", "user", "user_strict"],
user_id: int,
):
if requester != "discord_deleted_user":
return
all_members = await self.config.all_members()
async for guild_id, guild_data in AsyncIter(all_members.items(), steps=100):
if user_id in guild_data:
await self.config.member_from_ids(guild_id, user_id).clear()
@commands.group()
@commands.guild_only()
@checks.mod_or_permissions(administrator=True)
async def triviaset(self, ctx: commands.Context):
"""Manage Trivia settings."""
@triviaset.command(name="showsettings")
async def triviaset_showsettings(self, ctx: commands.Context):
"""Show the current trivia settings."""
settings = self.config.guild(ctx.guild)
settings_dict = await settings.all()
msg = box(
_(
"Current settings\n"
"Bot gains points: {bot_plays}\n"
"Answer time limit: {delay} seconds\n"
"Lack of response timeout: {timeout} seconds\n"
"Points to win: {max_score}\n"
"Reveal answer on timeout: {reveal_answer}\n"
"Payout multiplier: {payout_multiplier}\n"
"Allow lists to override settings: {allow_override}"
).format(**settings_dict),
lang="py",
)
await ctx.send(msg)
@triviaset.command(name="maxscore")
async def triviaset_max_score(self, ctx: commands.Context, score: int):
"""Set the total points required to win."""
if score < 0:
await ctx.send(_("Score must be greater than 0."))
return
settings = self.config.guild(ctx.guild)
await settings.max_score.set(score)
await ctx.send(_("Done. Points required to win set to {num}.").format(num=score))
@triviaset.command(name="timelimit")
async def triviaset_timelimit(self, ctx: commands.Context, seconds: finite_float):
"""Set the maximum seconds permitted to answer a question."""
if seconds < 4.0:
await ctx.send(_("Must be at least 4 seconds."))
return
settings = self.config.guild(ctx.guild)
await settings.delay.set(seconds)
await ctx.send(_("Done. Maximum seconds to answer set to {num}.").format(num=seconds))
@triviaset.command(name="stopafter")
async def triviaset_stopafter(self, ctx: commands.Context, seconds: finite_float):
"""Set how long until trivia stops due to no response."""
settings = self.config.guild(ctx.guild)
if seconds < await settings.delay():
await ctx.send(_("Must be larger than the answer time limit."))
return
await settings.timeout.set(seconds)
await ctx.send(
_(
"Done. Trivia sessions will now time out after {num} seconds of no responses."
).format(num=seconds)
)
@triviaset.command(name="override")
async def triviaset_allowoverride(self, ctx: commands.Context, enabled: bool):
"""Allow/disallow trivia lists to override settings."""
settings = self.config.guild(ctx.guild)
await settings.allow_override.set(enabled)
if enabled:
await ctx.send(
_("Done. Trivia lists can now override the trivia settings for this server.")
)
else:
await ctx.send(
_(
"Done. Trivia lists can no longer override the trivia settings for this "
"server."
)
)
@triviaset.command(name="botplays", usage="<true_or_false>")
async def trivaset_bot_plays(self, ctx: commands.Context, enabled: bool):
"""Set whether or not the bot gains points.
If enabled, the bot will gain a point if no one guesses correctly.
"""
settings = self.config.guild(ctx.guild)
await settings.bot_plays.set(enabled)
if enabled:
await ctx.send(_("Done. I'll now gain a point if users don't answer in time."))
else:
await ctx.send(_("Alright, I won't embarass you at trivia anymore."))
@triviaset.command(name="revealanswer", usage="<true_or_false>")
async def trivaset_reveal_answer(self, ctx: commands.Context, enabled: bool):
"""Set whether or not the answer is revealed.
If enabled, the bot will reveal the answer if no one guesses correctly
in time.
"""
settings = self.config.guild(ctx.guild)
await settings.reveal_answer.set(enabled)
if enabled:
await ctx.send(_("Done. I'll reveal the answer if no one knows it."))
else:
await ctx.send(_("Alright, I won't reveal the answer to the questions anymore."))
@is_owner_if_bank_global()
@checks.admin_or_permissions(manage_guild=True)
@triviaset.command(name="payout")
async def triviaset_payout_multiplier(self, ctx: commands.Context, multiplier: finite_float):
"""Set the payout multiplier.
This can be any positive decimal number. If a user wins trivia when at
least 3 members are playing, they will receive credits. Set to 0 to
disable.
The number of credits is determined by multiplying their total score by
this multiplier.
"""
settings = self.config.guild(ctx.guild)
if multiplier < 0:
await ctx.send(_("Multiplier must be at least 0."))
return
await settings.payout_multiplier.set(multiplier)
if multiplier:
await ctx.send(_("Done. Payout multiplier set to {num}.").format(num=multiplier))
else:
await ctx.send(_("Done. I will no longer reward the winner with a payout."))
@triviaset.group(name="custom")
@commands.is_owner()
async def triviaset_custom(self, ctx: commands.Context):
"""Manage Custom Trivia lists."""
pass
@triviaset_custom.command(name="list")
async def custom_trivia_list(self, ctx: commands.Context):
"""List uploaded custom trivia."""
personal_lists = sorted([p.resolve().stem for p in cog_data_path(self).glob("*.yaml")])
no_lists_uploaded = _("No custom Trivia lists uploaded.")
if not personal_lists:
if await ctx.embed_requested():
await ctx.send(
embed=discord.Embed(
colour=await ctx.embed_colour(), description=no_lists_uploaded
)
)
else:
await ctx.send(no_lists_uploaded)
return
if await ctx.embed_requested():
await ctx.send(
embed=discord.Embed(
title=_("Uploaded trivia lists"),
colour=await ctx.embed_colour(),
description=", ".join(sorted(personal_lists)),
)
)
else:
msg = box(
bold(_("Uploaded trivia lists")) + "\n\n" + ", ".join(sorted(personal_lists))
)
if len(msg) > 1000:
await ctx.author.send(msg)
else:
await ctx.send(msg)
@commands.is_owner()
@triviaset_custom.command(name="upload", aliases=["add"])
async def trivia_upload(self, ctx: commands.Context):
"""Upload a trivia file."""
if not ctx.message.attachments:
await ctx.send(_("Supply a file with next message or type anything to cancel."))
try:
message = await ctx.bot.wait_for(
"message", check=MessagePredicate.same_context(ctx), timeout=30
)
except asyncio.TimeoutError:
await ctx.send(_("You took too long to upload a list."))
return
if not message.attachments:
await ctx.send(_("You have cancelled the upload process."))
return
parsedfile = message.attachments[0]
else:
parsedfile = ctx.message.attachments[0]
try:
await self._save_trivia_list(ctx=ctx, attachment=parsedfile)
except yaml.error.MarkedYAMLError as exc:
await ctx.send(_("Invalid syntax: ") + str(exc))
except yaml.error.YAMLError:
await ctx.send(
_("There was an error parsing the trivia list. See logs for more info.")
)
LOG.exception("Custom Trivia file %s failed to upload", parsedfile.filename)
@commands.is_owner()
@triviaset_custom.command(name="delete", aliases=["remove"])
async def trivia_delete(self, ctx: commands.Context, name: str):
"""Delete a trivia file."""
filepath = cog_data_path(self) / f"{name}.yaml"
if filepath.exists():
filepath.unlink()
await ctx.send(_("Trivia {filename} was deleted.").format(filename=filepath.stem))
else:
await ctx.send(_("Trivia file was not found."))
@commands.group(invoke_without_command=True)
@commands.guild_only()
async def trivia(self, ctx: commands.Context, *categories: str):
"""Start trivia session on the specified category.
You may list multiple categories, in which case the trivia will involve
questions from all of them.
"""
if not categories:
await ctx.send_help()
return
categories = [c.lower() for c in categories]
session = self._get_trivia_session(ctx.channel)
if session is not None:
await ctx.send(_("There is already an ongoing trivia session in this channel."))
return
trivia_dict = {}
authors = []
for category in reversed(categories):
# We reverse the categories so that the first list's config takes
# priority over the others.
try:
dict_ = self.get_trivia_list(category)
except FileNotFoundError:
await ctx.send(
_(
"Invalid category `{name}`. See `{prefix}trivia list` for a list of "
"trivia categories."
).format(name=category, prefix=ctx.clean_prefix)
)
except InvalidListError:
await ctx.send(
_(
"There was an error parsing the trivia list for the `{name}` category. It "
"may be formatted incorrectly."
).format(name=category)
)
else:
trivia_dict.update(dict_)
authors.append(trivia_dict.pop("AUTHOR", None))
continue
return
if not trivia_dict:
await ctx.send(
_("The trivia list was parsed successfully, however it appears to be empty!")
)
return
settings = await self.config.guild(ctx.guild).all()
config = trivia_dict.pop("CONFIG", None)
if config and settings["allow_override"]:
settings.update(config)
settings["lists"] = dict(zip(categories, reversed(authors)))
session = TriviaSession.start(ctx, trivia_dict, settings)
self.trivia_sessions.append(session)
LOG.debug("New trivia session; #%s in %d", ctx.channel, ctx.guild.id)
@trivia_stop_check()
@trivia.command(name="stop")
async def trivia_stop(self, ctx: commands.Context):
"""Stop an ongoing trivia session."""
session = self._get_trivia_session(ctx.channel)
if session is None:
await ctx.send(_("There is no ongoing trivia session in this channel."))
return
await session.end_game()
session.force_stop()
await ctx.send(_("Trivia stopped."))
@trivia.command(name="list")
async def trivia_list(self, ctx: commands.Context):
"""List available trivia categories."""
lists = set(p.stem for p in self._all_lists())
if await ctx.embed_requested():
await ctx.send(
embed=discord.Embed(
title=_("Available trivia lists"),
colour=await ctx.embed_colour(),
description=", ".join(sorted(lists)),
)
)
else:
msg = box(bold(_("Available trivia lists")) + "\n\n" + ", ".join(sorted(lists)))
if len(msg) > 1000:
await ctx.author.send(msg)
else:
await ctx.send(msg)
@trivia.group(
name="leaderboard", aliases=["lboard"], autohelp=False, invoke_without_command=True
)
async def trivia_leaderboard(self, ctx: commands.Context):
"""Leaderboard for trivia.
Defaults to the top 10 of this server, sorted by total wins. Use
subcommands for a more customised leaderboard.
"""
cmd = self.trivia_leaderboard_server
if isinstance(ctx.channel, discord.abc.PrivateChannel):
cmd = self.trivia_leaderboard_global
await ctx.invoke(cmd, "wins", 10)
@trivia_leaderboard.command(name="server")
@commands.guild_only()
async def trivia_leaderboard_server(
self, ctx: commands.Context, sort_by: str = "wins", top: int = 10
):
"""Leaderboard for this server.
`<sort_by>` can be any of the following fields:
- `wins` : total wins
- `avg` : average score
- `total` : total correct answers
- `games` : total games played
`<top>` is the number of ranks to show on the leaderboard.
"""
key = self._get_sort_key(sort_by)
if key is None:
await ctx.send(
_(
"Unknown field `{field_name}`, see `{prefix}help trivia leaderboard server` "
"for valid fields to sort by."
).format(field_name=sort_by, prefix=ctx.clean_prefix)
)
return
guild = ctx.guild
data = await self.config.all_members(guild)
data = {guild.get_member(u): d for u, d in data.items()}
data.pop(None, None) # remove any members which aren't in the guild
await self.send_leaderboard(ctx, data, key, top)
@trivia_leaderboard.command(name="global")
async def trivia_leaderboard_global(
self, ctx: commands.Context, sort_by: str = "wins", top: int = 10
):
"""Global trivia leaderboard.
`<sort_by>` can be any of the following fields:
- `wins` : total wins
- `avg` : average score
- `total` : total correct answers from all sessions
- `games` : total games played
`<top>` is the number of ranks to show on the leaderboard.
"""
key = self._get_sort_key(sort_by)
if key is None:
await ctx.send(
_(
"Unknown field `{field_name}`, see `{prefix}help trivia leaderboard server` "
"for valid fields to sort by."
).format(field_name=sort_by, prefix=ctx.clean_prefix)
)
return
data = await self.config.all_members()
collated_data = {}
for guild_id, guild_data in data.items():
guild = ctx.bot.get_guild(guild_id)
if guild is None:
continue
for member_id, member_data in guild_data.items():
member = guild.get_member(member_id)
if member is None:
continue
collated_member_data = collated_data.get(member, Counter())
for v_key, value in member_data.items():
collated_member_data[v_key] += value
collated_data[member] = collated_member_data
await self.send_leaderboard(ctx, collated_data, key, top)
@staticmethod
def _get_sort_key(key: str):
key = key.lower()
if key in ("wins", "average_score", "total_score", "games"):
return key
elif key in ("avg", "average"):
return "average_score"
elif key in ("total", "score", "answers", "correct"):
return "total_score"
async def send_leaderboard(self, ctx: commands.Context, data: dict, key: str, top: int):
"""Send the leaderboard from the given data.
Parameters
----------
ctx : commands.Context
The context to send the leaderboard to.
data : dict
The data for the leaderboard. This must map `discord.Member` ->
`dict`.
key : str
The field to sort the data by. Can be ``wins``, ``total_score``,
``games`` or ``average_score``.
top : int
The number of members to display on the leaderboard.
Returns
-------
`list` of `discord.Message`
The sent leaderboard messages.
"""
if not data:
await ctx.send(_("There are no scores on record!"))
return
leaderboard = self._get_leaderboard(data, key, top)
ret = []
for page in pagify(leaderboard, shorten_by=10):
ret.append(await ctx.send(box(page, lang="py")))
return ret
@staticmethod
def _get_leaderboard(data: dict, key: str, top: int):
# Mix in average score
for member, stats in data.items():
if stats["games"] != 0:
stats["average_score"] = stats["total_score"] / stats["games"]
else:
stats["average_score"] = 0.0
# Sort by reverse order of priority
priority = ["average_score", "total_score", "wins", "games"]
try:
priority.remove(key)
except ValueError:
raise ValueError(f"{key} is not a valid key.")
# Put key last in reverse priority
priority.append(key)
items = data.items()
for key in priority:
items = sorted(items, key=lambda t: t[1][key], reverse=True)
max_name_len = max(map(lambda m: len(str(m)), data.keys()))
# Headers
headers = (
_("Rank"),
_("Member") + " " * (max_name_len - 6),
_("Wins"),
_("Games Played"),
_("Total Score"),
_("Average Score"),
)
lines = [" | ".join(headers), " | ".join(("-" * len(h) for h in headers))]
# Header underlines
for rank, tup in enumerate(items, 1):
member, m_data = tup
# Align fields to header width
fields = tuple(
map(
str,
(
rank,
member,
m_data["wins"],
m_data["games"],
m_data["total_score"],
round(m_data["average_score"], 2),
),
)
)
padding = [" " * (len(h) - len(f)) for h, f in zip(headers, fields)]
fields = tuple(f + padding[i] for i, f in enumerate(fields))
lines.append(" | ".join(fields))
if rank == top:
break
return "\n".join(lines)
@commands.Cog.listener()
async def on_trivia_end(self, session: TriviaSession):
"""Event for a trivia session ending.
This method removes the session from this cog's sessions, and
cancels any tasks which it was running.
Parameters
----------
session : TriviaSession
The session which has just ended.
"""
channel = session.ctx.channel
LOG.debug("Ending trivia session; #%s in %s", channel, channel.guild.id)
if session in self.trivia_sessions:
self.trivia_sessions.remove(session)
if session.scores:
await self.update_leaderboard(session)
async def update_leaderboard(self, session):
"""Update the leaderboard with the given scores.
Parameters
----------
session : TriviaSession
The trivia session to update scores from.
"""
max_score = session.settings["max_score"]
for member, score in session.scores.items():
if member.id == session.ctx.bot.user.id:
continue
stats = await self.config.member(member).all()
if score == max_score:
stats["wins"] += 1
stats["total_score"] += score
stats["games"] += 1
await self.config.member(member).set(stats)
def get_trivia_list(self, category: str) -> dict:
"""Get the trivia list corresponding to the given category.
Parameters
----------
category : str
The desired category. Case sensitive.
Returns
-------
`dict`
A dict mapping questions (`str`) to answers (`list` of `str`).
"""
try:
path = next(p for p in self._all_lists() if p.stem == category)
except StopIteration:
raise FileNotFoundError("Could not find the `{}` category.".format(category))
with path.open(encoding="utf-8") as file:
try:
dict_ = yaml.safe_load(file)
except yaml.error.YAMLError as exc:
raise InvalidListError("YAML parsing failed.") from exc
else:
return dict_
async def _save_trivia_list(
self, ctx: commands.Context, attachment: discord.Attachment
) -> None:
"""Checks and saves a trivia list to data folder.
Parameters
----------
file : discord.Attachment
A discord message attachment.
Returns
-------
None
"""
filename = attachment.filename.rsplit(".", 1)[0]
# Check if trivia filename exists in core files or if it is a command
if filename in self.trivia.all_commands or any(
filename == item.stem for item in get_core_lists()
):
await ctx.send(
_(
"{filename} is a reserved trivia name and cannot be replaced.\n"
"Choose another name."
).format(filename=filename)
)
return
file = cog_data_path(self) / f"{filename}.yaml"
if file.exists():
overwrite_message = _("{filename} already exists. Do you wish to overwrite?").format(
filename=filename
)
can_react = ctx.channel.permissions_for(ctx.me).add_reactions
if not can_react:
overwrite_message += " (y/n)"
overwrite_message_object: discord.Message = await ctx.send(overwrite_message)
if can_react:
# noinspection PyAsyncCall
start_adding_reactions(
overwrite_message_object, ReactionPredicate.YES_OR_NO_EMOJIS
)
pred = ReactionPredicate.yes_or_no(overwrite_message_object, ctx.author)
event = "reaction_add"
else:
pred = MessagePredicate.yes_or_no(ctx=ctx)
event = "message"
try:
await ctx.bot.wait_for(event, check=pred, timeout=30)
except asyncio.TimeoutError:
await ctx.send(_("You took too long answering."))
return
if pred.result is False:
await ctx.send(_("I am not replacing the existing file."))
return
buffer = io.BytesIO(await attachment.read())
yaml.safe_load(buffer)
buffer.seek(0)
with file.open("wb") as fp:
fp.write(buffer.read())
await ctx.send(_("Saved Trivia list as {filename}.").format(filename=filename))
def _get_trivia_session(self, channel: discord.TextChannel) -> TriviaSession:
return next(
(session for session in self.trivia_sessions if session.ctx.channel == channel), None
)
def _all_lists(self) -> List[pathlib.Path]:
personal_lists = [p.resolve() for p in cog_data_path(self).glob("*.yaml")]
return personal_lists + get_core_lists()
def cog_unload(self):
for session in self.trivia_sessions:
session.force_stop()
def get_core_lists() -> List[pathlib.Path]:
"""Return a list of paths for all trivia lists packaged with the bot."""
core_lists_path = pathlib.Path(__file__).parent.resolve() / "data/lists"
return list(core_lists_path.glob("*.yaml"))
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_4109_0 |
crossvul-python_data_bad_2223_1 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import sys
import re
import os
import shlex
import yaml
import copy
import optparse
import operator
from ansible import errors
from ansible import __version__
from ansible.utils import template
from ansible.utils.display_functions import *
from ansible.utils.plugins import *
from ansible.callbacks import display
import ansible.constants as C
import ast
import time
import StringIO
import stat
import termios
import tty
import pipes
import random
import difflib
import warnings
import traceback
import getpass
import sys
import json
#import vault
from vault import VaultLib
VERBOSITY=0
MAX_FILE_SIZE_FOR_DIFF=1*1024*1024
try:
import json
except ImportError:
import simplejson as json
try:
from hashlib import md5 as _md5
except ImportError:
from md5 import md5 as _md5
PASSLIB_AVAILABLE = False
try:
import passlib.hash
PASSLIB_AVAILABLE = True
except:
pass
KEYCZAR_AVAILABLE=False
try:
try:
# some versions of pycrypto may not have this?
from Crypto.pct_warnings import PowmInsecureWarning
except ImportError:
PowmInsecureWarning = RuntimeWarning
with warnings.catch_warnings(record=True) as warning_handler:
warnings.simplefilter("error", PowmInsecureWarning)
try:
import keyczar.errors as key_errors
from keyczar.keys import AesKey
except PowmInsecureWarning:
system_warning(
"The version of gmp you have installed has a known issue regarding " + \
"timing vulnerabilities when used with pycrypto. " + \
"If possible, you should update it (ie. yum update gmp)."
)
warnings.resetwarnings()
warnings.simplefilter("ignore")
import keyczar.errors as key_errors
from keyczar.keys import AesKey
KEYCZAR_AVAILABLE=True
except ImportError:
pass
###############################################################
# Abstractions around keyczar
###############################################################
def key_for_hostname(hostname):
# fireball mode is an implementation of ansible firing up zeromq via SSH
# to use no persistent daemons or key management
if not KEYCZAR_AVAILABLE:
raise errors.AnsibleError("python-keyczar must be installed on the control machine to use accelerated modes")
key_path = os.path.expanduser(C.ACCELERATE_KEYS_DIR)
if not os.path.exists(key_path):
os.makedirs(key_path, mode=0700)
os.chmod(key_path, int(C.ACCELERATE_KEYS_DIR_PERMS, 8))
elif not os.path.isdir(key_path):
raise errors.AnsibleError('ACCELERATE_KEYS_DIR is not a directory.')
if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_DIR_PERMS, 8):
raise errors.AnsibleError('Incorrect permissions on the private key directory. Use `chmod 0%o %s` to correct this issue, and make sure any of the keys files contained within that directory are set to 0%o' % (int(C.ACCELERATE_KEYS_DIR_PERMS, 8), C.ACCELERATE_KEYS_DIR, int(C.ACCELERATE_KEYS_FILE_PERMS, 8)))
key_path = os.path.join(key_path, hostname)
# use new AES keys every 2 hours, which means fireball must not allow running for longer either
if not os.path.exists(key_path) or (time.time() - os.path.getmtime(key_path) > 60*60*2):
key = AesKey.Generate()
fd = os.open(key_path, os.O_WRONLY | os.O_CREAT, int(C.ACCELERATE_KEYS_FILE_PERMS, 8))
fh = os.fdopen(fd, 'w')
fh.write(str(key))
fh.close()
return key
else:
if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_FILE_PERMS, 8):
raise errors.AnsibleError('Incorrect permissions on the key file for this host. Use `chmod 0%o %s` to correct this issue.' % (int(C.ACCELERATE_KEYS_FILE_PERMS, 8), key_path))
fh = open(key_path)
key = AesKey.Read(fh.read())
fh.close()
return key
def encrypt(key, msg):
return key.Encrypt(msg)
def decrypt(key, msg):
try:
return key.Decrypt(msg)
except key_errors.InvalidSignatureError:
raise errors.AnsibleError("decryption failed")
###############################################################
# UTILITY FUNCTIONS FOR COMMAND LINE TOOLS
###############################################################
def err(msg):
''' print an error message to stderr '''
print >> sys.stderr, msg
def exit(msg, rc=1):
''' quit with an error to stdout and a failure code '''
err(msg)
sys.exit(rc)
def jsonify(result, format=False):
''' format JSON output (uncompressed or uncompressed) '''
if result is None:
return "{}"
result2 = result.copy()
for key, value in result2.items():
if type(value) is str:
result2[key] = value.decode('utf-8', 'ignore')
if format:
return json.dumps(result2, sort_keys=True, indent=4)
else:
return json.dumps(result2, sort_keys=True)
def write_tree_file(tree, hostname, buf):
''' write something into treedir/hostname '''
# TODO: might be nice to append playbook runs per host in a similar way
# in which case, we'd want append mode.
path = os.path.join(tree, hostname)
fd = open(path, "w+")
fd.write(buf)
fd.close()
def is_failed(result):
''' is a given JSON result a failed result? '''
return ((result.get('rc', 0) != 0) or (result.get('failed', False) in [ True, 'True', 'true']))
def is_changed(result):
''' is a given JSON result a changed result? '''
return (result.get('changed', False) in [ True, 'True', 'true'])
def check_conditional(conditional, basedir, inject, fail_on_undefined=False):
if conditional is None or conditional == '':
return True
if isinstance(conditional, list):
for x in conditional:
if not check_conditional(x, basedir, inject, fail_on_undefined=fail_on_undefined):
return False
return True
if not isinstance(conditional, basestring):
return conditional
conditional = conditional.replace("jinja2_compare ","")
# allow variable names
if conditional in inject and '-' not in str(inject[conditional]):
conditional = inject[conditional]
conditional = template.template(basedir, conditional, inject, fail_on_undefined=fail_on_undefined)
original = str(conditional).replace("jinja2_compare ","")
# a Jinja2 evaluation that results in something Python can eval!
presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional
conditional = template.template(basedir, presented, inject)
val = conditional.strip()
if val == presented:
# the templating failed, meaning most likely a
# variable was undefined. If we happened to be
# looking for an undefined variable, return True,
# otherwise fail
if "is undefined" in conditional:
return True
elif "is defined" in conditional:
return False
else:
raise errors.AnsibleError("error while evaluating conditional: %s" % original)
elif val == "True":
return True
elif val == "False":
return False
else:
raise errors.AnsibleError("unable to evaluate conditional: %s" % original)
def is_executable(path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def unfrackpath(path):
'''
returns a path that is free of symlinks, environment
variables, relative path traversals and symbols (~)
example:
'$HOME/../../var/mail' becomes '/var/spool/mail'
'''
return os.path.normpath(os.path.realpath(os.path.expandvars(os.path.expanduser(path))))
def prepare_writeable_dir(tree,mode=0777):
''' make sure a directory exists and is writeable '''
# modify the mode to ensure the owner at least
# has read/write access to this directory
mode |= 0700
# make sure the tree path is always expanded
# and normalized and free of symlinks
tree = unfrackpath(tree)
if not os.path.exists(tree):
try:
os.makedirs(tree, mode)
except (IOError, OSError), e:
raise errors.AnsibleError("Could not make dir %s: %s" % (tree, e))
if not os.access(tree, os.W_OK):
raise errors.AnsibleError("Cannot write to path %s" % tree)
return tree
def path_dwim(basedir, given):
'''
make relative paths work like folks expect.
'''
if given.startswith("/"):
return os.path.abspath(given)
elif given.startswith("~"):
return os.path.abspath(os.path.expanduser(given))
else:
if basedir is None:
basedir = "."
return os.path.abspath(os.path.join(basedir, given))
def path_dwim_relative(original, dirname, source, playbook_base, check=True):
''' find one file in a directory one level up in a dir named dirname relative to current '''
# (used by roles code)
basedir = os.path.dirname(original)
if os.path.islink(basedir):
basedir = unfrackpath(basedir)
template2 = os.path.join(basedir, dirname, source)
else:
template2 = os.path.join(basedir, '..', dirname, source)
source2 = path_dwim(basedir, template2)
if os.path.exists(source2):
return source2
obvious_local_path = path_dwim(playbook_base, source)
if os.path.exists(obvious_local_path):
return obvious_local_path
if check:
raise errors.AnsibleError("input file not found at %s or %s" % (source2, obvious_local_path))
return source2 # which does not exist
def json_loads(data):
''' parse a JSON string and return a data structure '''
return json.loads(data)
def parse_json(raw_data):
''' this version for module return data only '''
orig_data = raw_data
# ignore stuff like tcgetattr spewage or other warnings
data = filter_leading_non_json_lines(raw_data)
try:
return json.loads(data)
except:
# not JSON, but try "Baby JSON" which allows many of our modules to not
# require JSON and makes writing modules in bash much simpler
results = {}
try:
tokens = shlex.split(data)
except:
print "failed to parse json: "+ data
raise
for t in tokens:
if "=" not in t:
raise errors.AnsibleError("failed to parse: %s" % orig_data)
(key,value) = t.split("=", 1)
if key == 'changed' or 'failed':
if value.lower() in [ 'true', '1' ]:
value = True
elif value.lower() in [ 'false', '0' ]:
value = False
if key == 'rc':
value = int(value)
results[key] = value
if len(results.keys()) == 0:
return { "failed" : True, "parsed" : False, "msg" : orig_data }
return results
def smush_braces(data):
''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed weird by key=value code '''
while '{{ ' in data:
data = data.replace('{{ ', '{{')
while ' }}' in data:
data = data.replace(' }}', '}}')
return data
def smush_ds(data):
# things like key={{ foo }} are not handled by shlex.split well, so preprocess any YAML we load
# so we do not have to call smush elsewhere
if type(data) == list:
return [ smush_ds(x) for x in data ]
elif type(data) == dict:
for (k,v) in data.items():
data[k] = smush_ds(v)
return data
elif isinstance(data, basestring):
return smush_braces(data)
else:
return data
def parse_yaml(data, path_hint=None):
''' convert a yaml string to a data structure. Also supports JSON, ssssssh!!!'''
stripped_data = data.lstrip()
loaded = None
if stripped_data.startswith("{") or stripped_data.startswith("["):
# since the line starts with { or [ we can infer this is a JSON document.
try:
loaded = json.loads(data)
except ValueError, ve:
if path_hint:
raise errors.AnsibleError(path_hint + ": " + str(ve))
else:
raise errors.AnsibleError(str(ve))
else:
# else this is pretty sure to be a YAML document
loaded = yaml.safe_load(data)
return smush_ds(loaded)
def process_common_errors(msg, probline, column):
replaced = probline.replace(" ","")
if ":{{" in replaced and "}}" in replaced:
msg = msg + """
This one looks easy to fix. YAML thought it was looking for the start of a
hash/dictionary and was confused to see a second "{". Most likely this was
meant to be an ansible template evaluation instead, so we have to give the
parser a small hint that we wanted a string instead. The solution here is to
just quote the entire value.
For instance, if the original line was:
app_path: {{ base_path }}/foo
It should be written as:
app_path: "{{ base_path }}/foo"
"""
return msg
elif len(probline) and len(probline) > 1 and len(probline) > column and probline[column] == ":" and probline.count(':') > 1:
msg = msg + """
This one looks easy to fix. There seems to be an extra unquoted colon in the line
and this is confusing the parser. It was only expecting to find one free
colon. The solution is just add some quotes around the colon, or quote the
entire line after the first colon.
For instance, if the original line was:
copy: src=file.txt dest=/path/filename:with_colon.txt
It can be written as:
copy: src=file.txt dest='/path/filename:with_colon.txt'
Or:
copy: 'src=file.txt dest=/path/filename:with_colon.txt'
"""
return msg
else:
parts = probline.split(":")
if len(parts) > 1:
middle = parts[1].strip()
match = False
unbalanced = False
if middle.startswith("'") and not middle.endswith("'"):
match = True
elif middle.startswith('"') and not middle.endswith('"'):
match = True
if len(middle) > 0 and middle[0] in [ '"', "'" ] and middle[-1] in [ '"', "'" ] and probline.count("'") > 2 or probline.count('"') > 2:
unbalanced = True
if match:
msg = msg + """
This one looks easy to fix. It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote. For instance:
when: "ok" in result.stdout
Could be written as:
when: '"ok" in result.stdout'
or equivalently:
when: "'ok' in result.stdout"
"""
return msg
if unbalanced:
msg = msg + """
We could be wrong, but this one looks like it might be an issue with
unbalanced quotes. If starting a value with a quote, make sure the
line ends with the same set of quotes. For instance this arbitrary
example:
foo: "bad" "wolf"
Could be written as:
foo: '"bad" "wolf"'
"""
return msg
return msg
def process_yaml_error(exc, data, path=None, show_content=True):
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
if show_content:
if mark.line -1 >= 0:
before_probline = data.split("\n")[mark.line-1]
else:
before_probline = ''
probline = data.split("\n")[mark.line]
arrow = " " * mark.column + "^"
msg = """Syntax Error while loading YAML script, %s
Note: The error may actually appear before this position: line %s, column %s
%s
%s
%s""" % (path, mark.line + 1, mark.column + 1, before_probline, probline, arrow)
unquoted_var = None
if '{{' in probline and '}}' in probline:
if '"{{' not in probline or "'{{" not in probline:
unquoted_var = True
if not unquoted_var:
msg = process_common_errors(msg, probline, mark.column)
else:
msg = msg + """
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
"""
else:
# most likely displaying a file with sensitive content,
# so don't show any of the actual lines of yaml just the
# line number itself
msg = """Syntax error while loading YAML script, %s
The error appears to have been on line %s, column %s, but may actually
be before there depending on the exact syntax problem.
""" % (path, mark.line + 1, mark.column + 1)
else:
# No problem markers means we have to throw a generic
# "stuff messed up" type message. Sry bud.
if path:
msg = "Could not parse YAML. Check over %s again." % path
else:
msg = "Could not parse YAML."
raise errors.AnsibleYAMLValidationFailed(msg)
def parse_yaml_from_file(path, vault_password=None):
''' convert a yaml file to a data structure '''
data = None
show_content = True
try:
data = open(path).read()
except IOError:
raise errors.AnsibleError("file could not read: %s" % path)
vault = VaultLib(password=vault_password)
if vault.is_encrypted(data):
data = vault.decrypt(data)
show_content = False
try:
return parse_yaml(data, path_hint=path)
except yaml.YAMLError, exc:
process_yaml_error(exc, data, path, show_content)
def parse_kv(args):
''' convert a string of key/value items to a dict '''
options = {}
if args is not None:
# attempting to split a unicode here does bad things
args = args.encode('utf-8')
try:
vargs = shlex.split(args, posix=True)
except ValueError, ve:
if 'no closing quotation' in str(ve).lower():
raise errors.AnsibleError("error parsing argument string, try quoting the entire line.")
else:
raise
vargs = [x.decode('utf-8') for x in vargs]
for x in vargs:
if "=" in x:
k, v = x.split("=",1)
options[k]=v
return options
def merge_hash(a, b):
''' recursively merges hash b into a
keys from b take precedence over keys from a '''
result = copy.deepcopy(a)
# next, iterate over b keys and values
for k, v in b.iteritems():
# if there's already such key in a
# and that key contains dict
if k in result and isinstance(result[k], dict):
# merge those dicts recursively
result[k] = merge_hash(a[k], v)
else:
# otherwise, just copy a value from b to a
result[k] = v
return result
def md5s(data):
''' Return MD5 hex digest of data. '''
digest = _md5()
try:
digest.update(data)
except UnicodeEncodeError:
digest.update(data.encode('utf-8'))
return digest.hexdigest()
def md5(filename):
''' Return MD5 hex digest of local file, None if file is not present or a directory. '''
if not os.path.exists(filename) or os.path.isdir(filename):
return None
digest = _md5()
blocksize = 64 * 1024
try:
infile = open(filename, 'rb')
block = infile.read(blocksize)
while block:
digest.update(block)
block = infile.read(blocksize)
infile.close()
except IOError, e:
raise errors.AnsibleError("error while accessing the file %s, error was: %s" % (filename, e))
return digest.hexdigest()
def default(value, function):
''' syntactic sugar around lazy evaluation of defaults '''
if value is None:
return function()
return value
def _gitinfo():
''' returns a string containing git branch, commit id and commit date '''
result = None
repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git')
if os.path.exists(repo_path):
# Check if the .git is a file. If it is a file, it means that we are in a submodule structure.
if os.path.isfile(repo_path):
try:
gitdir = yaml.safe_load(open(repo_path)).get('gitdir')
# There is a posibility the .git file to have an absolute path.
if os.path.isabs(gitdir):
repo_path = gitdir
else:
repo_path = os.path.join(repo_path.split('.git')[0], gitdir)
except (IOError, AttributeError):
return ''
f = open(os.path.join(repo_path, "HEAD"))
branch = f.readline().split('/')[-1].rstrip("\n")
f.close()
branch_path = os.path.join(repo_path, "refs", "heads", branch)
if os.path.exists(branch_path):
f = open(branch_path)
commit = f.readline()[:10]
f.close()
date = time.localtime(os.stat(branch_path).st_mtime)
if time.daylight == 0:
offset = time.timezone
else:
offset = time.altzone
result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit,
time.strftime("%Y/%m/%d %H:%M:%S", date), offset / -36)
else:
result = ''
return result
def version(prog):
result = "{0} {1}".format(prog, __version__)
gitinfo = _gitinfo()
if gitinfo:
result = result + " {0}".format(gitinfo)
return result
def getch():
''' read in a single character '''
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def sanitize_output(str):
''' strips private info out of a string '''
private_keys = ['password', 'login_password']
filter_re = [
# filter out things like user:pass@foo/whatever
# and http://username:pass@wherever/foo
re.compile('^(?P<before>.*:)(?P<password>.*)(?P<after>\@.*)$'),
]
parts = str.split()
output = ''
for part in parts:
try:
(k,v) = part.split('=', 1)
if k in private_keys:
output += " %s=VALUE_HIDDEN" % k
else:
found = False
for filter in filter_re:
m = filter.match(v)
if m:
d = m.groupdict()
output += " %s=%s" % (k, d['before'] + "********" + d['after'])
found = True
break
if not found:
output += " %s" % part
except:
output += " %s" % part
return output.strip()
####################################################################
# option handling code for /usr/bin/ansible and ansible-playbook
# below this line
class SortedOptParser(optparse.OptionParser):
'''Optparser which sorts the options by opt before outputting --help'''
def format_help(self, formatter=None):
self.option_list.sort(key=operator.methodcaller('get_opt_string'))
return optparse.OptionParser.format_help(self, formatter=None)
def increment_debug(option, opt, value, parser):
global VERBOSITY
VERBOSITY += 1
def base_parser(constants=C, usage="", output_opts=False, runas_opts=False,
async_opts=False, connect_opts=False, subset_opts=False, check_opts=False, diff_opts=False):
''' create an options parser for any ansible script '''
parser = SortedOptParser(usage, version=version("%prog"))
parser.add_option('-v','--verbose', default=False, action="callback",
callback=increment_debug, help="verbose mode (-vvv for more, -vvvv to enable connection debugging)")
parser.add_option('-f','--forks', dest='forks', default=constants.DEFAULT_FORKS, type='int',
help="specify number of parallel processes to use (default=%s)" % constants.DEFAULT_FORKS)
parser.add_option('-i', '--inventory-file', dest='inventory',
help="specify inventory host file (default=%s)" % constants.DEFAULT_HOST_LIST,
default=constants.DEFAULT_HOST_LIST)
parser.add_option('-k', '--ask-pass', default=False, dest='ask_pass', action='store_true',
help='ask for SSH password')
parser.add_option('--private-key', default=C.DEFAULT_PRIVATE_KEY_FILE, dest='private_key_file',
help='use this file to authenticate the connection')
parser.add_option('-K', '--ask-sudo-pass', default=False, dest='ask_sudo_pass', action='store_true',
help='ask for sudo password')
parser.add_option('--ask-su-pass', default=False, dest='ask_su_pass', action='store_true',
help='ask for su password')
parser.add_option('--ask-vault-pass', default=False, dest='ask_vault_pass', action='store_true',
help='ask for vault password')
parser.add_option('--vault-password-file', default=None, dest='vault_password_file',
help="vault password file")
parser.add_option('--list-hosts', dest='listhosts', action='store_true',
help='outputs a list of matching hosts; does not execute anything else')
parser.add_option('-M', '--module-path', dest='module_path',
help="specify path(s) to module library (default=%s)" % constants.DEFAULT_MODULE_PATH,
default=None)
if subset_opts:
parser.add_option('-l', '--limit', default=constants.DEFAULT_SUBSET, dest='subset',
help='further limit selected hosts to an additional pattern')
parser.add_option('-T', '--timeout', default=constants.DEFAULT_TIMEOUT, type='int',
dest='timeout',
help="override the SSH timeout in seconds (default=%s)" % constants.DEFAULT_TIMEOUT)
if output_opts:
parser.add_option('-o', '--one-line', dest='one_line', action='store_true',
help='condense output')
parser.add_option('-t', '--tree', dest='tree', default=None,
help='log output to this directory')
if runas_opts:
parser.add_option("-s", "--sudo", default=constants.DEFAULT_SUDO, action="store_true",
dest='sudo', help="run operations with sudo (nopasswd)")
parser.add_option('-U', '--sudo-user', dest='sudo_user', default=None,
help='desired sudo user (default=root)') # Can't default to root because we need to detect when this option was given
parser.add_option('-u', '--user', default=constants.DEFAULT_REMOTE_USER,
dest='remote_user', help='connect as this user (default=%s)' % constants.DEFAULT_REMOTE_USER)
parser.add_option('-S', '--su', default=constants.DEFAULT_SU,
action='store_true', help='run operations with su')
parser.add_option('-R', '--su-user', help='run operations with su as this '
'user (default=%s)' % constants.DEFAULT_SU_USER)
if connect_opts:
parser.add_option('-c', '--connection', dest='connection',
default=C.DEFAULT_TRANSPORT,
help="connection type to use (default=%s)" % C.DEFAULT_TRANSPORT)
if async_opts:
parser.add_option('-P', '--poll', default=constants.DEFAULT_POLL_INTERVAL, type='int',
dest='poll_interval',
help="set the poll interval if using -B (default=%s)" % constants.DEFAULT_POLL_INTERVAL)
parser.add_option('-B', '--background', dest='seconds', type='int', default=0,
help='run asynchronously, failing after X seconds (default=N/A)')
if check_opts:
parser.add_option("-C", "--check", default=False, dest='check', action='store_true',
help="don't make any changes; instead, try to predict some of the changes that may occur"
)
if diff_opts:
parser.add_option("-D", "--diff", default=False, dest='diff', action='store_true',
help="when changing (small) files and templates, show the differences in those files; works great with --check"
)
return parser
def ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=False, confirm_vault=False, confirm_new=False):
vault_pass = None
new_vault_pass = None
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
if ask_vault_pass and confirm_vault:
vault_pass2 = getpass.getpass(prompt="Confirm Vault password: ")
if vault_pass != vault_pass2:
raise errors.AnsibleError("Passwords do not match")
if ask_new_vault_pass:
new_vault_pass = getpass.getpass(prompt="New Vault password: ")
if ask_new_vault_pass and confirm_new:
new_vault_pass2 = getpass.getpass(prompt="Confirm New Vault password: ")
if new_vault_pass != new_vault_pass2:
raise errors.AnsibleError("Passwords do not match")
# enforce no newline chars at the end of passwords
if vault_pass:
vault_pass = vault_pass.strip()
if new_vault_pass:
new_vault_pass = new_vault_pass.strip()
return vault_pass, new_vault_pass
def ask_passwords(ask_pass=False, ask_sudo_pass=False, ask_su_pass=False, ask_vault_pass=False):
sshpass = None
sudopass = None
su_pass = None
vault_pass = None
sudo_prompt = "sudo password: "
su_prompt = "su password: "
if ask_pass:
sshpass = getpass.getpass(prompt="SSH password: ")
sudo_prompt = "sudo password [defaults to SSH password]: "
if ask_sudo_pass:
sudopass = getpass.getpass(prompt=sudo_prompt)
if ask_pass and sudopass == '':
sudopass = sshpass
if ask_su_pass:
su_pass = getpass.getpass(prompt=su_prompt)
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
return (sshpass, sudopass, su_pass, vault_pass)
def do_encrypt(result, encrypt, salt_size=None, salt=None):
if PASSLIB_AVAILABLE:
try:
crypt = getattr(passlib.hash, encrypt)
except:
raise errors.AnsibleError("passlib does not support '%s' algorithm" % encrypt)
if salt_size:
result = crypt.encrypt(result, salt_size=salt_size)
elif salt:
result = crypt.encrypt(result, salt=salt)
else:
result = crypt.encrypt(result)
else:
raise errors.AnsibleError("passlib must be installed to encrypt vars_prompt values")
return result
def last_non_blank_line(buf):
all_lines = buf.splitlines()
all_lines.reverse()
for line in all_lines:
if (len(line) > 0):
return line
# shouldn't occur unless there's no output
return ""
def filter_leading_non_json_lines(buf):
'''
used to avoid random output from SSH at the top of JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
need to filter anything which starts not with '{', '[', ', '=' or is an empty line.
filter only leading lines since multiline JSON is valid.
'''
kv_regex = re.compile(r'.*\w+=\w+.*')
filtered_lines = StringIO.StringIO()
stop_filtering = False
for line in buf.splitlines():
if stop_filtering or kv_regex.match(line) or line.startswith('{') or line.startswith('['):
stop_filtering = True
filtered_lines.write(line + '\n')
return filtered_lines.getvalue()
def boolean(value):
val = str(value)
if val.lower() in [ "true", "t", "y", "1", "yes" ]:
return True
else:
return False
def make_sudo_cmd(sudo_user, executable, cmd):
"""
helper function for connection plugins to create sudo commands
"""
# Rather than detect if sudo wants a password this time, -k makes
# sudo always ask for a password if one is required.
# Passing a quoted compound command to sudo (or sudo -s)
# directly doesn't work, so we shellquote it with pipes.quote()
# and pass the quoted string to the user's shell. We loop reading
# output until we see the randomly-generated sudo prompt set with
# the -p option.
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = '[sudo via ansible, key=%s] password: ' % randbits
success_key = 'SUDO-SUCCESS-%s' % randbits
sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % (
C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_FLAGS,
prompt, sudo_user, executable or '$SHELL', pipes.quote('echo %s; %s' % (success_key, cmd)))
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
def make_su_cmd(su_user, executable, cmd):
"""
Helper function for connection plugins to create direct su commands
"""
# TODO: work on this function
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = '[Pp]assword: ?$'
success_key = 'SUDO-SUCCESS-%s' % randbits
sudocmd = '%s %s %s -c "%s -c %s"' % (
C.DEFAULT_SU_EXE, C.DEFAULT_SU_FLAGS, su_user, executable or '$SHELL',
pipes.quote('echo %s; %s' % (success_key, cmd))
)
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
_TO_UNICODE_TYPES = (unicode, type(None))
def to_unicode(value):
if isinstance(value, _TO_UNICODE_TYPES):
return value
return value.decode("utf-8")
def get_diff(diff):
# called by --diff usage in playbook and runner via callbacks
# include names in diffs 'before' and 'after' and do diff -U 10
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ret = []
if 'dst_binary' in diff:
ret.append("diff skipped: destination file appears to be binary\n")
if 'src_binary' in diff:
ret.append("diff skipped: source file appears to be binary\n")
if 'dst_larger' in diff:
ret.append("diff skipped: destination file size is greater than %d\n" % diff['dst_larger'])
if 'src_larger' in diff:
ret.append("diff skipped: source file size is greater than %d\n" % diff['src_larger'])
if 'before' in diff and 'after' in diff:
if 'before_header' in diff:
before_header = "before: %s" % diff['before_header']
else:
before_header = 'before'
if 'after_header' in diff:
after_header = "after: %s" % diff['after_header']
else:
after_header = 'after'
differ = difflib.unified_diff(to_unicode(diff['before']).splitlines(True), to_unicode(diff['after']).splitlines(True), before_header, after_header, '', '', 10)
for line in list(differ):
ret.append(line)
return u"".join(ret)
except UnicodeDecodeError:
return ">> the files are different, but the diff library cannot compare unicode strings"
def is_list_of_strings(items):
for x in items:
if not isinstance(x, basestring):
return False
return True
def list_union(a, b):
result = []
for x in a:
if x not in result:
result.append(x)
for x in b:
if x not in result:
result.append(x)
return result
def list_intersection(a, b):
result = []
for x in a:
if x in b and x not in result:
result.append(x)
return result
def safe_eval(expr, locals={}, include_exceptions=False):
'''
this is intended for allowing things like:
with_items: a_list_variable
where Jinja2 would return a string
but we do not want to allow it to call functions (outside of Jinja2, where
the env is constrained)
Based on:
http://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe
'''
# this is the whitelist of AST nodes we are going to
# allow in the evaluation. Any node type other than
# those listed here will raise an exception in our custom
# visitor class defined below.
SAFE_NODES = set(
(
ast.Expression,
ast.Compare,
ast.Str,
ast.List,
ast.Tuple,
ast.Dict,
ast.Call,
ast.Load,
ast.BinOp,
ast.UnaryOp,
ast.Num,
ast.Name,
ast.Add,
ast.Sub,
ast.Mult,
ast.Div,
)
)
# AST node types were expanded after 2.6
if not sys.version.startswith('2.6'):
SAFE_NODES.union(
set(
(ast.Set,)
)
)
# builtin functions that are not safe to call
INVALID_CALLS = (
'classmethod', 'compile', 'delattr', 'eval', 'execfile', 'file',
'filter', 'help', 'input', 'object', 'open', 'raw_input', 'reduce',
'reload', 'repr', 'setattr', 'staticmethod', 'super', 'type',
)
class CleansingNodeVisitor(ast.NodeVisitor):
def generic_visit(self, node):
if type(node) not in SAFE_NODES:
#raise Exception("invalid expression (%s) type=%s" % (expr, type(node)))
raise Exception("invalid expression (%s)" % expr)
super(CleansingNodeVisitor, self).generic_visit(node)
def visit_Call(self, call):
if call.func.id in INVALID_CALLS:
raise Exception("invalid function: %s" % call.func.id)
if not isinstance(expr, basestring):
# already templated to a datastructure, perhaps?
if include_exceptions:
return (expr, None)
return expr
try:
parsed_tree = ast.parse(expr, mode='eval')
cnv = CleansingNodeVisitor()
cnv.visit(parsed_tree)
compiled = compile(parsed_tree, expr, 'eval')
result = eval(compiled, {}, locals)
if include_exceptions:
return (result, None)
else:
return result
except SyntaxError, e:
# special handling for syntax errors, we just return
# the expression string back as-is
if include_exceptions:
return (expr, None)
return expr
except Exception, e:
if include_exceptions:
return (expr, e)
return expr
def listify_lookup_plugin_terms(terms, basedir, inject):
if isinstance(terms, basestring):
# someone did:
# with_items: alist
# OR
# with_items: {{ alist }}
stripped = terms.strip()
if not (stripped.startswith('{') or stripped.startswith('[')) and not stripped.startswith("/") and not stripped.startswith('set(['):
# if not already a list, get ready to evaluate with Jinja2
# not sure why the "/" is in above code :)
try:
new_terms = template.template(basedir, "{{ %s }}" % terms, inject)
if isinstance(new_terms, basestring) and "{{" in new_terms:
pass
else:
terms = new_terms
except:
pass
if '{' in terms or '[' in terms:
# Jinja2 already evaluated a variable to a list.
# Jinja2-ified list needs to be converted back to a real type
# TODO: something a bit less heavy than eval
return safe_eval(terms)
if isinstance(terms, basestring):
terms = [ terms ]
return terms
def combine_vars(a, b):
if C.DEFAULT_HASH_BEHAVIOUR == "merge":
return merge_hash(a, b)
else:
return dict(a.items() + b.items())
def random_password(length=20, chars=C.DEFAULT_PASSWORD_CHARS):
'''Return a random password string of length containing only chars.'''
password = []
while len(password) < length:
new_char = os.urandom(1)
if new_char in chars:
password.append(new_char)
return ''.join(password)
def before_comment(msg):
''' what's the part of a string before a comment? '''
msg = msg.replace("\#","**NOT_A_COMMENT**")
msg = msg.split("#")[0]
msg = msg.replace("**NOT_A_COMMENT**","#")
return msg
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_2223_1 |
crossvul-python_data_bad_2223_0 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import pwd
import sys
import ConfigParser
from string import ascii_letters, digits
# copied from utils, avoid circular reference fun :)
def mk_boolean(value):
if value is None:
return False
val = str(value)
if val.lower() in [ "true", "t", "y", "1", "yes" ]:
return True
else:
return False
def get_config(p, section, key, env_var, default, boolean=False, integer=False, floating=False):
''' return a configuration variable with casting '''
value = _get_config(p, section, key, env_var, default)
if boolean:
return mk_boolean(value)
if value and integer:
return int(value)
if value and floating:
return float(value)
return value
def _get_config(p, section, key, env_var, default):
''' helper function for get_config '''
if env_var is not None:
value = os.environ.get(env_var, None)
if value is not None:
return value
if p is not None:
try:
return p.get(section, key, raw=True)
except:
return default
return default
def load_config_file():
''' Load Config File order(first found is used): ENV, CWD, HOME, /etc/ansible '''
p = ConfigParser.ConfigParser()
path0 = os.getenv("ANSIBLE_CONFIG", None)
if path0 is not None:
path0 = os.path.expanduser(path0)
path1 = os.getcwd() + "/ansible.cfg"
path2 = os.path.expanduser("~/.ansible.cfg")
path3 = "/etc/ansible/ansible.cfg"
for path in [path0, path1, path2, path3]:
if path is not None and os.path.exists(path):
p.read(path)
return p
return None
def shell_expand_path(path):
''' shell_expand_path is needed as os.path.expanduser does not work
when path is None, which is the default for ANSIBLE_PRIVATE_KEY_FILE '''
if path:
path = os.path.expanduser(path)
return path
p = load_config_file()
active_user = pwd.getpwuid(os.geteuid())[0]
# Needed so the RPM can call setup.py and have modules land in the
# correct location. See #1277 for discussion
if getattr(sys, "real_prefix", None):
# in a virtualenv
DIST_MODULE_PATH = os.path.join(sys.prefix, 'share/ansible/')
else:
DIST_MODULE_PATH = '/usr/share/ansible/'
# check all of these extensions when looking for yaml files for things like
# group variables -- really anything we can load
YAML_FILENAME_EXTENSIONS = [ "", ".yml", ".yaml", ".json" ]
# sections in config file
DEFAULTS='defaults'
# configurable things
DEFAULT_HOST_LIST = shell_expand_path(get_config(p, DEFAULTS, 'hostfile', 'ANSIBLE_HOSTS', '/etc/ansible/hosts'))
DEFAULT_MODULE_PATH = get_config(p, DEFAULTS, 'library', 'ANSIBLE_LIBRARY', DIST_MODULE_PATH)
DEFAULT_ROLES_PATH = shell_expand_path(get_config(p, DEFAULTS, 'roles_path', 'ANSIBLE_ROLES_PATH', '/etc/ansible/roles'))
DEFAULT_REMOTE_TMP = shell_expand_path(get_config(p, DEFAULTS, 'remote_tmp', 'ANSIBLE_REMOTE_TEMP', '$HOME/.ansible/tmp'))
DEFAULT_MODULE_NAME = get_config(p, DEFAULTS, 'module_name', None, 'command')
DEFAULT_PATTERN = get_config(p, DEFAULTS, 'pattern', None, '*')
DEFAULT_FORKS = get_config(p, DEFAULTS, 'forks', 'ANSIBLE_FORKS', 5, integer=True)
DEFAULT_MODULE_ARGS = get_config(p, DEFAULTS, 'module_args', 'ANSIBLE_MODULE_ARGS', '')
DEFAULT_MODULE_LANG = get_config(p, DEFAULTS, 'module_lang', 'ANSIBLE_MODULE_LANG', 'en_US.UTF-8')
DEFAULT_TIMEOUT = get_config(p, DEFAULTS, 'timeout', 'ANSIBLE_TIMEOUT', 10, integer=True)
DEFAULT_POLL_INTERVAL = get_config(p, DEFAULTS, 'poll_interval', 'ANSIBLE_POLL_INTERVAL', 15, integer=True)
DEFAULT_REMOTE_USER = get_config(p, DEFAULTS, 'remote_user', 'ANSIBLE_REMOTE_USER', active_user)
DEFAULT_ASK_PASS = get_config(p, DEFAULTS, 'ask_pass', 'ANSIBLE_ASK_PASS', False, boolean=True)
DEFAULT_PRIVATE_KEY_FILE = shell_expand_path(get_config(p, DEFAULTS, 'private_key_file', 'ANSIBLE_PRIVATE_KEY_FILE', None))
DEFAULT_SUDO_USER = get_config(p, DEFAULTS, 'sudo_user', 'ANSIBLE_SUDO_USER', 'root')
DEFAULT_ASK_SUDO_PASS = get_config(p, DEFAULTS, 'ask_sudo_pass', 'ANSIBLE_ASK_SUDO_PASS', False, boolean=True)
DEFAULT_REMOTE_PORT = get_config(p, DEFAULTS, 'remote_port', 'ANSIBLE_REMOTE_PORT', None, integer=True)
DEFAULT_ASK_VAULT_PASS = get_config(p, DEFAULTS, 'ask_vault_pass', 'ANSIBLE_ASK_VAULT_PASS', False, boolean=True)
DEFAULT_TRANSPORT = get_config(p, DEFAULTS, 'transport', 'ANSIBLE_TRANSPORT', 'smart')
DEFAULT_SCP_IF_SSH = get_config(p, 'ssh_connection', 'scp_if_ssh', 'ANSIBLE_SCP_IF_SSH', False, boolean=True)
DEFAULT_MANAGED_STR = get_config(p, DEFAULTS, 'ansible_managed', None, 'Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}')
DEFAULT_SYSLOG_FACILITY = get_config(p, DEFAULTS, 'syslog_facility', 'ANSIBLE_SYSLOG_FACILITY', 'LOG_USER')
DEFAULT_KEEP_REMOTE_FILES = get_config(p, DEFAULTS, 'keep_remote_files', 'ANSIBLE_KEEP_REMOTE_FILES', False, boolean=True)
DEFAULT_SUDO = get_config(p, DEFAULTS, 'sudo', 'ANSIBLE_SUDO', False, boolean=True)
DEFAULT_SUDO_EXE = get_config(p, DEFAULTS, 'sudo_exe', 'ANSIBLE_SUDO_EXE', 'sudo')
DEFAULT_SUDO_FLAGS = get_config(p, DEFAULTS, 'sudo_flags', 'ANSIBLE_SUDO_FLAGS', '-H')
DEFAULT_HASH_BEHAVIOUR = get_config(p, DEFAULTS, 'hash_behaviour', 'ANSIBLE_HASH_BEHAVIOUR', 'replace')
DEFAULT_JINJA2_EXTENSIONS = get_config(p, DEFAULTS, 'jinja2_extensions', 'ANSIBLE_JINJA2_EXTENSIONS', None)
DEFAULT_EXECUTABLE = get_config(p, DEFAULTS, 'executable', 'ANSIBLE_EXECUTABLE', '/bin/sh')
DEFAULT_SU_EXE = get_config(p, DEFAULTS, 'su_exe', 'ANSIBLE_SU_EXE', 'su')
DEFAULT_SU = get_config(p, DEFAULTS, 'su', 'ANSIBLE_SU', False, boolean=True)
DEFAULT_SU_FLAGS = get_config(p, DEFAULTS, 'su_flags', 'ANSIBLE_SU_FLAGS', '')
DEFAULT_SU_USER = get_config(p, DEFAULTS, 'su_user', 'ANSIBLE_SU_USER', 'root')
DEFAULT_ASK_SU_PASS = get_config(p, DEFAULTS, 'ask_su_pass', 'ANSIBLE_ASK_SU_PASS', False, boolean=True)
DEFAULT_GATHERING = get_config(p, DEFAULTS, 'gathering', 'ANSIBLE_GATHERING', 'implicit').lower()
DEFAULT_ACTION_PLUGIN_PATH = get_config(p, DEFAULTS, 'action_plugins', 'ANSIBLE_ACTION_PLUGINS', '/usr/share/ansible_plugins/action_plugins')
DEFAULT_CALLBACK_PLUGIN_PATH = get_config(p, DEFAULTS, 'callback_plugins', 'ANSIBLE_CALLBACK_PLUGINS', '/usr/share/ansible_plugins/callback_plugins')
DEFAULT_CONNECTION_PLUGIN_PATH = get_config(p, DEFAULTS, 'connection_plugins', 'ANSIBLE_CONNECTION_PLUGINS', '/usr/share/ansible_plugins/connection_plugins')
DEFAULT_LOOKUP_PLUGIN_PATH = get_config(p, DEFAULTS, 'lookup_plugins', 'ANSIBLE_LOOKUP_PLUGINS', '/usr/share/ansible_plugins/lookup_plugins')
DEFAULT_VARS_PLUGIN_PATH = get_config(p, DEFAULTS, 'vars_plugins', 'ANSIBLE_VARS_PLUGINS', '/usr/share/ansible_plugins/vars_plugins')
DEFAULT_FILTER_PLUGIN_PATH = get_config(p, DEFAULTS, 'filter_plugins', 'ANSIBLE_FILTER_PLUGINS', '/usr/share/ansible_plugins/filter_plugins')
DEFAULT_LOG_PATH = shell_expand_path(get_config(p, DEFAULTS, 'log_path', 'ANSIBLE_LOG_PATH', ''))
ANSIBLE_FORCE_COLOR = get_config(p, DEFAULTS, 'force_color', 'ANSIBLE_FORCE_COLOR', None, boolean=True)
ANSIBLE_NOCOLOR = get_config(p, DEFAULTS, 'nocolor', 'ANSIBLE_NOCOLOR', None, boolean=True)
ANSIBLE_NOCOWS = get_config(p, DEFAULTS, 'nocows', 'ANSIBLE_NOCOWS', None, boolean=True)
DISPLAY_SKIPPED_HOSTS = get_config(p, DEFAULTS, 'display_skipped_hosts', 'DISPLAY_SKIPPED_HOSTS', True, boolean=True)
DEFAULT_UNDEFINED_VAR_BEHAVIOR = get_config(p, DEFAULTS, 'error_on_undefined_vars', 'ANSIBLE_ERROR_ON_UNDEFINED_VARS', True, boolean=True)
HOST_KEY_CHECKING = get_config(p, DEFAULTS, 'host_key_checking', 'ANSIBLE_HOST_KEY_CHECKING', True, boolean=True)
SYSTEM_WARNINGS = get_config(p, DEFAULTS, 'system_warnings', 'ANSIBLE_SYSTEM_WARNINGS', True, boolean=True)
DEPRECATION_WARNINGS = get_config(p, DEFAULTS, 'deprecation_warnings', 'ANSIBLE_DEPRECATION_WARNINGS', True, boolean=True)
# CONNECTION RELATED
ANSIBLE_SSH_ARGS = get_config(p, 'ssh_connection', 'ssh_args', 'ANSIBLE_SSH_ARGS', None)
ANSIBLE_SSH_CONTROL_PATH = get_config(p, 'ssh_connection', 'control_path', 'ANSIBLE_SSH_CONTROL_PATH', "%(directory)s/ansible-ssh-%%h-%%p-%%r")
ANSIBLE_SSH_PIPELINING = get_config(p, 'ssh_connection', 'pipelining', 'ANSIBLE_SSH_PIPELINING', False, boolean=True)
PARAMIKO_RECORD_HOST_KEYS = get_config(p, 'paramiko_connection', 'record_host_keys', 'ANSIBLE_PARAMIKO_RECORD_HOST_KEYS', True, boolean=True)
# obsolete -- will be formally removed in 1.6
ZEROMQ_PORT = get_config(p, 'fireball_connection', 'zeromq_port', 'ANSIBLE_ZEROMQ_PORT', 5099, integer=True)
ACCELERATE_PORT = get_config(p, 'accelerate', 'accelerate_port', 'ACCELERATE_PORT', 5099, integer=True)
ACCELERATE_TIMEOUT = get_config(p, 'accelerate', 'accelerate_timeout', 'ACCELERATE_TIMEOUT', 30, integer=True)
ACCELERATE_CONNECT_TIMEOUT = get_config(p, 'accelerate', 'accelerate_connect_timeout', 'ACCELERATE_CONNECT_TIMEOUT', 1.0, floating=True)
ACCELERATE_DAEMON_TIMEOUT = get_config(p, 'accelerate', 'accelerate_daemon_timeout', 'ACCELERATE_DAEMON_TIMEOUT', 30, integer=True)
ACCELERATE_KEYS_DIR = get_config(p, 'accelerate', 'accelerate_keys_dir', 'ACCELERATE_KEYS_DIR', '~/.fireball.keys')
ACCELERATE_KEYS_DIR_PERMS = get_config(p, 'accelerate', 'accelerate_keys_dir_perms', 'ACCELERATE_KEYS_DIR_PERMS', '700')
ACCELERATE_KEYS_FILE_PERMS = get_config(p, 'accelerate', 'accelerate_keys_file_perms', 'ACCELERATE_KEYS_FILE_PERMS', '600')
ACCELERATE_MULTI_KEY = get_config(p, 'accelerate', 'accelerate_multi_key', 'ACCELERATE_MULTI_KEY', False, boolean=True)
PARAMIKO_PTY = get_config(p, 'paramiko_connection', 'pty', 'ANSIBLE_PARAMIKO_PTY', True, boolean=True)
# characters included in auto-generated passwords
DEFAULT_PASSWORD_CHARS = ascii_letters + digits + ".,:-_"
# non-configurable things
DEFAULT_SUDO_PASS = None
DEFAULT_REMOTE_PASS = None
DEFAULT_SUBSET = None
DEFAULT_SU_PASS = None
VAULT_VERSION_MIN = 1.0
VAULT_VERSION_MAX = 1.0
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_2223_0 |
crossvul-python_data_good_3934_1 | # -*- coding: utf-8 -*-
"""Small, fast HTTP client library for Python."""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = [
"Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger",
"Mark Pilgrim",
"Alex Yu",
]
__license__ = "MIT"
__version__ = '0.17.4'
import base64
import calendar
import copy
import email
import email.feedparser
from email import header
import email.message
import email.utils
import errno
from gettext import gettext as _
import gzip
from hashlib import md5 as _md5
from hashlib import sha1 as _sha
import hmac
import http.client
import io
import os
import random
import re
import socket
import ssl
import sys
import time
import urllib.parse
import zlib
try:
import socks
except ImportError:
# TODO: remove this fallback and copypasted socksipy module upon py2/3 merge,
# idea is to have soft-dependency on any compatible module called socks
from . import socks
from .iri2uri import iri2uri
def has_timeout(timeout):
if hasattr(socket, "_GLOBAL_DEFAULT_TIMEOUT"):
return timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT
return timeout is not None
__all__ = [
"debuglevel",
"FailedToDecompressContent",
"Http",
"HttpLib2Error",
"ProxyInfo",
"RedirectLimit",
"RedirectMissingLocation",
"Response",
"RETRIES",
"UnimplementedDigestAuthOptionError",
"UnimplementedHmacDigestAuthOptionError",
]
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# A request will be tried 'RETRIES' times if it fails at the socket/connection level.
RETRIES = 2
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception):
pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse):
pass
class RedirectLimit(HttpLib2ErrorWithResponse):
pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse):
pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class MalformedHeader(HttpLib2Error):
pass
class RelativeURIError(HttpLib2Error):
pass
class ServerNotFoundError(HttpLib2Error):
pass
class ProxiesUnavailableError(HttpLib2Error):
pass
# Open Items:
# -----------
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
]
# https://tools.ietf.org/html/rfc7231#section-8.1.3
SAFE_METHODS = ("GET", "HEAD", "OPTIONS", "TRACE")
# To change, assign to `Http().redirect_codes`
REDIRECT_CODES = frozenset((300, 301, 302, 303, 307, 308))
from httplib2 import certs
CA_CERTS = certs.where()
# PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated.
# Both PROTOCOL_TLS and PROTOCOL_SSLv23 are equivalent and means:
# > Selects the highest protocol version that both the client and server support.
# > Despite the name, this option can select “TLS” protocols as well as “SSL”.
# source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLS
DEFAULT_TLS_VERSION = getattr(ssl, "PROTOCOL_TLS", None) or getattr(
ssl, "PROTOCOL_SSLv23"
)
def _build_ssl_context(
disable_ssl_certificate_validation, ca_certs, cert_file=None, key_file=None,
maximum_version=None, minimum_version=None, key_password=None,
):
if not hasattr(ssl, "SSLContext"):
raise RuntimeError("httplib2 requires Python 3.2+ for ssl.SSLContext")
context = ssl.SSLContext(DEFAULT_TLS_VERSION)
context.verify_mode = (
ssl.CERT_NONE if disable_ssl_certificate_validation else ssl.CERT_REQUIRED
)
# SSLContext.maximum_version and SSLContext.minimum_version are python 3.7+.
# source: https://docs.python.org/3/library/ssl.html#ssl.SSLContext.maximum_version
if maximum_version is not None:
if hasattr(context, "maximum_version"):
context.maximum_version = getattr(ssl.TLSVersion, maximum_version)
else:
raise RuntimeError("setting tls_maximum_version requires Python 3.7 and OpenSSL 1.1 or newer")
if minimum_version is not None:
if hasattr(context, "minimum_version"):
context.minimum_version = getattr(ssl.TLSVersion, minimum_version)
else:
raise RuntimeError("setting tls_minimum_version requires Python 3.7 and OpenSSL 1.1 or newer")
# check_hostname requires python 3.4+
# we will perform the equivalent in HTTPSConnectionWithTimeout.connect() by calling ssl.match_hostname
# if check_hostname is not supported.
if hasattr(context, "check_hostname"):
context.check_hostname = not disable_ssl_certificate_validation
context.load_verify_locations(ca_certs)
if cert_file:
context.load_cert_chain(cert_file, key_file, key_password)
return context
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get("connection", "").split(",")])
return [header for header in list(response.keys()) if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r"^\w+://")
re_unsafe = re.compile(r"[^\w\-_.()=!]+", re.ASCII)
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
if isinstance(filename, bytes):
filename_bytes = filename
filename = filename.decode("utf-8")
else:
filename_bytes = filename.encode("utf-8")
filemd5 = _md5(filename_bytes).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_unsafe.sub("", filename)
# limit length of filename (vital for Windows)
# https://github.com/httplib2/httplib2/pull/74
# C:\Users\ <username> \AppData\Local\Temp\ <safe_filename> , <md5>
# 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars
# Thus max safe filename x = 93 chars. Let it be 90 to make a round sum:
filename = filename[:90]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r"(?:\r\n)?[ \t]+")
def _normalize_headers(headers):
return dict(
[
(
_convert_byte_str(key).lower(),
NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),
)
for (key, value) in headers.items()
]
)
def _convert_byte_str(s):
if not isinstance(s, str):
return str(s, "utf-8")
return s
def _parse_cache_control(headers):
retval = {}
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)])
for part in parts
if -1 != part.find("=")
]
parts_wo_args = [
(name.strip().lower(), 1) for name in parts if -1 == name.find("=")
]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, useful for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(
r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$"
)
WWW_AUTH_RELAXED = re.compile(
r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$"
)
UNQUOTE_PAIRS = re.compile(r"\\(.)")
def _parse_www_authenticate(headers, headername="www-authenticate"):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headername in headers:
try:
authenticate = headers[headername].strip()
www_auth = (
USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
)
while authenticate:
# Break off the scheme at the beginning of the line
if headername == "authentication-info":
(auth_scheme, the_rest) = ("digest", authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(
r"\1", value
) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if (
"pragma" in request_headers
and request_headers["pragma"].lower().find("no-cache") != -1
):
retval = "TRANSPARENT"
if "cache-control" not in request_headers:
request_headers["cache-control"] = "no-cache"
elif "no-cache" in cc:
retval = "TRANSPARENT"
elif "no-cache" in cc_response:
retval = "STALE"
elif "only-if-cached" in cc:
retval = "FRESH"
elif "date" in response_headers:
date = calendar.timegm(email.utils.parsedate_tz(response_headers["date"]))
now = time.time()
current_age = max(0, now - date)
if "max-age" in cc_response:
try:
freshness_lifetime = int(cc_response["max-age"])
except ValueError:
freshness_lifetime = 0
elif "expires" in response_headers:
expires = email.utils.parsedate_tz(response_headers["expires"])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if "max-age" in cc:
try:
freshness_lifetime = int(cc["max-age"])
except ValueError:
freshness_lifetime = 0
if "min-fresh" in cc:
try:
min_fresh = int(cc["min-fresh"])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get("content-encoding", None)
if encoding in ["gzip", "deflate"]:
if encoding == "gzip":
content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()
if encoding == "deflate":
content = zlib.decompress(content, -zlib.MAX_WBITS)
response["content-length"] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response["-content-encoding"] = response["content-encoding"]
del response["content-encoding"]
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
)
return content
def _bind_write_headers(msg):
def _write_headers(self):
# Self refers to the Generator object.
for h, v in msg.items():
print("%s:" % h, end=" ", file=self._fp)
if isinstance(v, header.Header):
print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
else:
# email.Header got lots of smarts, so use it.
headers = header.Header(
v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
)
print(headers.encode(), file=self._fp)
# A blank line always separates headers from body.
print(file=self._fp)
return _write_headers
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if "no-store" in cc or "no-store" in cc_response:
cache.delete(cachekey)
else:
info = email.message.Message()
for key, value in response_headers.items():
if key not in ["status", "content-encoding", "transfer-encoding"]:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get("vary", None)
if vary:
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = "status: %d\r\n" % status
try:
header_str = info.as_string()
except UnicodeEncodeError:
setattr(info, "_write_headers", _bind_write_headers(info))
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = b"".join(
[status_header.encode("utf-8"), header_str.encode("utf-8"), content]
)
cache.set(cachekey, text)
def _cnonce():
dig = _md5(
(
"%s:%s"
% (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])
).encode("utf-8")
).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(
_sha(("%s%s%s" % (cnonce, iso_now, password)).encode("utf-8")).digest()
).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path) :].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-rise this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
def __eq__(self, auth):
return False
def __ne__(self, auth):
return True
def __lt__(self, auth):
return True
def __gt__(self, auth):
return False
def __le__(self, auth):
return True
def __ge__(self, auth):
return False
def __bool__(self):
return True
class BasicAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = "Basic " + base64.b64encode(
("%s:%s" % self.credentials).encode("utf-8")
).strip().decode("utf-8")
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["digest"]
qop = self.challenge.get("qop", "auth")
self.challenge["qop"] = (
("auth" in [x.strip() for x in qop.split()]) and "auth" or None
)
if self.challenge["qop"] is None:
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for qop: %s." % qop)
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "MD5").upper()
if self.challenge["algorithm"] != "MD5":
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.A1 = "".join(
[
self.credentials[0],
":",
self.challenge["realm"],
":",
self.credentials[1],
]
)
self.challenge["nc"] = 1
def request(self, method, request_uri, headers, content, cnonce=None):
"""Modify the request headers"""
H = lambda x: _md5(x.encode("utf-8")).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge["cnonce"] = cnonce or _cnonce()
request_digest = '"%s"' % KD(
H(self.A1),
"%s:%s:%s:%s:%s"
% (
self.challenge["nonce"],
"%08x" % self.challenge["nc"],
self.challenge["cnonce"],
self.challenge["qop"],
H(A2),
),
)
headers["authorization"] = (
'Digest username="%s", realm="%s", nonce="%s", '
'uri="%s", algorithm=%s, response=%s, qop=%s, '
'nc=%08x, cnonce="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["nonce"],
request_uri,
self.challenge["algorithm"],
request_digest,
self.challenge["qop"],
self.challenge["nc"],
self.challenge["cnonce"],
)
if self.challenge.get("opaque"):
headers["authorization"] += ', opaque="%s"' % self.challenge["opaque"]
self.challenge["nc"] += 1
def response(self, response, content):
if "authentication-info" not in response:
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"digest", {}
)
if "true" == challenge.get("stale"):
self.challenge["nonce"] = challenge["nonce"]
self.challenge["nc"] = 1
return True
else:
updated_challenge = _parse_www_authenticate(
response, "authentication-info"
).get("digest", {})
if "nextnonce" in updated_challenge:
self.challenge["nonce"] = updated_challenge["nextnonce"]
self.challenge["nc"] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["hmacdigest"]
# TODO: self.challenge['domain']
self.challenge["reason"] = self.challenge.get("reason", "unauthorized")
if self.challenge["reason"] not in ["unauthorized", "integrity"]:
self.challenge["reason"] = "unauthorized"
self.challenge["salt"] = self.challenge.get("salt", "")
if not self.challenge.get("snonce"):
raise UnimplementedHmacDigestAuthOptionError(
_("The challenge doesn't contain a server nonce, or this one is empty.")
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "HMAC-SHA-1")
if self.challenge["algorithm"] not in ["HMAC-SHA-1", "HMAC-MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1")
if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_(
"Unsupported value for pw-algorithm: %s."
% self.challenge["pw-algorithm"]
)
)
if self.challenge["algorithm"] == "HMAC-MD5":
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge["pw-algorithm"] == "MD5":
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join(
[
self.credentials[0],
":",
self.pwhashmod.new(
"".join([self.credentials[1], self.challenge["salt"]])
)
.hexdigest()
.lower(),
":",
self.challenge["realm"],
]
)
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (
method,
request_uri,
cnonce,
self.challenge["snonce"],
headers_val,
)
request_digest = (
hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
)
headers["authorization"] = (
'HMACDigest username="%s", realm="%s", snonce="%s",'
' cnonce="%s", uri="%s", created="%s", '
'response="%s", headers="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["snonce"],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"hmacdigest", {}
)
if challenge.get("reason") in ["integrity", "stale"]:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = (
'UsernameToken Username="%s", PasswordDigest="%s", '
'Nonce="%s", Created="%s"'
) % (self.credentials[0], password_digest, cnonce, iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
from urllib.parse import urlencode
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
service = challenge["googlelogin"].get("service", "xapi")
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == "xapi" and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(
Email=credentials[0],
Passwd=credentials[1],
service=service,
source=headers["user-agent"],
)
resp, content = self.http.request(
"https://www.google.com/accounts/ClientLogin",
method="POST",
body=urlencode(auth),
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
lines = content.split("\n")
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d["Auth"]
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = "GoogleLogin Auth=" + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication,
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(
self, cache, safe=safename
): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = open(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = open(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
def iter(self, domain):
for (cdomain, key, cert, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (key, cert, password)
class AllHosts(object):
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
bypass_hosts = ()
def __init__(
self,
proxy_type,
proxy_host,
proxy_port,
proxy_rdns=True,
proxy_user=None,
proxy_pass=None,
proxy_headers=None,
):
"""Args:
proxy_type: The type of proxy server. This must be set to one of
socks.PROXY_TYPE_XXX constants. For example: p =
ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost',
proxy_port=8000)
proxy_host: The hostname or IP address of the proxy server.
proxy_port: The port that the proxy server is running on.
proxy_rdns: If True (default), DNS queries will not be performed
locally, and instead, handed to the proxy to resolve. This is useful
if the network does not allow resolution of non-local names. In
httplib2 0.9 and earlier, this defaulted to False.
proxy_user: The username used to authenticate with the proxy server.
proxy_pass: The password used to authenticate with the proxy server.
proxy_headers: Additional or modified headers for the proxy connect
request.
"""
if isinstance(proxy_user, bytes):
proxy_user = proxy_user.decode()
if isinstance(proxy_pass, bytes):
proxy_pass = proxy_pass.decode()
self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass, self.proxy_headers = (
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
def astuple(self):
return (
self.proxy_type,
self.proxy_host,
self.proxy_port,
self.proxy_rdns,
self.proxy_user,
self.proxy_pass,
self.proxy_headers,
)
def isgood(self):
return socks and (self.proxy_host != None) and (self.proxy_port != None)
def applies_to(self, hostname):
return not self.bypass_host(hostname)
def bypass_host(self, hostname):
"""Has this host been excluded from the proxy config"""
if self.bypass_hosts is AllHosts:
return True
hostname = "." + hostname.lstrip(".")
for skip_name in self.bypass_hosts:
# *.suffix
if skip_name.startswith(".") and hostname.endswith(skip_name):
return True
# exact match
if hostname == "." + skip_name:
return True
return False
def __repr__(self):
return (
"<ProxyInfo type={p.proxy_type} "
"host:port={p.proxy_host}:{p.proxy_port} rdns={p.proxy_rdns}"
+ " user={p.proxy_user} headers={p.proxy_headers}>"
).format(p=self)
def proxy_info_from_environment(method="http"):
"""Read proxy info from the environment variables.
"""
if method not in ("http", "https"):
return
env_var = method + "_proxy"
url = os.environ.get(env_var, os.environ.get(env_var.upper()))
if not url:
return
return proxy_info_from_url(url, method, noproxy=None)
def proxy_info_from_url(url, method="http", noproxy=None):
"""Construct a ProxyInfo from a URL (such as http_proxy env var)
"""
url = urllib.parse.urlparse(url)
username = None
password = None
port = None
if "@" in url[1]:
ident, host_port = url[1].split("@", 1)
if ":" in ident:
username, password = ident.split(":", 1)
else:
password = ident
else:
host_port = url[1]
if ":" in host_port:
host, port = host_port.split(":", 1)
else:
host = host_port
if port:
port = int(port)
else:
port = dict(https=443, http=80)[method]
proxy_type = 3 # socks.PROXY_TYPE_HTTP
pi = ProxyInfo(
proxy_type=proxy_type,
proxy_host=host,
proxy_port=port,
proxy_user=username or None,
proxy_pass=password or None,
proxy_headers=None,
)
bypass_hosts = []
# If not given an explicit noproxy value, respect values in env vars.
if noproxy is None:
noproxy = os.environ.get("no_proxy", os.environ.get("NO_PROXY", ""))
# Special case: A single '*' character means all hosts should be bypassed.
if noproxy == "*":
bypass_hosts = AllHosts
elif noproxy.strip():
bypass_hosts = noproxy.split(",")
bypass_hosts = tuple(filter(bool, bypass_hosts)) # To exclude empty string.
pi.bypass_hosts = bypass_hosts
return pi
class HTTPConnectionWithTimeout(http.client.HTTPConnection):
"""HTTPConnection subclass that supports timeouts
HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, timeout=None, proxy_info=None):
http.client.HTTPConnection.__init__(self, host, port=port, timeout=timeout)
self.proxy_info = proxy_info
if proxy_info and not isinstance(proxy_info, ProxyInfo):
self.proxy_info = proxy_info("http")
def connect(self):
"""Connect to the host and port specified in __init__."""
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
"Proxy support missing but proxy use was requested!"
)
if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_port
else:
use_proxy = False
host = self.host
port = self.port
proxy_type = None
socket_err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
)
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
if self.debuglevel > 0:
print(
"connect: ({0}, {1}) ************".format(self.host, self.port)
)
if use_proxy:
print(
"proxy: {0} ************".format(
str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
)
self.sock.connect((self.host, self.port) + sa[2:])
except socket.error as e:
socket_err = e
if self.debuglevel > 0:
print("connect fail: ({0}, {1})".format(self.host, self.port))
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket_err
class HTTPSConnectionWithTimeout(http.client.HTTPSConnection):
"""This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
timeout=None,
proxy_info=None,
ca_certs=None,
disable_ssl_certificate_validation=False,
tls_maximum_version=None,
tls_minimum_version=None,
key_password=None,
):
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.ca_certs = ca_certs if ca_certs else CA_CERTS
self.proxy_info = proxy_info
if proxy_info and not isinstance(proxy_info, ProxyInfo):
self.proxy_info = proxy_info("https")
context = _build_ssl_context(
self.disable_ssl_certificate_validation, self.ca_certs, cert_file, key_file,
maximum_version=tls_maximum_version, minimum_version=tls_minimum_version,
key_password=key_password,
)
super(HTTPSConnectionWithTimeout, self).__init__(
host,
port=port,
timeout=timeout,
context=context,
)
self.key_file = key_file
self.cert_file = cert_file
self.key_password = key_password
def connect(self):
"""Connect to a host on a given (SSL) port."""
if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_port
else:
use_proxy = False
host = self.host
port = self.port
proxy_type = None
proxy_headers = None
socket_err = None
address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
for family, socktype, proto, canonname, sockaddr in address_info:
try:
if use_proxy:
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
)
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
# Python 3.3 compatibility: emulate the check_hostname behavior
if (
not hasattr(self._context, "check_hostname")
and not self.disable_ssl_certificate_validation
):
try:
ssl.match_hostname(self.sock.getpeercert(), self.host)
except Exception:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
raise
if self.debuglevel > 0:
print("connect: ({0}, {1})".format(self.host, self.port))
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
)
except (ssl.SSLError, ssl.CertificateError) as e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error as e:
socket_err = e
if self.debuglevel > 0:
print("connect fail: ({0}, {1})".format(self.host, self.port))
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket_err
SCHEME_TO_CONNECTION = {
"http": HTTPConnectionWithTimeout,
"https": HTTPSConnectionWithTimeout,
}
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(
self,
cache=None,
timeout=None,
proxy_info=proxy_info_from_environment,
ca_certs=None,
disable_ssl_certificate_validation=False,
tls_maximum_version=None,
tls_minimum_version=None,
):
"""If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
`proxy_info` may be:
- a callable that takes the http scheme ('http' or 'https') and
returns a ProxyInfo instance per request. By default, uses
proxy_info_from_environment.
- a ProxyInfo instance (static proxy config).
- None (proxy disabled).
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
tls_maximum_version / tls_minimum_version require Python 3.7+ /
OpenSSL 1.1.0g+. A value of "TLSv1_3" requires OpenSSL 1.1.1+.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.tls_maximum_version = tls_maximum_version
self.tls_minimum_version = tls_minimum_version
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, str):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
self.redirect_codes = REDIRECT_CODES
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
self.safe_methods = list(SAFE_METHODS)
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
# Keep Authorization: headers on a redirect.
self.forward_authorization_headers = False
def close(self):
"""Close persistent connections, clear sensitive data.
Not thread-safe, requires external synchronization against concurrent requests.
"""
existing, self.connections = self.connections, {}
for _, c in existing.items():
c.close()
self.certificates.clear()
self.clear_credentials()
def __getstate__(self):
state_dict = copy.copy(self.__dict__)
# In case request is augmented by some foreign object such as
# credentials which handle auth
if "request" in state_dict:
del state_dict["request"]
if "connections" in state_dict:
del state_dict["connections"]
return state_dict
def __setstate__(self, state):
self.__dict__.update(state)
self.connections = {}
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if scheme in challenges:
yield AUTH_SCHEME_CLASSES[scheme](
cred, host, request_uri, headers, response, content, self
)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain, password=None):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain, password)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
i = 0
seen_bad_status_line = False
while i < RETRIES:
i += 1
try:
if conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
conn.close()
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except socket.error as e:
errno_ = (
e.args[0].errno if isinstance(e.args[0], socket.error) else e.errno
)
if errno_ in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
continue # retry on potentially transient errors
raise
except http.client.HTTPException:
if conn.sock is None:
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
pass
try:
response = conn.getresponse()
except (http.client.BadStatusLine, http.client.ResponseNotReady):
# If we get a BadStatusLine on the first try then that means
# the connection just went stale, so retry regardless of the
# number of RETRIES set.
if not seen_bad_status_line and i == 1:
i = 0
seen_bad_status_line = True
conn.close()
conn.connect()
continue
else:
conn.close()
raise
except socket.timeout:
raise
except (socket.error, http.client.HTTPException):
conn.close()
if i == 0:
conn.close()
conn.connect()
continue
else:
raise
else:
content = b""
if method == "HEAD":
conn.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(
self,
conn,
host,
absolute_uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [
(auth.depth(request_uri), auth)
for auth in self.authorizations
if auth.inscope(host, request_uri)
]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(
host, request_uri, headers, response, content
):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (
self.follow_all_redirects
or method in self.safe_methods
or response.status in (303, 308)
):
if self.follow_redirects and response.status in self.redirect_codes:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if "location" not in response and response.status != 300:
raise RedirectMissingLocation(
_(
"Redirected but the response is missing a Location: header."
),
response,
content,
)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if "location" in response:
location = response["location"]
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response["location"] = urllib.parse.urljoin(
absolute_uri, location
)
if response.status == 308 or (response.status == 301 and (method in self.safe_methods)):
response["-x-permanent-redirect-url"] = response["location"]
if "content-location" not in response:
response["content-location"] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if "if-none-match" in headers:
del headers["if-none-match"]
if "if-modified-since" in headers:
del headers["if-modified-since"]
if (
"authorization" in headers
and not self.forward_authorization_headers
):
del headers["authorization"]
if "location" in response:
location = response["location"]
old_response = copy.deepcopy(response)
if "content-location" not in old_response:
old_response["content-location"] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(
location,
method=redirect_method,
body=body,
headers=headers,
redirections=redirections - 1,
)
response.previous = old_response
else:
raise RedirectLimit(
"Redirected more times than redirection_limit allows.",
response,
content,
)
elif response.status in [200, 203] and method in self.safe_methods:
# Don't cache 206's since we aren't going to handle byte range requests
if "content-location" not in response:
response["content-location"] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(
self,
uri,
method="GET",
body=None,
headers=None,
redirections=DEFAULT_MAX_REDIRECTS,
connection_type=None,
):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin
with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc.
There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a string
object.
Any extra headers that are to be sent with the request should be provided in the
'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ''
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if "user-agent" not in headers:
headers["user-agent"] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
# Prevent CWE-75 space injection to manipulate request via part of uri.
# Prevent CWE-93 CRLF injection to modify headers via part of uri.
uri = uri.replace(" ", "%20").replace("\r", "%0D").replace("\n", "%0A")
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
conn_key = scheme + ":" + authority
conn = self.connections.get(conn_key)
if conn is None:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if issubclass(connection_type, HTTPSConnectionWithTimeout):
if certs:
conn = self.connections[conn_key] = connection_type(
authority,
key_file=certs[0][0],
cert_file=certs[0][1],
timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
tls_maximum_version=self.tls_maximum_version,
tls_minimum_version=self.tls_minimum_version,
key_password=certs[0][2],
)
else:
conn = self.connections[conn_key] = connection_type(
authority,
timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
tls_maximum_version=self.tls_maximum_version,
tls_minimum_version=self.tls_minimum_version,
)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout, proxy_info=self.proxy_info
)
conn.set_debuglevel(debuglevel)
if "range" not in headers and "accept-encoding" not in headers:
headers["accept-encoding"] = "gzip, deflate"
info = email.message.Message()
cachekey = None
cached_value = None
if self.cache:
cachekey = defrag_uri
cached_value = self.cache.get(cachekey)
if cached_value:
try:
info, content = cached_value.split(b"\r\n\r\n", 1)
info = email.message_from_bytes(info)
for k, v in info.items():
if v.startswith("=?") and v.endswith("?="):
info.replace_header(
k, str(*email.header.decode_header(v)[0])
)
except (IndexError, ValueError):
self.cache.delete(cachekey)
cachekey = None
cached_value = None
if (
method in self.optimistic_concurrency_methods
and self.cache
and "etag" in info
and not self.ignore_etag
and "if-match" not in headers
):
# http://www.w3.org/1999/04/Editing/
headers["if-match"] = info["etag"]
# https://tools.ietf.org/html/rfc7234
# A cache MUST invalidate the effective Request URI as well as [...] Location and Content-Location
# when a non-error status code is received in response to an unsafe request method.
if self.cache and cachekey and method not in self.safe_methods:
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in self.safe_methods and "vary" in info:
vary = info["vary"]
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if (
self.cache
and cached_value
and (method in self.safe_methods or info["status"] == "308")
and "range" not in headers
):
redirect_method = method
if info["status"] not in ("307", "308"):
redirect_method = "GET"
if "-x-permanent-redirect-url" in info:
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit(
"Redirected more times than redirection_limit allows.",
{},
"",
)
(response, new_content) = self.request(
info["-x-permanent-redirect-url"],
method=redirect_method,
headers=headers,
redirections=redirections - 1,
)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info["status"] = "504"
content = b""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if (
"etag" in info
and not self.ignore_etag
and not "if-none-match" in headers
):
headers["if-none-match"] = info["etag"]
if "last-modified" in info and not "last-modified" in headers:
headers["if-modified-since"] = info["last-modified"]
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(
headers, merged_response, content, self.cache, cachekey
)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if "only-if-cached" in cc:
info["status"] = "504"
response = Response(info)
content = b""
else:
(response, content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
)
except Exception as e:
is_timeout = isinstance(e, socket.timeout)
if is_timeout:
conn = self.connections.pop(conn_key, None)
if conn:
conn.close()
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = b"Request Timeout"
response = Response(
{
"content-type": "text/plain",
"status": "408",
"content-length": len(content),
}
)
response.reason = "Request Timeout"
else:
content = str(e).encode("utf-8")
response = Response(
{
"content-type": "text/plain",
"status": "400",
"content-length": len(content),
}
)
response.reason = "Bad Request"
else:
raise
return (response, content)
class Response(dict):
"""An object more like email.message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server.
10 for HTTP/1.0, 11 for HTTP/1.1.
"""
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.message or
# an httplib.HTTPResponse object.
if isinstance(info, http.client.HTTPResponse):
for key, value in info.getheaders():
key = key.lower()
prev = self.get(key)
if prev is not None:
value = ", ".join((prev, value))
self[key] = value
self.status = info.status
self["status"] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.message.Message):
for key, value in list(info.items()):
self[key.lower()] = value
self.status = int(self["status"])
else:
for key, value in info.items():
self[key.lower()] = value
self.status = int(self.get("status", self.status))
def __getattr__(self, name):
if name == "dict":
return self
else:
raise AttributeError(name)
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_3934_1 |
crossvul-python_data_bad_2234_3 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
from ansible import utils
import ansible.constants as C
import ansible.utils.template as template
from ansible import errors
from ansible.runner.return_data import ReturnData
import base64
import json
import stat
import tempfile
import pipes
## fixes https://github.com/ansible/ansible/issues/3518
# http://mypy.pythonblogs.com/12_mypy/archive/1253_workaround_for_python_bug_ascii_codec_cant_encode_character_uxa0_in_position_111_ordinal_not_in_range128.html
import sys
reload(sys)
sys.setdefaultencoding("utf8")
class ActionModule(object):
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp_path, module_name, module_args, inject, complex_args=None, **kwargs):
''' handler for file transfer operations '''
# load up options
options = {}
if complex_args:
options.update(complex_args)
options.update(utils.parse_kv(module_args))
source = options.get('src', None)
content = options.get('content', None)
dest = options.get('dest', None)
raw = utils.boolean(options.get('raw', 'no'))
force = utils.boolean(options.get('force', 'yes'))
# content with newlines is going to be escaped to safely load in yaml
# now we need to unescape it so that the newlines are evaluated properly
# when writing the file to disk
if content:
if isinstance(content, unicode):
try:
content = content.decode('unicode-escape')
except UnicodeDecodeError:
pass
if (source is None and content is None and not 'first_available_file' in inject) or dest is None:
result=dict(failed=True, msg="src (or content) and dest are required")
return ReturnData(conn=conn, result=result)
elif (source is not None or 'first_available_file' in inject) and content is not None:
result=dict(failed=True, msg="src and content are mutually exclusive")
return ReturnData(conn=conn, result=result)
# Check if the source ends with a "/"
source_trailing_slash = False
if source:
source_trailing_slash = source.endswith("/")
# Define content_tempfile in case we set it after finding content populated.
content_tempfile = None
# If content is defined make a temp file and write the content into it.
if content is not None:
try:
# If content comes to us as a dict it should be decoded json.
# We need to encode it back into a string to write it out.
if type(content) is dict:
content_tempfile = self._create_content_tempfile(json.dumps(content))
else:
content_tempfile = self._create_content_tempfile(content)
source = content_tempfile
except Exception, err:
result = dict(failed=True, msg="could not write content temp file: %s" % err)
return ReturnData(conn=conn, result=result)
# if we have first_available_file in our vars
# look up the files and use the first one we find as src
elif 'first_available_file' in inject:
found = False
for fn in inject.get('first_available_file'):
fn_orig = fn
fnt = template.template(self.runner.basedir, fn, inject)
fnd = utils.path_dwim(self.runner.basedir, fnt)
if not os.path.exists(fnd) and '_original_file' in inject:
fnd = utils.path_dwim_relative(inject['_original_file'], 'files', fnt, self.runner.basedir, check=False)
if os.path.exists(fnd):
source = fnd
found = True
break
if not found:
results = dict(failed=True, msg="could not find src in first_available_file list")
return ReturnData(conn=conn, result=results)
else:
source = template.template(self.runner.basedir, source, inject)
if '_original_file' in inject:
source = utils.path_dwim_relative(inject['_original_file'], 'files', source, self.runner.basedir)
else:
source = utils.path_dwim(self.runner.basedir, source)
# A list of source file tuples (full_path, relative_path) which will try to copy to the destination
source_files = []
# If source is a directory populate our list else source is a file and translate it to a tuple.
if os.path.isdir(source):
# Get the amount of spaces to remove to get the relative path.
if source_trailing_slash:
sz = len(source) + 1
else:
sz = len(source.rsplit('/', 1)[0]) + 1
# Walk the directory and append the file tuples to source_files.
for base_path, sub_folders, files in os.walk(source):
for file in files:
full_path = os.path.join(base_path, file)
rel_path = full_path[sz:]
source_files.append((full_path, rel_path))
# If it's recursive copy, destination is always a dir,
# explicitly mark it so (note - copy module relies on this).
if not dest.endswith("/"):
dest += "/"
else:
source_files.append((source, os.path.basename(source)))
changed = False
diffs = []
module_result = {"changed": False}
# A register for if we executed a module.
# Used to cut down on command calls when not recursive.
module_executed = False
# Tell _execute_module to delete the file if there is one file.
delete_remote_tmp = (len(source_files) == 1)
# If this is a recursive action create a tmp_path that we can share as the _exec_module create is too late.
if not delete_remote_tmp:
if "-tmp-" not in tmp_path:
tmp_path = self.runner._make_tmp_path(conn)
for source_full, source_rel in source_files:
# Generate the MD5 hash of the local file.
local_md5 = utils.md5(source_full)
# If local_md5 is not defined we can't find the file so we should fail out.
if local_md5 is None:
result = dict(failed=True, msg="could not find src=%s" % source_full)
return ReturnData(conn=conn, result=result)
# This is kind of optimization - if user told us destination is
# dir, do path manipulation right away, otherwise we still check
# for dest being a dir via remote call below.
if dest.endswith("/"):
dest_file = os.path.join(dest, source_rel)
else:
dest_file = dest
# Attempt to get the remote MD5 Hash.
remote_md5 = self.runner._remote_md5(conn, tmp_path, dest_file)
if remote_md5 == '3':
# The remote_md5 was executed on a directory.
if content is not None:
# If source was defined as content remove the temporary file and fail out.
self._remove_tempfile_if_content_defined(content, content_tempfile)
result = dict(failed=True, msg="can not use content with a dir as dest")
return ReturnData(conn=conn, result=result)
else:
# Append the relative source location to the destination and retry remote_md5.
dest_file = os.path.join(dest, source_rel)
remote_md5 = self.runner._remote_md5(conn, tmp_path, dest_file)
if remote_md5 != '1' and not force:
# remote_file does not exist so continue to next iteration.
continue
if local_md5 != remote_md5:
# The MD5 hashes don't match and we will change or error out.
changed = True
# Create a tmp_path if missing only if this is not recursive.
# If this is recursive we already have a tmp_path.
if delete_remote_tmp:
if "-tmp-" not in tmp_path:
tmp_path = self.runner._make_tmp_path(conn)
if self.runner.diff and not raw:
diff = self._get_diff_data(conn, tmp_path, inject, dest_file, source_full)
else:
diff = {}
if self.runner.noop_on_check(inject):
self._remove_tempfile_if_content_defined(content, content_tempfile)
diffs.append(diff)
changed = True
module_result = dict(changed=True)
continue
# Define a remote directory that we will copy the file to.
tmp_src = tmp_path + 'source'
if not raw:
conn.put_file(source_full, tmp_src)
else:
conn.put_file(source_full, dest_file)
# We have copied the file remotely and no longer require our content_tempfile
self._remove_tempfile_if_content_defined(content, content_tempfile)
# fix file permissions when the copy is done as a different user
if self.runner.sudo and self.runner.sudo_user != 'root' and not raw:
self.runner._low_level_exec_command(conn, "chmod a+r %s" % tmp_src, tmp_path)
if raw:
# Continue to next iteration if raw is defined.
continue
# Run the copy module
# src and dest here come after original and override them
# we pass dest only to make sure it includes trailing slash in case of recursive copy
module_args_tmp = "%s src=%s dest=%s original_basename=%s" % (module_args,
pipes.quote(tmp_src), pipes.quote(dest), pipes.quote(source_rel))
if self.runner.no_log:
module_args_tmp = "%s NO_LOG=True" % module_args_tmp
module_return = self.runner._execute_module(conn, tmp_path, 'copy', module_args_tmp, inject=inject, complex_args=complex_args, delete_remote_tmp=delete_remote_tmp)
module_executed = True
else:
# no need to transfer the file, already correct md5, but still need to call
# the file module in case we want to change attributes
self._remove_tempfile_if_content_defined(content, content_tempfile)
if raw:
# Continue to next iteration if raw is defined.
# self.runner._remove_tmp_path(conn, tmp_path)
continue
tmp_src = tmp_path + source_rel
# Build temporary module_args.
module_args_tmp = "%s src=%s original_basename=%s" % (module_args,
pipes.quote(tmp_src), pipes.quote(source_rel))
if self.runner.noop_on_check(inject):
module_args_tmp = "%s CHECKMODE=True" % module_args_tmp
if self.runner.no_log:
module_args_tmp = "%s NO_LOG=True" % module_args_tmp
# Execute the file module.
module_return = self.runner._execute_module(conn, tmp_path, 'file', module_args_tmp, inject=inject, complex_args=complex_args, delete_remote_tmp=delete_remote_tmp)
module_executed = True
module_result = module_return.result
if not module_result.get('md5sum'):
module_result['md5sum'] = local_md5
if module_result.get('failed') == True:
return module_return
if module_result.get('changed') == True:
changed = True
# Delete tmp_path if we were recursive or if we did not execute a module.
if (not C.DEFAULT_KEEP_REMOTE_FILES and not delete_remote_tmp) \
or (not C.DEFAULT_KEEP_REMOTE_FILES and delete_remote_tmp and not module_executed):
self.runner._remove_tmp_path(conn, tmp_path)
# the file module returns the file path as 'path', but
# the copy module uses 'dest', so add it if it's not there
if 'path' in module_result and 'dest' not in module_result:
module_result['dest'] = module_result['path']
# TODO: Support detailed status/diff for multiple files
if len(source_files) == 1:
result = module_result
else:
result = dict(dest=dest, src=source, changed=changed)
if len(diffs) == 1:
return ReturnData(conn=conn, result=result, diff=diffs[0])
else:
return ReturnData(conn=conn, result=result)
def _create_content_tempfile(self, content):
''' Create a tempfile containing defined content '''
fd, content_tempfile = tempfile.mkstemp()
f = os.fdopen(fd, 'w')
try:
f.write(content)
except Exception, err:
os.remove(content_tempfile)
raise Exception(err)
finally:
f.close()
return content_tempfile
def _get_diff_data(self, conn, tmp, inject, destination, source):
peek_result = self.runner._execute_module(conn, tmp, 'file', "path=%s diff_peek=1" % destination, inject=inject, persist_files=True)
if not peek_result.is_successful():
return {}
diff = {}
if peek_result.result['state'] == 'absent':
diff['before'] = ''
elif peek_result.result['appears_binary']:
diff['dst_binary'] = 1
elif peek_result.result['size'] > utils.MAX_FILE_SIZE_FOR_DIFF:
diff['dst_larger'] = utils.MAX_FILE_SIZE_FOR_DIFF
else:
dest_result = self.runner._execute_module(conn, tmp, 'slurp', "path=%s" % destination, inject=inject, persist_files=True)
if 'content' in dest_result.result:
dest_contents = dest_result.result['content']
if dest_result.result['encoding'] == 'base64':
dest_contents = base64.b64decode(dest_contents)
else:
raise Exception("unknown encoding, failed: %s" % dest_result.result)
diff['before_header'] = destination
diff['before'] = dest_contents
src = open(source)
src_contents = src.read(8192)
st = os.stat(source)
if "\x00" in src_contents:
diff['src_binary'] = 1
elif st[stat.ST_SIZE] > utils.MAX_FILE_SIZE_FOR_DIFF:
diff['src_larger'] = utils.MAX_FILE_SIZE_FOR_DIFF
else:
src.seek(0)
diff['after_header'] = source
diff['after'] = src.read()
return diff
def _remove_tempfile_if_content_defined(self, content, content_tempfile):
if content is not None:
os.remove(content_tempfile)
def _result_key_merge(self, options, results):
# add keys to file module results to mimic copy
if 'path' in results.result and 'dest' not in results.result:
results.result['dest'] = results.result['path']
del results.result['path']
return results
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_2234_3 |
crossvul-python_data_good_4621_1 | VERSION = (0, 9, '3b1')
__version__ = '.'.join(map(str, VERSION))
version = lambda: __version__
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_4621_1 |
crossvul-python_data_good_2234_0 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Copyright (c), Michael DeHaan <michael.dehaan@gmail.com>, 2012-2013
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# == BEGIN DYNAMICALLY INSERTED CODE ==
MODULE_ARGS = "<<INCLUDE_ANSIBLE_MODULE_ARGS>>"
MODULE_COMPLEX_ARGS = "<<INCLUDE_ANSIBLE_MODULE_COMPLEX_ARGS>>"
BOOLEANS_TRUE = ['yes', 'on', '1', 'true', 1]
BOOLEANS_FALSE = ['no', 'off', '0', 'false', 0]
BOOLEANS = BOOLEANS_TRUE + BOOLEANS_FALSE
# ansible modules can be written in any language. To simplify
# development of Python modules, the functions available here
# can be inserted in any module source automatically by including
# #<<INCLUDE_ANSIBLE_MODULE_COMMON>> on a blank line by itself inside
# of an ansible module. The source of this common code lives
# in lib/ansible/module_common.py
import locale
import os
import re
import pipes
import shlex
import subprocess
import sys
import syslog
import types
import time
import shutil
import stat
import tempfile
import traceback
import grp
import pwd
import platform
import errno
import tempfile
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
sys.stderr.write('Error: ansible requires a json module, none found!')
sys.exit(1)
except SyntaxError:
sys.stderr.write('SyntaxError: probably due to json and python being for different versions')
sys.exit(1)
HAVE_SELINUX=False
try:
import selinux
HAVE_SELINUX=True
except ImportError:
pass
HAVE_HASHLIB=False
try:
from hashlib import md5 as _md5
HAVE_HASHLIB=True
except ImportError:
from md5 import md5 as _md5
try:
from hashlib import sha256 as _sha256
except ImportError:
pass
try:
from systemd import journal
has_journal = True
except ImportError:
import syslog
has_journal = False
FILE_COMMON_ARGUMENTS=dict(
src = dict(),
mode = dict(),
owner = dict(),
group = dict(),
seuser = dict(),
serole = dict(),
selevel = dict(),
setype = dict(),
# not taken by the file module, but other modules call file so it must ignore them.
content = dict(),
backup = dict(),
force = dict(),
remote_src = dict(), # used by assemble
delimiter = dict(), # used by assemble
directory_mode = dict(), # used by copy
)
def get_platform():
''' what's the platform? example: Linux is a platform. '''
return platform.system()
def get_distribution():
''' return the distribution name '''
if platform.system() == 'Linux':
try:
distribution = platform.linux_distribution()[0].capitalize()
if not distribution and os.path.isfile('/etc/system-release'):
distribution = platform.linux_distribution(supported_dists=['system'])[0].capitalize()
if 'Amazon' in distribution:
distribution = 'Amazon'
else:
distribution = 'OtherLinux'
except:
# FIXME: MethodMissing, I assume?
distribution = platform.dist()[0].capitalize()
else:
distribution = None
return distribution
def load_platform_subclass(cls, *args, **kwargs):
'''
used by modules like User to have different implementations based on detected platform. See User
module for an example.
'''
this_platform = get_platform()
distribution = get_distribution()
subclass = None
# get the most specific superclass for this platform
if distribution is not None:
for sc in cls.__subclasses__():
if sc.distribution is not None and sc.distribution == distribution and sc.platform == this_platform:
subclass = sc
if subclass is None:
for sc in cls.__subclasses__():
if sc.platform == this_platform and sc.distribution is None:
subclass = sc
if subclass is None:
subclass = cls
return super(cls, subclass).__new__(subclass)
class AnsibleModule(object):
def __init__(self, argument_spec, bypass_checks=False, no_log=False,
check_invalid_arguments=True, mutually_exclusive=None, required_together=None,
required_one_of=None, add_file_common_args=False, supports_check_mode=False):
'''
common code for quickly building an ansible module in Python
(although you can write modules in anything that can return JSON)
see library/* for examples
'''
self.argument_spec = argument_spec
self.supports_check_mode = supports_check_mode
self.check_mode = False
self.no_log = no_log
self.cleanup_files = []
self.aliases = {}
if add_file_common_args:
for k, v in FILE_COMMON_ARGUMENTS.iteritems():
if k not in self.argument_spec:
self.argument_spec[k] = v
# check the locale as set by the current environment, and
# reset to LANG=C if it's an invalid/unavailable locale
self._check_locale()
(self.params, self.args) = self._load_params()
self._legal_inputs = ['CHECKMODE', 'NO_LOG']
self.aliases = self._handle_aliases()
if check_invalid_arguments:
self._check_invalid_arguments()
self._check_for_check_mode()
self._check_for_no_log()
# check exclusive early
if not bypass_checks:
self._check_mutually_exclusive(mutually_exclusive)
self._set_defaults(pre=True)
if not bypass_checks:
self._check_required_arguments()
self._check_argument_values()
self._check_argument_types()
self._check_required_together(required_together)
self._check_required_one_of(required_one_of)
self._set_defaults(pre=False)
if not self.no_log:
self._log_invocation()
# finally, make sure we're in a sane working dir
self._set_cwd()
def load_file_common_arguments(self, params):
'''
many modules deal with files, this encapsulates common
options that the file module accepts such that it is directly
available to all modules and they can share code.
'''
path = params.get('path', params.get('dest', None))
if path is None:
return {}
else:
path = os.path.expanduser(path)
mode = params.get('mode', None)
owner = params.get('owner', None)
group = params.get('group', None)
# selinux related options
seuser = params.get('seuser', None)
serole = params.get('serole', None)
setype = params.get('setype', None)
selevel = params.get('selevel', None)
secontext = [seuser, serole, setype]
if self.selinux_mls_enabled():
secontext.append(selevel)
default_secontext = self.selinux_default_context(path)
for i in range(len(default_secontext)):
if i is not None and secontext[i] == '_default':
secontext[i] = default_secontext[i]
return dict(
path=path, mode=mode, owner=owner, group=group,
seuser=seuser, serole=serole, setype=setype,
selevel=selevel, secontext=secontext,
)
# Detect whether using selinux that is MLS-aware.
# While this means you can set the level/range with
# selinux.lsetfilecon(), it may or may not mean that you
# will get the selevel as part of the context returned
# by selinux.lgetfilecon().
def selinux_mls_enabled(self):
if not HAVE_SELINUX:
return False
if selinux.is_selinux_mls_enabled() == 1:
return True
else:
return False
def selinux_enabled(self):
if not HAVE_SELINUX:
seenabled = self.get_bin_path('selinuxenabled')
if seenabled is not None:
(rc,out,err) = self.run_command(seenabled)
if rc == 0:
self.fail_json(msg="Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!")
return False
if selinux.is_selinux_enabled() == 1:
return True
else:
return False
# Determine whether we need a placeholder for selevel/mls
def selinux_initial_context(self):
context = [None, None, None]
if self.selinux_mls_enabled():
context.append(None)
return context
def _to_filesystem_str(self, path):
'''Returns filesystem path as a str, if it wasn't already.
Used in selinux interactions because it cannot accept unicode
instances, and specifying complex args in a playbook leaves
you with unicode instances. This method currently assumes
that your filesystem encoding is UTF-8.
'''
if isinstance(path, unicode):
path = path.encode("utf-8")
return path
# If selinux fails to find a default, return an array of None
def selinux_default_context(self, path, mode=0):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.matchpathcon(self._to_filesystem_str(path), mode)
except OSError:
return context
if ret[0] == -1:
return context
# Limit split to 4 because the selevel, the last in the list,
# may contain ':' characters
context = ret[1].split(':', 3)
return context
def selinux_context(self, path):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.lgetfilecon_raw(self._to_filesystem_str(path))
except OSError, e:
if e.errno == errno.ENOENT:
self.fail_json(path=path, msg='path %s does not exist' % path)
else:
self.fail_json(path=path, msg='failed to retrieve selinux context')
if ret[0] == -1:
return context
# Limit split to 4 because the selevel, the last in the list,
# may contain ':' characters
context = ret[1].split(':', 3)
return context
def user_and_group(self, filename):
filename = os.path.expanduser(filename)
st = os.lstat(filename)
uid = st.st_uid
gid = st.st_gid
return (uid, gid)
def find_mount_point(self, path):
path = os.path.abspath(os.path.expanduser(os.path.expandvars(path)))
while not os.path.ismount(path):
path = os.path.dirname(path)
return path
def is_nfs_path(self, path):
"""
Returns a tuple containing (True, selinux_context) if the given path
is on a NFS mount point, otherwise the return will be (False, None).
"""
try:
f = open('/proc/mounts', 'r')
mount_data = f.readlines()
f.close()
except:
return (False, None)
path_mount_point = self.find_mount_point(path)
for line in mount_data:
(device, mount_point, fstype, options, rest) = line.split(' ', 4)
if path_mount_point == mount_point and 'nfs' in fstype:
nfs_context = self.selinux_context(path_mount_point)
return (True, nfs_context)
return (False, None)
def set_default_selinux_context(self, path, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
context = self.selinux_default_context(path)
return self.set_context_if_different(path, context, False)
def set_context_if_different(self, path, context, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
cur_context = self.selinux_context(path)
new_context = list(cur_context)
# Iterate over the current context instead of the
# argument context, which may have selevel.
(is_nfs, nfs_context) = self.is_nfs_path(path)
if is_nfs:
new_context = nfs_context
else:
for i in range(len(cur_context)):
if len(context) > i:
if context[i] is not None and context[i] != cur_context[i]:
new_context[i] = context[i]
if context[i] is None:
new_context[i] = cur_context[i]
if cur_context != new_context:
try:
if self.check_mode:
return True
rc = selinux.lsetfilecon(self._to_filesystem_str(path),
str(':'.join(new_context)))
except OSError:
self.fail_json(path=path, msg='invalid selinux context', new_context=new_context, cur_context=cur_context, input_was=context)
if rc != 0:
self.fail_json(path=path, msg='set selinux context failed')
changed = True
return changed
def set_owner_if_different(self, path, owner, changed):
path = os.path.expanduser(path)
if owner is None:
return changed
orig_uid, orig_gid = self.user_and_group(path)
try:
uid = int(owner)
except ValueError:
try:
uid = pwd.getpwnam(owner).pw_uid
except KeyError:
self.fail_json(path=path, msg='chown failed: failed to look up user %s' % owner)
if orig_uid != uid:
if self.check_mode:
return True
try:
os.lchown(path, uid, -1)
except OSError:
self.fail_json(path=path, msg='chown failed')
changed = True
return changed
def set_group_if_different(self, path, group, changed):
path = os.path.expanduser(path)
if group is None:
return changed
orig_uid, orig_gid = self.user_and_group(path)
try:
gid = int(group)
except ValueError:
try:
gid = grp.getgrnam(group).gr_gid
except KeyError:
self.fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group)
if orig_gid != gid:
if self.check_mode:
return True
try:
os.lchown(path, -1, gid)
except OSError:
self.fail_json(path=path, msg='chgrp failed')
changed = True
return changed
def set_mode_if_different(self, path, mode, changed):
path = os.path.expanduser(path)
if mode is None:
return changed
try:
# FIXME: support English modes
if not isinstance(mode, int):
mode = int(mode, 8)
except Exception, e:
self.fail_json(path=path, msg='mode needs to be something octalish', details=str(e))
st = os.lstat(path)
prev_mode = stat.S_IMODE(st[stat.ST_MODE])
if prev_mode != mode:
if self.check_mode:
return True
# FIXME: comparison against string above will cause this to be executed
# every time
try:
if 'lchmod' in dir(os):
os.lchmod(path, mode)
else:
os.chmod(path, mode)
except OSError, e:
if os.path.islink(path) and e.errno == errno.EPERM: # Can't set mode on symbolic links
pass
elif e.errno == errno.ENOENT: # Can't set mode on broken symbolic links
pass
else:
raise e
except Exception, e:
self.fail_json(path=path, msg='chmod failed', details=str(e))
st = os.lstat(path)
new_mode = stat.S_IMODE(st[stat.ST_MODE])
if new_mode != prev_mode:
changed = True
return changed
def set_fs_attributes_if_different(self, file_args, changed):
# set modes owners and context as needed
changed = self.set_context_if_different(
file_args['path'], file_args['secontext'], changed
)
changed = self.set_owner_if_different(
file_args['path'], file_args['owner'], changed
)
changed = self.set_group_if_different(
file_args['path'], file_args['group'], changed
)
changed = self.set_mode_if_different(
file_args['path'], file_args['mode'], changed
)
return changed
def set_directory_attributes_if_different(self, file_args, changed):
return self.set_fs_attributes_if_different(file_args, changed)
def set_file_attributes_if_different(self, file_args, changed):
return self.set_fs_attributes_if_different(file_args, changed)
def add_path_info(self, kwargs):
'''
for results that are files, supplement the info about the file
in the return path with stats about the file path.
'''
path = kwargs.get('path', kwargs.get('dest', None))
if path is None:
return kwargs
if os.path.exists(path):
(uid, gid) = self.user_and_group(path)
kwargs['uid'] = uid
kwargs['gid'] = gid
try:
user = pwd.getpwuid(uid)[0]
except KeyError:
user = str(uid)
try:
group = grp.getgrgid(gid)[0]
except KeyError:
group = str(gid)
kwargs['owner'] = user
kwargs['group'] = group
st = os.lstat(path)
kwargs['mode'] = oct(stat.S_IMODE(st[stat.ST_MODE]))
# secontext not yet supported
if os.path.islink(path):
kwargs['state'] = 'link'
elif os.path.isdir(path):
kwargs['state'] = 'directory'
elif os.stat(path).st_nlink > 1:
kwargs['state'] = 'hard'
else:
kwargs['state'] = 'file'
if HAVE_SELINUX and self.selinux_enabled():
kwargs['secontext'] = ':'.join(self.selinux_context(path))
kwargs['size'] = st[stat.ST_SIZE]
else:
kwargs['state'] = 'absent'
return kwargs
def _check_locale(self):
'''
Uses the locale module to test the currently set locale
(per the LANG and LC_CTYPE environment settings)
'''
try:
# setting the locale to '' uses the default locale
# as it would be returned by locale.getdefaultlocale()
locale.setlocale(locale.LC_ALL, '')
except locale.Error, e:
# fallback to the 'C' locale, which may cause unicode
# issues but is preferable to simply failing because
# of an unknown locale
locale.setlocale(locale.LC_ALL, 'C')
os.environ['LANG'] = 'C'
os.environ['LC_CTYPE'] = 'C'
except Exception, e:
self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" % e)
def _handle_aliases(self):
aliases_results = {} #alias:canon
for (k,v) in self.argument_spec.iteritems():
self._legal_inputs.append(k)
aliases = v.get('aliases', None)
default = v.get('default', None)
required = v.get('required', False)
if default is not None and required:
# not alias specific but this is a good place to check this
self.fail_json(msg="internal error: required and default are mutally exclusive for %s" % k)
if aliases is None:
continue
if type(aliases) != list:
self.fail_json(msg='internal error: aliases must be a list')
for alias in aliases:
self._legal_inputs.append(alias)
aliases_results[alias] = k
if alias in self.params:
self.params[k] = self.params[alias]
return aliases_results
def _check_for_check_mode(self):
for (k,v) in self.params.iteritems():
if k == 'CHECKMODE':
if not self.supports_check_mode:
self.exit_json(skipped=True, msg="remote module does not support check mode")
if self.supports_check_mode:
self.check_mode = True
def _check_for_no_log(self):
for (k,v) in self.params.iteritems():
if k == 'NO_LOG':
self.no_log = self.boolean(v)
def _check_invalid_arguments(self):
for (k,v) in self.params.iteritems():
# these should be in legal inputs already
#if k in ('CHECKMODE', 'NO_LOG'):
# continue
if k not in self._legal_inputs:
self.fail_json(msg="unsupported parameter for module: %s" % k)
def _count_terms(self, check):
count = 0
for term in check:
if term in self.params:
count += 1
return count
def _check_mutually_exclusive(self, spec):
if spec is None:
return
for check in spec:
count = self._count_terms(check)
if count > 1:
self.fail_json(msg="parameters are mutually exclusive: %s" % check)
def _check_required_one_of(self, spec):
if spec is None:
return
for check in spec:
count = self._count_terms(check)
if count == 0:
self.fail_json(msg="one of the following is required: %s" % ','.join(check))
def _check_required_together(self, spec):
if spec is None:
return
for check in spec:
counts = [ self._count_terms([field]) for field in check ]
non_zero = [ c for c in counts if c > 0 ]
if len(non_zero) > 0:
if 0 in counts:
self.fail_json(msg="parameters are required together: %s" % check)
def _check_required_arguments(self):
''' ensure all required arguments are present '''
missing = []
for (k,v) in self.argument_spec.iteritems():
required = v.get('required', False)
if required and k not in self.params:
missing.append(k)
if len(missing) > 0:
self.fail_json(msg="missing required arguments: %s" % ",".join(missing))
def _check_argument_values(self):
''' ensure all arguments have the requested values, and there are no stray arguments '''
for (k,v) in self.argument_spec.iteritems():
choices = v.get('choices',None)
if choices is None:
continue
if type(choices) == list:
if k in self.params:
if self.params[k] not in choices:
choices_str=",".join([str(c) for c in choices])
msg="value of %s must be one of: %s, got: %s" % (k, choices_str, self.params[k])
self.fail_json(msg=msg)
else:
self.fail_json(msg="internal error: do not know how to interpret argument_spec")
def _check_argument_types(self):
''' ensure all arguments have the requested type '''
for (k, v) in self.argument_spec.iteritems():
wanted = v.get('type', None)
if wanted is None:
continue
if k not in self.params:
continue
value = self.params[k]
is_invalid = False
if wanted == 'str':
if not isinstance(value, basestring):
self.params[k] = str(value)
elif wanted == 'list':
if not isinstance(value, list):
if isinstance(value, basestring):
self.params[k] = value.split(",")
elif isinstance(value, int) or isinstance(value, float):
self.params[k] = [ str(value) ]
else:
is_invalid = True
elif wanted == 'dict':
if not isinstance(value, dict):
if isinstance(value, basestring):
if value.startswith("{"):
try:
self.params[k] = json.loads(value)
except:
(result, exc) = self.safe_eval(value, dict(), include_exceptions=True)
if exc is not None:
self.fail_json(msg="unable to evaluate dictionary for %s" % k)
self.params[k] = result
elif '=' in value:
self.params[k] = dict([x.split("=", 1) for x in value.split(",")])
else:
self.fail_json(msg="dictionary requested, could not parse JSON or key=value")
else:
is_invalid = True
elif wanted == 'bool':
if not isinstance(value, bool):
if isinstance(value, basestring):
self.params[k] = self.boolean(value)
else:
is_invalid = True
elif wanted == 'int':
if not isinstance(value, int):
if isinstance(value, basestring):
self.params[k] = int(value)
else:
is_invalid = True
elif wanted == 'float':
if not isinstance(value, float):
if isinstance(value, basestring):
self.params[k] = float(value)
else:
is_invalid = True
else:
self.fail_json(msg="implementation error: unknown type %s requested for %s" % (wanted, k))
if is_invalid:
self.fail_json(msg="argument %s is of invalid type: %s, required: %s" % (k, type(value), wanted))
def _set_defaults(self, pre=True):
for (k,v) in self.argument_spec.iteritems():
default = v.get('default', None)
if pre == True:
# this prevents setting defaults on required items
if default is not None and k not in self.params:
self.params[k] = default
else:
# make sure things without a default still get set None
if k not in self.params:
self.params[k] = default
def _load_params(self):
''' read the input and return a dictionary and the arguments string '''
args = MODULE_ARGS
items = shlex.split(args)
params = {}
for x in items:
try:
(k, v) = x.split("=",1)
except Exception, e:
self.fail_json(msg="this module requires key=value arguments (%s)" % (items))
if k in params:
self.fail_json(msg="duplicate parameter: %s (value=%s)" % (k, v))
params[k] = v
params2 = json.loads(MODULE_COMPLEX_ARGS)
params2.update(params)
return (params2, args)
def _log_invocation(self):
''' log that ansible ran the module '''
# TODO: generalize a separate log function and make log_invocation use it
# Sanitize possible password argument when logging.
log_args = dict()
passwd_keys = ['password', 'login_password']
filter_re = [
# filter out things like user:pass@foo/whatever
# and http://username:pass@wherever/foo
re.compile('^(?P<before>.*:)(?P<password>.*)(?P<after>\@.*)$'),
]
for param in self.params:
canon = self.aliases.get(param, param)
arg_opts = self.argument_spec.get(canon, {})
no_log = arg_opts.get('no_log', False)
if no_log:
log_args[param] = 'NOT_LOGGING_PARAMETER'
elif param in passwd_keys:
log_args[param] = 'NOT_LOGGING_PASSWORD'
else:
found = False
for filter in filter_re:
if isinstance(self.params[param], unicode):
m = filter.match(self.params[param])
else:
m = filter.match(str(self.params[param]))
if m:
d = m.groupdict()
log_args[param] = d['before'] + "********" + d['after']
found = True
break
if not found:
log_args[param] = self.params[param]
module = 'ansible-%s' % os.path.basename(__file__)
msg = ''
for arg in log_args:
if isinstance(log_args[arg], basestring):
msg = msg + arg + '=' + log_args[arg].decode('utf-8') + ' '
else:
msg = msg + arg + '=' + str(log_args[arg]) + ' '
if msg:
msg = 'Invoked with %s' % msg
else:
msg = 'Invoked'
# 6655 - allow for accented characters
try:
msg = msg.encode('utf8')
except UnicodeDecodeError, e:
pass
if (has_journal):
journal_args = ["MESSAGE=%s %s" % (module, msg)]
journal_args.append("MODULE=%s" % os.path.basename(__file__))
for arg in log_args:
journal_args.append(arg.upper() + "=" + str(log_args[arg]))
try:
journal.sendv(*journal_args)
except IOError, e:
# fall back to syslog since logging to journal failed
syslog.openlog(str(module), 0, syslog.LOG_USER)
syslog.syslog(syslog.LOG_NOTICE, msg) #1
else:
syslog.openlog(str(module), 0, syslog.LOG_USER)
syslog.syslog(syslog.LOG_NOTICE, msg) #2
def _set_cwd(self):
try:
cwd = os.getcwd()
if not os.access(cwd, os.F_OK|os.R_OK):
raise
return cwd
except:
# we don't have access to the cwd, probably because of sudo.
# Try and move to a neutral location to prevent errors
for cwd in [os.path.expandvars('$HOME'), tempfile.gettempdir()]:
try:
if os.access(cwd, os.F_OK|os.R_OK):
os.chdir(cwd)
return cwd
except:
pass
# we won't error here, as it may *not* be a problem,
# and we don't want to break modules unnecessarily
return None
def get_bin_path(self, arg, required=False, opt_dirs=[]):
'''
find system executable in PATH.
Optional arguments:
- required: if executable is not found and required is true, fail_json
- opt_dirs: optional list of directories to search in addition to PATH
if found return full path; otherwise return None
'''
sbin_paths = ['/sbin', '/usr/sbin', '/usr/local/sbin']
paths = []
for d in opt_dirs:
if d is not None and os.path.exists(d):
paths.append(d)
paths += os.environ.get('PATH', '').split(os.pathsep)
bin_path = None
# mangle PATH to include /sbin dirs
for p in sbin_paths:
if p not in paths and os.path.exists(p):
paths.append(p)
for d in paths:
path = os.path.join(d, arg)
if os.path.exists(path) and self.is_executable(path):
bin_path = path
break
if required and bin_path is None:
self.fail_json(msg='Failed to find required executable %s' % arg)
return bin_path
def boolean(self, arg):
''' return a bool for the arg '''
if arg is None or type(arg) == bool:
return arg
if type(arg) in types.StringTypes:
arg = arg.lower()
if arg in BOOLEANS_TRUE:
return True
elif arg in BOOLEANS_FALSE:
return False
else:
self.fail_json(msg='Boolean %s not in either boolean list' % arg)
def jsonify(self, data):
for encoding in ("utf-8", "latin-1", "unicode_escape"):
try:
return json.dumps(data, encoding=encoding)
# Old systems using simplejson module does not support encoding keyword.
except TypeError, e:
return json.dumps(data)
except UnicodeDecodeError, e:
continue
self.fail_json(msg='Invalid unicode encoding encountered')
def from_json(self, data):
return json.loads(data)
def add_cleanup_file(self, path):
if path not in self.cleanup_files:
self.cleanup_files.append(path)
def do_cleanup_files(self):
for path in self.cleanup_files:
self.cleanup(path)
def exit_json(self, **kwargs):
''' return from the module, without error '''
self.add_path_info(kwargs)
if not 'changed' in kwargs:
kwargs['changed'] = False
self.do_cleanup_files()
print self.jsonify(kwargs)
sys.exit(0)
def fail_json(self, **kwargs):
''' return from the module, with an error message '''
self.add_path_info(kwargs)
assert 'msg' in kwargs, "implementation error -- msg to explain the error is required"
kwargs['failed'] = True
self.do_cleanup_files()
print self.jsonify(kwargs)
sys.exit(1)
def is_executable(self, path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def digest_from_file(self, filename, digest_method):
''' Return hex digest of local file for a given digest_method, or None if file is not present. '''
if not os.path.exists(filename):
return None
if os.path.isdir(filename):
self.fail_json(msg="attempted to take checksum of directory: %s" % filename)
digest = digest_method
blocksize = 64 * 1024
infile = open(filename, 'rb')
block = infile.read(blocksize)
while block:
digest.update(block)
block = infile.read(blocksize)
infile.close()
return digest.hexdigest()
def md5(self, filename):
''' Return MD5 hex digest of local file using digest_from_file(). '''
return self.digest_from_file(filename, _md5())
def sha256(self, filename):
''' Return SHA-256 hex digest of local file using digest_from_file(). '''
if not HAVE_HASHLIB:
self.fail_json(msg="SHA-256 checksums require hashlib, which is available in Python 2.5 and higher")
return self.digest_from_file(filename, _sha256())
def backup_local(self, fn):
'''make a date-marked backup of the specified file, return True or False on success or failure'''
# backups named basename-YYYY-MM-DD@HH:MM~
ext = time.strftime("%Y-%m-%d@%H:%M~", time.localtime(time.time()))
backupdest = '%s.%s' % (fn, ext)
try:
shutil.copy2(fn, backupdest)
except shutil.Error, e:
self.fail_json(msg='Could not make backup of %s to %s: %s' % (fn, backupdest, e))
return backupdest
def cleanup(self, tmpfile):
if os.path.exists(tmpfile):
try:
os.unlink(tmpfile)
except OSError, e:
sys.stderr.write("could not cleanup %s: %s" % (tmpfile, e))
def atomic_move(self, src, dest):
'''atomically move src to dest, copying attributes from dest, returns true on success
it uses os.rename to ensure this as it is an atomic operation, rest of the function is
to work around limitations, corner cases and ensure selinux context is saved if possible'''
context = None
dest_stat = None
if os.path.exists(dest):
try:
dest_stat = os.stat(dest)
os.chmod(src, dest_stat.st_mode & 07777)
os.chown(src, dest_stat.st_uid, dest_stat.st_gid)
except OSError, e:
if e.errno != errno.EPERM:
raise
if self.selinux_enabled():
context = self.selinux_context(dest)
else:
if self.selinux_enabled():
context = self.selinux_default_context(dest)
creating = not os.path.exists(dest)
try:
login_name = os.getlogin()
except OSError:
# not having a tty can cause the above to fail, so
# just get the LOGNAME environment variable instead
login_name = os.environ.get('LOGNAME', None)
# if the original login_name doesn't match the currently
# logged-in user, or if the SUDO_USER environment variable
# is set, then this user has switched their credentials
switched_user = login_name and login_name != pwd.getpwuid(os.getuid())[0] or os.environ.get('SUDO_USER')
try:
# Optimistically try a rename, solves some corner cases and can avoid useless work, throws exception if not atomic.
os.rename(src, dest)
except (IOError,OSError), e:
# only try workarounds for errno 18 (cross device), 1 (not permited) and 13 (permission denied)
if e.errno != errno.EPERM and e.errno != errno.EXDEV and e.errno != errno.EACCES:
self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, e))
dest_dir = os.path.dirname(dest)
dest_file = os.path.basename(dest)
tmp_dest = tempfile.NamedTemporaryFile(
prefix=".ansible_tmp", dir=dest_dir, suffix=dest_file)
try: # leaves tmp file behind when sudo and not root
if switched_user and os.getuid() != 0:
# cleanup will happen by 'rm' of tempdir
# copy2 will preserve some metadata
shutil.copy2(src, tmp_dest.name)
else:
shutil.move(src, tmp_dest.name)
if self.selinux_enabled():
self.set_context_if_different(
tmp_dest.name, context, False)
tmp_stat = os.stat(tmp_dest.name)
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
os.chown(tmp_dest.name, dest_stat.st_uid, dest_stat.st_gid)
os.rename(tmp_dest.name, dest)
except (shutil.Error, OSError, IOError), e:
self.cleanup(tmp_dest.name)
self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, e))
if creating:
# make sure the file has the correct permissions
# based on the current value of umask
umask = os.umask(0)
os.umask(umask)
os.chmod(dest, 0666 ^ umask)
if switched_user:
os.chown(dest, os.getuid(), os.getgid())
if self.selinux_enabled():
# rename might not preserve context
self.set_context_if_different(dest, context, False)
def run_command(self, args, check_rc=False, close_fds=False, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None, use_unsafe_shell=False):
'''
Execute a command, returns rc, stdout, and stderr.
args is the command to run
If args is a list, the command will be run with shell=False.
If args is a string and use_unsafe_shell=False it will split args to a list and run with shell=False
If args is a string and use_unsafe_shell=True it run with shell=True.
Other arguments:
- check_rc (boolean) Whether to call fail_json in case of
non zero RC. Default is False.
- close_fds (boolean) See documentation for subprocess.Popen().
Default is False.
- executable (string) See documentation for subprocess.Popen().
Default is None.
'''
shell = False
if isinstance(args, list):
if use_unsafe_shell:
args = " ".join([pipes.quote(x) for x in args])
shell = True
elif isinstance(args, basestring) and use_unsafe_shell:
shell = True
elif isinstance(args, basestring):
args = shlex.split(args.encode('utf-8'))
else:
msg = "Argument 'args' to run_command must be list or string"
self.fail_json(rc=257, cmd=args, msg=msg)
# expand things like $HOME and ~
if not shell:
args = [ os.path.expandvars(os.path.expanduser(x)) for x in args ]
rc = 0
msg = None
st_in = None
# Set a temporart env path if a prefix is passed
env=os.environ
if path_prefix:
env['PATH']="%s:%s" % (path_prefix, env['PATH'])
# create a printable version of the command for use
# in reporting later, which strips out things like
# passwords from the args list
if isinstance(args, list):
clean_args = " ".join(pipes.quote(arg) for arg in args)
else:
clean_args = args
# all clean strings should return two match groups,
# where the first is the CLI argument and the second
# is the password/key/phrase that will be hidden
clean_re_strings = [
# this removes things like --password, --pass, --pass-wd, etc.
# optionally followed by an '=' or a space. The password can
# be quoted or not too, though it does not care about quotes
# that are not balanced
# source: http://blog.stevenlevithan.com/archives/match-quoted-string
r'([-]{0,2}pass[-]?(?:word|wd)?[=\s]?)((?:["\'])?(?:[^\s])*(?:\1)?)',
# TODO: add more regex checks here
]
for re_str in clean_re_strings:
r = re.compile(re_str)
clean_args = r.sub(r'\1********', clean_args)
if data:
st_in = subprocess.PIPE
kwargs = dict(
executable=executable,
shell=shell,
close_fds=close_fds,
stdin= st_in,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if path_prefix:
kwargs['env'] = env
if cwd and os.path.isdir(cwd):
kwargs['cwd'] = cwd
# store the pwd
prev_dir = os.getcwd()
# make sure we're in the right working directory
if cwd and os.path.isdir(cwd):
try:
os.chdir(cwd)
except (OSError, IOError), e:
self.fail_json(rc=e.errno, msg="Could not open %s , %s" % (cwd, str(e)))
try:
cmd = subprocess.Popen(args, **kwargs)
if data:
if not binary_data:
data += '\n'
out, err = cmd.communicate(input=data)
rc = cmd.returncode
except (OSError, IOError), e:
self.fail_json(rc=e.errno, msg=str(e), cmd=clean_args)
except:
self.fail_json(rc=257, msg=traceback.format_exc(), cmd=clean_args)
if rc != 0 and check_rc:
msg = err.rstrip()
self.fail_json(cmd=clean_args, rc=rc, stdout=out, stderr=err, msg=msg)
# reset the pwd
os.chdir(prev_dir)
return (rc, out, err)
def append_to_file(self, filename, str):
filename = os.path.expandvars(os.path.expanduser(filename))
fh = open(filename, 'a')
fh.write(str)
fh.close()
def pretty_bytes(self,size):
ranges = (
(1<<70L, 'ZB'),
(1<<60L, 'EB'),
(1<<50L, 'PB'),
(1<<40L, 'TB'),
(1<<30L, 'GB'),
(1<<20L, 'MB'),
(1<<10L, 'KB'),
(1, 'Bytes')
)
for limit, suffix in ranges:
if size >= limit:
break
return '%.2f %s' % (float(size)/ limit, suffix)
def get_module_path():
return os.path.dirname(os.path.realpath(__file__))
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_2234_0 |
crossvul-python_data_good_2223_0 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import pwd
import sys
import ConfigParser
from string import ascii_letters, digits
# copied from utils, avoid circular reference fun :)
def mk_boolean(value):
if value is None:
return False
val = str(value)
if val.lower() in [ "true", "t", "y", "1", "yes" ]:
return True
else:
return False
def get_config(p, section, key, env_var, default, boolean=False, integer=False, floating=False, islist=False):
''' return a configuration variable with casting '''
value = _get_config(p, section, key, env_var, default)
if boolean:
return mk_boolean(value)
if value and integer:
return int(value)
if value and floating:
return float(value)
if value and islist:
return [x.strip() for x in value.split(',')]
return value
def _get_config(p, section, key, env_var, default):
''' helper function for get_config '''
if env_var is not None:
value = os.environ.get(env_var, None)
if value is not None:
return value
if p is not None:
try:
return p.get(section, key, raw=True)
except:
return default
return default
def load_config_file():
''' Load Config File order(first found is used): ENV, CWD, HOME, /etc/ansible '''
p = ConfigParser.ConfigParser()
path0 = os.getenv("ANSIBLE_CONFIG", None)
if path0 is not None:
path0 = os.path.expanduser(path0)
path1 = os.getcwd() + "/ansible.cfg"
path2 = os.path.expanduser("~/.ansible.cfg")
path3 = "/etc/ansible/ansible.cfg"
for path in [path0, path1, path2, path3]:
if path is not None and os.path.exists(path):
p.read(path)
return p
return None
def shell_expand_path(path):
''' shell_expand_path is needed as os.path.expanduser does not work
when path is None, which is the default for ANSIBLE_PRIVATE_KEY_FILE '''
if path:
path = os.path.expanduser(path)
return path
p = load_config_file()
active_user = pwd.getpwuid(os.geteuid())[0]
# Needed so the RPM can call setup.py and have modules land in the
# correct location. See #1277 for discussion
if getattr(sys, "real_prefix", None):
# in a virtualenv
DIST_MODULE_PATH = os.path.join(sys.prefix, 'share/ansible/')
else:
DIST_MODULE_PATH = '/usr/share/ansible/'
# check all of these extensions when looking for yaml files for things like
# group variables -- really anything we can load
YAML_FILENAME_EXTENSIONS = [ "", ".yml", ".yaml", ".json" ]
# sections in config file
DEFAULTS='defaults'
# configurable things
DEFAULT_HOST_LIST = shell_expand_path(get_config(p, DEFAULTS, 'hostfile', 'ANSIBLE_HOSTS', '/etc/ansible/hosts'))
DEFAULT_MODULE_PATH = get_config(p, DEFAULTS, 'library', 'ANSIBLE_LIBRARY', DIST_MODULE_PATH)
DEFAULT_ROLES_PATH = shell_expand_path(get_config(p, DEFAULTS, 'roles_path', 'ANSIBLE_ROLES_PATH', '/etc/ansible/roles'))
DEFAULT_REMOTE_TMP = shell_expand_path(get_config(p, DEFAULTS, 'remote_tmp', 'ANSIBLE_REMOTE_TEMP', '$HOME/.ansible/tmp'))
DEFAULT_MODULE_NAME = get_config(p, DEFAULTS, 'module_name', None, 'command')
DEFAULT_PATTERN = get_config(p, DEFAULTS, 'pattern', None, '*')
DEFAULT_FORKS = get_config(p, DEFAULTS, 'forks', 'ANSIBLE_FORKS', 5, integer=True)
DEFAULT_MODULE_ARGS = get_config(p, DEFAULTS, 'module_args', 'ANSIBLE_MODULE_ARGS', '')
DEFAULT_MODULE_LANG = get_config(p, DEFAULTS, 'module_lang', 'ANSIBLE_MODULE_LANG', 'en_US.UTF-8')
DEFAULT_TIMEOUT = get_config(p, DEFAULTS, 'timeout', 'ANSIBLE_TIMEOUT', 10, integer=True)
DEFAULT_POLL_INTERVAL = get_config(p, DEFAULTS, 'poll_interval', 'ANSIBLE_POLL_INTERVAL', 15, integer=True)
DEFAULT_REMOTE_USER = get_config(p, DEFAULTS, 'remote_user', 'ANSIBLE_REMOTE_USER', active_user)
DEFAULT_ASK_PASS = get_config(p, DEFAULTS, 'ask_pass', 'ANSIBLE_ASK_PASS', False, boolean=True)
DEFAULT_PRIVATE_KEY_FILE = shell_expand_path(get_config(p, DEFAULTS, 'private_key_file', 'ANSIBLE_PRIVATE_KEY_FILE', None))
DEFAULT_SUDO_USER = get_config(p, DEFAULTS, 'sudo_user', 'ANSIBLE_SUDO_USER', 'root')
DEFAULT_ASK_SUDO_PASS = get_config(p, DEFAULTS, 'ask_sudo_pass', 'ANSIBLE_ASK_SUDO_PASS', False, boolean=True)
DEFAULT_REMOTE_PORT = get_config(p, DEFAULTS, 'remote_port', 'ANSIBLE_REMOTE_PORT', None, integer=True)
DEFAULT_ASK_VAULT_PASS = get_config(p, DEFAULTS, 'ask_vault_pass', 'ANSIBLE_ASK_VAULT_PASS', False, boolean=True)
DEFAULT_TRANSPORT = get_config(p, DEFAULTS, 'transport', 'ANSIBLE_TRANSPORT', 'smart')
DEFAULT_SCP_IF_SSH = get_config(p, 'ssh_connection', 'scp_if_ssh', 'ANSIBLE_SCP_IF_SSH', False, boolean=True)
DEFAULT_MANAGED_STR = get_config(p, DEFAULTS, 'ansible_managed', None, 'Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}')
DEFAULT_SYSLOG_FACILITY = get_config(p, DEFAULTS, 'syslog_facility', 'ANSIBLE_SYSLOG_FACILITY', 'LOG_USER')
DEFAULT_KEEP_REMOTE_FILES = get_config(p, DEFAULTS, 'keep_remote_files', 'ANSIBLE_KEEP_REMOTE_FILES', False, boolean=True)
DEFAULT_SUDO = get_config(p, DEFAULTS, 'sudo', 'ANSIBLE_SUDO', False, boolean=True)
DEFAULT_SUDO_EXE = get_config(p, DEFAULTS, 'sudo_exe', 'ANSIBLE_SUDO_EXE', 'sudo')
DEFAULT_SUDO_FLAGS = get_config(p, DEFAULTS, 'sudo_flags', 'ANSIBLE_SUDO_FLAGS', '-H')
DEFAULT_HASH_BEHAVIOUR = get_config(p, DEFAULTS, 'hash_behaviour', 'ANSIBLE_HASH_BEHAVIOUR', 'replace')
DEFAULT_JINJA2_EXTENSIONS = get_config(p, DEFAULTS, 'jinja2_extensions', 'ANSIBLE_JINJA2_EXTENSIONS', None)
DEFAULT_EXECUTABLE = get_config(p, DEFAULTS, 'executable', 'ANSIBLE_EXECUTABLE', '/bin/sh')
DEFAULT_SU_EXE = get_config(p, DEFAULTS, 'su_exe', 'ANSIBLE_SU_EXE', 'su')
DEFAULT_SU = get_config(p, DEFAULTS, 'su', 'ANSIBLE_SU', False, boolean=True)
DEFAULT_SU_FLAGS = get_config(p, DEFAULTS, 'su_flags', 'ANSIBLE_SU_FLAGS', '')
DEFAULT_SU_USER = get_config(p, DEFAULTS, 'su_user', 'ANSIBLE_SU_USER', 'root')
DEFAULT_ASK_SU_PASS = get_config(p, DEFAULTS, 'ask_su_pass', 'ANSIBLE_ASK_SU_PASS', False, boolean=True)
DEFAULT_GATHERING = get_config(p, DEFAULTS, 'gathering', 'ANSIBLE_GATHERING', 'implicit').lower()
DEFAULT_ACTION_PLUGIN_PATH = get_config(p, DEFAULTS, 'action_plugins', 'ANSIBLE_ACTION_PLUGINS', '/usr/share/ansible_plugins/action_plugins')
DEFAULT_CALLBACK_PLUGIN_PATH = get_config(p, DEFAULTS, 'callback_plugins', 'ANSIBLE_CALLBACK_PLUGINS', '/usr/share/ansible_plugins/callback_plugins')
DEFAULT_CONNECTION_PLUGIN_PATH = get_config(p, DEFAULTS, 'connection_plugins', 'ANSIBLE_CONNECTION_PLUGINS', '/usr/share/ansible_plugins/connection_plugins')
DEFAULT_LOOKUP_PLUGIN_PATH = get_config(p, DEFAULTS, 'lookup_plugins', 'ANSIBLE_LOOKUP_PLUGINS', '/usr/share/ansible_plugins/lookup_plugins')
DEFAULT_VARS_PLUGIN_PATH = get_config(p, DEFAULTS, 'vars_plugins', 'ANSIBLE_VARS_PLUGINS', '/usr/share/ansible_plugins/vars_plugins')
DEFAULT_FILTER_PLUGIN_PATH = get_config(p, DEFAULTS, 'filter_plugins', 'ANSIBLE_FILTER_PLUGINS', '/usr/share/ansible_plugins/filter_plugins')
DEFAULT_LOG_PATH = shell_expand_path(get_config(p, DEFAULTS, 'log_path', 'ANSIBLE_LOG_PATH', ''))
ANSIBLE_FORCE_COLOR = get_config(p, DEFAULTS, 'force_color', 'ANSIBLE_FORCE_COLOR', None, boolean=True)
ANSIBLE_NOCOLOR = get_config(p, DEFAULTS, 'nocolor', 'ANSIBLE_NOCOLOR', None, boolean=True)
ANSIBLE_NOCOWS = get_config(p, DEFAULTS, 'nocows', 'ANSIBLE_NOCOWS', None, boolean=True)
DISPLAY_SKIPPED_HOSTS = get_config(p, DEFAULTS, 'display_skipped_hosts', 'DISPLAY_SKIPPED_HOSTS', True, boolean=True)
DEFAULT_UNDEFINED_VAR_BEHAVIOR = get_config(p, DEFAULTS, 'error_on_undefined_vars', 'ANSIBLE_ERROR_ON_UNDEFINED_VARS', True, boolean=True)
HOST_KEY_CHECKING = get_config(p, DEFAULTS, 'host_key_checking', 'ANSIBLE_HOST_KEY_CHECKING', True, boolean=True)
SYSTEM_WARNINGS = get_config(p, DEFAULTS, 'system_warnings', 'ANSIBLE_SYSTEM_WARNINGS', True, boolean=True)
DEPRECATION_WARNINGS = get_config(p, DEFAULTS, 'deprecation_warnings', 'ANSIBLE_DEPRECATION_WARNINGS', True, boolean=True)
DEFAULT_CALLABLE_WHITELIST = get_config(p, DEFAULTS, 'callable_whitelist', 'ANSIBLE_CALLABLE_WHITELIST', [], islist=True)
# CONNECTION RELATED
ANSIBLE_SSH_ARGS = get_config(p, 'ssh_connection', 'ssh_args', 'ANSIBLE_SSH_ARGS', None)
ANSIBLE_SSH_CONTROL_PATH = get_config(p, 'ssh_connection', 'control_path', 'ANSIBLE_SSH_CONTROL_PATH', "%(directory)s/ansible-ssh-%%h-%%p-%%r")
ANSIBLE_SSH_PIPELINING = get_config(p, 'ssh_connection', 'pipelining', 'ANSIBLE_SSH_PIPELINING', False, boolean=True)
PARAMIKO_RECORD_HOST_KEYS = get_config(p, 'paramiko_connection', 'record_host_keys', 'ANSIBLE_PARAMIKO_RECORD_HOST_KEYS', True, boolean=True)
# obsolete -- will be formally removed in 1.6
ZEROMQ_PORT = get_config(p, 'fireball_connection', 'zeromq_port', 'ANSIBLE_ZEROMQ_PORT', 5099, integer=True)
ACCELERATE_PORT = get_config(p, 'accelerate', 'accelerate_port', 'ACCELERATE_PORT', 5099, integer=True)
ACCELERATE_TIMEOUT = get_config(p, 'accelerate', 'accelerate_timeout', 'ACCELERATE_TIMEOUT', 30, integer=True)
ACCELERATE_CONNECT_TIMEOUT = get_config(p, 'accelerate', 'accelerate_connect_timeout', 'ACCELERATE_CONNECT_TIMEOUT', 1.0, floating=True)
ACCELERATE_DAEMON_TIMEOUT = get_config(p, 'accelerate', 'accelerate_daemon_timeout', 'ACCELERATE_DAEMON_TIMEOUT', 30, integer=True)
ACCELERATE_KEYS_DIR = get_config(p, 'accelerate', 'accelerate_keys_dir', 'ACCELERATE_KEYS_DIR', '~/.fireball.keys')
ACCELERATE_KEYS_DIR_PERMS = get_config(p, 'accelerate', 'accelerate_keys_dir_perms', 'ACCELERATE_KEYS_DIR_PERMS', '700')
ACCELERATE_KEYS_FILE_PERMS = get_config(p, 'accelerate', 'accelerate_keys_file_perms', 'ACCELERATE_KEYS_FILE_PERMS', '600')
ACCELERATE_MULTI_KEY = get_config(p, 'accelerate', 'accelerate_multi_key', 'ACCELERATE_MULTI_KEY', False, boolean=True)
PARAMIKO_PTY = get_config(p, 'paramiko_connection', 'pty', 'ANSIBLE_PARAMIKO_PTY', True, boolean=True)
# characters included in auto-generated passwords
DEFAULT_PASSWORD_CHARS = ascii_letters + digits + ".,:-_"
# non-configurable things
DEFAULT_SUDO_PASS = None
DEFAULT_REMOTE_PASS = None
DEFAULT_SUBSET = None
DEFAULT_SU_PASS = None
VAULT_VERSION_MIN = 1.0
VAULT_VERSION_MAX = 1.0
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_2223_0 |
crossvul-python_data_bad_4109_0 | """Module for Trivia cog."""
import asyncio
import math
import pathlib
from collections import Counter
from typing import List, Literal
import io
import yaml
import discord
from redbot.core import Config, commands, checks
from redbot.cogs.bank import is_owner_if_bank_global
from redbot.core.data_manager import cog_data_path
from redbot.core.i18n import Translator, cog_i18n
from redbot.core.utils import AsyncIter
from redbot.core.utils.chat_formatting import box, pagify, bold
from redbot.core.utils.menus import start_adding_reactions
from redbot.core.utils.predicates import MessagePredicate, ReactionPredicate
from .checks import trivia_stop_check
from .converters import finite_float
from .log import LOG
from .session import TriviaSession
__all__ = ["Trivia", "UNIQUE_ID", "get_core_lists"]
UNIQUE_ID = 0xB3C0E453
_ = Translator("Trivia", __file__)
class InvalidListError(Exception):
"""A Trivia list file is in invalid format."""
pass
@cog_i18n(_)
class Trivia(commands.Cog):
"""Play trivia with friends!"""
def __init__(self):
super().__init__()
self.trivia_sessions = []
self.config = Config.get_conf(self, identifier=UNIQUE_ID, force_registration=True)
self.config.register_guild(
max_score=10,
timeout=120.0,
delay=15.0,
bot_plays=False,
reveal_answer=True,
payout_multiplier=0.0,
allow_override=True,
)
self.config.register_member(wins=0, games=0, total_score=0)
async def red_delete_data_for_user(
self,
*,
requester: Literal["discord_deleted_user", "owner", "user", "user_strict"],
user_id: int,
):
if requester != "discord_deleted_user":
return
all_members = await self.config.all_members()
async for guild_id, guild_data in AsyncIter(all_members.items(), steps=100):
if user_id in guild_data:
await self.config.member_from_ids(guild_id, user_id).clear()
@commands.group()
@commands.guild_only()
@checks.mod_or_permissions(administrator=True)
async def triviaset(self, ctx: commands.Context):
"""Manage Trivia settings."""
@triviaset.command(name="showsettings")
async def triviaset_showsettings(self, ctx: commands.Context):
"""Show the current trivia settings."""
settings = self.config.guild(ctx.guild)
settings_dict = await settings.all()
msg = box(
_(
"Current settings\n"
"Bot gains points: {bot_plays}\n"
"Answer time limit: {delay} seconds\n"
"Lack of response timeout: {timeout} seconds\n"
"Points to win: {max_score}\n"
"Reveal answer on timeout: {reveal_answer}\n"
"Payout multiplier: {payout_multiplier}\n"
"Allow lists to override settings: {allow_override}"
).format(**settings_dict),
lang="py",
)
await ctx.send(msg)
@triviaset.command(name="maxscore")
async def triviaset_max_score(self, ctx: commands.Context, score: int):
"""Set the total points required to win."""
if score < 0:
await ctx.send(_("Score must be greater than 0."))
return
settings = self.config.guild(ctx.guild)
await settings.max_score.set(score)
await ctx.send(_("Done. Points required to win set to {num}.").format(num=score))
@triviaset.command(name="timelimit")
async def triviaset_timelimit(self, ctx: commands.Context, seconds: finite_float):
"""Set the maximum seconds permitted to answer a question."""
if seconds < 4.0:
await ctx.send(_("Must be at least 4 seconds."))
return
settings = self.config.guild(ctx.guild)
await settings.delay.set(seconds)
await ctx.send(_("Done. Maximum seconds to answer set to {num}.").format(num=seconds))
@triviaset.command(name="stopafter")
async def triviaset_stopafter(self, ctx: commands.Context, seconds: finite_float):
"""Set how long until trivia stops due to no response."""
settings = self.config.guild(ctx.guild)
if seconds < await settings.delay():
await ctx.send(_("Must be larger than the answer time limit."))
return
await settings.timeout.set(seconds)
await ctx.send(
_(
"Done. Trivia sessions will now time out after {num} seconds of no responses."
).format(num=seconds)
)
@triviaset.command(name="override")
async def triviaset_allowoverride(self, ctx: commands.Context, enabled: bool):
"""Allow/disallow trivia lists to override settings."""
settings = self.config.guild(ctx.guild)
await settings.allow_override.set(enabled)
if enabled:
await ctx.send(
_("Done. Trivia lists can now override the trivia settings for this server.")
)
else:
await ctx.send(
_(
"Done. Trivia lists can no longer override the trivia settings for this "
"server."
)
)
@triviaset.command(name="botplays", usage="<true_or_false>")
async def trivaset_bot_plays(self, ctx: commands.Context, enabled: bool):
"""Set whether or not the bot gains points.
If enabled, the bot will gain a point if no one guesses correctly.
"""
settings = self.config.guild(ctx.guild)
await settings.bot_plays.set(enabled)
if enabled:
await ctx.send(_("Done. I'll now gain a point if users don't answer in time."))
else:
await ctx.send(_("Alright, I won't embarass you at trivia anymore."))
@triviaset.command(name="revealanswer", usage="<true_or_false>")
async def trivaset_reveal_answer(self, ctx: commands.Context, enabled: bool):
"""Set whether or not the answer is revealed.
If enabled, the bot will reveal the answer if no one guesses correctly
in time.
"""
settings = self.config.guild(ctx.guild)
await settings.reveal_answer.set(enabled)
if enabled:
await ctx.send(_("Done. I'll reveal the answer if no one knows it."))
else:
await ctx.send(_("Alright, I won't reveal the answer to the questions anymore."))
@is_owner_if_bank_global()
@checks.admin_or_permissions(manage_guild=True)
@triviaset.command(name="payout")
async def triviaset_payout_multiplier(self, ctx: commands.Context, multiplier: finite_float):
"""Set the payout multiplier.
This can be any positive decimal number. If a user wins trivia when at
least 3 members are playing, they will receive credits. Set to 0 to
disable.
The number of credits is determined by multiplying their total score by
this multiplier.
"""
settings = self.config.guild(ctx.guild)
if multiplier < 0:
await ctx.send(_("Multiplier must be at least 0."))
return
await settings.payout_multiplier.set(multiplier)
if multiplier:
await ctx.send(_("Done. Payout multiplier set to {num}.").format(num=multiplier))
else:
await ctx.send(_("Done. I will no longer reward the winner with a payout."))
@triviaset.group(name="custom")
@commands.is_owner()
async def triviaset_custom(self, ctx: commands.Context):
"""Manage Custom Trivia lists."""
pass
@triviaset_custom.command(name="list")
async def custom_trivia_list(self, ctx: commands.Context):
"""List uploaded custom trivia."""
personal_lists = sorted([p.resolve().stem for p in cog_data_path(self).glob("*.yaml")])
no_lists_uploaded = _("No custom Trivia lists uploaded.")
if not personal_lists:
if await ctx.embed_requested():
await ctx.send(
embed=discord.Embed(
colour=await ctx.embed_colour(), description=no_lists_uploaded
)
)
else:
await ctx.send(no_lists_uploaded)
return
if await ctx.embed_requested():
await ctx.send(
embed=discord.Embed(
title=_("Uploaded trivia lists"),
colour=await ctx.embed_colour(),
description=", ".join(sorted(personal_lists)),
)
)
else:
msg = box(
bold(_("Uploaded trivia lists")) + "\n\n" + ", ".join(sorted(personal_lists))
)
if len(msg) > 1000:
await ctx.author.send(msg)
else:
await ctx.send(msg)
@commands.is_owner()
@triviaset_custom.command(name="upload", aliases=["add"])
async def trivia_upload(self, ctx: commands.Context):
"""Upload a trivia file."""
if not ctx.message.attachments:
await ctx.send(_("Supply a file with next message or type anything to cancel."))
try:
message = await ctx.bot.wait_for(
"message", check=MessagePredicate.same_context(ctx), timeout=30
)
except asyncio.TimeoutError:
await ctx.send(_("You took too long to upload a list."))
return
if not message.attachments:
await ctx.send(_("You have cancelled the upload process."))
return
parsedfile = message.attachments[0]
else:
parsedfile = ctx.message.attachments[0]
try:
await self._save_trivia_list(ctx=ctx, attachment=parsedfile)
except yaml.error.MarkedYAMLError as exc:
await ctx.send(_("Invalid syntax: ") + str(exc))
except yaml.error.YAMLError:
await ctx.send(
_("There was an error parsing the trivia list. See logs for more info.")
)
LOG.exception("Custom Trivia file %s failed to upload", parsedfile.filename)
@commands.is_owner()
@triviaset_custom.command(name="delete", aliases=["remove"])
async def trivia_delete(self, ctx: commands.Context, name: str):
"""Delete a trivia file."""
filepath = cog_data_path(self) / f"{name}.yaml"
if filepath.exists():
filepath.unlink()
await ctx.send(_("Trivia {filename} was deleted.").format(filename=filepath.stem))
else:
await ctx.send(_("Trivia file was not found."))
@commands.group(invoke_without_command=True)
@commands.guild_only()
async def trivia(self, ctx: commands.Context, *categories: str):
"""Start trivia session on the specified category.
You may list multiple categories, in which case the trivia will involve
questions from all of them.
"""
if not categories:
await ctx.send_help()
return
categories = [c.lower() for c in categories]
session = self._get_trivia_session(ctx.channel)
if session is not None:
await ctx.send(_("There is already an ongoing trivia session in this channel."))
return
trivia_dict = {}
authors = []
for category in reversed(categories):
# We reverse the categories so that the first list's config takes
# priority over the others.
try:
dict_ = self.get_trivia_list(category)
except FileNotFoundError:
await ctx.send(
_(
"Invalid category `{name}`. See `{prefix}trivia list` for a list of "
"trivia categories."
).format(name=category, prefix=ctx.clean_prefix)
)
except InvalidListError:
await ctx.send(
_(
"There was an error parsing the trivia list for the `{name}` category. It "
"may be formatted incorrectly."
).format(name=category)
)
else:
trivia_dict.update(dict_)
authors.append(trivia_dict.pop("AUTHOR", None))
continue
return
if not trivia_dict:
await ctx.send(
_("The trivia list was parsed successfully, however it appears to be empty!")
)
return
settings = await self.config.guild(ctx.guild).all()
config = trivia_dict.pop("CONFIG", None)
if config and settings["allow_override"]:
settings.update(config)
settings["lists"] = dict(zip(categories, reversed(authors)))
session = TriviaSession.start(ctx, trivia_dict, settings)
self.trivia_sessions.append(session)
LOG.debug("New trivia session; #%s in %d", ctx.channel, ctx.guild.id)
@trivia_stop_check()
@trivia.command(name="stop")
async def trivia_stop(self, ctx: commands.Context):
"""Stop an ongoing trivia session."""
session = self._get_trivia_session(ctx.channel)
if session is None:
await ctx.send(_("There is no ongoing trivia session in this channel."))
return
await session.end_game()
session.force_stop()
await ctx.send(_("Trivia stopped."))
@trivia.command(name="list")
async def trivia_list(self, ctx: commands.Context):
"""List available trivia categories."""
lists = set(p.stem for p in self._all_lists())
if await ctx.embed_requested():
await ctx.send(
embed=discord.Embed(
title=_("Available trivia lists"),
colour=await ctx.embed_colour(),
description=", ".join(sorted(lists)),
)
)
else:
msg = box(bold(_("Available trivia lists")) + "\n\n" + ", ".join(sorted(lists)))
if len(msg) > 1000:
await ctx.author.send(msg)
else:
await ctx.send(msg)
@trivia.group(
name="leaderboard", aliases=["lboard"], autohelp=False, invoke_without_command=True
)
async def trivia_leaderboard(self, ctx: commands.Context):
"""Leaderboard for trivia.
Defaults to the top 10 of this server, sorted by total wins. Use
subcommands for a more customised leaderboard.
"""
cmd = self.trivia_leaderboard_server
if isinstance(ctx.channel, discord.abc.PrivateChannel):
cmd = self.trivia_leaderboard_global
await ctx.invoke(cmd, "wins", 10)
@trivia_leaderboard.command(name="server")
@commands.guild_only()
async def trivia_leaderboard_server(
self, ctx: commands.Context, sort_by: str = "wins", top: int = 10
):
"""Leaderboard for this server.
`<sort_by>` can be any of the following fields:
- `wins` : total wins
- `avg` : average score
- `total` : total correct answers
- `games` : total games played
`<top>` is the number of ranks to show on the leaderboard.
"""
key = self._get_sort_key(sort_by)
if key is None:
await ctx.send(
_(
"Unknown field `{field_name}`, see `{prefix}help trivia leaderboard server` "
"for valid fields to sort by."
).format(field_name=sort_by, prefix=ctx.clean_prefix)
)
return
guild = ctx.guild
data = await self.config.all_members(guild)
data = {guild.get_member(u): d for u, d in data.items()}
data.pop(None, None) # remove any members which aren't in the guild
await self.send_leaderboard(ctx, data, key, top)
@trivia_leaderboard.command(name="global")
async def trivia_leaderboard_global(
self, ctx: commands.Context, sort_by: str = "wins", top: int = 10
):
"""Global trivia leaderboard.
`<sort_by>` can be any of the following fields:
- `wins` : total wins
- `avg` : average score
- `total` : total correct answers from all sessions
- `games` : total games played
`<top>` is the number of ranks to show on the leaderboard.
"""
key = self._get_sort_key(sort_by)
if key is None:
await ctx.send(
_(
"Unknown field `{field_name}`, see `{prefix}help trivia leaderboard server` "
"for valid fields to sort by."
).format(field_name=sort_by, prefix=ctx.clean_prefix)
)
return
data = await self.config.all_members()
collated_data = {}
for guild_id, guild_data in data.items():
guild = ctx.bot.get_guild(guild_id)
if guild is None:
continue
for member_id, member_data in guild_data.items():
member = guild.get_member(member_id)
if member is None:
continue
collated_member_data = collated_data.get(member, Counter())
for v_key, value in member_data.items():
collated_member_data[v_key] += value
collated_data[member] = collated_member_data
await self.send_leaderboard(ctx, collated_data, key, top)
@staticmethod
def _get_sort_key(key: str):
key = key.lower()
if key in ("wins", "average_score", "total_score", "games"):
return key
elif key in ("avg", "average"):
return "average_score"
elif key in ("total", "score", "answers", "correct"):
return "total_score"
async def send_leaderboard(self, ctx: commands.Context, data: dict, key: str, top: int):
"""Send the leaderboard from the given data.
Parameters
----------
ctx : commands.Context
The context to send the leaderboard to.
data : dict
The data for the leaderboard. This must map `discord.Member` ->
`dict`.
key : str
The field to sort the data by. Can be ``wins``, ``total_score``,
``games`` or ``average_score``.
top : int
The number of members to display on the leaderboard.
Returns
-------
`list` of `discord.Message`
The sent leaderboard messages.
"""
if not data:
await ctx.send(_("There are no scores on record!"))
return
leaderboard = self._get_leaderboard(data, key, top)
ret = []
for page in pagify(leaderboard, shorten_by=10):
ret.append(await ctx.send(box(page, lang="py")))
return ret
@staticmethod
def _get_leaderboard(data: dict, key: str, top: int):
# Mix in average score
for member, stats in data.items():
if stats["games"] != 0:
stats["average_score"] = stats["total_score"] / stats["games"]
else:
stats["average_score"] = 0.0
# Sort by reverse order of priority
priority = ["average_score", "total_score", "wins", "games"]
try:
priority.remove(key)
except ValueError:
raise ValueError(f"{key} is not a valid key.")
# Put key last in reverse priority
priority.append(key)
items = data.items()
for key in priority:
items = sorted(items, key=lambda t: t[1][key], reverse=True)
max_name_len = max(map(lambda m: len(str(m)), data.keys()))
# Headers
headers = (
_("Rank"),
_("Member") + " " * (max_name_len - 6),
_("Wins"),
_("Games Played"),
_("Total Score"),
_("Average Score"),
)
lines = [" | ".join(headers), " | ".join(("-" * len(h) for h in headers))]
# Header underlines
for rank, tup in enumerate(items, 1):
member, m_data = tup
# Align fields to header width
fields = tuple(
map(
str,
(
rank,
member,
m_data["wins"],
m_data["games"],
m_data["total_score"],
round(m_data["average_score"], 2),
),
)
)
padding = [" " * (len(h) - len(f)) for h, f in zip(headers, fields)]
fields = tuple(f + padding[i] for i, f in enumerate(fields))
lines.append(" | ".join(fields).format(member=member, **m_data))
if rank == top:
break
return "\n".join(lines)
@commands.Cog.listener()
async def on_trivia_end(self, session: TriviaSession):
"""Event for a trivia session ending.
This method removes the session from this cog's sessions, and
cancels any tasks which it was running.
Parameters
----------
session : TriviaSession
The session which has just ended.
"""
channel = session.ctx.channel
LOG.debug("Ending trivia session; #%s in %s", channel, channel.guild.id)
if session in self.trivia_sessions:
self.trivia_sessions.remove(session)
if session.scores:
await self.update_leaderboard(session)
async def update_leaderboard(self, session):
"""Update the leaderboard with the given scores.
Parameters
----------
session : TriviaSession
The trivia session to update scores from.
"""
max_score = session.settings["max_score"]
for member, score in session.scores.items():
if member.id == session.ctx.bot.user.id:
continue
stats = await self.config.member(member).all()
if score == max_score:
stats["wins"] += 1
stats["total_score"] += score
stats["games"] += 1
await self.config.member(member).set(stats)
def get_trivia_list(self, category: str) -> dict:
"""Get the trivia list corresponding to the given category.
Parameters
----------
category : str
The desired category. Case sensitive.
Returns
-------
`dict`
A dict mapping questions (`str`) to answers (`list` of `str`).
"""
try:
path = next(p for p in self._all_lists() if p.stem == category)
except StopIteration:
raise FileNotFoundError("Could not find the `{}` category.".format(category))
with path.open(encoding="utf-8") as file:
try:
dict_ = yaml.safe_load(file)
except yaml.error.YAMLError as exc:
raise InvalidListError("YAML parsing failed.") from exc
else:
return dict_
async def _save_trivia_list(
self, ctx: commands.Context, attachment: discord.Attachment
) -> None:
"""Checks and saves a trivia list to data folder.
Parameters
----------
file : discord.Attachment
A discord message attachment.
Returns
-------
None
"""
filename = attachment.filename.rsplit(".", 1)[0]
# Check if trivia filename exists in core files or if it is a command
if filename in self.trivia.all_commands or any(
filename == item.stem for item in get_core_lists()
):
await ctx.send(
_(
"{filename} is a reserved trivia name and cannot be replaced.\n"
"Choose another name."
).format(filename=filename)
)
return
file = cog_data_path(self) / f"{filename}.yaml"
if file.exists():
overwrite_message = _("{filename} already exists. Do you wish to overwrite?").format(
filename=filename
)
can_react = ctx.channel.permissions_for(ctx.me).add_reactions
if not can_react:
overwrite_message += " (y/n)"
overwrite_message_object: discord.Message = await ctx.send(overwrite_message)
if can_react:
# noinspection PyAsyncCall
start_adding_reactions(
overwrite_message_object, ReactionPredicate.YES_OR_NO_EMOJIS
)
pred = ReactionPredicate.yes_or_no(overwrite_message_object, ctx.author)
event = "reaction_add"
else:
pred = MessagePredicate.yes_or_no(ctx=ctx)
event = "message"
try:
await ctx.bot.wait_for(event, check=pred, timeout=30)
except asyncio.TimeoutError:
await ctx.send(_("You took too long answering."))
return
if pred.result is False:
await ctx.send(_("I am not replacing the existing file."))
return
buffer = io.BytesIO(await attachment.read())
yaml.safe_load(buffer)
buffer.seek(0)
with file.open("wb") as fp:
fp.write(buffer.read())
await ctx.send(_("Saved Trivia list as {filename}.").format(filename=filename))
def _get_trivia_session(self, channel: discord.TextChannel) -> TriviaSession:
return next(
(session for session in self.trivia_sessions if session.ctx.channel == channel), None
)
def _all_lists(self) -> List[pathlib.Path]:
personal_lists = [p.resolve() for p in cog_data_path(self).glob("*.yaml")]
return personal_lists + get_core_lists()
def cog_unload(self):
for session in self.trivia_sessions:
session.force_stop()
def get_core_lists() -> List[pathlib.Path]:
"""Return a list of paths for all trivia lists packaged with the bot."""
core_lists_path = pathlib.Path(__file__).parent.resolve() / "data/lists"
return list(core_lists_path.glob("*.yaml"))
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_4109_0 |
crossvul-python_data_good_2234_3 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
from ansible import utils
import ansible.constants as C
import ansible.utils.template as template
from ansible import errors
from ansible.runner.return_data import ReturnData
import base64
import json
import stat
import tempfile
import pipes
## fixes https://github.com/ansible/ansible/issues/3518
# http://mypy.pythonblogs.com/12_mypy/archive/1253_workaround_for_python_bug_ascii_codec_cant_encode_character_uxa0_in_position_111_ordinal_not_in_range128.html
import sys
reload(sys)
sys.setdefaultencoding("utf8")
class ActionModule(object):
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp_path, module_name, module_args, inject, complex_args=None, **kwargs):
''' handler for file transfer operations '''
# load up options
options = {}
if complex_args:
options.update(complex_args)
options.update(utils.parse_kv(module_args))
source = options.get('src', None)
content = options.get('content', None)
dest = options.get('dest', None)
raw = utils.boolean(options.get('raw', 'no'))
force = utils.boolean(options.get('force', 'yes'))
# content with newlines is going to be escaped to safely load in yaml
# now we need to unescape it so that the newlines are evaluated properly
# when writing the file to disk
if content:
if isinstance(content, unicode):
try:
content = content.decode('unicode-escape')
except UnicodeDecodeError:
pass
if (source is None and content is None and not 'first_available_file' in inject) or dest is None:
result=dict(failed=True, msg="src (or content) and dest are required")
return ReturnData(conn=conn, result=result)
elif (source is not None or 'first_available_file' in inject) and content is not None:
result=dict(failed=True, msg="src and content are mutually exclusive")
return ReturnData(conn=conn, result=result)
# Check if the source ends with a "/"
source_trailing_slash = False
if source:
source_trailing_slash = source.endswith("/")
# Define content_tempfile in case we set it after finding content populated.
content_tempfile = None
# If content is defined make a temp file and write the content into it.
if content is not None:
try:
# If content comes to us as a dict it should be decoded json.
# We need to encode it back into a string to write it out.
if type(content) is dict:
content_tempfile = self._create_content_tempfile(json.dumps(content))
else:
content_tempfile = self._create_content_tempfile(content)
source = content_tempfile
except Exception, err:
result = dict(failed=True, msg="could not write content temp file: %s" % err)
return ReturnData(conn=conn, result=result)
# if we have first_available_file in our vars
# look up the files and use the first one we find as src
elif 'first_available_file' in inject:
found = False
for fn in inject.get('first_available_file'):
fn_orig = fn
fnt = template.template(self.runner.basedir, fn, inject)
fnd = utils.path_dwim(self.runner.basedir, fnt)
if not os.path.exists(fnd) and '_original_file' in inject:
fnd = utils.path_dwim_relative(inject['_original_file'], 'files', fnt, self.runner.basedir, check=False)
if os.path.exists(fnd):
source = fnd
found = True
break
if not found:
results = dict(failed=True, msg="could not find src in first_available_file list")
return ReturnData(conn=conn, result=results)
else:
source = template.template(self.runner.basedir, source, inject)
if '_original_file' in inject:
source = utils.path_dwim_relative(inject['_original_file'], 'files', source, self.runner.basedir)
else:
source = utils.path_dwim(self.runner.basedir, source)
# A list of source file tuples (full_path, relative_path) which will try to copy to the destination
source_files = []
# If source is a directory populate our list else source is a file and translate it to a tuple.
if os.path.isdir(source):
# Get the amount of spaces to remove to get the relative path.
if source_trailing_slash:
sz = len(source) + 1
else:
sz = len(source.rsplit('/', 1)[0]) + 1
# Walk the directory and append the file tuples to source_files.
for base_path, sub_folders, files in os.walk(source):
for file in files:
full_path = os.path.join(base_path, file)
rel_path = full_path[sz:]
source_files.append((full_path, rel_path))
# If it's recursive copy, destination is always a dir,
# explicitly mark it so (note - copy module relies on this).
if not dest.endswith("/"):
dest += "/"
else:
source_files.append((source, os.path.basename(source)))
changed = False
diffs = []
module_result = {"changed": False}
# A register for if we executed a module.
# Used to cut down on command calls when not recursive.
module_executed = False
# Tell _execute_module to delete the file if there is one file.
delete_remote_tmp = (len(source_files) == 1)
# If this is a recursive action create a tmp_path that we can share as the _exec_module create is too late.
if not delete_remote_tmp:
if "-tmp-" not in tmp_path:
tmp_path = self.runner._make_tmp_path(conn)
for source_full, source_rel in source_files:
# Generate the MD5 hash of the local file.
local_md5 = utils.md5(source_full)
# If local_md5 is not defined we can't find the file so we should fail out.
if local_md5 is None:
result = dict(failed=True, msg="could not find src=%s" % source_full)
return ReturnData(conn=conn, result=result)
# This is kind of optimization - if user told us destination is
# dir, do path manipulation right away, otherwise we still check
# for dest being a dir via remote call below.
if dest.endswith("/"):
dest_file = os.path.join(dest, source_rel)
else:
dest_file = dest
# Attempt to get the remote MD5 Hash.
remote_md5 = self.runner._remote_md5(conn, tmp_path, dest_file)
if remote_md5 == '3':
# The remote_md5 was executed on a directory.
if content is not None:
# If source was defined as content remove the temporary file and fail out.
self._remove_tempfile_if_content_defined(content, content_tempfile)
result = dict(failed=True, msg="can not use content with a dir as dest")
return ReturnData(conn=conn, result=result)
else:
# Append the relative source location to the destination and retry remote_md5.
dest_file = os.path.join(dest, source_rel)
remote_md5 = self.runner._remote_md5(conn, tmp_path, dest_file)
if remote_md5 != '1' and not force:
# remote_file does not exist so continue to next iteration.
continue
if local_md5 != remote_md5:
# The MD5 hashes don't match and we will change or error out.
changed = True
# Create a tmp_path if missing only if this is not recursive.
# If this is recursive we already have a tmp_path.
if delete_remote_tmp:
if "-tmp-" not in tmp_path:
tmp_path = self.runner._make_tmp_path(conn)
if self.runner.diff and not raw:
diff = self._get_diff_data(conn, tmp_path, inject, dest_file, source_full)
else:
diff = {}
if self.runner.noop_on_check(inject):
self._remove_tempfile_if_content_defined(content, content_tempfile)
diffs.append(diff)
changed = True
module_result = dict(changed=True)
continue
# Define a remote directory that we will copy the file to.
tmp_src = tmp_path + 'source'
if not raw:
conn.put_file(source_full, tmp_src)
else:
conn.put_file(source_full, dest_file)
# We have copied the file remotely and no longer require our content_tempfile
self._remove_tempfile_if_content_defined(content, content_tempfile)
# fix file permissions when the copy is done as a different user
if self.runner.sudo and self.runner.sudo_user != 'root' and not raw:
self.runner._low_level_exec_command(conn, "chmod a+r %s" % tmp_src, tmp_path)
if raw:
# Continue to next iteration if raw is defined.
continue
# Run the copy module
# src and dest here come after original and override them
# we pass dest only to make sure it includes trailing slash in case of recursive copy
new_module_args = dict(
src=tmp_src,
dest=dest,
original_basename=source_rel
)
if self.runner.no_log:
new_module_args['NO_LOG'] = True
module_args_tmp = utils.merge_module_args(module_args, new_module_args)
module_return = self.runner._execute_module(conn, tmp_path, 'copy', module_args_tmp, inject=inject, complex_args=complex_args, delete_remote_tmp=delete_remote_tmp)
module_executed = True
else:
# no need to transfer the file, already correct md5, but still need to call
# the file module in case we want to change attributes
self._remove_tempfile_if_content_defined(content, content_tempfile)
if raw:
# Continue to next iteration if raw is defined.
# self.runner._remove_tmp_path(conn, tmp_path)
continue
tmp_src = tmp_path + source_rel
# Build temporary module_args.
new_module_args = dict(
src=tmp_src,
dest=dest,
)
if self.runner.noop_on_check(inject):
new_module_args['CHECKMODE'] = True
if self.runner.no_log:
new_module_args['NO_LOG'] = True
module_args_tmp = utils.merge_module_args(module_args, new_module_args)
# Execute the file module.
module_return = self.runner._execute_module(conn, tmp_path, 'file', module_args_tmp, inject=inject, complex_args=complex_args, delete_remote_tmp=delete_remote_tmp)
module_executed = True
module_result = module_return.result
if not module_result.get('md5sum'):
module_result['md5sum'] = local_md5
if module_result.get('failed') == True:
return module_return
if module_result.get('changed') == True:
changed = True
# Delete tmp_path if we were recursive or if we did not execute a module.
if (not C.DEFAULT_KEEP_REMOTE_FILES and not delete_remote_tmp) \
or (not C.DEFAULT_KEEP_REMOTE_FILES and delete_remote_tmp and not module_executed):
self.runner._remove_tmp_path(conn, tmp_path)
# the file module returns the file path as 'path', but
# the copy module uses 'dest', so add it if it's not there
if 'path' in module_result and 'dest' not in module_result:
module_result['dest'] = module_result['path']
# TODO: Support detailed status/diff for multiple files
if len(source_files) == 1:
result = module_result
else:
result = dict(dest=dest, src=source, changed=changed)
if len(diffs) == 1:
return ReturnData(conn=conn, result=result, diff=diffs[0])
else:
return ReturnData(conn=conn, result=result)
def _create_content_tempfile(self, content):
''' Create a tempfile containing defined content '''
fd, content_tempfile = tempfile.mkstemp()
f = os.fdopen(fd, 'w')
try:
f.write(content)
except Exception, err:
os.remove(content_tempfile)
raise Exception(err)
finally:
f.close()
return content_tempfile
def _get_diff_data(self, conn, tmp, inject, destination, source):
peek_result = self.runner._execute_module(conn, tmp, 'file', "path=%s diff_peek=1" % destination, inject=inject, persist_files=True)
if not peek_result.is_successful():
return {}
diff = {}
if peek_result.result['state'] == 'absent':
diff['before'] = ''
elif peek_result.result['appears_binary']:
diff['dst_binary'] = 1
elif peek_result.result['size'] > utils.MAX_FILE_SIZE_FOR_DIFF:
diff['dst_larger'] = utils.MAX_FILE_SIZE_FOR_DIFF
else:
dest_result = self.runner._execute_module(conn, tmp, 'slurp', "path=%s" % destination, inject=inject, persist_files=True)
if 'content' in dest_result.result:
dest_contents = dest_result.result['content']
if dest_result.result['encoding'] == 'base64':
dest_contents = base64.b64decode(dest_contents)
else:
raise Exception("unknown encoding, failed: %s" % dest_result.result)
diff['before_header'] = destination
diff['before'] = dest_contents
src = open(source)
src_contents = src.read(8192)
st = os.stat(source)
if "\x00" in src_contents:
diff['src_binary'] = 1
elif st[stat.ST_SIZE] > utils.MAX_FILE_SIZE_FOR_DIFF:
diff['src_larger'] = utils.MAX_FILE_SIZE_FOR_DIFF
else:
src.seek(0)
diff['after_header'] = source
diff['after'] = src.read()
return diff
def _remove_tempfile_if_content_defined(self, content, content_tempfile):
if content is not None:
os.remove(content_tempfile)
def _result_key_merge(self, options, results):
# add keys to file module results to mimic copy
if 'path' in results.result and 'dest' not in results.result:
results.result['dest'] = results.result['path']
del results.result['path']
return results
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_2234_3 |
crossvul-python_data_good_2234_5 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import sys
import re
import os
import shlex
import yaml
import copy
import optparse
import operator
from ansible import errors
from ansible import __version__
from ansible.utils import template
from ansible.utils.display_functions import *
from ansible.utils.plugins import *
from ansible.callbacks import display
import ansible.constants as C
import ast
import time
import StringIO
import stat
import termios
import tty
import pipes
import random
import difflib
import warnings
import traceback
import getpass
import sys
import json
from vault import VaultLib
VERBOSITY=0
MAX_FILE_SIZE_FOR_DIFF=1*1024*1024
# caching the compilation of the regex used
# to check for lookup calls within data
LOOKUP_REGEX=re.compile(r'lookup\s*\(')
try:
import json
except ImportError:
import simplejson as json
try:
from hashlib import md5 as _md5
except ImportError:
from md5 import md5 as _md5
PASSLIB_AVAILABLE = False
try:
import passlib.hash
PASSLIB_AVAILABLE = True
except:
pass
try:
import builtin
except ImportError:
import __builtin__ as builtin
KEYCZAR_AVAILABLE=False
try:
try:
# some versions of pycrypto may not have this?
from Crypto.pct_warnings import PowmInsecureWarning
except ImportError:
PowmInsecureWarning = RuntimeWarning
with warnings.catch_warnings(record=True) as warning_handler:
warnings.simplefilter("error", PowmInsecureWarning)
try:
import keyczar.errors as key_errors
from keyczar.keys import AesKey
except PowmInsecureWarning:
system_warning(
"The version of gmp you have installed has a known issue regarding " + \
"timing vulnerabilities when used with pycrypto. " + \
"If possible, you should update it (ie. yum update gmp)."
)
warnings.resetwarnings()
warnings.simplefilter("ignore")
import keyczar.errors as key_errors
from keyczar.keys import AesKey
KEYCZAR_AVAILABLE=True
except ImportError:
pass
###############################################################
# Abstractions around keyczar
###############################################################
def key_for_hostname(hostname):
# fireball mode is an implementation of ansible firing up zeromq via SSH
# to use no persistent daemons or key management
if not KEYCZAR_AVAILABLE:
raise errors.AnsibleError("python-keyczar must be installed on the control machine to use accelerated modes")
key_path = os.path.expanduser(C.ACCELERATE_KEYS_DIR)
if not os.path.exists(key_path):
os.makedirs(key_path, mode=0700)
os.chmod(key_path, int(C.ACCELERATE_KEYS_DIR_PERMS, 8))
elif not os.path.isdir(key_path):
raise errors.AnsibleError('ACCELERATE_KEYS_DIR is not a directory.')
if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_DIR_PERMS, 8):
raise errors.AnsibleError('Incorrect permissions on the private key directory. Use `chmod 0%o %s` to correct this issue, and make sure any of the keys files contained within that directory are set to 0%o' % (int(C.ACCELERATE_KEYS_DIR_PERMS, 8), C.ACCELERATE_KEYS_DIR, int(C.ACCELERATE_KEYS_FILE_PERMS, 8)))
key_path = os.path.join(key_path, hostname)
# use new AES keys every 2 hours, which means fireball must not allow running for longer either
if not os.path.exists(key_path) or (time.time() - os.path.getmtime(key_path) > 60*60*2):
key = AesKey.Generate()
fd = os.open(key_path, os.O_WRONLY | os.O_CREAT, int(C.ACCELERATE_KEYS_FILE_PERMS, 8))
fh = os.fdopen(fd, 'w')
fh.write(str(key))
fh.close()
return key
else:
if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_FILE_PERMS, 8):
raise errors.AnsibleError('Incorrect permissions on the key file for this host. Use `chmod 0%o %s` to correct this issue.' % (int(C.ACCELERATE_KEYS_FILE_PERMS, 8), key_path))
fh = open(key_path)
key = AesKey.Read(fh.read())
fh.close()
return key
def encrypt(key, msg):
return key.Encrypt(msg)
def decrypt(key, msg):
try:
return key.Decrypt(msg)
except key_errors.InvalidSignatureError:
raise errors.AnsibleError("decryption failed")
###############################################################
# UTILITY FUNCTIONS FOR COMMAND LINE TOOLS
###############################################################
def err(msg):
''' print an error message to stderr '''
print >> sys.stderr, msg
def exit(msg, rc=1):
''' quit with an error to stdout and a failure code '''
err(msg)
sys.exit(rc)
def jsonify(result, format=False):
''' format JSON output (uncompressed or uncompressed) '''
if result is None:
return "{}"
result2 = result.copy()
for key, value in result2.items():
if type(value) is str:
result2[key] = value.decode('utf-8', 'ignore')
if format:
return json.dumps(result2, sort_keys=True, indent=4)
else:
return json.dumps(result2, sort_keys=True)
def write_tree_file(tree, hostname, buf):
''' write something into treedir/hostname '''
# TODO: might be nice to append playbook runs per host in a similar way
# in which case, we'd want append mode.
path = os.path.join(tree, hostname)
fd = open(path, "w+")
fd.write(buf)
fd.close()
def is_failed(result):
''' is a given JSON result a failed result? '''
return ((result.get('rc', 0) != 0) or (result.get('failed', False) in [ True, 'True', 'true']))
def is_changed(result):
''' is a given JSON result a changed result? '''
return (result.get('changed', False) in [ True, 'True', 'true'])
def check_conditional(conditional, basedir, inject, fail_on_undefined=False):
if conditional is None or conditional == '':
return True
if isinstance(conditional, list):
for x in conditional:
if not check_conditional(x, basedir, inject, fail_on_undefined=fail_on_undefined):
return False
return True
if not isinstance(conditional, basestring):
return conditional
conditional = conditional.replace("jinja2_compare ","")
# allow variable names
if conditional in inject and '-' not in str(inject[conditional]):
conditional = inject[conditional]
conditional = template.template(basedir, conditional, inject, fail_on_undefined=fail_on_undefined)
original = str(conditional).replace("jinja2_compare ","")
# a Jinja2 evaluation that results in something Python can eval!
presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional
conditional = template.template(basedir, presented, inject)
val = conditional.strip()
if val == presented:
# the templating failed, meaning most likely a
# variable was undefined. If we happened to be
# looking for an undefined variable, return True,
# otherwise fail
if "is undefined" in conditional:
return True
elif "is defined" in conditional:
return False
else:
raise errors.AnsibleError("error while evaluating conditional: %s" % original)
elif val == "True":
return True
elif val == "False":
return False
else:
raise errors.AnsibleError("unable to evaluate conditional: %s" % original)
def is_executable(path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def unfrackpath(path):
'''
returns a path that is free of symlinks, environment
variables, relative path traversals and symbols (~)
example:
'$HOME/../../var/mail' becomes '/var/spool/mail'
'''
return os.path.normpath(os.path.realpath(os.path.expandvars(os.path.expanduser(path))))
def prepare_writeable_dir(tree,mode=0777):
''' make sure a directory exists and is writeable '''
# modify the mode to ensure the owner at least
# has read/write access to this directory
mode |= 0700
# make sure the tree path is always expanded
# and normalized and free of symlinks
tree = unfrackpath(tree)
if not os.path.exists(tree):
try:
os.makedirs(tree, mode)
except (IOError, OSError), e:
raise errors.AnsibleError("Could not make dir %s: %s" % (tree, e))
if not os.access(tree, os.W_OK):
raise errors.AnsibleError("Cannot write to path %s" % tree)
return tree
def path_dwim(basedir, given):
'''
make relative paths work like folks expect.
'''
if given.startswith("/"):
return os.path.abspath(given)
elif given.startswith("~"):
return os.path.abspath(os.path.expanduser(given))
else:
if basedir is None:
basedir = "."
return os.path.abspath(os.path.join(basedir, given))
def path_dwim_relative(original, dirname, source, playbook_base, check=True):
''' find one file in a directory one level up in a dir named dirname relative to current '''
# (used by roles code)
basedir = os.path.dirname(original)
if os.path.islink(basedir):
basedir = unfrackpath(basedir)
template2 = os.path.join(basedir, dirname, source)
else:
template2 = os.path.join(basedir, '..', dirname, source)
source2 = path_dwim(basedir, template2)
if os.path.exists(source2):
return source2
obvious_local_path = path_dwim(playbook_base, source)
if os.path.exists(obvious_local_path):
return obvious_local_path
if check:
raise errors.AnsibleError("input file not found at %s or %s" % (source2, obvious_local_path))
return source2 # which does not exist
def json_loads(data):
''' parse a JSON string and return a data structure '''
return json.loads(data)
def _clean_data(orig_data, from_remote=False, from_inventory=False):
''' remove template tags from a string '''
data = orig_data
if isinstance(orig_data, basestring):
sub_list = [('{%','{#'), ('%}','#}')]
if from_remote or (from_inventory and '{{' in data and LOOKUP_REGEX.search(data)):
# if from a remote, we completely disable any jinja2 blocks
sub_list.extend([('{{','{#'), ('}}','#}')])
for pattern,replacement in sub_list:
data = data.replace(pattern, replacement)
return data
def _clean_data_struct(orig_data, from_remote=False, from_inventory=False):
'''
walk a complex data structure, and use _clean_data() to
remove any template tags that may exist
'''
if not from_remote and not from_inventory:
raise errors.AnsibleErrors("when cleaning data, you must specify either from_remote or from_inventory")
if isinstance(orig_data, dict):
data = orig_data.copy()
for key in data:
new_key = _clean_data_struct(key, from_remote, from_inventory)
new_val = _clean_data_struct(data[key], from_remote, from_inventory)
if key != new_key:
del data[key]
data[new_key] = new_val
elif isinstance(orig_data, list):
data = orig_data[:]
for i in range(0, len(data)):
data[i] = _clean_data_struct(data[i], from_remote, from_inventory)
elif isinstance(orig_data, basestring):
data = _clean_data(orig_data, from_remote, from_inventory)
else:
data = orig_data
return data
def parse_json(raw_data, from_remote=False, from_inventory=False):
''' this version for module return data only '''
orig_data = raw_data
# ignore stuff like tcgetattr spewage or other warnings
data = filter_leading_non_json_lines(raw_data)
try:
results = json.loads(data)
except:
# not JSON, but try "Baby JSON" which allows many of our modules to not
# require JSON and makes writing modules in bash much simpler
results = {}
try:
tokens = shlex.split(data)
except:
print "failed to parse json: "+ data
raise
for t in tokens:
if "=" not in t:
raise errors.AnsibleError("failed to parse: %s" % orig_data)
(key,value) = t.split("=", 1)
if key == 'changed' or 'failed':
if value.lower() in [ 'true', '1' ]:
value = True
elif value.lower() in [ 'false', '0' ]:
value = False
if key == 'rc':
value = int(value)
results[key] = value
if len(results.keys()) == 0:
return { "failed" : True, "parsed" : False, "msg" : orig_data }
if from_remote:
results = _clean_data_struct(results, from_remote, from_inventory)
return results
def merge_module_args(current_args, new_args):
'''
merges either a dictionary or string of k=v pairs with another string of k=v pairs,
and returns a new k=v string without duplicates.
'''
if not isinstance(current_args, basestring):
raise errors.AnsibleError("expected current_args to be a basestring")
# we use parse_kv to split up the current args into a dictionary
final_args = parse_kv(current_args)
if isinstance(new_args, dict):
final_args.update(new_args)
elif isinstance(new_args, basestring):
new_args_kv = parse_kv(new_args)
final_args.update(new_args_kv)
# then we re-assemble into a string
module_args = ""
for (k,v) in final_args.iteritems():
if isinstance(v, basestring):
module_args = "%s=%s %s" % (k, pipes.quote(v), module_args)
return module_args.strip()
def smush_braces(data):
''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed weird by key=value code '''
while '{{ ' in data:
data = data.replace('{{ ', '{{')
while ' }}' in data:
data = data.replace(' }}', '}}')
return data
def smush_ds(data):
# things like key={{ foo }} are not handled by shlex.split well, so preprocess any YAML we load
# so we do not have to call smush elsewhere
if type(data) == list:
return [ smush_ds(x) for x in data ]
elif type(data) == dict:
for (k,v) in data.items():
data[k] = smush_ds(v)
return data
elif isinstance(data, basestring):
return smush_braces(data)
else:
return data
def parse_yaml(data, path_hint=None):
''' convert a yaml string to a data structure. Also supports JSON, ssssssh!!!'''
stripped_data = data.lstrip()
loaded = None
if stripped_data.startswith("{") or stripped_data.startswith("["):
# since the line starts with { or [ we can infer this is a JSON document.
try:
loaded = json.loads(data)
except ValueError, ve:
if path_hint:
raise errors.AnsibleError(path_hint + ": " + str(ve))
else:
raise errors.AnsibleError(str(ve))
else:
# else this is pretty sure to be a YAML document
loaded = yaml.safe_load(data)
return smush_ds(loaded)
def process_common_errors(msg, probline, column):
replaced = probline.replace(" ","")
if ":{{" in replaced and "}}" in replaced:
msg = msg + """
This one looks easy to fix. YAML thought it was looking for the start of a
hash/dictionary and was confused to see a second "{". Most likely this was
meant to be an ansible template evaluation instead, so we have to give the
parser a small hint that we wanted a string instead. The solution here is to
just quote the entire value.
For instance, if the original line was:
app_path: {{ base_path }}/foo
It should be written as:
app_path: "{{ base_path }}/foo"
"""
return msg
elif len(probline) and len(probline) > 1 and len(probline) > column and probline[column] == ":" and probline.count(':') > 1:
msg = msg + """
This one looks easy to fix. There seems to be an extra unquoted colon in the line
and this is confusing the parser. It was only expecting to find one free
colon. The solution is just add some quotes around the colon, or quote the
entire line after the first colon.
For instance, if the original line was:
copy: src=file.txt dest=/path/filename:with_colon.txt
It can be written as:
copy: src=file.txt dest='/path/filename:with_colon.txt'
Or:
copy: 'src=file.txt dest=/path/filename:with_colon.txt'
"""
return msg
else:
parts = probline.split(":")
if len(parts) > 1:
middle = parts[1].strip()
match = False
unbalanced = False
if middle.startswith("'") and not middle.endswith("'"):
match = True
elif middle.startswith('"') and not middle.endswith('"'):
match = True
if len(middle) > 0 and middle[0] in [ '"', "'" ] and middle[-1] in [ '"', "'" ] and probline.count("'") > 2 or probline.count('"') > 2:
unbalanced = True
if match:
msg = msg + """
This one looks easy to fix. It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote. For instance:
when: "ok" in result.stdout
Could be written as:
when: '"ok" in result.stdout'
or equivalently:
when: "'ok' in result.stdout"
"""
return msg
if unbalanced:
msg = msg + """
We could be wrong, but this one looks like it might be an issue with
unbalanced quotes. If starting a value with a quote, make sure the
line ends with the same set of quotes. For instance this arbitrary
example:
foo: "bad" "wolf"
Could be written as:
foo: '"bad" "wolf"'
"""
return msg
return msg
def process_yaml_error(exc, data, path=None, show_content=True):
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
if show_content:
if mark.line -1 >= 0:
before_probline = data.split("\n")[mark.line-1]
else:
before_probline = ''
probline = data.split("\n")[mark.line]
arrow = " " * mark.column + "^"
msg = """Syntax Error while loading YAML script, %s
Note: The error may actually appear before this position: line %s, column %s
%s
%s
%s""" % (path, mark.line + 1, mark.column + 1, before_probline, probline, arrow)
unquoted_var = None
if '{{' in probline and '}}' in probline:
if '"{{' not in probline or "'{{" not in probline:
unquoted_var = True
msg = process_common_errors(msg, probline, mark.column)
if not unquoted_var:
msg = process_common_errors(msg, probline, mark.column)
else:
msg = msg + """
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
"""
msg = process_common_errors(msg, probline, mark.column)
else:
# most likely displaying a file with sensitive content,
# so don't show any of the actual lines of yaml just the
# line number itself
msg = """Syntax error while loading YAML script, %s
The error appears to have been on line %s, column %s, but may actually
be before there depending on the exact syntax problem.
""" % (path, mark.line + 1, mark.column + 1)
else:
# No problem markers means we have to throw a generic
# "stuff messed up" type message. Sry bud.
if path:
msg = "Could not parse YAML. Check over %s again." % path
else:
msg = "Could not parse YAML."
raise errors.AnsibleYAMLValidationFailed(msg)
def parse_yaml_from_file(path, vault_password=None):
''' convert a yaml file to a data structure '''
data = None
show_content = True
try:
data = open(path).read()
except IOError:
raise errors.AnsibleError("file could not read: %s" % path)
vault = VaultLib(password=vault_password)
if vault.is_encrypted(data):
data = vault.decrypt(data)
show_content = False
try:
return parse_yaml(data, path_hint=path)
except yaml.YAMLError, exc:
process_yaml_error(exc, data, path, show_content)
def parse_kv(args):
''' convert a string of key/value items to a dict '''
options = {}
if args is not None:
# attempting to split a unicode here does bad things
args = args.encode('utf-8')
try:
vargs = shlex.split(args, posix=True)
except ValueError, ve:
if 'no closing quotation' in str(ve).lower():
raise errors.AnsibleError("error parsing argument string, try quoting the entire line.")
else:
raise
vargs = [x.decode('utf-8') for x in vargs]
for x in vargs:
if "=" in x:
k, v = x.split("=",1)
options[k] = v
return options
def merge_hash(a, b):
''' recursively merges hash b into a
keys from b take precedence over keys from a '''
result = copy.deepcopy(a)
# next, iterate over b keys and values
for k, v in b.iteritems():
# if there's already such key in a
# and that key contains dict
if k in result and isinstance(result[k], dict):
# merge those dicts recursively
result[k] = merge_hash(a[k], v)
else:
# otherwise, just copy a value from b to a
result[k] = v
return result
def md5s(data):
''' Return MD5 hex digest of data. '''
digest = _md5()
try:
digest.update(data)
except UnicodeEncodeError:
digest.update(data.encode('utf-8'))
return digest.hexdigest()
def md5(filename):
''' Return MD5 hex digest of local file, or None if file is not present. '''
if not os.path.exists(filename):
return None
digest = _md5()
blocksize = 64 * 1024
try:
infile = open(filename, 'rb')
block = infile.read(blocksize)
while block:
digest.update(block)
block = infile.read(blocksize)
infile.close()
except IOError, e:
raise errors.AnsibleError("error while accessing the file %s, error was: %s" % (filename, e))
return digest.hexdigest()
def default(value, function):
''' syntactic sugar around lazy evaluation of defaults '''
if value is None:
return function()
return value
def _gitinfo():
''' returns a string containing git branch, commit id and commit date '''
result = None
repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git')
if os.path.exists(repo_path):
# Check if the .git is a file. If it is a file, it means that we are in a submodule structure.
if os.path.isfile(repo_path):
try:
gitdir = yaml.safe_load(open(repo_path)).get('gitdir')
# There is a posibility the .git file to have an absolute path.
if os.path.isabs(gitdir):
repo_path = gitdir
else:
repo_path = os.path.join(repo_path.split('.git')[0], gitdir)
except (IOError, AttributeError):
return ''
f = open(os.path.join(repo_path, "HEAD"))
branch = f.readline().split('/')[-1].rstrip("\n")
f.close()
branch_path = os.path.join(repo_path, "refs", "heads", branch)
if os.path.exists(branch_path):
f = open(branch_path)
commit = f.readline()[:10]
f.close()
date = time.localtime(os.stat(branch_path).st_mtime)
if time.daylight == 0:
offset = time.timezone
else:
offset = time.altzone
result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit,
time.strftime("%Y/%m/%d %H:%M:%S", date), offset / -36)
else:
result = ''
return result
def version(prog):
result = "{0} {1}".format(prog, __version__)
gitinfo = _gitinfo()
if gitinfo:
result = result + " {0}".format(gitinfo)
return result
def getch():
''' read in a single character '''
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def sanitize_output(str):
''' strips private info out of a string '''
private_keys = ['password', 'login_password']
filter_re = [
# filter out things like user:pass@foo/whatever
# and http://username:pass@wherever/foo
re.compile('^(?P<before>.*:)(?P<password>.*)(?P<after>\@.*)$'),
]
parts = str.split()
output = ''
for part in parts:
try:
(k,v) = part.split('=', 1)
if k in private_keys:
output += " %s=VALUE_HIDDEN" % k
else:
found = False
for filter in filter_re:
m = filter.match(v)
if m:
d = m.groupdict()
output += " %s=%s" % (k, d['before'] + "********" + d['after'])
found = True
break
if not found:
output += " %s" % part
except:
output += " %s" % part
return output.strip()
####################################################################
# option handling code for /usr/bin/ansible and ansible-playbook
# below this line
class SortedOptParser(optparse.OptionParser):
'''Optparser which sorts the options by opt before outputting --help'''
def format_help(self, formatter=None):
self.option_list.sort(key=operator.methodcaller('get_opt_string'))
return optparse.OptionParser.format_help(self, formatter=None)
def increment_debug(option, opt, value, parser):
global VERBOSITY
VERBOSITY += 1
def base_parser(constants=C, usage="", output_opts=False, runas_opts=False,
async_opts=False, connect_opts=False, subset_opts=False, check_opts=False, diff_opts=False):
''' create an options parser for any ansible script '''
parser = SortedOptParser(usage, version=version("%prog"))
parser.add_option('-v','--verbose', default=False, action="callback",
callback=increment_debug, help="verbose mode (-vvv for more, -vvvv to enable connection debugging)")
parser.add_option('-f','--forks', dest='forks', default=constants.DEFAULT_FORKS, type='int',
help="specify number of parallel processes to use (default=%s)" % constants.DEFAULT_FORKS)
parser.add_option('-i', '--inventory-file', dest='inventory',
help="specify inventory host file (default=%s)" % constants.DEFAULT_HOST_LIST,
default=constants.DEFAULT_HOST_LIST)
parser.add_option('-k', '--ask-pass', default=False, dest='ask_pass', action='store_true',
help='ask for SSH password')
parser.add_option('--private-key', default=C.DEFAULT_PRIVATE_KEY_FILE, dest='private_key_file',
help='use this file to authenticate the connection')
parser.add_option('-K', '--ask-sudo-pass', default=False, dest='ask_sudo_pass', action='store_true',
help='ask for sudo password')
parser.add_option('--ask-su-pass', default=False, dest='ask_su_pass', action='store_true',
help='ask for su password')
parser.add_option('--ask-vault-pass', default=False, dest='ask_vault_pass', action='store_true',
help='ask for vault password')
parser.add_option('--vault-password-file', default=None, dest='vault_password_file',
help="vault password file")
parser.add_option('--list-hosts', dest='listhosts', action='store_true',
help='outputs a list of matching hosts; does not execute anything else')
parser.add_option('-M', '--module-path', dest='module_path',
help="specify path(s) to module library (default=%s)" % constants.DEFAULT_MODULE_PATH,
default=None)
if subset_opts:
parser.add_option('-l', '--limit', default=constants.DEFAULT_SUBSET, dest='subset',
help='further limit selected hosts to an additional pattern')
parser.add_option('-T', '--timeout', default=constants.DEFAULT_TIMEOUT, type='int',
dest='timeout',
help="override the SSH timeout in seconds (default=%s)" % constants.DEFAULT_TIMEOUT)
if output_opts:
parser.add_option('-o', '--one-line', dest='one_line', action='store_true',
help='condense output')
parser.add_option('-t', '--tree', dest='tree', default=None,
help='log output to this directory')
if runas_opts:
parser.add_option("-s", "--sudo", default=constants.DEFAULT_SUDO, action="store_true",
dest='sudo', help="run operations with sudo (nopasswd)")
parser.add_option('-U', '--sudo-user', dest='sudo_user', default=None,
help='desired sudo user (default=root)') # Can't default to root because we need to detect when this option was given
parser.add_option('-u', '--user', default=constants.DEFAULT_REMOTE_USER,
dest='remote_user', help='connect as this user (default=%s)' % constants.DEFAULT_REMOTE_USER)
parser.add_option('-S', '--su', default=constants.DEFAULT_SU,
action='store_true', help='run operations with su')
parser.add_option('-R', '--su-user', help='run operations with su as this '
'user (default=%s)' % constants.DEFAULT_SU_USER)
if connect_opts:
parser.add_option('-c', '--connection', dest='connection',
default=C.DEFAULT_TRANSPORT,
help="connection type to use (default=%s)" % C.DEFAULT_TRANSPORT)
if async_opts:
parser.add_option('-P', '--poll', default=constants.DEFAULT_POLL_INTERVAL, type='int',
dest='poll_interval',
help="set the poll interval if using -B (default=%s)" % constants.DEFAULT_POLL_INTERVAL)
parser.add_option('-B', '--background', dest='seconds', type='int', default=0,
help='run asynchronously, failing after X seconds (default=N/A)')
if check_opts:
parser.add_option("-C", "--check", default=False, dest='check', action='store_true',
help="don't make any changes; instead, try to predict some of the changes that may occur"
)
if diff_opts:
parser.add_option("-D", "--diff", default=False, dest='diff', action='store_true',
help="when changing (small) files and templates, show the differences in those files; works great with --check"
)
return parser
def ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=False, confirm_vault=False, confirm_new=False):
vault_pass = None
new_vault_pass = None
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
if ask_vault_pass and confirm_vault:
vault_pass2 = getpass.getpass(prompt="Confirm Vault password: ")
if vault_pass != vault_pass2:
raise errors.AnsibleError("Passwords do not match")
if ask_new_vault_pass:
new_vault_pass = getpass.getpass(prompt="New Vault password: ")
if ask_new_vault_pass and confirm_new:
new_vault_pass2 = getpass.getpass(prompt="Confirm New Vault password: ")
if new_vault_pass != new_vault_pass2:
raise errors.AnsibleError("Passwords do not match")
# enforce no newline chars at the end of passwords
if vault_pass:
vault_pass = vault_pass.strip()
if new_vault_pass:
new_vault_pass = new_vault_pass.strip()
return vault_pass, new_vault_pass
def ask_passwords(ask_pass=False, ask_sudo_pass=False, ask_su_pass=False, ask_vault_pass=False):
sshpass = None
sudopass = None
su_pass = None
vault_pass = None
sudo_prompt = "sudo password: "
su_prompt = "su password: "
if ask_pass:
sshpass = getpass.getpass(prompt="SSH password: ")
sudo_prompt = "sudo password [defaults to SSH password]: "
if ask_sudo_pass:
sudopass = getpass.getpass(prompt=sudo_prompt)
if ask_pass and sudopass == '':
sudopass = sshpass
if ask_su_pass:
su_pass = getpass.getpass(prompt=su_prompt)
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
return (sshpass, sudopass, su_pass, vault_pass)
def do_encrypt(result, encrypt, salt_size=None, salt=None):
if PASSLIB_AVAILABLE:
try:
crypt = getattr(passlib.hash, encrypt)
except:
raise errors.AnsibleError("passlib does not support '%s' algorithm" % encrypt)
if salt_size:
result = crypt.encrypt(result, salt_size=salt_size)
elif salt:
result = crypt.encrypt(result, salt=salt)
else:
result = crypt.encrypt(result)
else:
raise errors.AnsibleError("passlib must be installed to encrypt vars_prompt values")
return result
def last_non_blank_line(buf):
all_lines = buf.splitlines()
all_lines.reverse()
for line in all_lines:
if (len(line) > 0):
return line
# shouldn't occur unless there's no output
return ""
def filter_leading_non_json_lines(buf):
'''
used to avoid random output from SSH at the top of JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
need to filter anything which starts not with '{', '[', ', '=' or is an empty line.
filter only leading lines since multiline JSON is valid.
'''
kv_regex = re.compile(r'.*\w+=\w+.*')
filtered_lines = StringIO.StringIO()
stop_filtering = False
for line in buf.splitlines():
if stop_filtering or kv_regex.match(line) or line.startswith('{') or line.startswith('['):
stop_filtering = True
filtered_lines.write(line + '\n')
return filtered_lines.getvalue()
def boolean(value):
val = str(value)
if val.lower() in [ "true", "t", "y", "1", "yes" ]:
return True
else:
return False
def make_sudo_cmd(sudo_user, executable, cmd):
"""
helper function for connection plugins to create sudo commands
"""
# Rather than detect if sudo wants a password this time, -k makes
# sudo always ask for a password if one is required.
# Passing a quoted compound command to sudo (or sudo -s)
# directly doesn't work, so we shellquote it with pipes.quote()
# and pass the quoted string to the user's shell. We loop reading
# output until we see the randomly-generated sudo prompt set with
# the -p option.
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = '[sudo via ansible, key=%s] password: ' % randbits
success_key = 'SUDO-SUCCESS-%s' % randbits
sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % (
C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_FLAGS,
prompt, sudo_user, executable or '$SHELL', pipes.quote('echo %s; %s' % (success_key, cmd)))
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
def make_su_cmd(su_user, executable, cmd):
"""
Helper function for connection plugins to create direct su commands
"""
# TODO: work on this function
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = 'assword: '
success_key = 'SUDO-SUCCESS-%s' % randbits
sudocmd = '%s %s %s %s -c %s' % (
C.DEFAULT_SU_EXE, C.DEFAULT_SU_FLAGS, su_user, executable or '$SHELL',
pipes.quote('echo %s; %s' % (success_key, cmd))
)
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
_TO_UNICODE_TYPES = (unicode, type(None))
def to_unicode(value):
if isinstance(value, _TO_UNICODE_TYPES):
return value
return value.decode("utf-8")
def get_diff(diff):
# called by --diff usage in playbook and runner via callbacks
# include names in diffs 'before' and 'after' and do diff -U 10
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ret = []
if 'dst_binary' in diff:
ret.append("diff skipped: destination file appears to be binary\n")
if 'src_binary' in diff:
ret.append("diff skipped: source file appears to be binary\n")
if 'dst_larger' in diff:
ret.append("diff skipped: destination file size is greater than %d\n" % diff['dst_larger'])
if 'src_larger' in diff:
ret.append("diff skipped: source file size is greater than %d\n" % diff['src_larger'])
if 'before' in diff and 'after' in diff:
if 'before_header' in diff:
before_header = "before: %s" % diff['before_header']
else:
before_header = 'before'
if 'after_header' in diff:
after_header = "after: %s" % diff['after_header']
else:
after_header = 'after'
differ = difflib.unified_diff(to_unicode(diff['before']).splitlines(True), to_unicode(diff['after']).splitlines(True), before_header, after_header, '', '', 10)
for line in list(differ):
ret.append(line)
return u"".join(ret)
except UnicodeDecodeError:
return ">> the files are different, but the diff library cannot compare unicode strings"
def is_list_of_strings(items):
for x in items:
if not isinstance(x, basestring):
return False
return True
def list_union(a, b):
result = []
for x in a:
if x not in result:
result.append(x)
for x in b:
if x not in result:
result.append(x)
return result
def list_intersection(a, b):
result = []
for x in a:
if x in b and x not in result:
result.append(x)
return result
def safe_eval(expr, locals={}, include_exceptions=False):
'''
This is intended for allowing things like:
with_items: a_list_variable
Where Jinja2 would return a string but we do not want to allow it to
call functions (outside of Jinja2, where the env is constrained). If
the input data to this function came from an untrusted (remote) source,
it should first be run through _clean_data_struct() to ensure the data
is further sanitized prior to evaluation.
Based on:
http://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe
'''
# this is the whitelist of AST nodes we are going to
# allow in the evaluation. Any node type other than
# those listed here will raise an exception in our custom
# visitor class defined below.
SAFE_NODES = set(
(
ast.Add,
ast.BinOp,
ast.Call,
ast.Compare,
ast.Dict,
ast.Div,
ast.Expression,
ast.List,
ast.Load,
ast.Mult,
ast.Num,
ast.Name,
ast.Str,
ast.Sub,
ast.Tuple,
ast.UnaryOp,
)
)
# AST node types were expanded after 2.6
if not sys.version.startswith('2.6'):
SAFE_NODES.union(
set(
(ast.Set,)
)
)
filter_list = []
for filter in filter_loader.all():
filter_list.extend(filter.filters().keys())
CALL_WHITELIST = C.DEFAULT_CALLABLE_WHITELIST + filter_list
class CleansingNodeVisitor(ast.NodeVisitor):
def generic_visit(self, node, inside_call=False):
if type(node) not in SAFE_NODES:
raise Exception("invalid expression (%s)" % expr)
elif isinstance(node, ast.Call):
inside_call = True
elif isinstance(node, ast.Name) and inside_call:
if hasattr(builtin, node.id) and node.id not in CALL_WHITELIST:
raise Exception("invalid function: %s" % node.id)
# iterate over all child nodes
for child_node in ast.iter_child_nodes(node):
self.generic_visit(child_node, inside_call)
if not isinstance(expr, basestring):
# already templated to a datastructure, perhaps?
if include_exceptions:
return (expr, None)
return expr
cnv = CleansingNodeVisitor()
try:
parsed_tree = ast.parse(expr, mode='eval')
cnv.visit(parsed_tree)
compiled = compile(parsed_tree, expr, 'eval')
result = eval(compiled, {}, locals)
if include_exceptions:
return (result, None)
else:
return result
except SyntaxError, e:
# special handling for syntax errors, we just return
# the expression string back as-is
if include_exceptions:
return (expr, None)
return expr
except Exception, e:
if include_exceptions:
return (expr, e)
return expr
def listify_lookup_plugin_terms(terms, basedir, inject):
if isinstance(terms, basestring):
# someone did:
# with_items: alist
# OR
# with_items: {{ alist }}
stripped = terms.strip()
if not (stripped.startswith('{') or stripped.startswith('[')) and not stripped.startswith("/") and not stripped.startswith('set(['):
# if not already a list, get ready to evaluate with Jinja2
# not sure why the "/" is in above code :)
try:
new_terms = template.template(basedir, "{{ %s }}" % terms, inject)
if isinstance(new_terms, basestring) and "{{" in new_terms:
pass
else:
terms = new_terms
except:
pass
if '{' in terms or '[' in terms:
# Jinja2 already evaluated a variable to a list.
# Jinja2-ified list needs to be converted back to a real type
# TODO: something a bit less heavy than eval
return safe_eval(terms)
if isinstance(terms, basestring):
terms = [ terms ]
return terms
def combine_vars(a, b):
if C.DEFAULT_HASH_BEHAVIOUR == "merge":
return merge_hash(a, b)
else:
return dict(a.items() + b.items())
def random_password(length=20, chars=C.DEFAULT_PASSWORD_CHARS):
'''Return a random password string of length containing only chars.'''
password = []
while len(password) < length:
new_char = os.urandom(1)
if new_char in chars:
password.append(new_char)
return ''.join(password)
def before_comment(msg):
''' what's the part of a string before a comment? '''
msg = msg.replace("\#","**NOT_A_COMMENT**")
msg = msg.split("#")[0]
msg = msg.replace("**NOT_A_COMMENT**","#")
return msg
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_2234_5 |
crossvul-python_data_bad_3934_1 | # -*- coding: utf-8 -*-
"""Small, fast HTTP client library for Python."""
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = [
"Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger",
"Mark Pilgrim",
"Alex Yu",
]
__license__ = "MIT"
__version__ = '0.17.4'
import base64
import calendar
import copy
import email
import email.feedparser
from email import header
import email.message
import email.utils
import errno
from gettext import gettext as _
import gzip
from hashlib import md5 as _md5
from hashlib import sha1 as _sha
import hmac
import http.client
import io
import os
import random
import re
import socket
import ssl
import sys
import time
import urllib.parse
import zlib
try:
import socks
except ImportError:
# TODO: remove this fallback and copypasted socksipy module upon py2/3 merge,
# idea is to have soft-dependency on any compatible module called socks
from . import socks
from .iri2uri import iri2uri
def has_timeout(timeout):
if hasattr(socket, "_GLOBAL_DEFAULT_TIMEOUT"):
return timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT
return timeout is not None
__all__ = [
"debuglevel",
"FailedToDecompressContent",
"Http",
"HttpLib2Error",
"ProxyInfo",
"RedirectLimit",
"RedirectMissingLocation",
"Response",
"RETRIES",
"UnimplementedDigestAuthOptionError",
"UnimplementedHmacDigestAuthOptionError",
]
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# A request will be tried 'RETRIES' times if it fails at the socket/connection level.
RETRIES = 2
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception):
pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse):
pass
class RedirectLimit(HttpLib2ErrorWithResponse):
pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse):
pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class MalformedHeader(HttpLib2Error):
pass
class RelativeURIError(HttpLib2Error):
pass
class ServerNotFoundError(HttpLib2Error):
pass
class ProxiesUnavailableError(HttpLib2Error):
pass
# Open Items:
# -----------
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
]
# https://tools.ietf.org/html/rfc7231#section-8.1.3
SAFE_METHODS = ("GET", "HEAD", "OPTIONS", "TRACE")
# To change, assign to `Http().redirect_codes`
REDIRECT_CODES = frozenset((300, 301, 302, 303, 307, 308))
from httplib2 import certs
CA_CERTS = certs.where()
# PROTOCOL_TLS is python 3.5.3+. PROTOCOL_SSLv23 is deprecated.
# Both PROTOCOL_TLS and PROTOCOL_SSLv23 are equivalent and means:
# > Selects the highest protocol version that both the client and server support.
# > Despite the name, this option can select “TLS” protocols as well as “SSL”.
# source: https://docs.python.org/3.5/library/ssl.html#ssl.PROTOCOL_TLS
DEFAULT_TLS_VERSION = getattr(ssl, "PROTOCOL_TLS", None) or getattr(
ssl, "PROTOCOL_SSLv23"
)
def _build_ssl_context(
disable_ssl_certificate_validation, ca_certs, cert_file=None, key_file=None,
maximum_version=None, minimum_version=None, key_password=None,
):
if not hasattr(ssl, "SSLContext"):
raise RuntimeError("httplib2 requires Python 3.2+ for ssl.SSLContext")
context = ssl.SSLContext(DEFAULT_TLS_VERSION)
context.verify_mode = (
ssl.CERT_NONE if disable_ssl_certificate_validation else ssl.CERT_REQUIRED
)
# SSLContext.maximum_version and SSLContext.minimum_version are python 3.7+.
# source: https://docs.python.org/3/library/ssl.html#ssl.SSLContext.maximum_version
if maximum_version is not None:
if hasattr(context, "maximum_version"):
context.maximum_version = getattr(ssl.TLSVersion, maximum_version)
else:
raise RuntimeError("setting tls_maximum_version requires Python 3.7 and OpenSSL 1.1 or newer")
if minimum_version is not None:
if hasattr(context, "minimum_version"):
context.minimum_version = getattr(ssl.TLSVersion, minimum_version)
else:
raise RuntimeError("setting tls_minimum_version requires Python 3.7 and OpenSSL 1.1 or newer")
# check_hostname requires python 3.4+
# we will perform the equivalent in HTTPSConnectionWithTimeout.connect() by calling ssl.match_hostname
# if check_hostname is not supported.
if hasattr(context, "check_hostname"):
context.check_hostname = not disable_ssl_certificate_validation
context.load_verify_locations(ca_certs)
if cert_file:
context.load_cert_chain(cert_file, key_file, key_password)
return context
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get("connection", "").split(",")])
return [header for header in list(response.keys()) if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r"^\w+://")
re_unsafe = re.compile(r"[^\w\-_.()=!]+", re.ASCII)
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
if isinstance(filename, bytes):
filename_bytes = filename
filename = filename.decode("utf-8")
else:
filename_bytes = filename.encode("utf-8")
filemd5 = _md5(filename_bytes).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_unsafe.sub("", filename)
# limit length of filename (vital for Windows)
# https://github.com/httplib2/httplib2/pull/74
# C:\Users\ <username> \AppData\Local\Temp\ <safe_filename> , <md5>
# 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars
# Thus max safe filename x = 93 chars. Let it be 90 to make a round sum:
filename = filename[:90]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r"(?:\r\n)?[ \t]+")
def _normalize_headers(headers):
return dict(
[
(
_convert_byte_str(key).lower(),
NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(),
)
for (key, value) in headers.items()
]
)
def _convert_byte_str(s):
if not isinstance(s, str):
return str(s, "utf-8")
return s
def _parse_cache_control(headers):
retval = {}
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)])
for part in parts
if -1 != part.find("=")
]
parts_wo_args = [
(name.strip().lower(), 1) for name in parts if -1 == name.find("=")
]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, useful for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(
r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$"
)
WWW_AUTH_RELAXED = re.compile(
r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$"
)
UNQUOTE_PAIRS = re.compile(r"\\(.)")
def _parse_www_authenticate(headers, headername="www-authenticate"):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headername in headers:
try:
authenticate = headers[headername].strip()
www_auth = (
USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
)
while authenticate:
# Break off the scheme at the beginning of the line
if headername == "authentication-info":
(auth_scheme, the_rest) = ("digest", authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(
r"\1", value
) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if (
"pragma" in request_headers
and request_headers["pragma"].lower().find("no-cache") != -1
):
retval = "TRANSPARENT"
if "cache-control" not in request_headers:
request_headers["cache-control"] = "no-cache"
elif "no-cache" in cc:
retval = "TRANSPARENT"
elif "no-cache" in cc_response:
retval = "STALE"
elif "only-if-cached" in cc:
retval = "FRESH"
elif "date" in response_headers:
date = calendar.timegm(email.utils.parsedate_tz(response_headers["date"]))
now = time.time()
current_age = max(0, now - date)
if "max-age" in cc_response:
try:
freshness_lifetime = int(cc_response["max-age"])
except ValueError:
freshness_lifetime = 0
elif "expires" in response_headers:
expires = email.utils.parsedate_tz(response_headers["expires"])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if "max-age" in cc:
try:
freshness_lifetime = int(cc["max-age"])
except ValueError:
freshness_lifetime = 0
if "min-fresh" in cc:
try:
min_fresh = int(cc["min-fresh"])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get("content-encoding", None)
if encoding in ["gzip", "deflate"]:
if encoding == "gzip":
content = gzip.GzipFile(fileobj=io.BytesIO(new_content)).read()
if encoding == "deflate":
content = zlib.decompress(content, -zlib.MAX_WBITS)
response["content-length"] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response["-content-encoding"] = response["content-encoding"]
del response["content-encoding"]
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
)
return content
def _bind_write_headers(msg):
def _write_headers(self):
# Self refers to the Generator object.
for h, v in msg.items():
print("%s:" % h, end=" ", file=self._fp)
if isinstance(v, header.Header):
print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp)
else:
# email.Header got lots of smarts, so use it.
headers = header.Header(
v, maxlinelen=self._maxheaderlen, charset="utf-8", header_name=h
)
print(headers.encode(), file=self._fp)
# A blank line always separates headers from body.
print(file=self._fp)
return _write_headers
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if "no-store" in cc or "no-store" in cc_response:
cache.delete(cachekey)
else:
info = email.message.Message()
for key, value in response_headers.items():
if key not in ["status", "content-encoding", "transfer-encoding"]:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get("vary", None)
if vary:
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = "status: %d\r\n" % status
try:
header_str = info.as_string()
except UnicodeEncodeError:
setattr(info, "_write_headers", _bind_write_headers(info))
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = b"".join(
[status_header.encode("utf-8"), header_str.encode("utf-8"), content]
)
cache.set(cachekey, text)
def _cnonce():
dig = _md5(
(
"%s:%s"
% (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])
).encode("utf-8")
).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(
_sha(("%s%s%s" % (cnonce, iso_now, password)).encode("utf-8")).digest()
).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path) :].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-rise this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
def __eq__(self, auth):
return False
def __ne__(self, auth):
return True
def __lt__(self, auth):
return True
def __gt__(self, auth):
return False
def __le__(self, auth):
return True
def __ge__(self, auth):
return False
def __bool__(self):
return True
class BasicAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = "Basic " + base64.b64encode(
("%s:%s" % self.credentials).encode("utf-8")
).strip().decode("utf-8")
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["digest"]
qop = self.challenge.get("qop", "auth")
self.challenge["qop"] = (
("auth" in [x.strip() for x in qop.split()]) and "auth" or None
)
if self.challenge["qop"] is None:
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for qop: %s." % qop)
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "MD5").upper()
if self.challenge["algorithm"] != "MD5":
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.A1 = "".join(
[
self.credentials[0],
":",
self.challenge["realm"],
":",
self.credentials[1],
]
)
self.challenge["nc"] = 1
def request(self, method, request_uri, headers, content, cnonce=None):
"""Modify the request headers"""
H = lambda x: _md5(x.encode("utf-8")).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge["cnonce"] = cnonce or _cnonce()
request_digest = '"%s"' % KD(
H(self.A1),
"%s:%s:%s:%s:%s"
% (
self.challenge["nonce"],
"%08x" % self.challenge["nc"],
self.challenge["cnonce"],
self.challenge["qop"],
H(A2),
),
)
headers["authorization"] = (
'Digest username="%s", realm="%s", nonce="%s", '
'uri="%s", algorithm=%s, response=%s, qop=%s, '
'nc=%08x, cnonce="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["nonce"],
request_uri,
self.challenge["algorithm"],
request_digest,
self.challenge["qop"],
self.challenge["nc"],
self.challenge["cnonce"],
)
if self.challenge.get("opaque"):
headers["authorization"] += ', opaque="%s"' % self.challenge["opaque"]
self.challenge["nc"] += 1
def response(self, response, content):
if "authentication-info" not in response:
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"digest", {}
)
if "true" == challenge.get("stale"):
self.challenge["nonce"] = challenge["nonce"]
self.challenge["nc"] = 1
return True
else:
updated_challenge = _parse_www_authenticate(
response, "authentication-info"
).get("digest", {})
if "nextnonce" in updated_challenge:
self.challenge["nonce"] = updated_challenge["nextnonce"]
self.challenge["nc"] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["hmacdigest"]
# TODO: self.challenge['domain']
self.challenge["reason"] = self.challenge.get("reason", "unauthorized")
if self.challenge["reason"] not in ["unauthorized", "integrity"]:
self.challenge["reason"] = "unauthorized"
self.challenge["salt"] = self.challenge.get("salt", "")
if not self.challenge.get("snonce"):
raise UnimplementedHmacDigestAuthOptionError(
_("The challenge doesn't contain a server nonce, or this one is empty.")
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "HMAC-SHA-1")
if self.challenge["algorithm"] not in ["HMAC-SHA-1", "HMAC-MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1")
if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_(
"Unsupported value for pw-algorithm: %s."
% self.challenge["pw-algorithm"]
)
)
if self.challenge["algorithm"] == "HMAC-MD5":
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge["pw-algorithm"] == "MD5":
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join(
[
self.credentials[0],
":",
self.pwhashmod.new(
"".join([self.credentials[1], self.challenge["salt"]])
)
.hexdigest()
.lower(),
":",
self.challenge["realm"],
]
)
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (
method,
request_uri,
cnonce,
self.challenge["snonce"],
headers_val,
)
request_digest = (
hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
)
headers["authorization"] = (
'HMACDigest username="%s", realm="%s", snonce="%s",'
' cnonce="%s", uri="%s", created="%s", '
'response="%s", headers="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["snonce"],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"hmacdigest", {}
)
if challenge.get("reason") in ["integrity", "stale"]:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = (
'UsernameToken Username="%s", PasswordDigest="%s", '
'Nonce="%s", Created="%s"'
) % (self.credentials[0], password_digest, cnonce, iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
from urllib.parse import urlencode
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
service = challenge["googlelogin"].get("service", "xapi")
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == "xapi" and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(
Email=credentials[0],
Passwd=credentials[1],
service=service,
source=headers["user-agent"],
)
resp, content = self.http.request(
"https://www.google.com/accounts/ClientLogin",
method="POST",
body=urlencode(auth),
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
lines = content.split("\n")
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d["Auth"]
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = "GoogleLogin Auth=" + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication,
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(
self, cache, safe=safename
): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = open(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = open(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
def iter(self, domain):
for (cdomain, key, cert, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (key, cert, password)
class AllHosts(object):
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
bypass_hosts = ()
def __init__(
self,
proxy_type,
proxy_host,
proxy_port,
proxy_rdns=True,
proxy_user=None,
proxy_pass=None,
proxy_headers=None,
):
"""Args:
proxy_type: The type of proxy server. This must be set to one of
socks.PROXY_TYPE_XXX constants. For example: p =
ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost',
proxy_port=8000)
proxy_host: The hostname or IP address of the proxy server.
proxy_port: The port that the proxy server is running on.
proxy_rdns: If True (default), DNS queries will not be performed
locally, and instead, handed to the proxy to resolve. This is useful
if the network does not allow resolution of non-local names. In
httplib2 0.9 and earlier, this defaulted to False.
proxy_user: The username used to authenticate with the proxy server.
proxy_pass: The password used to authenticate with the proxy server.
proxy_headers: Additional or modified headers for the proxy connect
request.
"""
if isinstance(proxy_user, bytes):
proxy_user = proxy_user.decode()
if isinstance(proxy_pass, bytes):
proxy_pass = proxy_pass.decode()
self.proxy_type, self.proxy_host, self.proxy_port, self.proxy_rdns, self.proxy_user, self.proxy_pass, self.proxy_headers = (
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
def astuple(self):
return (
self.proxy_type,
self.proxy_host,
self.proxy_port,
self.proxy_rdns,
self.proxy_user,
self.proxy_pass,
self.proxy_headers,
)
def isgood(self):
return socks and (self.proxy_host != None) and (self.proxy_port != None)
def applies_to(self, hostname):
return not self.bypass_host(hostname)
def bypass_host(self, hostname):
"""Has this host been excluded from the proxy config"""
if self.bypass_hosts is AllHosts:
return True
hostname = "." + hostname.lstrip(".")
for skip_name in self.bypass_hosts:
# *.suffix
if skip_name.startswith(".") and hostname.endswith(skip_name):
return True
# exact match
if hostname == "." + skip_name:
return True
return False
def __repr__(self):
return (
"<ProxyInfo type={p.proxy_type} "
"host:port={p.proxy_host}:{p.proxy_port} rdns={p.proxy_rdns}"
+ " user={p.proxy_user} headers={p.proxy_headers}>"
).format(p=self)
def proxy_info_from_environment(method="http"):
"""Read proxy info from the environment variables.
"""
if method not in ("http", "https"):
return
env_var = method + "_proxy"
url = os.environ.get(env_var, os.environ.get(env_var.upper()))
if not url:
return
return proxy_info_from_url(url, method, noproxy=None)
def proxy_info_from_url(url, method="http", noproxy=None):
"""Construct a ProxyInfo from a URL (such as http_proxy env var)
"""
url = urllib.parse.urlparse(url)
username = None
password = None
port = None
if "@" in url[1]:
ident, host_port = url[1].split("@", 1)
if ":" in ident:
username, password = ident.split(":", 1)
else:
password = ident
else:
host_port = url[1]
if ":" in host_port:
host, port = host_port.split(":", 1)
else:
host = host_port
if port:
port = int(port)
else:
port = dict(https=443, http=80)[method]
proxy_type = 3 # socks.PROXY_TYPE_HTTP
pi = ProxyInfo(
proxy_type=proxy_type,
proxy_host=host,
proxy_port=port,
proxy_user=username or None,
proxy_pass=password or None,
proxy_headers=None,
)
bypass_hosts = []
# If not given an explicit noproxy value, respect values in env vars.
if noproxy is None:
noproxy = os.environ.get("no_proxy", os.environ.get("NO_PROXY", ""))
# Special case: A single '*' character means all hosts should be bypassed.
if noproxy == "*":
bypass_hosts = AllHosts
elif noproxy.strip():
bypass_hosts = noproxy.split(",")
bypass_hosts = tuple(filter(bool, bypass_hosts)) # To exclude empty string.
pi.bypass_hosts = bypass_hosts
return pi
class HTTPConnectionWithTimeout(http.client.HTTPConnection):
"""HTTPConnection subclass that supports timeouts
HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, timeout=None, proxy_info=None):
http.client.HTTPConnection.__init__(self, host, port=port, timeout=timeout)
self.proxy_info = proxy_info
if proxy_info and not isinstance(proxy_info, ProxyInfo):
self.proxy_info = proxy_info("http")
def connect(self):
"""Connect to the host and port specified in __init__."""
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
"Proxy support missing but proxy use was requested!"
)
if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_port
else:
use_proxy = False
host = self.host
port = self.port
proxy_type = None
socket_err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
)
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
if self.debuglevel > 0:
print(
"connect: ({0}, {1}) ************".format(self.host, self.port)
)
if use_proxy:
print(
"proxy: {0} ************".format(
str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
)
self.sock.connect((self.host, self.port) + sa[2:])
except socket.error as e:
socket_err = e
if self.debuglevel > 0:
print("connect fail: ({0}, {1})".format(self.host, self.port))
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket_err
class HTTPSConnectionWithTimeout(http.client.HTTPSConnection):
"""This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
timeout=None,
proxy_info=None,
ca_certs=None,
disable_ssl_certificate_validation=False,
tls_maximum_version=None,
tls_minimum_version=None,
key_password=None,
):
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.ca_certs = ca_certs if ca_certs else CA_CERTS
self.proxy_info = proxy_info
if proxy_info and not isinstance(proxy_info, ProxyInfo):
self.proxy_info = proxy_info("https")
context = _build_ssl_context(
self.disable_ssl_certificate_validation, self.ca_certs, cert_file, key_file,
maximum_version=tls_maximum_version, minimum_version=tls_minimum_version,
key_password=key_password,
)
super(HTTPSConnectionWithTimeout, self).__init__(
host,
port=port,
timeout=timeout,
context=context,
)
self.key_file = key_file
self.cert_file = cert_file
self.key_password = key_password
def connect(self):
"""Connect to a host on a given (SSL) port."""
if self.proxy_info and self.proxy_info.isgood() and self.proxy_info.applies_to(self.host):
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_port
else:
use_proxy = False
host = self.host
port = self.port
proxy_type = None
proxy_headers = None
socket_err = None
address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
for family, socktype, proto, canonname, sockaddr in address_info:
try:
if use_proxy:
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
)
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
sock.connect((self.host, self.port))
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
# Python 3.3 compatibility: emulate the check_hostname behavior
if (
not hasattr(self._context, "check_hostname")
and not self.disable_ssl_certificate_validation
):
try:
ssl.match_hostname(self.sock.getpeercert(), self.host)
except Exception:
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
raise
if self.debuglevel > 0:
print("connect: ({0}, {1})".format(self.host, self.port))
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
)
except (ssl.SSLError, ssl.CertificateError) as e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error as e:
socket_err = e
if self.debuglevel > 0:
print("connect fail: ({0}, {1})".format(self.host, self.port))
if use_proxy:
print(
"proxy: {0}".format(
str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket_err
SCHEME_TO_CONNECTION = {
"http": HTTPConnectionWithTimeout,
"https": HTTPSConnectionWithTimeout,
}
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(
self,
cache=None,
timeout=None,
proxy_info=proxy_info_from_environment,
ca_certs=None,
disable_ssl_certificate_validation=False,
tls_maximum_version=None,
tls_minimum_version=None,
):
"""If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
`proxy_info` may be:
- a callable that takes the http scheme ('http' or 'https') and
returns a ProxyInfo instance per request. By default, uses
proxy_info_from_environment.
- a ProxyInfo instance (static proxy config).
- None (proxy disabled).
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
tls_maximum_version / tls_minimum_version require Python 3.7+ /
OpenSSL 1.1.0g+. A value of "TLSv1_3" requires OpenSSL 1.1.1+.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.tls_maximum_version = tls_maximum_version
self.tls_minimum_version = tls_minimum_version
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, str):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
self.redirect_codes = REDIRECT_CODES
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
self.safe_methods = list(SAFE_METHODS)
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
# Keep Authorization: headers on a redirect.
self.forward_authorization_headers = False
def close(self):
"""Close persistent connections, clear sensitive data.
Not thread-safe, requires external synchronization against concurrent requests.
"""
existing, self.connections = self.connections, {}
for _, c in existing.items():
c.close()
self.certificates.clear()
self.clear_credentials()
def __getstate__(self):
state_dict = copy.copy(self.__dict__)
# In case request is augmented by some foreign object such as
# credentials which handle auth
if "request" in state_dict:
del state_dict["request"]
if "connections" in state_dict:
del state_dict["connections"]
return state_dict
def __setstate__(self, state):
self.__dict__.update(state)
self.connections = {}
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if scheme in challenges:
yield AUTH_SCHEME_CLASSES[scheme](
cred, host, request_uri, headers, response, content, self
)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain, password=None):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain, password)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
i = 0
seen_bad_status_line = False
while i < RETRIES:
i += 1
try:
if conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
conn.close()
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except socket.error as e:
errno_ = (
e.args[0].errno if isinstance(e.args[0], socket.error) else e.errno
)
if errno_ in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
continue # retry on potentially transient errors
raise
except http.client.HTTPException:
if conn.sock is None:
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
pass
try:
response = conn.getresponse()
except (http.client.BadStatusLine, http.client.ResponseNotReady):
# If we get a BadStatusLine on the first try then that means
# the connection just went stale, so retry regardless of the
# number of RETRIES set.
if not seen_bad_status_line and i == 1:
i = 0
seen_bad_status_line = True
conn.close()
conn.connect()
continue
else:
conn.close()
raise
except socket.timeout:
raise
except (socket.error, http.client.HTTPException):
conn.close()
if i == 0:
conn.close()
conn.connect()
continue
else:
raise
else:
content = b""
if method == "HEAD":
conn.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(
self,
conn,
host,
absolute_uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [
(auth.depth(request_uri), auth)
for auth in self.authorizations
if auth.inscope(host, request_uri)
]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(
host, request_uri, headers, response, content
):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (
self.follow_all_redirects
or method in self.safe_methods
or response.status in (303, 308)
):
if self.follow_redirects and response.status in self.redirect_codes:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if "location" not in response and response.status != 300:
raise RedirectMissingLocation(
_(
"Redirected but the response is missing a Location: header."
),
response,
content,
)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if "location" in response:
location = response["location"]
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response["location"] = urllib.parse.urljoin(
absolute_uri, location
)
if response.status == 308 or (response.status == 301 and (method in self.safe_methods)):
response["-x-permanent-redirect-url"] = response["location"]
if "content-location" not in response:
response["content-location"] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if "if-none-match" in headers:
del headers["if-none-match"]
if "if-modified-since" in headers:
del headers["if-modified-since"]
if (
"authorization" in headers
and not self.forward_authorization_headers
):
del headers["authorization"]
if "location" in response:
location = response["location"]
old_response = copy.deepcopy(response)
if "content-location" not in old_response:
old_response["content-location"] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(
location,
method=redirect_method,
body=body,
headers=headers,
redirections=redirections - 1,
)
response.previous = old_response
else:
raise RedirectLimit(
"Redirected more times than redirection_limit allows.",
response,
content,
)
elif response.status in [200, 203] and method in self.safe_methods:
# Don't cache 206's since we aren't going to handle byte range requests
if "content-location" not in response:
response["content-location"] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(
self,
uri,
method="GET",
body=None,
headers=None,
redirections=DEFAULT_MAX_REDIRECTS,
connection_type=None,
):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin
with either 'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE, etc.
There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a string
object.
Any extra headers that are to be sent with the request should be provided in the
'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ''
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if "user-agent" not in headers:
headers["user-agent"] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
conn_key = scheme + ":" + authority
conn = self.connections.get(conn_key)
if conn is None:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if issubclass(connection_type, HTTPSConnectionWithTimeout):
if certs:
conn = self.connections[conn_key] = connection_type(
authority,
key_file=certs[0][0],
cert_file=certs[0][1],
timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
tls_maximum_version=self.tls_maximum_version,
tls_minimum_version=self.tls_minimum_version,
key_password=certs[0][2],
)
else:
conn = self.connections[conn_key] = connection_type(
authority,
timeout=self.timeout,
proxy_info=self.proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
tls_maximum_version=self.tls_maximum_version,
tls_minimum_version=self.tls_minimum_version,
)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout, proxy_info=self.proxy_info
)
conn.set_debuglevel(debuglevel)
if "range" not in headers and "accept-encoding" not in headers:
headers["accept-encoding"] = "gzip, deflate"
info = email.message.Message()
cachekey = None
cached_value = None
if self.cache:
cachekey = defrag_uri
cached_value = self.cache.get(cachekey)
if cached_value:
try:
info, content = cached_value.split(b"\r\n\r\n", 1)
info = email.message_from_bytes(info)
for k, v in info.items():
if v.startswith("=?") and v.endswith("?="):
info.replace_header(
k, str(*email.header.decode_header(v)[0])
)
except (IndexError, ValueError):
self.cache.delete(cachekey)
cachekey = None
cached_value = None
if (
method in self.optimistic_concurrency_methods
and self.cache
and "etag" in info
and not self.ignore_etag
and "if-match" not in headers
):
# http://www.w3.org/1999/04/Editing/
headers["if-match"] = info["etag"]
# https://tools.ietf.org/html/rfc7234
# A cache MUST invalidate the effective Request URI as well as [...] Location and Content-Location
# when a non-error status code is received in response to an unsafe request method.
if self.cache and cachekey and method not in self.safe_methods:
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in self.safe_methods and "vary" in info:
vary = info["vary"]
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if (
self.cache
and cached_value
and (method in self.safe_methods or info["status"] == "308")
and "range" not in headers
):
redirect_method = method
if info["status"] not in ("307", "308"):
redirect_method = "GET"
if "-x-permanent-redirect-url" in info:
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit(
"Redirected more times than redirection_limit allows.",
{},
"",
)
(response, new_content) = self.request(
info["-x-permanent-redirect-url"],
method=redirect_method,
headers=headers,
redirections=redirections - 1,
)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info["status"] = "504"
content = b""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if (
"etag" in info
and not self.ignore_etag
and not "if-none-match" in headers
):
headers["if-none-match"] = info["etag"]
if "last-modified" in info and not "last-modified" in headers:
headers["if-modified-since"] = info["last-modified"]
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(
headers, merged_response, content, self.cache, cachekey
)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if "only-if-cached" in cc:
info["status"] = "504"
response = Response(info)
content = b""
else:
(response, content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
)
except Exception as e:
is_timeout = isinstance(e, socket.timeout)
if is_timeout:
conn = self.connections.pop(conn_key, None)
if conn:
conn.close()
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif isinstance(e, socket.timeout):
content = b"Request Timeout"
response = Response(
{
"content-type": "text/plain",
"status": "408",
"content-length": len(content),
}
)
response.reason = "Request Timeout"
else:
content = str(e).encode("utf-8")
response = Response(
{
"content-type": "text/plain",
"status": "400",
"content-length": len(content),
}
)
response.reason = "Bad Request"
else:
raise
return (response, content)
class Response(dict):
"""An object more like email.message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server.
10 for HTTP/1.0, 11 for HTTP/1.1.
"""
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.message or
# an httplib.HTTPResponse object.
if isinstance(info, http.client.HTTPResponse):
for key, value in info.getheaders():
key = key.lower()
prev = self.get(key)
if prev is not None:
value = ", ".join((prev, value))
self[key] = value
self.status = info.status
self["status"] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.message.Message):
for key, value in list(info.items()):
self[key.lower()] = value
self.status = int(self["status"])
else:
for key, value in info.items():
self[key.lower()] = value
self.status = int(self.get("status", self.status))
def __getattr__(self, name):
if name == "dict":
return self
else:
raise AttributeError(name)
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_3934_1 |
crossvul-python_data_good_2234_4 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import pipes
from ansible.utils import template
from ansible import utils
from ansible import errors
from ansible.runner.return_data import ReturnData
import base64
class ActionModule(object):
TRANSFERS_FILES = True
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
''' handler for template operations '''
# note: since this module just calls the copy module, the --check mode support
# can be implemented entirely over there
if not self.runner.is_playbook:
raise errors.AnsibleError("in current versions of ansible, templates are only usable in playbooks")
# load up options
options = {}
if complex_args:
options.update(complex_args)
options.update(utils.parse_kv(module_args))
source = options.get('src', None)
dest = options.get('dest', None)
if (source is None and 'first_available_file' not in inject) or dest is None:
result = dict(failed=True, msg="src and dest are required")
return ReturnData(conn=conn, comm_ok=False, result=result)
# if we have first_available_file in our vars
# look up the files and use the first one we find as src
if 'first_available_file' in inject:
found = False
for fn in self.runner.module_vars.get('first_available_file'):
fn_orig = fn
fnt = template.template(self.runner.basedir, fn, inject)
fnd = utils.path_dwim(self.runner.basedir, fnt)
if not os.path.exists(fnd) and '_original_file' in inject:
fnd = utils.path_dwim_relative(inject['_original_file'], 'templates', fnt, self.runner.basedir, check=False)
if os.path.exists(fnd):
source = fnd
found = True
break
if not found:
result = dict(failed=True, msg="could not find src in first_available_file list")
return ReturnData(conn=conn, comm_ok=False, result=result)
else:
source = template.template(self.runner.basedir, source, inject)
if '_original_file' in inject:
source = utils.path_dwim_relative(inject['_original_file'], 'templates', source, self.runner.basedir)
else:
source = utils.path_dwim(self.runner.basedir, source)
if dest.endswith("/"):
base = os.path.basename(source)
dest = os.path.join(dest, base)
# template the source data locally & get ready to transfer
try:
resultant = template.template_from_file(self.runner.basedir, source, inject, vault_password=self.runner.vault_pass)
except Exception, e:
result = dict(failed=True, msg=str(e))
return ReturnData(conn=conn, comm_ok=False, result=result)
local_md5 = utils.md5s(resultant)
remote_md5 = self.runner._remote_md5(conn, tmp, dest)
if local_md5 != remote_md5:
# template is different from the remote value
# if showing diffs, we need to get the remote value
dest_contents = ''
if self.runner.diff:
# using persist_files to keep the temp directory around to avoid needing to grab another
dest_result = self.runner._execute_module(conn, tmp, 'slurp', "path=%s" % dest, inject=inject, persist_files=True)
if 'content' in dest_result.result:
dest_contents = dest_result.result['content']
if dest_result.result['encoding'] == 'base64':
dest_contents = base64.b64decode(dest_contents)
else:
raise Exception("unknown encoding, failed: %s" % dest_result.result)
xfered = self.runner._transfer_str(conn, tmp, 'source', resultant)
# fix file permissions when the copy is done as a different user
if self.runner.sudo and self.runner.sudo_user != 'root':
self.runner._low_level_exec_command(conn, "chmod a+r %s" % xfered, tmp)
# run the copy module
new_module_args = dict(
src=xfered,
dest=dest,
original_basename=os.path.basename(source),
)
module_args_tmp = utils.merge_module_args(module_args, new_module_args)
if self.runner.noop_on_check(inject):
return ReturnData(conn=conn, comm_ok=True, result=dict(changed=True), diff=dict(before_header=dest, after_header=source, before=dest_contents, after=resultant))
else:
res = self.runner._execute_module(conn, tmp, 'copy', module_args_tmp, inject=inject, complex_args=complex_args)
if res.result.get('changed', False):
res.diff = dict(before=dest_contents, after=resultant)
return res
else:
return self.runner._execute_module(conn, tmp, 'file', module_args, inject=inject, complex_args=complex_args)
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_2234_4 |
crossvul-python_data_good_2234_1 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import multiprocessing
import signal
import os
import pwd
import Queue
import random
import traceback
import tempfile
import time
import collections
import socket
import base64
import sys
import pipes
import jinja2
import subprocess
import shlex
import getpass
import ansible.constants as C
import ansible.inventory
from ansible import utils
from ansible.utils import template
from ansible.utils import check_conditional
from ansible.utils import string_functions
from ansible import errors
from ansible import module_common
import poller
import connection
from return_data import ReturnData
from ansible.callbacks import DefaultRunnerCallbacks, vv
from ansible.module_common import ModuleReplacer
module_replacer = ModuleReplacer(strip_comments=False)
HAS_ATFORK=True
try:
from Crypto.Random import atfork
except ImportError:
HAS_ATFORK=False
multiprocessing_runner = None
OUTPUT_LOCKFILE = tempfile.TemporaryFile()
PROCESS_LOCKFILE = tempfile.TemporaryFile()
################################################
def _executor_hook(job_queue, result_queue, new_stdin):
# attempt workaround of https://github.com/newsapps/beeswithmachineguns/issues/17
# this function also not present in CentOS 6
if HAS_ATFORK:
atfork()
signal.signal(signal.SIGINT, signal.SIG_IGN)
while not job_queue.empty():
try:
host = job_queue.get(block=False)
return_data = multiprocessing_runner._executor(host, new_stdin)
result_queue.put(return_data)
except Queue.Empty:
pass
except:
traceback.print_exc()
class HostVars(dict):
''' A special view of vars_cache that adds values from the inventory when needed. '''
def __init__(self, vars_cache, inventory, vault_password=None):
self.vars_cache = vars_cache
self.inventory = inventory
self.lookup = dict()
self.update(vars_cache)
self.vault_password = vault_password
def __getitem__(self, host):
if host not in self.lookup:
result = self.inventory.get_variables(host, vault_password=self.vault_password).copy()
result.update(self.vars_cache.get(host, {}))
self.lookup[host] = result
return self.lookup[host]
class Runner(object):
''' core API interface to ansible '''
# see bin/ansible for how this is used...
def __init__(self,
host_list=C.DEFAULT_HOST_LIST, # ex: /etc/ansible/hosts, legacy usage
module_path=None, # ex: /usr/share/ansible
module_name=C.DEFAULT_MODULE_NAME, # ex: copy
module_args=C.DEFAULT_MODULE_ARGS, # ex: "src=/tmp/a dest=/tmp/b"
forks=C.DEFAULT_FORKS, # parallelism level
timeout=C.DEFAULT_TIMEOUT, # SSH timeout
pattern=C.DEFAULT_PATTERN, # which hosts? ex: 'all', 'acme.example.org'
remote_user=C.DEFAULT_REMOTE_USER, # ex: 'username'
remote_pass=C.DEFAULT_REMOTE_PASS, # ex: 'password123' or None if using key
remote_port=None, # if SSH on different ports
private_key_file=C.DEFAULT_PRIVATE_KEY_FILE, # if not using keys/passwords
sudo_pass=C.DEFAULT_SUDO_PASS, # ex: 'password123' or None
background=0, # async poll every X seconds, else 0 for non-async
basedir=None, # directory of playbook, if applicable
setup_cache=None, # used to share fact data w/ other tasks
vars_cache=None, # used to store variables about hosts
transport=C.DEFAULT_TRANSPORT, # 'ssh', 'paramiko', 'local'
conditional='True', # run only if this fact expression evals to true
callbacks=None, # used for output
sudo=False, # whether to run sudo or not
sudo_user=C.DEFAULT_SUDO_USER, # ex: 'root'
module_vars=None, # a playbooks internals thing
default_vars=None, # ditto
is_playbook=False, # running from playbook or not?
inventory=None, # reference to Inventory object
subset=None, # subset pattern
check=False, # don't make any changes, just try to probe for potential changes
diff=False, # whether to show diffs for template files that change
environment=None, # environment variables (as dict) to use inside the command
complex_args=None, # structured data in addition to module_args, must be a dict
error_on_undefined_vars=C.DEFAULT_UNDEFINED_VAR_BEHAVIOR, # ex. False
accelerate=False, # use accelerated connection
accelerate_ipv6=False, # accelerated connection w/ IPv6
accelerate_port=None, # port to use with accelerated connection
su=False, # Are we running our command via su?
su_user=None, # User to su to when running command, ex: 'root'
su_pass=C.DEFAULT_SU_PASS,
vault_pass=None,
run_hosts=None, # an optional list of pre-calculated hosts to run on
no_log=False, # option to enable/disable logging for a given task
):
# used to lock multiprocess inputs and outputs at various levels
self.output_lockfile = OUTPUT_LOCKFILE
self.process_lockfile = PROCESS_LOCKFILE
if not complex_args:
complex_args = {}
# storage & defaults
self.check = check
self.diff = diff
self.setup_cache = utils.default(setup_cache, lambda: collections.defaultdict(dict))
self.vars_cache = utils.default(vars_cache, lambda: collections.defaultdict(dict))
self.basedir = utils.default(basedir, lambda: os.getcwd())
self.callbacks = utils.default(callbacks, lambda: DefaultRunnerCallbacks())
self.generated_jid = str(random.randint(0, 999999999999))
self.transport = transport
self.inventory = utils.default(inventory, lambda: ansible.inventory.Inventory(host_list))
self.module_vars = utils.default(module_vars, lambda: {})
self.default_vars = utils.default(default_vars, lambda: {})
self.always_run = None
self.connector = connection.Connection(self)
self.conditional = conditional
self.module_name = module_name
self.forks = int(forks)
self.pattern = pattern
self.module_args = module_args
self.timeout = timeout
self.remote_user = remote_user
self.remote_pass = remote_pass
self.remote_port = remote_port
self.private_key_file = private_key_file
self.background = background
self.sudo = sudo
self.sudo_user_var = sudo_user
self.sudo_user = None
self.sudo_pass = sudo_pass
self.is_playbook = is_playbook
self.environment = environment
self.complex_args = complex_args
self.error_on_undefined_vars = error_on_undefined_vars
self.accelerate = accelerate
self.accelerate_port = accelerate_port
self.accelerate_ipv6 = accelerate_ipv6
self.callbacks.runner = self
self.su = su
self.su_user_var = su_user
self.su_user = None
self.su_pass = su_pass
self.vault_pass = vault_pass
self.no_log = no_log
if self.transport == 'smart':
# if the transport is 'smart' see if SSH can support ControlPersist if not use paramiko
# 'smart' is the default since 1.2.1/1.3
cmd = subprocess.Popen(['ssh','-o','ControlPersist'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = cmd.communicate()
if "Bad configuration option" in err:
self.transport = "paramiko"
else:
self.transport = "ssh"
# save the original transport, in case it gets
# changed later via options like accelerate
self.original_transport = self.transport
# misc housekeeping
if subset and self.inventory._subset is None:
# don't override subset when passed from playbook
self.inventory.subset(subset)
# If we get a pre-built list of hosts to run on, from say a playbook, use them.
# Also where we will store the hosts to run on once discovered
self.run_hosts = run_hosts
if self.transport == 'local':
self.remote_user = pwd.getpwuid(os.geteuid())[0]
if module_path is not None:
for i in module_path.split(os.pathsep):
utils.plugins.module_finder.add_directory(i)
utils.plugins.push_basedir(self.basedir)
# ensure we are using unique tmp paths
random.seed()
# *****************************************************
def _complex_args_hack(self, complex_args, module_args):
"""
ansible-playbook both allows specifying key=value string arguments and complex arguments
however not all modules use our python common module system and cannot
access these. An example might be a Bash module. This hack allows users to still pass "args"
as a hash of simple scalars to those arguments and is short term. We could technically
just feed JSON to the module, but that makes it hard on Bash consumers. The way this is implemented
it does mean values in 'args' have LOWER priority than those on the key=value line, allowing
args to provide yet another way to have pluggable defaults.
"""
if complex_args is None:
return module_args
if not isinstance(complex_args, dict):
raise errors.AnsibleError("complex arguments are not a dictionary: %s" % complex_args)
for (k,v) in complex_args.iteritems():
if isinstance(v, basestring):
module_args = "%s=%s %s" % (k, pipes.quote(v), module_args)
return module_args
# *****************************************************
def _transfer_str(self, conn, tmp, name, data):
''' transfer string to remote file '''
if type(data) == dict:
data = utils.jsonify(data)
afd, afile = tempfile.mkstemp()
afo = os.fdopen(afd, 'w')
try:
if not isinstance(data, unicode):
#ensure the data is valid UTF-8
data.decode('utf-8')
else:
data = data.encode('utf-8')
afo.write(data)
except:
raise errors.AnsibleError("failure encoding into utf-8")
afo.flush()
afo.close()
remote = os.path.join(tmp, name)
try:
conn.put_file(afile, remote)
finally:
os.unlink(afile)
return remote
# *****************************************************
def _compute_environment_string(self, inject=None):
''' what environment variables to use when running the command? '''
default_environment = dict(
LANG = C.DEFAULT_MODULE_LANG,
LC_CTYPE = C.DEFAULT_MODULE_LANG,
)
if self.environment:
enviro = template.template(self.basedir, self.environment, inject, convert_bare=True)
enviro = utils.safe_eval(enviro)
if type(enviro) != dict:
raise errors.AnsibleError("environment must be a dictionary, received %s" % enviro)
default_environment.update(enviro)
result = ""
for (k,v) in default_environment.iteritems():
result = "%s=%s %s" % (k, pipes.quote(unicode(v)), result)
return result
# *****************************************************
def _compute_delegate(self, host, password, remote_inject):
""" Build a dictionary of all attributes for the delegate host """
delegate = {}
# allow delegated host to be templated
delegate['host'] = template.template(self.basedir, host,
remote_inject, fail_on_undefined=True)
delegate['inject'] = remote_inject.copy()
# set any interpreters
interpreters = []
for i in delegate['inject']:
if i.startswith("ansible_") and i.endswith("_interpreter"):
interpreters.append(i)
for i in interpreters:
del delegate['inject'][i]
port = C.DEFAULT_REMOTE_PORT
this_host = delegate['host']
# get the vars for the delegate by it's name
try:
this_info = delegate['inject']['hostvars'][this_host]
except:
# make sure the inject is empty for non-inventory hosts
this_info = {}
# get the real ssh_address for the delegate
# and allow ansible_ssh_host to be templated
delegate['ssh_host'] = template.template(self.basedir,
this_info.get('ansible_ssh_host', this_host),
this_info, fail_on_undefined=True)
delegate['port'] = this_info.get('ansible_ssh_port', port)
delegate['user'] = self._compute_delegate_user(this_host, delegate['inject'])
delegate['pass'] = this_info.get('ansible_ssh_pass', password)
delegate['private_key_file'] = this_info.get('ansible_ssh_private_key_file',
self.private_key_file)
delegate['transport'] = this_info.get('ansible_connection', self.transport)
delegate['sudo_pass'] = this_info.get('ansible_sudo_pass', self.sudo_pass)
# Last chance to get private_key_file from global variables.
# this is usefull if delegated host is not defined in the inventory
if delegate['private_key_file'] is None:
delegate['private_key_file'] = remote_inject.get(
'ansible_ssh_private_key_file', None)
if delegate['private_key_file'] is not None:
delegate['private_key_file'] = os.path.expanduser(delegate['private_key_file'])
for i in this_info:
if i.startswith("ansible_") and i.endswith("_interpreter"):
delegate['inject'][i] = this_info[i]
return delegate
def _compute_delegate_user(self, host, inject):
""" Caculate the remote user based on an order of preference """
# inventory > playbook > original_host
actual_user = inject.get('ansible_ssh_user', self.remote_user)
thisuser = None
if host in inject['hostvars']:
if inject['hostvars'][host].get('ansible_ssh_user'):
# user for delegate host in inventory
thisuser = inject['hostvars'][host].get('ansible_ssh_user')
if thisuser is None and self.remote_user:
# user defined by play/runner
thisuser = self.remote_user
if thisuser is not None:
actual_user = thisuser
else:
# fallback to the inventory user of the play host
#actual_user = inject.get('ansible_ssh_user', actual_user)
actual_user = inject.get('ansible_ssh_user', self.remote_user)
return actual_user
def _count_module_args(self, args):
'''
Count the number of k=v pairs in the supplied module args. This is
basically a specialized version of parse_kv() from utils with a few
minor changes.
'''
options = {}
if args is not None:
args = args.encode('utf-8')
try:
lexer = shlex.shlex(args, posix=True)
lexer.whitespace_split = True
lexer.quotes = '"'
lexer.ignore_quotes = "'"
vargs = list(lexer)
except ValueError, ve:
if 'no closing quotation' in str(ve).lower():
raise errors.AnsibleError("error parsing argument string '%s', try quoting the entire line." % args)
else:
raise
vargs = [x.decode('utf-8') for x in vargs]
for x in vargs:
if "=" in x:
k, v = x.split("=",1)
if k in options:
raise errors.AnsibleError("a duplicate parameter was found in the argument string (%s)" % k)
options[k] = v
return len(options)
# *****************************************************
def _execute_module(self, conn, tmp, module_name, args,
async_jid=None, async_module=None, async_limit=None, inject=None, persist_files=False, complex_args=None, delete_remote_tmp=True):
''' transfer and run a module along with its arguments on the remote side'''
# hack to support fireball mode
if module_name == 'fireball':
args = "%s password=%s" % (args, base64.b64encode(str(utils.key_for_hostname(conn.host))))
if 'port' not in args:
args += " port=%s" % C.ZEROMQ_PORT
(
module_style,
shebang,
module_data
) = self._configure_module(conn, module_name, args, inject, complex_args)
# a remote tmp path may be necessary and not already created
if self._late_needs_tmp_path(conn, tmp, module_style):
tmp = self._make_tmp_path(conn)
remote_module_path = os.path.join(tmp, module_name)
if (module_style != 'new'
or async_jid is not None
or not conn.has_pipelining
or not C.ANSIBLE_SSH_PIPELINING
or C.DEFAULT_KEEP_REMOTE_FILES
or self.su):
self._transfer_str(conn, tmp, module_name, module_data)
environment_string = self._compute_environment_string(inject)
if "tmp" in tmp and ((self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root')):
# deal with possible umask issues once sudo'ed to other user
cmd_chmod = "chmod a+r %s" % remote_module_path
self._low_level_exec_command(conn, cmd_chmod, tmp, sudoable=False)
cmd = ""
in_data = None
if module_style != 'new':
if 'CHECKMODE=True' in args:
# if module isn't using AnsibleModuleCommon infrastructure we can't be certain it knows how to
# do --check mode, so to be safe we will not run it.
return ReturnData(conn=conn, result=dict(skipped=True, msg="cannot yet run check mode against old-style modules"))
elif 'NO_LOG' in args:
return ReturnData(conn=conn, result=dict(skipped=True, msg="cannot use no_log: with old-style modules"))
args = template.template(self.basedir, args, inject)
# decide whether we need to transfer JSON or key=value
argsfile = None
if module_style == 'non_native_want_json':
if complex_args:
complex_args.update(utils.parse_kv(args))
argsfile = self._transfer_str(conn, tmp, 'arguments', utils.jsonify(complex_args))
else:
argsfile = self._transfer_str(conn, tmp, 'arguments', utils.jsonify(utils.parse_kv(args)))
else:
argsfile = self._transfer_str(conn, tmp, 'arguments', args)
if (self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root'):
# deal with possible umask issues once sudo'ed to other user
cmd_args_chmod = "chmod a+r %s" % argsfile
self._low_level_exec_command(conn, cmd_args_chmod, tmp, sudoable=False)
if async_jid is None:
cmd = "%s %s" % (remote_module_path, argsfile)
else:
cmd = " ".join([str(x) for x in [remote_module_path, async_jid, async_limit, async_module, argsfile]])
else:
if async_jid is None:
if conn.has_pipelining and C.ANSIBLE_SSH_PIPELINING and not C.DEFAULT_KEEP_REMOTE_FILES and not self.su:
in_data = module_data
else:
cmd = "%s" % (remote_module_path)
else:
cmd = " ".join([str(x) for x in [remote_module_path, async_jid, async_limit, async_module]])
if not shebang:
raise errors.AnsibleError("module is missing interpreter line")
cmd = " ".join([environment_string.strip(), shebang.replace("#!","").strip(), cmd])
cmd = cmd.strip()
if "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if not self.sudo or self.su or self.sudo_user == 'root' or self.su_user == 'root':
# not sudoing or sudoing to root, so can cleanup files in the same step
cmd = cmd + "; rm -rf %s >/dev/null 2>&1" % tmp
sudoable = True
if module_name == "accelerate":
# always run the accelerate module as the user
# specified in the play, not the sudo_user
sudoable = False
if self.su:
res = self._low_level_exec_command(conn, cmd, tmp, su=True, in_data=in_data)
else:
res = self._low_level_exec_command(conn, cmd, tmp, sudoable=sudoable, in_data=in_data)
if "tmp" in tmp and not C.DEFAULT_KEEP_REMOTE_FILES and not persist_files and delete_remote_tmp:
if (self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root'):
# not sudoing to root, so maybe can't delete files as that other user
# have to clean up temp files as original user in a second step
cmd2 = "rm -rf %s >/dev/null 2>&1" % tmp
self._low_level_exec_command(conn, cmd2, tmp, sudoable=False)
data = utils.parse_json(res['stdout'], from_remote=True)
if 'parsed' in data and data['parsed'] == False:
data['msg'] += res['stderr']
return ReturnData(conn=conn, result=data)
# *****************************************************
def _executor(self, host, new_stdin):
''' handler for multiprocessing library '''
try:
fileno = sys.stdin.fileno()
except ValueError:
fileno = None
try:
self._new_stdin = new_stdin
if not new_stdin and fileno is not None:
try:
self._new_stdin = os.fdopen(os.dup(fileno))
except OSError, e:
# couldn't dupe stdin, most likely because it's
# not a valid file descriptor, so we just rely on
# using the one that was passed in
pass
exec_rc = self._executor_internal(host, new_stdin)
if type(exec_rc) != ReturnData:
raise Exception("unexpected return type: %s" % type(exec_rc))
# redundant, right?
if not exec_rc.comm_ok:
self.callbacks.on_unreachable(host, exec_rc.result)
return exec_rc
except errors.AnsibleError, ae:
msg = str(ae)
self.callbacks.on_unreachable(host, msg)
return ReturnData(host=host, comm_ok=False, result=dict(failed=True, msg=msg))
except Exception:
msg = traceback.format_exc()
self.callbacks.on_unreachable(host, msg)
return ReturnData(host=host, comm_ok=False, result=dict(failed=True, msg=msg))
# *****************************************************
def _executor_internal(self, host, new_stdin):
''' executes any module one or more times '''
host_variables = self.inventory.get_variables(host, vault_password=self.vault_pass)
host_connection = host_variables.get('ansible_connection', self.transport)
if host_connection in [ 'paramiko', 'ssh', 'accelerate' ]:
port = host_variables.get('ansible_ssh_port', self.remote_port)
if port is None:
port = C.DEFAULT_REMOTE_PORT
else:
# fireball, local, etc
port = self.remote_port
# merge the VARS and SETUP caches for this host
combined_cache = self.setup_cache.copy()
combined_cache.setdefault(host, {}).update(self.vars_cache.get(host, {}))
hostvars = HostVars(combined_cache, self.inventory, vault_password=self.vault_pass)
# use combined_cache and host_variables to template the module_vars
# we update the inject variables with the data we're about to template
# since some of the variables we'll be replacing may be contained there too
module_vars_inject = utils.combine_vars(host_variables, combined_cache.get(host, {}))
module_vars_inject = utils.combine_vars(self.module_vars, module_vars_inject)
module_vars = template.template(self.basedir, self.module_vars, module_vars_inject)
inject = {}
inject = utils.combine_vars(inject, self.default_vars)
inject = utils.combine_vars(inject, host_variables)
inject = utils.combine_vars(inject, module_vars)
inject = utils.combine_vars(inject, combined_cache.get(host, {}))
inject.setdefault('ansible_ssh_user', self.remote_user)
inject['hostvars'] = hostvars
inject['group_names'] = host_variables.get('group_names', [])
inject['groups'] = self.inventory.groups_list()
inject['vars'] = self.module_vars
inject['defaults'] = self.default_vars
inject['environment'] = self.environment
inject['playbook_dir'] = self.basedir
if self.inventory.basedir() is not None:
inject['inventory_dir'] = self.inventory.basedir()
if self.inventory.src() is not None:
inject['inventory_file'] = self.inventory.src()
# allow with_foo to work in playbooks...
items = None
items_plugin = self.module_vars.get('items_lookup_plugin', None)
if items_plugin is not None and items_plugin in utils.plugins.lookup_loader:
basedir = self.basedir
if '_original_file' in inject:
basedir = os.path.dirname(inject['_original_file'])
filesdir = os.path.join(basedir, '..', 'files')
if os.path.exists(filesdir):
basedir = filesdir
items_terms = self.module_vars.get('items_lookup_terms', '')
items_terms = template.template(basedir, items_terms, inject)
items = utils.plugins.lookup_loader.get(items_plugin, runner=self, basedir=basedir).run(items_terms, inject=inject)
# strip out any jinja2 template syntax within
# the data returned by the lookup plugin
items = utils._clean_data_struct(items, from_remote=True)
if type(items) != list:
raise errors.AnsibleError("lookup plugins have to return a list: %r" % items)
if len(items) and utils.is_list_of_strings(items) and self.module_name in [ 'apt', 'yum', 'pkgng' ]:
# hack for apt, yum, and pkgng so that with_items maps back into a single module call
use_these_items = []
for x in items:
inject['item'] = x
if not self.conditional or utils.check_conditional(self.conditional, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
use_these_items.append(x)
inject['item'] = ",".join(use_these_items)
items = None
# logic to replace complex args if possible
complex_args = self.complex_args
# logic to decide how to run things depends on whether with_items is used
if items is None:
if isinstance(complex_args, basestring):
complex_args = template.template(self.basedir, complex_args, inject, convert_bare=True)
complex_args = utils.safe_eval(complex_args)
if type(complex_args) != dict:
raise errors.AnsibleError("args must be a dictionary, received %s" % complex_args)
return self._executor_internal_inner(host, self.module_name, self.module_args, inject, port, complex_args=complex_args)
elif len(items) > 0:
# executing using with_items, so make multiple calls
# TODO: refactor
if self.background > 0:
raise errors.AnsibleError("lookup plugins (with_*) cannot be used with async tasks")
all_comm_ok = True
all_changed = False
all_failed = False
results = []
for x in items:
# use a fresh inject for each item
this_inject = inject.copy()
this_inject['item'] = x
# TODO: this idiom should be replaced with an up-conversion to a Jinja2 template evaluation
if isinstance(self.complex_args, basestring):
complex_args = template.template(self.basedir, self.complex_args, this_inject, convert_bare=True)
complex_args = utils.safe_eval(complex_args)
if type(complex_args) != dict:
raise errors.AnsibleError("args must be a dictionary, received %s" % complex_args)
result = self._executor_internal_inner(
host,
self.module_name,
self.module_args,
this_inject,
port,
complex_args=complex_args
)
results.append(result.result)
if result.comm_ok == False:
all_comm_ok = False
all_failed = True
break
for x in results:
if x.get('changed') == True:
all_changed = True
if (x.get('failed') == True) or ('failed_when_result' in x and [x['failed_when_result']] or [('rc' in x) and (x['rc'] != 0)])[0]:
all_failed = True
break
msg = 'All items completed'
if all_failed:
msg = "One or more items failed."
rd_result = dict(failed=all_failed, changed=all_changed, results=results, msg=msg)
if not all_failed:
del rd_result['failed']
return ReturnData(host=host, comm_ok=all_comm_ok, result=rd_result)
else:
self.callbacks.on_skipped(host, None)
return ReturnData(host=host, comm_ok=True, result=dict(changed=False, skipped=True))
# *****************************************************
def _executor_internal_inner(self, host, module_name, module_args, inject, port, is_chained=False, complex_args=None):
''' decides how to invoke a module '''
# late processing of parameterized sudo_user (with_items,..)
if self.sudo_user_var is not None:
self.sudo_user = template.template(self.basedir, self.sudo_user_var, inject)
if self.su_user_var is not None:
self.su_user = template.template(self.basedir, self.su_user_var, inject)
# allow module args to work as a dictionary
# though it is usually a string
new_args = ""
if type(module_args) == dict:
for (k,v) in module_args.iteritems():
new_args = new_args + "%s='%s' " % (k,v)
module_args = new_args
# module_name may be dynamic (but cannot contain {{ ansible_ssh_user }})
module_name = template.template(self.basedir, module_name, inject)
if module_name in utils.plugins.action_loader:
if self.background != 0:
raise errors.AnsibleError("async mode is not supported with the %s module" % module_name)
handler = utils.plugins.action_loader.get(module_name, self)
elif self.background == 0:
handler = utils.plugins.action_loader.get('normal', self)
else:
handler = utils.plugins.action_loader.get('async', self)
if type(self.conditional) != list:
self.conditional = [ self.conditional ]
for cond in self.conditional:
if not utils.check_conditional(cond, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
result = utils.jsonify(dict(changed=False, skipped=True))
self.callbacks.on_skipped(host, inject.get('item',None))
return ReturnData(host=host, result=result)
if getattr(handler, 'setup', None) is not None:
handler.setup(module_name, inject)
conn = None
actual_host = inject.get('ansible_ssh_host', host)
# allow ansible_ssh_host to be templated
actual_host = template.template(self.basedir, actual_host, inject, fail_on_undefined=True)
actual_port = port
actual_user = inject.get('ansible_ssh_user', self.remote_user)
actual_pass = inject.get('ansible_ssh_pass', self.remote_pass)
actual_transport = inject.get('ansible_connection', self.transport)
actual_private_key_file = inject.get('ansible_ssh_private_key_file', self.private_key_file)
actual_private_key_file = template.template(self.basedir, actual_private_key_file, inject, fail_on_undefined=True)
self.sudo = utils.boolean(inject.get('ansible_sudo', self.sudo))
self.sudo_user = inject.get('ansible_sudo_user', self.sudo_user)
self.sudo_pass = inject.get('ansible_sudo_pass', self.sudo_pass)
self.su = inject.get('ansible_su', self.su)
self.su_pass = inject.get('ansible_su_pass', self.su_pass)
# select default root user in case self.sudo requested
# but no user specified; happens e.g. in host vars when
# just ansible_sudo=True is specified
if self.sudo and self.sudo_user is None:
self.sudo_user = 'root'
if actual_private_key_file is not None:
actual_private_key_file = os.path.expanduser(actual_private_key_file)
if self.accelerate and actual_transport != 'local':
#Fix to get the inventory name of the host to accelerate plugin
if inject.get('ansible_ssh_host', None):
self.accelerate_inventory_host = host
else:
self.accelerate_inventory_host = None
# if we're using accelerated mode, force the
# transport to accelerate
actual_transport = "accelerate"
if not self.accelerate_port:
self.accelerate_port = C.ACCELERATE_PORT
if actual_transport in [ 'paramiko', 'ssh', 'accelerate' ]:
actual_port = inject.get('ansible_ssh_port', port)
# the delegated host may have different SSH port configured, etc
# and we need to transfer those, and only those, variables
delegate_to = inject.get('delegate_to', None)
if delegate_to is not None:
delegate = self._compute_delegate(delegate_to, actual_pass, inject)
actual_transport = delegate['transport']
actual_host = delegate['ssh_host']
actual_port = delegate['port']
actual_user = delegate['user']
actual_pass = delegate['pass']
actual_private_key_file = delegate['private_key_file']
self.sudo_pass = delegate['sudo_pass']
inject = delegate['inject']
# user/pass may still contain variables at this stage
actual_user = template.template(self.basedir, actual_user, inject)
actual_pass = template.template(self.basedir, actual_pass, inject)
self.sudo_pass = template.template(self.basedir, self.sudo_pass, inject)
# make actual_user available as __magic__ ansible_ssh_user variable
inject['ansible_ssh_user'] = actual_user
try:
if actual_transport == 'accelerate':
# for accelerate, we stuff both ports into a single
# variable so that we don't have to mangle other function
# calls just to accomodate this one case
actual_port = [actual_port, self.accelerate_port]
elif actual_port is not None:
actual_port = int(template.template(self.basedir, actual_port, inject))
except ValueError, e:
result = dict(failed=True, msg="FAILED: Configured port \"%s\" is not a valid port, expected integer" % actual_port)
return ReturnData(host=host, comm_ok=False, result=result)
try:
conn = self.connector.connect(actual_host, actual_port, actual_user, actual_pass, actual_transport, actual_private_key_file)
if delegate_to or host != actual_host:
conn.delegate = host
except errors.AnsibleConnectionFailed, e:
result = dict(failed=True, msg="FAILED: %s" % str(e))
return ReturnData(host=host, comm_ok=False, result=result)
tmp = ''
# action plugins may DECLARE via TRANSFERS_FILES = True that they need a remote tmp path working dir
if self._early_needs_tmp_path(module_name, handler):
tmp = self._make_tmp_path(conn)
# render module_args and complex_args templates
try:
# When templating module_args, we need to be careful to ensure
# that no variables inadvertantly (or maliciously) add params
# to the list of args. We do this by counting the number of k=v
# pairs before and after templating.
num_args_pre = self._count_module_args(module_args)
module_args = template.template(self.basedir, module_args, inject, fail_on_undefined=self.error_on_undefined_vars)
num_args_post = self._count_module_args(module_args)
if num_args_pre != num_args_post:
raise errors.AnsibleError("A variable inserted a new parameter into the module args. " + \
"Be sure to quote variables if they contain equal signs (for example: \"{{var}}\").")
# And we also make sure nothing added in special flags for things
# like the command/shell module (ie. #USE_SHELL)
if '#USE_SHELL' in module_args:
raise errors.AnsibleError("A variable tried to add #USE_SHELL to the module arguments.")
complex_args = template.template(self.basedir, complex_args, inject, fail_on_undefined=self.error_on_undefined_vars)
except jinja2.exceptions.UndefinedError, e:
raise errors.AnsibleUndefinedVariable("One or more undefined variables: %s" % str(e))
result = handler.run(conn, tmp, module_name, module_args, inject, complex_args)
# Code for do until feature
until = self.module_vars.get('until', None)
if until is not None and result.comm_ok:
inject[self.module_vars.get('register')] = result.result
cond = template.template(self.basedir, until, inject, expand_lists=False)
if not utils.check_conditional(cond, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
retries = self.module_vars.get('retries')
delay = self.module_vars.get('delay')
for x in range(1, int(retries) + 1):
# template the delay, cast to float and sleep
delay = template.template(self.basedir, delay, inject, expand_lists=False)
delay = float(delay)
time.sleep(delay)
tmp = ''
if self._early_needs_tmp_path(module_name, handler):
tmp = self._make_tmp_path(conn)
result = handler.run(conn, tmp, module_name, module_args, inject, complex_args)
result.result['attempts'] = x
vv("Result from run %i is: %s" % (x, result.result))
inject[self.module_vars.get('register')] = result.result
cond = template.template(self.basedir, until, inject, expand_lists=False)
if utils.check_conditional(cond, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
break
if result.result['attempts'] == retries and not utils.check_conditional(cond, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars):
result.result['failed'] = True
result.result['msg'] = "Task failed as maximum retries was encountered"
else:
result.result['attempts'] = 0
conn.close()
if not result.comm_ok:
# connection or parsing errors...
self.callbacks.on_unreachable(host, result.result)
else:
data = result.result
# https://github.com/ansible/ansible/issues/4958
if hasattr(sys.stdout, "isatty"):
if "stdout" in data and sys.stdout.isatty():
if not string_functions.isprintable(data['stdout']):
data['stdout'] = ''
if 'item' in inject:
result.result['item'] = inject['item']
result.result['invocation'] = dict(
module_args=module_args,
module_name=module_name
)
changed_when = self.module_vars.get('changed_when')
failed_when = self.module_vars.get('failed_when')
if (changed_when is not None or failed_when is not None) and self.background == 0:
register = self.module_vars.get('register')
if register is not None:
if 'stdout' in data:
data['stdout_lines'] = data['stdout'].splitlines()
inject[register] = data
# only run the final checks if the async_status has finished,
# or if we're not running an async_status check at all
if (module_name == 'async_status' and "finished" in data) or module_name != 'async_status':
if changed_when is not None and 'skipped' not in data:
data['changed'] = utils.check_conditional(changed_when, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars)
if failed_when is not None and 'skipped' not in data:
data['failed_when_result'] = data['failed'] = utils.check_conditional(failed_when, self.basedir, inject, fail_on_undefined=self.error_on_undefined_vars)
if is_chained:
# no callbacks
return result
if 'skipped' in data:
self.callbacks.on_skipped(host, inject.get('item',None))
elif not result.is_successful():
ignore_errors = self.module_vars.get('ignore_errors', False)
self.callbacks.on_failed(host, data, ignore_errors)
else:
if self.diff:
self.callbacks.on_file_diff(conn.host, result.diff)
self.callbacks.on_ok(host, data)
return result
def _early_needs_tmp_path(self, module_name, handler):
''' detect if a tmp path should be created before the handler is called '''
if module_name in utils.plugins.action_loader:
return getattr(handler, 'TRANSFERS_FILES', False)
# other modules never need tmp path at early stage
return False
def _late_needs_tmp_path(self, conn, tmp, module_style):
if "tmp" in tmp:
# tmp has already been created
return False
if not conn.has_pipelining or not C.ANSIBLE_SSH_PIPELINING or C.DEFAULT_KEEP_REMOTE_FILES or self.su:
# tmp is necessary to store module source code
return True
if not conn.has_pipelining:
# tmp is necessary to store the module source code
# or we want to keep the files on the target system
return True
if module_style != "new":
# even when conn has pipelining, old style modules need tmp to store arguments
return True
return False
# *****************************************************
def _low_level_exec_command(self, conn, cmd, tmp, sudoable=False,
executable=None, su=False, in_data=None):
''' execute a command string over SSH, return the output '''
if executable is None:
executable = C.DEFAULT_EXECUTABLE
sudo_user = self.sudo_user
su_user = self.su_user
# compare connection user to (su|sudo)_user and disable if the same
if hasattr(conn, 'user'):
if (not su and conn.user == sudo_user) or (su and conn.user == su_user):
sudoable = False
su = False
else:
# assume connection type is local if no user attribute
this_user = getpass.getuser()
if (not su and this_user == sudo_user) or (su and this_user == su_user):
sudoable = False
su = False
if su:
rc, stdin, stdout, stderr = conn.exec_command(cmd,
tmp,
su=su,
su_user=su_user,
executable=executable,
in_data=in_data)
else:
rc, stdin, stdout, stderr = conn.exec_command(cmd,
tmp,
sudo_user,
sudoable=sudoable,
executable=executable,
in_data=in_data)
if type(stdout) not in [ str, unicode ]:
out = ''.join(stdout.readlines())
else:
out = stdout
if type(stderr) not in [ str, unicode ]:
err = ''.join(stderr.readlines())
else:
err = stderr
if rc is not None:
return dict(rc=rc, stdout=out, stderr=err)
else:
return dict(stdout=out, stderr=err)
# *****************************************************
def _remote_md5(self, conn, tmp, path):
''' takes a remote md5sum without requiring python, and returns 1 if no file '''
path = pipes.quote(path)
# The following test needs to be SH-compliant. BASH-isms will
# not work if /bin/sh points to a non-BASH shell.
test = "rc=0; [ -r \"%s\" ] || rc=2; [ -f \"%s\" ] || rc=1; [ -d \"%s\" ] && echo 3 && exit 0" % ((path,) * 3)
md5s = [
"(/usr/bin/md5sum %s 2>/dev/null)" % path, # Linux
"(/sbin/md5sum -q %s 2>/dev/null)" % path, # ?
"(/usr/bin/digest -a md5 %s 2>/dev/null)" % path, # Solaris 10+
"(/sbin/md5 -q %s 2>/dev/null)" % path, # Freebsd
"(/usr/bin/md5 -n %s 2>/dev/null)" % path, # Netbsd
"(/bin/md5 -q %s 2>/dev/null)" % path, # Openbsd
"(/usr/bin/csum -h MD5 %s 2>/dev/null)" % path, # AIX
"(/bin/csum -h MD5 %s 2>/dev/null)" % path # AIX also
]
cmd = " || ".join(md5s)
cmd = "%s; %s || (echo \"${rc} %s\")" % (test, cmd, path)
data = self._low_level_exec_command(conn, cmd, tmp, sudoable=True)
data2 = utils.last_non_blank_line(data['stdout'])
try:
if data2 == '':
# this may happen if the connection to the remote server
# failed, so just return "INVALIDMD5SUM" to avoid errors
return "INVALIDMD5SUM"
else:
return data2.split()[0]
except IndexError:
sys.stderr.write("warning: md5sum command failed unusually, please report this to the list so it can be fixed\n")
sys.stderr.write("command: %s\n" % md5s)
sys.stderr.write("----\n")
sys.stderr.write("output: %s\n" % data)
sys.stderr.write("----\n")
# this will signal that it changed and allow things to keep going
return "INVALIDMD5SUM"
# *****************************************************
def _make_tmp_path(self, conn):
''' make and return a temporary path on a remote box '''
basefile = 'ansible-tmp-%s-%s' % (time.time(), random.randint(0, 2**48))
basetmp = os.path.join(C.DEFAULT_REMOTE_TMP, basefile)
if (self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root') and basetmp.startswith('$HOME'):
basetmp = os.path.join('/tmp', basefile)
cmd = 'mkdir -p %s' % basetmp
if self.remote_user != 'root' or ((self.sudo and self.sudo_user != 'root') or (self.su and self.su_user != 'root')):
cmd += ' && chmod a+rx %s' % basetmp
cmd += ' && echo %s' % basetmp
result = self._low_level_exec_command(conn, cmd, None, sudoable=False)
# error handling on this seems a little aggressive?
if result['rc'] != 0:
if result['rc'] == 5:
output = 'Authentication failure.'
elif result['rc'] == 255 and self.transport in ['ssh']:
if utils.VERBOSITY > 3:
output = 'SSH encountered an unknown error. The output was:\n%s' % (result['stdout']+result['stderr'])
else:
output = 'SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue'
else:
output = 'Authentication or permission failure. In some cases, you may have been able to authenticate and did not have permissions on the remote directory. Consider changing the remote temp path in ansible.cfg to a path rooted in "/tmp". Failed command was: %s, exited with result %d' % (cmd, result['rc'])
if 'stdout' in result and result['stdout'] != '':
output = output + ": %s" % result['stdout']
raise errors.AnsibleError(output)
rc = utils.last_non_blank_line(result['stdout']).strip() + '/'
# Catch failure conditions, files should never be
# written to locations in /.
if rc == '/':
raise errors.AnsibleError('failed to resolve remote temporary directory from %s: `%s` returned empty string' % (basetmp, cmd))
return rc
# *****************************************************
def _remove_tmp_path(self, conn, tmp_path):
''' Remove a tmp_path. '''
if "-tmp-" in tmp_path:
cmd = "rm -rf %s >/dev/null 2>&1" % tmp_path
self._low_level_exec_command(conn, cmd, None, sudoable=False)
# If we have gotten here we have a working ssh configuration.
# If ssh breaks we could leave tmp directories out on the remote system.
# *****************************************************
def _copy_module(self, conn, tmp, module_name, module_args, inject, complex_args=None):
''' transfer a module over SFTP, does not run it '''
(
module_style,
module_shebang,
module_data
) = self._configure_module(conn, module_name, module_args, inject, complex_args)
module_remote_path = os.path.join(tmp, module_name)
self._transfer_str(conn, tmp, module_name, module_data)
return (module_remote_path, module_style, module_shebang)
# *****************************************************
def _configure_module(self, conn, module_name, module_args, inject, complex_args=None):
''' find module and configure it '''
# Search module path(s) for named module.
module_path = utils.plugins.module_finder.find_plugin(module_name)
if module_path is None:
raise errors.AnsibleFileNotFound("module %s not found in %s" % (module_name, utils.plugins.module_finder.print_paths()))
# insert shared code and arguments into the module
(module_data, module_style, module_shebang) = module_replacer.modify_module(
module_path, complex_args, module_args, inject
)
return (module_style, module_shebang, module_data)
# *****************************************************
def _parallel_exec(self, hosts):
''' handles mulitprocessing when more than 1 fork is required '''
manager = multiprocessing.Manager()
job_queue = manager.Queue()
for host in hosts:
job_queue.put(host)
result_queue = manager.Queue()
try:
fileno = sys.stdin.fileno()
except ValueError:
fileno = None
workers = []
for i in range(self.forks):
new_stdin = None
if fileno is not None:
try:
new_stdin = os.fdopen(os.dup(fileno))
except OSError, e:
# couldn't dupe stdin, most likely because it's
# not a valid file descriptor, so we just rely on
# using the one that was passed in
pass
prc = multiprocessing.Process(target=_executor_hook,
args=(job_queue, result_queue, new_stdin))
prc.start()
workers.append(prc)
try:
for worker in workers:
worker.join()
except KeyboardInterrupt:
for worker in workers:
worker.terminate()
worker.join()
results = []
try:
while not result_queue.empty():
results.append(result_queue.get(block=False))
except socket.error:
raise errors.AnsibleError("<interrupted>")
return results
# *****************************************************
def _partition_results(self, results):
''' separate results by ones we contacted & ones we didn't '''
if results is None:
return None
results2 = dict(contacted={}, dark={})
for result in results:
host = result.host
if host is None:
raise Exception("internal error, host not set")
if result.communicated_ok():
results2["contacted"][host] = result.result
else:
results2["dark"][host] = result.result
# hosts which were contacted but never got a chance to return
for host in self.run_hosts:
if not (host in results2['dark'] or host in results2['contacted']):
results2["dark"][host] = {}
return results2
# *****************************************************
def run(self):
''' xfer & run module on all matched hosts '''
# find hosts that match the pattern
if not self.run_hosts:
self.run_hosts = self.inventory.list_hosts(self.pattern)
hosts = self.run_hosts
if len(hosts) == 0:
self.callbacks.on_no_hosts()
return dict(contacted={}, dark={})
global multiprocessing_runner
multiprocessing_runner = self
results = None
# Check if this is an action plugin. Some of them are designed
# to be ran once per group of hosts. Example module: pause,
# run once per hostgroup, rather than pausing once per each
# host.
p = utils.plugins.action_loader.get(self.module_name, self)
if self.forks == 0 or self.forks > len(hosts):
self.forks = len(hosts)
if p and getattr(p, 'BYPASS_HOST_LOOP', None):
# Expose the current hostgroup to the bypassing plugins
self.host_set = hosts
# We aren't iterating over all the hosts in this
# group. So, just pick the first host in our group to
# construct the conn object with.
result_data = self._executor(hosts[0], None).result
# Create a ResultData item for each host in this group
# using the returned result. If we didn't do this we would
# get false reports of dark hosts.
results = [ ReturnData(host=h, result=result_data, comm_ok=True) \
for h in hosts ]
del self.host_set
elif self.forks > 1:
try:
results = self._parallel_exec(hosts)
except IOError, ie:
print ie.errno
if ie.errno == 32:
# broken pipe from Ctrl+C
raise errors.AnsibleError("interrupted")
raise
else:
results = [ self._executor(h, None) for h in hosts ]
return self._partition_results(results)
# *****************************************************
def run_async(self, time_limit):
''' Run this module asynchronously and return a poller. '''
self.background = time_limit
results = self.run()
return results, poller.AsyncPoller(results, self)
# *****************************************************
def noop_on_check(self, inject):
''' Should the runner run in check mode or not ? '''
# initialize self.always_run on first call
if self.always_run is None:
self.always_run = self.module_vars.get('always_run', False)
self.always_run = check_conditional(
self.always_run, self.basedir, inject, fail_on_undefined=True)
return (self.check and not self.always_run)
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_2234_1 |
crossvul-python_data_bad_2234_4 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import os
import pipes
from ansible.utils import template
from ansible import utils
from ansible import errors
from ansible.runner.return_data import ReturnData
import base64
class ActionModule(object):
TRANSFERS_FILES = True
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
''' handler for template operations '''
# note: since this module just calls the copy module, the --check mode support
# can be implemented entirely over there
if not self.runner.is_playbook:
raise errors.AnsibleError("in current versions of ansible, templates are only usable in playbooks")
# load up options
options = {}
if complex_args:
options.update(complex_args)
options.update(utils.parse_kv(module_args))
source = options.get('src', None)
dest = options.get('dest', None)
if (source is None and 'first_available_file' not in inject) or dest is None:
result = dict(failed=True, msg="src and dest are required")
return ReturnData(conn=conn, comm_ok=False, result=result)
# if we have first_available_file in our vars
# look up the files and use the first one we find as src
if 'first_available_file' in inject:
found = False
for fn in self.runner.module_vars.get('first_available_file'):
fn_orig = fn
fnt = template.template(self.runner.basedir, fn, inject)
fnd = utils.path_dwim(self.runner.basedir, fnt)
if not os.path.exists(fnd) and '_original_file' in inject:
fnd = utils.path_dwim_relative(inject['_original_file'], 'templates', fnt, self.runner.basedir, check=False)
if os.path.exists(fnd):
source = fnd
found = True
break
if not found:
result = dict(failed=True, msg="could not find src in first_available_file list")
return ReturnData(conn=conn, comm_ok=False, result=result)
else:
source = template.template(self.runner.basedir, source, inject)
if '_original_file' in inject:
source = utils.path_dwim_relative(inject['_original_file'], 'templates', source, self.runner.basedir)
else:
source = utils.path_dwim(self.runner.basedir, source)
if dest.endswith("/"):
base = os.path.basename(source)
dest = os.path.join(dest, base)
# template the source data locally & get ready to transfer
try:
resultant = template.template_from_file(self.runner.basedir, source, inject, vault_password=self.runner.vault_pass)
except Exception, e:
result = dict(failed=True, msg=str(e))
return ReturnData(conn=conn, comm_ok=False, result=result)
local_md5 = utils.md5s(resultant)
remote_md5 = self.runner._remote_md5(conn, tmp, dest)
if local_md5 != remote_md5:
# template is different from the remote value
# if showing diffs, we need to get the remote value
dest_contents = ''
if self.runner.diff:
# using persist_files to keep the temp directory around to avoid needing to grab another
dest_result = self.runner._execute_module(conn, tmp, 'slurp', "path=%s" % dest, inject=inject, persist_files=True)
if 'content' in dest_result.result:
dest_contents = dest_result.result['content']
if dest_result.result['encoding'] == 'base64':
dest_contents = base64.b64decode(dest_contents)
else:
raise Exception("unknown encoding, failed: %s" % dest_result.result)
xfered = self.runner._transfer_str(conn, tmp, 'source', resultant)
# fix file permissions when the copy is done as a different user
if self.runner.sudo and self.runner.sudo_user != 'root':
self.runner._low_level_exec_command(conn, "chmod a+r %s" % xfered, tmp)
# run the copy module
module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(source)))
if self.runner.noop_on_check(inject):
return ReturnData(conn=conn, comm_ok=True, result=dict(changed=True), diff=dict(before_header=dest, after_header=source, before=dest_contents, after=resultant))
else:
res = self.runner._execute_module(conn, tmp, 'copy', module_args, inject=inject, complex_args=complex_args)
if res.result.get('changed', False):
res.diff = dict(before=dest_contents, after=resultant)
return res
else:
return self.runner._execute_module(conn, tmp, 'file', module_args, inject=inject, complex_args=complex_args)
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_2234_4 |
crossvul-python_data_bad_3934_2 | from __future__ import print_function
import base64
import contextlib
import copy
import email.utils
import functools
import gzip
import hashlib
import httplib2
import os
import random
import re
import shutil
import six
import socket
import ssl
import struct
import sys
import threading
import time
import traceback
import zlib
from six.moves import http_client, queue
DUMMY_URL = "http://127.0.0.1:1"
DUMMY_HTTPS_URL = "https://127.0.0.1:2"
tls_dir = os.path.join(os.path.dirname(__file__), "tls")
CA_CERTS = os.path.join(tls_dir, "ca.pem")
CA_UNUSED_CERTS = os.path.join(tls_dir, "ca_unused.pem")
CLIENT_PEM = os.path.join(tls_dir, "client.pem")
CLIENT_ENCRYPTED_PEM = os.path.join(tls_dir, "client_encrypted.pem")
SERVER_PEM = os.path.join(tls_dir, "server.pem")
SERVER_CHAIN = os.path.join(tls_dir, "server_chain.pem")
@contextlib.contextmanager
def assert_raises(exc_type):
def _name(t):
return getattr(t, "__name__", None) or str(t)
if not isinstance(exc_type, tuple):
exc_type = (exc_type,)
names = ", ".join(map(_name, exc_type))
try:
yield
except exc_type:
pass
else:
assert False, "Expected exception(s) {0}".format(names)
class BufferedReader(object):
"""io.BufferedReader with \r\n support
"""
def __init__(self, sock):
self._buf = b""
self._end = False
self._newline = b"\r\n"
self._sock = sock
if isinstance(sock, bytes):
self._sock = None
self._buf = sock
def _fill(self, target=1, more=None, untilend=False):
if more:
target = len(self._buf) + more
while untilend or (len(self._buf) < target):
# crutch to enable HttpRequest.from_bytes
if self._sock is None:
chunk = b""
else:
chunk = self._sock.recv(8 << 10)
# print('!!! recv', chunk)
if not chunk:
self._end = True
if untilend:
return
else:
raise EOFError
self._buf += chunk
def peek(self, size):
self._fill(target=size)
return self._buf[:size]
def read(self, size):
self._fill(target=size)
chunk, self._buf = self._buf[:size], self._buf[size:]
return chunk
def readall(self):
self._fill(untilend=True)
chunk, self._buf = self._buf, b""
return chunk
def readline(self):
while True:
i = self._buf.find(self._newline)
if i >= 0:
break
self._fill(more=1)
inext = i + len(self._newline)
line, self._buf = self._buf[:inext], self._buf[inext:]
return line
def parse_http_message(kind, buf):
if buf._end:
return None
try:
start_line = buf.readline()
except EOFError:
return None
msg = kind()
msg.raw = start_line
if kind is HttpRequest:
assert re.match(
br".+ HTTP/\d\.\d\r\n$", start_line
), "Start line does not look like HTTP request: " + repr(start_line)
msg.method, msg.uri, msg.proto = start_line.rstrip().decode().split(" ", 2)
assert msg.proto.startswith("HTTP/"), repr(start_line)
elif kind is HttpResponse:
assert re.match(
br"^HTTP/\d\.\d \d+ .+\r\n$", start_line
), "Start line does not look like HTTP response: " + repr(start_line)
msg.proto, msg.status, msg.reason = start_line.rstrip().decode().split(" ", 2)
msg.status = int(msg.status)
assert msg.proto.startswith("HTTP/"), repr(start_line)
else:
raise Exception("Use HttpRequest or HttpResponse .from_{bytes,buffered}")
msg.version = msg.proto[5:]
while True:
line = buf.readline()
msg.raw += line
line = line.rstrip()
if not line:
break
t = line.decode().split(":", 1)
msg.headers[t[0].lower()] = t[1].lstrip()
content_length_string = msg.headers.get("content-length", "")
if content_length_string.isdigit():
content_length = int(content_length_string)
msg.body = msg.body_raw = buf.read(content_length)
elif msg.headers.get("transfer-encoding") == "chunked":
raise NotImplemented
elif msg.version == "1.0":
msg.body = msg.body_raw = buf.readall()
else:
msg.body = msg.body_raw = b""
msg.raw += msg.body_raw
return msg
class HttpMessage(object):
def __init__(self):
self.headers = {}
@classmethod
def from_bytes(cls, bs):
buf = BufferedReader(bs)
return parse_http_message(cls, buf)
@classmethod
def from_buffered(cls, buf):
return parse_http_message(cls, buf)
def __repr__(self):
return "{} {}".format(self.__class__, repr(vars(self)))
class HttpRequest(HttpMessage):
pass
class HttpResponse(HttpMessage):
pass
class MockResponse(six.BytesIO):
def __init__(self, body, **kwargs):
six.BytesIO.__init__(self, body)
self.headers = kwargs
def items(self):
return self.headers.items()
def iteritems(self):
return six.iteritems(self.headers)
class MockHTTPConnection(object):
"""This class is just a mock of httplib.HTTPConnection used for testing
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
):
self.host = host
self.port = port
self.timeout = timeout
self.log = ""
self.sock = None
def set_debuglevel(self, level):
pass
def connect(self):
"Connect to a host on a given port."
pass
def close(self):
pass
def request(self, method, request_uri, body, headers):
pass
def getresponse(self):
return MockResponse(b"the body", status="200")
class MockHTTPBadStatusConnection(object):
"""Mock of httplib.HTTPConnection that raises BadStatusLine.
"""
num_calls = 0
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
):
self.host = host
self.port = port
self.timeout = timeout
self.log = ""
self.sock = None
MockHTTPBadStatusConnection.num_calls = 0
def set_debuglevel(self, level):
pass
def connect(self):
pass
def close(self):
pass
def request(self, method, request_uri, body, headers):
pass
def getresponse(self):
MockHTTPBadStatusConnection.num_calls += 1
raise http_client.BadStatusLine("")
@contextlib.contextmanager
def server_socket(fun, request_count=1, timeout=5, scheme="", tls=None):
"""Base socket server for tests.
Likely you want to use server_request or other higher level helpers.
All arguments except fun can be passed to other server_* helpers.
:param fun: fun(client_sock, tick) called after successful accept().
:param request_count: test succeeds after exactly this number of requests, triggered by tick(request)
:param timeout: seconds.
:param scheme: affects yielded value
"" - build normal http/https URI.
string - build normal URI using supplied scheme.
None - yield (addr, port) tuple.
:param tls:
None (default) - plain HTTP.
True - HTTPS with reasonable defaults. Likely you want httplib2.Http(ca_certs=tests.CA_CERTS)
string - path to custom server cert+key PEM file.
callable - function(context, listener, skip_errors) -> ssl_wrapped_listener
"""
gresult = [None]
gcounter = [0]
tls_skip_errors = [
"TLSV1_ALERT_UNKNOWN_CA",
]
def tick(request):
gcounter[0] += 1
keep = True
keep &= gcounter[0] < request_count
if request is not None:
keep &= request.headers.get("connection", "").lower() != "close"
return keep
def server_socket_thread(srv):
try:
while gcounter[0] < request_count:
try:
client, _ = srv.accept()
except ssl.SSLError as e:
if e.reason in tls_skip_errors:
return
raise
try:
client.settimeout(timeout)
fun(client, tick)
finally:
try:
client.shutdown(socket.SHUT_RDWR)
except (IOError, socket.error):
pass
# FIXME: client.close() introduces connection reset by peer
# at least in other/connection_close test
# should not be a problem since socket would close upon garbage collection
if gcounter[0] > request_count:
gresult[0] = Exception(
"Request count expected={0} actual={1}".format(
request_count, gcounter[0]
)
)
except Exception as e:
# traceback.print_exc caused IOError: concurrent operation on sys.stderr.close() under setup.py test
print(traceback.format_exc(), file=sys.stderr)
gresult[0] = e
bind_hostname = "localhost"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_hostname, 0))
try:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error as ex:
print("non critical error on SO_REUSEADDR", ex)
server.listen(10)
server.settimeout(timeout)
server_port = server.getsockname()[1]
if tls is True:
tls = SERVER_CHAIN
if tls:
context = ssl_context()
if callable(tls):
context.load_cert_chain(SERVER_CHAIN)
server = tls(context, server, tls_skip_errors)
else:
context.load_cert_chain(tls)
server = context.wrap_socket(server, server_side=True)
if scheme == "":
scheme = "https" if tls else "http"
t = threading.Thread(target=server_socket_thread, args=(server,))
t.daemon = True
t.start()
if scheme is None:
yield (bind_hostname, server_port)
else:
yield u"{scheme}://{host}:{port}/".format(scheme=scheme, host=bind_hostname, port=server_port)
server.close()
t.join()
if gresult[0] is not None:
raise gresult[0]
def server_yield(fun, **kwargs):
q = queue.Queue(1)
g = fun(q.get)
def server_yield_socket_handler(sock, tick):
buf = BufferedReader(sock)
i = 0
while True:
request = HttpRequest.from_buffered(buf)
if request is None:
break
i += 1
request.client_sock = sock
request.number = i
q.put(request)
response = six.next(g)
sock.sendall(response)
request.client_sock = None
if not tick(request):
break
return server_socket(server_yield_socket_handler, **kwargs)
def server_request(request_handler, **kwargs):
def server_request_socket_handler(sock, tick):
buf = BufferedReader(sock)
i = 0
while True:
request = HttpRequest.from_buffered(buf)
if request is None:
break
# print("--- debug request\n" + request.raw.decode("ascii", "replace"))
i += 1
request.client_sock = sock
request.number = i
response = request_handler(request=request)
# print("--- debug response\n" + response.decode("ascii", "replace"))
sock.sendall(response)
request.client_sock = None
if not tick(request):
break
return server_socket(server_request_socket_handler, **kwargs)
def server_const_bytes(response_content, **kwargs):
return server_request(lambda request: response_content, **kwargs)
_http_kwargs = (
"proto",
"status",
"headers",
"body",
"add_content_length",
"add_date",
"add_etag",
"undefined_body_length",
)
def http_response_bytes(
proto="HTTP/1.1",
status="200 OK",
headers=None,
body=b"",
add_content_length=True,
add_date=False,
add_etag=False,
undefined_body_length=False,
**kwargs
):
if undefined_body_length:
add_content_length = False
if headers is None:
headers = {}
if add_content_length:
headers.setdefault("content-length", str(len(body)))
if add_date:
headers.setdefault("date", email.utils.formatdate())
if add_etag:
headers.setdefault("etag", '"{0}"'.format(hashlib.md5(body).hexdigest()))
header_string = "".join("{0}: {1}\r\n".format(k, v) for k, v in headers.items())
if (
not undefined_body_length
and proto != "HTTP/1.0"
and "content-length" not in headers
):
raise Exception(
"httplib2.tests.http_response_bytes: client could not figure response body length"
)
if str(status).isdigit():
status = "{} {}".format(status, http_client.responses[status])
response = (
"{proto} {status}\r\n{headers}\r\n".format(
proto=proto, status=status, headers=header_string
).encode()
+ body
)
return response
def make_http_reflect(**kwargs):
assert "body" not in kwargs, "make_http_reflect will overwrite response " "body"
def fun(request):
kw = copy.deepcopy(kwargs)
kw["body"] = request.raw
response = http_response_bytes(**kw)
return response
return fun
def server_route(routes, **kwargs):
response_404 = http_response_bytes(status="404 Not Found")
response_wildcard = routes.get("")
def handler(request):
target = routes.get(request.uri, response_wildcard) or response_404
if callable(target):
response = target(request=request)
else:
response = target
return response
return server_request(handler, **kwargs)
def server_const_http(**kwargs):
response_kwargs = {k: kwargs.pop(k) for k in dict(kwargs) if k in _http_kwargs}
response = http_response_bytes(**response_kwargs)
return server_const_bytes(response, **kwargs)
def server_list_http(responses, **kwargs):
i = iter(responses)
def handler(request):
return next(i)
kwargs.setdefault("request_count", len(responses))
return server_request(handler, **kwargs)
def server_reflect(**kwargs):
response_kwargs = {k: kwargs.pop(k) for k in dict(kwargs) if k in _http_kwargs}
http_handler = make_http_reflect(**response_kwargs)
return server_request(http_handler, **kwargs)
def http_parse_auth(s):
"""https://tools.ietf.org/html/rfc7235#section-2.1
"""
scheme, rest = s.split(" ", 1)
result = {}
while True:
m = httplib2.WWW_AUTH_RELAXED.search(rest)
if not m:
break
if len(m.groups()) == 3:
key, value, rest = m.groups()
result[key.lower()] = httplib2.UNQUOTE_PAIRS.sub(r"\1", value)
return result
def store_request_response(out):
def wrapper(fun):
@functools.wraps(fun)
def wrapped(request, *a, **kw):
response_bytes = fun(request, *a, **kw)
if out is not None:
response = HttpResponse.from_bytes(response_bytes)
out.append((request, response))
return response_bytes
return wrapped
return wrapper
def http_reflect_with_auth(
allow_scheme, allow_credentials, out_renew_nonce=None, out_requests=None
):
"""allow_scheme - 'basic', 'digest', etc allow_credentials - sequence of ('name', 'password') out_renew_nonce - None | [function]
Way to return nonce renew function to caller.
Kind of `out` parameter in some programming languages.
Allows to keep same signature for all handler builder functions.
out_requests - None | []
If set to list, every parsed request will be appended here.
"""
glastnc = [None]
gnextnonce = [None]
gserver_nonce = [gen_digest_nonce(salt=b"n")]
realm = "httplib2 test"
server_opaque = gen_digest_nonce(salt=b"o")
def renew_nonce():
if gnextnonce[0]:
assert False, (
"previous nextnonce was not used, probably bug in " "test code"
)
gnextnonce[0] = gen_digest_nonce()
return gserver_nonce[0], gnextnonce[0]
if out_renew_nonce:
out_renew_nonce[0] = renew_nonce
def deny(**kwargs):
nonce_stale = kwargs.pop("nonce_stale", False)
if nonce_stale:
kwargs.setdefault("body", b"nonce stale")
if allow_scheme == "basic":
authenticate = 'basic realm="{realm}"'.format(realm=realm)
elif allow_scheme == "digest":
authenticate = (
'digest realm="{realm}", qop="auth"'
+ ', nonce="{nonce}", opaque="{opaque}"'
+ (", stale=true" if nonce_stale else "")
).format(realm=realm, nonce=gserver_nonce[0], opaque=server_opaque)
else:
raise Exception("unknown allow_scheme={0}".format(allow_scheme))
deny_headers = {"www-authenticate": authenticate}
kwargs.setdefault("status", 401)
# supplied headers may overwrite generated ones
deny_headers.update(kwargs.get("headers", {}))
kwargs["headers"] = deny_headers
kwargs.setdefault("body", b"HTTP authorization required")
return http_response_bytes(**kwargs)
@store_request_response(out_requests)
def http_reflect_with_auth_handler(request):
auth_header = request.headers.get("authorization", "")
if not auth_header:
return deny()
if " " not in auth_header:
return http_response_bytes(
status=400, body=b"authorization header syntax error"
)
scheme, data = auth_header.split(" ", 1)
scheme = scheme.lower()
if scheme != allow_scheme:
return deny(body=b"must use different auth scheme")
if scheme == "basic":
decoded = base64.b64decode(data).decode()
username, password = decoded.split(":", 1)
if (username, password) in allow_credentials:
return make_http_reflect()(request)
else:
return deny(body=b"supplied credentials are not allowed")
elif scheme == "digest":
server_nonce_old = gserver_nonce[0]
nextnonce = gnextnonce[0]
if nextnonce:
# server decided to change nonce, in this case, guided by caller test code
gserver_nonce[0] = nextnonce
gnextnonce[0] = None
server_nonce_current = gserver_nonce[0]
auth_info = http_parse_auth(data)
client_cnonce = auth_info.get("cnonce", "")
client_nc = auth_info.get("nc", "")
client_nonce = auth_info.get("nonce", "")
client_opaque = auth_info.get("opaque", "")
client_qop = auth_info.get("qop", "auth").strip('"')
# TODO: auth_info.get('algorithm', 'md5')
hasher = hashlib.md5
# TODO: client_qop auth-int
ha2 = hasher(":".join((request.method, request.uri)).encode()).hexdigest()
if client_nonce != server_nonce_current:
if client_nonce == server_nonce_old:
return deny(nonce_stale=True)
return deny(body=b"invalid nonce")
if not client_nc:
return deny(body=b"auth-info nc missing")
if client_opaque != server_opaque:
return deny(
body="auth-info opaque mismatch expected={} actual={}".format(
server_opaque, client_opaque
).encode()
)
for allow_username, allow_password in allow_credentials:
ha1 = hasher(
":".join((allow_username, realm, allow_password)).encode()
).hexdigest()
allow_response = hasher(
":".join(
(ha1, client_nonce, client_nc, client_cnonce, client_qop, ha2)
).encode()
).hexdigest()
rspauth_ha2 = hasher(":{}".format(request.uri).encode()).hexdigest()
rspauth = hasher(
":".join(
(
ha1,
client_nonce,
client_nc,
client_cnonce,
client_qop,
rspauth_ha2,
)
).encode()
).hexdigest()
if auth_info.get("response", "") == allow_response:
# TODO: fix or remove doubtful comment
# do we need to save nc only on success?
glastnc[0] = client_nc
allow_headers = {
"authentication-info": " ".join(
(
'nextnonce="{}"'.format(nextnonce) if nextnonce else "",
"qop={}".format(client_qop),
'rspauth="{}"'.format(rspauth),
'cnonce="{}"'.format(client_cnonce),
"nc={}".format(client_nc),
)
).strip()
}
return make_http_reflect(headers=allow_headers)(request)
return deny(body=b"supplied credentials are not allowed")
else:
return http_response_bytes(
status=400,
body="unknown authorization scheme={0}".format(scheme).encode(),
)
return http_reflect_with_auth_handler
def get_cache_path():
default = "./_httplib2_test_cache"
path = os.environ.get("httplib2_test_cache_path") or default
if os.path.exists(path):
shutil.rmtree(path)
return path
def gen_digest_nonce(salt=b""):
t = struct.pack(">Q", int(time.time() * 1e9))
return base64.b64encode(t + b":" + hashlib.sha1(t + salt).digest()).decode()
def gen_password():
length = random.randint(8, 64)
return "".join(six.unichr(random.randint(0, 127)) for _ in range(length))
def gzip_compress(bs):
# gzipobj = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
# result = gzipobj.compress(text) + gzipobj.flush()
buf = six.BytesIO()
gf = gzip.GzipFile(fileobj=buf, mode="wb", compresslevel=6)
gf.write(bs)
gf.close()
return buf.getvalue()
def gzip_decompress(bs):
return zlib.decompress(bs, zlib.MAX_WBITS | 16)
def deflate_compress(bs):
do = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
return do.compress(bs) + do.flush()
def deflate_decompress(bs):
return zlib.decompress(bs, -zlib.MAX_WBITS)
def ssl_context(protocol=None):
"""Workaround for old SSLContext() required protocol argument.
"""
if sys.version_info < (3, 5, 3):
return ssl.SSLContext(ssl.PROTOCOL_SSLv23)
return ssl.SSLContext()
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_3934_2 |
crossvul-python_data_good_4621_2 | import re
from pathlib import Path
from urllib.parse import unquote
import base64
import json, os, requests, time, pytz, pymongo
from shutil import rmtree
from requests.exceptions import ConnectionError
from os.path import join, exists
from django.shortcuts import render
from django.core.serializers import serialize
from django.http import HttpResponse
from django.forms.models import model_to_dict
from django.utils import timezone
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from subprocess import Popen, PIPE
from gerapy import get_logger
from gerapy.server.core.response import JsonResponse
from gerapy.cmd.init import PROJECTS_FOLDER
from gerapy.server.server.settings import TIME_ZONE
from gerapy.server.core.models import Client, Project, Deploy, Monitor, Task
from gerapy.server.core.build import build_project, find_egg
from gerapy.server.core.utils import IGNORES, scrapyd_url, log_url, get_tree, get_scrapyd, process_html, bytes2str, \
clients_of_task, get_job_id
from django_apscheduler.models import DjangoJob, DjangoJobExecution
from django.core.files.storage import FileSystemStorage
import zipfile
logger = get_logger(__name__)
@api_view(['GET'])
# @permission_classes([IsAuthenticated])
def index(request):
"""
render index page
:param request: request object
:return: page
"""
return render(request, 'index.html')
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def index_status(request):
"""
index statistics
:param request: request object
:return: json
"""
if request.method == 'GET':
clients = Client.objects.all()
data = {
'success': 0,
'error': 0,
'project': 0,
}
# clients info
for client in clients:
try:
requests.get(scrapyd_url(client.ip, client.port), timeout=1)
data['success'] += 1
except ConnectionError:
data['error'] += 1
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
files = os.listdir(path)
# projects info
for file in files:
if os.path.isdir(join(path, file)) and not file in IGNORES:
data['project'] += 1
return JsonResponse(data)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def client_index(request):
"""
get client list
:param request: request object
:return: client list
"""
return HttpResponse(serialize('json', Client.objects.order_by('-id')))
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def client_info(request, client_id):
"""
get client info
:param request: request object
:param id: client id
:return: json
"""
if request.method == 'GET':
return JsonResponse(model_to_dict(Client.objects.get(id=client_id)))
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def client_status(request, client_id):
"""
get client status
:param request: request object
:param client_id: client id
:return: json
"""
if request.method == 'GET':
# get client object
client = Client.objects.get(id=client_id)
requests.get(scrapyd_url(client.ip, client.port), timeout=3)
return JsonResponse({'result': '1'})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def client_update(request, client_id):
"""
update client info
:param request: request object
:param client_id: client id
:return: json
"""
if request.method == 'POST':
client = Client.objects.filter(id=client_id)
data = json.loads(request.body)
client.update(**data)
return JsonResponse(model_to_dict(Client.objects.get(id=client_id)))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def client_create(request):
"""
create a client
:param request: request object
:return: json
"""
if request.method == 'POST':
data = json.loads(request.body)
client = Client.objects.create(**data)
return JsonResponse(model_to_dict(client))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def client_remove(request, client_id):
"""
remove a client
:param request: request object
:param client_id: client id
:return: json
"""
if request.method == 'POST':
client = Client.objects.get(id=client_id)
# delete deploy
Deploy.objects.filter(client=client).delete()
# delete client
Client.objects.filter(id=client_id).delete()
return JsonResponse({'result': '1'})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def spider_list(request, client_id, project_name):
"""
get spider list from one client
:param request: request Object
:param client_id: client id
:param project_name: project name
:return: json
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
spiders = scrapyd.list_spiders(project_name)
spiders = [{'name': spider, 'id': index + 1} for index, spider in enumerate(spiders)]
return JsonResponse(spiders)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def spider_start(request, client_id, project_name, spider_name):
"""
start a spider
:param request: request object
:param client_id: client id
:param project_name: project name
:param spider_name: spider name
:return: json
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
job = scrapyd.schedule(project_name, spider_name)
return JsonResponse({'job': job})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def project_list(request, client_id):
"""
project deployed list on one client
:param request: request object
:param client_id: client id
:return: json
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
projects = scrapyd.list_projects()
return JsonResponse(projects)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def project_index(request):
"""
project index list
:param request: request object
:return: json
"""
if request.method == 'GET':
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
files = os.listdir(path)
project_list = []
for file in files:
if os.path.isdir(join(path, file)) and not file in IGNORES:
project_list.append({'name': file})
return JsonResponse(project_list)
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def project_configure(request, project_name):
"""
get configuration
:param request: request object
:param project_name: project name
:return: json
"""
# get configuration
if request.method == 'GET':
project = Project.objects.get(name=project_name)
project = model_to_dict(project)
project['configuration'] = json.loads(project['configuration']) if project['configuration'] else None
return JsonResponse(project)
# update configuration
elif request.method == 'POST':
project = Project.objects.filter(name=project_name)
data = json.loads(request.body)
configuration = json.dumps(data.get('configuration'), ensure_ascii=False)
project.update(**{'configuration': configuration})
# for safe protection
project_name = re.sub('[\!\@\#\$\;\&\*\~\"\'\{\}\]\[\-\+\%\^]+', '', project_name)
# execute generate cmd
cmd = ' '.join(['gerapy', 'generate', project_name])
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())
if not stderr:
return JsonResponse({'status': '1'})
else:
return JsonResponse({'status': '0', 'message': stderr})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def project_tree(request, project_name):
"""
get file tree of project
:param request: request object
:param project_name: project name
:return: json of tree
"""
if request.method == 'GET':
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
# get tree data
tree = get_tree(join(path, project_name))
return JsonResponse(tree)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_create(request):
"""
create a configurable project
:param request: request object
:return: json
"""
if request.method == 'POST':
data = json.loads(request.body)
data['configurable'] = 1
project, result = Project.objects.update_or_create(**data)
# generate a single project folder
path = join(os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER)), data['name'])
os.mkdir(path)
return JsonResponse(model_to_dict(project))
@api_view(['POST'])
# @permission_classes([IsAuthenticated])
def project_upload(request):
"""
upload project
:param request: request object
:return: json
"""
if request.method == 'POST':
file = request.FILES['file']
file_name = file.name
fs = FileSystemStorage(PROJECTS_FOLDER)
zip_file_name = fs.save(file_name, file)
logger.debug('zip file name %s', zip_file_name)
# extract zip file
with zipfile.ZipFile(join(PROJECTS_FOLDER, zip_file_name), 'r') as zip_ref:
zip_ref.extractall(PROJECTS_FOLDER)
logger.debug('extracted files to %s', PROJECTS_FOLDER)
return JsonResponse({'status': True})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_clone(request):
"""
clone project from github
:param request: request object
:return: json
"""
if request.method == 'POST':
data = json.loads(request.body)
address = data.get('address')
if not address.startswith('http'):
return JsonResponse({'status': False})
address = address + '.git' if not address.endswith('.git') else address
cmd = 'git clone {address} {target}'.format(address=address, target=join(PROJECTS_FOLDER, Path(address).stem))
logger.debug('clone cmd %s', cmd)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())
logger.debug('clone run result %s', stdout)
if stderr: logger.error(stderr)
return JsonResponse({'status': True}) if not stderr else JsonResponse({'status': False})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_remove(request, project_name):
"""
remove project from disk and db
:param request: request object
:param project_name: project name
:return: result of remove
"""
if request.method == 'POST':
# delete deployments
project = Project.objects.get(name=project_name)
Deploy.objects.filter(project=project).delete()
# delete project
result = Project.objects.filter(name=project_name).delete()
# get project path
path = join(os.path.abspath(os.getcwd()), PROJECTS_FOLDER)
project_path = join(path, project_name)
# delete project file tree
if exists(project_path):
rmtree(project_path)
return JsonResponse({'result': result})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def project_version(request, client_id, project_name):
"""
get project deploy version
:param request: request object
:param client_id: client id
:param project_name: project name
:return: deploy version of project
"""
if request.method == 'GET':
# get client and project model
client = Client.objects.get(id=client_id)
project = Project.objects.get(name=project_name)
scrapyd = get_scrapyd(client)
# if deploy info exists in db, return it
if Deploy.objects.filter(client=client, project=project):
deploy = Deploy.objects.get(client=client, project=project)
# if deploy info does not exists in db, create deploy info
else:
try:
versions = scrapyd.list_versions(project_name)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'}, status=500)
if len(versions) > 0:
version = versions[-1]
deployed_at = timezone.datetime.fromtimestamp(int(version), tz=pytz.timezone(TIME_ZONE))
else:
deployed_at = None
deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at)
# return deploy json info
return JsonResponse(model_to_dict(deploy))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_deploy(request, client_id, project_name):
"""
deploy project operation
:param request: request object
:param client_id: client id
:param project_name: project name
:return: json of deploy result
"""
if request.method == 'POST':
# get project folder
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
project_path = join(path, project_name)
# find egg file
egg = find_egg(project_path)
if not egg:
return JsonResponse({'message': 'egg not found'}, status=500)
egg_file = open(join(project_path, egg), 'rb')
# get client and project model
client = Client.objects.get(id=client_id)
project = Project.objects.get(name=project_name)
# execute deploy operation
scrapyd = get_scrapyd(client)
scrapyd.add_version(project_name, int(time.time()), egg_file.read())
# update deploy info
deployed_at = timezone.now()
Deploy.objects.filter(client=client, project=project).delete()
deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at,
description=project.description)
return JsonResponse(model_to_dict(deploy))
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def project_build(request, project_name):
"""
get build info or execute build operation
:param request: request object
:param project_name: project name
:return: json
"""
# get project folder
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
project_path = join(path, project_name)
# get build version
if request.method == 'GET':
egg = find_egg(project_path)
# if built, save or update project to db
if egg:
built_at = timezone.datetime.fromtimestamp(os.path.getmtime(join(project_path, egg)),
tz=pytz.timezone(TIME_ZONE))
if not Project.objects.filter(name=project_name):
Project(name=project_name, built_at=built_at, egg=egg).save()
model = Project.objects.get(name=project_name)
else:
model = Project.objects.get(name=project_name)
model.built_at = built_at
model.egg = egg
model.save()
# if not built, just save project name to db
else:
if not Project.objects.filter(name=project_name):
Project(name=project_name).save()
model = Project.objects.get(name=project_name)
# transfer model to dict then dumps it to json
data = model_to_dict(model)
return JsonResponse(data)
# build operation manually by clicking button
elif request.method == 'POST':
data = json.loads(request.body)
description = data['description']
build_project(project_name)
egg = find_egg(project_path)
if not egg:
return JsonResponse({'message': 'egg not found'}, status=500)
# update built_at info
built_at = timezone.now()
# if project does not exists in db, create it
if not Project.objects.filter(name=project_name):
Project(name=project_name, description=description, built_at=built_at, egg=egg).save()
model = Project.objects.get(name=project_name)
# if project exists, update egg, description, built_at info
else:
model = Project.objects.get(name=project_name)
model.built_at = built_at
model.egg = egg
model.description = description
model.save()
# transfer model to dict then dumps it to json
data = model_to_dict(model)
return JsonResponse(data)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_parse(request, project_name):
"""
parse project
:param request: request object
:param project_name: project name
:return: requests, items, response
"""
if request.method == 'POST':
project_path = join(PROJECTS_FOLDER, project_name)
data = json.loads(request.body)
logger.debug('post data %s', data)
spider_name = data.get('spider')
args = {
'start': data.get('start', False),
'method': data.get('method', 'GET'),
'url': data.get('url'),
'callback': data.get('callback'),
'cookies': "'" + json.dumps(data.get('cookies', {}), ensure_ascii=False) + "'",
'headers': "'" + json.dumps(data.get('headers', {}), ensure_ascii=False) + "'",
'meta': "'" + json.dumps(data.get('meta', {}), ensure_ascii=False) + "'",
'dont_filter': data.get('dont_filter', False),
'priority': data.get('priority', 0),
}
# set request body
body = data.get('body', '')
if args.get('method').lower() != 'get':
args['body'] = "'" + json.dumps(body, ensure_ascii=False) + "'"
args_cmd = ' '.join(
['--{arg} {value}'.format(arg=arg, value=value) for arg, value in args.items()])
logger.debug('args cmd %s', args_cmd)
cmd = 'gerapy parse {args_cmd} {project_path} {spider_name}'.format(
args_cmd=args_cmd,
project_path=project_path,
spider_name=spider_name
)
logger.debug('parse cmd %s', cmd)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())
logger.debug('stdout %s, stderr %s', stdout, stderr)
if not stderr:
return JsonResponse({'status': True, 'result': json.loads(stdout)})
else:
return JsonResponse({'status': False, 'message': stderr})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_read(request):
"""
get content of project file
:param request: request object
:return: file content
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['label'])
# binary file
with open(path, 'rb') as f:
return HttpResponse(f.read().decode('utf-8'))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_update(request):
"""
update project file
:param request: request object
:return: result of update
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['label'])
code = data['code']
with open(path, 'w', encoding='utf-8') as f:
f.write(code)
return JsonResponse({'result': '1'})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_create(request):
"""
create project file
:param request: request object
:return: result of create
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['name'])
open(path, 'w', encoding='utf-8').close()
return JsonResponse({'result': '1'})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_delete(request):
"""
delete project file
:param request: request object
:return: result of delete
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['label'])
result = os.remove(path)
return JsonResponse({'result': result})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_rename(request):
"""
rename file name
:param request: request object
:return: result of rename
"""
if request.method == 'POST':
data = json.loads(request.body)
pre = join(data['path'], data['pre'])
new = join(data['path'], data['new'])
os.rename(pre, new)
return JsonResponse({'result': '1'})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def job_list(request, client_id, project_name):
"""
get job list of project from one client
:param request: request object
:param client_id: client id
:param project_name: project name
:return: list of jobs
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
result = scrapyd.list_jobs(project_name)
jobs = []
statuses = ['pending', 'running', 'finished']
for status in statuses:
for job in result.get(status):
job['status'] = status
jobs.append(job)
return JsonResponse(jobs)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def job_log(request, client_id, project_name, spider_name, job_id):
"""
get log of jog
:param request: request object
:param client_id: client id
:param project_name: project name
:param spider_name: spider name
:param job_id: job id
:return: log of job
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
# get log url
url = log_url(client.ip, client.port, project_name, spider_name, job_id)
# get last 1000 bytes of log
response = requests.get(url, timeout=5, headers={
'Range': 'bytes=-1000'
}, auth=(client.username, client.password) if client.auth else None)
# Get encoding
encoding = response.apparent_encoding
# log not found
if response.status_code == 404:
return JsonResponse({'message': 'Log Not Found'}, status=404)
# bytes to string
text = response.content.decode(encoding, errors='replace')
return HttpResponse(text)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def job_cancel(request, client_id, project_name, job_id):
"""
cancel a job
:param request: request object
:param client_id: client id
:param project_name: project name
:param job_id: job id
:return: json of cancel
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
result = scrapyd.cancel(project_name, job_id)
return JsonResponse(result)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def del_version(request, client_id, project, version):
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
result = scrapyd.delete_version(project=project, version=version)
return JsonResponse(result)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def del_project(request, client_id, project):
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
result = scrapyd.delete_project(project=project)
return JsonResponse(result)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_db_list(request):
"""
get monitor db list
:param request: request object
:return: json of db list
"""
if request.method == 'POST':
data = json.loads(request.body)
url = data['url']
type = data['type']
if type == 'MongoDB':
client = pymongo.MongoClient(url)
dbs = client.list_database_names()
return JsonResponse(dbs)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_collection_list(request):
"""
get monitor collection list
:param request: request object
:return: json of collection list
"""
if request.method == 'POST':
data = json.loads(request.body)
url = data['url']
db = data['db']
type = data['type']
if type == 'MongoDB':
client = pymongo.MongoClient(url)
db = client[db]
collections = db.collection_names()
return JsonResponse(collections)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_create(request):
"""
create a monitor
:param request: request object
:return: json of create
"""
if request.method == 'POST':
data = json.loads(request.body)
data = data['form']
data['configuration'] = json.dumps(data['configuration'], ensure_ascii=False)
monitor = Monitor.objects.create(**data)
return JsonResponse(model_to_dict(monitor))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def task_create(request):
"""
add task
:param request: request object
:return: Bool
"""
if request.method == 'POST':
data = json.loads(request.body)
task = Task.objects.create(clients=json.dumps(data.get('clients'), ensure_ascii=False),
project=data.get('project'),
name=data.get('name'),
spider=data.get('spider'),
trigger=data.get('trigger'),
configuration=json.dumps(data.get('configuration'), ensure_ascii=False),
modified=1)
return JsonResponse({'result': '1', 'data': model_to_dict(task)})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def task_update(request, task_id):
"""
update task info
:param request: request object
:param task_id: task id
:return: json
"""
if request.method == 'POST':
task = Task.objects.filter(id=task_id)
data = json.loads(request.body)
data['clients'] = json.dumps(data.get('clients'), ensure_ascii=False)
data['configuration'] = json.dumps(data.get('configuration'), ensure_ascii=False)
data['modified'] = 1
task.update(**data)
return JsonResponse(model_to_dict(Task.objects.get(id=task_id)))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def task_remove(request, task_id):
"""
remove task by task_id
:param request:
:return:
"""
if request.method == 'POST':
# delete job from DjangoJob
task = Task.objects.get(id=task_id)
clients = clients_of_task(task)
for client in clients:
job_id = get_job_id(client, task)
DjangoJob.objects.filter(name=job_id).delete()
# delete task
Task.objects.filter(id=task_id).delete()
return JsonResponse({'result': '1'})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def task_info(request, task_id):
"""
get task info
:param request: request object
:param task_id: task id
:return: json
"""
if request.method == 'GET':
task = Task.objects.get(id=task_id)
data = model_to_dict(task)
data['clients'] = json.loads(data.get('clients'))
data['configuration'] = json.loads(data.get('configuration'))
return JsonResponse({'data': data})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def task_index(request):
"""
get all tasks
:param request:
:return:
"""
if request.method == 'GET':
tasks = Task.objects.values()
return JsonResponse({'result': '1', 'data': tasks})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def task_status(request, task_id):
"""
get task status info
:param request: request object
:param task_id: task id
:return:
"""
if request.method == 'GET':
result = []
task = Task.objects.get(id=task_id)
clients = clients_of_task(task)
for client in clients:
job_id = get_job_id(client, task)
jobs = DjangoJob.objects.filter(name=job_id)
logger.debug('jobs from djangojob %s', jobs)
# if job does not exist, for date mode exceed time
if not jobs: continue
job = DjangoJob.objects.get(name=job_id)
executions = serialize('json', DjangoJobExecution.objects.filter(job=job))
result.append({
'client': model_to_dict(client),
'next': job.next_run_time,
'executions': json.loads(executions)
})
return JsonResponse({'data': result})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def render_html(request):
"""
render html with url
:param request:
:return:
"""
if request.method == 'GET':
url = request.GET.get('url')
url = unquote(base64.b64decode(url).decode('utf-8'))
js = request.GET.get('js', 0)
script = request.GET.get('script')
response = requests.get(url, timeout=5)
response.encoding = response.apparent_encoding
html = process_html(response.text)
return HttpResponse(html)
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_4621_2 |
crossvul-python_data_bad_2234_0 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Copyright (c), Michael DeHaan <michael.dehaan@gmail.com>, 2012-2013
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# == BEGIN DYNAMICALLY INSERTED CODE ==
MODULE_ARGS = "<<INCLUDE_ANSIBLE_MODULE_ARGS>>"
MODULE_COMPLEX_ARGS = "<<INCLUDE_ANSIBLE_MODULE_COMPLEX_ARGS>>"
BOOLEANS_TRUE = ['yes', 'on', '1', 'true', 1]
BOOLEANS_FALSE = ['no', 'off', '0', 'false', 0]
BOOLEANS = BOOLEANS_TRUE + BOOLEANS_FALSE
# ansible modules can be written in any language. To simplify
# development of Python modules, the functions available here
# can be inserted in any module source automatically by including
# #<<INCLUDE_ANSIBLE_MODULE_COMMON>> on a blank line by itself inside
# of an ansible module. The source of this common code lives
# in lib/ansible/module_common.py
import locale
import os
import re
import pipes
import shlex
import subprocess
import sys
import syslog
import types
import time
import shutil
import stat
import tempfile
import traceback
import grp
import pwd
import platform
import errno
import tempfile
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
sys.stderr.write('Error: ansible requires a json module, none found!')
sys.exit(1)
except SyntaxError:
sys.stderr.write('SyntaxError: probably due to json and python being for different versions')
sys.exit(1)
HAVE_SELINUX=False
try:
import selinux
HAVE_SELINUX=True
except ImportError:
pass
HAVE_HASHLIB=False
try:
from hashlib import md5 as _md5
HAVE_HASHLIB=True
except ImportError:
from md5 import md5 as _md5
try:
from hashlib import sha256 as _sha256
except ImportError:
pass
try:
from systemd import journal
has_journal = True
except ImportError:
import syslog
has_journal = False
FILE_COMMON_ARGUMENTS=dict(
src = dict(),
mode = dict(),
owner = dict(),
group = dict(),
seuser = dict(),
serole = dict(),
selevel = dict(),
setype = dict(),
# not taken by the file module, but other modules call file so it must ignore them.
content = dict(),
backup = dict(),
force = dict(),
remote_src = dict(), # used by assemble
delimiter = dict(), # used by assemble
directory_mode = dict(), # used by copy
)
def get_platform():
''' what's the platform? example: Linux is a platform. '''
return platform.system()
def get_distribution():
''' return the distribution name '''
if platform.system() == 'Linux':
try:
distribution = platform.linux_distribution()[0].capitalize()
if not distribution and os.path.isfile('/etc/system-release'):
distribution = platform.linux_distribution(supported_dists=['system'])[0].capitalize()
if 'Amazon' in distribution:
distribution = 'Amazon'
else:
distribution = 'OtherLinux'
except:
# FIXME: MethodMissing, I assume?
distribution = platform.dist()[0].capitalize()
else:
distribution = None
return distribution
def load_platform_subclass(cls, *args, **kwargs):
'''
used by modules like User to have different implementations based on detected platform. See User
module for an example.
'''
this_platform = get_platform()
distribution = get_distribution()
subclass = None
# get the most specific superclass for this platform
if distribution is not None:
for sc in cls.__subclasses__():
if sc.distribution is not None and sc.distribution == distribution and sc.platform == this_platform:
subclass = sc
if subclass is None:
for sc in cls.__subclasses__():
if sc.platform == this_platform and sc.distribution is None:
subclass = sc
if subclass is None:
subclass = cls
return super(cls, subclass).__new__(subclass)
class AnsibleModule(object):
def __init__(self, argument_spec, bypass_checks=False, no_log=False,
check_invalid_arguments=True, mutually_exclusive=None, required_together=None,
required_one_of=None, add_file_common_args=False, supports_check_mode=False):
'''
common code for quickly building an ansible module in Python
(although you can write modules in anything that can return JSON)
see library/* for examples
'''
self.argument_spec = argument_spec
self.supports_check_mode = supports_check_mode
self.check_mode = False
self.no_log = no_log
self.cleanup_files = []
self.aliases = {}
if add_file_common_args:
for k, v in FILE_COMMON_ARGUMENTS.iteritems():
if k not in self.argument_spec:
self.argument_spec[k] = v
# check the locale as set by the current environment, and
# reset to LANG=C if it's an invalid/unavailable locale
self._check_locale()
(self.params, self.args) = self._load_params()
self._legal_inputs = ['CHECKMODE', 'NO_LOG']
self.aliases = self._handle_aliases()
if check_invalid_arguments:
self._check_invalid_arguments()
self._check_for_check_mode()
self._check_for_no_log()
# check exclusive early
if not bypass_checks:
self._check_mutually_exclusive(mutually_exclusive)
self._set_defaults(pre=True)
if not bypass_checks:
self._check_required_arguments()
self._check_argument_values()
self._check_argument_types()
self._check_required_together(required_together)
self._check_required_one_of(required_one_of)
self._set_defaults(pre=False)
if not self.no_log:
self._log_invocation()
# finally, make sure we're in a sane working dir
self._set_cwd()
def load_file_common_arguments(self, params):
'''
many modules deal with files, this encapsulates common
options that the file module accepts such that it is directly
available to all modules and they can share code.
'''
path = params.get('path', params.get('dest', None))
if path is None:
return {}
else:
path = os.path.expanduser(path)
mode = params.get('mode', None)
owner = params.get('owner', None)
group = params.get('group', None)
# selinux related options
seuser = params.get('seuser', None)
serole = params.get('serole', None)
setype = params.get('setype', None)
selevel = params.get('selevel', None)
secontext = [seuser, serole, setype]
if self.selinux_mls_enabled():
secontext.append(selevel)
default_secontext = self.selinux_default_context(path)
for i in range(len(default_secontext)):
if i is not None and secontext[i] == '_default':
secontext[i] = default_secontext[i]
return dict(
path=path, mode=mode, owner=owner, group=group,
seuser=seuser, serole=serole, setype=setype,
selevel=selevel, secontext=secontext,
)
# Detect whether using selinux that is MLS-aware.
# While this means you can set the level/range with
# selinux.lsetfilecon(), it may or may not mean that you
# will get the selevel as part of the context returned
# by selinux.lgetfilecon().
def selinux_mls_enabled(self):
if not HAVE_SELINUX:
return False
if selinux.is_selinux_mls_enabled() == 1:
return True
else:
return False
def selinux_enabled(self):
if not HAVE_SELINUX:
seenabled = self.get_bin_path('selinuxenabled')
if seenabled is not None:
(rc,out,err) = self.run_command(seenabled)
if rc == 0:
self.fail_json(msg="Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!")
return False
if selinux.is_selinux_enabled() == 1:
return True
else:
return False
# Determine whether we need a placeholder for selevel/mls
def selinux_initial_context(self):
context = [None, None, None]
if self.selinux_mls_enabled():
context.append(None)
return context
def _to_filesystem_str(self, path):
'''Returns filesystem path as a str, if it wasn't already.
Used in selinux interactions because it cannot accept unicode
instances, and specifying complex args in a playbook leaves
you with unicode instances. This method currently assumes
that your filesystem encoding is UTF-8.
'''
if isinstance(path, unicode):
path = path.encode("utf-8")
return path
# If selinux fails to find a default, return an array of None
def selinux_default_context(self, path, mode=0):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.matchpathcon(self._to_filesystem_str(path), mode)
except OSError:
return context
if ret[0] == -1:
return context
# Limit split to 4 because the selevel, the last in the list,
# may contain ':' characters
context = ret[1].split(':', 3)
return context
def selinux_context(self, path):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.lgetfilecon_raw(self._to_filesystem_str(path))
except OSError, e:
if e.errno == errno.ENOENT:
self.fail_json(path=path, msg='path %s does not exist' % path)
else:
self.fail_json(path=path, msg='failed to retrieve selinux context')
if ret[0] == -1:
return context
# Limit split to 4 because the selevel, the last in the list,
# may contain ':' characters
context = ret[1].split(':', 3)
return context
def user_and_group(self, filename):
filename = os.path.expanduser(filename)
st = os.lstat(filename)
uid = st.st_uid
gid = st.st_gid
return (uid, gid)
def find_mount_point(self, path):
path = os.path.abspath(os.path.expanduser(os.path.expandvars(path)))
while not os.path.ismount(path):
path = os.path.dirname(path)
return path
def is_nfs_path(self, path):
"""
Returns a tuple containing (True, selinux_context) if the given path
is on a NFS mount point, otherwise the return will be (False, None).
"""
try:
f = open('/proc/mounts', 'r')
mount_data = f.readlines()
f.close()
except:
return (False, None)
path_mount_point = self.find_mount_point(path)
for line in mount_data:
(device, mount_point, fstype, options, rest) = line.split(' ', 4)
if path_mount_point == mount_point and 'nfs' in fstype:
nfs_context = self.selinux_context(path_mount_point)
return (True, nfs_context)
return (False, None)
def set_default_selinux_context(self, path, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
context = self.selinux_default_context(path)
return self.set_context_if_different(path, context, False)
def set_context_if_different(self, path, context, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
cur_context = self.selinux_context(path)
new_context = list(cur_context)
# Iterate over the current context instead of the
# argument context, which may have selevel.
(is_nfs, nfs_context) = self.is_nfs_path(path)
if is_nfs:
new_context = nfs_context
else:
for i in range(len(cur_context)):
if len(context) > i:
if context[i] is not None and context[i] != cur_context[i]:
new_context[i] = context[i]
if context[i] is None:
new_context[i] = cur_context[i]
if cur_context != new_context:
try:
if self.check_mode:
return True
rc = selinux.lsetfilecon(self._to_filesystem_str(path),
str(':'.join(new_context)))
except OSError:
self.fail_json(path=path, msg='invalid selinux context', new_context=new_context, cur_context=cur_context, input_was=context)
if rc != 0:
self.fail_json(path=path, msg='set selinux context failed')
changed = True
return changed
def set_owner_if_different(self, path, owner, changed):
path = os.path.expanduser(path)
if owner is None:
return changed
orig_uid, orig_gid = self.user_and_group(path)
try:
uid = int(owner)
except ValueError:
try:
uid = pwd.getpwnam(owner).pw_uid
except KeyError:
self.fail_json(path=path, msg='chown failed: failed to look up user %s' % owner)
if orig_uid != uid:
if self.check_mode:
return True
try:
os.lchown(path, uid, -1)
except OSError:
self.fail_json(path=path, msg='chown failed')
changed = True
return changed
def set_group_if_different(self, path, group, changed):
path = os.path.expanduser(path)
if group is None:
return changed
orig_uid, orig_gid = self.user_and_group(path)
try:
gid = int(group)
except ValueError:
try:
gid = grp.getgrnam(group).gr_gid
except KeyError:
self.fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group)
if orig_gid != gid:
if self.check_mode:
return True
try:
os.lchown(path, -1, gid)
except OSError:
self.fail_json(path=path, msg='chgrp failed')
changed = True
return changed
def set_mode_if_different(self, path, mode, changed):
path = os.path.expanduser(path)
if mode is None:
return changed
try:
# FIXME: support English modes
if not isinstance(mode, int):
mode = int(mode, 8)
except Exception, e:
self.fail_json(path=path, msg='mode needs to be something octalish', details=str(e))
st = os.lstat(path)
prev_mode = stat.S_IMODE(st[stat.ST_MODE])
if prev_mode != mode:
if self.check_mode:
return True
# FIXME: comparison against string above will cause this to be executed
# every time
try:
if 'lchmod' in dir(os):
os.lchmod(path, mode)
else:
os.chmod(path, mode)
except OSError, e:
if os.path.islink(path) and e.errno == errno.EPERM: # Can't set mode on symbolic links
pass
elif e.errno == errno.ENOENT: # Can't set mode on broken symbolic links
pass
else:
raise e
except Exception, e:
self.fail_json(path=path, msg='chmod failed', details=str(e))
st = os.lstat(path)
new_mode = stat.S_IMODE(st[stat.ST_MODE])
if new_mode != prev_mode:
changed = True
return changed
def set_fs_attributes_if_different(self, file_args, changed):
# set modes owners and context as needed
changed = self.set_context_if_different(
file_args['path'], file_args['secontext'], changed
)
changed = self.set_owner_if_different(
file_args['path'], file_args['owner'], changed
)
changed = self.set_group_if_different(
file_args['path'], file_args['group'], changed
)
changed = self.set_mode_if_different(
file_args['path'], file_args['mode'], changed
)
return changed
def set_directory_attributes_if_different(self, file_args, changed):
return self.set_fs_attributes_if_different(file_args, changed)
def set_file_attributes_if_different(self, file_args, changed):
return self.set_fs_attributes_if_different(file_args, changed)
def add_path_info(self, kwargs):
'''
for results that are files, supplement the info about the file
in the return path with stats about the file path.
'''
path = kwargs.get('path', kwargs.get('dest', None))
if path is None:
return kwargs
if os.path.exists(path):
(uid, gid) = self.user_and_group(path)
kwargs['uid'] = uid
kwargs['gid'] = gid
try:
user = pwd.getpwuid(uid)[0]
except KeyError:
user = str(uid)
try:
group = grp.getgrgid(gid)[0]
except KeyError:
group = str(gid)
kwargs['owner'] = user
kwargs['group'] = group
st = os.lstat(path)
kwargs['mode'] = oct(stat.S_IMODE(st[stat.ST_MODE]))
# secontext not yet supported
if os.path.islink(path):
kwargs['state'] = 'link'
elif os.path.isdir(path):
kwargs['state'] = 'directory'
elif os.stat(path).st_nlink > 1:
kwargs['state'] = 'hard'
else:
kwargs['state'] = 'file'
if HAVE_SELINUX and self.selinux_enabled():
kwargs['secontext'] = ':'.join(self.selinux_context(path))
kwargs['size'] = st[stat.ST_SIZE]
else:
kwargs['state'] = 'absent'
return kwargs
def _check_locale(self):
'''
Uses the locale module to test the currently set locale
(per the LANG and LC_CTYPE environment settings)
'''
try:
# setting the locale to '' uses the default locale
# as it would be returned by locale.getdefaultlocale()
locale.setlocale(locale.LC_ALL, '')
except locale.Error, e:
# fallback to the 'C' locale, which may cause unicode
# issues but is preferable to simply failing because
# of an unknown locale
locale.setlocale(locale.LC_ALL, 'C')
os.environ['LANG'] = 'C'
os.environ['LC_CTYPE'] = 'C'
except Exception, e:
self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" % e)
def _handle_aliases(self):
aliases_results = {} #alias:canon
for (k,v) in self.argument_spec.iteritems():
self._legal_inputs.append(k)
aliases = v.get('aliases', None)
default = v.get('default', None)
required = v.get('required', False)
if default is not None and required:
# not alias specific but this is a good place to check this
self.fail_json(msg="internal error: required and default are mutally exclusive for %s" % k)
if aliases is None:
continue
if type(aliases) != list:
self.fail_json(msg='internal error: aliases must be a list')
for alias in aliases:
self._legal_inputs.append(alias)
aliases_results[alias] = k
if alias in self.params:
self.params[k] = self.params[alias]
return aliases_results
def _check_for_check_mode(self):
for (k,v) in self.params.iteritems():
if k == 'CHECKMODE':
if not self.supports_check_mode:
self.exit_json(skipped=True, msg="remote module does not support check mode")
if self.supports_check_mode:
self.check_mode = True
def _check_for_no_log(self):
for (k,v) in self.params.iteritems():
if k == 'NO_LOG':
self.no_log = self.boolean(v)
def _check_invalid_arguments(self):
for (k,v) in self.params.iteritems():
# these should be in legal inputs already
#if k in ('CHECKMODE', 'NO_LOG'):
# continue
if k not in self._legal_inputs:
self.fail_json(msg="unsupported parameter for module: %s" % k)
def _count_terms(self, check):
count = 0
for term in check:
if term in self.params:
count += 1
return count
def _check_mutually_exclusive(self, spec):
if spec is None:
return
for check in spec:
count = self._count_terms(check)
if count > 1:
self.fail_json(msg="parameters are mutually exclusive: %s" % check)
def _check_required_one_of(self, spec):
if spec is None:
return
for check in spec:
count = self._count_terms(check)
if count == 0:
self.fail_json(msg="one of the following is required: %s" % ','.join(check))
def _check_required_together(self, spec):
if spec is None:
return
for check in spec:
counts = [ self._count_terms([field]) for field in check ]
non_zero = [ c for c in counts if c > 0 ]
if len(non_zero) > 0:
if 0 in counts:
self.fail_json(msg="parameters are required together: %s" % check)
def _check_required_arguments(self):
''' ensure all required arguments are present '''
missing = []
for (k,v) in self.argument_spec.iteritems():
required = v.get('required', False)
if required and k not in self.params:
missing.append(k)
if len(missing) > 0:
self.fail_json(msg="missing required arguments: %s" % ",".join(missing))
def _check_argument_values(self):
''' ensure all arguments have the requested values, and there are no stray arguments '''
for (k,v) in self.argument_spec.iteritems():
choices = v.get('choices',None)
if choices is None:
continue
if type(choices) == list:
if k in self.params:
if self.params[k] not in choices:
choices_str=",".join([str(c) for c in choices])
msg="value of %s must be one of: %s, got: %s" % (k, choices_str, self.params[k])
self.fail_json(msg=msg)
else:
self.fail_json(msg="internal error: do not know how to interpret argument_spec")
def _check_argument_types(self):
''' ensure all arguments have the requested type '''
for (k, v) in self.argument_spec.iteritems():
wanted = v.get('type', None)
if wanted is None:
continue
if k not in self.params:
continue
value = self.params[k]
is_invalid = False
if wanted == 'str':
if not isinstance(value, basestring):
self.params[k] = str(value)
elif wanted == 'list':
if not isinstance(value, list):
if isinstance(value, basestring):
self.params[k] = value.split(",")
elif isinstance(value, int) or isinstance(value, float):
self.params[k] = [ str(value) ]
else:
is_invalid = True
elif wanted == 'dict':
if not isinstance(value, dict):
if isinstance(value, basestring):
if value.startswith("{"):
try:
self.params[k] = json.loads(value)
except:
(result, exc) = self.safe_eval(value, dict(), include_exceptions=True)
if exc is not None:
self.fail_json(msg="unable to evaluate dictionary for %s" % k)
self.params[k] = result
elif '=' in value:
self.params[k] = dict([x.split("=", 1) for x in value.split(",")])
else:
self.fail_json(msg="dictionary requested, could not parse JSON or key=value")
else:
is_invalid = True
elif wanted == 'bool':
if not isinstance(value, bool):
if isinstance(value, basestring):
self.params[k] = self.boolean(value)
else:
is_invalid = True
elif wanted == 'int':
if not isinstance(value, int):
if isinstance(value, basestring):
self.params[k] = int(value)
else:
is_invalid = True
elif wanted == 'float':
if not isinstance(value, float):
if isinstance(value, basestring):
self.params[k] = float(value)
else:
is_invalid = True
else:
self.fail_json(msg="implementation error: unknown type %s requested for %s" % (wanted, k))
if is_invalid:
self.fail_json(msg="argument %s is of invalid type: %s, required: %s" % (k, type(value), wanted))
def _set_defaults(self, pre=True):
for (k,v) in self.argument_spec.iteritems():
default = v.get('default', None)
if pre == True:
# this prevents setting defaults on required items
if default is not None and k not in self.params:
self.params[k] = default
else:
# make sure things without a default still get set None
if k not in self.params:
self.params[k] = default
def _load_params(self):
''' read the input and return a dictionary and the arguments string '''
args = MODULE_ARGS
items = shlex.split(args)
params = {}
for x in items:
try:
(k, v) = x.split("=",1)
except Exception, e:
self.fail_json(msg="this module requires key=value arguments (%s)" % (items))
params[k] = v
params2 = json.loads(MODULE_COMPLEX_ARGS)
params2.update(params)
return (params2, args)
def _log_invocation(self):
''' log that ansible ran the module '''
# TODO: generalize a separate log function and make log_invocation use it
# Sanitize possible password argument when logging.
log_args = dict()
passwd_keys = ['password', 'login_password']
filter_re = [
# filter out things like user:pass@foo/whatever
# and http://username:pass@wherever/foo
re.compile('^(?P<before>.*:)(?P<password>.*)(?P<after>\@.*)$'),
]
for param in self.params:
canon = self.aliases.get(param, param)
arg_opts = self.argument_spec.get(canon, {})
no_log = arg_opts.get('no_log', False)
if no_log:
log_args[param] = 'NOT_LOGGING_PARAMETER'
elif param in passwd_keys:
log_args[param] = 'NOT_LOGGING_PASSWORD'
else:
found = False
for filter in filter_re:
if isinstance(self.params[param], unicode):
m = filter.match(self.params[param])
else:
m = filter.match(str(self.params[param]))
if m:
d = m.groupdict()
log_args[param] = d['before'] + "********" + d['after']
found = True
break
if not found:
log_args[param] = self.params[param]
module = 'ansible-%s' % os.path.basename(__file__)
msg = ''
for arg in log_args:
if isinstance(log_args[arg], basestring):
msg = msg + arg + '=' + log_args[arg].decode('utf-8') + ' '
else:
msg = msg + arg + '=' + str(log_args[arg]) + ' '
if msg:
msg = 'Invoked with %s' % msg
else:
msg = 'Invoked'
# 6655 - allow for accented characters
try:
msg = msg.encode('utf8')
except UnicodeDecodeError, e:
pass
if (has_journal):
journal_args = ["MESSAGE=%s %s" % (module, msg)]
journal_args.append("MODULE=%s" % os.path.basename(__file__))
for arg in log_args:
journal_args.append(arg.upper() + "=" + str(log_args[arg]))
try:
journal.sendv(*journal_args)
except IOError, e:
# fall back to syslog since logging to journal failed
syslog.openlog(str(module), 0, syslog.LOG_USER)
syslog.syslog(syslog.LOG_NOTICE, msg) #1
else:
syslog.openlog(str(module), 0, syslog.LOG_USER)
syslog.syslog(syslog.LOG_NOTICE, msg) #2
def _set_cwd(self):
try:
cwd = os.getcwd()
if not os.access(cwd, os.F_OK|os.R_OK):
raise
return cwd
except:
# we don't have access to the cwd, probably because of sudo.
# Try and move to a neutral location to prevent errors
for cwd in [os.path.expandvars('$HOME'), tempfile.gettempdir()]:
try:
if os.access(cwd, os.F_OK|os.R_OK):
os.chdir(cwd)
return cwd
except:
pass
# we won't error here, as it may *not* be a problem,
# and we don't want to break modules unnecessarily
return None
def get_bin_path(self, arg, required=False, opt_dirs=[]):
'''
find system executable in PATH.
Optional arguments:
- required: if executable is not found and required is true, fail_json
- opt_dirs: optional list of directories to search in addition to PATH
if found return full path; otherwise return None
'''
sbin_paths = ['/sbin', '/usr/sbin', '/usr/local/sbin']
paths = []
for d in opt_dirs:
if d is not None and os.path.exists(d):
paths.append(d)
paths += os.environ.get('PATH', '').split(os.pathsep)
bin_path = None
# mangle PATH to include /sbin dirs
for p in sbin_paths:
if p not in paths and os.path.exists(p):
paths.append(p)
for d in paths:
path = os.path.join(d, arg)
if os.path.exists(path) and self.is_executable(path):
bin_path = path
break
if required and bin_path is None:
self.fail_json(msg='Failed to find required executable %s' % arg)
return bin_path
def boolean(self, arg):
''' return a bool for the arg '''
if arg is None or type(arg) == bool:
return arg
if type(arg) in types.StringTypes:
arg = arg.lower()
if arg in BOOLEANS_TRUE:
return True
elif arg in BOOLEANS_FALSE:
return False
else:
self.fail_json(msg='Boolean %s not in either boolean list' % arg)
def jsonify(self, data):
for encoding in ("utf-8", "latin-1", "unicode_escape"):
try:
return json.dumps(data, encoding=encoding)
# Old systems using simplejson module does not support encoding keyword.
except TypeError, e:
return json.dumps(data)
except UnicodeDecodeError, e:
continue
self.fail_json(msg='Invalid unicode encoding encountered')
def from_json(self, data):
return json.loads(data)
def add_cleanup_file(self, path):
if path not in self.cleanup_files:
self.cleanup_files.append(path)
def do_cleanup_files(self):
for path in self.cleanup_files:
self.cleanup(path)
def exit_json(self, **kwargs):
''' return from the module, without error '''
self.add_path_info(kwargs)
if not 'changed' in kwargs:
kwargs['changed'] = False
self.do_cleanup_files()
print self.jsonify(kwargs)
sys.exit(0)
def fail_json(self, **kwargs):
''' return from the module, with an error message '''
self.add_path_info(kwargs)
assert 'msg' in kwargs, "implementation error -- msg to explain the error is required"
kwargs['failed'] = True
self.do_cleanup_files()
print self.jsonify(kwargs)
sys.exit(1)
def is_executable(self, path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def digest_from_file(self, filename, digest_method):
''' Return hex digest of local file for a given digest_method, or None if file is not present. '''
if not os.path.exists(filename):
return None
if os.path.isdir(filename):
self.fail_json(msg="attempted to take checksum of directory: %s" % filename)
digest = digest_method
blocksize = 64 * 1024
infile = open(filename, 'rb')
block = infile.read(blocksize)
while block:
digest.update(block)
block = infile.read(blocksize)
infile.close()
return digest.hexdigest()
def md5(self, filename):
''' Return MD5 hex digest of local file using digest_from_file(). '''
return self.digest_from_file(filename, _md5())
def sha256(self, filename):
''' Return SHA-256 hex digest of local file using digest_from_file(). '''
if not HAVE_HASHLIB:
self.fail_json(msg="SHA-256 checksums require hashlib, which is available in Python 2.5 and higher")
return self.digest_from_file(filename, _sha256())
def backup_local(self, fn):
'''make a date-marked backup of the specified file, return True or False on success or failure'''
# backups named basename-YYYY-MM-DD@HH:MM~
ext = time.strftime("%Y-%m-%d@%H:%M~", time.localtime(time.time()))
backupdest = '%s.%s' % (fn, ext)
try:
shutil.copy2(fn, backupdest)
except shutil.Error, e:
self.fail_json(msg='Could not make backup of %s to %s: %s' % (fn, backupdest, e))
return backupdest
def cleanup(self, tmpfile):
if os.path.exists(tmpfile):
try:
os.unlink(tmpfile)
except OSError, e:
sys.stderr.write("could not cleanup %s: %s" % (tmpfile, e))
def atomic_move(self, src, dest):
'''atomically move src to dest, copying attributes from dest, returns true on success
it uses os.rename to ensure this as it is an atomic operation, rest of the function is
to work around limitations, corner cases and ensure selinux context is saved if possible'''
context = None
dest_stat = None
if os.path.exists(dest):
try:
dest_stat = os.stat(dest)
os.chmod(src, dest_stat.st_mode & 07777)
os.chown(src, dest_stat.st_uid, dest_stat.st_gid)
except OSError, e:
if e.errno != errno.EPERM:
raise
if self.selinux_enabled():
context = self.selinux_context(dest)
else:
if self.selinux_enabled():
context = self.selinux_default_context(dest)
creating = not os.path.exists(dest)
try:
login_name = os.getlogin()
except OSError:
# not having a tty can cause the above to fail, so
# just get the LOGNAME environment variable instead
login_name = os.environ.get('LOGNAME', None)
# if the original login_name doesn't match the currently
# logged-in user, or if the SUDO_USER environment variable
# is set, then this user has switched their credentials
switched_user = login_name and login_name != pwd.getpwuid(os.getuid())[0] or os.environ.get('SUDO_USER')
try:
# Optimistically try a rename, solves some corner cases and can avoid useless work, throws exception if not atomic.
os.rename(src, dest)
except (IOError,OSError), e:
# only try workarounds for errno 18 (cross device), 1 (not permited) and 13 (permission denied)
if e.errno != errno.EPERM and e.errno != errno.EXDEV and e.errno != errno.EACCES:
self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, e))
dest_dir = os.path.dirname(dest)
dest_file = os.path.basename(dest)
tmp_dest = tempfile.NamedTemporaryFile(
prefix=".ansible_tmp", dir=dest_dir, suffix=dest_file)
try: # leaves tmp file behind when sudo and not root
if switched_user and os.getuid() != 0:
# cleanup will happen by 'rm' of tempdir
# copy2 will preserve some metadata
shutil.copy2(src, tmp_dest.name)
else:
shutil.move(src, tmp_dest.name)
if self.selinux_enabled():
self.set_context_if_different(
tmp_dest.name, context, False)
tmp_stat = os.stat(tmp_dest.name)
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
os.chown(tmp_dest.name, dest_stat.st_uid, dest_stat.st_gid)
os.rename(tmp_dest.name, dest)
except (shutil.Error, OSError, IOError), e:
self.cleanup(tmp_dest.name)
self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, e))
if creating:
# make sure the file has the correct permissions
# based on the current value of umask
umask = os.umask(0)
os.umask(umask)
os.chmod(dest, 0666 ^ umask)
if switched_user:
os.chown(dest, os.getuid(), os.getgid())
if self.selinux_enabled():
# rename might not preserve context
self.set_context_if_different(dest, context, False)
def run_command(self, args, check_rc=False, close_fds=False, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None, use_unsafe_shell=False):
'''
Execute a command, returns rc, stdout, and stderr.
args is the command to run
If args is a list, the command will be run with shell=False.
If args is a string and use_unsafe_shell=False it will split args to a list and run with shell=False
If args is a string and use_unsafe_shell=True it run with shell=True.
Other arguments:
- check_rc (boolean) Whether to call fail_json in case of
non zero RC. Default is False.
- close_fds (boolean) See documentation for subprocess.Popen().
Default is False.
- executable (string) See documentation for subprocess.Popen().
Default is None.
'''
shell = False
if isinstance(args, list):
if use_unsafe_shell:
args = " ".join([pipes.quote(x) for x in args])
shell = True
elif isinstance(args, basestring) and use_unsafe_shell:
shell = True
elif isinstance(args, basestring):
args = shlex.split(args.encode('utf-8'))
else:
msg = "Argument 'args' to run_command must be list or string"
self.fail_json(rc=257, cmd=args, msg=msg)
# expand things like $HOME and ~
if not shell:
args = [ os.path.expandvars(os.path.expanduser(x)) for x in args ]
rc = 0
msg = None
st_in = None
# Set a temporart env path if a prefix is passed
env=os.environ
if path_prefix:
env['PATH']="%s:%s" % (path_prefix, env['PATH'])
# create a printable version of the command for use
# in reporting later, which strips out things like
# passwords from the args list
if isinstance(args, list):
clean_args = " ".join(pipes.quote(arg) for arg in args)
else:
clean_args = args
# all clean strings should return two match groups,
# where the first is the CLI argument and the second
# is the password/key/phrase that will be hidden
clean_re_strings = [
# this removes things like --password, --pass, --pass-wd, etc.
# optionally followed by an '=' or a space. The password can
# be quoted or not too, though it does not care about quotes
# that are not balanced
# source: http://blog.stevenlevithan.com/archives/match-quoted-string
r'([-]{0,2}pass[-]?(?:word|wd)?[=\s]?)((?:["\'])?(?:[^\s])*(?:\1)?)',
# TODO: add more regex checks here
]
for re_str in clean_re_strings:
r = re.compile(re_str)
clean_args = r.sub(r'\1********', clean_args)
if data:
st_in = subprocess.PIPE
kwargs = dict(
executable=executable,
shell=shell,
close_fds=close_fds,
stdin= st_in,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if path_prefix:
kwargs['env'] = env
if cwd and os.path.isdir(cwd):
kwargs['cwd'] = cwd
# store the pwd
prev_dir = os.getcwd()
# make sure we're in the right working directory
if cwd and os.path.isdir(cwd):
try:
os.chdir(cwd)
except (OSError, IOError), e:
self.fail_json(rc=e.errno, msg="Could not open %s , %s" % (cwd, str(e)))
try:
cmd = subprocess.Popen(args, **kwargs)
if data:
if not binary_data:
data += '\n'
out, err = cmd.communicate(input=data)
rc = cmd.returncode
except (OSError, IOError), e:
self.fail_json(rc=e.errno, msg=str(e), cmd=clean_args)
except:
self.fail_json(rc=257, msg=traceback.format_exc(), cmd=clean_args)
if rc != 0 and check_rc:
msg = err.rstrip()
self.fail_json(cmd=clean_args, rc=rc, stdout=out, stderr=err, msg=msg)
# reset the pwd
os.chdir(prev_dir)
return (rc, out, err)
def append_to_file(self, filename, str):
filename = os.path.expandvars(os.path.expanduser(filename))
fh = open(filename, 'a')
fh.write(str)
fh.close()
def pretty_bytes(self,size):
ranges = (
(1<<70L, 'ZB'),
(1<<60L, 'EB'),
(1<<50L, 'PB'),
(1<<40L, 'TB'),
(1<<30L, 'GB'),
(1<<20L, 'MB'),
(1<<10L, 'KB'),
(1, 'Bytes')
)
for limit, suffix in ranges:
if size >= limit:
break
return '%.2f %s' % (float(size)/ limit, suffix)
def get_module_path():
return os.path.dirname(os.path.realpath(__file__))
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_2234_0 |
crossvul-python_data_bad_2234_2 | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Stephen Fromm <sfromm@gmail.com>
# Brian Coca <briancoca+dev@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
import os
import os.path
import pipes
import shutil
import tempfile
import base64
from ansible import utils
from ansible.runner.return_data import ReturnData
class ActionModule(object):
TRANSFERS_FILES = True
def __init__(self, runner):
self.runner = runner
def _assemble_from_fragments(self, src_path, delimiter=None, compiled_regexp=None):
''' assemble a file from a directory of fragments '''
tmpfd, temp_path = tempfile.mkstemp()
tmp = os.fdopen(tmpfd,'w')
delimit_me = False
add_newline = False
for f in sorted(os.listdir(src_path)):
if compiled_regexp and not compiled_regexp.search(f):
continue
fragment = "%s/%s" % (src_path, f)
if not os.path.isfile(fragment):
continue
fragment_content = file(fragment).read()
# always put a newline between fragments if the previous fragment didn't end with a newline.
if add_newline:
tmp.write('\n')
# delimiters should only appear between fragments
if delimit_me:
if delimiter:
# un-escape anything like newlines
delimiter = delimiter.decode('unicode-escape')
tmp.write(delimiter)
# always make sure there's a newline after the
# delimiter, so lines don't run together
if delimiter[-1] != '\n':
tmp.write('\n')
tmp.write(fragment_content)
delimit_me = True
if fragment_content.endswith('\n'):
add_newline = False
else:
add_newline = True
tmp.close()
return temp_path
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
# load up options
options = {}
if complex_args:
options.update(complex_args)
options.update(utils.parse_kv(module_args))
src = options.get('src', None)
dest = options.get('dest', None)
delimiter = options.get('delimiter', None)
remote_src = utils.boolean(options.get('remote_src', 'yes'))
if src is None or dest is None:
result = dict(failed=True, msg="src and dest are required")
return ReturnData(conn=conn, comm_ok=False, result=result)
if remote_src:
return self.runner._execute_module(conn, tmp, 'assemble', module_args, inject=inject, complex_args=complex_args)
elif '_original_file' in inject:
src = utils.path_dwim_relative(inject['_original_file'], 'files', src, self.runner.basedir)
else:
# the source is local, so expand it here
src = os.path.expanduser(src)
# Does all work assembling the file
path = self._assemble_from_fragments(src, delimiter)
pathmd5 = utils.md5s(path)
remote_md5 = self.runner._remote_md5(conn, tmp, dest)
if pathmd5 != remote_md5:
resultant = file(path).read()
if self.runner.diff:
dest_result = self.runner._execute_module(conn, tmp, 'slurp', "path=%s" % dest, inject=inject, persist_files=True)
if 'content' in dest_result.result:
dest_contents = dest_result.result['content']
if dest_result.result['encoding'] == 'base64':
dest_contents = base64.b64decode(dest_contents)
else:
raise Exception("unknown encoding, failed: %s" % dest_result.result)
xfered = self.runner._transfer_str(conn, tmp, 'src', resultant)
# fix file permissions when the copy is done as a different user
if self.runner.sudo and self.runner.sudo_user != 'root':
self.runner._low_level_exec_command(conn, "chmod a+r %s" % xfered, tmp)
# run the copy module
module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(src)))
if self.runner.noop_on_check(inject):
return ReturnData(conn=conn, comm_ok=True, result=dict(changed=True), diff=dict(before_header=dest, after_header=src, after=resultant))
else:
res = self.runner._execute_module(conn, tmp, 'copy', module_args, inject=inject)
res.diff = dict(after=resultant)
return res
else:
module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(src)))
return self.runner._execute_module(conn, tmp, 'file', module_args, inject=inject)
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_2234_2 |
crossvul-python_data_good_2234_2 | # (c) 2013-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Stephen Fromm <sfromm@gmail.com>
# Brian Coca <briancoca+dev@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
import os
import os.path
import pipes
import shutil
import tempfile
import base64
from ansible import utils
from ansible.runner.return_data import ReturnData
class ActionModule(object):
TRANSFERS_FILES = True
def __init__(self, runner):
self.runner = runner
def _assemble_from_fragments(self, src_path, delimiter=None, compiled_regexp=None):
''' assemble a file from a directory of fragments '''
tmpfd, temp_path = tempfile.mkstemp()
tmp = os.fdopen(tmpfd,'w')
delimit_me = False
add_newline = False
for f in sorted(os.listdir(src_path)):
if compiled_regexp and not compiled_regexp.search(f):
continue
fragment = "%s/%s" % (src_path, f)
if not os.path.isfile(fragment):
continue
fragment_content = file(fragment).read()
# always put a newline between fragments if the previous fragment didn't end with a newline.
if add_newline:
tmp.write('\n')
# delimiters should only appear between fragments
if delimit_me:
if delimiter:
# un-escape anything like newlines
delimiter = delimiter.decode('unicode-escape')
tmp.write(delimiter)
# always make sure there's a newline after the
# delimiter, so lines don't run together
if delimiter[-1] != '\n':
tmp.write('\n')
tmp.write(fragment_content)
delimit_me = True
if fragment_content.endswith('\n'):
add_newline = False
else:
add_newline = True
tmp.close()
return temp_path
def run(self, conn, tmp, module_name, module_args, inject, complex_args=None, **kwargs):
# load up options
options = {}
if complex_args:
options.update(complex_args)
options.update(utils.parse_kv(module_args))
src = options.get('src', None)
dest = options.get('dest', None)
delimiter = options.get('delimiter', None)
remote_src = utils.boolean(options.get('remote_src', 'yes'))
if src is None or dest is None:
result = dict(failed=True, msg="src and dest are required")
return ReturnData(conn=conn, comm_ok=False, result=result)
if remote_src:
return self.runner._execute_module(conn, tmp, 'assemble', module_args, inject=inject, complex_args=complex_args)
elif '_original_file' in inject:
src = utils.path_dwim_relative(inject['_original_file'], 'files', src, self.runner.basedir)
else:
# the source is local, so expand it here
src = os.path.expanduser(src)
# Does all work assembling the file
path = self._assemble_from_fragments(src, delimiter)
pathmd5 = utils.md5s(path)
remote_md5 = self.runner._remote_md5(conn, tmp, dest)
if pathmd5 != remote_md5:
resultant = file(path).read()
if self.runner.diff:
dest_result = self.runner._execute_module(conn, tmp, 'slurp', "path=%s" % dest, inject=inject, persist_files=True)
if 'content' in dest_result.result:
dest_contents = dest_result.result['content']
if dest_result.result['encoding'] == 'base64':
dest_contents = base64.b64decode(dest_contents)
else:
raise Exception("unknown encoding, failed: %s" % dest_result.result)
xfered = self.runner._transfer_str(conn, tmp, 'src', resultant)
# fix file permissions when the copy is done as a different user
if self.runner.sudo and self.runner.sudo_user != 'root':
self.runner._low_level_exec_command(conn, "chmod a+r %s" % xfered, tmp)
# run the copy module
new_module_args = dict(
src=xfered,
dest=dest,
original_basename=os.path.basename(src),
)
module_args_tmp = utils.merge_module_args(module_args, new_module_args)
if self.runner.noop_on_check(inject):
return ReturnData(conn=conn, comm_ok=True, result=dict(changed=True), diff=dict(before_header=dest, after_header=src, after=resultant))
else:
res = self.runner._execute_module(conn, tmp, 'copy', module_args_tmp, inject=inject)
res.diff = dict(after=resultant)
return res
else:
new_module_args = dict(
src=xfered,
dest=dest,
original_basename=os.path.basename(src),
)
module_args_tmp = utils.merge_module_args(module_args, new_module_args)
return self.runner._execute_module(conn, tmp, 'file', module_args_tmp, inject=inject)
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_2234_2 |
crossvul-python_data_bad_4621_2 | from pathlib import Path
from urllib.parse import unquote
import base64
import json, os, requests, time, pytz, pymongo
from shutil import rmtree
from requests.exceptions import ConnectionError
from os.path import join, exists
from django.shortcuts import render
from django.core.serializers import serialize
from django.http import HttpResponse
from django.forms.models import model_to_dict
from django.utils import timezone
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from subprocess import Popen, PIPE
from gerapy import get_logger
from gerapy.server.core.response import JsonResponse
from gerapy.cmd.init import PROJECTS_FOLDER
from gerapy.server.server.settings import TIME_ZONE
from gerapy.server.core.models import Client, Project, Deploy, Monitor, Task
from gerapy.server.core.build import build_project, find_egg
from gerapy.server.core.utils import IGNORES, scrapyd_url, log_url, get_tree, get_scrapyd, process_html, bytes2str, \
clients_of_task, get_job_id
from django_apscheduler.models import DjangoJob, DjangoJobExecution
from django.core.files.storage import FileSystemStorage
import zipfile
logger = get_logger(__name__)
@api_view(['GET'])
# @permission_classes([IsAuthenticated])
def index(request):
"""
render index page
:param request: request object
:return: page
"""
return render(request, 'index.html')
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def index_status(request):
"""
index statistics
:param request: request object
:return: json
"""
if request.method == 'GET':
clients = Client.objects.all()
data = {
'success': 0,
'error': 0,
'project': 0,
}
# clients info
for client in clients:
try:
requests.get(scrapyd_url(client.ip, client.port), timeout=1)
data['success'] += 1
except ConnectionError:
data['error'] += 1
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
files = os.listdir(path)
# projects info
for file in files:
if os.path.isdir(join(path, file)) and not file in IGNORES:
data['project'] += 1
return JsonResponse(data)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def client_index(request):
"""
get client list
:param request: request object
:return: client list
"""
return HttpResponse(serialize('json', Client.objects.order_by('-id')))
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def client_info(request, client_id):
"""
get client info
:param request: request object
:param id: client id
:return: json
"""
if request.method == 'GET':
return JsonResponse(model_to_dict(Client.objects.get(id=client_id)))
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def client_status(request, client_id):
"""
get client status
:param request: request object
:param client_id: client id
:return: json
"""
if request.method == 'GET':
# get client object
client = Client.objects.get(id=client_id)
requests.get(scrapyd_url(client.ip, client.port), timeout=3)
return JsonResponse({'result': '1'})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def client_update(request, client_id):
"""
update client info
:param request: request object
:param client_id: client id
:return: json
"""
if request.method == 'POST':
client = Client.objects.filter(id=client_id)
data = json.loads(request.body)
client.update(**data)
return JsonResponse(model_to_dict(Client.objects.get(id=client_id)))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def client_create(request):
"""
create a client
:param request: request object
:return: json
"""
if request.method == 'POST':
data = json.loads(request.body)
client = Client.objects.create(**data)
return JsonResponse(model_to_dict(client))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def client_remove(request, client_id):
"""
remove a client
:param request: request object
:param client_id: client id
:return: json
"""
if request.method == 'POST':
client = Client.objects.get(id=client_id)
# delete deploy
Deploy.objects.filter(client=client).delete()
# delete client
Client.objects.filter(id=client_id).delete()
return JsonResponse({'result': '1'})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def spider_list(request, client_id, project_name):
"""
get spider list from one client
:param request: request Object
:param client_id: client id
:param project_name: project name
:return: json
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
spiders = scrapyd.list_spiders(project_name)
spiders = [{'name': spider, 'id': index + 1} for index, spider in enumerate(spiders)]
return JsonResponse(spiders)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def spider_start(request, client_id, project_name, spider_name):
"""
start a spider
:param request: request object
:param client_id: client id
:param project_name: project name
:param spider_name: spider name
:return: json
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
job = scrapyd.schedule(project_name, spider_name)
return JsonResponse({'job': job})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def project_list(request, client_id):
"""
project deployed list on one client
:param request: request object
:param client_id: client id
:return: json
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
projects = scrapyd.list_projects()
return JsonResponse(projects)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def project_index(request):
"""
project index list
:param request: request object
:return: json
"""
if request.method == 'GET':
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
files = os.listdir(path)
project_list = []
for file in files:
if os.path.isdir(join(path, file)) and not file in IGNORES:
project_list.append({'name': file})
return JsonResponse(project_list)
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def project_configure(request, project_name):
"""
get configuration
:param request: request object
:param project_name: project name
:return: json
"""
# get configuration
if request.method == 'GET':
project = Project.objects.get(name=project_name)
project = model_to_dict(project)
project['configuration'] = json.loads(project['configuration']) if project['configuration'] else None
return JsonResponse(project)
# update configuration
elif request.method == 'POST':
project = Project.objects.filter(name=project_name)
data = json.loads(request.body)
configuration = json.dumps(data.get('configuration'), ensure_ascii=False)
project.update(**{'configuration': configuration})
# execute generate cmd
cmd = ' '.join(['gerapy', 'generate', project_name])
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())
if not stderr:
return JsonResponse({'status': '1'})
else:
return JsonResponse({'status': '0', 'message': stderr})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def project_tree(request, project_name):
"""
get file tree of project
:param request: request object
:param project_name: project name
:return: json of tree
"""
if request.method == 'GET':
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
# get tree data
tree = get_tree(join(path, project_name))
return JsonResponse(tree)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_create(request):
"""
create a configurable project
:param request: request object
:return: json
"""
if request.method == 'POST':
data = json.loads(request.body)
data['configurable'] = 1
project, result = Project.objects.update_or_create(**data)
# generate a single project folder
path = join(os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER)), data['name'])
os.mkdir(path)
return JsonResponse(model_to_dict(project))
@api_view(['POST'])
# @permission_classes([IsAuthenticated])
def project_upload(request):
"""
upload project
:param request: request object
:return: json
"""
if request.method == 'POST':
file = request.FILES['file']
file_name = file.name
fs = FileSystemStorage(PROJECTS_FOLDER)
zip_file_name = fs.save(file_name, file)
logger.debug('zip file name %s', zip_file_name)
# extract zip file
with zipfile.ZipFile(join(PROJECTS_FOLDER, zip_file_name), 'r') as zip_ref:
zip_ref.extractall(PROJECTS_FOLDER)
logger.debug('extracted files to %s', PROJECTS_FOLDER)
return JsonResponse({'status': True})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_clone(request):
"""
clone project from github
:param request: request object
:return: json
"""
if request.method == 'POST':
data = json.loads(request.body)
address = data.get('address')
if not address.startswith('http'):
return JsonResponse({'status': False})
address = address + '.git' if not address.endswith('.git') else address
cmd = 'git clone {address} {target}'.format(address=address, target=join(PROJECTS_FOLDER, Path(address).stem))
logger.debug('clone cmd %s', cmd)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())
logger.debug('clone run result %s', stdout)
if stderr: logger.error(stderr)
return JsonResponse({'status': True}) if not stderr else JsonResponse({'status': False})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_remove(request, project_name):
"""
remove project from disk and db
:param request: request object
:param project_name: project name
:return: result of remove
"""
if request.method == 'POST':
# delete deployments
project = Project.objects.get(name=project_name)
Deploy.objects.filter(project=project).delete()
# delete project
result = Project.objects.filter(name=project_name).delete()
# get project path
path = join(os.path.abspath(os.getcwd()), PROJECTS_FOLDER)
project_path = join(path, project_name)
# delete project file tree
if exists(project_path):
rmtree(project_path)
return JsonResponse({'result': result})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def project_version(request, client_id, project_name):
"""
get project deploy version
:param request: request object
:param client_id: client id
:param project_name: project name
:return: deploy version of project
"""
if request.method == 'GET':
# get client and project model
client = Client.objects.get(id=client_id)
project = Project.objects.get(name=project_name)
scrapyd = get_scrapyd(client)
# if deploy info exists in db, return it
if Deploy.objects.filter(client=client, project=project):
deploy = Deploy.objects.get(client=client, project=project)
# if deploy info does not exists in db, create deploy info
else:
try:
versions = scrapyd.list_versions(project_name)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'}, status=500)
if len(versions) > 0:
version = versions[-1]
deployed_at = timezone.datetime.fromtimestamp(int(version), tz=pytz.timezone(TIME_ZONE))
else:
deployed_at = None
deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at)
# return deploy json info
return JsonResponse(model_to_dict(deploy))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_deploy(request, client_id, project_name):
"""
deploy project operation
:param request: request object
:param client_id: client id
:param project_name: project name
:return: json of deploy result
"""
if request.method == 'POST':
# get project folder
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
project_path = join(path, project_name)
# find egg file
egg = find_egg(project_path)
if not egg:
return JsonResponse({'message': 'egg not found'}, status=500)
egg_file = open(join(project_path, egg), 'rb')
# get client and project model
client = Client.objects.get(id=client_id)
project = Project.objects.get(name=project_name)
# execute deploy operation
scrapyd = get_scrapyd(client)
scrapyd.add_version(project_name, int(time.time()), egg_file.read())
# update deploy info
deployed_at = timezone.now()
Deploy.objects.filter(client=client, project=project).delete()
deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at,
description=project.description)
return JsonResponse(model_to_dict(deploy))
@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def project_build(request, project_name):
"""
get build info or execute build operation
:param request: request object
:param project_name: project name
:return: json
"""
# get project folder
path = os.path.abspath(join(os.getcwd(), PROJECTS_FOLDER))
project_path = join(path, project_name)
# get build version
if request.method == 'GET':
egg = find_egg(project_path)
# if built, save or update project to db
if egg:
built_at = timezone.datetime.fromtimestamp(os.path.getmtime(join(project_path, egg)),
tz=pytz.timezone(TIME_ZONE))
if not Project.objects.filter(name=project_name):
Project(name=project_name, built_at=built_at, egg=egg).save()
model = Project.objects.get(name=project_name)
else:
model = Project.objects.get(name=project_name)
model.built_at = built_at
model.egg = egg
model.save()
# if not built, just save project name to db
else:
if not Project.objects.filter(name=project_name):
Project(name=project_name).save()
model = Project.objects.get(name=project_name)
# transfer model to dict then dumps it to json
data = model_to_dict(model)
return JsonResponse(data)
# build operation manually by clicking button
elif request.method == 'POST':
data = json.loads(request.body)
description = data['description']
build_project(project_name)
egg = find_egg(project_path)
if not egg:
return JsonResponse({'message': 'egg not found'}, status=500)
# update built_at info
built_at = timezone.now()
# if project does not exists in db, create it
if not Project.objects.filter(name=project_name):
Project(name=project_name, description=description, built_at=built_at, egg=egg).save()
model = Project.objects.get(name=project_name)
# if project exists, update egg, description, built_at info
else:
model = Project.objects.get(name=project_name)
model.built_at = built_at
model.egg = egg
model.description = description
model.save()
# transfer model to dict then dumps it to json
data = model_to_dict(model)
return JsonResponse(data)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_parse(request, project_name):
"""
parse project
:param request: request object
:param project_name: project name
:return: requests, items, response
"""
if request.method == 'POST':
project_path = join(PROJECTS_FOLDER, project_name)
data = json.loads(request.body)
logger.debug('post data %s', data)
spider_name = data.get('spider')
args = {
'start': data.get('start', False),
'method': data.get('method', 'GET'),
'url': data.get('url'),
'callback': data.get('callback'),
'cookies': "'" + json.dumps(data.get('cookies', {}), ensure_ascii=False) + "'",
'headers': "'" + json.dumps(data.get('headers', {}), ensure_ascii=False) + "'",
'meta': "'" + json.dumps(data.get('meta', {}), ensure_ascii=False) + "'",
'dont_filter': data.get('dont_filter', False),
'priority': data.get('priority', 0),
}
# set request body
body = data.get('body', '')
if args.get('method').lower() != 'get':
args['body'] = "'" + json.dumps(body, ensure_ascii=False) + "'"
args_cmd = ' '.join(
['--{arg} {value}'.format(arg=arg, value=value) for arg, value in args.items()])
logger.debug('args cmd %s', args_cmd)
cmd = 'gerapy parse {args_cmd} {project_path} {spider_name}'.format(
args_cmd=args_cmd,
project_path=project_path,
spider_name=spider_name
)
logger.debug('parse cmd %s', cmd)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read())
logger.debug('stdout %s, stderr %s', stdout, stderr)
if not stderr:
return JsonResponse({'status': True, 'result': json.loads(stdout)})
else:
return JsonResponse({'status': False, 'message': stderr})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_read(request):
"""
get content of project file
:param request: request object
:return: file content
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['label'])
# binary file
with open(path, 'rb') as f:
return HttpResponse(f.read().decode('utf-8'))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_update(request):
"""
update project file
:param request: request object
:return: result of update
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['label'])
code = data['code']
with open(path, 'w', encoding='utf-8') as f:
f.write(code)
return JsonResponse({'result': '1'})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_create(request):
"""
create project file
:param request: request object
:return: result of create
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['name'])
open(path, 'w', encoding='utf-8').close()
return JsonResponse({'result': '1'})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_delete(request):
"""
delete project file
:param request: request object
:return: result of delete
"""
if request.method == 'POST':
data = json.loads(request.body)
path = join(data['path'], data['label'])
result = os.remove(path)
return JsonResponse({'result': result})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def project_file_rename(request):
"""
rename file name
:param request: request object
:return: result of rename
"""
if request.method == 'POST':
data = json.loads(request.body)
pre = join(data['path'], data['pre'])
new = join(data['path'], data['new'])
os.rename(pre, new)
return JsonResponse({'result': '1'})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def job_list(request, client_id, project_name):
"""
get job list of project from one client
:param request: request object
:param client_id: client id
:param project_name: project name
:return: list of jobs
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
scrapyd = get_scrapyd(client)
try:
result = scrapyd.list_jobs(project_name)
jobs = []
statuses = ['pending', 'running', 'finished']
for status in statuses:
for job in result.get(status):
job['status'] = status
jobs.append(job)
return JsonResponse(jobs)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'}, status=500)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def job_log(request, client_id, project_name, spider_name, job_id):
"""
get log of jog
:param request: request object
:param client_id: client id
:param project_name: project name
:param spider_name: spider name
:param job_id: job id
:return: log of job
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
# get log url
url = log_url(client.ip, client.port, project_name, spider_name, job_id)
try:
# get last 1000 bytes of log
response = requests.get(url, timeout=5, headers={
'Range': 'bytes=-1000'
}, auth=(client.username, client.password) if client.auth else None)
# Get encoding
encoding = response.apparent_encoding
# log not found
if response.status_code == 404:
return JsonResponse({'message': 'Log Not Found'}, status=404)
# bytes to string
text = response.content.decode(encoding, errors='replace')
return HttpResponse(text)
except requests.ConnectionError:
return JsonResponse({'message': 'Load Log Error'}, status=500)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def job_cancel(request, client_id, project_name, job_id):
"""
cancel a job
:param request: request object
:param client_id: client id
:param project_name: project name
:param job_id: job id
:return: json of cancel
"""
if request.method == 'GET':
client = Client.objects.get(id=client_id)
try:
scrapyd = get_scrapyd(client)
result = scrapyd.cancel(project_name, job_id)
return JsonResponse(result)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def del_version(request, client_id, project, version):
if request.method == 'GET':
client = Client.objects.get(id=client_id)
try:
scrapyd = get_scrapyd(client)
result = scrapyd.delete_version(project=project, version=version)
return JsonResponse(result)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def del_project(request, client_id, project):
if request.method == 'GET':
client = Client.objects.get(id=client_id)
try:
scrapyd = get_scrapyd(client)
result = scrapyd.delete_project(project=project)
return JsonResponse(result)
except ConnectionError:
return JsonResponse({'message': 'Connect Error'})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_db_list(request):
"""
get monitor db list
:param request: request object
:return: json of db list
"""
if request.method == 'POST':
data = json.loads(request.body)
url = data['url']
type = data['type']
if type == 'MongoDB':
client = pymongo.MongoClient(url)
dbs = client.list_database_names()
return JsonResponse(dbs)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_collection_list(request):
"""
get monitor collection list
:param request: request object
:return: json of collection list
"""
if request.method == 'POST':
data = json.loads(request.body)
url = data['url']
db = data['db']
type = data['type']
if type == 'MongoDB':
client = pymongo.MongoClient(url)
db = client[db]
collections = db.collection_names()
return JsonResponse(collections)
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def monitor_create(request):
"""
create a monitor
:param request: request object
:return: json of create
"""
if request.method == 'POST':
data = json.loads(request.body)
data = data['form']
data['configuration'] = json.dumps(data['configuration'], ensure_ascii=False)
monitor = Monitor.objects.create(**data)
return JsonResponse(model_to_dict(monitor))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def task_create(request):
"""
add task
:param request: request object
:return: Bool
"""
if request.method == 'POST':
data = json.loads(request.body)
task = Task.objects.create(clients=json.dumps(data.get('clients'), ensure_ascii=False),
project=data.get('project'),
name=data.get('name'),
spider=data.get('spider'),
trigger=data.get('trigger'),
configuration=json.dumps(data.get('configuration'), ensure_ascii=False),
modified=1)
return JsonResponse({'result': '1', 'data': model_to_dict(task)})
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def task_update(request, task_id):
"""
update task info
:param request: request object
:param task_id: task id
:return: json
"""
if request.method == 'POST':
task = Task.objects.filter(id=task_id)
data = json.loads(request.body)
data['clients'] = json.dumps(data.get('clients'), ensure_ascii=False)
data['configuration'] = json.dumps(data.get('configuration'), ensure_ascii=False)
data['modified'] = 1
task.update(**data)
return JsonResponse(model_to_dict(Task.objects.get(id=task_id)))
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def task_remove(request, task_id):
"""
remove task by task_id
:param request:
:return:
"""
if request.method == 'POST':
try:
# delete job from DjangoJob
task = Task.objects.get(id=task_id)
clients = clients_of_task(task)
for client in clients:
job_id = get_job_id(client, task)
DjangoJob.objects.filter(name=job_id).delete()
# delete task
Task.objects.filter(id=task_id).delete()
return JsonResponse({'result': '1'})
except:
return JsonResponse({'result': '0'})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def task_info(request, task_id):
"""
get task info
:param request: request object
:param task_id: task id
:return: json
"""
if request.method == 'GET':
task = Task.objects.get(id=task_id)
data = model_to_dict(task)
data['clients'] = json.loads(data.get('clients'))
data['configuration'] = json.loads(data.get('configuration'))
return JsonResponse({'data': data})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def task_index(request):
"""
get all tasks
:param request:
:return:
"""
if request.method == 'GET':
tasks = Task.objects.values()
return JsonResponse({'result': '1', 'data': tasks})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def task_status(request, task_id):
"""
get task status info
:param request: request object
:param task_id: task id
:return:
"""
if request.method == 'GET':
result = []
task = Task.objects.get(id=task_id)
clients = clients_of_task(task)
for client in clients:
job_id = get_job_id(client, task)
jobs = DjangoJob.objects.filter(name=job_id)
logger.debug('jobs from djangojob %s', jobs)
# if job does not exist, for date mode exceed time
if not jobs: continue
job = DjangoJob.objects.get(name=job_id)
executions = serialize('json', DjangoJobExecution.objects.filter(job=job))
result.append({
'client': model_to_dict(client),
'next': job.next_run_time,
'executions': json.loads(executions)
})
return JsonResponse({'data': result})
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def render_html(request):
"""
render html with url
:param request:
:return:
"""
if request.method == 'GET':
url = request.GET.get('url')
url = unquote(base64.b64decode(url).decode('utf-8'))
js = request.GET.get('js', 0)
script = request.GET.get('script')
try:
response = requests.get(url, timeout=5)
response.encoding = response.apparent_encoding
html = process_html(response.text)
return HttpResponse(html)
except Exception as e:
return JsonResponse({'message': e.args}, status=500)
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_4621_2 |
crossvul-python_data_bad_4621_1 | VERSION = (0, 9, '3a3')
__version__ = '.'.join(map(str, VERSION))
version = lambda: __version__
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_4621_1 |
crossvul-python_data_bad_3934_0 | """Small, fast HTTP client library for Python.
Features persistent connections, cache, and Google App Engine Standard
Environment support.
"""
from __future__ import print_function
__author__ = "Joe Gregorio (joe@bitworking.org)"
__copyright__ = "Copyright 2006, Joe Gregorio"
__contributors__ = [
"Thomas Broyer (t.broyer@ltgt.net)",
"James Antill",
"Xavier Verges Farrero",
"Jonathan Feinberg",
"Blair Zajac",
"Sam Ruby",
"Louis Nyffenegger",
"Alex Yu",
]
__license__ = "MIT"
__version__ = '0.17.4'
import base64
import calendar
import copy
import email
import email.FeedParser
import email.Message
import email.Utils
import errno
import gzip
import httplib
import os
import random
import re
import StringIO
import sys
import time
import urllib
import urlparse
import zlib
try:
from hashlib import sha1 as _sha, md5 as _md5
except ImportError:
# prior to Python 2.5, these were separate modules
import sha
import md5
_sha = sha.new
_md5 = md5.new
import hmac
from gettext import gettext as _
import socket
try:
from httplib2 import socks
except ImportError:
try:
import socks
except (ImportError, AttributeError):
socks = None
# Build the appropriate socket wrapper for ssl
ssl = None
ssl_SSLError = None
ssl_CertificateError = None
try:
import ssl # python 2.6
except ImportError:
pass
if ssl is not None:
ssl_SSLError = getattr(ssl, "SSLError", None)
ssl_CertificateError = getattr(ssl, "CertificateError", None)
def _ssl_wrap_socket(
sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password
):
if disable_validation:
cert_reqs = ssl.CERT_NONE
else:
cert_reqs = ssl.CERT_REQUIRED
if ssl_version is None:
ssl_version = ssl.PROTOCOL_SSLv23
if hasattr(ssl, "SSLContext"): # Python 2.7.9
context = ssl.SSLContext(ssl_version)
context.verify_mode = cert_reqs
context.check_hostname = cert_reqs != ssl.CERT_NONE
if cert_file:
if key_password:
context.load_cert_chain(cert_file, key_file, key_password)
else:
context.load_cert_chain(cert_file, key_file)
if ca_certs:
context.load_verify_locations(ca_certs)
return context.wrap_socket(sock, server_hostname=hostname)
else:
if key_password:
raise NotSupportedOnThisPlatform("Certificate with password is not supported.")
return ssl.wrap_socket(
sock,
keyfile=key_file,
certfile=cert_file,
cert_reqs=cert_reqs,
ca_certs=ca_certs,
ssl_version=ssl_version,
)
def _ssl_wrap_socket_unsupported(
sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password
):
if not disable_validation:
raise CertificateValidationUnsupported(
"SSL certificate validation is not supported without "
"the ssl module installed. To avoid this error, install "
"the ssl module, or explicity disable validation."
)
if key_password:
raise NotSupportedOnThisPlatform("Certificate with password is not supported.")
ssl_sock = socket.ssl(sock, key_file, cert_file)
return httplib.FakeSocket(sock, ssl_sock)
if ssl is None:
_ssl_wrap_socket = _ssl_wrap_socket_unsupported
if sys.version_info >= (2, 3):
from .iri2uri import iri2uri
else:
def iri2uri(uri):
return uri
def has_timeout(timeout): # python 2.6
if hasattr(socket, "_GLOBAL_DEFAULT_TIMEOUT"):
return timeout is not None and timeout is not socket._GLOBAL_DEFAULT_TIMEOUT
return timeout is not None
__all__ = [
"Http",
"Response",
"ProxyInfo",
"HttpLib2Error",
"RedirectMissingLocation",
"RedirectLimit",
"FailedToDecompressContent",
"UnimplementedDigestAuthOptionError",
"UnimplementedHmacDigestAuthOptionError",
"debuglevel",
"ProxiesUnavailableError",
]
# The httplib debug level, set to a non-zero value to get debug output
debuglevel = 0
# A request will be tried 'RETRIES' times if it fails at the socket/connection level.
RETRIES = 2
# Python 2.3 support
if sys.version_info < (2, 4):
def sorted(seq):
seq.sort()
return seq
# Python 2.3 support
def HTTPResponse__getheaders(self):
"""Return list of (header, value) tuples."""
if self.msg is None:
raise httplib.ResponseNotReady()
return self.msg.items()
if not hasattr(httplib.HTTPResponse, "getheaders"):
httplib.HTTPResponse.getheaders = HTTPResponse__getheaders
# All exceptions raised here derive from HttpLib2Error
class HttpLib2Error(Exception):
pass
# Some exceptions can be caught and optionally
# be turned back into responses.
class HttpLib2ErrorWithResponse(HttpLib2Error):
def __init__(self, desc, response, content):
self.response = response
self.content = content
HttpLib2Error.__init__(self, desc)
class RedirectMissingLocation(HttpLib2ErrorWithResponse):
pass
class RedirectLimit(HttpLib2ErrorWithResponse):
pass
class FailedToDecompressContent(HttpLib2ErrorWithResponse):
pass
class UnimplementedDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class UnimplementedHmacDigestAuthOptionError(HttpLib2ErrorWithResponse):
pass
class MalformedHeader(HttpLib2Error):
pass
class RelativeURIError(HttpLib2Error):
pass
class ServerNotFoundError(HttpLib2Error):
pass
class ProxiesUnavailableError(HttpLib2Error):
pass
class CertificateValidationUnsupported(HttpLib2Error):
pass
class SSLHandshakeError(HttpLib2Error):
pass
class NotSupportedOnThisPlatform(HttpLib2Error):
pass
class CertificateHostnameMismatch(SSLHandshakeError):
def __init__(self, desc, host, cert):
HttpLib2Error.__init__(self, desc)
self.host = host
self.cert = cert
class NotRunningAppEngineEnvironment(HttpLib2Error):
pass
# Open Items:
# -----------
# Proxy support
# Are we removing the cached content too soon on PUT (only delete on 200 Maybe?)
# Pluggable cache storage (supports storing the cache in
# flat files by default. We need a plug-in architecture
# that can support Berkeley DB and Squid)
# == Known Issues ==
# Does not handle a resource that uses conneg and Last-Modified but no ETag as a cache validator.
# Does not handle Cache-Control: max-stale
# Does not use Age: headers when calculating cache freshness.
# The number of redirections to follow before giving up.
# Note that only GET redirects are automatically followed.
# Will also honor 301 requests by saving that info and never
# requesting that URI again.
DEFAULT_MAX_REDIRECTS = 5
from httplib2 import certs
CA_CERTS = certs.where()
# Which headers are hop-by-hop headers by default
HOP_BY_HOP = [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
]
# https://tools.ietf.org/html/rfc7231#section-8.1.3
SAFE_METHODS = ("GET", "HEAD") # TODO add "OPTIONS", "TRACE"
# To change, assign to `Http().redirect_codes`
REDIRECT_CODES = frozenset((300, 301, 302, 303, 307, 308))
def _get_end2end_headers(response):
hopbyhop = list(HOP_BY_HOP)
hopbyhop.extend([x.strip() for x in response.get("connection", "").split(",")])
return [header for header in response.keys() if header not in hopbyhop]
URI = re.compile(r"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?")
def parse_uri(uri):
"""Parses a URI using the regex given in Appendix B of RFC 3986.
(scheme, authority, path, query, fragment) = parse_uri(uri)
"""
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8])
def urlnorm(uri):
(scheme, authority, path, query, fragment) = parse_uri(uri)
if not scheme or not authority:
raise RelativeURIError("Only absolute URIs are allowed. uri = %s" % uri)
authority = authority.lower()
scheme = scheme.lower()
if not path:
path = "/"
# Could do syntax based normalization of the URI before
# computing the digest. See Section 6.2.2 of Std 66.
request_uri = query and "?".join([path, query]) or path
scheme = scheme.lower()
defrag_uri = scheme + "://" + authority + request_uri
return scheme, authority, request_uri, defrag_uri
# Cache filename construction (original borrowed from Venus http://intertwingly.net/code/venus/)
re_url_scheme = re.compile(r"^\w+://")
re_unsafe = re.compile(r"[^\w\-_.()=!]+")
def safename(filename):
"""Return a filename suitable for the cache.
Strips dangerous and common characters to create a filename we
can use to store the cache in.
"""
if isinstance(filename, str):
filename_bytes = filename
filename = filename.decode("utf-8")
else:
filename_bytes = filename.encode("utf-8")
filemd5 = _md5(filename_bytes).hexdigest()
filename = re_url_scheme.sub("", filename)
filename = re_unsafe.sub("", filename)
# limit length of filename (vital for Windows)
# https://github.com/httplib2/httplib2/pull/74
# C:\Users\ <username> \AppData\Local\Temp\ <safe_filename> , <md5>
# 9 chars + max 104 chars + 20 chars + x + 1 + 32 = max 259 chars
# Thus max safe filename x = 93 chars. Let it be 90 to make a round sum:
filename = filename[:90]
return ",".join((filename, filemd5))
NORMALIZE_SPACE = re.compile(r"(?:\r\n)?[ \t]+")
def _normalize_headers(headers):
return dict(
[
(key.lower(), NORMALIZE_SPACE.sub(value, " ").strip())
for (key, value) in headers.iteritems()
]
)
def _parse_cache_control(headers):
retval = {}
if "cache-control" in headers:
parts = headers["cache-control"].split(",")
parts_with_args = [
tuple([x.strip().lower() for x in part.split("=", 1)])
for part in parts
if -1 != part.find("=")
]
parts_wo_args = [
(name.strip().lower(), 1) for name in parts if -1 == name.find("=")
]
retval = dict(parts_with_args + parts_wo_args)
return retval
# Whether to use a strict mode to parse WWW-Authenticate headers
# Might lead to bad results in case of ill-formed header value,
# so disabled by default, falling back to relaxed parsing.
# Set to true to turn on, usefull for testing servers.
USE_WWW_AUTH_STRICT_PARSING = 0
# In regex below:
# [^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+ matches a "token" as defined by HTTP
# "(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?" matches a "quoted-string" as defined by HTTP, when LWS have already been replaced by a single space
# Actually, as an auth-param value can be either a token or a quoted-string, they are combined in a single pattern which matches both:
# \"?((?<=\")(?:[^\0-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x08\x0A-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?
WWW_AUTH_STRICT = re.compile(
r"^(?:\s*(?:,\s*)?([^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+)\s*=\s*\"?((?<=\")(?:[^\0-\x08\x0A-\x1f\x7f-\xff\\\"]|\\[\0-\x7f])*?(?=\")|(?<!\")[^\0-\x1f\x7f-\xff()<>@,;:\\\"/[\]?={} \t]+(?!\"))\"?)(.*)$"
)
WWW_AUTH_RELAXED = re.compile(
r"^(?:\s*(?:,\s*)?([^ \t\r\n=]+)\s*=\s*\"?((?<=\")(?:[^\\\"]|\\.)*?(?=\")|(?<!\")[^ \t\r\n,]+(?!\"))\"?)(.*)$"
)
UNQUOTE_PAIRS = re.compile(r"\\(.)")
def _parse_www_authenticate(headers, headername="www-authenticate"):
"""Returns a dictionary of dictionaries, one dict
per auth_scheme."""
retval = {}
if headername in headers:
try:
authenticate = headers[headername].strip()
www_auth = (
USE_WWW_AUTH_STRICT_PARSING and WWW_AUTH_STRICT or WWW_AUTH_RELAXED
)
while authenticate:
# Break off the scheme at the beginning of the line
if headername == "authentication-info":
(auth_scheme, the_rest) = ("digest", authenticate)
else:
(auth_scheme, the_rest) = authenticate.split(" ", 1)
# Now loop over all the key value pairs that come after the scheme,
# being careful not to roll into the next scheme
match = www_auth.search(the_rest)
auth_params = {}
while match:
if match and len(match.groups()) == 3:
(key, value, the_rest) = match.groups()
auth_params[key.lower()] = UNQUOTE_PAIRS.sub(
r"\1", value
) # '\\'.join([x.replace('\\', '') for x in value.split('\\\\')])
match = www_auth.search(the_rest)
retval[auth_scheme.lower()] = auth_params
authenticate = the_rest.strip()
except ValueError:
raise MalformedHeader("WWW-Authenticate")
return retval
# TODO: add current time as _entry_disposition argument to avoid sleep in tests
def _entry_disposition(response_headers, request_headers):
"""Determine freshness from the Date, Expires and Cache-Control headers.
We don't handle the following:
1. Cache-Control: max-stale
2. Age: headers are not used in the calculations.
Not that this algorithm is simpler than you might think
because we are operating as a private (non-shared) cache.
This lets us ignore 's-maxage'. We can also ignore
'proxy-invalidate' since we aren't a proxy.
We will never return a stale document as
fresh as a design decision, and thus the non-implementation
of 'max-stale'. This also lets us safely ignore 'must-revalidate'
since we operate as if every server has sent 'must-revalidate'.
Since we are private we get to ignore both 'public' and
'private' parameters. We also ignore 'no-transform' since
we don't do any transformations.
The 'no-store' parameter is handled at a higher level.
So the only Cache-Control parameters we look at are:
no-cache
only-if-cached
max-age
min-fresh
"""
retval = "STALE"
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if (
"pragma" in request_headers
and request_headers["pragma"].lower().find("no-cache") != -1
):
retval = "TRANSPARENT"
if "cache-control" not in request_headers:
request_headers["cache-control"] = "no-cache"
elif "no-cache" in cc:
retval = "TRANSPARENT"
elif "no-cache" in cc_response:
retval = "STALE"
elif "only-if-cached" in cc:
retval = "FRESH"
elif "date" in response_headers:
date = calendar.timegm(email.Utils.parsedate_tz(response_headers["date"]))
now = time.time()
current_age = max(0, now - date)
if "max-age" in cc_response:
try:
freshness_lifetime = int(cc_response["max-age"])
except ValueError:
freshness_lifetime = 0
elif "expires" in response_headers:
expires = email.Utils.parsedate_tz(response_headers["expires"])
if None == expires:
freshness_lifetime = 0
else:
freshness_lifetime = max(0, calendar.timegm(expires) - date)
else:
freshness_lifetime = 0
if "max-age" in cc:
try:
freshness_lifetime = int(cc["max-age"])
except ValueError:
freshness_lifetime = 0
if "min-fresh" in cc:
try:
min_fresh = int(cc["min-fresh"])
except ValueError:
min_fresh = 0
current_age += min_fresh
if freshness_lifetime > current_age:
retval = "FRESH"
return retval
def _decompressContent(response, new_content):
content = new_content
try:
encoding = response.get("content-encoding", None)
if encoding in ["gzip", "deflate"]:
if encoding == "gzip":
content = gzip.GzipFile(fileobj=StringIO.StringIO(new_content)).read()
if encoding == "deflate":
content = zlib.decompress(content, -zlib.MAX_WBITS)
response["content-length"] = str(len(content))
# Record the historical presence of the encoding in a way the won't interfere.
response["-content-encoding"] = response["content-encoding"]
del response["content-encoding"]
except (IOError, zlib.error):
content = ""
raise FailedToDecompressContent(
_("Content purported to be compressed with %s but failed to decompress.")
% response.get("content-encoding"),
response,
content,
)
return content
def _updateCache(request_headers, response_headers, content, cache, cachekey):
if cachekey:
cc = _parse_cache_control(request_headers)
cc_response = _parse_cache_control(response_headers)
if "no-store" in cc or "no-store" in cc_response:
cache.delete(cachekey)
else:
info = email.Message.Message()
for key, value in response_headers.iteritems():
if key not in ["status", "content-encoding", "transfer-encoding"]:
info[key] = value
# Add annotations to the cache to indicate what headers
# are variant for this request.
vary = response_headers.get("vary", None)
if vary:
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
try:
info[key] = request_headers[header]
except KeyError:
pass
status = response_headers.status
if status == 304:
status = 200
status_header = "status: %d\r\n" % status
header_str = info.as_string()
header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str)
text = "".join([status_header, header_str, content])
cache.set(cachekey, text)
def _cnonce():
dig = _md5(
"%s:%s"
% (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)])
).hexdigest()
return dig[:16]
def _wsse_username_token(cnonce, iso_now, password):
return base64.b64encode(
_sha("%s%s%s" % (cnonce, iso_now, password)).digest()
).strip()
# For credentials we need two things, first
# a pool of credential to try (not necesarily tied to BAsic, Digest, etc.)
# Then we also need a list of URIs that have already demanded authentication
# That list is tricky since sub-URIs can take the same auth, or the
# auth scheme may change as you descend the tree.
# So we also need each Auth instance to be able to tell us
# how close to the 'top' it is.
class Authentication(object):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
self.path = path
self.host = host
self.credentials = credentials
self.http = http
def depth(self, request_uri):
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return request_uri[len(self.path) :].count("/")
def inscope(self, host, request_uri):
# XXX Should we normalize the request_uri?
(scheme, authority, path, query, fragment) = parse_uri(request_uri)
return (host == self.host) and path.startswith(self.path)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header. Over-ride this in sub-classes."""
pass
def response(self, response, content):
"""Gives us a chance to update with new nonces
or such returned from the last authorized response.
Over-rise this in sub-classes if necessary.
Return TRUE is the request is to be retried, for
example Digest may return stale=true.
"""
return False
class BasicAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = (
"Basic " + base64.b64encode("%s:%s" % self.credentials).strip()
)
class DigestAuthentication(Authentication):
"""Only do qop='auth' and MD5, since that
is all Apache currently implements"""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["digest"]
qop = self.challenge.get("qop", "auth")
self.challenge["qop"] = (
("auth" in [x.strip() for x in qop.split()]) and "auth" or None
)
if self.challenge["qop"] is None:
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for qop: %s." % qop)
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "MD5").upper()
if self.challenge["algorithm"] != "MD5":
raise UnimplementedDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.A1 = "".join(
[
self.credentials[0],
":",
self.challenge["realm"],
":",
self.credentials[1],
]
)
self.challenge["nc"] = 1
def request(self, method, request_uri, headers, content, cnonce=None):
"""Modify the request headers"""
H = lambda x: _md5(x).hexdigest()
KD = lambda s, d: H("%s:%s" % (s, d))
A2 = "".join([method, ":", request_uri])
self.challenge["cnonce"] = cnonce or _cnonce()
request_digest = '"%s"' % KD(
H(self.A1),
"%s:%s:%s:%s:%s"
% (
self.challenge["nonce"],
"%08x" % self.challenge["nc"],
self.challenge["cnonce"],
self.challenge["qop"],
H(A2),
),
)
headers["authorization"] = (
'Digest username="%s", realm="%s", nonce="%s", '
'uri="%s", algorithm=%s, response=%s, qop=%s, '
'nc=%08x, cnonce="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["nonce"],
request_uri,
self.challenge["algorithm"],
request_digest,
self.challenge["qop"],
self.challenge["nc"],
self.challenge["cnonce"],
)
if self.challenge.get("opaque"):
headers["authorization"] += ', opaque="%s"' % self.challenge["opaque"]
self.challenge["nc"] += 1
def response(self, response, content):
if "authentication-info" not in response:
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"digest", {}
)
if "true" == challenge.get("stale"):
self.challenge["nonce"] = challenge["nonce"]
self.challenge["nc"] = 1
return True
else:
updated_challenge = _parse_www_authenticate(
response, "authentication-info"
).get("digest", {})
if "nextnonce" in updated_challenge:
self.challenge["nonce"] = updated_challenge["nextnonce"]
self.challenge["nc"] = 1
return False
class HmacDigestAuthentication(Authentication):
"""Adapted from Robert Sayre's code and DigestAuthentication above."""
__author__ = "Thomas Broyer (t.broyer@ltgt.net)"
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
self.challenge = challenge["hmacdigest"]
# TODO: self.challenge['domain']
self.challenge["reason"] = self.challenge.get("reason", "unauthorized")
if self.challenge["reason"] not in ["unauthorized", "integrity"]:
self.challenge["reason"] = "unauthorized"
self.challenge["salt"] = self.challenge.get("salt", "")
if not self.challenge.get("snonce"):
raise UnimplementedHmacDigestAuthOptionError(
_("The challenge doesn't contain a server nonce, or this one is empty.")
)
self.challenge["algorithm"] = self.challenge.get("algorithm", "HMAC-SHA-1")
if self.challenge["algorithm"] not in ["HMAC-SHA-1", "HMAC-MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_("Unsupported value for algorithm: %s." % self.challenge["algorithm"])
)
self.challenge["pw-algorithm"] = self.challenge.get("pw-algorithm", "SHA-1")
if self.challenge["pw-algorithm"] not in ["SHA-1", "MD5"]:
raise UnimplementedHmacDigestAuthOptionError(
_(
"Unsupported value for pw-algorithm: %s."
% self.challenge["pw-algorithm"]
)
)
if self.challenge["algorithm"] == "HMAC-MD5":
self.hashmod = _md5
else:
self.hashmod = _sha
if self.challenge["pw-algorithm"] == "MD5":
self.pwhashmod = _md5
else:
self.pwhashmod = _sha
self.key = "".join(
[
self.credentials[0],
":",
self.pwhashmod.new(
"".join([self.credentials[1], self.challenge["salt"]])
)
.hexdigest()
.lower(),
":",
self.challenge["realm"],
]
)
self.key = self.pwhashmod.new(self.key).hexdigest().lower()
def request(self, method, request_uri, headers, content):
"""Modify the request headers"""
keys = _get_end2end_headers(headers)
keylist = "".join(["%s " % k for k in keys])
headers_val = "".join([headers[k] for k in keys])
created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
request_digest = "%s:%s:%s:%s:%s" % (
method,
request_uri,
cnonce,
self.challenge["snonce"],
headers_val,
)
request_digest = (
hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower()
)
headers["authorization"] = (
'HMACDigest username="%s", realm="%s", snonce="%s",'
' cnonce="%s", uri="%s", created="%s", '
'response="%s", headers="%s"'
) % (
self.credentials[0],
self.challenge["realm"],
self.challenge["snonce"],
cnonce,
request_uri,
created,
request_digest,
keylist,
)
def response(self, response, content):
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"hmacdigest", {}
)
if challenge.get("reason") in ["integrity", "stale"]:
return True
return False
class WsseAuthentication(Authentication):
"""This is thinly tested and should not be relied upon.
At this time there isn't any third party server to test against.
Blogger and TypePad implemented this algorithm at one point
but Blogger has since switched to Basic over HTTPS and
TypePad has implemented it wrong, by never issuing a 401
challenge but instead requiring your client to telepathically know that
their endpoint is expecting WSSE profile="UsernameToken"."""
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = 'WSSE profile="UsernameToken"'
iso_now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
cnonce = _cnonce()
password_digest = _wsse_username_token(cnonce, iso_now, self.credentials[1])
headers["X-WSSE"] = (
'UsernameToken Username="%s", PasswordDigest="%s", '
'Nonce="%s", Created="%s"'
) % (self.credentials[0], password_digest, cnonce, iso_now)
class GoogleLoginAuthentication(Authentication):
def __init__(
self, credentials, host, request_uri, headers, response, content, http
):
from urllib import urlencode
Authentication.__init__(
self, credentials, host, request_uri, headers, response, content, http
)
challenge = _parse_www_authenticate(response, "www-authenticate")
service = challenge["googlelogin"].get("service", "xapi")
# Bloggger actually returns the service in the challenge
# For the rest we guess based on the URI
if service == "xapi" and request_uri.find("calendar") > 0:
service = "cl"
# No point in guessing Base or Spreadsheet
# elif request_uri.find("spreadsheets") > 0:
# service = "wise"
auth = dict(
Email=credentials[0],
Passwd=credentials[1],
service=service,
source=headers["user-agent"],
)
resp, content = self.http.request(
"https://www.google.com/accounts/ClientLogin",
method="POST",
body=urlencode(auth),
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
lines = content.split("\n")
d = dict([tuple(line.split("=", 1)) for line in lines if line])
if resp.status == 403:
self.Auth = ""
else:
self.Auth = d["Auth"]
def request(self, method, request_uri, headers, content):
"""Modify the request headers to add the appropriate
Authorization header."""
headers["authorization"] = "GoogleLogin Auth=" + self.Auth
AUTH_SCHEME_CLASSES = {
"basic": BasicAuthentication,
"wsse": WsseAuthentication,
"digest": DigestAuthentication,
"hmacdigest": HmacDigestAuthentication,
"googlelogin": GoogleLoginAuthentication,
}
AUTH_SCHEME_ORDER = ["hmacdigest", "googlelogin", "digest", "wsse", "basic"]
class FileCache(object):
"""Uses a local directory as a store for cached files.
Not really safe to use if multiple threads or processes are going to
be running on the same cache.
"""
def __init__(
self, cache, safe=safename
): # use safe=lambda x: md5.new(x).hexdigest() for the old behavior
self.cache = cache
self.safe = safe
if not os.path.exists(cache):
os.makedirs(self.cache)
def get(self, key):
retval = None
cacheFullPath = os.path.join(self.cache, self.safe(key))
try:
f = file(cacheFullPath, "rb")
retval = f.read()
f.close()
except IOError:
pass
return retval
def set(self, key, value):
cacheFullPath = os.path.join(self.cache, self.safe(key))
f = file(cacheFullPath, "wb")
f.write(value)
f.close()
def delete(self, key):
cacheFullPath = os.path.join(self.cache, self.safe(key))
if os.path.exists(cacheFullPath):
os.remove(cacheFullPath)
class Credentials(object):
def __init__(self):
self.credentials = []
def add(self, name, password, domain=""):
self.credentials.append((domain.lower(), name, password))
def clear(self):
self.credentials = []
def iter(self, domain):
for (cdomain, name, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (name, password)
class KeyCerts(Credentials):
"""Identical to Credentials except that
name/password are mapped to key/cert."""
def add(self, key, cert, domain, password):
self.credentials.append((domain.lower(), key, cert, password))
def iter(self, domain):
for (cdomain, key, cert, password) in self.credentials:
if cdomain == "" or domain == cdomain:
yield (key, cert, password)
class AllHosts(object):
pass
class ProxyInfo(object):
"""Collect information required to use a proxy."""
bypass_hosts = ()
def __init__(
self,
proxy_type,
proxy_host,
proxy_port,
proxy_rdns=True,
proxy_user=None,
proxy_pass=None,
proxy_headers=None,
):
"""Args:
proxy_type: The type of proxy server. This must be set to one of
socks.PROXY_TYPE_XXX constants. For example: p =
ProxyInfo(proxy_type=socks.PROXY_TYPE_HTTP, proxy_host='localhost',
proxy_port=8000)
proxy_host: The hostname or IP address of the proxy server.
proxy_port: The port that the proxy server is running on.
proxy_rdns: If True (default), DNS queries will not be performed
locally, and instead, handed to the proxy to resolve. This is useful
if the network does not allow resolution of non-local names. In
httplib2 0.9 and earlier, this defaulted to False.
proxy_user: The username used to authenticate with the proxy server.
proxy_pass: The password used to authenticate with the proxy server.
proxy_headers: Additional or modified headers for the proxy connect
request.
"""
self.proxy_type = proxy_type
self.proxy_host = proxy_host
self.proxy_port = proxy_port
self.proxy_rdns = proxy_rdns
self.proxy_user = proxy_user
self.proxy_pass = proxy_pass
self.proxy_headers = proxy_headers
def astuple(self):
return (
self.proxy_type,
self.proxy_host,
self.proxy_port,
self.proxy_rdns,
self.proxy_user,
self.proxy_pass,
self.proxy_headers,
)
def isgood(self):
return (self.proxy_host != None) and (self.proxy_port != None)
def applies_to(self, hostname):
return not self.bypass_host(hostname)
def bypass_host(self, hostname):
"""Has this host been excluded from the proxy config"""
if self.bypass_hosts is AllHosts:
return True
hostname = "." + hostname.lstrip(".")
for skip_name in self.bypass_hosts:
# *.suffix
if skip_name.startswith(".") and hostname.endswith(skip_name):
return True
# exact match
if hostname == "." + skip_name:
return True
return False
def __repr__(self):
return (
"<ProxyInfo type={p.proxy_type} "
"host:port={p.proxy_host}:{p.proxy_port} rdns={p.proxy_rdns}"
+ " user={p.proxy_user} headers={p.proxy_headers}>"
).format(p=self)
def proxy_info_from_environment(method="http"):
"""Read proxy info from the environment variables.
"""
if method not in ["http", "https"]:
return
env_var = method + "_proxy"
url = os.environ.get(env_var, os.environ.get(env_var.upper()))
if not url:
return
return proxy_info_from_url(url, method, None)
def proxy_info_from_url(url, method="http", noproxy=None):
"""Construct a ProxyInfo from a URL (such as http_proxy env var)
"""
url = urlparse.urlparse(url)
username = None
password = None
port = None
if "@" in url[1]:
ident, host_port = url[1].split("@", 1)
if ":" in ident:
username, password = ident.split(":", 1)
else:
password = ident
else:
host_port = url[1]
if ":" in host_port:
host, port = host_port.split(":", 1)
else:
host = host_port
if port:
port = int(port)
else:
port = dict(https=443, http=80)[method]
proxy_type = 3 # socks.PROXY_TYPE_HTTP
pi = ProxyInfo(
proxy_type=proxy_type,
proxy_host=host,
proxy_port=port,
proxy_user=username or None,
proxy_pass=password or None,
proxy_headers=None,
)
bypass_hosts = []
# If not given an explicit noproxy value, respect values in env vars.
if noproxy is None:
noproxy = os.environ.get("no_proxy", os.environ.get("NO_PROXY", ""))
# Special case: A single '*' character means all hosts should be bypassed.
if noproxy == "*":
bypass_hosts = AllHosts
elif noproxy.strip():
bypass_hosts = noproxy.split(",")
bypass_hosts = filter(bool, bypass_hosts) # To exclude empty string.
pi.bypass_hosts = bypass_hosts
return pi
class HTTPConnectionWithTimeout(httplib.HTTPConnection):
"""HTTPConnection subclass that supports timeouts
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(self, host, port=None, strict=None, timeout=None, proxy_info=None):
httplib.HTTPConnection.__init__(self, host, port, strict)
self.timeout = timeout
self.proxy_info = proxy_info
def connect(self):
"""Connect to the host and port specified in __init__."""
# Mostly verbatim from httplib.py.
if self.proxy_info and socks is None:
raise ProxiesUnavailableError(
"Proxy support missing but proxy use was requested!"
)
if self.proxy_info and self.proxy_info.isgood():
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_port
else:
use_proxy = False
host = self.host
port = self.port
socket_err = None
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
if use_proxy:
self.sock = socks.socksocket(af, socktype, proto)
self.sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
else:
self.sock = socket.socket(af, socktype, proto)
self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
# Different from httplib: support timeouts.
if has_timeout(self.timeout):
self.sock.settimeout(self.timeout)
# End of difference from httplib.
if self.debuglevel > 0:
print("connect: (%s, %s) ************" % (self.host, self.port))
if use_proxy:
print(
"proxy: %s ************"
% str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
if use_proxy:
self.sock.connect((self.host, self.port) + sa[2:])
else:
self.sock.connect(sa)
except socket.error as e:
socket_err = e
if self.debuglevel > 0:
print("connect fail: (%s, %s)" % (self.host, self.port))
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket_err or socket.error("getaddrinfo returns an empty list")
class HTTPSConnectionWithTimeout(httplib.HTTPSConnection):
"""This class allows communication via SSL.
All timeouts are in seconds. If None is passed for timeout then
Python's default timeout for sockets will be used. See for example
the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
ca_certs=None,
disable_ssl_certificate_validation=False,
ssl_version=None,
key_password=None,
):
if key_password:
httplib.HTTPSConnection.__init__(self, host, port=port, strict=strict)
self._context.load_cert_chain(cert_file, key_file, key_password)
self.key_file = key_file
self.cert_file = cert_file
self.key_password = key_password
else:
httplib.HTTPSConnection.__init__(
self, host, port=port, key_file=key_file, cert_file=cert_file, strict=strict
)
self.key_password = None
self.timeout = timeout
self.proxy_info = proxy_info
if ca_certs is None:
ca_certs = CA_CERTS
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.ssl_version = ssl_version
# The following two methods were adapted from https_wrapper.py, released
# with the Google Appengine SDK at
# http://googleappengine.googlecode.com/svn-history/r136/trunk/python/google/appengine/tools/https_wrapper.py
# under the following license:
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
def _GetValidHostsForCert(self, cert):
"""Returns a list of valid host globs for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
Returns:
list: A list of valid host globs.
"""
if "subjectAltName" in cert:
return [x[1] for x in cert["subjectAltName"] if x[0].lower() == "dns"]
else:
return [x[0][1] for x in cert["subject"] if x[0][0].lower() == "commonname"]
def _ValidateCertificateHostname(self, cert, hostname):
"""Validates that a given hostname is valid for an SSL certificate.
Args:
cert: A dictionary representing an SSL certificate.
hostname: The hostname to test.
Returns:
bool: Whether or not the hostname is valid for this certificate.
"""
hosts = self._GetValidHostsForCert(cert)
for host in hosts:
host_re = host.replace(".", "\.").replace("*", "[^.]*")
if re.search("^%s$" % (host_re,), hostname, re.I):
return True
return False
def connect(self):
"Connect to a host on a given (SSL) port."
if self.proxy_info and self.proxy_info.isgood():
use_proxy = True
proxy_type, proxy_host, proxy_port, proxy_rdns, proxy_user, proxy_pass, proxy_headers = (
self.proxy_info.astuple()
)
host = proxy_host
port = proxy_port
else:
use_proxy = False
host = self.host
port = self.port
socket_err = None
address_info = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
for family, socktype, proto, canonname, sockaddr in address_info:
try:
if use_proxy:
sock = socks.socksocket(family, socktype, proto)
sock.setproxy(
proxy_type,
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
else:
sock = socket.socket(family, socktype, proto)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
if has_timeout(self.timeout):
sock.settimeout(self.timeout)
if use_proxy:
sock.connect((self.host, self.port) + sockaddr[:2])
else:
sock.connect(sockaddr)
self.sock = _ssl_wrap_socket(
sock,
self.key_file,
self.cert_file,
self.disable_ssl_certificate_validation,
self.ca_certs,
self.ssl_version,
self.host,
self.key_password,
)
if self.debuglevel > 0:
print("connect: (%s, %s)" % (self.host, self.port))
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
if not self.disable_ssl_certificate_validation:
cert = self.sock.getpeercert()
hostname = self.host.split(":", 0)[0]
if not self._ValidateCertificateHostname(cert, hostname):
raise CertificateHostnameMismatch(
"Server presented certificate that does not match "
"host %s: %s" % (hostname, cert),
hostname,
cert,
)
except (
ssl_SSLError,
ssl_CertificateError,
CertificateHostnameMismatch,
) as e:
if sock:
sock.close()
if self.sock:
self.sock.close()
self.sock = None
# Unfortunately the ssl module doesn't seem to provide any way
# to get at more detailed error information, in particular
# whether the error is due to certificate validation or
# something else (such as SSL protocol mismatch).
if getattr(e, "errno", None) == ssl.SSL_ERROR_SSL:
raise SSLHandshakeError(e)
else:
raise
except (socket.timeout, socket.gaierror):
raise
except socket.error as e:
socket_err = e
if self.debuglevel > 0:
print("connect fail: (%s, %s)" % (self.host, self.port))
if use_proxy:
print(
"proxy: %s"
% str(
(
proxy_host,
proxy_port,
proxy_rdns,
proxy_user,
proxy_pass,
proxy_headers,
)
)
)
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket_err or socket.error("getaddrinfo returns an empty list")
SCHEME_TO_CONNECTION = {
"http": HTTPConnectionWithTimeout,
"https": HTTPSConnectionWithTimeout,
}
def _new_fixed_fetch(validate_certificate):
def fixed_fetch(
url,
payload=None,
method="GET",
headers={},
allow_truncated=False,
follow_redirects=True,
deadline=None,
):
return fetch(
url,
payload=payload,
method=method,
headers=headers,
allow_truncated=allow_truncated,
follow_redirects=follow_redirects,
deadline=deadline,
validate_certificate=validate_certificate,
)
return fixed_fetch
class AppEngineHttpConnection(httplib.HTTPConnection):
"""Use httplib on App Engine, but compensate for its weirdness.
The parameters key_file, cert_file, proxy_info, ca_certs,
disable_ssl_certificate_validation, and ssl_version are all dropped on
the ground.
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
ca_certs=None,
disable_ssl_certificate_validation=False,
ssl_version=None,
):
httplib.HTTPConnection.__init__(
self, host, port=port, strict=strict, timeout=timeout
)
class AppEngineHttpsConnection(httplib.HTTPSConnection):
"""Same as AppEngineHttpConnection, but for HTTPS URIs.
The parameters proxy_info, ca_certs, disable_ssl_certificate_validation,
and ssl_version are all dropped on the ground.
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
ca_certs=None,
disable_ssl_certificate_validation=False,
ssl_version=None,
key_password=None,
):
if key_password:
raise NotSupportedOnThisPlatform("Certificate with password is not supported.")
httplib.HTTPSConnection.__init__(
self,
host,
port=port,
key_file=key_file,
cert_file=cert_file,
strict=strict,
timeout=timeout,
)
self._fetch = _new_fixed_fetch(not disable_ssl_certificate_validation)
# Use a different connection object for Google App Engine Standard Environment.
def is_gae_instance():
server_software = os.environ.get('SERVER_SOFTWARE', '')
if (server_software.startswith('Google App Engine/') or
server_software.startswith('Development/') or
server_software.startswith('testutil/')):
return True
return False
try:
if not is_gae_instance():
raise NotRunningAppEngineEnvironment()
from google.appengine.api import apiproxy_stub_map
if apiproxy_stub_map.apiproxy.GetStub("urlfetch") is None:
raise ImportError
from google.appengine.api.urlfetch import fetch
# Update the connection classes to use the Googel App Engine specific ones.
SCHEME_TO_CONNECTION = {
"http": AppEngineHttpConnection,
"https": AppEngineHttpsConnection,
}
except (ImportError, NotRunningAppEngineEnvironment):
pass
class Http(object):
"""An HTTP client that handles:
- all methods
- caching
- ETags
- compression,
- HTTPS
- Basic
- Digest
- WSSE
and more.
"""
def __init__(
self,
cache=None,
timeout=None,
proxy_info=proxy_info_from_environment,
ca_certs=None,
disable_ssl_certificate_validation=False,
ssl_version=None,
):
"""If 'cache' is a string then it is used as a directory name for
a disk cache. Otherwise it must be an object that supports the
same interface as FileCache.
All timeouts are in seconds. If None is passed for timeout
then Python's default timeout for sockets will be used. See
for example the docs of socket.setdefaulttimeout():
http://docs.python.org/library/socket.html#socket.setdefaulttimeout
`proxy_info` may be:
- a callable that takes the http scheme ('http' or 'https') and
returns a ProxyInfo instance per request. By default, uses
proxy_nfo_from_environment.
- a ProxyInfo instance (static proxy config).
- None (proxy disabled).
ca_certs is the path of a file containing root CA certificates for SSL
server certificate validation. By default, a CA cert file bundled with
httplib2 is used.
If disable_ssl_certificate_validation is true, SSL cert validation will
not be performed.
By default, ssl.PROTOCOL_SSLv23 will be used for the ssl version.
"""
self.proxy_info = proxy_info
self.ca_certs = ca_certs
self.disable_ssl_certificate_validation = disable_ssl_certificate_validation
self.ssl_version = ssl_version
# Map domain name to an httplib connection
self.connections = {}
# The location of the cache, for now a directory
# where cached responses are held.
if cache and isinstance(cache, basestring):
self.cache = FileCache(cache)
else:
self.cache = cache
# Name/password
self.credentials = Credentials()
# Key/cert
self.certificates = KeyCerts()
# authorization objects
self.authorizations = []
# If set to False then no redirects are followed, even safe ones.
self.follow_redirects = True
self.redirect_codes = REDIRECT_CODES
# Which HTTP methods do we apply optimistic concurrency to, i.e.
# which methods get an "if-match:" etag header added to them.
self.optimistic_concurrency_methods = ["PUT", "PATCH"]
self.safe_methods = list(SAFE_METHODS)
# If 'follow_redirects' is True, and this is set to True then
# all redirecs are followed, including unsafe ones.
self.follow_all_redirects = False
self.ignore_etag = False
self.force_exception_to_status_code = False
self.timeout = timeout
# Keep Authorization: headers on a redirect.
self.forward_authorization_headers = False
def close(self):
"""Close persistent connections, clear sensitive data.
Not thread-safe, requires external synchronization against concurrent requests.
"""
existing, self.connections = self.connections, {}
for _, c in existing.iteritems():
c.close()
self.certificates.clear()
self.clear_credentials()
def __getstate__(self):
state_dict = copy.copy(self.__dict__)
# In case request is augmented by some foreign object such as
# credentials which handle auth
if "request" in state_dict:
del state_dict["request"]
if "connections" in state_dict:
del state_dict["connections"]
return state_dict
def __setstate__(self, state):
self.__dict__.update(state)
self.connections = {}
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if scheme in challenges:
yield AUTH_SCHEME_CLASSES[scheme](
cred, host, request_uri, headers, response, content, self
)
def add_credentials(self, name, password, domain=""):
"""Add a name and password that will be used
any time a request requires authentication."""
self.credentials.add(name, password, domain)
def add_certificate(self, key, cert, domain, password=None):
"""Add a key and cert that will be used
any time a request requires authentication."""
self.certificates.add(key, cert, domain, password)
def clear_credentials(self):
"""Remove all the names and passwords
that are used for authentication"""
self.credentials.clear()
self.authorizations = []
def _conn_request(self, conn, request_uri, method, body, headers):
i = 0
seen_bad_status_line = False
while i < RETRIES:
i += 1
try:
if hasattr(conn, "sock") and conn.sock is None:
conn.connect()
conn.request(method, request_uri, body, headers)
except socket.timeout:
raise
except socket.gaierror:
conn.close()
raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
except ssl_SSLError:
conn.close()
raise
except socket.error as e:
err = 0
if hasattr(e, "args"):
err = getattr(e, "args")[0]
else:
err = e.errno
if err == errno.ECONNREFUSED: # Connection refused
raise
if err in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
continue # retry on potentially transient socket errors
except httplib.HTTPException:
# Just because the server closed the connection doesn't apparently mean
# that the server didn't send a response.
if hasattr(conn, "sock") and conn.sock is None:
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
try:
response = conn.getresponse()
except httplib.BadStatusLine:
# If we get a BadStatusLine on the first try then that means
# the connection just went stale, so retry regardless of the
# number of RETRIES set.
if not seen_bad_status_line and i == 1:
i = 0
seen_bad_status_line = True
conn.close()
conn.connect()
continue
else:
conn.close()
raise
except (socket.error, httplib.HTTPException):
if i < RETRIES - 1:
conn.close()
conn.connect()
continue
else:
conn.close()
raise
else:
content = ""
if method == "HEAD":
conn.close()
else:
content = response.read()
response = Response(response)
if method != "HEAD":
content = _decompressContent(response, content)
break
return (response, content)
def _request(
self,
conn,
host,
absolute_uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
):
"""Do the actual request using the connection object
and also follow one level of redirects if necessary"""
auths = [
(auth.depth(request_uri), auth)
for auth in self.authorizations
if auth.inscope(host, request_uri)
]
auth = auths and sorted(auths)[0][1] or None
if auth:
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
if auth:
if auth.response(response, body):
auth.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
response._stale_digest = 1
if response.status == 401:
for authorization in self._auth_from_challenge(
host, request_uri, headers, response, content
):
authorization.request(method, request_uri, headers, body)
(response, content) = self._conn_request(
conn, request_uri, method, body, headers
)
if response.status != 401:
self.authorizations.append(authorization)
authorization.response(response, body)
break
if (
self.follow_all_redirects
or method in self.safe_methods
or response.status in (303, 308)
):
if self.follow_redirects and response.status in self.redirect_codes:
# Pick out the location header and basically start from the beginning
# remembering first to strip the ETag header and decrement our 'depth'
if redirections:
if "location" not in response and response.status != 300:
raise RedirectMissingLocation(
_(
"Redirected but the response is missing a Location: header."
),
response,
content,
)
# Fix-up relative redirects (which violate an RFC 2616 MUST)
if "location" in response:
location = response["location"]
(scheme, authority, path, query, fragment) = parse_uri(location)
if authority == None:
response["location"] = urlparse.urljoin(
absolute_uri, location
)
if response.status == 308 or (response.status == 301 and method in self.safe_methods):
response["-x-permanent-redirect-url"] = response["location"]
if "content-location" not in response:
response["content-location"] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
if "if-none-match" in headers:
del headers["if-none-match"]
if "if-modified-since" in headers:
del headers["if-modified-since"]
if (
"authorization" in headers
and not self.forward_authorization_headers
):
del headers["authorization"]
if "location" in response:
location = response["location"]
old_response = copy.deepcopy(response)
if "content-location" not in old_response:
old_response["content-location"] = absolute_uri
redirect_method = method
if response.status in [302, 303]:
redirect_method = "GET"
body = None
(response, content) = self.request(
location,
method=redirect_method,
body=body,
headers=headers,
redirections=redirections - 1,
)
response.previous = old_response
else:
raise RedirectLimit(
"Redirected more times than rediection_limit allows.",
response,
content,
)
elif response.status in [200, 203] and method in self.safe_methods:
# Don't cache 206's since we aren't going to handle byte range requests
if "content-location" not in response:
response["content-location"] = absolute_uri
_updateCache(headers, response, content, self.cache, cachekey)
return (response, content)
def _normalize_headers(self, headers):
return _normalize_headers(headers)
# Need to catch and rebrand some exceptions
# Then need to optionally turn all exceptions into status codes
# including all socket.* and httplib.* exceptions.
def request(
self,
uri,
method="GET",
body=None,
headers=None,
redirections=DEFAULT_MAX_REDIRECTS,
connection_type=None,
):
""" Performs a single HTTP request.
The 'uri' is the URI of the HTTP resource and can begin with either
'http' or 'https'. The value of 'uri' must be an absolute URI.
The 'method' is the HTTP method to perform, such as GET, POST, DELETE,
etc. There is no restriction on the methods allowed.
The 'body' is the entity body to be sent with the request. It is a
string object.
Any extra headers that are to be sent with the request should be
provided in the 'headers' dictionary.
The maximum number of redirect to follow before raising an
exception is 'redirections. The default is 5.
The return value is a tuple of (response, content), the first
being and instance of the 'Response' class, the second being
a string that contains the response entity body.
"""
conn_key = ''
try:
if headers is None:
headers = {}
else:
headers = self._normalize_headers(headers)
if "user-agent" not in headers:
headers["user-agent"] = "Python-httplib2/%s (gzip)" % __version__
uri = iri2uri(uri)
(scheme, authority, request_uri, defrag_uri) = urlnorm(uri)
proxy_info = self._get_proxy_info(scheme, authority)
conn_key = scheme + ":" + authority
conn = self.connections.get(conn_key)
if conn is None:
if not connection_type:
connection_type = SCHEME_TO_CONNECTION[scheme]
certs = list(self.certificates.iter(authority))
if scheme == "https":
if certs:
conn = self.connections[conn_key] = connection_type(
authority,
key_file=certs[0][0],
cert_file=certs[0][1],
timeout=self.timeout,
proxy_info=proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
ssl_version=self.ssl_version,
key_password=certs[0][2],
)
else:
conn = self.connections[conn_key] = connection_type(
authority,
timeout=self.timeout,
proxy_info=proxy_info,
ca_certs=self.ca_certs,
disable_ssl_certificate_validation=self.disable_ssl_certificate_validation,
ssl_version=self.ssl_version,
)
else:
conn = self.connections[conn_key] = connection_type(
authority, timeout=self.timeout, proxy_info=proxy_info
)
conn.set_debuglevel(debuglevel)
if "range" not in headers and "accept-encoding" not in headers:
headers["accept-encoding"] = "gzip, deflate"
info = email.Message.Message()
cachekey = None
cached_value = None
if self.cache:
cachekey = defrag_uri.encode("utf-8")
cached_value = self.cache.get(cachekey)
if cached_value:
# info = email.message_from_string(cached_value)
#
# Need to replace the line above with the kludge below
# to fix the non-existent bug not fixed in this
# bug report: http://mail.python.org/pipermail/python-bugs-list/2005-September/030289.html
try:
info, content = cached_value.split("\r\n\r\n", 1)
feedparser = email.FeedParser.FeedParser()
feedparser.feed(info)
info = feedparser.close()
feedparser._parse = None
except (IndexError, ValueError):
self.cache.delete(cachekey)
cachekey = None
cached_value = None
if (
method in self.optimistic_concurrency_methods
and self.cache
and "etag" in info
and not self.ignore_etag
and "if-match" not in headers
):
# http://www.w3.org/1999/04/Editing/
headers["if-match"] = info["etag"]
# https://tools.ietf.org/html/rfc7234
# A cache MUST invalidate the effective Request URI as well as [...] Location and Content-Location
# when a non-error status code is received in response to an unsafe request method.
if self.cache and cachekey and method not in self.safe_methods:
self.cache.delete(cachekey)
# Check the vary header in the cache to see if this request
# matches what varies in the cache.
if method in self.safe_methods and "vary" in info:
vary = info["vary"]
vary_headers = vary.lower().replace(" ", "").split(",")
for header in vary_headers:
key = "-varied-%s" % header
value = info[key]
if headers.get(header, None) != value:
cached_value = None
break
if (
self.cache
and cached_value
and (method in self.safe_methods or info["status"] == "308")
and "range" not in headers
):
redirect_method = method
if info["status"] not in ("307", "308"):
redirect_method = "GET"
if "-x-permanent-redirect-url" in info:
# Should cached permanent redirects be counted in our redirection count? For now, yes.
if redirections <= 0:
raise RedirectLimit(
"Redirected more times than rediection_limit allows.",
{},
"",
)
(response, new_content) = self.request(
info["-x-permanent-redirect-url"],
method=redirect_method,
headers=headers,
redirections=redirections - 1,
)
response.previous = Response(info)
response.previous.fromcache = True
else:
# Determine our course of action:
# Is the cached entry fresh or stale?
# Has the client requested a non-cached response?
#
# There seems to be three possible answers:
# 1. [FRESH] Return the cache entry w/o doing a GET
# 2. [STALE] Do the GET (but add in cache validators if available)
# 3. [TRANSPARENT] Do a GET w/o any cache validators (Cache-Control: no-cache) on the request
entry_disposition = _entry_disposition(info, headers)
if entry_disposition == "FRESH":
if not cached_value:
info["status"] = "504"
content = ""
response = Response(info)
if cached_value:
response.fromcache = True
return (response, content)
if entry_disposition == "STALE":
if (
"etag" in info
and not self.ignore_etag
and not "if-none-match" in headers
):
headers["if-none-match"] = info["etag"]
if "last-modified" in info and not "last-modified" in headers:
headers["if-modified-since"] = info["last-modified"]
elif entry_disposition == "TRANSPARENT":
pass
(response, new_content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
)
if response.status == 304 and method == "GET":
# Rewrite the cache entry with the new end-to-end headers
# Take all headers that are in response
# and overwrite their values in info.
# unless they are hop-by-hop, or are listed in the connection header.
for key in _get_end2end_headers(response):
info[key] = response[key]
merged_response = Response(info)
if hasattr(response, "_stale_digest"):
merged_response._stale_digest = response._stale_digest
_updateCache(
headers, merged_response, content, self.cache, cachekey
)
response = merged_response
response.status = 200
response.fromcache = True
elif response.status == 200:
content = new_content
else:
self.cache.delete(cachekey)
content = new_content
else:
cc = _parse_cache_control(headers)
if "only-if-cached" in cc:
info["status"] = "504"
response = Response(info)
content = ""
else:
(response, content) = self._request(
conn,
authority,
uri,
request_uri,
method,
body,
headers,
redirections,
cachekey,
)
except Exception as e:
is_timeout = isinstance(e, socket.timeout)
if is_timeout:
conn = self.connections.pop(conn_key, None)
if conn:
conn.close()
if self.force_exception_to_status_code:
if isinstance(e, HttpLib2ErrorWithResponse):
response = e.response
content = e.content
response.status = 500
response.reason = str(e)
elif is_timeout:
content = "Request Timeout"
response = Response(
{
"content-type": "text/plain",
"status": "408",
"content-length": len(content),
}
)
response.reason = "Request Timeout"
else:
content = str(e)
response = Response(
{
"content-type": "text/plain",
"status": "400",
"content-length": len(content),
}
)
response.reason = "Bad Request"
else:
raise
return (response, content)
def _get_proxy_info(self, scheme, authority):
"""Return a ProxyInfo instance (or None) based on the scheme
and authority.
"""
hostname, port = urllib.splitport(authority)
proxy_info = self.proxy_info
if callable(proxy_info):
proxy_info = proxy_info(scheme)
if hasattr(proxy_info, "applies_to") and not proxy_info.applies_to(hostname):
proxy_info = None
return proxy_info
class Response(dict):
"""An object more like email.Message than httplib.HTTPResponse."""
"""Is this response from our local cache"""
fromcache = False
"""HTTP protocol version used by server.
10 for HTTP/1.0, 11 for HTTP/1.1.
"""
version = 11
"Status code returned by server. "
status = 200
"""Reason phrase returned by server."""
reason = "Ok"
previous = None
def __init__(self, info):
# info is either an email.Message or
# an httplib.HTTPResponse object.
if isinstance(info, httplib.HTTPResponse):
for key, value in info.getheaders():
self[key.lower()] = value
self.status = info.status
self["status"] = str(self.status)
self.reason = info.reason
self.version = info.version
elif isinstance(info, email.Message.Message):
for key, value in info.items():
self[key.lower()] = value
self.status = int(self["status"])
else:
for key, value in info.iteritems():
self[key.lower()] = value
self.status = int(self.get("status", self.status))
self.reason = self.get("reason", self.reason)
def __getattr__(self, name):
if name == "dict":
return self
else:
raise AttributeError(name)
| ./CrossVul/dataset_final_sorted/CWE-74/py/bad_3934_0 |
crossvul-python_data_good_2223_1 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
import sys
import re
import os
import shlex
import yaml
import copy
import optparse
import operator
from ansible import errors
from ansible import __version__
from ansible.utils import template
from ansible.utils.display_functions import *
from ansible.utils.plugins import *
from ansible.callbacks import display
import ansible.constants as C
import ast
import time
import StringIO
import stat
import termios
import tty
import pipes
import random
import difflib
import warnings
import traceback
import getpass
import sys
import json
#import vault
from vault import VaultLib
VERBOSITY=0
MAX_FILE_SIZE_FOR_DIFF=1*1024*1024
try:
import json
except ImportError:
import simplejson as json
try:
from hashlib import md5 as _md5
except ImportError:
from md5 import md5 as _md5
PASSLIB_AVAILABLE = False
try:
import passlib.hash
PASSLIB_AVAILABLE = True
except:
pass
KEYCZAR_AVAILABLE=False
try:
try:
# some versions of pycrypto may not have this?
from Crypto.pct_warnings import PowmInsecureWarning
except ImportError:
PowmInsecureWarning = RuntimeWarning
with warnings.catch_warnings(record=True) as warning_handler:
warnings.simplefilter("error", PowmInsecureWarning)
try:
import keyczar.errors as key_errors
from keyczar.keys import AesKey
except PowmInsecureWarning:
system_warning(
"The version of gmp you have installed has a known issue regarding " + \
"timing vulnerabilities when used with pycrypto. " + \
"If possible, you should update it (ie. yum update gmp)."
)
warnings.resetwarnings()
warnings.simplefilter("ignore")
import keyczar.errors as key_errors
from keyczar.keys import AesKey
KEYCZAR_AVAILABLE=True
except ImportError:
pass
###############################################################
# Abstractions around keyczar
###############################################################
def key_for_hostname(hostname):
# fireball mode is an implementation of ansible firing up zeromq via SSH
# to use no persistent daemons or key management
if not KEYCZAR_AVAILABLE:
raise errors.AnsibleError("python-keyczar must be installed on the control machine to use accelerated modes")
key_path = os.path.expanduser(C.ACCELERATE_KEYS_DIR)
if not os.path.exists(key_path):
os.makedirs(key_path, mode=0700)
os.chmod(key_path, int(C.ACCELERATE_KEYS_DIR_PERMS, 8))
elif not os.path.isdir(key_path):
raise errors.AnsibleError('ACCELERATE_KEYS_DIR is not a directory.')
if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_DIR_PERMS, 8):
raise errors.AnsibleError('Incorrect permissions on the private key directory. Use `chmod 0%o %s` to correct this issue, and make sure any of the keys files contained within that directory are set to 0%o' % (int(C.ACCELERATE_KEYS_DIR_PERMS, 8), C.ACCELERATE_KEYS_DIR, int(C.ACCELERATE_KEYS_FILE_PERMS, 8)))
key_path = os.path.join(key_path, hostname)
# use new AES keys every 2 hours, which means fireball must not allow running for longer either
if not os.path.exists(key_path) or (time.time() - os.path.getmtime(key_path) > 60*60*2):
key = AesKey.Generate()
fd = os.open(key_path, os.O_WRONLY | os.O_CREAT, int(C.ACCELERATE_KEYS_FILE_PERMS, 8))
fh = os.fdopen(fd, 'w')
fh.write(str(key))
fh.close()
return key
else:
if stat.S_IMODE(os.stat(key_path).st_mode) != int(C.ACCELERATE_KEYS_FILE_PERMS, 8):
raise errors.AnsibleError('Incorrect permissions on the key file for this host. Use `chmod 0%o %s` to correct this issue.' % (int(C.ACCELERATE_KEYS_FILE_PERMS, 8), key_path))
fh = open(key_path)
key = AesKey.Read(fh.read())
fh.close()
return key
def encrypt(key, msg):
return key.Encrypt(msg)
def decrypt(key, msg):
try:
return key.Decrypt(msg)
except key_errors.InvalidSignatureError:
raise errors.AnsibleError("decryption failed")
###############################################################
# UTILITY FUNCTIONS FOR COMMAND LINE TOOLS
###############################################################
def err(msg):
''' print an error message to stderr '''
print >> sys.stderr, msg
def exit(msg, rc=1):
''' quit with an error to stdout and a failure code '''
err(msg)
sys.exit(rc)
def jsonify(result, format=False):
''' format JSON output (uncompressed or uncompressed) '''
if result is None:
return "{}"
result2 = result.copy()
for key, value in result2.items():
if type(value) is str:
result2[key] = value.decode('utf-8', 'ignore')
if format:
return json.dumps(result2, sort_keys=True, indent=4)
else:
return json.dumps(result2, sort_keys=True)
def write_tree_file(tree, hostname, buf):
''' write something into treedir/hostname '''
# TODO: might be nice to append playbook runs per host in a similar way
# in which case, we'd want append mode.
path = os.path.join(tree, hostname)
fd = open(path, "w+")
fd.write(buf)
fd.close()
def is_failed(result):
''' is a given JSON result a failed result? '''
return ((result.get('rc', 0) != 0) or (result.get('failed', False) in [ True, 'True', 'true']))
def is_changed(result):
''' is a given JSON result a changed result? '''
return (result.get('changed', False) in [ True, 'True', 'true'])
def check_conditional(conditional, basedir, inject, fail_on_undefined=False):
if conditional is None or conditional == '':
return True
if isinstance(conditional, list):
for x in conditional:
if not check_conditional(x, basedir, inject, fail_on_undefined=fail_on_undefined):
return False
return True
if not isinstance(conditional, basestring):
return conditional
conditional = conditional.replace("jinja2_compare ","")
# allow variable names
if conditional in inject and '-' not in str(inject[conditional]):
conditional = inject[conditional]
conditional = template.template(basedir, conditional, inject, fail_on_undefined=fail_on_undefined)
original = str(conditional).replace("jinja2_compare ","")
# a Jinja2 evaluation that results in something Python can eval!
presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional
conditional = template.template(basedir, presented, inject)
val = conditional.strip()
if val == presented:
# the templating failed, meaning most likely a
# variable was undefined. If we happened to be
# looking for an undefined variable, return True,
# otherwise fail
if "is undefined" in conditional:
return True
elif "is defined" in conditional:
return False
else:
raise errors.AnsibleError("error while evaluating conditional: %s" % original)
elif val == "True":
return True
elif val == "False":
return False
else:
raise errors.AnsibleError("unable to evaluate conditional: %s" % original)
def is_executable(path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE])
def unfrackpath(path):
'''
returns a path that is free of symlinks, environment
variables, relative path traversals and symbols (~)
example:
'$HOME/../../var/mail' becomes '/var/spool/mail'
'''
return os.path.normpath(os.path.realpath(os.path.expandvars(os.path.expanduser(path))))
def prepare_writeable_dir(tree,mode=0777):
''' make sure a directory exists and is writeable '''
# modify the mode to ensure the owner at least
# has read/write access to this directory
mode |= 0700
# make sure the tree path is always expanded
# and normalized and free of symlinks
tree = unfrackpath(tree)
if not os.path.exists(tree):
try:
os.makedirs(tree, mode)
except (IOError, OSError), e:
raise errors.AnsibleError("Could not make dir %s: %s" % (tree, e))
if not os.access(tree, os.W_OK):
raise errors.AnsibleError("Cannot write to path %s" % tree)
return tree
def path_dwim(basedir, given):
'''
make relative paths work like folks expect.
'''
if given.startswith("/"):
return os.path.abspath(given)
elif given.startswith("~"):
return os.path.abspath(os.path.expanduser(given))
else:
if basedir is None:
basedir = "."
return os.path.abspath(os.path.join(basedir, given))
def path_dwim_relative(original, dirname, source, playbook_base, check=True):
''' find one file in a directory one level up in a dir named dirname relative to current '''
# (used by roles code)
basedir = os.path.dirname(original)
if os.path.islink(basedir):
basedir = unfrackpath(basedir)
template2 = os.path.join(basedir, dirname, source)
else:
template2 = os.path.join(basedir, '..', dirname, source)
source2 = path_dwim(basedir, template2)
if os.path.exists(source2):
return source2
obvious_local_path = path_dwim(playbook_base, source)
if os.path.exists(obvious_local_path):
return obvious_local_path
if check:
raise errors.AnsibleError("input file not found at %s or %s" % (source2, obvious_local_path))
return source2 # which does not exist
def json_loads(data):
''' parse a JSON string and return a data structure '''
return json.loads(data)
def parse_json(raw_data):
''' this version for module return data only '''
orig_data = raw_data
# ignore stuff like tcgetattr spewage or other warnings
data = filter_leading_non_json_lines(raw_data)
try:
return json.loads(data)
except:
# not JSON, but try "Baby JSON" which allows many of our modules to not
# require JSON and makes writing modules in bash much simpler
results = {}
try:
tokens = shlex.split(data)
except:
print "failed to parse json: "+ data
raise
for t in tokens:
if "=" not in t:
raise errors.AnsibleError("failed to parse: %s" % orig_data)
(key,value) = t.split("=", 1)
if key == 'changed' or 'failed':
if value.lower() in [ 'true', '1' ]:
value = True
elif value.lower() in [ 'false', '0' ]:
value = False
if key == 'rc':
value = int(value)
results[key] = value
if len(results.keys()) == 0:
return { "failed" : True, "parsed" : False, "msg" : orig_data }
return results
def smush_braces(data):
''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed weird by key=value code '''
while '{{ ' in data:
data = data.replace('{{ ', '{{')
while ' }}' in data:
data = data.replace(' }}', '}}')
return data
def smush_ds(data):
# things like key={{ foo }} are not handled by shlex.split well, so preprocess any YAML we load
# so we do not have to call smush elsewhere
if type(data) == list:
return [ smush_ds(x) for x in data ]
elif type(data) == dict:
for (k,v) in data.items():
data[k] = smush_ds(v)
return data
elif isinstance(data, basestring):
return smush_braces(data)
else:
return data
def parse_yaml(data, path_hint=None):
''' convert a yaml string to a data structure. Also supports JSON, ssssssh!!!'''
stripped_data = data.lstrip()
loaded = None
if stripped_data.startswith("{") or stripped_data.startswith("["):
# since the line starts with { or [ we can infer this is a JSON document.
try:
loaded = json.loads(data)
except ValueError, ve:
if path_hint:
raise errors.AnsibleError(path_hint + ": " + str(ve))
else:
raise errors.AnsibleError(str(ve))
else:
# else this is pretty sure to be a YAML document
loaded = yaml.safe_load(data)
return smush_ds(loaded)
def process_common_errors(msg, probline, column):
replaced = probline.replace(" ","")
if ":{{" in replaced and "}}" in replaced:
msg = msg + """
This one looks easy to fix. YAML thought it was looking for the start of a
hash/dictionary and was confused to see a second "{". Most likely this was
meant to be an ansible template evaluation instead, so we have to give the
parser a small hint that we wanted a string instead. The solution here is to
just quote the entire value.
For instance, if the original line was:
app_path: {{ base_path }}/foo
It should be written as:
app_path: "{{ base_path }}/foo"
"""
return msg
elif len(probline) and len(probline) > 1 and len(probline) > column and probline[column] == ":" and probline.count(':') > 1:
msg = msg + """
This one looks easy to fix. There seems to be an extra unquoted colon in the line
and this is confusing the parser. It was only expecting to find one free
colon. The solution is just add some quotes around the colon, or quote the
entire line after the first colon.
For instance, if the original line was:
copy: src=file.txt dest=/path/filename:with_colon.txt
It can be written as:
copy: src=file.txt dest='/path/filename:with_colon.txt'
Or:
copy: 'src=file.txt dest=/path/filename:with_colon.txt'
"""
return msg
else:
parts = probline.split(":")
if len(parts) > 1:
middle = parts[1].strip()
match = False
unbalanced = False
if middle.startswith("'") and not middle.endswith("'"):
match = True
elif middle.startswith('"') and not middle.endswith('"'):
match = True
if len(middle) > 0 and middle[0] in [ '"', "'" ] and middle[-1] in [ '"', "'" ] and probline.count("'") > 2 or probline.count('"') > 2:
unbalanced = True
if match:
msg = msg + """
This one looks easy to fix. It seems that there is a value started
with a quote, and the YAML parser is expecting to see the line ended
with the same kind of quote. For instance:
when: "ok" in result.stdout
Could be written as:
when: '"ok" in result.stdout'
or equivalently:
when: "'ok' in result.stdout"
"""
return msg
if unbalanced:
msg = msg + """
We could be wrong, but this one looks like it might be an issue with
unbalanced quotes. If starting a value with a quote, make sure the
line ends with the same set of quotes. For instance this arbitrary
example:
foo: "bad" "wolf"
Could be written as:
foo: '"bad" "wolf"'
"""
return msg
return msg
def process_yaml_error(exc, data, path=None, show_content=True):
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
if show_content:
if mark.line -1 >= 0:
before_probline = data.split("\n")[mark.line-1]
else:
before_probline = ''
probline = data.split("\n")[mark.line]
arrow = " " * mark.column + "^"
msg = """Syntax Error while loading YAML script, %s
Note: The error may actually appear before this position: line %s, column %s
%s
%s
%s""" % (path, mark.line + 1, mark.column + 1, before_probline, probline, arrow)
unquoted_var = None
if '{{' in probline and '}}' in probline:
if '"{{' not in probline or "'{{" not in probline:
unquoted_var = True
if not unquoted_var:
msg = process_common_errors(msg, probline, mark.column)
else:
msg = msg + """
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- "{{ foo }}"
"""
else:
# most likely displaying a file with sensitive content,
# so don't show any of the actual lines of yaml just the
# line number itself
msg = """Syntax error while loading YAML script, %s
The error appears to have been on line %s, column %s, but may actually
be before there depending on the exact syntax problem.
""" % (path, mark.line + 1, mark.column + 1)
else:
# No problem markers means we have to throw a generic
# "stuff messed up" type message. Sry bud.
if path:
msg = "Could not parse YAML. Check over %s again." % path
else:
msg = "Could not parse YAML."
raise errors.AnsibleYAMLValidationFailed(msg)
def parse_yaml_from_file(path, vault_password=None):
''' convert a yaml file to a data structure '''
data = None
show_content = True
try:
data = open(path).read()
except IOError:
raise errors.AnsibleError("file could not read: %s" % path)
vault = VaultLib(password=vault_password)
if vault.is_encrypted(data):
data = vault.decrypt(data)
show_content = False
try:
return parse_yaml(data, path_hint=path)
except yaml.YAMLError, exc:
process_yaml_error(exc, data, path, show_content)
def parse_kv(args):
''' convert a string of key/value items to a dict '''
options = {}
if args is not None:
# attempting to split a unicode here does bad things
args = args.encode('utf-8')
try:
vargs = shlex.split(args, posix=True)
except ValueError, ve:
if 'no closing quotation' in str(ve).lower():
raise errors.AnsibleError("error parsing argument string, try quoting the entire line.")
else:
raise
vargs = [x.decode('utf-8') for x in vargs]
for x in vargs:
if "=" in x:
k, v = x.split("=",1)
options[k]=v
return options
def merge_hash(a, b):
''' recursively merges hash b into a
keys from b take precedence over keys from a '''
result = copy.deepcopy(a)
# next, iterate over b keys and values
for k, v in b.iteritems():
# if there's already such key in a
# and that key contains dict
if k in result and isinstance(result[k], dict):
# merge those dicts recursively
result[k] = merge_hash(a[k], v)
else:
# otherwise, just copy a value from b to a
result[k] = v
return result
def md5s(data):
''' Return MD5 hex digest of data. '''
digest = _md5()
try:
digest.update(data)
except UnicodeEncodeError:
digest.update(data.encode('utf-8'))
return digest.hexdigest()
def md5(filename):
''' Return MD5 hex digest of local file, None if file is not present or a directory. '''
if not os.path.exists(filename) or os.path.isdir(filename):
return None
digest = _md5()
blocksize = 64 * 1024
try:
infile = open(filename, 'rb')
block = infile.read(blocksize)
while block:
digest.update(block)
block = infile.read(blocksize)
infile.close()
except IOError, e:
raise errors.AnsibleError("error while accessing the file %s, error was: %s" % (filename, e))
return digest.hexdigest()
def default(value, function):
''' syntactic sugar around lazy evaluation of defaults '''
if value is None:
return function()
return value
def _gitinfo():
''' returns a string containing git branch, commit id and commit date '''
result = None
repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git')
if os.path.exists(repo_path):
# Check if the .git is a file. If it is a file, it means that we are in a submodule structure.
if os.path.isfile(repo_path):
try:
gitdir = yaml.safe_load(open(repo_path)).get('gitdir')
# There is a posibility the .git file to have an absolute path.
if os.path.isabs(gitdir):
repo_path = gitdir
else:
repo_path = os.path.join(repo_path.split('.git')[0], gitdir)
except (IOError, AttributeError):
return ''
f = open(os.path.join(repo_path, "HEAD"))
branch = f.readline().split('/')[-1].rstrip("\n")
f.close()
branch_path = os.path.join(repo_path, "refs", "heads", branch)
if os.path.exists(branch_path):
f = open(branch_path)
commit = f.readline()[:10]
f.close()
date = time.localtime(os.stat(branch_path).st_mtime)
if time.daylight == 0:
offset = time.timezone
else:
offset = time.altzone
result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit,
time.strftime("%Y/%m/%d %H:%M:%S", date), offset / -36)
else:
result = ''
return result
def version(prog):
result = "{0} {1}".format(prog, __version__)
gitinfo = _gitinfo()
if gitinfo:
result = result + " {0}".format(gitinfo)
return result
def getch():
''' read in a single character '''
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def sanitize_output(str):
''' strips private info out of a string '''
private_keys = ['password', 'login_password']
filter_re = [
# filter out things like user:pass@foo/whatever
# and http://username:pass@wherever/foo
re.compile('^(?P<before>.*:)(?P<password>.*)(?P<after>\@.*)$'),
]
parts = str.split()
output = ''
for part in parts:
try:
(k,v) = part.split('=', 1)
if k in private_keys:
output += " %s=VALUE_HIDDEN" % k
else:
found = False
for filter in filter_re:
m = filter.match(v)
if m:
d = m.groupdict()
output += " %s=%s" % (k, d['before'] + "********" + d['after'])
found = True
break
if not found:
output += " %s" % part
except:
output += " %s" % part
return output.strip()
####################################################################
# option handling code for /usr/bin/ansible and ansible-playbook
# below this line
class SortedOptParser(optparse.OptionParser):
'''Optparser which sorts the options by opt before outputting --help'''
def format_help(self, formatter=None):
self.option_list.sort(key=operator.methodcaller('get_opt_string'))
return optparse.OptionParser.format_help(self, formatter=None)
def increment_debug(option, opt, value, parser):
global VERBOSITY
VERBOSITY += 1
def base_parser(constants=C, usage="", output_opts=False, runas_opts=False,
async_opts=False, connect_opts=False, subset_opts=False, check_opts=False, diff_opts=False):
''' create an options parser for any ansible script '''
parser = SortedOptParser(usage, version=version("%prog"))
parser.add_option('-v','--verbose', default=False, action="callback",
callback=increment_debug, help="verbose mode (-vvv for more, -vvvv to enable connection debugging)")
parser.add_option('-f','--forks', dest='forks', default=constants.DEFAULT_FORKS, type='int',
help="specify number of parallel processes to use (default=%s)" % constants.DEFAULT_FORKS)
parser.add_option('-i', '--inventory-file', dest='inventory',
help="specify inventory host file (default=%s)" % constants.DEFAULT_HOST_LIST,
default=constants.DEFAULT_HOST_LIST)
parser.add_option('-k', '--ask-pass', default=False, dest='ask_pass', action='store_true',
help='ask for SSH password')
parser.add_option('--private-key', default=C.DEFAULT_PRIVATE_KEY_FILE, dest='private_key_file',
help='use this file to authenticate the connection')
parser.add_option('-K', '--ask-sudo-pass', default=False, dest='ask_sudo_pass', action='store_true',
help='ask for sudo password')
parser.add_option('--ask-su-pass', default=False, dest='ask_su_pass', action='store_true',
help='ask for su password')
parser.add_option('--ask-vault-pass', default=False, dest='ask_vault_pass', action='store_true',
help='ask for vault password')
parser.add_option('--vault-password-file', default=None, dest='vault_password_file',
help="vault password file")
parser.add_option('--list-hosts', dest='listhosts', action='store_true',
help='outputs a list of matching hosts; does not execute anything else')
parser.add_option('-M', '--module-path', dest='module_path',
help="specify path(s) to module library (default=%s)" % constants.DEFAULT_MODULE_PATH,
default=None)
if subset_opts:
parser.add_option('-l', '--limit', default=constants.DEFAULT_SUBSET, dest='subset',
help='further limit selected hosts to an additional pattern')
parser.add_option('-T', '--timeout', default=constants.DEFAULT_TIMEOUT, type='int',
dest='timeout',
help="override the SSH timeout in seconds (default=%s)" % constants.DEFAULT_TIMEOUT)
if output_opts:
parser.add_option('-o', '--one-line', dest='one_line', action='store_true',
help='condense output')
parser.add_option('-t', '--tree', dest='tree', default=None,
help='log output to this directory')
if runas_opts:
parser.add_option("-s", "--sudo", default=constants.DEFAULT_SUDO, action="store_true",
dest='sudo', help="run operations with sudo (nopasswd)")
parser.add_option('-U', '--sudo-user', dest='sudo_user', default=None,
help='desired sudo user (default=root)') # Can't default to root because we need to detect when this option was given
parser.add_option('-u', '--user', default=constants.DEFAULT_REMOTE_USER,
dest='remote_user', help='connect as this user (default=%s)' % constants.DEFAULT_REMOTE_USER)
parser.add_option('-S', '--su', default=constants.DEFAULT_SU,
action='store_true', help='run operations with su')
parser.add_option('-R', '--su-user', help='run operations with su as this '
'user (default=%s)' % constants.DEFAULT_SU_USER)
if connect_opts:
parser.add_option('-c', '--connection', dest='connection',
default=C.DEFAULT_TRANSPORT,
help="connection type to use (default=%s)" % C.DEFAULT_TRANSPORT)
if async_opts:
parser.add_option('-P', '--poll', default=constants.DEFAULT_POLL_INTERVAL, type='int',
dest='poll_interval',
help="set the poll interval if using -B (default=%s)" % constants.DEFAULT_POLL_INTERVAL)
parser.add_option('-B', '--background', dest='seconds', type='int', default=0,
help='run asynchronously, failing after X seconds (default=N/A)')
if check_opts:
parser.add_option("-C", "--check", default=False, dest='check', action='store_true',
help="don't make any changes; instead, try to predict some of the changes that may occur"
)
if diff_opts:
parser.add_option("-D", "--diff", default=False, dest='diff', action='store_true',
help="when changing (small) files and templates, show the differences in those files; works great with --check"
)
return parser
def ask_vault_passwords(ask_vault_pass=False, ask_new_vault_pass=False, confirm_vault=False, confirm_new=False):
vault_pass = None
new_vault_pass = None
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
if ask_vault_pass and confirm_vault:
vault_pass2 = getpass.getpass(prompt="Confirm Vault password: ")
if vault_pass != vault_pass2:
raise errors.AnsibleError("Passwords do not match")
if ask_new_vault_pass:
new_vault_pass = getpass.getpass(prompt="New Vault password: ")
if ask_new_vault_pass and confirm_new:
new_vault_pass2 = getpass.getpass(prompt="Confirm New Vault password: ")
if new_vault_pass != new_vault_pass2:
raise errors.AnsibleError("Passwords do not match")
# enforce no newline chars at the end of passwords
if vault_pass:
vault_pass = vault_pass.strip()
if new_vault_pass:
new_vault_pass = new_vault_pass.strip()
return vault_pass, new_vault_pass
def ask_passwords(ask_pass=False, ask_sudo_pass=False, ask_su_pass=False, ask_vault_pass=False):
sshpass = None
sudopass = None
su_pass = None
vault_pass = None
sudo_prompt = "sudo password: "
su_prompt = "su password: "
if ask_pass:
sshpass = getpass.getpass(prompt="SSH password: ")
sudo_prompt = "sudo password [defaults to SSH password]: "
if ask_sudo_pass:
sudopass = getpass.getpass(prompt=sudo_prompt)
if ask_pass and sudopass == '':
sudopass = sshpass
if ask_su_pass:
su_pass = getpass.getpass(prompt=su_prompt)
if ask_vault_pass:
vault_pass = getpass.getpass(prompt="Vault password: ")
return (sshpass, sudopass, su_pass, vault_pass)
def do_encrypt(result, encrypt, salt_size=None, salt=None):
if PASSLIB_AVAILABLE:
try:
crypt = getattr(passlib.hash, encrypt)
except:
raise errors.AnsibleError("passlib does not support '%s' algorithm" % encrypt)
if salt_size:
result = crypt.encrypt(result, salt_size=salt_size)
elif salt:
result = crypt.encrypt(result, salt=salt)
else:
result = crypt.encrypt(result)
else:
raise errors.AnsibleError("passlib must be installed to encrypt vars_prompt values")
return result
def last_non_blank_line(buf):
all_lines = buf.splitlines()
all_lines.reverse()
for line in all_lines:
if (len(line) > 0):
return line
# shouldn't occur unless there's no output
return ""
def filter_leading_non_json_lines(buf):
'''
used to avoid random output from SSH at the top of JSON output, like messages from
tcagetattr, or where dropbear spews MOTD on every single command (which is nuts).
need to filter anything which starts not with '{', '[', ', '=' or is an empty line.
filter only leading lines since multiline JSON is valid.
'''
kv_regex = re.compile(r'.*\w+=\w+.*')
filtered_lines = StringIO.StringIO()
stop_filtering = False
for line in buf.splitlines():
if stop_filtering or kv_regex.match(line) or line.startswith('{') or line.startswith('['):
stop_filtering = True
filtered_lines.write(line + '\n')
return filtered_lines.getvalue()
def boolean(value):
val = str(value)
if val.lower() in [ "true", "t", "y", "1", "yes" ]:
return True
else:
return False
def make_sudo_cmd(sudo_user, executable, cmd):
"""
helper function for connection plugins to create sudo commands
"""
# Rather than detect if sudo wants a password this time, -k makes
# sudo always ask for a password if one is required.
# Passing a quoted compound command to sudo (or sudo -s)
# directly doesn't work, so we shellquote it with pipes.quote()
# and pass the quoted string to the user's shell. We loop reading
# output until we see the randomly-generated sudo prompt set with
# the -p option.
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = '[sudo via ansible, key=%s] password: ' % randbits
success_key = 'SUDO-SUCCESS-%s' % randbits
sudocmd = '%s -k && %s %s -S -p "%s" -u %s %s -c %s' % (
C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_EXE, C.DEFAULT_SUDO_FLAGS,
prompt, sudo_user, executable or '$SHELL', pipes.quote('echo %s; %s' % (success_key, cmd)))
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
def make_su_cmd(su_user, executable, cmd):
"""
Helper function for connection plugins to create direct su commands
"""
# TODO: work on this function
randbits = ''.join(chr(random.randint(ord('a'), ord('z'))) for x in xrange(32))
prompt = '[Pp]assword: ?$'
success_key = 'SUDO-SUCCESS-%s' % randbits
sudocmd = '%s %s %s -c "%s -c %s"' % (
C.DEFAULT_SU_EXE, C.DEFAULT_SU_FLAGS, su_user, executable or '$SHELL',
pipes.quote('echo %s; %s' % (success_key, cmd))
)
return ('/bin/sh -c ' + pipes.quote(sudocmd), prompt, success_key)
_TO_UNICODE_TYPES = (unicode, type(None))
def to_unicode(value):
if isinstance(value, _TO_UNICODE_TYPES):
return value
return value.decode("utf-8")
def get_diff(diff):
# called by --diff usage in playbook and runner via callbacks
# include names in diffs 'before' and 'after' and do diff -U 10
try:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
ret = []
if 'dst_binary' in diff:
ret.append("diff skipped: destination file appears to be binary\n")
if 'src_binary' in diff:
ret.append("diff skipped: source file appears to be binary\n")
if 'dst_larger' in diff:
ret.append("diff skipped: destination file size is greater than %d\n" % diff['dst_larger'])
if 'src_larger' in diff:
ret.append("diff skipped: source file size is greater than %d\n" % diff['src_larger'])
if 'before' in diff and 'after' in diff:
if 'before_header' in diff:
before_header = "before: %s" % diff['before_header']
else:
before_header = 'before'
if 'after_header' in diff:
after_header = "after: %s" % diff['after_header']
else:
after_header = 'after'
differ = difflib.unified_diff(to_unicode(diff['before']).splitlines(True), to_unicode(diff['after']).splitlines(True), before_header, after_header, '', '', 10)
for line in list(differ):
ret.append(line)
return u"".join(ret)
except UnicodeDecodeError:
return ">> the files are different, but the diff library cannot compare unicode strings"
def is_list_of_strings(items):
for x in items:
if not isinstance(x, basestring):
return False
return True
def list_union(a, b):
result = []
for x in a:
if x not in result:
result.append(x)
for x in b:
if x not in result:
result.append(x)
return result
def list_intersection(a, b):
result = []
for x in a:
if x in b and x not in result:
result.append(x)
return result
def safe_eval(expr, locals={}, include_exceptions=False):
'''
this is intended for allowing things like:
with_items: a_list_variable
where Jinja2 would return a string
but we do not want to allow it to call functions (outside of Jinja2, where
the env is constrained)
Based on:
http://stackoverflow.com/questions/12523516/using-ast-and-whitelists-to-make-pythons-eval-safe
'''
# this is the whitelist of AST nodes we are going to
# allow in the evaluation. Any node type other than
# those listed here will raise an exception in our custom
# visitor class defined below.
SAFE_NODES = set(
(
ast.Expression,
ast.Compare,
ast.Str,
ast.List,
ast.Tuple,
ast.Dict,
ast.Call,
ast.Load,
ast.BinOp,
ast.UnaryOp,
ast.Num,
ast.Name,
ast.Add,
ast.Sub,
ast.Mult,
ast.Div,
)
)
# AST node types were expanded after 2.6
if not sys.version.startswith('2.6'):
SAFE_NODES.union(
set(
(ast.Set,)
)
)
# builtin functions that are safe to call
BUILTIN_WHITELIST = [
'abs', 'all', 'any', 'basestring', 'bin', 'bool', 'buffer', 'bytearray',
'bytes', 'callable', 'chr', 'cmp', 'coerce', 'complex', 'copyright', 'credits',
'dict', 'dir', 'divmod', 'enumerate', 'exit', 'float', 'format', 'frozenset',
'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id', 'int', 'intern',
'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long',
'map', 'max', 'memoryview', 'min', 'next', 'oct', 'ord', 'pow', 'print',
'property', 'quit', 'range', 'reversed', 'round', 'set', 'slice', 'sorted',
'str', 'sum', 'tuple', 'unichr', 'unicode', 'vars', 'xrange', 'zip',
]
filter_list = []
for filter in filter_loader.all():
filter_list.extend(filter.filters().keys())
CALL_WHITELIST = BUILTIN_WHITELIST + filter_list + C.DEFAULT_CALLABLE_WHITELIST
class CleansingNodeVisitor(ast.NodeVisitor):
def generic_visit(self, node):
if type(node) not in SAFE_NODES:
raise Exception("invalid expression (%s)" % expr)
super(CleansingNodeVisitor, self).generic_visit(node)
def visit_Call(self, call):
if call.func.id not in CALL_WHITELIST:
raise Exception("invalid function: %s" % call.func.id)
if not isinstance(expr, basestring):
# already templated to a datastructure, perhaps?
if include_exceptions:
return (expr, None)
return expr
try:
parsed_tree = ast.parse(expr, mode='eval')
cnv = CleansingNodeVisitor()
cnv.visit(parsed_tree)
compiled = compile(parsed_tree, expr, 'eval')
result = eval(compiled, {}, locals)
if include_exceptions:
return (result, None)
else:
return result
except SyntaxError, e:
# special handling for syntax errors, we just return
# the expression string back as-is
if include_exceptions:
return (expr, None)
return expr
except Exception, e:
if include_exceptions:
return (expr, e)
return expr
def listify_lookup_plugin_terms(terms, basedir, inject):
if isinstance(terms, basestring):
# someone did:
# with_items: alist
# OR
# with_items: {{ alist }}
stripped = terms.strip()
if not (stripped.startswith('{') or stripped.startswith('[')) and not stripped.startswith("/") and not stripped.startswith('set(['):
# if not already a list, get ready to evaluate with Jinja2
# not sure why the "/" is in above code :)
try:
new_terms = template.template(basedir, "{{ %s }}" % terms, inject)
if isinstance(new_terms, basestring) and "{{" in new_terms:
pass
else:
terms = new_terms
except:
pass
if '{' in terms or '[' in terms:
# Jinja2 already evaluated a variable to a list.
# Jinja2-ified list needs to be converted back to a real type
# TODO: something a bit less heavy than eval
return safe_eval(terms)
if isinstance(terms, basestring):
terms = [ terms ]
return terms
def combine_vars(a, b):
if C.DEFAULT_HASH_BEHAVIOUR == "merge":
return merge_hash(a, b)
else:
return dict(a.items() + b.items())
def random_password(length=20, chars=C.DEFAULT_PASSWORD_CHARS):
'''Return a random password string of length containing only chars.'''
password = []
while len(password) < length:
new_char = os.urandom(1)
if new_char in chars:
password.append(new_char)
return ''.join(password)
def before_comment(msg):
''' what's the part of a string before a comment? '''
msg = msg.replace("\#","**NOT_A_COMMENT**")
msg = msg.split("#")[0]
msg = msg.replace("**NOT_A_COMMENT**","#")
return msg
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_2223_1 |
crossvul-python_data_good_3934_2 | from __future__ import print_function
import base64
import contextlib
import copy
import email.utils
import functools
import gzip
import hashlib
import httplib2
import os
import random
import re
import shutil
import six
import socket
import ssl
import struct
import sys
import threading
import time
import traceback
import zlib
from six.moves import http_client, queue
DUMMY_URL = "http://127.0.0.1:1"
DUMMY_HTTPS_URL = "https://127.0.0.1:2"
tls_dir = os.path.join(os.path.dirname(__file__), "tls")
CA_CERTS = os.path.join(tls_dir, "ca.pem")
CA_UNUSED_CERTS = os.path.join(tls_dir, "ca_unused.pem")
CLIENT_PEM = os.path.join(tls_dir, "client.pem")
CLIENT_ENCRYPTED_PEM = os.path.join(tls_dir, "client_encrypted.pem")
SERVER_PEM = os.path.join(tls_dir, "server.pem")
SERVER_CHAIN = os.path.join(tls_dir, "server_chain.pem")
@contextlib.contextmanager
def assert_raises(exc_type):
def _name(t):
return getattr(t, "__name__", None) or str(t)
if not isinstance(exc_type, tuple):
exc_type = (exc_type,)
names = ", ".join(map(_name, exc_type))
try:
yield
except exc_type:
pass
else:
assert False, "Expected exception(s) {0}".format(names)
class BufferedReader(object):
"""io.BufferedReader with \r\n support
"""
def __init__(self, sock):
self._buf = b""
self._end = False
self._newline = b"\r\n"
self._sock = sock
if isinstance(sock, bytes):
self._sock = None
self._buf = sock
def _fill(self, target=1, more=None, untilend=False):
if more:
target = len(self._buf) + more
while untilend or (len(self._buf) < target):
# crutch to enable HttpRequest.from_bytes
if self._sock is None:
chunk = b""
else:
chunk = self._sock.recv(8 << 10)
# print("!!! recv", chunk)
if not chunk:
self._end = True
if untilend:
return
else:
raise EOFError
self._buf += chunk
def peek(self, size):
self._fill(target=size)
return self._buf[:size]
def read(self, size):
self._fill(target=size)
chunk, self._buf = self._buf[:size], self._buf[size:]
return chunk
def readall(self):
self._fill(untilend=True)
chunk, self._buf = self._buf, b""
return chunk
def readline(self):
while True:
i = self._buf.find(self._newline)
if i >= 0:
break
self._fill(more=1)
inext = i + len(self._newline)
line, self._buf = self._buf[:inext], self._buf[inext:]
return line
def parse_http_message(kind, buf):
if buf._end:
return None
try:
start_line = buf.readline()
except EOFError:
return None
msg = kind()
msg.raw = start_line
if kind is HttpRequest:
assert re.match(
br".+ HTTP/\d\.\d\r\n$", start_line
), "Start line does not look like HTTP request: " + repr(start_line)
msg.method, msg.uri, msg.proto = start_line.rstrip().decode().split(" ", 2)
assert msg.proto.startswith("HTTP/"), repr(start_line)
elif kind is HttpResponse:
assert re.match(
br"^HTTP/\d\.\d \d+ .+\r\n$", start_line
), "Start line does not look like HTTP response: " + repr(start_line)
msg.proto, msg.status, msg.reason = start_line.rstrip().decode().split(" ", 2)
msg.status = int(msg.status)
assert msg.proto.startswith("HTTP/"), repr(start_line)
else:
raise Exception("Use HttpRequest or HttpResponse .from_{bytes,buffered}")
msg.version = msg.proto[5:]
while True:
line = buf.readline()
msg.raw += line
line = line.rstrip()
if not line:
break
t = line.decode().split(":", 1)
msg.headers[t[0].lower()] = t[1].lstrip()
content_length_string = msg.headers.get("content-length", "")
if content_length_string.isdigit():
content_length = int(content_length_string)
msg.body = msg.body_raw = buf.read(content_length)
elif msg.headers.get("transfer-encoding") == "chunked":
raise NotImplemented
elif msg.version == "1.0":
msg.body = msg.body_raw = buf.readall()
else:
msg.body = msg.body_raw = b""
msg.raw += msg.body_raw
return msg
class HttpMessage(object):
def __init__(self):
self.headers = {}
@classmethod
def from_bytes(cls, bs):
buf = BufferedReader(bs)
return parse_http_message(cls, buf)
@classmethod
def from_buffered(cls, buf):
return parse_http_message(cls, buf)
def __repr__(self):
return "{} {}".format(self.__class__, repr(vars(self)))
class HttpRequest(HttpMessage):
pass
class HttpResponse(HttpMessage):
pass
class MockResponse(six.BytesIO):
def __init__(self, body, **kwargs):
six.BytesIO.__init__(self, body)
self.headers = kwargs
def items(self):
return self.headers.items()
def iteritems(self):
return six.iteritems(self.headers)
class MockHTTPConnection(object):
"""This class is just a mock of httplib.HTTPConnection used for testing
"""
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
):
self.host = host
self.port = port
self.timeout = timeout
self.log = ""
self.sock = None
def set_debuglevel(self, level):
pass
def connect(self):
"Connect to a host on a given port."
pass
def close(self):
pass
def request(self, method, request_uri, body, headers):
pass
def getresponse(self):
return MockResponse(b"the body", status="200")
class MockHTTPBadStatusConnection(object):
"""Mock of httplib.HTTPConnection that raises BadStatusLine.
"""
num_calls = 0
def __init__(
self,
host,
port=None,
key_file=None,
cert_file=None,
strict=None,
timeout=None,
proxy_info=None,
):
self.host = host
self.port = port
self.timeout = timeout
self.log = ""
self.sock = None
MockHTTPBadStatusConnection.num_calls = 0
def set_debuglevel(self, level):
pass
def connect(self):
pass
def close(self):
pass
def request(self, method, request_uri, body, headers):
pass
def getresponse(self):
MockHTTPBadStatusConnection.num_calls += 1
raise http_client.BadStatusLine("")
@contextlib.contextmanager
def server_socket(fun, request_count=1, timeout=5, scheme="", tls=None):
"""Base socket server for tests.
Likely you want to use server_request or other higher level helpers.
All arguments except fun can be passed to other server_* helpers.
:param fun: fun(client_sock, tick) called after successful accept().
:param request_count: test succeeds after exactly this number of requests, triggered by tick(request)
:param timeout: seconds.
:param scheme: affects yielded value
"" - build normal http/https URI.
string - build normal URI using supplied scheme.
None - yield (addr, port) tuple.
:param tls:
None (default) - plain HTTP.
True - HTTPS with reasonable defaults. Likely you want httplib2.Http(ca_certs=tests.CA_CERTS)
string - path to custom server cert+key PEM file.
callable - function(context, listener, skip_errors) -> ssl_wrapped_listener
"""
gresult = [None]
gcounter = [0]
tls_skip_errors = [
"TLSV1_ALERT_UNKNOWN_CA",
]
def tick(request):
gcounter[0] += 1
keep = True
keep &= gcounter[0] < request_count
if request is not None:
keep &= request.headers.get("connection", "").lower() != "close"
return keep
def server_socket_thread(srv):
try:
while gcounter[0] < request_count:
try:
client, _ = srv.accept()
except ssl.SSLError as e:
if e.reason in tls_skip_errors:
return
raise
try:
client.settimeout(timeout)
fun(client, tick)
finally:
try:
client.shutdown(socket.SHUT_RDWR)
except (IOError, socket.error):
pass
# FIXME: client.close() introduces connection reset by peer
# at least in other/connection_close test
# should not be a problem since socket would close upon garbage collection
if gcounter[0] > request_count:
gresult[0] = Exception(
"Request count expected={0} actual={1}".format(
request_count, gcounter[0]
)
)
except Exception as e:
# traceback.print_exc caused IOError: concurrent operation on sys.stderr.close() under setup.py test
print(traceback.format_exc(), file=sys.stderr)
gresult[0] = e
bind_hostname = "localhost"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_hostname, 0))
try:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error as ex:
print("non critical error on SO_REUSEADDR", ex)
server.listen(10)
server.settimeout(timeout)
server_port = server.getsockname()[1]
if tls is True:
tls = SERVER_CHAIN
if tls:
context = ssl_context()
if callable(tls):
context.load_cert_chain(SERVER_CHAIN)
server = tls(context, server, tls_skip_errors)
else:
context.load_cert_chain(tls)
server = context.wrap_socket(server, server_side=True)
if scheme == "":
scheme = "https" if tls else "http"
t = threading.Thread(target=server_socket_thread, args=(server,))
t.daemon = True
t.start()
if scheme is None:
yield (bind_hostname, server_port)
else:
yield u"{scheme}://{host}:{port}/".format(scheme=scheme, host=bind_hostname, port=server_port)
server.close()
t.join()
if gresult[0] is not None:
raise gresult[0]
def server_yield(fun, **kwargs):
q = queue.Queue(1)
g = fun(q.get)
def server_yield_socket_handler(sock, tick):
buf = BufferedReader(sock)
i = 0
while True:
request = HttpRequest.from_buffered(buf)
if request is None:
break
i += 1
request.client_sock = sock
request.number = i
q.put(request)
response = six.next(g)
sock.sendall(response)
request.client_sock = None
if not tick(request):
break
return server_socket(server_yield_socket_handler, **kwargs)
def server_request(request_handler, **kwargs):
def server_request_socket_handler(sock, tick):
buf = BufferedReader(sock)
i = 0
while True:
request = HttpRequest.from_buffered(buf)
if request is None:
break
# print("--- debug request\n" + request.raw.decode("ascii", "replace"))
i += 1
request.client_sock = sock
request.number = i
response = request_handler(request=request)
# print("--- debug response\n" + response.decode("ascii", "replace"))
sock.sendall(response)
request.client_sock = None
if not tick(request):
break
return server_socket(server_request_socket_handler, **kwargs)
def server_const_bytes(response_content, **kwargs):
return server_request(lambda request: response_content, **kwargs)
_http_kwargs = (
"proto",
"status",
"headers",
"body",
"add_content_length",
"add_date",
"add_etag",
"undefined_body_length",
)
def http_response_bytes(
proto="HTTP/1.1",
status="200 OK",
headers=None,
body=b"",
add_content_length=True,
add_date=False,
add_etag=False,
undefined_body_length=False,
**kwargs
):
if undefined_body_length:
add_content_length = False
if headers is None:
headers = {}
if add_content_length:
headers.setdefault("content-length", str(len(body)))
if add_date:
headers.setdefault("date", email.utils.formatdate())
if add_etag:
headers.setdefault("etag", '"{0}"'.format(hashlib.md5(body).hexdigest()))
header_string = "".join("{0}: {1}\r\n".format(k, v) for k, v in headers.items())
if (
not undefined_body_length
and proto != "HTTP/1.0"
and "content-length" not in headers
):
raise Exception(
"httplib2.tests.http_response_bytes: client could not figure response body length"
)
if str(status).isdigit():
status = "{} {}".format(status, http_client.responses[status])
response = (
"{proto} {status}\r\n{headers}\r\n".format(
proto=proto, status=status, headers=header_string
).encode()
+ body
)
return response
def make_http_reflect(**kwargs):
assert "body" not in kwargs, "make_http_reflect will overwrite response " "body"
def fun(request):
kw = copy.deepcopy(kwargs)
kw["body"] = request.raw
response = http_response_bytes(**kw)
return response
return fun
def server_route(routes, **kwargs):
response_404 = http_response_bytes(status="404 Not Found")
response_wildcard = routes.get("")
def handler(request):
target = routes.get(request.uri, response_wildcard) or response_404
if callable(target):
response = target(request=request)
else:
response = target
return response
return server_request(handler, **kwargs)
def server_const_http(**kwargs):
response_kwargs = {k: kwargs.pop(k) for k in dict(kwargs) if k in _http_kwargs}
response = http_response_bytes(**response_kwargs)
return server_const_bytes(response, **kwargs)
def server_list_http(responses, **kwargs):
i = iter(responses)
def handler(request):
return next(i)
kwargs.setdefault("request_count", len(responses))
return server_request(handler, **kwargs)
def server_reflect(**kwargs):
response_kwargs = {k: kwargs.pop(k) for k in dict(kwargs) if k in _http_kwargs}
http_handler = make_http_reflect(**response_kwargs)
return server_request(http_handler, **kwargs)
def http_parse_auth(s):
"""https://tools.ietf.org/html/rfc7235#section-2.1
"""
scheme, rest = s.split(" ", 1)
result = {}
while True:
m = httplib2.WWW_AUTH_RELAXED.search(rest)
if not m:
break
if len(m.groups()) == 3:
key, value, rest = m.groups()
result[key.lower()] = httplib2.UNQUOTE_PAIRS.sub(r"\1", value)
return result
def store_request_response(out):
def wrapper(fun):
@functools.wraps(fun)
def wrapped(request, *a, **kw):
response_bytes = fun(request, *a, **kw)
if out is not None:
response = HttpResponse.from_bytes(response_bytes)
out.append((request, response))
return response_bytes
return wrapped
return wrapper
def http_reflect_with_auth(
allow_scheme, allow_credentials, out_renew_nonce=None, out_requests=None
):
"""allow_scheme - 'basic', 'digest', etc allow_credentials - sequence of ('name', 'password') out_renew_nonce - None | [function]
Way to return nonce renew function to caller.
Kind of `out` parameter in some programming languages.
Allows to keep same signature for all handler builder functions.
out_requests - None | []
If set to list, every parsed request will be appended here.
"""
glastnc = [None]
gnextnonce = [None]
gserver_nonce = [gen_digest_nonce(salt=b"n")]
realm = "httplib2 test"
server_opaque = gen_digest_nonce(salt=b"o")
def renew_nonce():
if gnextnonce[0]:
assert False, (
"previous nextnonce was not used, probably bug in " "test code"
)
gnextnonce[0] = gen_digest_nonce()
return gserver_nonce[0], gnextnonce[0]
if out_renew_nonce:
out_renew_nonce[0] = renew_nonce
def deny(**kwargs):
nonce_stale = kwargs.pop("nonce_stale", False)
if nonce_stale:
kwargs.setdefault("body", b"nonce stale")
if allow_scheme == "basic":
authenticate = 'basic realm="{realm}"'.format(realm=realm)
elif allow_scheme == "digest":
authenticate = (
'digest realm="{realm}", qop="auth"'
+ ', nonce="{nonce}", opaque="{opaque}"'
+ (", stale=true" if nonce_stale else "")
).format(realm=realm, nonce=gserver_nonce[0], opaque=server_opaque)
else:
raise Exception("unknown allow_scheme={0}".format(allow_scheme))
deny_headers = {"www-authenticate": authenticate}
kwargs.setdefault("status", 401)
# supplied headers may overwrite generated ones
deny_headers.update(kwargs.get("headers", {}))
kwargs["headers"] = deny_headers
kwargs.setdefault("body", b"HTTP authorization required")
return http_response_bytes(**kwargs)
@store_request_response(out_requests)
def http_reflect_with_auth_handler(request):
auth_header = request.headers.get("authorization", "")
if not auth_header:
return deny()
if " " not in auth_header:
return http_response_bytes(
status=400, body=b"authorization header syntax error"
)
scheme, data = auth_header.split(" ", 1)
scheme = scheme.lower()
if scheme != allow_scheme:
return deny(body=b"must use different auth scheme")
if scheme == "basic":
decoded = base64.b64decode(data).decode()
username, password = decoded.split(":", 1)
if (username, password) in allow_credentials:
return make_http_reflect()(request)
else:
return deny(body=b"supplied credentials are not allowed")
elif scheme == "digest":
server_nonce_old = gserver_nonce[0]
nextnonce = gnextnonce[0]
if nextnonce:
# server decided to change nonce, in this case, guided by caller test code
gserver_nonce[0] = nextnonce
gnextnonce[0] = None
server_nonce_current = gserver_nonce[0]
auth_info = http_parse_auth(data)
client_cnonce = auth_info.get("cnonce", "")
client_nc = auth_info.get("nc", "")
client_nonce = auth_info.get("nonce", "")
client_opaque = auth_info.get("opaque", "")
client_qop = auth_info.get("qop", "auth").strip('"')
# TODO: auth_info.get('algorithm', 'md5')
hasher = hashlib.md5
# TODO: client_qop auth-int
ha2 = hasher(":".join((request.method, request.uri)).encode()).hexdigest()
if client_nonce != server_nonce_current:
if client_nonce == server_nonce_old:
return deny(nonce_stale=True)
return deny(body=b"invalid nonce")
if not client_nc:
return deny(body=b"auth-info nc missing")
if client_opaque != server_opaque:
return deny(
body="auth-info opaque mismatch expected={} actual={}".format(
server_opaque, client_opaque
).encode()
)
for allow_username, allow_password in allow_credentials:
ha1 = hasher(
":".join((allow_username, realm, allow_password)).encode()
).hexdigest()
allow_response = hasher(
":".join(
(ha1, client_nonce, client_nc, client_cnonce, client_qop, ha2)
).encode()
).hexdigest()
rspauth_ha2 = hasher(":{}".format(request.uri).encode()).hexdigest()
rspauth = hasher(
":".join(
(
ha1,
client_nonce,
client_nc,
client_cnonce,
client_qop,
rspauth_ha2,
)
).encode()
).hexdigest()
if auth_info.get("response", "") == allow_response:
# TODO: fix or remove doubtful comment
# do we need to save nc only on success?
glastnc[0] = client_nc
allow_headers = {
"authentication-info": " ".join(
(
'nextnonce="{}"'.format(nextnonce) if nextnonce else "",
"qop={}".format(client_qop),
'rspauth="{}"'.format(rspauth),
'cnonce="{}"'.format(client_cnonce),
"nc={}".format(client_nc),
)
).strip()
}
return make_http_reflect(headers=allow_headers)(request)
return deny(body=b"supplied credentials are not allowed")
else:
return http_response_bytes(
status=400,
body="unknown authorization scheme={0}".format(scheme).encode(),
)
return http_reflect_with_auth_handler
def get_cache_path():
default = "./_httplib2_test_cache"
path = os.environ.get("httplib2_test_cache_path") or default
if os.path.exists(path):
shutil.rmtree(path)
return path
def gen_digest_nonce(salt=b""):
t = struct.pack(">Q", int(time.time() * 1e9))
return base64.b64encode(t + b":" + hashlib.sha1(t + salt).digest()).decode()
def gen_password():
length = random.randint(8, 64)
return "".join(six.unichr(random.randint(0, 127)) for _ in range(length))
def gzip_compress(bs):
# gzipobj = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS | 16)
# result = gzipobj.compress(text) + gzipobj.flush()
buf = six.BytesIO()
gf = gzip.GzipFile(fileobj=buf, mode="wb", compresslevel=6)
gf.write(bs)
gf.close()
return buf.getvalue()
def gzip_decompress(bs):
return zlib.decompress(bs, zlib.MAX_WBITS | 16)
def deflate_compress(bs):
do = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
return do.compress(bs) + do.flush()
def deflate_decompress(bs):
return zlib.decompress(bs, -zlib.MAX_WBITS)
def ssl_context(protocol=None):
"""Workaround for old SSLContext() required protocol argument.
"""
if sys.version_info < (3, 5, 3):
return ssl.SSLContext(ssl.PROTOCOL_SSLv23)
return ssl.SSLContext()
| ./CrossVul/dataset_final_sorted/CWE-74/py/good_3934_2 |
crossvul-python_data_good_3895_3 | import operator
from functools import partial
from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Tuple
from pypika import Table
from pypika.functions import Upper
from pypika.terms import (
BasicCriterion,
Criterion,
Enum,
Equality,
Term,
ValueWrapper,
basestring,
date,
format_quotes,
)
from tortoise.fields import Field
from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstance
if TYPE_CHECKING: # pragma: nocoverage
from tortoise.models import Model
##############################################################################
# Here we monkey-patch PyPika Valuewrapper to behave differently for MySQL
##############################################################################
def get_value_sql(self, **kwargs): # pragma: nocoverage
quote_char = kwargs.get("secondary_quote_char") or ""
dialect = kwargs.get("dialect")
if dialect:
dialect = dialect.value
if isinstance(self.value, Term):
return self.value.get_sql(**kwargs)
if isinstance(self.value, Enum):
return self.value.value
if isinstance(self.value, date):
value = self.value.isoformat()
return format_quotes(value, quote_char)
if isinstance(self.value, basestring):
value = self.value.replace(quote_char, quote_char * 2)
if dialect == "mysql":
value = value.replace("\\", "\\\\")
return format_quotes(value, quote_char)
if isinstance(self.value, bool):
return str.lower(str(self.value))
if self.value is None:
return "null"
return str(self.value)
ValueWrapper.get_value_sql = get_value_sql
##############################################################################
class Like(BasicCriterion): # type: ignore
def __init__(self, left, right, alias=None, escape=" ESCAPE '\\'") -> None:
"""
A Like that supports an ESCAPE clause
"""
super().__init__(" LIKE ", left, right, alias=alias)
self.escape = escape
def get_sql(self, quote_char='"', with_alias=False, **kwargs):
sql = "{left}{comparator}{right}{escape}".format(
comparator=self.comparator,
left=self.left.get_sql(quote_char=quote_char, **kwargs),
right=self.right.get_sql(quote_char=quote_char, **kwargs),
escape=self.escape,
)
if with_alias and self.alias: # pragma: nocoverage
return '{sql} "{alias}"'.format(sql=sql, alias=self.alias)
return sql
def escape_val(val: Any) -> Any:
if isinstance(val, str):
print(val)
return val.replace("\\", "\\\\")
return val
def escape_like(val: str) -> str:
return val.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
##############################################################################
# Encoders
# Should be type: (Any, instance: "Model", field: Field) -> type:
##############################################################################
def list_encoder(values: Iterable[Any], instance: "Model", field: Field) -> list:
"""Encodes an iterable of a given field into a database-compatible format."""
return [field.to_db_value(element, instance) for element in values]
def related_list_encoder(values: Iterable[Any], instance: "Model", field: Field) -> list:
return [
field.to_db_value(element.pk if hasattr(element, "pk") else element, instance)
for element in values
]
def bool_encoder(value: Any, instance: "Model", field: Field) -> bool:
return bool(value)
def string_encoder(value: Any, instance: "Model", field: Field) -> str:
return str(value)
##############################################################################
# Operators
# Should be type: (field: Term, value: Any) -> Criterion:
##############################################################################
def is_in(field: Term, value: Any) -> Criterion:
if value:
return field.isin(value)
# SQL has no False, so we return 1=0
return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(0))
def not_in(field: Term, value: Any) -> Criterion:
if value:
return field.notin(value) | field.isnull()
# SQL has no True, so we return 1=1
return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(1))
def between_and(field: Term, value: Tuple[Any, Any]) -> Criterion:
return field.between(value[0], value[1])
def not_equal(field: Term, value: Any) -> Criterion:
return field.ne(value) | field.isnull()
def is_null(field: Term, value: Any) -> Criterion:
if value:
return field.isnull()
return field.notnull()
def not_null(field: Term, value: Any) -> Criterion:
if value:
return field.notnull()
return field.isnull()
def contains(field: Term, value: str) -> Criterion:
return Like(field, field.wrap_constant(f"%{escape_like(value)}%"))
def starts_with(field: Term, value: str) -> Criterion:
return Like(field, field.wrap_constant(f"{escape_like(value)}%"))
def ends_with(field: Term, value: str) -> Criterion:
return Like(field, field.wrap_constant(f"%{escape_like(value)}"))
def insensitive_exact(field: Term, value: str) -> Criterion:
return Upper(field).eq(Upper(str(value)))
def insensitive_contains(field: Term, value: str) -> Criterion:
return Like(Upper(field), field.wrap_constant(Upper(f"%{escape_like(value)}%")))
def insensitive_starts_with(field: Term, value: str) -> Criterion:
return Like(Upper(field), field.wrap_constant(Upper(f"{escape_like(value)}%")))
def insensitive_ends_with(field: Term, value: str) -> Criterion:
return Like(Upper(field), field.wrap_constant(Upper(f"%{escape_like(value)}")))
##############################################################################
# Filter resolvers
##############################################################################
def get_m2m_filters(field_name: str, field: ManyToManyFieldInstance) -> Dict[str, dict]:
target_table_pk = field.related_model._meta.pk
return {
field_name: {
"field": field.forward_key,
"backward_key": field.backward_key,
"operator": operator.eq,
"table": Table(field.through),
"value_encoder": target_table_pk.to_db_value,
},
f"{field_name}__not": {
"field": field.forward_key,
"backward_key": field.backward_key,
"operator": not_equal,
"table": Table(field.through),
"value_encoder": target_table_pk.to_db_value,
},
f"{field_name}__in": {
"field": field.forward_key,
"backward_key": field.backward_key,
"operator": is_in,
"table": Table(field.through),
"value_encoder": partial(related_list_encoder, field=target_table_pk),
},
f"{field_name}__not_in": {
"field": field.forward_key,
"backward_key": field.backward_key,
"operator": not_in,
"table": Table(field.through),
"value_encoder": partial(related_list_encoder, field=target_table_pk),
},
}
def get_backward_fk_filters(field_name: str, field: BackwardFKRelation) -> Dict[str, dict]:
target_table_pk = field.related_model._meta.pk
return {
field_name: {
"field": field.related_model._meta.pk_attr,
"backward_key": field.relation_field,
"operator": operator.eq,
"table": Table(field.related_model._meta.db_table),
"value_encoder": target_table_pk.to_db_value,
},
f"{field_name}__not": {
"field": field.related_model._meta.pk_attr,
"backward_key": field.relation_field,
"operator": not_equal,
"table": Table(field.related_model._meta.db_table),
"value_encoder": target_table_pk.to_db_value,
},
f"{field_name}__in": {
"field": field.related_model._meta.pk_attr,
"backward_key": field.relation_field,
"operator": is_in,
"table": Table(field.related_model._meta.db_table),
"value_encoder": partial(related_list_encoder, field=target_table_pk),
},
f"{field_name}__not_in": {
"field": field.related_model._meta.pk_attr,
"backward_key": field.relation_field,
"operator": not_in,
"table": Table(field.related_model._meta.db_table),
"value_encoder": partial(related_list_encoder, field=target_table_pk),
},
}
def get_filters_for_field(
field_name: str, field: Optional[Field], source_field: str
) -> Dict[str, dict]:
if isinstance(field, ManyToManyFieldInstance):
return get_m2m_filters(field_name, field)
if isinstance(field, BackwardFKRelation):
return get_backward_fk_filters(field_name, field)
actual_field_name = field_name
if field_name == "pk" and field:
actual_field_name = field.model_field_name
return {
field_name: {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.eq,
},
f"{field_name}__not": {
"field": actual_field_name,
"source_field": source_field,
"operator": not_equal,
},
f"{field_name}__in": {
"field": actual_field_name,
"source_field": source_field,
"operator": is_in,
"value_encoder": list_encoder,
},
f"{field_name}__not_in": {
"field": actual_field_name,
"source_field": source_field,
"operator": not_in,
"value_encoder": list_encoder,
},
f"{field_name}__isnull": {
"field": actual_field_name,
"source_field": source_field,
"operator": is_null,
"value_encoder": bool_encoder,
},
f"{field_name}__not_isnull": {
"field": actual_field_name,
"source_field": source_field,
"operator": not_null,
"value_encoder": bool_encoder,
},
f"{field_name}__gte": {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.ge,
},
f"{field_name}__lte": {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.le,
},
f"{field_name}__gt": {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.gt,
},
f"{field_name}__lt": {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.lt,
},
f"{field_name}__range": {
"field": actual_field_name,
"source_field": source_field,
"operator": between_and,
"value_encoder": list_encoder,
},
f"{field_name}__contains": {
"field": actual_field_name,
"source_field": source_field,
"operator": contains,
"value_encoder": string_encoder,
},
f"{field_name}__startswith": {
"field": actual_field_name,
"source_field": source_field,
"operator": starts_with,
"value_encoder": string_encoder,
},
f"{field_name}__endswith": {
"field": actual_field_name,
"source_field": source_field,
"operator": ends_with,
"value_encoder": string_encoder,
},
f"{field_name}__iexact": {
"field": actual_field_name,
"source_field": source_field,
"operator": insensitive_exact,
"value_encoder": string_encoder,
},
f"{field_name}__icontains": {
"field": actual_field_name,
"source_field": source_field,
"operator": insensitive_contains,
"value_encoder": string_encoder,
},
f"{field_name}__istartswith": {
"field": actual_field_name,
"source_field": source_field,
"operator": insensitive_starts_with,
"value_encoder": string_encoder,
},
f"{field_name}__iendswith": {
"field": actual_field_name,
"source_field": source_field,
"operator": insensitive_ends_with,
"value_encoder": string_encoder,
},
}
| ./CrossVul/dataset_final_sorted/CWE-89/py/good_3895_3 |
crossvul-python_data_bad_4605_0 | from django.contrib.postgres.fields import ArrayField, JSONField
from django.db.models.aggregates import Aggregate
from .mixins import OrderableAggMixin
__all__ = [
'ArrayAgg', 'BitAnd', 'BitOr', 'BoolAnd', 'BoolOr', 'JSONBAgg', 'StringAgg',
]
class ArrayAgg(OrderableAggMixin, Aggregate):
function = 'ARRAY_AGG'
template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
allow_distinct = True
@property
def output_field(self):
return ArrayField(self.source_expressions[0].output_field)
def convert_value(self, value, expression, connection):
if not value:
return []
return value
class BitAnd(Aggregate):
function = 'BIT_AND'
class BitOr(Aggregate):
function = 'BIT_OR'
class BoolAnd(Aggregate):
function = 'BOOL_AND'
class BoolOr(Aggregate):
function = 'BOOL_OR'
class JSONBAgg(Aggregate):
function = 'JSONB_AGG'
output_field = JSONField()
def convert_value(self, value, expression, connection):
if not value:
return []
return value
class StringAgg(OrderableAggMixin, Aggregate):
function = 'STRING_AGG'
template = "%(function)s(%(distinct)s%(expressions)s, '%(delimiter)s'%(ordering)s)"
allow_distinct = True
def __init__(self, expression, delimiter, **extra):
super().__init__(expression, delimiter=delimiter, **extra)
def convert_value(self, value, expression, connection):
if not value:
return ''
return value
| ./CrossVul/dataset_final_sorted/CWE-89/py/bad_4605_0 |
crossvul-python_data_good_4605_1 | from django.db.models.expressions import F, OrderBy
class OrderableAggMixin:
def __init__(self, *expressions, ordering=(), **extra):
if not isinstance(ordering, (list, tuple)):
ordering = [ordering]
ordering = ordering or []
# Transform minus sign prefixed strings into an OrderBy() expression.
ordering = (
(OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o)
for o in ordering
)
super().__init__(*expressions, **extra)
self.ordering = self._parse_expressions(*ordering)
def resolve_expression(self, *args, **kwargs):
self.ordering = [expr.resolve_expression(*args, **kwargs) for expr in self.ordering]
return super().resolve_expression(*args, **kwargs)
def as_sql(self, compiler, connection):
if self.ordering:
ordering_params = []
ordering_expr_sql = []
for expr in self.ordering:
expr_sql, expr_params = expr.as_sql(compiler, connection)
ordering_expr_sql.append(expr_sql)
ordering_params.extend(expr_params)
sql, sql_params = super().as_sql(compiler, connection, ordering=(
'ORDER BY ' + ', '.join(ordering_expr_sql)
))
return sql, sql_params + ordering_params
return super().as_sql(compiler, connection, ordering='')
def set_source_expressions(self, exprs):
# Extract the ordering expressions because ORDER BY clause is handled
# in a custom way.
self.ordering = exprs[self._get_ordering_expressions_index():]
return super().set_source_expressions(exprs[:self._get_ordering_expressions_index()])
def get_source_expressions(self):
return super().get_source_expressions() + self.ordering
def _get_ordering_expressions_index(self):
"""Return the index at which the ordering expressions start."""
source_expressions = self.get_source_expressions()
return len(source_expressions) - len(self.ordering)
| ./CrossVul/dataset_final_sorted/CWE-89/py/good_4605_1 |
crossvul-python_data_bad_2971_0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#**
#
#########
# trape #
#########
#
# trape depends of this file
# For full copyright information this visit: https://github.com/boxug/trape
#
# Copyright 2017 by boxug / <hey@boxug.com>
#**
import sqlite3
class Database(object):
def __init__(self):
self.conn = sqlite3.connect("database.db", check_same_thread=False)
self.cursor = self.conn.cursor()
def loadDatabase(self):
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "geo" ( `id` TEXT, `city` TEXT, `country_code` TEXT, `country_name` TEXT, `ip` TEXT, `latitude` TEXT, `longitude` TEXT, `metro_code` TEXT, `region_code` TEXT, `region_name` TEXT, `time_zone` TEXT, `zip_code` TEXT, `isp` TEXT, `ua` TEXT, PRIMARY KEY(`id`) )""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "networks" ( `id` TEXT, `ip` TEXT, `public_ip` INTEGER, `network` TEXT, `date` TEXT )""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "requests" ( `id` TEXT, `user_id` TEXT, `site` TEXT, `fid` TEXT, `name` TEXT, `value` TEXT, `date` TEXT )""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "victims" ( `id` TEXT, `ip` TEXT, `date` TEXT, `time` REAL, `bVersion` TEXT, `browser` TEXT, `device` TEXT, `cpu` TEXT, `ports` TEXT, `status` TEXT )""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "clicks" ( `id` TEXT, `site` TEXT, `date` TEXT )""")
self.conn.commit()
return True
def sql_execute(self, sentence):
self.cursor.execute(sentence)
return self.cursor.fetchall()
def sql_one_row(self, sentence, column):
self.cursor.execute(sentence)
return self.cursor.fetchone()[column]
def sql_insert(self, sentence):
self.cursor.execute(sentence)
self.conn.commit()
return True
def prop_sentences_stats(self, type, vId = None):
return {
'get_data' : "SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC",
'all_networks' : "SELECT networks.* FROM networks ORDER BY id",
'get_preview' : "SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = '%s'" % (vId),
'id_networks' : "SELECT networks.* FROM networks WHERE id = '%s'" % (vId),
'get_requests' : "SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id ",
'get_sessions' : "SELECT COUNT(*) AS Total FROM networks",
'get_clicks' : "SELECT COUNT(*) AS Total FROM clicks",
'get_online' : "SELECT COUNT(*) AS Total FROM victims WHERE status = '%s'" % ('online')
}.get(type, False)
def sentences_stats(self, type, vId = None):
return self.sql_execute(self.prop_sentences_stats(type, vId))
def prop_sentences_victim(self, type, data = None):
if type == 'count_victim':
return "SELECT COUNT(*) AS C FROM victims WHERE id = '%s'" % (data)
elif type == 'count_times':
return "SELECT COUNT(*) AS C FROM clicks WHERE id = '%s'" % (data)
elif type == 'update_victim':
return "UPDATE victims SET ip = '%s', date = '%s', bVersion = '%s', browser = '%s', device = '%s', ports = '%s', time = '%s', cpu = '%s', status = '%s' WHERE id = '%s'" % (data[0].ip, data[0].date, data[0].version, data[0].browser, data[0].device, data[0].ports, data[2], data[0].cpu, 'online', data[1])
elif type == 'update_victim_geo':
return "UPDATE geo SET city = '%s', country_code = '%s', country_name = '%s', ip = '%s', latitude = '%s', longitude = '%s', metro_code = '%s', region_code = '%s', region_name = '%s', time_zone = '%s', zip_code = '%s', isp = '%s', ua='%s' WHERE id = '%s'" % (data[0].city, data[0].country_code, data[0].country_name, data[0].ip, data[0].latitude, data[0].longitude, data[0].metro_code, data[0].region_code, data[0].region_name, data[0].time_zone, data[0].zip_code, data[0].isp, data[0].ua, data[1])
elif type == 'insert_victim':
return "INSERT INTO victims(id, ip, date, bVersion, browser, device, ports, time, cpu, status) VALUES('%s','%s', '%s','%s', '%s','%s', '%s', '%s', '%s', '%s')" % (data[1], data[0].ip, data[0].date, data[0].version, data[0].browser, data[0].device, data[0].ports, data[2], data[0].cpu, 'online')
elif type == 'insert_victim_geo':
return "INSERT INTO geo(id, city, country_code, country_name, ip, latitude, longitude, metro_code, region_code, region_name, time_zone, zip_code, isp, ua) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (data[1], data[0].city, data[0].country_code, data[0].country_name, data[0].ip, data[0].latitude, data[0].longitude, data[0].metro_code, data[0].region_code, data[0].region_name, data[0].time_zone, data[0].zip_code, data[0].isp, data[0].ua)
elif type == 'count_victim_network':
return "SELECT COUNT(*) AS C FROM networks WHERE id = '%s' AND network = '%s'" % (data[0], data[1])
elif type == 'delete_networks':
return "DELETE FROM networks WHERE id = '%s'" % (data[0])
elif type == 'update_network':
return "UPDATE networks SET date = '%s' WHERE id = '%s' AND network = '%s'" % (data[2], data[0], data[1])
elif type == 'insert_networks':
return "INSERT INTO networks(id, public_ip, ip, network, date) VALUES('%s','%s', '%s', '%s','%s')" % (data[0], data[1], data[2], data[3], data[4])
elif type == 'insert_requests':
return "INSERT INTO requests(id, user_id, site, fid, name, value, date) VALUES('%s', '%s','%s', '%s', '%s','%s', '%s')" % (data[0].sId, data[0].id, data[0].site, data[0].fid, data[0].name, data[0].value, data[1])
elif type == 'insert_click':
return "INSERT INTO clicks(id, site, date) VALUES('%s', '%s','%s')" % (data[0], data[1], data[2])
elif type == 'report_online':
return "UPDATE victims SET status = '%s' WHERE id = '%s'" % ('online', data[0])
elif type == 'clean_online':
return "UPDATE victims SET status = '%s' " % ('offline')
elif type == 'disconnect_victim':
return "UPDATE victims SET status = '%s' WHERE id = '%s'" % ('offline', data)
else:
return False
def sentences_victim(self, type, data = None, sRun = 1, column = 0):
if sRun == 2:
return self.sql_insert(self.prop_sentences_victim(type, data))
elif sRun == 3:
return self.sql_one_row(self.prop_sentences_victim(type, data), column)
else:
return self.sql_execute(self.prop_sentences_victim(type, data))
def __del__(self):
self.conn.close() | ./CrossVul/dataset_final_sorted/CWE-89/py/bad_2971_0 |
crossvul-python_data_bad_2971_1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#**
#
#########
# trape #
#########
#
# trape depends of this file
# For full copyright information this visit: https://github.com/boxug/trape
#
# Copyright 2017 by boxug / <hey@boxug.com>
#**
import urllib2
from flask import Flask, render_template, session, request, json
from core.trape import Trape
from core.db import Database
# Main parts, to generate relationships among others
trape = Trape()
app = Flask(__name__, template_folder='../templates', static_folder='../static')
# call database
db = Database()
# preview header tool in console
trape.header()
@app.route("/" + trape.stats_path)
def index():
return render_template("/login.html")
@app.route("/logout")
def logout():
return render_template("/login.html")
@app.route("/login", methods=["POST"])
def login():
id = request.form['id']
if id == trape.stats_key:
return json.dumps({'status':'OK', 'path' : trape.home_path, 'victim_path' : trape.victim_path, 'url_to_clone' : trape.url_to_clone, 'app_port' : trape.app_port, 'date_start' : trape.date_start, 'user_ip' : '127.0.0.1'});
else:
return json.dumps({'status':'NOPE', 'path' : '/'});
@app.route("/get_data", methods=["POST"])
def home_get_dat():
d = db.sentences_stats('get_data')
n = db.sentences_stats('all_networks')
('clean_online')
rows = db.sentences_stats('get_clicks')
c = rows[0][0]
rows = db.sentences_stats('get_sessions')
s = rows[0][0]
rows = db.sentences_stats('get_online')
o = rows[0][0]
return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o});
@app.route("/get_preview", methods=["POST"])
def home_get_preview():
vId = request.form['vId']
d = db.sentences_stats('get_preview', vId)
n = db.sentences_stats('id_networks', vId)
return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n});
@app.route("/get_title", methods=["POST"])
def home_get_title():
opener = urllib2.build_opener()
html = opener.open(trape.url_to_clone).read()
html = html[html.find('<title>') + 7 : html.find('</title>')]
return json.dumps({'status' : 'OK', 'title' : html});
@app.route("/get_requests", methods=["POST"])
def home_get_requests():
d = db.sentences_stats('get_requests')
return json.dumps({'status' : 'OK', 'd' : d}); | ./CrossVul/dataset_final_sorted/CWE-89/py/bad_2971_1 |
crossvul-python_data_good_3895_2 | from pypika import Parameter, functions
from pypika.enums import SqlTypes
from pypika.terms import Criterion
from tortoise import Model
from tortoise.backends.base.executor import BaseExecutor
from tortoise.fields import BigIntField, IntField, SmallIntField
from tortoise.filters import (
Like,
Term,
ValueWrapper,
contains,
ends_with,
format_quotes,
insensitive_contains,
insensitive_ends_with,
insensitive_exact,
insensitive_starts_with,
starts_with,
)
class StrWrapper(ValueWrapper): # type: ignore
"""
Naive str wrapper that doesn't use the monkey-patched pypika ValueWraper for MySQL
"""
def get_value_sql(self, **kwargs):
quote_char = kwargs.get("secondary_quote_char") or ""
value = self.value.replace(quote_char, quote_char * 2)
return format_quotes(value, quote_char)
def escape_like(val: str) -> str:
return val.replace("\\", "\\\\\\\\").replace("%", "\\%").replace("_", "\\_")
def mysql_contains(field: Term, value: str) -> Criterion:
return Like(
functions.Cast(field, SqlTypes.CHAR), StrWrapper(f"%{escape_like(value)}%"), escape=""
)
def mysql_starts_with(field: Term, value: str) -> Criterion:
return Like(
functions.Cast(field, SqlTypes.CHAR), StrWrapper(f"{escape_like(value)}%"), escape=""
)
def mysql_ends_with(field: Term, value: str) -> Criterion:
return Like(
functions.Cast(field, SqlTypes.CHAR), StrWrapper(f"%{escape_like(value)}"), escape=""
)
def mysql_insensitive_exact(field: Term, value: str) -> Criterion:
return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).eq(functions.Upper(str(value)))
def mysql_insensitive_contains(field: Term, value: str) -> Criterion:
return Like(
functions.Upper(functions.Cast(field, SqlTypes.CHAR)),
functions.Upper(StrWrapper(f"%{escape_like(value)}%")),
escape="",
)
def mysql_insensitive_starts_with(field: Term, value: str) -> Criterion:
return Like(
functions.Upper(functions.Cast(field, SqlTypes.CHAR)),
functions.Upper(StrWrapper(f"{escape_like(value)}%")),
escape="",
)
def mysql_insensitive_ends_with(field: Term, value: str) -> Criterion:
return Like(
functions.Upper(functions.Cast(field, SqlTypes.CHAR)),
functions.Upper(StrWrapper(f"%{escape_like(value)}")),
escape="",
)
class MySQLExecutor(BaseExecutor):
FILTER_FUNC_OVERRIDE = {
contains: mysql_contains,
starts_with: mysql_starts_with,
ends_with: mysql_ends_with,
insensitive_exact: mysql_insensitive_exact,
insensitive_contains: mysql_insensitive_contains,
insensitive_starts_with: mysql_insensitive_starts_with,
insensitive_ends_with: mysql_insensitive_ends_with,
}
EXPLAIN_PREFIX = "EXPLAIN FORMAT=JSON"
def parameter(self, pos: int) -> Parameter:
return Parameter("%s")
async def _process_insert_result(self, instance: Model, results: int) -> None:
pk_field_object = self.model._meta.pk
if (
isinstance(pk_field_object, (SmallIntField, IntField, BigIntField))
and pk_field_object.generated
):
instance.pk = results
# MySQL can only generate a single ROWID
# so if any other primary key, it won't generate what we want.
| ./CrossVul/dataset_final_sorted/CWE-89/py/good_3895_2 |
crossvul-python_data_good_2971_2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#**
#
#########
# trape #
#########
#
# trape depends of this file
# For full copyright information this visit: https://github.com/boxug/trape
#
# Copyright 2017 by boxug / <hey@boxug.com>
#**
import time
import urllib2
from flask import Flask, render_template, session, request, json
from core.victim_objects import *
import core.stats
from core.utils import utils
from core.db import Database
# Main parts, to generate relationships among others
trape = core.stats.trape
app = core.stats.app
# call database
db = Database()
class victim_server(object):
@app.route("/" + trape.victim_path)
def homeVictim():
opener = urllib2.build_opener()
headers = victim_headers()
opener.addheaders = headers
html = victim_inject_code(opener.open(trape.url_to_clone).read(), 'lure')
return html
@app.route("/register", methods=["POST"])
def register():
vId = request.form['vId']
if vId == '':
vId = utils.generateToken(5)
victimConnect = victim(vId, request.environ['REMOTE_ADDR'], request.user_agent.platform, request.user_agent.browser, request.user_agent.version, utils.portScanner(request.environ['REMOTE_ADDR']), request.form['cpu'], time.strftime("%Y-%m-%d - %H:%M:%S"))
victimGeo = victim_geo(vId, 'city', request.form['countryCode'], request.form['country'], request.form['query'], request.form['lat'], request.form['lon'], request.form['org'], request.form['region'], request.form['regionName'], request.form['timezone'], request.form['zip'], request.form['isp'], str(request.user_agent))
utils.Go(utils.Color['white'] + "[" + utils.Color['blueBold'] + "*" + utils.Color['white'] + "]" + " A victim has been connected from " + utils.Color['blue'] + victimGeo.ip + utils.Color['white'] + ' with the following identifier: ' + utils.Color['green'] + vId + utils.Color['white'])
cant = int(db.sentences_victim('count_times', vId, 3, 0))
db.sentences_victim('insert_click', [vId, trape.url_to_clone, time.strftime("%Y-%m-%d - %H:%M:%S")], 2)
db.sentences_victim('delete_networks', [vId], 2)
if cant > 0:
utils.Go(utils.Color['white'] + "[" + utils.Color['blueBold'] + "*" + utils.Color['white'] + "]" + " " + "It\'s his " + str(cant + 1) + " time")
db.sentences_victim('update_victim', [victimConnect, vId, time.time()], 2)
db.sentences_victim('update_victim_geo', [victimGeo, vId], 2)
else:
utils.Go(utils.Color['white'] + "[" + utils.Color['blueBold'] + "*" + utils.Color['white'] + "]" + " " + "It\'s his first time")
db.sentences_victim('insert_victim', [victimConnect, vId, time.time()], 2)
db.sentences_victim('insert_victim_geo', [victimGeo, vId], 2)
return json.dumps({'status' : 'OK', 'vId' : vId});
@app.route("/nr", methods=["POST"])
def networkRegister():
vId = request.form['vId']
vIp = request.form['ip']
vnetwork = request.form['red']
if vId == '':
vId = utils.generateToken(5)
utils.Go(utils.Color['white'] + "[" + utils.Color['greenBold'] + "+" + utils.Color['white'] + "]" + utils.Color['whiteBold'] + " " + vnetwork + utils.Color['white'] + " session detected from " + utils.Color['blue'] + vIp + utils.Color['white'] + ' ' + "with ID: " + utils.Color['green'] + vId + utils.Color['white'])
cant = int(db.sentences_victim('count_victim_network', [vId, vnetwork], 3, 0))
if cant > 0:
db.sentences_victim('update_network', [vId, vnetwork, time.strftime("%Y-%m-%d - %H:%M:%S")], 2)
else:
db.sentences_victim('insert_networks', [vId, vIp, request.environ['REMOTE_ADDR'], vnetwork, time.strftime("%Y-%m-%d - %H:%M:%S")], 2)
return json.dumps({'status' : 'OK', 'vId' : vId});
@app.route("/redv")
def redirectVictim():
url = request.args.get('url')
opener = urllib2.build_opener()
headers = victim_headers()
opener.addheaders = headers
html = victim_inject_code(opener.open(url).read(), 'vscript')
return html
@app.route("/regv", methods=["POST"])
def registerRequest():
vrequest = victim_request(request.form['vId'], request.form['site'], request.form['fid'], request.form['name'], request.form['value'], request.form['sId'])
db.sentences_victim('insert_requests', [vrequest, time.strftime("%Y-%m-%d - %H:%M:%S")], 2)
utils.Go(utils.Color['white'] + "[" + utils.Color['greenBold'] + "=" + utils.Color['white'] + "]" + " " + 'Receiving data from: ' + utils.Color['green'] + vrequest.id + utils.Color['white'] + ' ' + 'on' + ' ' + utils.Color['blue'] + vrequest.site + utils.Color['white'] + '\t\n' + vrequest.fid + '\t' + vrequest.name + ':\t' + vrequest.value)
return json.dumps({'status' : 'OK', 'vId' : vrequest.id});
@app.route("/tping", methods=["POST"])
def receivePing():
vrequest = request.form['id']
db.sentences_victim('report_online', [vrequest], 2)
return json.dumps({'status' : 'OK', 'vId' : vrequest});
| ./CrossVul/dataset_final_sorted/CWE-89/py/good_2971_2 |
crossvul-python_data_bad_3895_2 | from pypika import Parameter, functions
from pypika.enums import SqlTypes
from pypika.terms import Criterion
from tortoise import Model
from tortoise.backends.base.executor import BaseExecutor
from tortoise.fields import BigIntField, Field, IntField, SmallIntField
from tortoise.filters import (
contains,
ends_with,
insensitive_contains,
insensitive_ends_with,
insensitive_exact,
insensitive_starts_with,
starts_with,
)
def mysql_contains(field: Field, value: str) -> Criterion:
return functions.Cast(field, SqlTypes.CHAR).like(f"%{value}%")
def mysql_starts_with(field: Field, value: str) -> Criterion:
return functions.Cast(field, SqlTypes.CHAR).like(f"{value}%")
def mysql_ends_with(field: Field, value: str) -> Criterion:
return functions.Cast(field, SqlTypes.CHAR).like(f"%{value}")
def mysql_insensitive_exact(field: Field, value: str) -> Criterion:
return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).eq(functions.Upper(f"{value}"))
def mysql_insensitive_contains(field: Field, value: str) -> Criterion:
return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"%{value}%"))
def mysql_insensitive_starts_with(field: Field, value: str) -> Criterion:
return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"{value}%"))
def mysql_insensitive_ends_with(field: Field, value: str) -> Criterion:
return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.Upper(f"%{value}"))
class MySQLExecutor(BaseExecutor):
FILTER_FUNC_OVERRIDE = {
contains: mysql_contains,
starts_with: mysql_starts_with,
ends_with: mysql_ends_with,
insensitive_exact: mysql_insensitive_exact,
insensitive_contains: mysql_insensitive_contains,
insensitive_starts_with: mysql_insensitive_starts_with,
insensitive_ends_with: mysql_insensitive_ends_with,
}
EXPLAIN_PREFIX = "EXPLAIN FORMAT=JSON"
def parameter(self, pos: int) -> Parameter:
return Parameter("%s")
async def _process_insert_result(self, instance: Model, results: int) -> None:
pk_field_object = self.model._meta.pk
if (
isinstance(pk_field_object, (SmallIntField, IntField, BigIntField))
and pk_field_object.generated
):
instance.pk = results
# MySQL can only generate a single ROWID
# so if any other primary key, it won't generate what we want.
| ./CrossVul/dataset_final_sorted/CWE-89/py/bad_3895_2 |
crossvul-python_data_bad_3895_3 | import operator
from functools import partial
from typing import TYPE_CHECKING, Any, Dict, Iterable, Optional, Tuple
from pypika import Table
from pypika.functions import Upper
from pypika.terms import BasicCriterion, Criterion, Equality, Term, ValueWrapper
from tortoise.fields import Field
from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstance
if TYPE_CHECKING: # pragma: nocoverage
from tortoise.models import Model
##############################################################################
# Encoders
# Should be type: (Any, instance: "Model", field: Field) -> type:
##############################################################################
def list_encoder(values: Iterable[Any], instance: "Model", field: Field) -> list:
"""Encodes an iterable of a given field into a database-compatible format."""
return [field.to_db_value(element, instance) for element in values]
def related_list_encoder(values: Iterable[Any], instance: "Model", field: Field) -> list:
return [
field.to_db_value(element.pk if hasattr(element, "pk") else element, instance)
for element in values
]
def bool_encoder(value: Any, instance: "Model", field: Field) -> bool:
return bool(value)
def string_encoder(value: Any, instance: "Model", field: Field) -> str:
return str(value)
##############################################################################
# Operators
# Should be type: (field: Term, value: Any) -> Criterion:
##############################################################################
def is_in(field: Term, value: Any) -> Criterion:
if value:
return field.isin(value)
# SQL has no False, so we return 1=0
return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(0))
def not_in(field: Term, value: Any) -> Criterion:
if value:
return field.notin(value) | field.isnull()
# SQL has no True, so we return 1=1
return BasicCriterion(Equality.eq, ValueWrapper(1), ValueWrapper(1))
def between_and(field: Term, value: Tuple[Any, Any]) -> Criterion:
return field.between(value[0], value[1])
def not_equal(field: Term, value: Any) -> Criterion:
return field.ne(value) | field.isnull()
def is_null(field: Term, value: Any) -> Criterion:
if value:
return field.isnull()
return field.notnull()
def not_null(field: Term, value: Any) -> Criterion:
if value:
return field.notnull()
return field.isnull()
def contains(field: Term, value: str) -> Criterion:
return field.like(f"%{value}%")
def starts_with(field: Term, value: str) -> Criterion:
return field.like(f"{value}%")
def ends_with(field: Term, value: str) -> Criterion:
return field.like(f"%{value}")
def insensitive_exact(field: Term, value: str) -> Criterion:
return Upper(field).eq(Upper(f"{value}"))
def insensitive_contains(field: Term, value: str) -> Criterion:
return Upper(field).like(Upper(f"%{value}%"))
def insensitive_starts_with(field: Term, value: str) -> Criterion:
return Upper(field).like(Upper(f"{value}%"))
def insensitive_ends_with(field: Term, value: str) -> Criterion:
return Upper(field).like(Upper(f"%{value}"))
##############################################################################
# Filter resolvers
##############################################################################
def get_m2m_filters(field_name: str, field: ManyToManyFieldInstance) -> Dict[str, dict]:
target_table_pk = field.related_model._meta.pk
return {
field_name: {
"field": field.forward_key,
"backward_key": field.backward_key,
"operator": operator.eq,
"table": Table(field.through),
"value_encoder": target_table_pk.to_db_value,
},
f"{field_name}__not": {
"field": field.forward_key,
"backward_key": field.backward_key,
"operator": not_equal,
"table": Table(field.through),
"value_encoder": target_table_pk.to_db_value,
},
f"{field_name}__in": {
"field": field.forward_key,
"backward_key": field.backward_key,
"operator": is_in,
"table": Table(field.through),
"value_encoder": partial(related_list_encoder, field=target_table_pk),
},
f"{field_name}__not_in": {
"field": field.forward_key,
"backward_key": field.backward_key,
"operator": not_in,
"table": Table(field.through),
"value_encoder": partial(related_list_encoder, field=target_table_pk),
},
}
def get_backward_fk_filters(field_name: str, field: BackwardFKRelation) -> Dict[str, dict]:
target_table_pk = field.related_model._meta.pk
return {
field_name: {
"field": field.related_model._meta.pk_attr,
"backward_key": field.relation_field,
"operator": operator.eq,
"table": Table(field.related_model._meta.db_table),
"value_encoder": target_table_pk.to_db_value,
},
f"{field_name}__not": {
"field": field.related_model._meta.pk_attr,
"backward_key": field.relation_field,
"operator": not_equal,
"table": Table(field.related_model._meta.db_table),
"value_encoder": target_table_pk.to_db_value,
},
f"{field_name}__in": {
"field": field.related_model._meta.pk_attr,
"backward_key": field.relation_field,
"operator": is_in,
"table": Table(field.related_model._meta.db_table),
"value_encoder": partial(related_list_encoder, field=target_table_pk),
},
f"{field_name}__not_in": {
"field": field.related_model._meta.pk_attr,
"backward_key": field.relation_field,
"operator": not_in,
"table": Table(field.related_model._meta.db_table),
"value_encoder": partial(related_list_encoder, field=target_table_pk),
},
}
def get_filters_for_field(
field_name: str, field: Optional[Field], source_field: str
) -> Dict[str, dict]:
if isinstance(field, ManyToManyFieldInstance):
return get_m2m_filters(field_name, field)
if isinstance(field, BackwardFKRelation):
return get_backward_fk_filters(field_name, field)
actual_field_name = field_name
if field_name == "pk" and field:
actual_field_name = field.model_field_name
return {
field_name: {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.eq,
},
f"{field_name}__not": {
"field": actual_field_name,
"source_field": source_field,
"operator": not_equal,
},
f"{field_name}__in": {
"field": actual_field_name,
"source_field": source_field,
"operator": is_in,
"value_encoder": list_encoder,
},
f"{field_name}__not_in": {
"field": actual_field_name,
"source_field": source_field,
"operator": not_in,
"value_encoder": list_encoder,
},
f"{field_name}__isnull": {
"field": actual_field_name,
"source_field": source_field,
"operator": is_null,
"value_encoder": bool_encoder,
},
f"{field_name}__not_isnull": {
"field": actual_field_name,
"source_field": source_field,
"operator": not_null,
"value_encoder": bool_encoder,
},
f"{field_name}__gte": {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.ge,
},
f"{field_name}__lte": {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.le,
},
f"{field_name}__gt": {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.gt,
},
f"{field_name}__lt": {
"field": actual_field_name,
"source_field": source_field,
"operator": operator.lt,
},
f"{field_name}__range": {
"field": actual_field_name,
"source_field": source_field,
"operator": between_and,
"value_encoder": list_encoder,
},
f"{field_name}__contains": {
"field": actual_field_name,
"source_field": source_field,
"operator": contains,
"value_encoder": string_encoder,
},
f"{field_name}__startswith": {
"field": actual_field_name,
"source_field": source_field,
"operator": starts_with,
"value_encoder": string_encoder,
},
f"{field_name}__endswith": {
"field": actual_field_name,
"source_field": source_field,
"operator": ends_with,
"value_encoder": string_encoder,
},
f"{field_name}__iexact": {
"field": actual_field_name,
"source_field": source_field,
"operator": insensitive_exact,
"value_encoder": string_encoder,
},
f"{field_name}__icontains": {
"field": actual_field_name,
"source_field": source_field,
"operator": insensitive_contains,
"value_encoder": string_encoder,
},
f"{field_name}__istartswith": {
"field": actual_field_name,
"source_field": source_field,
"operator": insensitive_starts_with,
"value_encoder": string_encoder,
},
f"{field_name}__iendswith": {
"field": actual_field_name,
"source_field": source_field,
"operator": insensitive_ends_with,
"value_encoder": string_encoder,
},
}
| ./CrossVul/dataset_final_sorted/CWE-89/py/bad_3895_3 |
crossvul-python_data_bad_2971_2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#**
#
#########
# trape #
#########
#
# trape depends of this file
# For full copyright information this visit: https://github.com/boxug/trape
#
# Copyright 2017 by boxug / <hey@boxug.com>
#**
import time
import urllib2
from flask import Flask, render_template, session, request, json
from core.victim_objects import *
import core.stats
from core.utils import utils
from core.db import Database
# Main parts, to generate relationships among others
trape = core.stats.trape
app = core.stats.app
# call database
db = Database()
class victim_server(object):
@app.route("/" + trape.victim_path)
def homeVictim():
opener = urllib2.build_opener()
headers = victim_headers()
opener.addheaders = headers
html = victim_inject_code(opener.open(trape.url_to_clone).read(), 'lure')
return html
@app.route("/register", methods=["POST"])
def register():
vId = request.form['vId']
if vId == '':
vId = utils.generateToken(5)
victimConnect = victim(vId, request.environ['REMOTE_ADDR'], request.user_agent.platform, request.user_agent.browser, request.user_agent.version, utils.portScanner(request.environ['REMOTE_ADDR']), request.form['cpu'], time.strftime("%Y-%m-%d - %H:%M:%S"))
victimGeo = victim_geo(vId, 'city', request.form['countryCode'], request.form['country'], request.form['query'], request.form['lat'], request.form['lon'], request.form['org'], request.form['region'], request.form['regionName'], request.form['timezone'], request.form['zip'], request.form['isp'], str(request.user_agent))
utils.Go(utils.Color['white'] + "[" + utils.Color['blueBold'] + "*" + utils.Color['white'] + "]" + " A victim has been connected from " + utils.Color['blue'] + victimGeo.ip + utils.Color['white'] + ' with the following identifier: ' + utils.Color['green'] + vId + utils.Color['white'])
cant = int(db.sentences_victim('count_times', vId, 3, 0))
db.sentences_victim('insert_click', [vId, trape.url_to_clone, time.strftime("%Y-%m-%d - %H:%M:%S")], 2)
db.sentences_victim('delete_networks', [vId], 2)
if cant > 0:
utils.Go(utils.Color['white'] + "[" + utils.Color['blueBold'] + "*" + utils.Color['white'] + "]" + " " + "It\'s his " + str(cant + 1) + " time")
db.sentences_victim('update_victim', [victimConnect, vId, time.time()], 2)
db.sentences_victim('update_victim_geo', [victimGeo, vId], 2)
else:
utils.Go(utils.Color['white'] + "[" + utils.Color['blueBold'] + "*" + utils.Color['white'] + "]" + " " + "It\'s his first time")
db.sentences_victim('insert_victim', [victimConnect, vId, time.time()], 2)
db.sentences_victim('insert_victim_geo', [victimGeo, vId], 2)
return json.dumps({'status' : 'OK', 'vId' : vId});
@app.route("/nr", methods=["POST"])
def networkRegister():
vId = request.form['vId']
vIp = request.form['ip']
vnetwork = request.form['red']
if vId == '':
vId = utils.generateToken(5)
utils.Go(utils.Color['white'] + "[" + utils.Color['greenBold'] + "+" + utils.Color['white'] + "]" + utils.Color['whiteBold'] + " " + vnetwork + utils.Color['white'] + " session detected from " + utils.Color['blue'] + vIp + utils.Color['white'] + ' ' + "with ID: " + utils.Color['green'] + vId + utils.Color['white'])
cant = int(db.sentences_victim('count_victim_network', [vId, vnetwork], 3, 0))
if cant > 0:
db.sentences_victim('update_network', [vId, vnetwork, time.strftime("%Y-%m-%d - %H:%M:%S")], 2)
else:
db.sentences_victim('insert_networks', [vId, vIp, request.environ['REMOTE_ADDR'], vnetwork, time.strftime("%Y-%m-%d - %H:%M:%S")], 2)
return json.dumps({'status' : 'OK', 'vId' : vId});
@app.route("/redv")
def redirectVictim():
url = request.args.get('url')
opener = urllib2.build_opener()
headers = victim_headers()
opener.addheaders = headers
html = victim_inject_code(opener.open(url).read(), 'vscript')
return html
@app.route("/regv", methods=["POST"])
def registerRequest():
vrequest = victim_request(request.form['vId'], request.form['site'], request.form['fid'], request.form['name'], request.form['value'], request.form['sId'])
db.sentences_victim('insert_requests', [vrequest, time.strftime("%Y-%m-%d - %H:%M:%S")], 2)
utils.Go(utils.Color['white'] + "[" + utils.Color['greenBold'] + "=" + utils.Color['white'] + "]" + " " + 'Receiving data from: ' + utils.Color['green'] + vrequest.id + utils.Color['white'] + ' ' + 'on' + ' ' + utils.Color['blue'] + vrequest.site + utils.Color['white'] + '\t\n' + vrequest.fid + '\t' + vrequest.name + ':\t' + vrequest.value)
return json.dumps({'status' : 'OK', 'vId' : vrequest.id});
@app.route("/tping", methods=["POST"])
def receivePing():
vrequest = request.form['id']
db.sentences_victim('report_online', [vrequest])
return json.dumps({'status' : 'OK', 'vId' : vrequest});
| ./CrossVul/dataset_final_sorted/CWE-89/py/bad_2971_2 |
crossvul-python_data_good_2971_1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#**
#
#########
# trape #
#########
#
# trape depends of this file
# For full copyright information this visit: https://github.com/boxug/trape
#
# Copyright 2017 by boxug / <hey@boxug.com>
#**
import urllib2
from flask import Flask, render_template, session, request, json
from core.trape import Trape
from core.db import Database
# Main parts, to generate relationships among others
trape = Trape()
app = Flask(__name__, template_folder='../templates', static_folder='../static')
# call database
db = Database()
# preview header tool in console
trape.header()
@app.route("/" + trape.stats_path)
def index():
return render_template("/login.html")
@app.route("/logout")
def logout():
return render_template("/login.html")
@app.route("/login", methods=["POST"])
def login():
id = request.form['id']
if id == trape.stats_key:
return json.dumps({'status':'OK', 'path' : trape.home_path, 'victim_path' : trape.victim_path, 'url_to_clone' : trape.url_to_clone, 'app_port' : trape.app_port, 'date_start' : trape.date_start, 'user_ip' : '127.0.0.1'});
else:
return json.dumps({'status':'NOPE', 'path' : '/'});
@app.route("/get_data", methods=["POST"])
def home_get_dat():
d = db.sentences_stats('get_data')
n = db.sentences_stats('all_networks')
rows = db.sentences_stats('get_clicks')
c = rows[0][0]
rows = db.sentences_stats('get_sessions')
s = rows[0][0]
vId = ('online', )
rows = db.sentences_stats('get_online', vId)
o = rows[0][0]
return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o});
@app.route("/get_preview", methods=["POST"])
def home_get_preview():
vId = request.form['vId']
t = (vId,)
d = db.sentences_stats('get_preview', t)
n = db.sentences_stats('id_networks', t)
return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n});
@app.route("/get_title", methods=["POST"])
def home_get_title():
opener = urllib2.build_opener()
html = opener.open(trape.url_to_clone).read()
html = html[html.find('<title>') + 7 : html.find('</title>')]
return json.dumps({'status' : 'OK', 'title' : html});
@app.route("/get_requests", methods=["POST"])
def home_get_requests():
d = db.sentences_stats('get_requests')
return json.dumps({'status' : 'OK', 'd' : d}); | ./CrossVul/dataset_final_sorted/CWE-89/py/good_2971_1 |
crossvul-python_data_good_2971_0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#**
#
#########
# trape #
#########
#
# trape depends of this file
# For full copyright information this visit: https://github.com/boxug/trape
#
# Copyright 2017 by boxug / <hey@boxug.com>
#**
import sqlite3
class Database(object):
def __init__(self):
self.conn = sqlite3.connect("database.db", check_same_thread=False)
self.cursor = self.conn.cursor()
def loadDatabase(self):
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "geo" ( `id` TEXT, `city` TEXT, `country_code` TEXT, `country_name` TEXT, `ip` TEXT, `latitude` TEXT, `longitude` TEXT, `metro_code` TEXT, `region_code` TEXT, `region_name` TEXT, `time_zone` TEXT, `zip_code` TEXT, `isp` TEXT, `ua` TEXT, PRIMARY KEY(`id`) )""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "networks" ( `id` TEXT, `ip` TEXT, `public_ip` INTEGER, `network` TEXT, `date` TEXT )""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "requests" ( `id` TEXT, `user_id` TEXT, `site` TEXT, `fid` TEXT, `name` TEXT, `value` TEXT, `date` TEXT )""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "victims" ( `id` TEXT, `ip` TEXT, `date` TEXT, `time` REAL, `bVersion` TEXT, `browser` TEXT, `device` TEXT, `cpu` TEXT, `ports` TEXT, `status` TEXT )""")
self.cursor.execute("""CREATE TABLE IF NOT EXISTS "clicks" ( `id` TEXT, `site` TEXT, `date` TEXT )""")
self.conn.commit()
return True
def sql_execute(self, sentence):
if type(sentence) is str:
self.cursor.execute(sentence)
else:
self.cursor.execute(sentence[0], sentence[1])
return self.cursor.fetchall()
def sql_one_row(self, sentence, column):
if type(sentence) is str:
self.cursor.execute(sentence)
else:
self.cursor.execute(sentence[0], sentence[1])
return self.cursor.fetchone()[column]
def sql_insert(self, sentence):
if type(sentence) is str:
self.cursor.execute(sentence)
else:
self.cursor.execute(sentence[0], sentence[1])
self.conn.commit()
return True
def prop_sentences_stats(self, type, vId = None):
return {
'get_data' : "SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC",
'all_networks' : "SELECT networks.* FROM networks ORDER BY id",
'get_preview' : ("SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = ?" , vId),
'id_networks' : ("SELECT networks.* FROM networks WHERE id = ?", vId),
'get_requests' : "SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id ",
'get_sessions' : "SELECT COUNT(*) AS Total FROM networks",
'get_clicks' : "SELECT COUNT(*) AS Total FROM clicks",
'get_online' : ("SELECT COUNT(*) AS Total FROM victims WHERE status = ?", vId)
}.get(type, False)
def sentences_stats(self, type, vId = None):
return self.sql_execute(self.prop_sentences_stats(type, vId))
def prop_sentences_victim(self, type, data = None):
if type == 'count_victim':
t = (data,)
return ("SELECT COUNT(*) AS C FROM victims WHERE id = ?" , t)
elif type == 'count_times':
t = (data,)
return ("SELECT COUNT(*) AS C FROM clicks WHERE id = ?" , t)
elif type == 'update_victim':
t = (data[0].ip, data[0].date, data[0].version, data[0].browser, data[0].device, data[0].ports, data[2], data[0].cpu, 'online', data[1],)
return ("UPDATE victims SET ip = ?, date = ?, bVersion = ?, browser = ?, device = ?, ports = ?, time = ?, cpu = ?, status = ? WHERE id = ?", t)
elif type == 'update_victim_geo':
t = (data[0].city, data[0].country_code, data[0].country_name, data[0].ip, data[0].latitude, data[0].longitude, data[0].metro_code, data[0].region_code, data[0].region_name, data[0].time_zone, data[0].zip_code, data[0].isp, data[0].ua, data[1],)
return ("UPDATE geo SET city = ?, country_code = ?, country_name = ?, ip = ?, latitude = ?, longitude = ?, metro_code = ?, region_code = ?, region_name = ?, time_zone = ?, zip_code = ?, isp = ?, ua=? WHERE id = ?", t)
elif type == 'insert_victim':
t = (data[1], data[0].ip, data[0].date, data[0].version, data[0].browser, data[0].device, data[0].ports, data[2], data[0].cpu, 'online',)
return ("INSERT INTO victims(id, ip, date, bVersion, browser, device, ports, time, cpu, status) VALUES(?,?, ?,?, ?,?, ?, ?, ?, ?)", t)
elif type == 'insert_victim_geo':
t = (data[1], data[0].city, data[0].country_code, data[0].country_name, data[0].ip, data[0].latitude, data[0].longitude, data[0].metro_code, data[0].region_code, data[0].region_name, data[0].time_zone, data[0].zip_code, data[0].isp, data[0].ua,)
return ("INSERT INTO geo(id, city, country_code, country_name, ip, latitude, longitude, metro_code, region_code, region_name, time_zone, zip_code, isp, ua) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" , t)
elif type == 'count_victim_network':
return ("SELECT COUNT(*) AS C FROM networks WHERE id = ? AND network = ?", (data[0], data[1],))
elif type == 'delete_networks':
return ("DELETE FROM networks WHERE id = ?", (data[0],))
elif type == 'update_network':
return ("UPDATE networks SET date = ? WHERE id = ? AND network = ?" , (data[2], data[0], data[1],))
elif type == 'insert_networks':
t = (data[0], data[1], data[2], data[3], data[4],)
return ("INSERT INTO networks(id, public_ip, ip, network, date) VALUES(?,?, ?, ?,?)" , t)
elif type == 'insert_requests':
t = (data[0].sId, data[0].id, data[0].site, data[0].fid, data[0].name, data[0].value, data[1],)
return ("INSERT INTO requests(id, user_id, site, fid, name, value, date) VALUES(?, ?,?, ?, ?,?, ?)" , t)
elif type == 'insert_click':
return ("INSERT INTO clicks(id, site, date) VALUES(?, ?,?)", (data[0], data[1], data[2],))
elif type == 'report_online':
return ("UPDATE victims SET status = ? WHERE id = ?" , ('online', data[0],))
elif type == 'clean_online':
return ("UPDATE victims SET status = ? ", ('offline',))
elif type == 'disconnect_victim':
return ("UPDATE victims SET status = ? WHERE id = ?" , ('offline', data,))
else:
return False
def sentences_victim(self, type, data = None, sRun = 1, column = 0):
if sRun == 2:
return self.sql_insert(self.prop_sentences_victim(type, data))
elif sRun == 3:
return self.sql_one_row(self.prop_sentences_victim(type, data), column)
else:
return self.sql_execute(self.prop_sentences_victim(type, data))
def __del__(self):
self.conn.close() | ./CrossVul/dataset_final_sorted/CWE-89/py/good_2971_0 |
crossvul-python_data_good_4605_0 | from django.contrib.postgres.fields import ArrayField, JSONField
from django.db.models import Value
from django.db.models.aggregates import Aggregate
from .mixins import OrderableAggMixin
__all__ = [
'ArrayAgg', 'BitAnd', 'BitOr', 'BoolAnd', 'BoolOr', 'JSONBAgg', 'StringAgg',
]
class ArrayAgg(OrderableAggMixin, Aggregate):
function = 'ARRAY_AGG'
template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
allow_distinct = True
@property
def output_field(self):
return ArrayField(self.source_expressions[0].output_field)
def convert_value(self, value, expression, connection):
if not value:
return []
return value
class BitAnd(Aggregate):
function = 'BIT_AND'
class BitOr(Aggregate):
function = 'BIT_OR'
class BoolAnd(Aggregate):
function = 'BOOL_AND'
class BoolOr(Aggregate):
function = 'BOOL_OR'
class JSONBAgg(Aggregate):
function = 'JSONB_AGG'
output_field = JSONField()
def convert_value(self, value, expression, connection):
if not value:
return []
return value
class StringAgg(OrderableAggMixin, Aggregate):
function = 'STRING_AGG'
template = '%(function)s(%(distinct)s%(expressions)s %(ordering)s)'
allow_distinct = True
def __init__(self, expression, delimiter, **extra):
delimiter_expr = Value(str(delimiter))
super().__init__(expression, delimiter_expr, **extra)
def convert_value(self, value, expression, connection):
if not value:
return ''
return value
| ./CrossVul/dataset_final_sorted/CWE-89/py/good_4605_0 |
crossvul-python_data_bad_4605_1 | from django.db.models.expressions import F, OrderBy
class OrderableAggMixin:
def __init__(self, expression, ordering=(), **extra):
if not isinstance(ordering, (list, tuple)):
ordering = [ordering]
ordering = ordering or []
# Transform minus sign prefixed strings into an OrderBy() expression.
ordering = (
(OrderBy(F(o[1:]), descending=True) if isinstance(o, str) and o[0] == '-' else o)
for o in ordering
)
super().__init__(expression, **extra)
self.ordering = self._parse_expressions(*ordering)
def resolve_expression(self, *args, **kwargs):
self.ordering = [expr.resolve_expression(*args, **kwargs) for expr in self.ordering]
return super().resolve_expression(*args, **kwargs)
def as_sql(self, compiler, connection):
if self.ordering:
ordering_params = []
ordering_expr_sql = []
for expr in self.ordering:
expr_sql, expr_params = expr.as_sql(compiler, connection)
ordering_expr_sql.append(expr_sql)
ordering_params.extend(expr_params)
sql, sql_params = super().as_sql(compiler, connection, ordering=(
'ORDER BY ' + ', '.join(ordering_expr_sql)
))
return sql, sql_params + ordering_params
return super().as_sql(compiler, connection, ordering='')
def set_source_expressions(self, exprs):
# Extract the ordering expressions because ORDER BY clause is handled
# in a custom way.
self.ordering = exprs[self._get_ordering_expressions_index():]
return super().set_source_expressions(exprs[:self._get_ordering_expressions_index()])
def get_source_expressions(self):
return super().get_source_expressions() + self.ordering
def _get_ordering_expressions_index(self):
"""Return the index at which the ordering expressions start."""
source_expressions = self.get_source_expressions()
return len(source_expressions) - len(self.ordering)
| ./CrossVul/dataset_final_sorted/CWE-89/py/bad_4605_1 |
crossvul-python_data_good_4531_0 | # -*- coding: utf-8 -*-
'''
feedgen.entry
~~~~~~~~~~~~~
:copyright: 2013-2020, Lars Kiesow <lkiesow@uos.de>
:license: FreeBSD and LGPL, see license.* for more details.
'''
from datetime import datetime
import dateutil.parser
import dateutil.tz
import warnings
from lxml.etree import CDATA # nosec - adding CDATA entry is safe
from feedgen.compat import string_types
from feedgen.util import ensure_format, formatRFC2822, xml_fromstring, xml_elem
def _add_text_elm(entry, data, name):
"""Add a text subelement to an entry"""
if not data:
return
elm = xml_elem(name, entry)
type_ = data.get('type')
if data.get('src'):
if name != 'content':
raise ValueError("Only the 'content' element of an entry can "
"contain a 'src' attribute")
elm.attrib['src'] = data['src']
elif data.get(name):
# Surround xhtml with a div tag, parse it and embed it
if type_ == 'xhtml':
xhtml = '<div xmlns="http://www.w3.org/1999/xhtml">' \
+ data.get(name) + '</div>'
elm.append(xml_fromstring(xhtml))
elif type_ == 'CDATA':
elm.text = CDATA(data.get(name))
# Parse XML and embed it
elif type_ and (type_.endswith('/xml') or type_.endswith('+xml')):
elm.append(xml_fromstring(data[name]))
# Embed the text in escaped form
elif not type_ or type_.startswith('text') or type_ == 'html':
elm.text = data.get(name)
# Everything else should be included base64 encoded
else:
raise NotImplementedError(
'base64 encoded {} is not supported at the moment. '
'Pull requests adding support are welcome.'.format(name)
)
# Add type description of the content
if type_:
elm.attrib['type'] = type_
class FeedEntry(object):
'''FeedEntry call representing an ATOM feeds entry node or an RSS feeds item
node.
'''
def __init__(self):
# ATOM
# required
self.__atom_id = None
self.__atom_title = None
self.__atom_updated = datetime.now(dateutil.tz.tzutc())
# recommended
self.__atom_author = None
self.__atom_content = None
self.__atom_link = None
self.__atom_summary = None
# optional
self.__atom_category = None
self.__atom_contributor = None
self.__atom_published = None
self.__atom_source = None
self.__atom_rights = None
# RSS
self.__rss_author = None
self.__rss_category = None
self.__rss_comments = None
self.__rss_description = None
self.__rss_content = None
self.__rss_enclosure = None
self.__rss_guid = {}
self.__rss_link = None
self.__rss_pubDate = None
self.__rss_source = None
self.__rss_title = None
# Extension list:
self.__extensions = {}
self.__extensions_register = {}
def atom_entry(self, extensions=True):
'''Create an ATOM entry and return it.'''
entry = xml_elem('entry')
if not (self.__atom_id and self.__atom_title and self.__atom_updated):
raise ValueError('Required fields not set')
id = xml_elem('id', entry)
id.text = self.__atom_id
title = xml_elem('title', entry)
title.text = self.__atom_title
updated = xml_elem('updated', entry)
updated.text = self.__atom_updated.isoformat()
# An entry must contain an alternate link if there is no content
# element.
if not self.__atom_content:
links = self.__atom_link or []
if not [l for l in links if l.get('rel') == 'alternate']:
raise ValueError('Entry must contain an alternate link or ' +
'a content element.')
# Add author elements
for a in self.__atom_author or []:
# Atom requires a name. Skip elements without.
if not a.get('name'):
continue
author = xml_elem('author', entry)
name = xml_elem('name', author)
name.text = a.get('name')
if a.get('email'):
email = xml_elem('email', author)
email.text = a.get('email')
if a.get('uri'):
uri = xml_elem('uri', author)
uri.text = a.get('uri')
_add_text_elm(entry, self.__atom_content, 'content')
for l in self.__atom_link or []:
link = xml_elem('link', entry, href=l['href'])
if l.get('rel'):
link.attrib['rel'] = l['rel']
if l.get('type'):
link.attrib['type'] = l['type']
if l.get('hreflang'):
link.attrib['hreflang'] = l['hreflang']
if l.get('title'):
link.attrib['title'] = l['title']
if l.get('length'):
link.attrib['length'] = l['length']
_add_text_elm(entry, self.__atom_summary, 'summary')
for c in self.__atom_category or []:
cat = xml_elem('category', entry, term=c['term'])
if c.get('scheme'):
cat.attrib['scheme'] = c['scheme']
if c.get('label'):
cat.attrib['label'] = c['label']
# Add author elements
for c in self.__atom_contributor or []:
# Atom requires a name. Skip elements without.
if not c.get('name'):
continue
contrib = xml_elem('contributor', entry)
name = xml_elem('name', contrib)
name.text = c.get('name')
if c.get('email'):
email = xml_elem('email', contrib)
email.text = c.get('email')
if c.get('uri'):
uri = xml_elem('uri', contrib)
uri.text = c.get('uri')
if self.__atom_published:
published = xml_elem('published', entry)
published.text = self.__atom_published.isoformat()
if self.__atom_rights:
rights = xml_elem('rights', entry)
rights.text = self.__atom_rights
if self.__atom_source:
source = xml_elem('source', entry)
if self.__atom_source.get('title'):
source_title = xml_elem('title', source)
source_title.text = self.__atom_source['title']
if self.__atom_source.get('link'):
xml_elem('link', source, href=self.__atom_source['link'])
if extensions:
for ext in self.__extensions.values() or []:
if ext.get('atom'):
ext['inst'].extend_atom(entry)
return entry
def rss_entry(self, extensions=True):
'''Create a RSS item and return it.'''
entry = xml_elem('item')
if not (self.__rss_title or
self.__rss_description or
self.__rss_content):
raise ValueError('Required fields not set')
if self.__rss_title:
title = xml_elem('title', entry)
title.text = self.__rss_title
if self.__rss_link:
link = xml_elem('link', entry)
link.text = self.__rss_link
if self.__rss_description and self.__rss_content:
description = xml_elem('description', entry)
description.text = self.__rss_description
XMLNS_CONTENT = 'http://purl.org/rss/1.0/modules/content/'
content = xml_elem('{%s}encoded' % XMLNS_CONTENT, entry)
content.text = CDATA(self.__rss_content['content']) \
if self.__rss_content.get('type', '') == 'CDATA' \
else self.__rss_content['content']
elif self.__rss_description:
description = xml_elem('description', entry)
description.text = self.__rss_description
elif self.__rss_content:
description = xml_elem('description', entry)
description.text = CDATA(self.__rss_content['content']) \
if self.__rss_content.get('type', '') == 'CDATA' \
else self.__rss_content['content']
for a in self.__rss_author or []:
author = xml_elem('author', entry)
author.text = a
if self.__rss_guid.get('guid'):
guid = xml_elem('guid', entry)
guid.text = self.__rss_guid['guid']
permaLink = str(self.__rss_guid.get('permalink', False)).lower()
guid.attrib['isPermaLink'] = permaLink
for cat in self.__rss_category or []:
category = xml_elem('category', entry)
category.text = cat['value']
if cat.get('domain'):
category.attrib['domain'] = cat['domain']
if self.__rss_comments:
comments = xml_elem('comments', entry)
comments.text = self.__rss_comments
if self.__rss_enclosure:
enclosure = xml_elem('enclosure', entry)
enclosure.attrib['url'] = self.__rss_enclosure['url']
enclosure.attrib['length'] = self.__rss_enclosure['length']
enclosure.attrib['type'] = self.__rss_enclosure['type']
if self.__rss_pubDate:
pubDate = xml_elem('pubDate', entry)
pubDate.text = formatRFC2822(self.__rss_pubDate)
if self.__rss_source:
source = xml_elem('source', entry, url=self.__rss_source['url'])
source.text = self.__rss_source['title']
if extensions:
for ext in self.__extensions.values() or []:
if ext.get('rss'):
ext['inst'].extend_rss(entry)
return entry
def title(self, title=None):
'''Get or set the title value of the entry. It should contain a human
readable title for the entry. Title is mandatory for both ATOM and RSS
and should not be blank.
:param title: The new title of the entry.
:returns: The entriess title.
'''
if title is not None:
self.__atom_title = title
self.__rss_title = title
return self.__atom_title
def id(self, id=None):
'''Get or set the entry id which identifies the entry using a
universally unique and permanent URI. Two entries in a feed can have
the same value for id if they represent the same entry at different
points in time. This method will also set rss:guid with permalink set
to False. Id is mandatory for an ATOM entry.
:param id: New Id of the entry.
:returns: Id of the entry.
'''
if id is not None:
self.__atom_id = id
self.__rss_guid = {'guid': id, 'permalink': False}
return self.__atom_id
def guid(self, guid=None, permalink=False):
'''Get or set the entries guid which is a string that uniquely
identifies the item. This will also set atom:id.
:param guid: Id of the entry.
:param permalink: If this is a permanent identifier for this item
:returns: Id and permalink setting of the entry.
'''
if guid is not None:
self.__atom_id = guid
self.__rss_guid = {'guid': guid, 'permalink': permalink}
return self.__rss_guid
def updated(self, updated=None):
'''Set or get the updated value which indicates the last time the entry
was modified in a significant way.
The value can either be a string which will automatically be parsed or
a datetime.datetime object. In any case it is necessary that the value
include timezone information.
:param updated: The modification date.
:returns: Modification date as datetime.datetime
'''
if updated is not None:
if isinstance(updated, string_types):
updated = dateutil.parser.parse(updated)
if not isinstance(updated, datetime):
raise ValueError('Invalid datetime format')
if updated.tzinfo is None:
raise ValueError('Datetime object has no timezone info')
self.__atom_updated = updated
self.__rss_lastBuildDate = updated
return self.__atom_updated
def author(self, author=None, replace=False, **kwargs):
'''Get or set author data. An author element is a dict containing a
name, an email address and a uri. Name is mandatory for ATOM, email is
mandatory for RSS.
This method can be called with:
- the fields of an author as keyword arguments
- the fields of an author as a dictionary
- a list of dictionaries containing the author fields
An author has the following fields:
- *name* conveys a human-readable name for the person.
- *uri* contains a home page for the person.
- *email* contains an email address for the person.
:param author: Dict or list of dicts with author data.
:param replace: Add or replace old data.
Example::
>>> author({'name':'John Doe', 'email':'jdoe@example.com'})
[{'name':'John Doe','email':'jdoe@example.com'}]
>>> author([{'name': 'Mr. X'}, {'name': 'Max'}])
[{'name':'John Doe','email':'jdoe@example.com'},
{'name':'John Doe'}, {'name':'Max'}]
>>> author(name='John Doe', email='jdoe@example.com', replace=True)
[{'name':'John Doe','email':'jdoe@example.com'}]
'''
if author is None and kwargs:
author = kwargs
if author is not None:
if replace or self.__atom_author is None:
self.__atom_author = []
self.__atom_author += ensure_format(author,
set(['name', 'email', 'uri']),
set())
self.__rss_author = []
for a in self.__atom_author:
if a.get('email'):
if a.get('name'):
self.__rss_author.append('%(email)s (%(name)s)' % a)
else:
self.__rss_author.append('%(email)s' % a)
return self.__atom_author
def content(self, content=None, src=None, type=None):
'''Get or set the content of the entry which contains or links to the
complete content of the entry. Content must be provided for ATOM
entries if there is no alternate link, and should be provided if there
is no summary. If the content is set (not linked) it will also set
rss:description.
:param content: The content of the feed entry.
:param src: Link to the entries content.
:param type: If type is CDATA content would not be escaped.
:returns: Content element of the entry.
'''
if src is not None:
self.__atom_content = {'src': src}
elif content is not None:
self.__atom_content = {'content': content}
self.__rss_content = {'content': content}
if type is not None:
self.__atom_content['type'] = type
self.__rss_content['type'] = type
return self.__atom_content
def link(self, link=None, replace=False, **kwargs):
'''Get or set link data. An link element is a dict with the fields
href, rel, type, hreflang, title, and length. Href is mandatory for
ATOM.
This method can be called with:
- the fields of a link as keyword arguments
- the fields of a link as a dictionary
- a list of dictionaries containing the link fields
A link has the following fields:
- *href* is the URI of the referenced resource (typically a Web page)
- *rel* contains a single link relationship type. It can be a full URI,
or one of the following predefined values (default=alternate):
- *alternate* an alternate representation of the entry or feed, for
example a permalink to the html version of the entry, or the
front page of the weblog.
- *enclosure* a related resource which is potentially large in size
and might require special handling, for example an audio or video
recording.
- *related* an document related to the entry or feed.
- *self* the feed itself.
- *via* the source of the information provided in the entry.
- *type* indicates the media type of the resource.
- *hreflang* indicates the language of the referenced resource.
- *title* human readable information about the link, typically for
display purposes.
- *length* the length of the resource, in bytes.
RSS only supports one link with nothing but a URL. So for the RSS link
element the last link with rel=alternate is used.
RSS also supports one enclusure element per entry which is covered by
the link element in ATOM feed entries. So for the RSS enclusure element
the last link with rel=enclosure is used.
:param link: Dict or list of dicts with data.
:param replace: Add or replace old data.
:returns: List of link data.
'''
if link is None and kwargs:
link = kwargs
if link is not None:
if replace or self.__atom_link is None:
self.__atom_link = []
self.__atom_link += ensure_format(
link,
set(['href', 'rel', 'type', 'hreflang', 'title', 'length']),
set(['href']),
{'rel': ['alternate', 'enclosure', 'related', 'self', 'via']},
{'rel': 'alternate'})
# RSS only needs one URL. We use the first link for RSS:
for l in self.__atom_link:
if l.get('rel') == 'alternate':
self.__rss_link = l['href']
elif l.get('rel') == 'enclosure':
self.__rss_enclosure = {'url': l['href']}
self.__rss_enclosure['type'] = l.get('type')
self.__rss_enclosure['length'] = l.get('length') or '0'
# return the set with more information (atom)
return self.__atom_link
def summary(self, summary=None, type=None):
'''Get or set the summary element of an entry which conveys a short
summary, abstract, or excerpt of the entry. Summary is an ATOM only
element and should be provided if there either is no content provided
for the entry, or that content is not inline (i.e., contains a src
attribute), or if the content is encoded in base64. This method will
also set the rss:description field if it wasn't previously set or
contains the old value of summary.
:param summary: Summary of the entries contents.
:returns: Summary of the entries contents.
'''
if summary is not None:
# Replace the RSS description with the summary if it was the
# summary before. Not if it is the description.
if not self.__rss_description or (
self.__atom_summary and
self.__rss_description == self.__atom_summary.get("summary")
):
self.__rss_description = summary
self.__atom_summary = {'summary': summary}
if type is not None:
self.__atom_summary['type'] = type
return self.__atom_summary
def description(self, description=None, isSummary=False):
'''Get or set the description value which is the item synopsis.
Description is an RSS only element. For ATOM feeds it is split in
summary and content. The isSummary parameter can be used to control
which ATOM value is set when setting description.
:param description: Description of the entry.
:param isSummary: If the description should be used as content or
summary.
:returns: The entries description.
'''
if description is not None:
self.__rss_description = description
if isSummary:
self.__atom_summary = description
else:
self.__atom_content = {'content': description}
return self.__rss_description
def category(self, category=None, replace=False, **kwargs):
'''Get or set categories that the entry belongs to.
This method can be called with:
- the fields of a category as keyword arguments
- the fields of a category as a dictionary
- a list of dictionaries containing the category fields
A categories has the following fields:
- *term* identifies the category
- *scheme* identifies the categorization scheme via a URI.
- *label* provides a human-readable label for display
If a label is present it is used for the RSS feeds. Otherwise the term
is used. The scheme is used for the domain attribute in RSS.
:param category: Dict or list of dicts with data.
:param replace: Add or replace old data.
:returns: List of category data.
'''
if category is None and kwargs:
category = kwargs
if category is not None:
if replace or self.__atom_category is None:
self.__atom_category = []
self.__atom_category += ensure_format(
category,
set(['term', 'scheme', 'label']),
set(['term']))
# Map the ATOM categories to RSS categories. Use the atom:label as
# name or if not present the atom:term. The atom:scheme is the
# rss:domain.
self.__rss_category = []
for cat in self.__atom_category:
rss_cat = {}
rss_cat['value'] = cat.get('label', cat['term'])
if cat.get('scheme'):
rss_cat['domain'] = cat['scheme']
self.__rss_category.append(rss_cat)
return self.__atom_category
def contributor(self, contributor=None, replace=False, **kwargs):
'''Get or set the contributor data of the feed. This is an ATOM only
value.
This method can be called with:
- the fields of an contributor as keyword arguments
- the fields of an contributor as a dictionary
- a list of dictionaries containing the contributor fields
An contributor has the following fields:
- *name* conveys a human-readable name for the person.
- *uri* contains a home page for the person.
- *email* contains an email address for the person.
:param contributor: Dictionary or list of dictionaries with contributor
data.
:param replace: Add or replace old data.
:returns: List of contributors as dictionaries.
'''
if contributor is None and kwargs:
contributor = kwargs
if contributor is not None:
if replace or self.__atom_contributor is None:
self.__atom_contributor = []
self.__atom_contributor += ensure_format(
contributor, set(['name', 'email', 'uri']), set(['name']))
return self.__atom_contributor
def published(self, published=None):
'''Set or get the published value which contains the time of the initial
creation or first availability of the entry.
The value can either be a string which will automatically be parsed or
a datetime.datetime object. In any case it is necessary that the value
include timezone information.
:param published: The creation date.
:returns: Creation date as datetime.datetime
'''
if published is not None:
if isinstance(published, string_types):
published = dateutil.parser.parse(published)
if not isinstance(published, datetime):
raise ValueError('Invalid datetime format')
if published.tzinfo is None:
raise ValueError('Datetime object has no timezone info')
self.__atom_published = published
self.__rss_pubDate = published
return self.__atom_published
def pubDate(self, pubDate=None):
'''Get or set the pubDate of the entry which indicates when the entry
was published. This method is just another name for the published(...)
method.
'''
return self.published(pubDate)
def pubdate(self, pubDate=None):
'''Get or set the pubDate of the entry which indicates when the entry
was published. This method is just another name for the published(...)
method.
pubdate(…) is deprecated and may be removed in feedgen ≥ 0.8. Use
pubDate(…) instead.
'''
warnings.warn('pubdate(…) is deprecated and may be removed in feedgen '
'≥ 0.8. Use pubDate(…) instead.')
return self.published(pubDate)
def rights(self, rights=None):
'''Get or set the rights value of the entry which conveys information
about rights, e.g. copyrights, held in and over the entry. This ATOM
value will also set rss:copyright.
:param rights: Rights information of the feed.
:returns: Rights information of the feed.
'''
if rights is not None:
self.__atom_rights = rights
return self.__atom_rights
def comments(self, comments=None):
'''Get or set the value of comments which is the URL of the comments
page for the item. This is a RSS only value.
:param comments: URL to the comments page.
:returns: URL to the comments page.
'''
if comments is not None:
self.__rss_comments = comments
return self.__rss_comments
def source(self, url=None, title=None):
'''Get or set the source for the current feed entry.
Note that ATOM feeds support a lot more sub elements than title and URL
(which is what RSS supports) but these are currently not supported.
Patches are welcome.
:param url: Link to the source.
:param title: Title of the linked resource
:returns: Source element as dictionaries.
'''
if url is not None and title is not None:
self.__rss_source = {'url': url, 'title': title}
self.__atom_source = {'link': url, 'title': title}
return self.__rss_source
def enclosure(self, url=None, length=None, type=None):
'''Get or set the value of enclosure which describes a media object
that is attached to the item. This is a RSS only value which is
represented by link(rel=enclosure) in ATOM. ATOM feeds can furthermore
contain several enclosures while RSS may contain only one. That is why
this method, if repeatedly called, will add more than one enclosures to
the feed. However, only the last one is used for RSS.
:param url: URL of the media object.
:param length: Size of the media in bytes.
:param type: Mimetype of the linked media.
:returns: Data of the enclosure element.
'''
if url is not None:
self.link(href=url, rel='enclosure', type=type, length=length)
return self.__rss_enclosure
def ttl(self, ttl=None):
'''Get or set the ttl value. It is an RSS only element. ttl stands for
time to live. It's a number of minutes that indicates how long a
channel can be cached before refreshing from the source.
:param ttl: Integer value representing the time to live.
:returns: Time to live of of the entry.
'''
if ttl is not None:
self.__rss_ttl = int(ttl)
return self.__rss_ttl
def load_extension(self, name, atom=True, rss=True):
'''Load a specific extension by name.
:param name: Name of the extension to load.
:param atom: If the extension should be used for ATOM feeds.
:param rss: If the extension should be used for RSS feeds.
'''
# Check loaded extensions
if not isinstance(self.__extensions, dict):
self.__extensions = {}
if name in self.__extensions.keys():
raise ImportError('Extension already loaded')
# Load extension
extname = name[0].upper() + name[1:] + 'EntryExtension'
try:
supmod = __import__('feedgen.ext.%s_entry' % name)
extmod = getattr(supmod.ext, name + '_entry')
except ImportError:
# Use FeedExtension module instead
supmod = __import__('feedgen.ext.%s' % name)
extmod = getattr(supmod.ext, name)
ext = getattr(extmod, extname)
self.register_extension(name, ext, atom, rss)
def register_extension(self, namespace, extension_class_entry=None,
atom=True, rss=True):
'''Register a specific extension by classes to a namespace.
:param namespace: namespace for the extension
:param extension_class_entry: Class of the entry extension to load.
:param atom: If the extension should be used for ATOM feeds.
:param rss: If the extension should be used for RSS feeds.
'''
# Check loaded extensions
# `load_extension` ignores the "Extension" suffix.
if not isinstance(self.__extensions, dict):
self.__extensions = {}
if namespace in self.__extensions.keys():
raise ImportError('Extension already loaded')
if not extension_class_entry:
raise ImportError('No extension class')
extinst = extension_class_entry()
setattr(self, namespace, extinst)
# `load_extension` registry
self.__extensions[namespace] = {
'inst': extinst,
'extension_class_entry': extension_class_entry,
'atom': atom,
'rss': rss
}
| ./CrossVul/dataset_final_sorted/CWE-776/py/good_4531_0 |
crossvul-python_data_bad_4531_1 | # -*- coding: utf-8 -*-
'''
feedgen.ext.dc
~~~~~~~~~~~~~~~~~~~
Extends the FeedGenerator to add Dubline Core Elements to the feeds.
Descriptions partly taken from
http://dublincore.org/documents/dcmi-terms/#elements-coverage
:copyright: 2013-2017, Lars Kiesow <lkiesow@uos.de>
:license: FreeBSD and LGPL, see license.* for more details.
'''
from lxml import etree
from feedgen.ext.base import BaseExtension
class DcBaseExtension(BaseExtension):
'''Dublin Core Elements extension for podcasts.
'''
def __init__(self):
# http://dublincore.org/documents/usageguide/elements.shtml
# http://dublincore.org/documents/dces/
# http://dublincore.org/documents/dcmi-terms/
self._dcelem_contributor = None
self._dcelem_coverage = None
self._dcelem_creator = None
self._dcelem_date = None
self._dcelem_description = None
self._dcelem_format = None
self._dcelem_identifier = None
self._dcelem_language = None
self._dcelem_publisher = None
self._dcelem_relation = None
self._dcelem_rights = None
self._dcelem_source = None
self._dcelem_subject = None
self._dcelem_title = None
self._dcelem_type = None
def extend_ns(self):
return {'dc': 'http://purl.org/dc/elements/1.1/'}
def _extend_xml(self, xml_elem):
'''Extend xml_elem with set DC fields.
:param xml_elem: etree element
'''
DCELEMENTS_NS = 'http://purl.org/dc/elements/1.1/'
for elem in ['contributor', 'coverage', 'creator', 'date',
'description', 'language', 'publisher', 'relation',
'rights', 'source', 'subject', 'title', 'type', 'format',
'identifier']:
if hasattr(self, '_dcelem_%s' % elem):
for val in getattr(self, '_dcelem_%s' % elem) or []:
node = etree.SubElement(xml_elem,
'{%s}%s' % (DCELEMENTS_NS, elem))
node.text = val
def extend_atom(self, atom_feed):
'''Extend an Atom feed with the set DC fields.
:param atom_feed: The feed root element
:returns: The feed root element
'''
self._extend_xml(atom_feed)
return atom_feed
def extend_rss(self, rss_feed):
'''Extend a RSS feed with the set DC fields.
:param rss_feed: The feed root element
:returns: The feed root element.
'''
channel = rss_feed[0]
self._extend_xml(channel)
return rss_feed
def dc_contributor(self, contributor=None, replace=False):
'''Get or set the dc:contributor which is an entity responsible for
making contributions to the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-contributor
:param contributor: Contributor or list of contributors.
:param replace: Replace alredy set contributors (deault: False).
:returns: List of contributors.
'''
if contributor is not None:
if not isinstance(contributor, list):
contributor = [contributor]
if replace or not self._dcelem_contributor:
self._dcelem_contributor = []
self._dcelem_contributor += contributor
return self._dcelem_contributor
def dc_coverage(self, coverage=None, replace=True):
'''Get or set the dc:coverage which indicated the spatial or temporal
topic of the resource, the spatial applicability of the resource, or
the jurisdiction under which the resource is relevant.
Spatial topic and spatial applicability may be a named place or a
location specified by its geographic coordinates. Temporal topic may be
a named period, date, or date range. A jurisdiction may be a named
administrative entity or a geographic place to which the resource
applies. Recommended best practice is to use a controlled vocabulary
such as the Thesaurus of Geographic Names [TGN]. Where appropriate,
named places or time periods can be used in preference to numeric
identifiers such as sets of coordinates or date ranges.
References:
[TGN] http://www.getty.edu/research/tools/vocabulary/tgn/index.html
:param coverage: Coverage of the feed.
:param replace: Replace already set coverage (default: True).
:returns: Coverage of the feed.
'''
if coverage is not None:
if not isinstance(coverage, list):
coverage = [coverage]
if replace or not self._dcelem_coverage:
self._dcelem_coverage = []
self._dcelem_coverage = coverage
return self._dcelem_coverage
def dc_creator(self, creator=None, replace=False):
'''Get or set the dc:creator which is an entity primarily responsible
for making the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-creator
:param creator: Creator or list of creators.
:param replace: Replace alredy set creators (deault: False).
:returns: List of creators.
'''
if creator is not None:
if not isinstance(creator, list):
creator = [creator]
if replace or not self._dcelem_creator:
self._dcelem_creator = []
self._dcelem_creator += creator
return self._dcelem_creator
def dc_date(self, date=None, replace=True):
'''Get or set the dc:date which describes a point or period of time
associated with an event in the lifecycle of the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-date
:param date: Date or list of dates.
:param replace: Replace alredy set dates (deault: True).
:returns: List of dates.
'''
if date is not None:
if not isinstance(date, list):
date = [date]
if replace or not self._dcelem_date:
self._dcelem_date = []
self._dcelem_date += date
return self._dcelem_date
def dc_description(self, description=None, replace=True):
'''Get or set the dc:description which is an account of the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-description
:param description: Description or list of descriptions.
:param replace: Replace alredy set descriptions (deault: True).
:returns: List of descriptions.
'''
if description is not None:
if not isinstance(description, list):
description = [description]
if replace or not self._dcelem_description:
self._dcelem_description = []
self._dcelem_description += description
return self._dcelem_description
def dc_format(self, format=None, replace=True):
'''Get or set the dc:format which describes the file format, physical
medium, or dimensions of the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-format
:param format: Format of the resource or list of formats.
:param replace: Replace alredy set format (deault: True).
:returns: Format of the resource.
'''
if format is not None:
if not isinstance(format, list):
format = [format]
if replace or not self._dcelem_format:
self._dcelem_format = []
self._dcelem_format += format
return self._dcelem_format
def dc_identifier(self, identifier=None, replace=True):
'''Get or set the dc:identifier which should be an unambiguous
reference to the resource within a given context.
For more inidentifierion see:
http://dublincore.org/documents/dcmi-terms/#elements-identifier
:param identifier: Identifier of the resource or list of identifiers.
:param replace: Replace alredy set identifier (deault: True).
:returns: Identifiers of the resource.
'''
if identifier is not None:
if not isinstance(identifier, list):
identifier = [identifier]
if replace or not self._dcelem_identifier:
self._dcelem_identifier = []
self._dcelem_identifier += identifier
return self._dcelem_identifier
def dc_language(self, language=None, replace=True):
'''Get or set the dc:language which describes a language of the
resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-language
:param language: Language or list of languages.
:param replace: Replace alredy set languages (deault: True).
:returns: List of languages.
'''
if language is not None:
if not isinstance(language, list):
language = [language]
if replace or not self._dcelem_language:
self._dcelem_language = []
self._dcelem_language += language
return self._dcelem_language
def dc_publisher(self, publisher=None, replace=False):
'''Get or set the dc:publisher which is an entity responsible for
making the resource available.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-publisher
:param publisher: Publisher or list of publishers.
:param replace: Replace alredy set publishers (deault: False).
:returns: List of publishers.
'''
if publisher is not None:
if not isinstance(publisher, list):
publisher = [publisher]
if replace or not self._dcelem_publisher:
self._dcelem_publisher = []
self._dcelem_publisher += publisher
return self._dcelem_publisher
def dc_relation(self, relation=None, replace=False):
'''Get or set the dc:relation which describes a related resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-relation
:param relation: Relation or list of relations.
:param replace: Replace alredy set relations (deault: False).
:returns: List of relations.
'''
if relation is not None:
if not isinstance(relation, list):
relation = [relation]
if replace or not self._dcelem_relation:
self._dcelem_relation = []
self._dcelem_relation += relation
return self._dcelem_relation
def dc_rights(self, rights=None, replace=False):
'''Get or set the dc:rights which may contain information about rights
held in and over the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-rights
:param rights: Rights information or list of rights information.
:param replace: Replace alredy set rightss (deault: False).
:returns: List of rights information.
'''
if rights is not None:
if not isinstance(rights, list):
rights = [rights]
if replace or not self._dcelem_rights:
self._dcelem_rights = []
self._dcelem_rights += rights
return self._dcelem_rights
def dc_source(self, source=None, replace=False):
'''Get or set the dc:source which is a related resource from which the
described resource is derived.
The described resource may be derived from the related resource in
whole or in part. Recommended best practice is to identify the related
resource by means of a string conforming to a formal identification
system.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-source
:param source: Source or list of sources.
:param replace: Replace alredy set sources (deault: False).
:returns: List of sources.
'''
if source is not None:
if not isinstance(source, list):
source = [source]
if replace or not self._dcelem_source:
self._dcelem_source = []
self._dcelem_source += source
return self._dcelem_source
def dc_subject(self, subject=None, replace=False):
'''Get or set the dc:subject which describes the topic of the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-subject
:param subject: Subject or list of subjects.
:param replace: Replace alredy set subjects (deault: False).
:returns: List of subjects.
'''
if subject is not None:
if not isinstance(subject, list):
subject = [subject]
if replace or not self._dcelem_subject:
self._dcelem_subject = []
self._dcelem_subject += subject
return self._dcelem_subject
def dc_title(self, title=None, replace=True):
'''Get or set the dc:title which is a name given to the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-title
:param title: Title or list of titles.
:param replace: Replace alredy set titles (deault: False).
:returns: List of titles.
'''
if title is not None:
if not isinstance(title, list):
title = [title]
if replace or not self._dcelem_title:
self._dcelem_title = []
self._dcelem_title += title
return self._dcelem_title
def dc_type(self, type=None, replace=False):
'''Get or set the dc:type which describes the nature or genre of the
resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-type
:param type: Type or list of types.
:param replace: Replace alredy set types (deault: False).
:returns: List of types.
'''
if type is not None:
if not isinstance(type, list):
type = [type]
if replace or not self._dcelem_type:
self._dcelem_type = []
self._dcelem_type += type
return self._dcelem_type
class DcExtension(DcBaseExtension):
'''Dublin Core Elements extension for podcasts.
'''
class DcEntryExtension(DcBaseExtension):
'''Dublin Core Elements extension for podcasts.
'''
def extend_atom(self, entry):
'''Add dc elements to an atom item. Alters the item itself.
:param entry: An atom entry element.
:returns: The entry element.
'''
self._extend_xml(entry)
return entry
def extend_rss(self, item):
'''Add dc elements to a RSS item. Alters the item itself.
:param item: A RSS item element.
:returns: The item element.
'''
self._extend_xml(item)
return item
| ./CrossVul/dataset_final_sorted/CWE-776/py/bad_4531_1 |
crossvul-python_data_good_4531_3 | # -*- coding: utf-8 -*-
'''
feedgen.ext.media
~~~~~~~~~~~~~~~~~
Extends the feedgen to produce media tags.
:copyright: 2013-2017, Lars Kiesow <lkiesow@uos.de>
:license: FreeBSD and LGPL, see license.* for more details.
'''
from feedgen.ext.base import BaseEntryExtension, BaseExtension
from feedgen.util import ensure_format, xml_elem
MEDIA_NS = 'http://search.yahoo.com/mrss/'
class MediaExtension(BaseExtension):
'''FeedGenerator extension for torrent feeds.
'''
def extend_ns(self):
return {'media': MEDIA_NS}
class MediaEntryExtension(BaseEntryExtension):
'''FeedEntry extension for media tags.
'''
def __init__(self):
self.__media_content = []
self.__media_thumbnail = []
def extend_atom(self, entry):
'''Add additional fields to an RSS item.
:param feed: The RSS item XML element to use.
'''
groups = {None: entry}
for media_content in self.__media_content:
# Define current media:group
group = groups.get(media_content.get('group'))
if group is None:
group = xml_elem('{%s}group' % MEDIA_NS, entry)
groups[media_content.get('group')] = group
# Add content
content = xml_elem('{%s}content' % MEDIA_NS, group)
for attr in ('url', 'fileSize', 'type', 'medium', 'isDefault',
'expression', 'bitrate', 'framerate', 'samplingrate',
'channels', 'duration', 'height', 'width', 'lang'):
if media_content.get(attr):
content.set(attr, media_content[attr])
for media_thumbnail in self.__media_thumbnail:
# Define current media:group
group = groups.get(media_thumbnail.get('group'))
if group is None:
group = xml_elem('{%s}group' % MEDIA_NS, entry)
groups[media_thumbnail.get('group')] = group
# Add thumbnails
thumbnail = xml_elem('{%s}thumbnail' % MEDIA_NS, group)
for attr in ('url', 'height', 'width', 'time'):
if media_thumbnail.get(attr):
thumbnail.set(attr, media_thumbnail[attr])
return entry
def extend_rss(self, item):
return self.extend_atom(item)
def content(self, content=None, replace=False, group='default', **kwargs):
'''Get or set media:content data.
This method can be called with:
- the fields of a media:content as keyword arguments
- the fields of a media:content as a dictionary
- a list of dictionaries containing the media:content fields
<media:content> is a sub-element of either <item> or <media:group>.
Media objects that are not the same content should not be included in
the same <media:group> element. The sequence of these items implies
the order of presentation. While many of the attributes appear to be
audio/video specific, this element can be used to publish any type
of media. It contains 14 attributes, most of which are optional.
media:content has the following fields:
- *url* should specify the direct URL to the media object.
- *fileSize* number of bytes of the media object.
- *type* standard MIME type of the object.
- *medium* type of object (image | audio | video | document |
executable).
- *isDefault* determines if this is the default object.
- *expression* determines if the object is a sample or the full version
of the object, or even if it is a continuous stream (sample | full |
nonstop).
- *bitrate* kilobits per second rate of media.
- *framerate* number of frames per second for the media object.
- *samplingrate* number of samples per second taken to create the media
object. It is expressed in thousands of samples per second (kHz).
- *channels* number of audio channels in the media object.
- *duration* number of seconds the media object plays.
- *height* height of the media object.
- *width* width of the media object.
- *lang* is the primary language encapsulated in the media object.
:param content: Dictionary or list of dictionaries with content data.
:param replace: Add or replace old data.
:param group: Media group to put this content in.
:returns: The media content tag.
'''
# Handle kwargs
if content is None and kwargs:
content = kwargs
# Handle new data
if content is not None:
# Reset data if we want to replace them
if replace or self.__media_content is None:
self.__media_content = []
# Ensure list
if not isinstance(content, list):
content = [content]
# define media group
for c in content:
c['group'] = c.get('group', group)
self.__media_content += ensure_format(
content,
set(['url', 'fileSize', 'type', 'medium', 'isDefault',
'expression', 'bitrate', 'framerate', 'samplingrate',
'channels', 'duration', 'height', 'width', 'lang',
'group']),
set(['url', 'group']))
return self.__media_content
def thumbnail(self, thumbnail=None, replace=False, group='default',
**kwargs):
'''Get or set media:thumbnail data.
This method can be called with:
- the fields of a media:content as keyword arguments
- the fields of a media:content as a dictionary
- a list of dictionaries containing the media:content fields
Allows particular images to be used as representative images for
the media object. If multiple thumbnails are included, and time
coding is not at play, it is assumed that the images are in order
of importance. It has one required attribute and three optional
attributes.
media:thumbnail has the following fields:
- *url* should specify the direct URL to the media object.
- *height* height of the media object.
- *width* width of the media object.
- *time* specifies the time offset in relation to the media object.
:param thumbnail: Dictionary or list of dictionaries with thumbnail
data.
:param replace: Add or replace old data.
:param group: Media group to put this content in.
:returns: The media thumbnail tag.
'''
# Handle kwargs
if thumbnail is None and kwargs:
thumbnail = kwargs
# Handle new data
if thumbnail is not None:
# Reset data if we want to replace them
if replace or self.__media_thumbnail is None:
self.__media_thumbnail = []
# Ensure list
if not isinstance(thumbnail, list):
thumbnail = [thumbnail]
# Define media group
for t in thumbnail:
t['group'] = t.get('group', group)
self.__media_thumbnail += ensure_format(
thumbnail,
set(['url', 'height', 'width', 'time', 'group']),
set(['url', 'group']))
return self.__media_thumbnail
| ./CrossVul/dataset_final_sorted/CWE-776/py/good_4531_3 |
crossvul-python_data_bad_4531_3 | # -*- coding: utf-8 -*-
'''
feedgen.ext.media
~~~~~~~~~~~~~~~~~
Extends the feedgen to produce media tags.
:copyright: 2013-2017, Lars Kiesow <lkiesow@uos.de>
:license: FreeBSD and LGPL, see license.* for more details.
'''
from lxml import etree
from feedgen.ext.base import BaseEntryExtension, BaseExtension
from feedgen.util import ensure_format
MEDIA_NS = 'http://search.yahoo.com/mrss/'
class MediaExtension(BaseExtension):
'''FeedGenerator extension for torrent feeds.
'''
def extend_ns(self):
return {'media': MEDIA_NS}
class MediaEntryExtension(BaseEntryExtension):
'''FeedEntry extension for media tags.
'''
def __init__(self):
self.__media_content = []
self.__media_thumbnail = []
def extend_atom(self, entry):
'''Add additional fields to an RSS item.
:param feed: The RSS item XML element to use.
'''
groups = {None: entry}
for media_content in self.__media_content:
# Define current media:group
group = groups.get(media_content.get('group'))
if group is None:
group = etree.SubElement(entry, '{%s}group' % MEDIA_NS)
groups[media_content.get('group')] = group
# Add content
content = etree.SubElement(group, '{%s}content' % MEDIA_NS)
for attr in ('url', 'fileSize', 'type', 'medium', 'isDefault',
'expression', 'bitrate', 'framerate', 'samplingrate',
'channels', 'duration', 'height', 'width', 'lang'):
if media_content.get(attr):
content.set(attr, media_content[attr])
for media_thumbnail in self.__media_thumbnail:
# Define current media:group
group = groups.get(media_thumbnail.get('group'))
if group is None:
group = etree.SubElement(entry, '{%s}group' % MEDIA_NS)
groups[media_thumbnail.get('group')] = group
# Add thumbnails
thumbnail = etree.SubElement(group, '{%s}thumbnail' % MEDIA_NS)
for attr in ('url', 'height', 'width', 'time'):
if media_thumbnail.get(attr):
thumbnail.set(attr, media_thumbnail[attr])
return entry
def extend_rss(self, item):
return self.extend_atom(item)
def content(self, content=None, replace=False, group='default', **kwargs):
'''Get or set media:content data.
This method can be called with:
- the fields of a media:content as keyword arguments
- the fields of a media:content as a dictionary
- a list of dictionaries containing the media:content fields
<media:content> is a sub-element of either <item> or <media:group>.
Media objects that are not the same content should not be included in
the same <media:group> element. The sequence of these items implies
the order of presentation. While many of the attributes appear to be
audio/video specific, this element can be used to publish any type
of media. It contains 14 attributes, most of which are optional.
media:content has the following fields:
- *url* should specify the direct URL to the media object.
- *fileSize* number of bytes of the media object.
- *type* standard MIME type of the object.
- *medium* type of object (image | audio | video | document |
executable).
- *isDefault* determines if this is the default object.
- *expression* determines if the object is a sample or the full version
of the object, or even if it is a continuous stream (sample | full |
nonstop).
- *bitrate* kilobits per second rate of media.
- *framerate* number of frames per second for the media object.
- *samplingrate* number of samples per second taken to create the media
object. It is expressed in thousands of samples per second (kHz).
- *channels* number of audio channels in the media object.
- *duration* number of seconds the media object plays.
- *height* height of the media object.
- *width* width of the media object.
- *lang* is the primary language encapsulated in the media object.
:param content: Dictionary or list of dictionaries with content data.
:param replace: Add or replace old data.
:param group: Media group to put this content in.
:returns: The media content tag.
'''
# Handle kwargs
if content is None and kwargs:
content = kwargs
# Handle new data
if content is not None:
# Reset data if we want to replace them
if replace or self.__media_content is None:
self.__media_content = []
# Ensure list
if not isinstance(content, list):
content = [content]
# define media group
for c in content:
c['group'] = c.get('group', group)
self.__media_content += ensure_format(
content,
set(['url', 'fileSize', 'type', 'medium', 'isDefault',
'expression', 'bitrate', 'framerate', 'samplingrate',
'channels', 'duration', 'height', 'width', 'lang',
'group']),
set(['url', 'group']))
return self.__media_content
def thumbnail(self, thumbnail=None, replace=False, group='default',
**kwargs):
'''Get or set media:thumbnail data.
This method can be called with:
- the fields of a media:content as keyword arguments
- the fields of a media:content as a dictionary
- a list of dictionaries containing the media:content fields
Allows particular images to be used as representative images for
the media object. If multiple thumbnails are included, and time
coding is not at play, it is assumed that the images are in order
of importance. It has one required attribute and three optional
attributes.
media:thumbnail has the following fields:
- *url* should specify the direct URL to the media object.
- *height* height of the media object.
- *width* width of the media object.
- *time* specifies the time offset in relation to the media object.
:param thumbnail: Dictionary or list of dictionaries with thumbnail
data.
:param replace: Add or replace old data.
:param group: Media group to put this content in.
:returns: The media thumbnail tag.
'''
# Handle kwargs
if thumbnail is None and kwargs:
thumbnail = kwargs
# Handle new data
if thumbnail is not None:
# Reset data if we want to replace them
if replace or self.__media_thumbnail is None:
self.__media_thumbnail = []
# Ensure list
if not isinstance(thumbnail, list):
thumbnail = [thumbnail]
# Define media group
for t in thumbnail:
t['group'] = t.get('group', group)
self.__media_thumbnail += ensure_format(
thumbnail,
set(['url', 'height', 'width', 'time', 'group']),
set(['url', 'group']))
return self.__media_thumbnail
| ./CrossVul/dataset_final_sorted/CWE-776/py/bad_4531_3 |
crossvul-python_data_bad_4531_2 | # -*- coding: utf-8 -*-
'''
feedgen.ext.geo_entry
~~~~~~~~~~~~~~~~~~~
Extends the FeedGenerator to produce Simple GeoRSS feeds.
:copyright: 2017, Bob Breznak <bob.breznak@gmail.com>
:license: FreeBSD and LGPL, see license.* for more details.
'''
import numbers
import warnings
from lxml import etree
from feedgen.ext.base import BaseEntryExtension
class GeoRSSPolygonInteriorWarning(Warning):
"""
Simple placeholder for warning about ignored polygon interiors.
Stores the original geom on a ``geom`` attribute (if required warnings are
raised as errors).
"""
def __init__(self, geom, *args, **kwargs):
self.geom = geom
super(GeoRSSPolygonInteriorWarning, self).__init__(*args, **kwargs)
def __str__(self):
return '{:d} interiors of polygon ignored'.format(
len(self.geom.__geo_interface__['coordinates']) - 1
) # ignore exterior in count
class GeoRSSGeometryError(ValueError):
"""
Subclass of ValueError for a GeoRSS geometry error
Only some geometries are supported in Simple GeoRSS, so if not raise an
error. Offending geometry is stored on the ``geom`` attribute.
"""
def __init__(self, geom, *args, **kwargs):
self.geom = geom
super(GeoRSSGeometryError, self).__init__(*args, **kwargs)
def __str__(self):
msg = "Geometry of type '{}' not in Point, Linestring or Polygon"
return msg.format(
self.geom.__geo_interface__['type']
)
class GeoEntryExtension(BaseEntryExtension):
'''FeedEntry extension for Simple GeoRSS.
'''
def __init__(self):
'''Simple GeoRSS tag'''
# geometries
self.__point = None
self.__line = None
self.__polygon = None
self.__box = None
# additional properties
self.__featuretypetag = None
self.__relationshiptag = None
self.__featurename = None
# elevation
self.__elev = None
self.__floor = None
# radius
self.__radius = None
def extend_file(self, entry):
'''Add additional fields to an RSS item.
:param feed: The RSS item XML element to use.
'''
GEO_NS = 'http://www.georss.org/georss'
if self.__point:
point = etree.SubElement(entry, '{%s}point' % GEO_NS)
point.text = self.__point
if self.__line:
line = etree.SubElement(entry, '{%s}line' % GEO_NS)
line.text = self.__line
if self.__polygon:
polygon = etree.SubElement(entry, '{%s}polygon' % GEO_NS)
polygon.text = self.__polygon
if self.__box:
box = etree.SubElement(entry, '{%s}box' % GEO_NS)
box.text = self.__box
if self.__featuretypetag:
featuretypetag = etree.SubElement(
entry,
'{%s}featuretypetag' % GEO_NS
)
featuretypetag.text = self.__featuretypetag
if self.__relationshiptag:
relationshiptag = etree.SubElement(
entry,
'{%s}relationshiptag' % GEO_NS
)
relationshiptag.text = self.__relationshiptag
if self.__featurename:
featurename = etree.SubElement(entry, '{%s}featurename' % GEO_NS)
featurename.text = self.__featurename
if self.__elev:
elevation = etree.SubElement(entry, '{%s}elev' % GEO_NS)
elevation.text = str(self.__elev)
if self.__floor:
floor = etree.SubElement(entry, '{%s}floor' % GEO_NS)
floor.text = str(self.__floor)
if self.__radius:
radius = etree.SubElement(entry, '{%s}radius' % GEO_NS)
radius.text = str(self.__radius)
return entry
def extend_rss(self, entry):
return self.extend_file(entry)
def extend_atom(self, entry):
return self.extend_file(entry)
def point(self, point=None):
'''Get or set the georss:point of the entry.
:param point: The GeoRSS formatted point (i.e. "42.36 -71.05")
:returns: The current georss:point of the entry.
'''
if point is not None:
self.__point = point
return self.__point
def line(self, line=None):
'''Get or set the georss:line of the entry
:param point: The GeoRSS formatted line (i.e. "45.256 -110.45 46.46
-109.48 43.84 -109.86")
:return: The current georss:line of the entry
'''
if line is not None:
self.__line = line
return self.__line
def polygon(self, polygon=None):
'''Get or set the georss:polygon of the entry
:param polygon: The GeoRSS formatted polygon (i.e. "45.256 -110.45
46.46 -109.48 43.84 -109.86 45.256 -110.45")
:return: The current georss:polygon of the entry
'''
if polygon is not None:
self.__polygon = polygon
return self.__polygon
def box(self, box=None):
'''
Get or set the georss:box of the entry
:param box: The GeoRSS formatted box (i.e. "42.943 -71.032 43.039
-69.856")
:return: The current georss:box of the entry
'''
if box is not None:
self.__box = box
return self.__box
def featuretypetag(self, featuretypetag=None):
'''
Get or set the georss:featuretypetag of the entry
:param featuretypetag: The GeoRSS feaaturertyptag (e.g. "city")
:return: The current georss:featurertypetag
'''
if featuretypetag is not None:
self.__featuretypetag = featuretypetag
return self.__featuretypetag
def relationshiptag(self, relationshiptag=None):
'''
Get or set the georss:relationshiptag of the entry
:param relationshiptag: The GeoRSS relationshiptag (e.g.
"is-centred-at")
:return: the current georss:relationshiptag
'''
if relationshiptag is not None:
self.__relationshiptag = relationshiptag
return self.__relationshiptag
def featurename(self, featurename=None):
'''
Get or set the georss:featurename of the entry
:param featuretypetag: The GeoRSS featurename (e.g. "Footscray")
:return: the current georss:featurename
'''
if featurename is not None:
self.__featurename = featurename
return self.__featurename
def elev(self, elev=None):
'''
Get or set the georss:elev of the entry
:param elev: The GeoRSS elevation (e.g. 100.3)
:type elev: numbers.Number
:return: the current georss:elev
'''
if elev is not None:
if not isinstance(elev, numbers.Number):
raise ValueError("elev tag must be numeric: {}".format(elev))
self.__elev = elev
return self.__elev
def floor(self, floor=None):
'''
Get or set the georss:floor of the entry
:param floor: The GeoRSS floor (e.g. 4)
:type floor: int
:return: the current georss:floor
'''
if floor is not None:
if not isinstance(floor, int):
raise ValueError("floor tag must be int: {}".format(floor))
self.__floor = floor
return self.__floor
def radius(self, radius=None):
'''
Get or set the georss:radius of the entry
:param radius: The GeoRSS radius (e.g. 100.3)
:type radius: numbers.Number
:return: the current georss:radius
'''
if radius is not None:
if not isinstance(radius, numbers.Number):
raise ValueError(
"radius tag must be numeric: {}".format(radius)
)
self.__radius = radius
return self.__radius
def geom_from_geo_interface(self, geom):
'''
Generate a georss geometry from some Python object with a
``__geo_interface__`` property (see the `geo_interface specification by
Sean Gillies`_geointerface )
Note only a subset of GeoJSON (see `geojson.org`_geojson ) can be
easily converted to GeoRSS:
- Point
- LineString
- Polygon (if there are holes / donuts in the polygons a warning will
be generaated
Other GeoJson types will raise a ``ValueError``.
.. note:: The geometry is assumed to be x, y as longitude, latitude in
the WGS84 projection.
.. _geointerface: https://gist.github.com/sgillies/2217756
.. _geojson: https://geojson.org/
:param geom: Geometry object with a __geo_interface__ property
:return: the formatted GeoRSS geometry
'''
geojson = geom.__geo_interface__
if geojson['type'] not in ('Point', 'LineString', 'Polygon'):
raise GeoRSSGeometryError(geom)
if geojson['type'] == 'Point':
coords = '{:f} {:f}'.format(
geojson['coordinates'][1], # latitude is y
geojson['coordinates'][0]
)
return self.point(coords)
elif geojson['type'] == 'LineString':
coords = ' '.join(
'{:f} {:f}'.format(vertex[1], vertex[0])
for vertex in
geojson['coordinates']
)
return self.line(coords)
elif geojson['type'] == 'Polygon':
if len(geojson['coordinates']) > 1:
warnings.warn(GeoRSSPolygonInteriorWarning(geom))
coords = ' '.join(
'{:f} {:f}'.format(vertex[1], vertex[0])
for vertex in
geojson['coordinates'][0]
)
return self.polygon(coords)
| ./CrossVul/dataset_final_sorted/CWE-776/py/bad_4531_2 |
crossvul-python_data_good_4531_1 | # -*- coding: utf-8 -*-
'''
feedgen.ext.dc
~~~~~~~~~~~~~~~~~~~
Extends the FeedGenerator to add Dubline Core Elements to the feeds.
Descriptions partly taken from
http://dublincore.org/documents/dcmi-terms/#elements-coverage
:copyright: 2013-2017, Lars Kiesow <lkiesow@uos.de>
:license: FreeBSD and LGPL, see license.* for more details.
'''
from feedgen.ext.base import BaseExtension
from feedgen.util import xml_elem
class DcBaseExtension(BaseExtension):
'''Dublin Core Elements extension for podcasts.
'''
def __init__(self):
# http://dublincore.org/documents/usageguide/elements.shtml
# http://dublincore.org/documents/dces/
# http://dublincore.org/documents/dcmi-terms/
self._dcelem_contributor = None
self._dcelem_coverage = None
self._dcelem_creator = None
self._dcelem_date = None
self._dcelem_description = None
self._dcelem_format = None
self._dcelem_identifier = None
self._dcelem_language = None
self._dcelem_publisher = None
self._dcelem_relation = None
self._dcelem_rights = None
self._dcelem_source = None
self._dcelem_subject = None
self._dcelem_title = None
self._dcelem_type = None
def extend_ns(self):
return {'dc': 'http://purl.org/dc/elements/1.1/'}
def _extend_xml(self, xml_element):
'''Extend xml_element with set DC fields.
:param xml_element: etree element
'''
DCELEMENTS_NS = 'http://purl.org/dc/elements/1.1/'
for elem in ['contributor', 'coverage', 'creator', 'date',
'description', 'language', 'publisher', 'relation',
'rights', 'source', 'subject', 'title', 'type', 'format',
'identifier']:
if hasattr(self, '_dcelem_%s' % elem):
for val in getattr(self, '_dcelem_%s' % elem) or []:
node = xml_elem('{%s}%s' % (DCELEMENTS_NS, elem),
xml_element)
node.text = val
def extend_atom(self, atom_feed):
'''Extend an Atom feed with the set DC fields.
:param atom_feed: The feed root element
:returns: The feed root element
'''
self._extend_xml(atom_feed)
return atom_feed
def extend_rss(self, rss_feed):
'''Extend a RSS feed with the set DC fields.
:param rss_feed: The feed root element
:returns: The feed root element.
'''
channel = rss_feed[0]
self._extend_xml(channel)
return rss_feed
def dc_contributor(self, contributor=None, replace=False):
'''Get or set the dc:contributor which is an entity responsible for
making contributions to the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-contributor
:param contributor: Contributor or list of contributors.
:param replace: Replace alredy set contributors (deault: False).
:returns: List of contributors.
'''
if contributor is not None:
if not isinstance(contributor, list):
contributor = [contributor]
if replace or not self._dcelem_contributor:
self._dcelem_contributor = []
self._dcelem_contributor += contributor
return self._dcelem_contributor
def dc_coverage(self, coverage=None, replace=True):
'''Get or set the dc:coverage which indicated the spatial or temporal
topic of the resource, the spatial applicability of the resource, or
the jurisdiction under which the resource is relevant.
Spatial topic and spatial applicability may be a named place or a
location specified by its geographic coordinates. Temporal topic may be
a named period, date, or date range. A jurisdiction may be a named
administrative entity or a geographic place to which the resource
applies. Recommended best practice is to use a controlled vocabulary
such as the Thesaurus of Geographic Names [TGN]. Where appropriate,
named places or time periods can be used in preference to numeric
identifiers such as sets of coordinates or date ranges.
References:
[TGN] http://www.getty.edu/research/tools/vocabulary/tgn/index.html
:param coverage: Coverage of the feed.
:param replace: Replace already set coverage (default: True).
:returns: Coverage of the feed.
'''
if coverage is not None:
if not isinstance(coverage, list):
coverage = [coverage]
if replace or not self._dcelem_coverage:
self._dcelem_coverage = []
self._dcelem_coverage = coverage
return self._dcelem_coverage
def dc_creator(self, creator=None, replace=False):
'''Get or set the dc:creator which is an entity primarily responsible
for making the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-creator
:param creator: Creator or list of creators.
:param replace: Replace alredy set creators (deault: False).
:returns: List of creators.
'''
if creator is not None:
if not isinstance(creator, list):
creator = [creator]
if replace or not self._dcelem_creator:
self._dcelem_creator = []
self._dcelem_creator += creator
return self._dcelem_creator
def dc_date(self, date=None, replace=True):
'''Get or set the dc:date which describes a point or period of time
associated with an event in the lifecycle of the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-date
:param date: Date or list of dates.
:param replace: Replace alredy set dates (deault: True).
:returns: List of dates.
'''
if date is not None:
if not isinstance(date, list):
date = [date]
if replace or not self._dcelem_date:
self._dcelem_date = []
self._dcelem_date += date
return self._dcelem_date
def dc_description(self, description=None, replace=True):
'''Get or set the dc:description which is an account of the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-description
:param description: Description or list of descriptions.
:param replace: Replace alredy set descriptions (deault: True).
:returns: List of descriptions.
'''
if description is not None:
if not isinstance(description, list):
description = [description]
if replace or not self._dcelem_description:
self._dcelem_description = []
self._dcelem_description += description
return self._dcelem_description
def dc_format(self, format=None, replace=True):
'''Get or set the dc:format which describes the file format, physical
medium, or dimensions of the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-format
:param format: Format of the resource or list of formats.
:param replace: Replace alredy set format (deault: True).
:returns: Format of the resource.
'''
if format is not None:
if not isinstance(format, list):
format = [format]
if replace or not self._dcelem_format:
self._dcelem_format = []
self._dcelem_format += format
return self._dcelem_format
def dc_identifier(self, identifier=None, replace=True):
'''Get or set the dc:identifier which should be an unambiguous
reference to the resource within a given context.
For more inidentifierion see:
http://dublincore.org/documents/dcmi-terms/#elements-identifier
:param identifier: Identifier of the resource or list of identifiers.
:param replace: Replace alredy set identifier (deault: True).
:returns: Identifiers of the resource.
'''
if identifier is not None:
if not isinstance(identifier, list):
identifier = [identifier]
if replace or not self._dcelem_identifier:
self._dcelem_identifier = []
self._dcelem_identifier += identifier
return self._dcelem_identifier
def dc_language(self, language=None, replace=True):
'''Get or set the dc:language which describes a language of the
resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-language
:param language: Language or list of languages.
:param replace: Replace alredy set languages (deault: True).
:returns: List of languages.
'''
if language is not None:
if not isinstance(language, list):
language = [language]
if replace or not self._dcelem_language:
self._dcelem_language = []
self._dcelem_language += language
return self._dcelem_language
def dc_publisher(self, publisher=None, replace=False):
'''Get or set the dc:publisher which is an entity responsible for
making the resource available.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-publisher
:param publisher: Publisher or list of publishers.
:param replace: Replace alredy set publishers (deault: False).
:returns: List of publishers.
'''
if publisher is not None:
if not isinstance(publisher, list):
publisher = [publisher]
if replace or not self._dcelem_publisher:
self._dcelem_publisher = []
self._dcelem_publisher += publisher
return self._dcelem_publisher
def dc_relation(self, relation=None, replace=False):
'''Get or set the dc:relation which describes a related resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-relation
:param relation: Relation or list of relations.
:param replace: Replace alredy set relations (deault: False).
:returns: List of relations.
'''
if relation is not None:
if not isinstance(relation, list):
relation = [relation]
if replace or not self._dcelem_relation:
self._dcelem_relation = []
self._dcelem_relation += relation
return self._dcelem_relation
def dc_rights(self, rights=None, replace=False):
'''Get or set the dc:rights which may contain information about rights
held in and over the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-rights
:param rights: Rights information or list of rights information.
:param replace: Replace alredy set rightss (deault: False).
:returns: List of rights information.
'''
if rights is not None:
if not isinstance(rights, list):
rights = [rights]
if replace or not self._dcelem_rights:
self._dcelem_rights = []
self._dcelem_rights += rights
return self._dcelem_rights
def dc_source(self, source=None, replace=False):
'''Get or set the dc:source which is a related resource from which the
described resource is derived.
The described resource may be derived from the related resource in
whole or in part. Recommended best practice is to identify the related
resource by means of a string conforming to a formal identification
system.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-source
:param source: Source or list of sources.
:param replace: Replace alredy set sources (deault: False).
:returns: List of sources.
'''
if source is not None:
if not isinstance(source, list):
source = [source]
if replace or not self._dcelem_source:
self._dcelem_source = []
self._dcelem_source += source
return self._dcelem_source
def dc_subject(self, subject=None, replace=False):
'''Get or set the dc:subject which describes the topic of the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-subject
:param subject: Subject or list of subjects.
:param replace: Replace alredy set subjects (deault: False).
:returns: List of subjects.
'''
if subject is not None:
if not isinstance(subject, list):
subject = [subject]
if replace or not self._dcelem_subject:
self._dcelem_subject = []
self._dcelem_subject += subject
return self._dcelem_subject
def dc_title(self, title=None, replace=True):
'''Get or set the dc:title which is a name given to the resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-title
:param title: Title or list of titles.
:param replace: Replace alredy set titles (deault: False).
:returns: List of titles.
'''
if title is not None:
if not isinstance(title, list):
title = [title]
if replace or not self._dcelem_title:
self._dcelem_title = []
self._dcelem_title += title
return self._dcelem_title
def dc_type(self, type=None, replace=False):
'''Get or set the dc:type which describes the nature or genre of the
resource.
For more information see:
http://dublincore.org/documents/dcmi-terms/#elements-type
:param type: Type or list of types.
:param replace: Replace alredy set types (deault: False).
:returns: List of types.
'''
if type is not None:
if not isinstance(type, list):
type = [type]
if replace or not self._dcelem_type:
self._dcelem_type = []
self._dcelem_type += type
return self._dcelem_type
class DcExtension(DcBaseExtension):
'''Dublin Core Elements extension for podcasts.
'''
class DcEntryExtension(DcBaseExtension):
'''Dublin Core Elements extension for podcasts.
'''
def extend_atom(self, entry):
'''Add dc elements to an atom item. Alters the item itself.
:param entry: An atom entry element.
:returns: The entry element.
'''
self._extend_xml(entry)
return entry
def extend_rss(self, item):
'''Add dc elements to a RSS item. Alters the item itself.
:param item: A RSS item element.
:returns: The item element.
'''
self._extend_xml(item)
return item
| ./CrossVul/dataset_final_sorted/CWE-776/py/good_4531_1 |
crossvul-python_data_bad_4531_0 | # -*- coding: utf-8 -*-
'''
feedgen.entry
~~~~~~~~~~~~~
:copyright: 2013, Lars Kiesow <lkiesow@uos.de>
:license: FreeBSD and LGPL, see license.* for more details.
'''
from datetime import datetime
import dateutil.parser
import dateutil.tz
import warnings
from lxml import etree
from feedgen.compat import string_types
from feedgen.util import ensure_format, formatRFC2822
def _add_text_elm(entry, data, name):
"""Add a text subelement to an entry"""
if not data:
return
elm = etree.SubElement(entry, name)
type_ = data.get('type')
if data.get('src'):
if name != 'content':
raise ValueError("Only the 'content' element of an entry can "
"contain a 'src' attribute")
elm.attrib['src'] = data['src']
elif data.get(name):
# Surround xhtml with a div tag, parse it and embed it
if type_ == 'xhtml':
elm.append(etree.fromstring(
'<div xmlns="http://www.w3.org/1999/xhtml">' +
data.get(name) + '</div>'))
elif type_ == 'CDATA':
elm.text = etree.CDATA(
data.get(name))
# Parse XML and embed it
elif type_ and (type_.endswith('/xml') or type_.endswith('+xml')):
elm.append(etree.fromstring(
data[name]))
# Embed the text in escaped form
elif not type_ or type_.startswith('text') or type_ == 'html':
elm.text = data.get(name)
# Everything else should be included base64 encoded
else:
raise NotImplementedError(
'base64 encoded {} is not supported at the moment. '
'Pull requests adding support are welcome.'.format(name)
)
# Add type description of the content
if type_:
elm.attrib['type'] = type_
class FeedEntry(object):
'''FeedEntry call representing an ATOM feeds entry node or an RSS feeds item
node.
'''
def __init__(self):
# ATOM
# required
self.__atom_id = None
self.__atom_title = None
self.__atom_updated = datetime.now(dateutil.tz.tzutc())
# recommended
self.__atom_author = None
self.__atom_content = None
self.__atom_link = None
self.__atom_summary = None
# optional
self.__atom_category = None
self.__atom_contributor = None
self.__atom_published = None
self.__atom_source = None
self.__atom_rights = None
# RSS
self.__rss_author = None
self.__rss_category = None
self.__rss_comments = None
self.__rss_description = None
self.__rss_content = None
self.__rss_enclosure = None
self.__rss_guid = {}
self.__rss_link = None
self.__rss_pubDate = None
self.__rss_source = None
self.__rss_title = None
# Extension list:
self.__extensions = {}
self.__extensions_register = {}
def atom_entry(self, extensions=True):
'''Create an ATOM entry and return it.'''
entry = etree.Element('entry')
if not (self.__atom_id and self.__atom_title and self.__atom_updated):
raise ValueError('Required fields not set')
id = etree.SubElement(entry, 'id')
id.text = self.__atom_id
title = etree.SubElement(entry, 'title')
title.text = self.__atom_title
updated = etree.SubElement(entry, 'updated')
updated.text = self.__atom_updated.isoformat()
# An entry must contain an alternate link if there is no content
# element.
if not self.__atom_content:
links = self.__atom_link or []
if not [l for l in links if l.get('rel') == 'alternate']:
raise ValueError('Entry must contain an alternate link or ' +
'a content element.')
# Add author elements
for a in self.__atom_author or []:
# Atom requires a name. Skip elements without.
if not a.get('name'):
continue
author = etree.SubElement(entry, 'author')
name = etree.SubElement(author, 'name')
name.text = a.get('name')
if a.get('email'):
email = etree.SubElement(author, 'email')
email.text = a.get('email')
if a.get('uri'):
uri = etree.SubElement(author, 'uri')
uri.text = a.get('uri')
_add_text_elm(entry, self.__atom_content, 'content')
for l in self.__atom_link or []:
link = etree.SubElement(entry, 'link', href=l['href'])
if l.get('rel'):
link.attrib['rel'] = l['rel']
if l.get('type'):
link.attrib['type'] = l['type']
if l.get('hreflang'):
link.attrib['hreflang'] = l['hreflang']
if l.get('title'):
link.attrib['title'] = l['title']
if l.get('length'):
link.attrib['length'] = l['length']
_add_text_elm(entry, self.__atom_summary, 'summary')
for c in self.__atom_category or []:
cat = etree.SubElement(entry, 'category', term=c['term'])
if c.get('scheme'):
cat.attrib['scheme'] = c['scheme']
if c.get('label'):
cat.attrib['label'] = c['label']
# Add author elements
for c in self.__atom_contributor or []:
# Atom requires a name. Skip elements without.
if not c.get('name'):
continue
contrib = etree.SubElement(entry, 'contributor')
name = etree.SubElement(contrib, 'name')
name.text = c.get('name')
if c.get('email'):
email = etree.SubElement(contrib, 'email')
email.text = c.get('email')
if c.get('uri'):
uri = etree.SubElement(contrib, 'uri')
uri.text = c.get('uri')
if self.__atom_published:
published = etree.SubElement(entry, 'published')
published.text = self.__atom_published.isoformat()
if self.__atom_rights:
rights = etree.SubElement(entry, 'rights')
rights.text = self.__atom_rights
if self.__atom_source:
source = etree.SubElement(entry, 'source')
if self.__atom_source.get('title'):
source_title = etree.SubElement(source, 'title')
source_title.text = self.__atom_source['title']
if self.__atom_source.get('link'):
etree.SubElement(source, 'link',
href=self.__atom_source['link'])
if extensions:
for ext in self.__extensions.values() or []:
if ext.get('atom'):
ext['inst'].extend_atom(entry)
return entry
def rss_entry(self, extensions=True):
'''Create a RSS item and return it.'''
entry = etree.Element('item')
if not (self.__rss_title or
self.__rss_description or
self.__rss_content):
raise ValueError('Required fields not set')
if self.__rss_title:
title = etree.SubElement(entry, 'title')
title.text = self.__rss_title
if self.__rss_link:
link = etree.SubElement(entry, 'link')
link.text = self.__rss_link
if self.__rss_description and self.__rss_content:
description = etree.SubElement(entry, 'description')
description.text = self.__rss_description
XMLNS_CONTENT = 'http://purl.org/rss/1.0/modules/content/'
content = etree.SubElement(entry, '{%s}encoded' % XMLNS_CONTENT)
content.text = etree.CDATA(self.__rss_content['content']) \
if self.__rss_content.get('type', '') == 'CDATA' \
else self.__rss_content['content']
elif self.__rss_description:
description = etree.SubElement(entry, 'description')
description.text = self.__rss_description
elif self.__rss_content:
description = etree.SubElement(entry, 'description')
description.text = etree.CDATA(self.__rss_content['content']) \
if self.__rss_content.get('type', '') == 'CDATA' \
else self.__rss_content['content']
for a in self.__rss_author or []:
author = etree.SubElement(entry, 'author')
author.text = a
if self.__rss_guid.get('guid'):
guid = etree.SubElement(entry, 'guid')
guid.text = self.__rss_guid['guid']
permaLink = str(self.__rss_guid.get('permalink', False)).lower()
guid.attrib['isPermaLink'] = permaLink
for cat in self.__rss_category or []:
category = etree.SubElement(entry, 'category')
category.text = cat['value']
if cat.get('domain'):
category.attrib['domain'] = cat['domain']
if self.__rss_comments:
comments = etree.SubElement(entry, 'comments')
comments.text = self.__rss_comments
if self.__rss_enclosure:
enclosure = etree.SubElement(entry, 'enclosure')
enclosure.attrib['url'] = self.__rss_enclosure['url']
enclosure.attrib['length'] = self.__rss_enclosure['length']
enclosure.attrib['type'] = self.__rss_enclosure['type']
if self.__rss_pubDate:
pubDate = etree.SubElement(entry, 'pubDate')
pubDate.text = formatRFC2822(self.__rss_pubDate)
if self.__rss_source:
source = etree.SubElement(entry, 'source',
url=self.__rss_source['url'])
source.text = self.__rss_source['title']
if extensions:
for ext in self.__extensions.values() or []:
if ext.get('rss'):
ext['inst'].extend_rss(entry)
return entry
def title(self, title=None):
'''Get or set the title value of the entry. It should contain a human
readable title for the entry. Title is mandatory for both ATOM and RSS
and should not be blank.
:param title: The new title of the entry.
:returns: The entriess title.
'''
if title is not None:
self.__atom_title = title
self.__rss_title = title
return self.__atom_title
def id(self, id=None):
'''Get or set the entry id which identifies the entry using a
universally unique and permanent URI. Two entries in a feed can have
the same value for id if they represent the same entry at different
points in time. This method will also set rss:guid with permalink set
to False. Id is mandatory for an ATOM entry.
:param id: New Id of the entry.
:returns: Id of the entry.
'''
if id is not None:
self.__atom_id = id
self.__rss_guid = {'guid': id, 'permalink': False}
return self.__atom_id
def guid(self, guid=None, permalink=False):
'''Get or set the entries guid which is a string that uniquely
identifies the item. This will also set atom:id.
:param guid: Id of the entry.
:param permalink: If this is a permanent identifier for this item
:returns: Id and permalink setting of the entry.
'''
if guid is not None:
self.__atom_id = guid
self.__rss_guid = {'guid': guid, 'permalink': permalink}
return self.__rss_guid
def updated(self, updated=None):
'''Set or get the updated value which indicates the last time the entry
was modified in a significant way.
The value can either be a string which will automatically be parsed or
a datetime.datetime object. In any case it is necessary that the value
include timezone information.
:param updated: The modification date.
:returns: Modification date as datetime.datetime
'''
if updated is not None:
if isinstance(updated, string_types):
updated = dateutil.parser.parse(updated)
if not isinstance(updated, datetime):
raise ValueError('Invalid datetime format')
if updated.tzinfo is None:
raise ValueError('Datetime object has no timezone info')
self.__atom_updated = updated
self.__rss_lastBuildDate = updated
return self.__atom_updated
def author(self, author=None, replace=False, **kwargs):
'''Get or set author data. An author element is a dict containing a
name, an email address and a uri. Name is mandatory for ATOM, email is
mandatory for RSS.
This method can be called with:
- the fields of an author as keyword arguments
- the fields of an author as a dictionary
- a list of dictionaries containing the author fields
An author has the following fields:
- *name* conveys a human-readable name for the person.
- *uri* contains a home page for the person.
- *email* contains an email address for the person.
:param author: Dict or list of dicts with author data.
:param replace: Add or replace old data.
Example::
>>> author({'name':'John Doe', 'email':'jdoe@example.com'})
[{'name':'John Doe','email':'jdoe@example.com'}]
>>> author([{'name': 'Mr. X'}, {'name': 'Max'}])
[{'name':'John Doe','email':'jdoe@example.com'},
{'name':'John Doe'}, {'name':'Max'}]
>>> author(name='John Doe', email='jdoe@example.com', replace=True)
[{'name':'John Doe','email':'jdoe@example.com'}]
'''
if author is None and kwargs:
author = kwargs
if author is not None:
if replace or self.__atom_author is None:
self.__atom_author = []
self.__atom_author += ensure_format(author,
set(['name', 'email', 'uri']),
set())
self.__rss_author = []
for a in self.__atom_author:
if a.get('email'):
if a.get('name'):
self.__rss_author.append('%(email)s (%(name)s)' % a)
else:
self.__rss_author.append('%(email)s' % a)
return self.__atom_author
def content(self, content=None, src=None, type=None):
'''Get or set the content of the entry which contains or links to the
complete content of the entry. Content must be provided for ATOM
entries if there is no alternate link, and should be provided if there
is no summary. If the content is set (not linked) it will also set
rss:description.
:param content: The content of the feed entry.
:param src: Link to the entries content.
:param type: If type is CDATA content would not be escaped.
:returns: Content element of the entry.
'''
if src is not None:
self.__atom_content = {'src': src}
elif content is not None:
self.__atom_content = {'content': content}
self.__rss_content = {'content': content}
if type is not None:
self.__atom_content['type'] = type
self.__rss_content['type'] = type
return self.__atom_content
def link(self, link=None, replace=False, **kwargs):
'''Get or set link data. An link element is a dict with the fields
href, rel, type, hreflang, title, and length. Href is mandatory for
ATOM.
This method can be called with:
- the fields of a link as keyword arguments
- the fields of a link as a dictionary
- a list of dictionaries containing the link fields
A link has the following fields:
- *href* is the URI of the referenced resource (typically a Web page)
- *rel* contains a single link relationship type. It can be a full URI,
or one of the following predefined values (default=alternate):
- *alternate* an alternate representation of the entry or feed, for
example a permalink to the html version of the entry, or the
front page of the weblog.
- *enclosure* a related resource which is potentially large in size
and might require special handling, for example an audio or video
recording.
- *related* an document related to the entry or feed.
- *self* the feed itself.
- *via* the source of the information provided in the entry.
- *type* indicates the media type of the resource.
- *hreflang* indicates the language of the referenced resource.
- *title* human readable information about the link, typically for
display purposes.
- *length* the length of the resource, in bytes.
RSS only supports one link with nothing but a URL. So for the RSS link
element the last link with rel=alternate is used.
RSS also supports one enclusure element per entry which is covered by
the link element in ATOM feed entries. So for the RSS enclusure element
the last link with rel=enclosure is used.
:param link: Dict or list of dicts with data.
:param replace: Add or replace old data.
:returns: List of link data.
'''
if link is None and kwargs:
link = kwargs
if link is not None:
if replace or self.__atom_link is None:
self.__atom_link = []
self.__atom_link += ensure_format(
link,
set(['href', 'rel', 'type', 'hreflang', 'title', 'length']),
set(['href']),
{'rel': ['alternate', 'enclosure', 'related', 'self', 'via']},
{'rel': 'alternate'})
# RSS only needs one URL. We use the first link for RSS:
for l in self.__atom_link:
if l.get('rel') == 'alternate':
self.__rss_link = l['href']
elif l.get('rel') == 'enclosure':
self.__rss_enclosure = {'url': l['href']}
self.__rss_enclosure['type'] = l.get('type')
self.__rss_enclosure['length'] = l.get('length') or '0'
# return the set with more information (atom)
return self.__atom_link
def summary(self, summary=None, type=None):
'''Get or set the summary element of an entry which conveys a short
summary, abstract, or excerpt of the entry. Summary is an ATOM only
element and should be provided if there either is no content provided
for the entry, or that content is not inline (i.e., contains a src
attribute), or if the content is encoded in base64. This method will
also set the rss:description field if it wasn't previously set or
contains the old value of summary.
:param summary: Summary of the entries contents.
:returns: Summary of the entries contents.
'''
if summary is not None:
# Replace the RSS description with the summary if it was the
# summary before. Not if it is the description.
if not self.__rss_description or (
self.__atom_summary and
self.__rss_description == self.__atom_summary.get("summary")
):
self.__rss_description = summary
self.__atom_summary = {'summary': summary}
if type is not None:
self.__atom_summary['type'] = type
return self.__atom_summary
def description(self, description=None, isSummary=False):
'''Get or set the description value which is the item synopsis.
Description is an RSS only element. For ATOM feeds it is split in
summary and content. The isSummary parameter can be used to control
which ATOM value is set when setting description.
:param description: Description of the entry.
:param isSummary: If the description should be used as content or
summary.
:returns: The entries description.
'''
if description is not None:
self.__rss_description = description
if isSummary:
self.__atom_summary = description
else:
self.__atom_content = {'content': description}
return self.__rss_description
def category(self, category=None, replace=False, **kwargs):
'''Get or set categories that the entry belongs to.
This method can be called with:
- the fields of a category as keyword arguments
- the fields of a category as a dictionary
- a list of dictionaries containing the category fields
A categories has the following fields:
- *term* identifies the category
- *scheme* identifies the categorization scheme via a URI.
- *label* provides a human-readable label for display
If a label is present it is used for the RSS feeds. Otherwise the term
is used. The scheme is used for the domain attribute in RSS.
:param category: Dict or list of dicts with data.
:param replace: Add or replace old data.
:returns: List of category data.
'''
if category is None and kwargs:
category = kwargs
if category is not None:
if replace or self.__atom_category is None:
self.__atom_category = []
self.__atom_category += ensure_format(
category,
set(['term', 'scheme', 'label']),
set(['term']))
# Map the ATOM categories to RSS categories. Use the atom:label as
# name or if not present the atom:term. The atom:scheme is the
# rss:domain.
self.__rss_category = []
for cat in self.__atom_category:
rss_cat = {}
rss_cat['value'] = cat.get('label', cat['term'])
if cat.get('scheme'):
rss_cat['domain'] = cat['scheme']
self.__rss_category.append(rss_cat)
return self.__atom_category
def contributor(self, contributor=None, replace=False, **kwargs):
'''Get or set the contributor data of the feed. This is an ATOM only
value.
This method can be called with:
- the fields of an contributor as keyword arguments
- the fields of an contributor as a dictionary
- a list of dictionaries containing the contributor fields
An contributor has the following fields:
- *name* conveys a human-readable name for the person.
- *uri* contains a home page for the person.
- *email* contains an email address for the person.
:param contributor: Dictionary or list of dictionaries with contributor
data.
:param replace: Add or replace old data.
:returns: List of contributors as dictionaries.
'''
if contributor is None and kwargs:
contributor = kwargs
if contributor is not None:
if replace or self.__atom_contributor is None:
self.__atom_contributor = []
self.__atom_contributor += ensure_format(
contributor, set(['name', 'email', 'uri']), set(['name']))
return self.__atom_contributor
def published(self, published=None):
'''Set or get the published value which contains the time of the initial
creation or first availability of the entry.
The value can either be a string which will automatically be parsed or
a datetime.datetime object. In any case it is necessary that the value
include timezone information.
:param published: The creation date.
:returns: Creation date as datetime.datetime
'''
if published is not None:
if isinstance(published, string_types):
published = dateutil.parser.parse(published)
if not isinstance(published, datetime):
raise ValueError('Invalid datetime format')
if published.tzinfo is None:
raise ValueError('Datetime object has no timezone info')
self.__atom_published = published
self.__rss_pubDate = published
return self.__atom_published
def pubDate(self, pubDate=None):
'''Get or set the pubDate of the entry which indicates when the entry
was published. This method is just another name for the published(...)
method.
'''
return self.published(pubDate)
def pubdate(self, pubDate=None):
'''Get or set the pubDate of the entry which indicates when the entry
was published. This method is just another name for the published(...)
method.
pubdate(…) is deprecated and may be removed in feedgen ≥ 0.8. Use
pubDate(…) instead.
'''
warnings.warn('pubdate(…) is deprecated and may be removed in feedgen '
'≥ 0.8. Use pubDate(…) instead.')
return self.published(pubDate)
def rights(self, rights=None):
'''Get or set the rights value of the entry which conveys information
about rights, e.g. copyrights, held in and over the entry. This ATOM
value will also set rss:copyright.
:param rights: Rights information of the feed.
:returns: Rights information of the feed.
'''
if rights is not None:
self.__atom_rights = rights
return self.__atom_rights
def comments(self, comments=None):
'''Get or set the value of comments which is the URL of the comments
page for the item. This is a RSS only value.
:param comments: URL to the comments page.
:returns: URL to the comments page.
'''
if comments is not None:
self.__rss_comments = comments
return self.__rss_comments
def source(self, url=None, title=None):
'''Get or set the source for the current feed entry.
Note that ATOM feeds support a lot more sub elements than title and URL
(which is what RSS supports) but these are currently not supported.
Patches are welcome.
:param url: Link to the source.
:param title: Title of the linked resource
:returns: Source element as dictionaries.
'''
if url is not None and title is not None:
self.__rss_source = {'url': url, 'title': title}
self.__atom_source = {'link': url, 'title': title}
return self.__rss_source
def enclosure(self, url=None, length=None, type=None):
'''Get or set the value of enclosure which describes a media object
that is attached to the item. This is a RSS only value which is
represented by link(rel=enclosure) in ATOM. ATOM feeds can furthermore
contain several enclosures while RSS may contain only one. That is why
this method, if repeatedly called, will add more than one enclosures to
the feed. However, only the last one is used for RSS.
:param url: URL of the media object.
:param length: Size of the media in bytes.
:param type: Mimetype of the linked media.
:returns: Data of the enclosure element.
'''
if url is not None:
self.link(href=url, rel='enclosure', type=type, length=length)
return self.__rss_enclosure
def ttl(self, ttl=None):
'''Get or set the ttl value. It is an RSS only element. ttl stands for
time to live. It's a number of minutes that indicates how long a
channel can be cached before refreshing from the source.
:param ttl: Integer value representing the time to live.
:returns: Time to live of of the entry.
'''
if ttl is not None:
self.__rss_ttl = int(ttl)
return self.__rss_ttl
def load_extension(self, name, atom=True, rss=True):
'''Load a specific extension by name.
:param name: Name of the extension to load.
:param atom: If the extension should be used for ATOM feeds.
:param rss: If the extension should be used for RSS feeds.
'''
# Check loaded extensions
if not isinstance(self.__extensions, dict):
self.__extensions = {}
if name in self.__extensions.keys():
raise ImportError('Extension already loaded')
# Load extension
extname = name[0].upper() + name[1:] + 'EntryExtension'
try:
supmod = __import__('feedgen.ext.%s_entry' % name)
extmod = getattr(supmod.ext, name + '_entry')
except ImportError:
# Use FeedExtension module instead
supmod = __import__('feedgen.ext.%s' % name)
extmod = getattr(supmod.ext, name)
ext = getattr(extmod, extname)
self.register_extension(name, ext, atom, rss)
def register_extension(self, namespace, extension_class_entry=None,
atom=True, rss=True):
'''Register a specific extension by classes to a namespace.
:param namespace: namespace for the extension
:param extension_class_entry: Class of the entry extension to load.
:param atom: If the extension should be used for ATOM feeds.
:param rss: If the extension should be used for RSS feeds.
'''
# Check loaded extensions
# `load_extension` ignores the "Extension" suffix.
if not isinstance(self.__extensions, dict):
self.__extensions = {}
if namespace in self.__extensions.keys():
raise ImportError('Extension already loaded')
if not extension_class_entry:
raise ImportError('No extension class')
extinst = extension_class_entry()
setattr(self, namespace, extinst)
# `load_extension` registry
self.__extensions[namespace] = {
'inst': extinst,
'extension_class_entry': extension_class_entry,
'atom': atom,
'rss': rss
}
| ./CrossVul/dataset_final_sorted/CWE-776/py/bad_4531_0 |
crossvul-python_data_good_4531_2 | # -*- coding: utf-8 -*-
'''
feedgen.ext.geo_entry
~~~~~~~~~~~~~~~~~~~
Extends the FeedGenerator to produce Simple GeoRSS feeds.
:copyright: 2017, Bob Breznak <bob.breznak@gmail.com>
:license: FreeBSD and LGPL, see license.* for more details.
'''
import numbers
import warnings
from feedgen.ext.base import BaseEntryExtension
from feedgen.util import xml_elem
class GeoRSSPolygonInteriorWarning(Warning):
"""
Simple placeholder for warning about ignored polygon interiors.
Stores the original geom on a ``geom`` attribute (if required warnings are
raised as errors).
"""
def __init__(self, geom, *args, **kwargs):
self.geom = geom
super(GeoRSSPolygonInteriorWarning, self).__init__(*args, **kwargs)
def __str__(self):
return '{:d} interiors of polygon ignored'.format(
len(self.geom.__geo_interface__['coordinates']) - 1
) # ignore exterior in count
class GeoRSSGeometryError(ValueError):
"""
Subclass of ValueError for a GeoRSS geometry error
Only some geometries are supported in Simple GeoRSS, so if not raise an
error. Offending geometry is stored on the ``geom`` attribute.
"""
def __init__(self, geom, *args, **kwargs):
self.geom = geom
super(GeoRSSGeometryError, self).__init__(*args, **kwargs)
def __str__(self):
msg = "Geometry of type '{}' not in Point, Linestring or Polygon"
return msg.format(
self.geom.__geo_interface__['type']
)
class GeoEntryExtension(BaseEntryExtension):
'''FeedEntry extension for Simple GeoRSS.
'''
def __init__(self):
'''Simple GeoRSS tag'''
# geometries
self.__point = None
self.__line = None
self.__polygon = None
self.__box = None
# additional properties
self.__featuretypetag = None
self.__relationshiptag = None
self.__featurename = None
# elevation
self.__elev = None
self.__floor = None
# radius
self.__radius = None
def extend_file(self, entry):
'''Add additional fields to an RSS item.
:param feed: The RSS item XML element to use.
'''
GEO_NS = 'http://www.georss.org/georss'
if self.__point:
point = xml_elem('{%s}point' % GEO_NS, entry)
point.text = self.__point
if self.__line:
line = xml_elem('{%s}line' % GEO_NS, entry)
line.text = self.__line
if self.__polygon:
polygon = xml_elem('{%s}polygon' % GEO_NS, entry)
polygon.text = self.__polygon
if self.__box:
box = xml_elem('{%s}box' % GEO_NS, entry)
box.text = self.__box
if self.__featuretypetag:
featuretypetag = xml_elem('{%s}featuretypetag' % GEO_NS, entry)
featuretypetag.text = self.__featuretypetag
if self.__relationshiptag:
relationshiptag = xml_elem('{%s}relationshiptag' % GEO_NS, entry)
relationshiptag.text = self.__relationshiptag
if self.__featurename:
featurename = xml_elem('{%s}featurename' % GEO_NS, entry)
featurename.text = self.__featurename
if self.__elev:
elevation = xml_elem('{%s}elev' % GEO_NS, entry)
elevation.text = str(self.__elev)
if self.__floor:
floor = xml_elem('{%s}floor' % GEO_NS, entry)
floor.text = str(self.__floor)
if self.__radius:
radius = xml_elem('{%s}radius' % GEO_NS, entry)
radius.text = str(self.__radius)
return entry
def extend_rss(self, entry):
return self.extend_file(entry)
def extend_atom(self, entry):
return self.extend_file(entry)
def point(self, point=None):
'''Get or set the georss:point of the entry.
:param point: The GeoRSS formatted point (i.e. "42.36 -71.05")
:returns: The current georss:point of the entry.
'''
if point is not None:
self.__point = point
return self.__point
def line(self, line=None):
'''Get or set the georss:line of the entry
:param point: The GeoRSS formatted line (i.e. "45.256 -110.45 46.46
-109.48 43.84 -109.86")
:return: The current georss:line of the entry
'''
if line is not None:
self.__line = line
return self.__line
def polygon(self, polygon=None):
'''Get or set the georss:polygon of the entry
:param polygon: The GeoRSS formatted polygon (i.e. "45.256 -110.45
46.46 -109.48 43.84 -109.86 45.256 -110.45")
:return: The current georss:polygon of the entry
'''
if polygon is not None:
self.__polygon = polygon
return self.__polygon
def box(self, box=None):
'''
Get or set the georss:box of the entry
:param box: The GeoRSS formatted box (i.e. "42.943 -71.032 43.039
-69.856")
:return: The current georss:box of the entry
'''
if box is not None:
self.__box = box
return self.__box
def featuretypetag(self, featuretypetag=None):
'''
Get or set the georss:featuretypetag of the entry
:param featuretypetag: The GeoRSS feaaturertyptag (e.g. "city")
:return: The current georss:featurertypetag
'''
if featuretypetag is not None:
self.__featuretypetag = featuretypetag
return self.__featuretypetag
def relationshiptag(self, relationshiptag=None):
'''
Get or set the georss:relationshiptag of the entry
:param relationshiptag: The GeoRSS relationshiptag (e.g.
"is-centred-at")
:return: the current georss:relationshiptag
'''
if relationshiptag is not None:
self.__relationshiptag = relationshiptag
return self.__relationshiptag
def featurename(self, featurename=None):
'''
Get or set the georss:featurename of the entry
:param featuretypetag: The GeoRSS featurename (e.g. "Footscray")
:return: the current georss:featurename
'''
if featurename is not None:
self.__featurename = featurename
return self.__featurename
def elev(self, elev=None):
'''
Get or set the georss:elev of the entry
:param elev: The GeoRSS elevation (e.g. 100.3)
:type elev: numbers.Number
:return: the current georss:elev
'''
if elev is not None:
if not isinstance(elev, numbers.Number):
raise ValueError("elev tag must be numeric: {}".format(elev))
self.__elev = elev
return self.__elev
def floor(self, floor=None):
'''
Get or set the georss:floor of the entry
:param floor: The GeoRSS floor (e.g. 4)
:type floor: int
:return: the current georss:floor
'''
if floor is not None:
if not isinstance(floor, int):
raise ValueError("floor tag must be int: {}".format(floor))
self.__floor = floor
return self.__floor
def radius(self, radius=None):
'''
Get or set the georss:radius of the entry
:param radius: The GeoRSS radius (e.g. 100.3)
:type radius: numbers.Number
:return: the current georss:radius
'''
if radius is not None:
if not isinstance(radius, numbers.Number):
raise ValueError(
"radius tag must be numeric: {}".format(radius)
)
self.__radius = radius
return self.__radius
def geom_from_geo_interface(self, geom):
'''
Generate a georss geometry from some Python object with a
``__geo_interface__`` property (see the `geo_interface specification by
Sean Gillies`_geointerface )
Note only a subset of GeoJSON (see `geojson.org`_geojson ) can be
easily converted to GeoRSS:
- Point
- LineString
- Polygon (if there are holes / donuts in the polygons a warning will
be generaated
Other GeoJson types will raise a ``ValueError``.
.. note:: The geometry is assumed to be x, y as longitude, latitude in
the WGS84 projection.
.. _geointerface: https://gist.github.com/sgillies/2217756
.. _geojson: https://geojson.org/
:param geom: Geometry object with a __geo_interface__ property
:return: the formatted GeoRSS geometry
'''
geojson = geom.__geo_interface__
if geojson['type'] not in ('Point', 'LineString', 'Polygon'):
raise GeoRSSGeometryError(geom)
if geojson['type'] == 'Point':
coords = '{:f} {:f}'.format(
geojson['coordinates'][1], # latitude is y
geojson['coordinates'][0]
)
return self.point(coords)
elif geojson['type'] == 'LineString':
coords = ' '.join(
'{:f} {:f}'.format(vertex[1], vertex[0])
for vertex in
geojson['coordinates']
)
return self.line(coords)
elif geojson['type'] == 'Polygon':
if len(geojson['coordinates']) > 1:
warnings.warn(GeoRSSPolygonInteriorWarning(geom))
coords = ' '.join(
'{:f} {:f}'.format(vertex[1], vertex[0])
for vertex in
geojson['coordinates'][0]
)
return self.polygon(coords)
| ./CrossVul/dataset_final_sorted/CWE-776/py/good_4531_2 |
crossvul-python_data_good_4204_6 | """
Misc ASCII art
"""
WARNING = r"""
_mBma
sQf "QL
jW( -$g.
jW' -$m,
.y@' _aa. 4m,
.mD` ]QQWQ. 4Q,
_mP` ]QQQQ ?Q/
_QF )WQQ@ ?Qc
<QF QQQF )Qa
jW( QQQf "QL
jW' ]H8' -Q6.
.y@' _as. -$m.
.m@` ]QQWQ. -4m,
_mP` -?$8! 4Q,
mE $m
?$gyygggggggggwywgyygggggggygggggD(
"""
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_4204_6 |
crossvul-python_data_good_461_1 | # -*- coding: utf-8 -*-
# Copyright (C) 2017-2018 CIRCL Computer Incident Response Center Luxembourg (smile gie)
# Copyright (C) 2017-2018 Christian Studer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import json
import os
import time
import uuid
import base64
import stix2misp_mapping
import stix.extensions.marking.ais
from operator import attrgetter
from pymisp import MISPEvent, MISPObject, MISPAttribute, __path__
from stix.core import STIXPackage
from collections import defaultdict
cybox_to_misp_object = {"Account": "credential", "AutonomousSystem": "asn",
"EmailMessage": "email", "NetworkConnection": "network-connection",
"NetworkSocket": "network-socket", "Process": "process",
"x509Certificate": "x509", "Whois": "whois"}
threat_level_mapping = {'High': '1', 'Medium': '2', 'Low': '3', 'Undefined': '4'}
descFilename = os.path.join(__path__[0], 'data/describeTypes.json')
with open(descFilename, 'r') as f:
categories = json.loads(f.read())['result'].get('categories')
class StixParser():
def __init__(self):
super(StixParser, self).__init__()
self.misp_event = MISPEvent()
self.misp_event['Galaxy'] = []
self.references = defaultdict(list)
################################################################################
## LOADING & UTILITY FUNCTIONS USED BY BOTH SUBCLASSES. ##
################################################################################
# Load data from STIX document, and other usefull data
def load_event(self, args, filename, from_misp, stix_version):
self.outputname = '{}.json'.format(filename)
try:
event_distribution = args[0]
if not isinstance(event_distribution, int):
event_distribution = int(event_distribution) if event_distribution.isdigit() else 5
except IndexError:
event_distribution = 5
try:
attribute_distribution = args[1]
if attribute_distribution == 'event':
attribute_distribution = event_distribution
elif not isinstance(attribute_distribution, int):
attribute_distribution = int(attribute_distribution) if attribute_distribution.isdigit() else event_distribution
except IndexError:
attribute_distribution = event_distribution
self.misp_event.distribution = event_distribution
self.__attribute_distribution = attribute_distribution
self.from_misp = from_misp
self.load_mapping()
# Convert the MISP event we create from the STIX document into json format
# and write it in the output file
def saveFile(self):
eventDict = self.misp_event.to_json()
with open(self.outputname, 'wt', encoding='utf-8') as f:
f.write(eventDict)
# Load the mapping dictionary for STIX object types
def load_mapping(self):
self.attribute_types_mapping = {
"AccountObjectType": self.handle_credential,
'AddressObjectType': self.handle_address,
"ArtifactObjectType": self.handle_attachment,
"ASObjectType": self.handle_as,
"CustomObjectType": self.handle_custom,
"DNSRecordObjectType": self.handle_dns,
'DomainNameObjectType': self.handle_domain_or_url,
'EmailMessageObjectType': self.handle_email_attribute,
'FileObjectType': self.handle_file,
'HostnameObjectType': self.handle_hostname,
'HTTPSessionObjectType': self.handle_http,
'MutexObjectType': self.handle_mutex,
'NetworkConnectionObjectType': self.handle_network_connection,
'NetworkSocketObjectType': self.handle_network_socket,
'PDFFileObjectType': self.handle_file,
'PortObjectType': self.handle_port,
'ProcessObjectType': self.handle_process,
'SocketAddressObjectType': self.handle_socket_address,
'SystemObjectType': self.handle_system,
'URIObjectType': self.handle_domain_or_url,
"WhoisObjectType": self.handle_whois,
"WindowsFileObjectType": self.handle_file,
'WindowsRegistryKeyObjectType': self.handle_regkey,
"WindowsExecutableFileObjectType": self.handle_pe,
"WindowsServiceObjectType": self.handle_windows_service,
"X509CertificateObjectType": self.handle_x509
}
self.marking_mapping = {
'AIS:AISMarkingStructure': self.parse_AIS_marking,
'tlpMarking:TLPMarkingStructureType': self.parse_TLP_marking
}
def parse_marking(self, handling):
tags = []
if hasattr(handling, 'marking_structures') and handling.marking_structures:
for marking in handling.marking_structures:
try:
tags.extend(self.marking_mapping[marking._XSI_TYPE](marking))
except KeyError:
print(marking._XSI_TYPE, file=sys.stderr)
continue
return tags
def set_distribution(self):
for attribute in self.misp_event.attributes:
attribute.distribution = self.__attribute_distribution
for misp_object in self.misp_event.objects:
misp_object.distribution = self.__attribute_distribution
for attribute in misp_object.attributes:
attribute.distribution = self.__attribute_distribution
# Make references between objects
def build_references(self):
for misp_object in self.misp_event.objects:
object_uuid = misp_object.uuid
if object_uuid in self.references:
for reference in self.references[object_uuid]:
misp_object.add_reference(reference['idref'], reference['relationship'])
# Set info & title values in the new MISP event
def get_event_info(self):
info = "Imported from external STIX event"
try:
try:
title = self.event.stix_header.title
except AttributeError:
title = self.event.title
if title:
info = title
except AttributeError:
pass
return info
# Get timestamp & date values in the new MISP event
def get_timestamp_and_date(self):
stix_date = self.event.timestamp
try:
date = stix_date.split("T")[0]
except AttributeError:
date = stix_date
return date, self.getTimestampfromDate(stix_date)
# Translate date into timestamp
@staticmethod
def getTimestampfromDate(date):
try:
try:
dt = date.split('+')[0]
d = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
except ValueError:
dt = date.split('.')[0]
d = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
except AttributeError:
d = int(time.mktime(date.timetuple()))
return d
################################################################################
## STIX OBJECTS PARSING FUNCTIONS USED BY BOTH SUBCLASSES ##
################################################################################
# Define type & value of an attribute or object in MISP
def handle_attribute_type(self, properties, is_object=False, title=None, observable_id=None):
xsi_type = properties._XSI_TYPE
# try:
args = [properties]
if xsi_type in ("FileObjectType", "PDFFileObjectType", "WindowsFileObjectType"):
args.append(is_object)
elif xsi_type == "ArtifactObjectType":
args.append(title)
return self.attribute_types_mapping[xsi_type](*args)
# except AttributeError:
# # ATM USED TO TEST TYPES
# print("Unparsed type: {}".format(xsi_type))
# sys.exit(1)
# Return type & value of an ip address attribute
@staticmethod
def handle_address(properties):
if properties.is_source:
ip_type = "ip-src"
else:
ip_type = "ip-dst"
return ip_type, properties.address_value.value, "ip"
def handle_as(self, properties):
attributes = self.fetch_attributes_with_partial_key_parsing(properties, stix2misp_mapping._as_mapping)
return attributes[0] if len(attributes) == 1 else ('asn', self.return_attributes(attributes), '')
# Return type & value of an attachment attribute
@staticmethod
def handle_attachment(properties, title):
if properties.hashes:
return "malware-sample", "{}|{}".format(title, properties.hashes[0], properties.raw_artifact.value)
return stix2misp_mapping.eventTypes[properties._XSI_TYPE]['type'], title, properties.raw_artifact.value
# Return type & attributes of a credential object
def handle_credential(self, properties):
attributes = []
if properties.description:
attributes.append(["text", properties.description.value, "text"])
if properties.authentication:
for authentication in properties.authentication:
attributes += self.fetch_attributes_with_key_parsing(authentication, stix2misp_mapping._credential_authentication_mapping)
if properties.custom_properties:
for prop in properties.custom_properties:
if prop.name in stix2misp_mapping._credential_custom_types:
attributes.append(['text', prop.value, prop.name])
return attributes[0] if len(attributes) == 1 else ("credential", self.return_attributes(attributes), "")
# Return type & attributes of a dns object
def handle_dns(self, properties):
relation = []
if properties.domain_name:
relation.append(["domain", str(properties.domain_name.value), ""])
if properties.ip_address:
relation.append(["ip-dst", str(properties.ip_address.value), ""])
if relation:
if len(relation) == '2':
domain = relation[0][1]
ip = relattion[1][1]
attributes = [["text", domain, "rrname"], ["text", ip, "rdata"]]
rrtype = "AAAA" if ":" in ip else "A"
attributes.append(["text", rrtype, "rrtype"])
return "passive-dns", self.return_attributes(attributes), ""
return relation[0]
# Return type & value of a domain or url attribute
@staticmethod
def handle_domain_or_url(properties):
event_types = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
return event_types['type'], properties.value.value, event_types['relation']
# Return type & value of an email attribute
def handle_email_attribute(self, properties):
if properties.header:
header = properties.header
attributes = self.fetch_attributes_with_key_parsing(header, stix2misp_mapping._email_mapping)
if header.to:
for to in header.to:
attributes.append(["email-dst", to.address_value.value, "to"])
if header.cc:
for cc in header.cc:
attributes.append(["email-dst", cc.address_value.value, "cc"])
else:
attributes = []
if properties.attachments:
attributes.append(self.handle_email_attachment(properties.parent))
return attributes[0] if len(attributes) == 1 else ("email", self.return_attributes(attributes), "")
# Return type & value of an email attachment
@staticmethod
def handle_email_attachment(indicator_object):
properties = indicator_object.related_objects[0].properties
return ["email-attachment", properties.file_name.value, "attachment"]
# Return type & attributes of a file object
def handle_file(self, properties, is_object):
b_hash, b_file = False, False
attributes = []
if properties.hashes:
b_hash = True
for h in properties.hashes:
attributes.append(self.handle_hashes_attribute(h))
if properties.file_name:
value = properties.file_name.value
if value:
b_file = True
attribute_type, relation = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
attributes.append([attribute_type, value, relation])
attributes.extend(self.fetch_attributes_with_keys(properties, stix2misp_mapping._file_mapping))
if len(attributes) == 1:
attribute = attributes[0]
return attribute[0] if attribute[2] != "fullpath" else "filename", attribute[1], ""
if len(attributes) == 2:
if b_hash and b_file:
return self.handle_filename_object(attributes, is_object)
path, filename = self.handle_filename_path_case(attributes)
if path and filename:
attribute_value = "{}\\{}".format(path, filename)
if '\\' in filename and path == filename:
attribute_value = filename
return "filename", attribute_value, ""
return "file", self.return_attributes(attributes), ""
# Determine path & filename from a complete path or filename attribute
@staticmethod
def handle_filename_path_case(attributes):
path, filename = [""] * 2
if attributes[0][2] == 'filename' and attributes[1][2] == 'path':
path = attributes[1][1]
filename = attributes[0][1]
elif attributes[0][2] == 'path' and attributes[1][2] == 'filename':
path = attributes[0][1]
filename = attributes[1][1]
return path, filename
# Return the appropriate type & value when we have 1 filename & 1 hash value
@staticmethod
def handle_filename_object(attributes, is_object):
for attribute in attributes:
attribute_type, attribute_value, _ = attribute
if attribute_type == "filename":
filename_value = attribute_value
else:
hash_type, hash_value = attribute_type, attribute_value
value = "{}|{}".format(filename_value, hash_value)
if is_object:
# file object attributes cannot be filename|hash, so it is malware-sample
attr_type = "malware-sample"
return attr_type, value, attr_type
# it could be malware-sample as well, but STIX is losing this information
return "filename|{}".format(hash_type), value, ""
# Return type & value of a hash attribute
@staticmethod
def handle_hashes_attribute(properties):
hash_type = properties.type_.value.lower()
try:
hash_value = properties.simple_hash_value.value
except AttributeError:
hash_value = properties.fuzzy_hash_value.value
return hash_type, hash_value, hash_type
# Return type & value of a hostname attribute
@staticmethod
def handle_hostname(properties):
event_types = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
return event_types['type'], properties.hostname_value.value, event_types['relation']
# Return type & value of a http request attribute
@staticmethod
def handle_http(properties):
client_request = properties.http_request_response[0].http_client_request
if client_request.http_request_header:
request_header = client_request.http_request_header
if request_header.parsed_header:
value = request_header.parsed_header.user_agent.value
return "user-agent", value, "user-agent"
elif request_header.raw_header:
value = request_header.raw_header.value
return "http-method", value, "method"
elif client_request.http_request_line:
value = client_request.http_request_line.http_method.value
return "http-method", value, "method"
# Return type & value of a mutex attribute
@staticmethod
def handle_mutex(properties):
event_types = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
return event_types['type'], properties.name.value, event_types['relation']
# Return type & attributes of a network connection object
def handle_network_connection(self, properties):
attributes = self.fetch_attributes_from_sockets(properties, stix2misp_mapping._network_connection_addresses)
for prop in ('layer3_protocol', 'layer4_protocol', 'layer7_protocol'):
if getattr(properties, prop):
attributes.append(['text', attrgetter("{}.value".format(prop))(properties), prop.replace('_', '-')])
if attributes:
return "network-connection", self.return_attributes(attributes), ""
# Return type & attributes of a network socket objet
def handle_network_socket(self, properties):
attributes = self.fetch_attributes_from_sockets(properties, stix2misp_mapping._network_socket_addresses)
attributes.extend(self.fetch_attributes_with_keys(properties, stix2misp_mapping._network_socket_mapping))
for prop in ('is_listening', 'is_blocking'):
if getattr(properties, prop):
attributes.append(["text", prop.split('_')[1], "state"])
if attributes:
return "network-socket", self.return_attributes(attributes), ""
# Return type & value of a port attribute
@staticmethod
def handle_port(*kwargs):
properties = kwargs[0]
event_types = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
relation = event_types['relation']
if len(kwargs) > 1:
observable_id = kwargs[1]
if "srcPort" in observable_id:
relation = "src-{}".format(relation)
elif "dstPort" in observable_id:
relation = "dst-{}".format(relation)
return event_types['type'], properties.port_value.value, relation
# Return type & attributes of a process object
def handle_process(self, properties):
attributes = self.fetch_attributes_with_partial_key_parsing(properties, stix2misp_mapping._process_mapping)
if properties.child_pid_list:
for child in properties.child_pid_list:
attributes.append(["text", child.value, "child-pid"])
# if properties.port_list:
# for port in properties.port_list:
# attributes.append(["src-port", port.port_value.value, "port"])
if properties.network_connection_list:
references = []
for connection in properties.network_connection_list:
object_name, object_attributes, _ = self.handle_network_connection(connection)
object_uuid = str(uuid.uuid4())
misp_object = MISPObject(object_name)
misp_object.uuid = object_uuid
for attribute in object_attributes:
misp_object.add_attribute(**attribute)
references.append(object_uuid)
return "process", self.return_attributes(attributes), {"process_uuid": references}
return "process", self.return_attributes(attributes), ""
# Return type & value of a regkey attribute
def handle_regkey(self, properties):
attributes = self.fetch_attributes_with_partial_key_parsing(properties, stix2misp_mapping._regkey_mapping)
if properties.values:
values = properties.values
value = values[0]
attributes += self.fetch_attributes_with_partial_key_parsing(value, stix2misp_mapping._regkey_value_mapping)
if len(attributes) in (2,3):
d_regkey = {key: value for (_, value, key) in attributes}
if 'hive' in d_regkey and 'key' in d_regkey:
regkey = "{}\\{}".format(d_regkey['hive'], d_regkey['key'])
if 'data' in d_regkey:
return "regkey|value", "{} | {}".format(regkey, d_regkey['data']), ""
return "regkey", regkey, ""
return "registry-key", self.return_attributes(attributes), ""
@staticmethod
def handle_socket(attributes, socket, s_type):
for prop, mapping in stix2misp_mapping._socket_mapping.items():
if getattr(socket, prop):
attribute_type, properties_key, relation = mapping
attribute_type, relation = [elem.format(s_type) for elem in (attribute_type, relation)]
attributes.append([attribute_type, attrgetter('{}.{}.value'.format(prop, properties_key))(socket), relation])
# Parse a socket address object in order to return type & value
# of a composite attribute ip|port or hostname|port
def handle_socket_address(self, properties):
if properties.ip_address:
type1, value1, _ = self.handle_address(properties.ip_address)
elif properties.hostname:
type1 = "hostname"
value1 = properties.hostname.hostname_value.value
return "{}|port".format(type1), "{}|{}".format(value1, properties.port.port_value.value), ""
# Parse a system object to extract a mac-address attribute
@staticmethod
def handle_system(properties):
if properties.network_interface_list:
return "mac-address", str(properties.network_interface_list[0].mac), ""
# Parse a whois object:
# Return type & attributes of a whois object if we have the required fields
# Otherwise create attributes and return type & value of the last attribute to avoid crashing the parent function
def handle_whois(self, properties):
attributes = self.fetch_attributes_with_key_parsing(properties, stix2misp_mapping._whois_mapping)
required_one_of = True if attributes else False
if properties.registrants:
registrant = properties.registrants[0]
attributes += self.fetch_attributes_with_key_parsing(registrant, stix2misp_mapping._whois_registrant_mapping)
if properties.creation_date:
attributes.append(["datetime", properties.creation_date.value.strftime('%Y-%m-%d'), "creation-date"])
required_one_of = True
if properties.updated_date:
attributes.append(["datetime", properties.updated_date.value.strftime('%Y-%m-%d'), "modification-date"])
if properties.expiration_date:
attributes.append(["datetime", properties.expiration_date.value.strftime('%Y-%m-%d'), "expiration-date"])
if properties.nameservers:
for nameserver in properties.nameservers:
attributes.append(["hostname", nameserver.value.value, "nameserver"])
if properties.remarks:
attribute_type = "text"
relation = "comment" if attributes else attribute_type
attributes.append([attribute_type, properties.remarks.value, relation])
required_one_of = True
# Testing if we have the required attribute types for Object whois
if required_one_of:
# if yes, we return the object type and the attributes
return "whois", self.return_attributes(attributes), ""
# otherwise, attributes are added in the event, and one attribute is returned to not make the function crash
if len(attributes) == 1:
return attributes[0]
last_attribute = attributes.pop(-1)
for attribute in attributes:
attribute_type, attribute_value, attribute_relation = attribute
misp_attributes = {"comment": "Whois {}".format(attribute_relation)}
self.misp_event.add_attribute(attribute_type, attribute_value, **misp_attributes)
return last_attribute
# Return type & value of a windows service object
@staticmethod
def handle_windows_service(properties):
if properties.name:
return "windows-service-name", properties.name.value, ""
def handle_x509(self, properties):
attributes = self.handle_x509_certificate(properties.certificate) if properties.certificate else []
if properties.raw_certificate:
raw = properties.raw_certificate.value
try:
relation = "raw-base64" if raw == base64.b64encode(base64.b64decode(raw)).strip() else "pem"
except Exception:
relation = "pem"
attributes.append(["text", raw, relation])
if properties.certificate_signature:
signature = properties.certificate_signature
attribute_type = "x509-fingerprint-{}".format(signature.signature_algorithm.value.lower())
attributes.append([attribute_type, signature.signature.value, attribute_type])
return "x509", self.return_attributes(attributes), ""
@staticmethod
def handle_x509_certificate(certificate):
attributes = []
if certificate.validity:
validity = certificate.validity
for prop in stix2misp_mapping._x509_datetime_types:
if getattr(validity, prop):
attributes.append(['datetime', attrgetter('{}.value'.format(prop))(validity), 'validity-{}'.format(prop.replace('_', '-'))])
if certificate.subject_public_key:
subject_pubkey = certificate.subject_public_key
if subject_pubkey.rsa_public_key:
rsa_pubkey = subject_pubkey.rsa_public_key
for prop in stix2misp_mapping._x509__x509_pubkey_types:
if getattr(rsa_pubkey, prop):
attributes.append(['text', attrgetter('{}.value'.format(prop))(rsa_pubkey), 'pubkey-info-{}'.format(prop)])
if subject_pubkey.public_key_algorithm:
attributes.append(["text", subject_pubkey.public_key_algorithm.value, "pubkey-info-algorithm"])
for prop in stix2misp_mapping._x509_certificate_types:
if getattr(certificate, prop):
attributes.append(['text', attrgetter('{}.value'.format(prop))(certificate), prop.replace('_', '-')])
return attributes
# Return type & attributes of the file defining a portable executable object
def handle_pe(self, properties):
pe_uuid = self.parse_pe(properties)
file_type, file_value, _ = self.handle_file(properties, False)
return file_type, file_value, pe_uuid
# Parse attributes of a portable executable, create the corresponding object,
# and return its uuid to build the reference for the file object generated at the same time
def parse_pe(self, properties):
misp_object = MISPObject('pe')
filename = properties.file_name.value
for attr in ('internal-filename', 'original-filename'):
misp_object.add_attribute(**dict(zip(('type', 'value', 'object_relation'),('filename', filename, attr))))
if properties.headers:
headers = properties.headers
header_object = MISPObject('pe-section')
if headers.entropy:
header_object.add_attribute(**{"type": "float", "object_relation": "entropy",
"value": headers.entropy.value.value})
file_header = headers.file_header
misp_object.add_attribute(**{"type": "counter", "object_relation": "number-sections",
"value": file_header.number_of_sections.value})
for h in file_header.hashes:
hash_type, hash_value, hash_relation = self.handle_hashes_attribute(h)
header_object.add_attribute(**{"type": hash_type, "value": hash_value, "object_relation": hash_relation})
if file_header.size_of_optional_header:
header_object.add_attribute(**{"type": "size-in-bytes", "object_relation": "size-in-bytes",
"value": file_header.size_of_optional_header.value})
self.misp_event.add_object(**header_object)
misp_object.add_reference(header_object.uuid, 'header-of')
if properties.sections:
for section in properties.sections:
section_uuid = self.parse_pe_section(section)
misp_object.add_reference(section_uuid, 'included-in')
self.misp_event.add_object(**misp_object)
return {"pe_uuid": misp_object.uuid}
# Parse attributes of a portable executable section, create the corresponding object,
# and return its uuid to build the reference for the pe object generated at the same time
def parse_pe_section(self, section):
section_object = MISPObject('pe-section')
header_hashes = section.header_hashes
for h in header_hashes:
hash_type, hash_value, hash_relation = self.handle_hashes_attribute(h)
section_object.add_attribute(**{"type": hash_type, "value": hash_value, "object_relation": hash_relation})
if section.entropy:
section_object.add_attribute(**{"type": "float", "object_relation": "entropy",
"value": section.entropy.value.value})
if section.section_header:
section_header = section.section_header
section_object.add_attribute(**{"type": "text", "object_relation": "name",
"value": section_header.name.value})
section_object.add_attribute(**{"type": "size-in-bytes", "object_relation": "size-in-bytes",
"value": section_header.size_of_raw_data.value})
self.misp_event.add_object(**section_object)
return section_object.uuid
################################################################################
## MARKINGS PARSING FUNCTIONS USED BY BOTH SUBCLASSES ##
################################################################################
def parse_AIS_marking(self, marking):
tags = []
if hasattr(marking, 'is_proprietary') and marking.is_proprietary:
proprietary = "Is"
marking = marking.is_proprietary
elif hasattr(marking, 'not_proprietary') and marking.not_proprietary:
proprietary = "Not"
marking = marking.not_proprietary
else:
return
mapping = stix2misp_mapping._AIS_marking_mapping
prefix = mapping['prefix']
tags.append('{}{}'.format(prefix, mapping['proprietary'].format(proprietary)))
if hasattr(marking, 'cisa_proprietary'):
try:
cisa_proprietary = marking.cisa_proprietary.numerator
cisa_proprietary = 'true' if cisa_proprietary == 1 else 'false'
tags.append('{}{}'.format(prefix, mapping['cisa_proprietary'].format(cisa_proprietary)))
except AttributeError:
pass
for ais_field in ('ais_consent', 'tlp_marking'):
if hasattr(marking, ais_field) and getattr(marking, ais_field):
key, tag = mapping[ais_field]
tags.append('{}{}'.format(prefix, tag.format(getattr(getattr(marking, ais_field), key))))
return tags
def parse_TLP_marking(self, marking):
return ['tlp:{}'.format(marking.color.lower())]
################################################################################
## FUNCTIONS HANDLING PARSED DATA, USED BY BOTH SUBCLASSES. ##
################################################################################
# The value returned by the indicators or observables parser is of type str or int
# Thus we can add an attribute in the MISP event with the type & value
def handle_attribute_case(self, attribute_type, attribute_value, data, attribute):
if attribute_type == 'attachment':
attribute['data'] = data
elif attribute_type == 'text':
attribute['comment'] = data
self.misp_event.add_attribute(attribute_type, attribute_value, **attribute)
# The value returned by the indicators or observables parser is a list of dictionaries
# These dictionaries are the attributes we add in an object, itself added in the MISP event
def handle_object_case(self, attribute_type, attribute_value, compl_data, to_ids=False, object_uuid=None):
misp_object = MISPObject(attribute_type)
if object_uuid:
misp_object.uuid = object_uuid
for attribute in attribute_value:
attribute['to_ids'] = to_ids
misp_object.add_attribute(**attribute)
if isinstance(compl_data, dict):
# if some complementary data is a dictionary containing an uuid,
# it means we are using it to add an object reference
if "pe_uuid" in compl_data:
misp_object.add_reference(compl_data['pe_uuid'], 'included-in')
if "process_uuid" in compl_data:
for uuid in compl_data["process_uuid"]:
misp_object.add_reference(uuid, 'connected-to')
self.misp_event.add_object(**misp_object)
################################################################################
## UTILITY FUNCTIONS USED BY PARSING FUNCTION ABOVE ##
################################################################################
def fetch_attributes_from_sockets(self, properties, mapping_dict):
attributes = []
for prop, s_type in zip(mapping_dict, stix2misp_mapping._s_types):
address_property = getattr(properties, prop)
if address_property:
self.handle_socket(attributes, address_property, s_type)
return attributes
@staticmethod
def fetch_attributes_with_keys(properties, mapping_dict):
attributes = []
for prop, mapping in mapping_dict.items():
if getattr(properties,prop):
attribute_type, properties_key, relation = mapping
attributes.append([attribute_type, attrgetter(properties_key)(properties), relation])
return attributes
@staticmethod
def fetch_attributes_with_key_parsing(properties, mapping_dict):
attributes = []
for prop, mapping in mapping_dict.items():
if getattr(properties, prop):
attribute_type, properties_key, relation = mapping
attributes.append([attribute_type, attrgetter('{}.{}'.format(prop, properties_key))(properties), relation])
return attributes
@staticmethod
def fetch_attributes_with_partial_key_parsing(properties, mapping_dict):
attributes = []
for prop, mapping in mapping_dict.items():
if getattr(properties, prop):
attribute_type, relation = mapping
attributes.append([attribute_type, attrgetter('{}.value'.format(prop))(properties), relation])
return attributes
# Extract the uuid from a stix id
@staticmethod
def fetch_uuid(object_id):
try:
return "-".join(object_id.split("-")[-5:])
except Exception:
return str(uuid.uuid4())
# Return the attributes that will be added in a MISP object as a list of dictionaries
@staticmethod
def return_attributes(attributes):
return_attributes = []
for attribute in attributes:
return_attributes.append(dict(zip(('type', 'value', 'object_relation'), attribute)))
return return_attributes
class StixFromMISPParser(StixParser):
def __init__(self):
super(StixFromMISPParser, self).__init__()
self.dates = []
self.timestamps = []
self.titles = []
def build_misp_dict(self, event):
for item in event.related_packages.related_package:
package = item.item
self.event = package.incidents[0]
self.set_timestamp_and_date()
self.set_event_info()
if self.event.related_indicators:
for indicator in self.event.related_indicators.indicator:
self.parse_misp_indicator(indicator)
if self.event.related_observables:
for observable in self.event.related_observables.observable:
self.parse_misp_observable(observable)
if self.event.history:
self.parse_journal_entries()
if self.event.information_source and self.event.information_source.references:
for reference in self.event.information_source.references:
self.misp_event.add_attribute(**{'type': 'link', 'value': reference})
if package.ttps:
for ttp in package.ttps.ttps:
if ttp.exploit_targets:
self.parse_vulnerability(ttp.exploit_targets.exploit_target)
# if ttp.handling:
# self.parse_tlp_marking(ttp.handling)
self.set_distribution()
# Return type & attributes (or value) of a Custom Object
def handle_custom(self, properties):
custom_properties = properties.custom_properties
attributes = []
for prop in custom_properties:
attribute_type, relation = prop.name.split(': ')
attribute_type = attribute_type.split(' ')[1]
attributes.append([attribute_type, prop.value, relation])
if len(attributes) > 1:
name = custom_properties[0].name.split(' ')[0]
return name, self.return_attributes(attributes), ""
return attributes[0]
def parse_journal_entries(self):
for entry in self.event.history.history_items:
journal_entry = entry.journal_entry.value
try:
entry_type, entry_value = journal_entry.split(': ')
if entry_type == "MISP Tag":
self.parse_tag(entry_value)
elif entry_type.startswith('attribute['):
_, category, attribute_type = entry_type.split('[')
self.misp_event.add_attribute(**{'type': attribute_type[:-1], 'category': category[:-1], 'value': entry_value})
elif entry_type == "Event Threat Level":
self.misp_event.threat_level_id = threat_level_mapping[entry_value]
except ValueError:
continue
# Parse indicators of a STIX document coming from our exporter
def parse_misp_indicator(self, indicator):
# define is an indicator will be imported as attribute or object
if indicator.relationship in categories:
self.parse_misp_attribute_indicator(indicator)
else:
self.parse_misp_object_indicator(indicator)
def parse_misp_observable(self, observable):
if observable.relationship in categories:
self.parse_misp_attribute_observable(observable)
else:
self.parse_misp_object_observable(observable)
# Parse STIX objects that we know will give MISP attributes
def parse_misp_attribute_indicator(self, indicator):
misp_attribute = {'to_ids': True, 'category': str(indicator.relationship),
'uuid': self.fetch_uuid(indicator.id_)}
item = indicator.item
misp_attribute['timestamp'] = self.getTimestampfromDate(item.timestamp)
if item.observable:
observable = item.observable
self.parse_misp_attribute(observable, misp_attribute, to_ids=True)
def parse_misp_attribute_observable(self, observable):
misp_attribute = {'to_ids': False, 'category': str(observable.relationship),
'uuid': self.fetch_uuid(observable.id_)}
if observable.item:
self.parse_misp_attribute(observable.item, misp_attribute)
def parse_misp_attribute(self, observable, misp_attribute, to_ids=False):
try:
properties = observable.object_.properties
if properties:
attribute_type, attribute_value, compl_data = self.handle_attribute_type(properties)
if isinstance(attribute_value, (str, int)):
self.handle_attribute_case(attribute_type, attribute_value, compl_data, misp_attribute)
else:
self.handle_object_case(attribute_type, attribute_value, compl_data, to_ids=to_ids)
except AttributeError:
attribute_dict = {}
for observables in observable.observable_composition.observables:
properties = observables.object_.properties
attribute_type, attribute_value, _ = self.handle_attribute_type(properties, observable_id=observable.id_)
attribute_dict[attribute_type] = attribute_value
attribute_type, attribute_value = self.composite_type(attribute_dict)
self.misp_event.add_attribute(attribute_type, attribute_value, **misp_attribute)
# Return type & value of a composite attribute in MISP
@staticmethod
def composite_type(attributes):
if "port" in attributes:
if "ip-src" in attributes:
return "ip-src|port", "{}|{}".format(attributes["ip-src"], attributes["port"])
elif "ip-dst" in attributes:
return "ip-dst|port", "{}|{}".format(attributes["ip-dst"], attributes["port"])
elif "hostname" in attributes:
return "hostname|port", "{}|{}".format(attributes["hostname"], attributes["port"])
elif "domain" in attributes:
if "ip-src" in attributes:
ip_value = attributes["ip-src"]
elif "ip-dst" in attributes:
ip_value = attributes["ip-dst"]
return "domain|ip", "{}|{}".format(attributes["domain"], ip_value)
# Parse STIX object that we know will give MISP objects
def parse_misp_object_indicator(self, indicator):
object_type = str(indicator.relationship)
item = indicator.item
name = item.title.split(' ')[0]
if name not in ('passive-dns'):
self.fill_misp_object(item, name, to_ids=True)
else:
if object_type != "misc":
print("Unparsed Object type: {}".format(name), file=sys.stderr)
def parse_misp_object_observable(self, observable):
object_type = str(observable.relationship)
observable = observable.item
observable_id = observable.id_
if object_type == "file":
name = "registry-key" if "WinRegistryKey" in observable_id else "file"
elif object_type == "network":
if "Custom" in observable_id:
name = observable_id.split("Custom")[0].split(":")[1]
elif "ObservableComposition" in observable_id:
name = observable_id.split("_")[0].split(":")[1]
else:
name = cybox_to_misp_object[observable_id.split('-')[0].split(':')[1]]
else:
name = cybox_to_misp_object[observable_id.split('-')[0].split(':')[1]]
try:
self.fill_misp_object(observable, name)
except Exception:
print("Unparsed Object type: {}".format(observable.to_json()), file=sys.stderr)
# Create a MISP object, its attributes, and add it in the MISP event
def fill_misp_object(self, item, name, to_ids=False):
uuid = self.fetch_uuid(item.id_)
try:
misp_object = MISPObject(name)
misp_object.uuid = uuid
if to_ids:
observables = item.observable.observable_composition.observables
misp_object.timestamp = self.getTimestampfromDate(item.timestamp)
else:
observables = item.observable_composition.observables
for observable in observables:
properties = observable.object_.properties
misp_attribute = MISPAttribute()
misp_attribute.type, misp_attribute.value, misp_attribute.object_relation = self.handle_attribute_type(properties, is_object=True, observable_id=observable.id_)
misp_attribute.to_ids = to_ids
misp_object.add_attribute(**misp_attribute)
self.misp_event.add_object(**misp_object)
except AttributeError:
properties = item.observable.object_.properties if to_ids else item.object_.properties
self.parse_observable(properties, to_ids, uuid)
# Create a MISP attribute and add it in its MISP object
def parse_observable(self, properties, to_ids, uuid):
attribute_type, attribute_value, compl_data = self.handle_attribute_type(properties)
if isinstance(attribute_value, (str, int)):
attribute = {'to_ids': to_ids, 'uuid': uuid}
self.handle_attribute_case(attribute_type, attribute_value, compl_data, attribute)
else:
self.handle_object_case(attribute_type, attribute_value, compl_data, to_ids=to_ids, object_uuid=uuid)
def parse_tag(self, entry):
if entry.startswith('misp-galaxy:'):
tag_type, value = entry.split('=')
galaxy_type = tag_type.split(':')[1]
cluster = {'type': galaxy_type, 'value': value[1:-1], 'tag_name': entry}
self.misp_event['Galaxy'].append({'type': galaxy_type, 'GalaxyCluster': [cluster]})
self.misp_event.add_tag(entry)
def parse_vulnerability(self, exploit_targets):
for exploit_target in exploit_targets:
if exploit_target.item:
for vulnerability in exploit_target.item.vulnerabilities:
self.misp_event.add_attribute(**{'type': 'vulnerability', 'value': vulnerability.cve_id})
def set_event_info(self):
info = self.get_event_info()
self.titles.append(info)
def set_timestamp_and_date(self):
if self.event.timestamp:
date, timestamp = self.get_timestamp_and_date()
self.dates.append(date)
self.timestamps.append(timestamp)
class ExternalStixParser(StixParser):
def __init__(self):
super(ExternalStixParser, self).__init__()
self.dns_objects = defaultdict(dict)
self.dns_ips = []
def build_misp_dict(self, event):
self.event = event
self.set_timestamp_and_date()
self.set_event_info()
header = self.event.stix_header
if hasattr(header, 'description') and hasattr(header.description, 'value'):
self.misp_event.add_attribute(**{'type': 'comment', 'value': header.description.value,
'comment': 'Imported from STIX header description'})
if hasattr(header, 'handling') and header.handling:
for handling in header.handling:
tags = self.parse_marking(handling)
for tag in tags:
self.misp_event.add_tag(tag)
if self.event.indicators:
self.parse_external_indicators(self.event.indicators)
if self.event.observables:
self.parse_external_observable(self.event.observables.observables)
if self.event.ttps:
self.parse_ttps(self.event.ttps.ttps)
if self.event.courses_of_action:
self.parse_coa(self.event.courses_of_action)
if self.dns_objects:
self.resolve_dns_objects()
self.set_distribution()
if self.references:
self.build_references()
def set_event_info(self):
info = self.get_event_info()
self.misp_event.info = str(info)
def set_timestamp_and_date(self):
if self.event.timestamp:
date, timestamp = self.get_timestamp_and_date()
self.misp_event.date = date
self.misp_event.timestamp = timestamp
# Return type & attributes (or value) of a Custom Object
def handle_custom(self, properties):
custom_properties = properties.custom_properties
if len(custom_properties) > 1:
for prop in custom_properties[:-1]:
misp_attribute = {'type': 'text', 'value': prop.value, 'comment': prop.name}
self.misp_event.add_attribute(**misp_attribute)
to_return = custom_properties[-1]
return 'text', to_return.value, to_return.name
# Parse the courses of action field of an external STIX document
def parse_coa(self, courses_of_action):
for coa in courses_of_action:
misp_object = MISPObject('course-of-action')
if coa.title:
attribute = {'type': 'text', 'object_relation': 'name',
'value': coa.title}
misp_object.add_attribute(**attribute)
for prop, properties_key in stix2misp_mapping._coa_mapping.items():
if getattr(coa, prop):
attribute = {'type': 'text', 'object_relation': prop.replace('_', ''),
'value': attrgetter('{}.{}'.format(prop, properties_key))(coa)}
misp_object.add_attribute(**attribute)
if coa.parameter_observables:
for observable in coa.parameter_observables.observables:
properties = observable.object_.properties
attribute = MISPAttribute()
attribute.type, attribute.value, _ = self.handle_attribute_type(properties)
referenced_uuid = str(uuid.uuid4())
attribute.uuid = referenced_uuid
self.misp_event.add_attribute(**attribute)
misp_object.add_reference(referenced_uuid, 'observable', None, **attribute)
self.misp_event.add_object(**misp_object)
# Parse description of an external indicator or observable and add it in the MISP event as an attribute
def parse_description(self, stix_object):
if stix_object.description:
misp_attribute = {}
if stix_object.timestamp:
misp_attribute['timestamp'] = self.getTimestampfromDate(stix_object.timestamp)
self.misp_event.add_attribute("text", stix_object.description.value, **misp_attribute)
# Parse indicators of an external STIX document
def parse_external_indicators(self, indicators):
for indicator in indicators:
self.parse_external_single_indicator(indicator)
def parse_external_single_indicator(self, indicator):
if hasattr(indicator, 'observable') and indicator.observable:
observable = indicator.observable
if hasattr(observable, 'object_') and observable.object_:
uuid = self.fetch_uuid(observable.object_.id_)
try:
properties = observable.object_.properties
if properties:
attribute_type, attribute_value, compl_data = self.handle_attribute_type(properties)
if isinstance(attribute_value, (str, int)):
# if the returned value is a simple value, we build an attribute
attribute = {'to_ids': True, 'uuid': uuid}
if indicator.timestamp:
attribute['timestamp'] = self.getTimestampfromDate(indicator.timestamp)
if hasattr(observable, 'handling') and observable.handling:
attribute['Tag'] = []
for handling in observable.handling:
attribute['Tag'].extend(self.parse_marking(handling))
parsed = self.special_parsing(observable.object_, attribute_type, attribute_value, attribute, uuid)
if parsed is not None:
return
self.handle_attribute_case(attribute_type, attribute_value, compl_data, attribute)
else:
# otherwise, it is a dictionary of attributes, so we build an object
self.handle_object_case(attribute_type, attribute_value, compl_data, to_ids=True, object_uuid=uuid)
except AttributeError:
self.parse_description(indicator)
if hasattr(indicator, 'related_indicators') and indicator.related_indicators:
for related_indicator in indicator.related_indicators:
self.parse_external_single_indicator(related_indicator.item)
# Parse observables of an external STIX document
def parse_external_observable(self, observables):
for observable in observables:
title = observable.title
observable_object = observable.object_
try:
properties = observable_object.properties
except AttributeError:
self.parse_description(observable)
continue
if properties:
try:
attribute_type, attribute_value, compl_data = self.handle_attribute_type(properties, title=title)
except KeyError:
# print("Error with an object of type: {}\n{}".format(properties._XSI_TYPE, observable.to_json()))
continue
object_uuid = self.fetch_uuid(observable_object.id_)
if isinstance(attribute_value, (str, int)):
# if the returned value is a simple value, we build an attribute
attribute = {'to_ids': False, 'uuid': object_uuid}
if hasattr(observable, 'handling') and observable.handling:
attribute['Tag'] = []
for handling in observable.handling:
attribute['Tag'].extend(self.parse_marking(handling))
parsed = self.special_parsing(observable_object, attribute_type, attribute_value, attribute, object_uuid)
if parsed is not None:
continue
self.handle_attribute_case(attribute_type, attribute_value, compl_data, attribute)
else:
# otherwise, it is a dictionary of attributes, so we build an object
if attribute_value:
self.handle_object_case(attribute_type, attribute_value, compl_data, object_uuid=object_uuid)
if observable_object.related_objects:
for related_object in observable_object.related_objects:
relationship = related_object.relationship.value.lower().replace('_', '-')
self.references[object_uuid].append({"idref": self.fetch_uuid(related_object.idref),
"relationship": relationship})
# Parse the ttps field of an external STIX document
def parse_ttps(self, ttps):
for ttp in ttps:
if ttp.behavior and ttp.behavior.malware_instances:
mi = ttp.behavior.malware_instances[0]
if mi.types:
mi_type = mi.types[0].value
galaxy = {'type': mi_type}
cluster = defaultdict(dict)
cluster['type'] = mi_type
if mi.description:
cluster['description'] = mi.description.value
cluster['value'] = ttp.title
if mi.names:
synonyms = []
for name in mi.names:
synonyms.append(name.value)
cluster['meta']['synonyms'] = synonyms
galaxy['GalaxyCluster'] = [cluster]
self.misp_event['Galaxy'].append(galaxy)
# Parse a DNS object
def resolve_dns_objects(self):
for domain, domain_dict in self.dns_objects['domain'].items():
ip_reference = domain_dict['related']
domain_attribute = domain_dict['data']
if ip_reference in self.dns_objects['ip']:
misp_object = MISPObject('passive-dns')
domain_attribute['object_relation'] = "rrname"
misp_object.add_attribute(**domain_attribute)
ip = self.dns_objects['ip'][ip_reference]['value']
ip_attribute = {"type": "text", "value": ip, "object_relation": "rdata"}
misp_object.add_attribute(**ip_attribute)
rrtype = "AAAA" if ":" in ip else "A"
rrtype_attribute = {"type": "text", "value": rrtype, "object_relation": "rrtype"}
misp_object.add_attribute(**rrtype_attribute)
self.misp_event.add_object(**misp_object)
else:
self.misp_event.add_attribute(**domain_attribute)
for ip, ip_dict in self.dns_objects['ip'].items():
if ip not in self.dns_ips:
self.misp_event.add_attribute(**ip_dict)
def special_parsing(self, observable_object, attribute_type, attribute_value, attribute, uuid):
if observable_object.related_objects:
related_objects = observable_object.related_objects
if attribute_type == "url" and len(related_objects) == 1 and related_objects[0].relationship.value == "Resolved_To":
related_ip = self.fetch_uuid(related_objects[0].idref)
self.dns_objects['domain'][uuid] = {"related": related_ip,
"data": {"type": "text", "value": attribute_value}}
if related_ip not in self.dns_ips:
self.dns_ips.append(related_ip)
return 1
if attribute_type in ('ip-src', 'ip-dst'):
attribute['type'] = attribute_type
attribute['value'] = attribute_value
self.dns_objects['ip'][uuid] = attribute
return 2
def generate_event(filename):
try:
return STIXPackage.from_xml(filename)
except Exception:
try:
import maec
print(2)
except ImportError:
print(3)
sys.exit(0)
def main(args):
filename = '{}/tmp/{}'.format(os.path.dirname(args[0]), args[1])
event = generate_event(filename)
title = event.stix_header.title
from_misp = (title is not None and "Export from " in title and "MISP" in title)
stix_parser = StixFromMISPParser() if from_misp else ExternalStixParser()
stix_parser.load_event(args[2:], filename, from_misp, event.version)
stix_parser.build_misp_dict(event)
stix_parser.saveFile()
print(1)
if __name__ == "__main__":
main(sys.argv)
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_461_1 |
crossvul-python_data_bad_3682_0 | import os
import Bcfg2.Server.Plugin
def async_run(prog, args):
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
dpid = os.fork()
if not dpid:
os.system(" ".join([prog] + args))
os._exit(0)
class Trigger(Bcfg2.Server.Plugin.Plugin,
Bcfg2.Server.Plugin.Statistics):
"""Trigger is a plugin that calls external scripts (on the server)."""
name = 'Trigger'
__version__ = '$Id'
__author__ = 'bcfg-dev@mcs.anl.gov'
def __init__(self, core, datastore):
Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)
Bcfg2.Server.Plugin.Statistics.__init__(self)
try:
os.stat(self.data)
except:
self.logger.error("Trigger: spool directory %s does not exist; "
"unloading" % self.data)
raise Bcfg2.Server.Plugin.PluginInitError
def process_statistics(self, metadata, _):
args = [metadata.hostname, '-p', metadata.profile, '-g',
':'.join([g for g in metadata.groups])]
for notifier in os.listdir(self.data):
if ((notifier[-1] == '~') or
(notifier[:2] == '.#') or
(notifier[-4:] == '.swp') or
(notifier in ['SCCS', '.svn', '4913'])):
continue
npath = self.data + '/' + notifier
self.logger.debug("Running %s %s" % (npath, " ".join(args)))
async_run(npath, args)
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_3682_0 |
crossvul-python_data_good_3682_0 | import os
import pipes
import Bcfg2.Server.Plugin
from subprocess import Popen, PIPE
class Trigger(Bcfg2.Server.Plugin.Plugin,
Bcfg2.Server.Plugin.Statistics):
"""Trigger is a plugin that calls external scripts (on the server)."""
name = 'Trigger'
__version__ = '$Id'
__author__ = 'bcfg-dev@mcs.anl.gov'
def __init__(self, core, datastore):
Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)
Bcfg2.Server.Plugin.Statistics.__init__(self)
try:
os.stat(self.data)
except:
self.logger.error("Trigger: spool directory %s does not exist; "
"unloading" % self.data)
raise Bcfg2.Server.Plugin.PluginInitError
def async_run(self, args):
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
dpid = os.fork()
if not dpid:
self.debug_log("Running %s" % " ".join(pipes.quote(a)
for a in args))
proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE)
(out, err) = proc.communicate()
rv = proc.wait()
if rv != 0:
self.logger.error("Trigger: Error running %s (%s): %s" %
(args[0], rv, err))
elif err:
self.debug_log("Trigger: Error: %s" % err)
os._exit(0)
def process_statistics(self, metadata, _):
args = [metadata.hostname, '-p', metadata.profile, '-g',
':'.join([g for g in metadata.groups])]
self.debug_log("running triggers")
for notifier in os.listdir(self.data):
self.debug_log("running %s" % notifier)
if ((notifier[-1] == '~') or
(notifier[:2] == '.#') or
(notifier[-4:] == '.swp') or
(notifier in ['SCCS', '.svn', '4913'])):
continue
npath = os.path.join(self.data, notifier)
self.async_run([npath] + args)
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_3682_0 |
crossvul-python_data_good_4204_5 | #!/usr/bin/env python3
"""
This is the main CLI for lookatme
"""
import click
import logging
import io
import os
import pygments.styles
import sys
import tempfile
import lookatme.tui
import lookatme.log
import lookatme.config
from lookatme.pres import Presentation
from lookatme.schemas import StyleSchema
@click.command("lookatme")
@click.option("--debug", "debug", is_flag="True", default=False)
@click.option(
"-l",
"--log",
"log_path",
type=click.Path(writable=True),
default=os.path.join(tempfile.gettempdir(), "lookatme.log"),
)
@click.option(
"-t",
"--theme",
"theme",
type=click.Choice(["dark", "light"]),
default="dark",
)
@click.option(
"-s",
"--style",
"code_style",
default=None,
type=click.Choice(list(pygments.styles.get_all_styles())),
)
@click.option(
"--dump-styles",
help="Dump the resolved styles that will be used with the presentation to stdout",
is_flag=True,
default=False,
)
@click.option(
"--live",
"--live-reload",
"live_reload",
help="Watch the input filename for modifications and automatically reload",
is_flag=True,
default=False,
)
@click.option(
"-s",
"--safe",
help="Do not load any new extensions specified in the source markdown. "
"Extensions specified via env var or -e are still loaded",
is_flag=True,
default=False,
)
@click.option(
"--no-ext-warn",
help="Load new extensions specified in the source markdown without warning",
is_flag=True,
default=False,
)
@click.option(
"-i",
"--ignore-ext-failure",
help="Ignore load failures of extensions",
is_flag=True,
default=False,
)
@click.option(
"-e",
"--exts",
"extensions",
help="A comma-separated list of extension names to automatically load"
" (LOOKATME_EXTS)",
envvar="LOOKATME_EXTS",
default="",
)
@click.option(
"--single",
"--one",
"single_slide",
help="Render the source as a single slide",
is_flag=True,
default=False
)
@click.version_option(lookatme.__version__)
@click.argument(
"input_files",
type=click.File("r"),
nargs=-1,
)
def main(debug, log_path, theme, code_style, dump_styles,
input_files, live_reload, extensions, single_slide, safe, no_ext_warn,
ignore_ext_failure):
"""lookatme - An interactive, terminal-based markdown presentation tool.
See https://lookatme.readthedocs.io/en/v{{VERSION}} for documentation
"""
if debug:
lookatme.config.LOG = lookatme.log.create_log(log_path)
else:
lookatme.config.LOG = lookatme.log.create_null_log()
if len(input_files) == 0:
input_files = [io.StringIO("")]
preload_exts = [x.strip() for x in extensions.split(',')]
preload_exts = list(filter(lambda x: x != '', preload_exts))
pres = Presentation(
input_files[0],
theme,
code_style,
live_reload=live_reload,
single_slide=single_slide,
preload_extensions=preload_exts,
safe=safe,
no_ext_warn=no_ext_warn,
ignore_ext_failure=ignore_ext_failure,
)
if dump_styles:
print(StyleSchema().dumps(pres.styles))
return 0
try:
pres.run()
except Exception as e:
number = pres.tui.curr_slide.number + 1
click.echo(f"Error rendering slide {number}: {e}")
if not debug:
click.echo("Rerun with --debug to view the full traceback in logs")
else:
lookatme.config.LOG.exception(f"Error rendering slide {number}: {e}")
click.echo(f"See {log_path} for traceback")
raise click.Abort()
if __name__ == "__main__":
main()
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_4204_5 |
crossvul-python_data_good_2926_1 | # Back In Time
# Copyright (C) 2008-2017 Oprea Dan, Bart de Koning, Richard Bailey, Germar Reitze
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os
import pluginmanager
import gettext
import subprocess
_=gettext.gettext
class NotifyPlugin( pluginmanager.Plugin ):
def __init__( self ):
self.user = ''
try:
self.user = os.getlogin()
except:
pass
if not self.user:
try:
user = os.environ['USER']
except:
pass
if not self.user:
try:
user = os.environ['LOGNAME']
except:
pass
def init( self, snapshots ):
return True
def is_gui( self ):
return True
def on_process_begins( self ):
pass
def on_process_ends( self ):
pass
def on_error( self, code, message ):
return
def on_new_snapshot( self, snapshot_id, snapshot_path ):
return
def on_message( self, profile_id, profile_name, level, message, timeout ):
if 1 == level:
cmd = ['notify-send']
if timeout > 0:
cmd.extend(['-t', str(1000 * timeout)])
title = "Back In Time (%s) : %s" % (self.user, profile_name)
message = message.replace("\n", ' ')
message = message.replace("\r", '')
cmd.append(title)
cmd.append(message)
subprocess.Popen(cmd).communicate()
return
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_2926_1 |
crossvul-python_data_bad_4204_3 | """
Defines a calendar extension that overrides code block rendering if the
language type is calendar
"""
import datetime
import calendar
import urwid
from lookatme.exceptions import IgnoredByContrib
def render_code(token, body, stack, loop):
lang = token["lang"] or ""
if lang != "calendar":
raise IgnoredByContrib()
today = datetime.datetime.utcnow()
return urwid.Text(calendar.month(today.year, today.month))
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_4204_3 |
crossvul-python_data_good_4204_7 | """
This module handles loading and using lookatme_contriba modules
Contrib modules are directly used
"""
import contextlib
import lookatme.ascii_art
from lookatme.exceptions import IgnoredByContrib
import lookatme.prompt
from . import terminal
from . import file_loader
CONTRIB_MODULES = []
def validate_extension_mod(ext_name, ext_mod):
"""Validate the extension, returns an array of warnings associated with the
module
"""
res = []
if not hasattr(ext_mod, "user_warnings"):
res.append("'user_warnings' is missing. Extension is not able to "
"provide user warnings.")
else:
res += ext_mod.user_warnings()
return res
def load_contribs(contrib_names, safe_contribs, ignore_load_failure=False):
"""Load all contrib modules specified by ``contrib_names``. These should
all be namespaced packages under the ``lookatmecontrib`` namespace. E.g.
``lookatmecontrib.calendar`` would be an extension provided by a
contrib module, and would be added to an ``extensions`` list in a slide's
YAML header as ``calendar``.
``safe_contribs`` is a set of contrib names that are manually provided
by the user by the ``-e`` flag or env variable of extensions to auto-load.
"""
if contrib_names is None:
return
errors = []
all_warnings = []
for contrib_name in contrib_names:
module_name = f"lookatme.contrib.{contrib_name}"
try:
mod = __import__(module_name, fromlist=[contrib_name])
except Exception as e:
if ignore_load_failure:
continue
errors.append(str(e))
else:
if contrib_name not in safe_contribs:
ext_warnings = validate_extension_mod(contrib_name, mod)
if len(ext_warnings) > 0:
all_warnings.append((contrib_name, ext_warnings))
CONTRIB_MODULES.append(mod)
if len(errors) > 0:
raise Exception(
"Error loading one or more extensions:\n\n" + "\n".join(errors),
)
if len(all_warnings) == 0:
return
print("\nExtension-provided user warnings:")
for ext_name, ext_warnings in all_warnings:
print("\n {!r}:\n".format(ext_name))
for ext_warning in ext_warnings:
print(" * {}".format(ext_warning))
print("")
if not lookatme.prompt.yes("Continue anyways?"):
exit(1)
def contrib_first(fn):
"""A decorator that allows contrib modules to override default behavior
of lookatme. E.g., a contrib module may override how a table is displayed
to enable sorting, or enable displaying images rendered with ANSII color
codes and box drawing characters, etc.
Contrib modules may ignore chances to override default behavior by raising
the ``lookatme.contrib.IgnoredByContrib`` exception.
"""
fn_name = fn.__name__
@contextlib.wraps(fn)
def inner(*args, **kwargs):
for mod in CONTRIB_MODULES:
if not hasattr(mod, fn_name):
continue
try:
return getattr(mod, fn_name)(*args, **kwargs)
except IgnoredByContrib:
pass
return fn(*args, **kwargs)
return inner
def shutdown_contribs():
"""Call the shutdown function on all contrib modules
"""
for mod in CONTRIB_MODULES:
getattr(mod, "shutdown", lambda: 1)()
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_4204_7 |
crossvul-python_data_good_4204_8 | """
This module defines a built-in contrib module that enables external files to
be included within the slide. This is extremely useful when having source
code displayed in a code block, and then running/doing something with the
source data in a terminal on the same slide.
"""
from marshmallow import fields, Schema
import os
import subprocess
import yaml
import lookatme.config
from lookatme.exceptions import IgnoredByContrib
def user_warnings():
"""Provide warnings to the user that loading this extension may cause
shell commands specified in the markdown to be run.
"""
return [
"Code-blocks with a language starting with 'file' may cause shell",
" commands from the source markdown to be run if the 'transform'",
" field is set",
"See https://lookatme.readthedocs.io/en/latest/builtin_extensions/file_loader.html",
" for more details",
]
class YamlRender:
loads = lambda data: yaml.safe_load(data)
dumps = lambda data: yaml.safe_dump(data)
class LineRange(Schema):
start = fields.Integer(default=0, missing=0)
end = fields.Integer(default=None, missing=None)
class FileSchema(Schema):
path = fields.Str()
relative = fields.Boolean(default=True, missing=True)
lang = fields.Str(default="auto", missing="auto")
transform = fields.Str(default=None, missing=None)
lines = fields.Nested(
LineRange,
default=LineRange().dump(LineRange()),
missing=LineRange().dump(LineRange()),
)
class Meta:
render_module = YamlRender
def transform_data(transform_shell_cmd, input_data):
"""Transform the ``input_data`` using the ``transform_shell_cmd``
shell command.
"""
proc = subprocess.Popen(
transform_shell_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE,
)
stdout, _ = proc.communicate(input=input_data)
return stdout
def render_code(token, body, stack, loop):
"""Render the code, ignoring all code blocks except ones with the language
set to ``file``.
"""
lang = token["lang"] or ""
if lang != "file":
raise IgnoredByContrib
file_info_data = token["text"]
file_info = FileSchema().loads(file_info_data)
# relative to the slide source
if file_info["relative"]:
base_dir = lookatme.config.SLIDE_SOURCE_DIR
else:
base_dir = os.getcwd()
full_path = os.path.join(base_dir, file_info["path"])
if not os.path.exists(full_path):
token["text"] = "File not found"
token["lang"] = "text"
raise IgnoredByContrib
with open(full_path, "rb") as f:
file_data = f.read()
if file_info["transform"] is not None:
file_data = transform_data(file_info["transform"], file_data)
lines = file_data.split(b"\n")
lines = lines[file_info["lines"]["start"]:file_info["lines"]["end"]]
file_data = b"\n".join(lines)
token["text"] = file_data
token["lang"] = file_info["lang"]
raise IgnoredByContrib
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_4204_8 |
crossvul-python_data_bad_4204_8 | """
This module defines a built-in contrib module that enables external files to
be included within the slide. This is extremely useful when having source
code displayed in a code block, and then running/doing something with the
source data in a terminal on the same slide.
"""
from marshmallow import fields, Schema
import os
import subprocess
import yaml
import lookatme.config
from lookatme.exceptions import IgnoredByContrib
class YamlRender:
loads = lambda data: yaml.safe_load(data)
dumps = lambda data: yaml.safe_dump(data)
class LineRange(Schema):
start = fields.Integer(default=0, missing=0)
end = fields.Integer(default=None, missing=None)
class FileSchema(Schema):
path = fields.Str()
relative = fields.Boolean(default=True, missing=True)
lang = fields.Str(default="auto", missing="auto")
transform = fields.Str(default=None, missing=None)
lines = fields.Nested(
LineRange,
default=LineRange().dump(LineRange()),
missing=LineRange().dump(LineRange()),
)
class Meta:
render_module = YamlRender
def transform_data(transform_shell_cmd, input_data):
"""Transform the ``input_data`` using the ``transform_shell_cmd``
shell command.
"""
proc = subprocess.Popen(
transform_shell_cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
stdin=subprocess.PIPE,
)
stdout, _ = proc.communicate(input=input_data)
return stdout
def render_code(token, body, stack, loop):
"""Render the code, ignoring all code blocks except ones with the language
set to ``file``.
"""
lang = token["lang"] or ""
if lang != "file":
raise IgnoredByContrib
file_info_data = token["text"]
file_info = FileSchema().loads(file_info_data)
# relative to the slide source
if file_info["relative"]:
base_dir = lookatme.config.SLIDE_SOURCE_DIR
else:
base_dir = os.getcwd()
full_path = os.path.join(base_dir, file_info["path"])
if not os.path.exists(full_path):
token["text"] = "File not found"
token["lang"] = "text"
raise IgnoredByContrib
with open(full_path, "rb") as f:
file_data = f.read()
if file_info["transform"] is not None:
file_data = transform_data(file_info["transform"], file_data)
lines = file_data.split(b"\n")
lines = lines[file_info["lines"]["start"]:file_info["lines"]["end"]]
file_data = b"\n".join(lines)
token["text"] = file_data
token["lang"] = file_info["lang"]
raise IgnoredByContrib
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_4204_8 |
crossvul-python_data_bad_461_1 | # -*- coding: utf-8 -*-
# Copyright (C) 2017-2018 CIRCL Computer Incident Response Center Luxembourg (smile gie)
# Copyright (C) 2017-2018 Christian Studer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import json
import os
import time
import uuid
import base64
import stix2misp_mapping
import stix.extensions.marking.ais
from operator import attrgetter
from pymisp import MISPEvent, MISPObject, MISPAttribute, __path__
from stix.core import STIXPackage
from collections import defaultdict
cybox_to_misp_object = {"Account": "credential", "AutonomousSystem": "asn",
"EmailMessage": "email", "NetworkConnection": "network-connection",
"NetworkSocket": "network-socket", "Process": "process",
"x509Certificate": "x509", "Whois": "whois"}
threat_level_mapping = {'High': '1', 'Medium': '2', 'Low': '3', 'Undefined': '4'}
descFilename = os.path.join(__path__[0], 'data/describeTypes.json')
with open(descFilename, 'r') as f:
categories = json.loads(f.read())['result'].get('categories')
class StixParser():
def __init__(self):
super(StixParser, self).__init__()
self.misp_event = MISPEvent()
self.misp_event['Galaxy'] = []
self.references = defaultdict(list)
################################################################################
## LOADING & UTILITY FUNCTIONS USED BY BOTH SUBCLASSES. ##
################################################################################
# Load data from STIX document, and other usefull data
def load_event(self, args, filename, from_misp, stix_version):
self.outputname = '{}.json'.format(filename)
if len(args) > 0 and args[0]:
self.add_original_file(filename, args[0], stix_version)
try:
event_distribution = args[1]
if not isinstance(event_distribution, int):
event_distribution = int(event_distribution) if event_distribution.isdigit() else 5
except IndexError:
event_distribution = 5
try:
attribute_distribution = args[2]
if attribute_distribution == 'event':
attribute_distribution = event_distribution
elif not isinstance(attribute_distribution, int):
attribute_distribution = int(attribute_distribution) if attribute_distribution.isdigit() else event_distribution
except IndexError:
attribute_distribution = event_distribution
self.misp_event.distribution = event_distribution
self.__attribute_distribution = attribute_distribution
self.from_misp = from_misp
self.load_mapping()
# Convert the MISP event we create from the STIX document into json format
# and write it in the output file
def saveFile(self):
eventDict = self.misp_event.to_json()
with open(self.outputname, 'wt', encoding='utf-8') as f:
f.write(eventDict)
def add_original_file(self, filename, original_filename, version):
with open(filename, 'rb') as f:
sample = base64.b64encode(f.read()).decode('utf-8')
original_file = MISPObject('original-imported-file')
original_file.add_attribute(**{'type': 'attachment', 'value': original_filename,
'object_relation': 'imported-sample', 'data': sample})
original_file.add_attribute(**{'type': 'text', 'object_relation': 'format',
'value': 'STIX {}'.format(version)})
self.misp_event.add_object(**original_file)
# Load the mapping dictionary for STIX object types
def load_mapping(self):
self.attribute_types_mapping = {
"AccountObjectType": self.handle_credential,
'AddressObjectType': self.handle_address,
"ArtifactObjectType": self.handle_attachment,
"ASObjectType": self.handle_as,
"CustomObjectType": self.handle_custom,
"DNSRecordObjectType": self.handle_dns,
'DomainNameObjectType': self.handle_domain_or_url,
'EmailMessageObjectType': self.handle_email_attribute,
'FileObjectType': self.handle_file,
'HostnameObjectType': self.handle_hostname,
'HTTPSessionObjectType': self.handle_http,
'MutexObjectType': self.handle_mutex,
'NetworkConnectionObjectType': self.handle_network_connection,
'NetworkSocketObjectType': self.handle_network_socket,
'PDFFileObjectType': self.handle_file,
'PortObjectType': self.handle_port,
'ProcessObjectType': self.handle_process,
'SocketAddressObjectType': self.handle_socket_address,
'SystemObjectType': self.handle_system,
'URIObjectType': self.handle_domain_or_url,
"WhoisObjectType": self.handle_whois,
"WindowsFileObjectType": self.handle_file,
'WindowsRegistryKeyObjectType': self.handle_regkey,
"WindowsExecutableFileObjectType": self.handle_pe,
"WindowsServiceObjectType": self.handle_windows_service,
"X509CertificateObjectType": self.handle_x509
}
self.marking_mapping = {
'AIS:AISMarkingStructure': self.parse_AIS_marking,
'tlpMarking:TLPMarkingStructureType': self.parse_TLP_marking
}
def parse_marking(self, handling):
tags = []
if hasattr(handling, 'marking_structures') and handling.marking_structures:
for marking in handling.marking_structures:
try:
tags.extend(self.marking_mapping[marking._XSI_TYPE](marking))
except KeyError:
print(marking._XSI_TYPE, file=sys.stderr)
continue
return tags
def set_distribution(self):
for attribute in self.misp_event.attributes:
attribute.distribution = self.__attribute_distribution
for misp_object in self.misp_event.objects:
misp_object.distribution = self.__attribute_distribution
for attribute in misp_object.attributes:
attribute.distribution = self.__attribute_distribution
# Make references between objects
def build_references(self):
for misp_object in self.misp_event.objects:
object_uuid = misp_object.uuid
if object_uuid in self.references:
for reference in self.references[object_uuid]:
misp_object.add_reference(reference['idref'], reference['relationship'])
# Set info & title values in the new MISP event
def get_event_info(self):
info = "Imported from external STIX event"
try:
try:
title = self.event.stix_header.title
except AttributeError:
title = self.event.title
if title:
info = title
except AttributeError:
pass
return info
# Get timestamp & date values in the new MISP event
def get_timestamp_and_date(self):
stix_date = self.event.timestamp
try:
date = stix_date.split("T")[0]
except AttributeError:
date = stix_date
return date, self.getTimestampfromDate(stix_date)
# Translate date into timestamp
@staticmethod
def getTimestampfromDate(date):
try:
try:
dt = date.split('+')[0]
d = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
except ValueError:
dt = date.split('.')[0]
d = int(time.mktime(time.strptime(dt, "%Y-%m-%d %H:%M:%S")))
except AttributeError:
d = int(time.mktime(date.timetuple()))
return d
################################################################################
## STIX OBJECTS PARSING FUNCTIONS USED BY BOTH SUBCLASSES ##
################################################################################
# Define type & value of an attribute or object in MISP
def handle_attribute_type(self, properties, is_object=False, title=None, observable_id=None):
xsi_type = properties._XSI_TYPE
# try:
args = [properties]
if xsi_type in ("FileObjectType", "PDFFileObjectType", "WindowsFileObjectType"):
args.append(is_object)
elif xsi_type == "ArtifactObjectType":
args.append(title)
return self.attribute_types_mapping[xsi_type](*args)
# except AttributeError:
# # ATM USED TO TEST TYPES
# print("Unparsed type: {}".format(xsi_type))
# sys.exit(1)
# Return type & value of an ip address attribute
@staticmethod
def handle_address(properties):
if properties.is_source:
ip_type = "ip-src"
else:
ip_type = "ip-dst"
return ip_type, properties.address_value.value, "ip"
def handle_as(self, properties):
attributes = self.fetch_attributes_with_partial_key_parsing(properties, stix2misp_mapping._as_mapping)
return attributes[0] if len(attributes) == 1 else ('asn', self.return_attributes(attributes), '')
# Return type & value of an attachment attribute
@staticmethod
def handle_attachment(properties, title):
if properties.hashes:
return "malware-sample", "{}|{}".format(title, properties.hashes[0], properties.raw_artifact.value)
return stix2misp_mapping.eventTypes[properties._XSI_TYPE]['type'], title, properties.raw_artifact.value
# Return type & attributes of a credential object
def handle_credential(self, properties):
attributes = []
if properties.description:
attributes.append(["text", properties.description.value, "text"])
if properties.authentication:
for authentication in properties.authentication:
attributes += self.fetch_attributes_with_key_parsing(authentication, stix2misp_mapping._credential_authentication_mapping)
if properties.custom_properties:
for prop in properties.custom_properties:
if prop.name in stix2misp_mapping._credential_custom_types:
attributes.append(['text', prop.value, prop.name])
return attributes[0] if len(attributes) == 1 else ("credential", self.return_attributes(attributes), "")
# Return type & attributes of a dns object
def handle_dns(self, properties):
relation = []
if properties.domain_name:
relation.append(["domain", str(properties.domain_name.value), ""])
if properties.ip_address:
relation.append(["ip-dst", str(properties.ip_address.value), ""])
if relation:
if len(relation) == '2':
domain = relation[0][1]
ip = relattion[1][1]
attributes = [["text", domain, "rrname"], ["text", ip, "rdata"]]
rrtype = "AAAA" if ":" in ip else "A"
attributes.append(["text", rrtype, "rrtype"])
return "passive-dns", self.return_attributes(attributes), ""
return relation[0]
# Return type & value of a domain or url attribute
@staticmethod
def handle_domain_or_url(properties):
event_types = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
return event_types['type'], properties.value.value, event_types['relation']
# Return type & value of an email attribute
def handle_email_attribute(self, properties):
if properties.header:
header = properties.header
attributes = self.fetch_attributes_with_key_parsing(header, stix2misp_mapping._email_mapping)
if header.to:
for to in header.to:
attributes.append(["email-dst", to.address_value.value, "to"])
if header.cc:
for cc in header.cc:
attributes.append(["email-dst", cc.address_value.value, "cc"])
else:
attributes = []
if properties.attachments:
attributes.append(self.handle_email_attachment(properties.parent))
return attributes[0] if len(attributes) == 1 else ("email", self.return_attributes(attributes), "")
# Return type & value of an email attachment
@staticmethod
def handle_email_attachment(indicator_object):
properties = indicator_object.related_objects[0].properties
return ["email-attachment", properties.file_name.value, "attachment"]
# Return type & attributes of a file object
def handle_file(self, properties, is_object):
b_hash, b_file = False, False
attributes = []
if properties.hashes:
b_hash = True
for h in properties.hashes:
attributes.append(self.handle_hashes_attribute(h))
if properties.file_name:
value = properties.file_name.value
if value:
b_file = True
attribute_type, relation = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
attributes.append([attribute_type, value, relation])
attributes.extend(self.fetch_attributes_with_keys(properties, stix2misp_mapping._file_mapping))
if len(attributes) == 1:
attribute = attributes[0]
return attribute[0] if attribute[2] != "fullpath" else "filename", attribute[1], ""
if len(attributes) == 2:
if b_hash and b_file:
return self.handle_filename_object(attributes, is_object)
path, filename = self.handle_filename_path_case(attributes)
if path and filename:
attribute_value = "{}\\{}".format(path, filename)
if '\\' in filename and path == filename:
attribute_value = filename
return "filename", attribute_value, ""
return "file", self.return_attributes(attributes), ""
# Determine path & filename from a complete path or filename attribute
@staticmethod
def handle_filename_path_case(attributes):
path, filename = [""] * 2
if attributes[0][2] == 'filename' and attributes[1][2] == 'path':
path = attributes[1][1]
filename = attributes[0][1]
elif attributes[0][2] == 'path' and attributes[1][2] == 'filename':
path = attributes[0][1]
filename = attributes[1][1]
return path, filename
# Return the appropriate type & value when we have 1 filename & 1 hash value
@staticmethod
def handle_filename_object(attributes, is_object):
for attribute in attributes:
attribute_type, attribute_value, _ = attribute
if attribute_type == "filename":
filename_value = attribute_value
else:
hash_type, hash_value = attribute_type, attribute_value
value = "{}|{}".format(filename_value, hash_value)
if is_object:
# file object attributes cannot be filename|hash, so it is malware-sample
attr_type = "malware-sample"
return attr_type, value, attr_type
# it could be malware-sample as well, but STIX is losing this information
return "filename|{}".format(hash_type), value, ""
# Return type & value of a hash attribute
@staticmethod
def handle_hashes_attribute(properties):
hash_type = properties.type_.value.lower()
try:
hash_value = properties.simple_hash_value.value
except AttributeError:
hash_value = properties.fuzzy_hash_value.value
return hash_type, hash_value, hash_type
# Return type & value of a hostname attribute
@staticmethod
def handle_hostname(properties):
event_types = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
return event_types['type'], properties.hostname_value.value, event_types['relation']
# Return type & value of a http request attribute
@staticmethod
def handle_http(properties):
client_request = properties.http_request_response[0].http_client_request
if client_request.http_request_header:
request_header = client_request.http_request_header
if request_header.parsed_header:
value = request_header.parsed_header.user_agent.value
return "user-agent", value, "user-agent"
elif request_header.raw_header:
value = request_header.raw_header.value
return "http-method", value, "method"
elif client_request.http_request_line:
value = client_request.http_request_line.http_method.value
return "http-method", value, "method"
# Return type & value of a mutex attribute
@staticmethod
def handle_mutex(properties):
event_types = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
return event_types['type'], properties.name.value, event_types['relation']
# Return type & attributes of a network connection object
def handle_network_connection(self, properties):
attributes = self.fetch_attributes_from_sockets(properties, stix2misp_mapping._network_connection_addresses)
for prop in ('layer3_protocol', 'layer4_protocol', 'layer7_protocol'):
if getattr(properties, prop):
attributes.append(['text', attrgetter("{}.value".format(prop))(properties), prop.replace('_', '-')])
if attributes:
return "network-connection", self.return_attributes(attributes), ""
# Return type & attributes of a network socket objet
def handle_network_socket(self, properties):
attributes = self.fetch_attributes_from_sockets(properties, stix2misp_mapping._network_socket_addresses)
attributes.extend(self.fetch_attributes_with_keys(properties, stix2misp_mapping._network_socket_mapping))
for prop in ('is_listening', 'is_blocking'):
if getattr(properties, prop):
attributes.append(["text", prop.split('_')[1], "state"])
if attributes:
return "network-socket", self.return_attributes(attributes), ""
# Return type & value of a port attribute
@staticmethod
def handle_port(*kwargs):
properties = kwargs[0]
event_types = stix2misp_mapping.eventTypes[properties._XSI_TYPE]
relation = event_types['relation']
if len(kwargs) > 1:
observable_id = kwargs[1]
if "srcPort" in observable_id:
relation = "src-{}".format(relation)
elif "dstPort" in observable_id:
relation = "dst-{}".format(relation)
return event_types['type'], properties.port_value.value, relation
# Return type & attributes of a process object
def handle_process(self, properties):
attributes = self.fetch_attributes_with_partial_key_parsing(properties, stix2misp_mapping._process_mapping)
if properties.child_pid_list:
for child in properties.child_pid_list:
attributes.append(["text", child.value, "child-pid"])
# if properties.port_list:
# for port in properties.port_list:
# attributes.append(["src-port", port.port_value.value, "port"])
if properties.network_connection_list:
references = []
for connection in properties.network_connection_list:
object_name, object_attributes, _ = self.handle_network_connection(connection)
object_uuid = str(uuid.uuid4())
misp_object = MISPObject(object_name)
misp_object.uuid = object_uuid
for attribute in object_attributes:
misp_object.add_attribute(**attribute)
references.append(object_uuid)
return "process", self.return_attributes(attributes), {"process_uuid": references}
return "process", self.return_attributes(attributes), ""
# Return type & value of a regkey attribute
def handle_regkey(self, properties):
attributes = self.fetch_attributes_with_partial_key_parsing(properties, stix2misp_mapping._regkey_mapping)
if properties.values:
values = properties.values
value = values[0]
attributes += self.fetch_attributes_with_partial_key_parsing(value, stix2misp_mapping._regkey_value_mapping)
if len(attributes) in (2,3):
d_regkey = {key: value for (_, value, key) in attributes}
if 'hive' in d_regkey and 'key' in d_regkey:
regkey = "{}\\{}".format(d_regkey['hive'], d_regkey['key'])
if 'data' in d_regkey:
return "regkey|value", "{} | {}".format(regkey, d_regkey['data']), ""
return "regkey", regkey, ""
return "registry-key", self.return_attributes(attributes), ""
@staticmethod
def handle_socket(attributes, socket, s_type):
for prop, mapping in stix2misp_mapping._socket_mapping.items():
if getattr(socket, prop):
attribute_type, properties_key, relation = mapping
attribute_type, relation = [elem.format(s_type) for elem in (attribute_type, relation)]
attributes.append([attribute_type, attrgetter('{}.{}.value'.format(prop, properties_key))(socket), relation])
# Parse a socket address object in order to return type & value
# of a composite attribute ip|port or hostname|port
def handle_socket_address(self, properties):
if properties.ip_address:
type1, value1, _ = self.handle_address(properties.ip_address)
elif properties.hostname:
type1 = "hostname"
value1 = properties.hostname.hostname_value.value
return "{}|port".format(type1), "{}|{}".format(value1, properties.port.port_value.value), ""
# Parse a system object to extract a mac-address attribute
@staticmethod
def handle_system(properties):
if properties.network_interface_list:
return "mac-address", str(properties.network_interface_list[0].mac), ""
# Parse a whois object:
# Return type & attributes of a whois object if we have the required fields
# Otherwise create attributes and return type & value of the last attribute to avoid crashing the parent function
def handle_whois(self, properties):
attributes = self.fetch_attributes_with_key_parsing(properties, stix2misp_mapping._whois_mapping)
required_one_of = True if attributes else False
if properties.registrants:
registrant = properties.registrants[0]
attributes += self.fetch_attributes_with_key_parsing(registrant, stix2misp_mapping._whois_registrant_mapping)
if properties.creation_date:
attributes.append(["datetime", properties.creation_date.value.strftime('%Y-%m-%d'), "creation-date"])
required_one_of = True
if properties.updated_date:
attributes.append(["datetime", properties.updated_date.value.strftime('%Y-%m-%d'), "modification-date"])
if properties.expiration_date:
attributes.append(["datetime", properties.expiration_date.value.strftime('%Y-%m-%d'), "expiration-date"])
if properties.nameservers:
for nameserver in properties.nameservers:
attributes.append(["hostname", nameserver.value.value, "nameserver"])
if properties.remarks:
attribute_type = "text"
relation = "comment" if attributes else attribute_type
attributes.append([attribute_type, properties.remarks.value, relation])
required_one_of = True
# Testing if we have the required attribute types for Object whois
if required_one_of:
# if yes, we return the object type and the attributes
return "whois", self.return_attributes(attributes), ""
# otherwise, attributes are added in the event, and one attribute is returned to not make the function crash
if len(attributes) == 1:
return attributes[0]
last_attribute = attributes.pop(-1)
for attribute in attributes:
attribute_type, attribute_value, attribute_relation = attribute
misp_attributes = {"comment": "Whois {}".format(attribute_relation)}
self.misp_event.add_attribute(attribute_type, attribute_value, **misp_attributes)
return last_attribute
# Return type & value of a windows service object
@staticmethod
def handle_windows_service(properties):
if properties.name:
return "windows-service-name", properties.name.value, ""
def handle_x509(self, properties):
attributes = self.handle_x509_certificate(properties.certificate) if properties.certificate else []
if properties.raw_certificate:
raw = properties.raw_certificate.value
try:
relation = "raw-base64" if raw == base64.b64encode(base64.b64decode(raw)).strip() else "pem"
except Exception:
relation = "pem"
attributes.append(["text", raw, relation])
if properties.certificate_signature:
signature = properties.certificate_signature
attribute_type = "x509-fingerprint-{}".format(signature.signature_algorithm.value.lower())
attributes.append([attribute_type, signature.signature.value, attribute_type])
return "x509", self.return_attributes(attributes), ""
@staticmethod
def handle_x509_certificate(certificate):
attributes = []
if certificate.validity:
validity = certificate.validity
for prop in stix2misp_mapping._x509_datetime_types:
if getattr(validity, prop):
attributes.append(['datetime', attrgetter('{}.value'.format(prop))(validity), 'validity-{}'.format(prop.replace('_', '-'))])
if certificate.subject_public_key:
subject_pubkey = certificate.subject_public_key
if subject_pubkey.rsa_public_key:
rsa_pubkey = subject_pubkey.rsa_public_key
for prop in stix2misp_mapping._x509__x509_pubkey_types:
if getattr(rsa_pubkey, prop):
attributes.append(['text', attrgetter('{}.value'.format(prop))(rsa_pubkey), 'pubkey-info-{}'.format(prop)])
if subject_pubkey.public_key_algorithm:
attributes.append(["text", subject_pubkey.public_key_algorithm.value, "pubkey-info-algorithm"])
for prop in stix2misp_mapping._x509_certificate_types:
if getattr(certificate, prop):
attributes.append(['text', attrgetter('{}.value'.format(prop))(certificate), prop.replace('_', '-')])
return attributes
# Return type & attributes of the file defining a portable executable object
def handle_pe(self, properties):
pe_uuid = self.parse_pe(properties)
file_type, file_value, _ = self.handle_file(properties, False)
return file_type, file_value, pe_uuid
# Parse attributes of a portable executable, create the corresponding object,
# and return its uuid to build the reference for the file object generated at the same time
def parse_pe(self, properties):
misp_object = MISPObject('pe')
filename = properties.file_name.value
for attr in ('internal-filename', 'original-filename'):
misp_object.add_attribute(**dict(zip(('type', 'value', 'object_relation'),('filename', filename, attr))))
if properties.headers:
headers = properties.headers
header_object = MISPObject('pe-section')
if headers.entropy:
header_object.add_attribute(**{"type": "float", "object_relation": "entropy",
"value": headers.entropy.value.value})
file_header = headers.file_header
misp_object.add_attribute(**{"type": "counter", "object_relation": "number-sections",
"value": file_header.number_of_sections.value})
for h in file_header.hashes:
hash_type, hash_value, hash_relation = self.handle_hashes_attribute(h)
header_object.add_attribute(**{"type": hash_type, "value": hash_value, "object_relation": hash_relation})
if file_header.size_of_optional_header:
header_object.add_attribute(**{"type": "size-in-bytes", "object_relation": "size-in-bytes",
"value": file_header.size_of_optional_header.value})
self.misp_event.add_object(**header_object)
misp_object.add_reference(header_object.uuid, 'header-of')
if properties.sections:
for section in properties.sections:
section_uuid = self.parse_pe_section(section)
misp_object.add_reference(section_uuid, 'included-in')
self.misp_event.add_object(**misp_object)
return {"pe_uuid": misp_object.uuid}
# Parse attributes of a portable executable section, create the corresponding object,
# and return its uuid to build the reference for the pe object generated at the same time
def parse_pe_section(self, section):
section_object = MISPObject('pe-section')
header_hashes = section.header_hashes
for h in header_hashes:
hash_type, hash_value, hash_relation = self.handle_hashes_attribute(h)
section_object.add_attribute(**{"type": hash_type, "value": hash_value, "object_relation": hash_relation})
if section.entropy:
section_object.add_attribute(**{"type": "float", "object_relation": "entropy",
"value": section.entropy.value.value})
if section.section_header:
section_header = section.section_header
section_object.add_attribute(**{"type": "text", "object_relation": "name",
"value": section_header.name.value})
section_object.add_attribute(**{"type": "size-in-bytes", "object_relation": "size-in-bytes",
"value": section_header.size_of_raw_data.value})
self.misp_event.add_object(**section_object)
return section_object.uuid
################################################################################
## MARKINGS PARSING FUNCTIONS USED BY BOTH SUBCLASSES ##
################################################################################
def parse_AIS_marking(self, marking):
tags = []
if hasattr(marking, 'is_proprietary') and marking.is_proprietary:
proprietary = "Is"
marking = marking.is_proprietary
elif hasattr(marking, 'not_proprietary') and marking.not_proprietary:
proprietary = "Not"
marking = marking.not_proprietary
else:
return
mapping = stix2misp_mapping._AIS_marking_mapping
prefix = mapping['prefix']
tags.append('{}{}'.format(prefix, mapping['proprietary'].format(proprietary)))
if hasattr(marking, 'cisa_proprietary'):
try:
cisa_proprietary = marking.cisa_proprietary.numerator
cisa_proprietary = 'true' if cisa_proprietary == 1 else 'false'
tags.append('{}{}'.format(prefix, mapping['cisa_proprietary'].format(cisa_proprietary)))
except AttributeError:
pass
for ais_field in ('ais_consent', 'tlp_marking'):
if hasattr(marking, ais_field) and getattr(marking, ais_field):
key, tag = mapping[ais_field]
tags.append('{}{}'.format(prefix, tag.format(getattr(getattr(marking, ais_field), key))))
return tags
def parse_TLP_marking(self, marking):
return ['tlp:{}'.format(marking.color.lower())]
################################################################################
## FUNCTIONS HANDLING PARSED DATA, USED BY BOTH SUBCLASSES. ##
################################################################################
# The value returned by the indicators or observables parser is of type str or int
# Thus we can add an attribute in the MISP event with the type & value
def handle_attribute_case(self, attribute_type, attribute_value, data, attribute):
if attribute_type == 'attachment':
attribute['data'] = data
elif attribute_type == 'text':
attribute['comment'] = data
self.misp_event.add_attribute(attribute_type, attribute_value, **attribute)
# The value returned by the indicators or observables parser is a list of dictionaries
# These dictionaries are the attributes we add in an object, itself added in the MISP event
def handle_object_case(self, attribute_type, attribute_value, compl_data, to_ids=False, object_uuid=None):
misp_object = MISPObject(attribute_type)
if object_uuid:
misp_object.uuid = object_uuid
for attribute in attribute_value:
attribute['to_ids'] = to_ids
misp_object.add_attribute(**attribute)
if isinstance(compl_data, dict):
# if some complementary data is a dictionary containing an uuid,
# it means we are using it to add an object reference
if "pe_uuid" in compl_data:
misp_object.add_reference(compl_data['pe_uuid'], 'included-in')
if "process_uuid" in compl_data:
for uuid in compl_data["process_uuid"]:
misp_object.add_reference(uuid, 'connected-to')
self.misp_event.add_object(**misp_object)
################################################################################
## UTILITY FUNCTIONS USED BY PARSING FUNCTION ABOVE ##
################################################################################
def fetch_attributes_from_sockets(self, properties, mapping_dict):
attributes = []
for prop, s_type in zip(mapping_dict, stix2misp_mapping._s_types):
address_property = getattr(properties, prop)
if address_property:
self.handle_socket(attributes, address_property, s_type)
return attributes
@staticmethod
def fetch_attributes_with_keys(properties, mapping_dict):
attributes = []
for prop, mapping in mapping_dict.items():
if getattr(properties,prop):
attribute_type, properties_key, relation = mapping
attributes.append([attribute_type, attrgetter(properties_key)(properties), relation])
return attributes
@staticmethod
def fetch_attributes_with_key_parsing(properties, mapping_dict):
attributes = []
for prop, mapping in mapping_dict.items():
if getattr(properties, prop):
attribute_type, properties_key, relation = mapping
attributes.append([attribute_type, attrgetter('{}.{}'.format(prop, properties_key))(properties), relation])
return attributes
@staticmethod
def fetch_attributes_with_partial_key_parsing(properties, mapping_dict):
attributes = []
for prop, mapping in mapping_dict.items():
if getattr(properties, prop):
attribute_type, relation = mapping
attributes.append([attribute_type, attrgetter('{}.value'.format(prop))(properties), relation])
return attributes
# Extract the uuid from a stix id
@staticmethod
def fetch_uuid(object_id):
try:
return "-".join(object_id.split("-")[-5:])
except Exception:
return str(uuid.uuid4())
# Return the attributes that will be added in a MISP object as a list of dictionaries
@staticmethod
def return_attributes(attributes):
return_attributes = []
for attribute in attributes:
return_attributes.append(dict(zip(('type', 'value', 'object_relation'), attribute)))
return return_attributes
class StixFromMISPParser(StixParser):
def __init__(self):
super(StixFromMISPParser, self).__init__()
self.dates = []
self.timestamps = []
self.titles = []
def build_misp_dict(self, event):
for item in event.related_packages.related_package:
package = item.item
self.event = package.incidents[0]
self.set_timestamp_and_date()
self.set_event_info()
if self.event.related_indicators:
for indicator in self.event.related_indicators.indicator:
self.parse_misp_indicator(indicator)
if self.event.related_observables:
for observable in self.event.related_observables.observable:
self.parse_misp_observable(observable)
if self.event.history:
self.parse_journal_entries()
if self.event.information_source and self.event.information_source.references:
for reference in self.event.information_source.references:
self.misp_event.add_attribute(**{'type': 'link', 'value': reference})
if package.ttps:
for ttp in package.ttps.ttps:
if ttp.exploit_targets:
self.parse_vulnerability(ttp.exploit_targets.exploit_target)
# if ttp.handling:
# self.parse_tlp_marking(ttp.handling)
self.set_distribution()
# Return type & attributes (or value) of a Custom Object
def handle_custom(self, properties):
custom_properties = properties.custom_properties
attributes = []
for prop in custom_properties:
attribute_type, relation = prop.name.split(': ')
attribute_type = attribute_type.split(' ')[1]
attributes.append([attribute_type, prop.value, relation])
if len(attributes) > 1:
name = custom_properties[0].name.split(' ')[0]
return name, self.return_attributes(attributes), ""
return attributes[0]
def parse_journal_entries(self):
for entry in self.event.history.history_items:
journal_entry = entry.journal_entry.value
try:
entry_type, entry_value = journal_entry.split(': ')
if entry_type == "MISP Tag":
self.parse_tag(entry_value)
elif entry_type.startswith('attribute['):
_, category, attribute_type = entry_type.split('[')
self.misp_event.add_attribute(**{'type': attribute_type[:-1], 'category': category[:-1], 'value': entry_value})
elif entry_type == "Event Threat Level":
self.misp_event.threat_level_id = threat_level_mapping[entry_value]
except ValueError:
continue
# Parse indicators of a STIX document coming from our exporter
def parse_misp_indicator(self, indicator):
# define is an indicator will be imported as attribute or object
if indicator.relationship in categories:
self.parse_misp_attribute_indicator(indicator)
else:
self.parse_misp_object_indicator(indicator)
def parse_misp_observable(self, observable):
if observable.relationship in categories:
self.parse_misp_attribute_observable(observable)
else:
self.parse_misp_object_observable(observable)
# Parse STIX objects that we know will give MISP attributes
def parse_misp_attribute_indicator(self, indicator):
misp_attribute = {'to_ids': True, 'category': str(indicator.relationship),
'uuid': self.fetch_uuid(indicator.id_)}
item = indicator.item
misp_attribute['timestamp'] = self.getTimestampfromDate(item.timestamp)
if item.observable:
observable = item.observable
self.parse_misp_attribute(observable, misp_attribute, to_ids=True)
def parse_misp_attribute_observable(self, observable):
misp_attribute = {'to_ids': False, 'category': str(observable.relationship),
'uuid': self.fetch_uuid(observable.id_)}
if observable.item:
self.parse_misp_attribute(observable.item, misp_attribute)
def parse_misp_attribute(self, observable, misp_attribute, to_ids=False):
try:
properties = observable.object_.properties
if properties:
attribute_type, attribute_value, compl_data = self.handle_attribute_type(properties)
if isinstance(attribute_value, (str, int)):
self.handle_attribute_case(attribute_type, attribute_value, compl_data, misp_attribute)
else:
self.handle_object_case(attribute_type, attribute_value, compl_data, to_ids=to_ids)
except AttributeError:
attribute_dict = {}
for observables in observable.observable_composition.observables:
properties = observables.object_.properties
attribute_type, attribute_value, _ = self.handle_attribute_type(properties, observable_id=observable.id_)
attribute_dict[attribute_type] = attribute_value
attribute_type, attribute_value = self.composite_type(attribute_dict)
self.misp_event.add_attribute(attribute_type, attribute_value, **misp_attribute)
# Return type & value of a composite attribute in MISP
@staticmethod
def composite_type(attributes):
if "port" in attributes:
if "ip-src" in attributes:
return "ip-src|port", "{}|{}".format(attributes["ip-src"], attributes["port"])
elif "ip-dst" in attributes:
return "ip-dst|port", "{}|{}".format(attributes["ip-dst"], attributes["port"])
elif "hostname" in attributes:
return "hostname|port", "{}|{}".format(attributes["hostname"], attributes["port"])
elif "domain" in attributes:
if "ip-src" in attributes:
ip_value = attributes["ip-src"]
elif "ip-dst" in attributes:
ip_value = attributes["ip-dst"]
return "domain|ip", "{}|{}".format(attributes["domain"], ip_value)
# Parse STIX object that we know will give MISP objects
def parse_misp_object_indicator(self, indicator):
object_type = str(indicator.relationship)
item = indicator.item
name = item.title.split(' ')[0]
if name not in ('passive-dns'):
self.fill_misp_object(item, name, to_ids=True)
else:
if object_type != "misc":
print("Unparsed Object type: {}".format(name), file=sys.stderr)
def parse_misp_object_observable(self, observable):
object_type = str(observable.relationship)
observable = observable.item
observable_id = observable.id_
if object_type == "file":
name = "registry-key" if "WinRegistryKey" in observable_id else "file"
elif object_type == "network":
if "Custom" in observable_id:
name = observable_id.split("Custom")[0].split(":")[1]
elif "ObservableComposition" in observable_id:
name = observable_id.split("_")[0].split(":")[1]
else:
name = cybox_to_misp_object[observable_id.split('-')[0].split(':')[1]]
else:
name = cybox_to_misp_object[observable_id.split('-')[0].split(':')[1]]
try:
self.fill_misp_object(observable, name)
except Exception:
print("Unparsed Object type: {}".format(observable.to_json()), file=sys.stderr)
# Create a MISP object, its attributes, and add it in the MISP event
def fill_misp_object(self, item, name, to_ids=False):
uuid = self.fetch_uuid(item.id_)
try:
misp_object = MISPObject(name)
misp_object.uuid = uuid
if to_ids:
observables = item.observable.observable_composition.observables
misp_object.timestamp = self.getTimestampfromDate(item.timestamp)
else:
observables = item.observable_composition.observables
for observable in observables:
properties = observable.object_.properties
misp_attribute = MISPAttribute()
misp_attribute.type, misp_attribute.value, misp_attribute.object_relation = self.handle_attribute_type(properties, is_object=True, observable_id=observable.id_)
misp_attribute.to_ids = to_ids
misp_object.add_attribute(**misp_attribute)
self.misp_event.add_object(**misp_object)
except AttributeError:
properties = item.observable.object_.properties if to_ids else item.object_.properties
self.parse_observable(properties, to_ids, uuid)
# Create a MISP attribute and add it in its MISP object
def parse_observable(self, properties, to_ids, uuid):
attribute_type, attribute_value, compl_data = self.handle_attribute_type(properties)
if isinstance(attribute_value, (str, int)):
attribute = {'to_ids': to_ids, 'uuid': uuid}
self.handle_attribute_case(attribute_type, attribute_value, compl_data, attribute)
else:
self.handle_object_case(attribute_type, attribute_value, compl_data, to_ids=to_ids, object_uuid=uuid)
def parse_tag(self, entry):
if entry.startswith('misp-galaxy:'):
tag_type, value = entry.split('=')
galaxy_type = tag_type.split(':')[1]
cluster = {'type': galaxy_type, 'value': value[1:-1], 'tag_name': entry}
self.misp_event['Galaxy'].append({'type': galaxy_type, 'GalaxyCluster': [cluster]})
self.misp_event.add_tag(entry)
def parse_vulnerability(self, exploit_targets):
for exploit_target in exploit_targets:
if exploit_target.item:
for vulnerability in exploit_target.item.vulnerabilities:
self.misp_event.add_attribute(**{'type': 'vulnerability', 'value': vulnerability.cve_id})
def set_event_info(self):
info = self.get_event_info()
self.titles.append(info)
def set_timestamp_and_date(self):
if self.event.timestamp:
date, timestamp = self.get_timestamp_and_date()
self.dates.append(date)
self.timestamps.append(timestamp)
class ExternalStixParser(StixParser):
def __init__(self):
super(ExternalStixParser, self).__init__()
self.dns_objects = defaultdict(dict)
self.dns_ips = []
def build_misp_dict(self, event):
self.event = event
self.set_timestamp_and_date()
self.set_event_info()
header = self.event.stix_header
if hasattr(header, 'description') and hasattr(header.description, 'value'):
self.misp_event.add_attribute(**{'type': 'comment', 'value': header.description.value,
'comment': 'Imported from STIX header description'})
if hasattr(header, 'handling') and header.handling:
for handling in header.handling:
tags = self.parse_marking(handling)
for tag in tags:
self.misp_event.add_tag(tag)
if self.event.indicators:
self.parse_external_indicators(self.event.indicators)
if self.event.observables:
self.parse_external_observable(self.event.observables.observables)
if self.event.ttps:
self.parse_ttps(self.event.ttps.ttps)
if self.event.courses_of_action:
self.parse_coa(self.event.courses_of_action)
if self.dns_objects:
self.resolve_dns_objects()
self.set_distribution()
if self.references:
self.build_references()
def set_event_info(self):
info = self.get_event_info()
self.misp_event.info = str(info)
def set_timestamp_and_date(self):
if self.event.timestamp:
date, timestamp = self.get_timestamp_and_date()
self.misp_event.date = date
self.misp_event.timestamp = timestamp
# Return type & attributes (or value) of a Custom Object
def handle_custom(self, properties):
custom_properties = properties.custom_properties
if len(custom_properties) > 1:
for prop in custom_properties[:-1]:
misp_attribute = {'type': 'text', 'value': prop.value, 'comment': prop.name}
self.misp_event.add_attribute(**misp_attribute)
to_return = custom_properties[-1]
return 'text', to_return.value, to_return.name
# Parse the courses of action field of an external STIX document
def parse_coa(self, courses_of_action):
for coa in courses_of_action:
misp_object = MISPObject('course-of-action')
if coa.title:
attribute = {'type': 'text', 'object_relation': 'name',
'value': coa.title}
misp_object.add_attribute(**attribute)
for prop, properties_key in stix2misp_mapping._coa_mapping.items():
if getattr(coa, prop):
attribute = {'type': 'text', 'object_relation': prop.replace('_', ''),
'value': attrgetter('{}.{}'.format(prop, properties_key))(coa)}
misp_object.add_attribute(**attribute)
if coa.parameter_observables:
for observable in coa.parameter_observables.observables:
properties = observable.object_.properties
attribute = MISPAttribute()
attribute.type, attribute.value, _ = self.handle_attribute_type(properties)
referenced_uuid = str(uuid.uuid4())
attribute.uuid = referenced_uuid
self.misp_event.add_attribute(**attribute)
misp_object.add_reference(referenced_uuid, 'observable', None, **attribute)
self.misp_event.add_object(**misp_object)
# Parse description of an external indicator or observable and add it in the MISP event as an attribute
def parse_description(self, stix_object):
if stix_object.description:
misp_attribute = {}
if stix_object.timestamp:
misp_attribute['timestamp'] = self.getTimestampfromDate(stix_object.timestamp)
self.misp_event.add_attribute("text", stix_object.description.value, **misp_attribute)
# Parse indicators of an external STIX document
def parse_external_indicators(self, indicators):
for indicator in indicators:
self.parse_external_single_indicator(indicator)
def parse_external_single_indicator(self, indicator):
if hasattr(indicator, 'observable') and indicator.observable:
observable = indicator.observable
if hasattr(observable, 'object_') and observable.object_:
uuid = self.fetch_uuid(observable.object_.id_)
try:
properties = observable.object_.properties
if properties:
attribute_type, attribute_value, compl_data = self.handle_attribute_type(properties)
if isinstance(attribute_value, (str, int)):
# if the returned value is a simple value, we build an attribute
attribute = {'to_ids': True, 'uuid': uuid}
if indicator.timestamp:
attribute['timestamp'] = self.getTimestampfromDate(indicator.timestamp)
if hasattr(observable, 'handling') and observable.handling:
attribute['Tag'] = []
for handling in observable.handling:
attribute['Tag'].extend(self.parse_marking(handling))
parsed = self.special_parsing(observable.object_, attribute_type, attribute_value, attribute, uuid)
if parsed is not None:
return
self.handle_attribute_case(attribute_type, attribute_value, compl_data, attribute)
else:
# otherwise, it is a dictionary of attributes, so we build an object
self.handle_object_case(attribute_type, attribute_value, compl_data, to_ids=True, object_uuid=uuid)
except AttributeError:
self.parse_description(indicator)
if hasattr(indicator, 'related_indicators') and indicator.related_indicators:
for related_indicator in indicator.related_indicators:
self.parse_external_single_indicator(related_indicator.item)
# Parse observables of an external STIX document
def parse_external_observable(self, observables):
for observable in observables:
title = observable.title
observable_object = observable.object_
try:
properties = observable_object.properties
except AttributeError:
self.parse_description(observable)
continue
if properties:
try:
attribute_type, attribute_value, compl_data = self.handle_attribute_type(properties, title=title)
except KeyError:
# print("Error with an object of type: {}\n{}".format(properties._XSI_TYPE, observable.to_json()))
continue
object_uuid = self.fetch_uuid(observable_object.id_)
if isinstance(attribute_value, (str, int)):
# if the returned value is a simple value, we build an attribute
attribute = {'to_ids': False, 'uuid': object_uuid}
if hasattr(observable, 'handling') and observable.handling:
attribute['Tag'] = []
for handling in observable.handling:
attribute['Tag'].extend(self.parse_marking(handling))
parsed = self.special_parsing(observable_object, attribute_type, attribute_value, attribute, object_uuid)
if parsed is not None:
continue
self.handle_attribute_case(attribute_type, attribute_value, compl_data, attribute)
else:
# otherwise, it is a dictionary of attributes, so we build an object
if attribute_value:
self.handle_object_case(attribute_type, attribute_value, compl_data, object_uuid=object_uuid)
if observable_object.related_objects:
for related_object in observable_object.related_objects:
relationship = related_object.relationship.value.lower().replace('_', '-')
self.references[object_uuid].append({"idref": self.fetch_uuid(related_object.idref),
"relationship": relationship})
# Parse the ttps field of an external STIX document
def parse_ttps(self, ttps):
for ttp in ttps:
if ttp.behavior and ttp.behavior.malware_instances:
mi = ttp.behavior.malware_instances[0]
if mi.types:
mi_type = mi.types[0].value
galaxy = {'type': mi_type}
cluster = defaultdict(dict)
cluster['type'] = mi_type
if mi.description:
cluster['description'] = mi.description.value
cluster['value'] = ttp.title
if mi.names:
synonyms = []
for name in mi.names:
synonyms.append(name.value)
cluster['meta']['synonyms'] = synonyms
galaxy['GalaxyCluster'] = [cluster]
self.misp_event['Galaxy'].append(galaxy)
# Parse a DNS object
def resolve_dns_objects(self):
for domain, domain_dict in self.dns_objects['domain'].items():
ip_reference = domain_dict['related']
domain_attribute = domain_dict['data']
if ip_reference in self.dns_objects['ip']:
misp_object = MISPObject('passive-dns')
domain_attribute['object_relation'] = "rrname"
misp_object.add_attribute(**domain_attribute)
ip = self.dns_objects['ip'][ip_reference]['value']
ip_attribute = {"type": "text", "value": ip, "object_relation": "rdata"}
misp_object.add_attribute(**ip_attribute)
rrtype = "AAAA" if ":" in ip else "A"
rrtype_attribute = {"type": "text", "value": rrtype, "object_relation": "rrtype"}
misp_object.add_attribute(**rrtype_attribute)
self.misp_event.add_object(**misp_object)
else:
self.misp_event.add_attribute(**domain_attribute)
for ip, ip_dict in self.dns_objects['ip'].items():
if ip not in self.dns_ips:
self.misp_event.add_attribute(**ip_dict)
def special_parsing(self, observable_object, attribute_type, attribute_value, attribute, uuid):
if observable_object.related_objects:
related_objects = observable_object.related_objects
if attribute_type == "url" and len(related_objects) == 1 and related_objects[0].relationship.value == "Resolved_To":
related_ip = self.fetch_uuid(related_objects[0].idref)
self.dns_objects['domain'][uuid] = {"related": related_ip,
"data": {"type": "text", "value": attribute_value}}
if related_ip not in self.dns_ips:
self.dns_ips.append(related_ip)
return 1
if attribute_type in ('ip-src', 'ip-dst'):
attribute['type'] = attribute_type
attribute['value'] = attribute_value
self.dns_objects['ip'][uuid] = attribute
return 2
def generate_event(filename):
try:
return STIXPackage.from_xml(filename)
except Exception:
try:
import maec
print(2)
except ImportError:
print(3)
sys.exit(0)
def main(args):
filename = '{}/tmp/{}'.format(os.path.dirname(args[0]), args[1])
event = generate_event(filename)
title = event.stix_header.title
from_misp = (title is not None and "Export from " in title and "MISP" in title)
stix_parser = StixFromMISPParser() if from_misp else ExternalStixParser()
stix_parser.load_event(args[2:], filename, from_misp, event.version)
stix_parser.build_misp_dict(event)
stix_parser.saveFile()
print(1)
if __name__ == "__main__":
main(sys.argv)
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_461_1 |
crossvul-python_data_bad_4204_9 | """
This module defines a built-in contrib module that enables terminal embedding
within a slide.
"""
from marshmallow import fields, Schema
import os
import re
import shlex
import signal
import urwid
import yaml
import lookatme.render
from lookatme.exceptions import IgnoredByContrib
import lookatme.config
class YamlRender:
loads = lambda data: yaml.safe_load(data)
dumps = lambda data: yaml.safe_dump(data)
class TerminalExSchema(Schema):
"""The schema used for ``terminal-ex`` code blocks.
"""
command = fields.Str()
rows = fields.Int(default=10, missing=10)
init_text = fields.Str(default=None, missing=None)
init_wait = fields.Str(default=None, missing=None)
init_codeblock = fields.Bool(default=True, missing=True)
init_codeblock_lang = fields.Str(default="text", missing="text")
class Meta:
render_module = YamlRender
CREATED_TERMS = []
def render_code(token, body, stack, loop):
lang = token["lang"] or ""
numbered_term_match = re.match(r'terminal(\d+)', lang)
if lang != "terminal-ex" and numbered_term_match is None:
raise IgnoredByContrib
if numbered_term_match is not None:
term_data = TerminalExSchema().load({
"command": token["text"].strip(),
"rows": int(numbered_term_match.group(1)),
"init_codeblock": False,
})
else:
term_data = TerminalExSchema().loads(token["text"])
if term_data["init_text"] is not None and term_data["init_wait"] is not None:
orig_command = term_data["command"]
term_data["command"] = " ".join([shlex.quote(x) for x in [
"expect", "-c", ";".join([
'spawn -noecho {}'.format(term_data["command"]),
'expect {{{}}}'.format(term_data["init_wait"]),
'send {{{}}}'.format(term_data["init_text"]),
'interact',
'exit',
])
]])
term = urwid.Terminal(
shlex.split(term_data["command"].strip()),
main_loop=loop,
encoding="utf8",
)
CREATED_TERMS.append(term)
line_box = urwid.LineBox(urwid.BoxAdapter(term, height=term_data["rows"]))
line_box.no_cache = ["render"]
res = []
if term_data["init_codeblock"] is True:
fake_token = {
"text": term_data["init_text"],
"lang": term_data["init_codeblock_lang"],
}
res += lookatme.render.markdown_block.render_code(
fake_token, body, stack, loop
)
res += [
urwid.Divider(),
line_box,
urwid.Divider(),
]
return res
def shutdown():
for idx, term in enumerate(CREATED_TERMS):
lookatme.config.LOG.debug(f"Terminating terminal {idx+1}/{len(CREATED_TERMS)}")
if term.pid is not None:
term.terminate()
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_4204_9 |
crossvul-python_data_good_49_0 | """Utility functions for copying and archiving files and directory trees.
XXX The functions here don't copy the resource fork or other metadata on Mac.
"""
import os
import sys
import stat
from os.path import abspath
import fnmatch
import collections
import errno
try:
import zlib
del zlib
_ZLIB_SUPPORTED = True
except ImportError:
_ZLIB_SUPPORTED = False
try:
import bz2
del bz2
_BZ2_SUPPORTED = True
except ImportError:
_BZ2_SUPPORTED = False
try:
from pwd import getpwnam
except ImportError:
getpwnam = None
try:
from grp import getgrnam
except ImportError:
getgrnam = None
__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
"copytree", "move", "rmtree", "Error", "SpecialFileError",
"ExecError", "make_archive", "get_archive_formats",
"register_archive_format", "unregister_archive_format",
"ignore_patterns"]
class Error(EnvironmentError):
pass
class SpecialFileError(EnvironmentError):
"""Raised when trying to do a kind of operation (e.g. copying) which is
not supported on a special file (e.g. a named pipe)"""
class ExecError(EnvironmentError):
"""Raised when a command could not be executed"""
try:
WindowsError
except NameError:
WindowsError = None
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
def _samefile(src, dst):
# Macintosh, Unix.
if hasattr(os.path, 'samefile'):
try:
return os.path.samefile(src, dst)
except OSError:
return False
# All other platforms: check for same pathname.
return (os.path.normcase(os.path.abspath(src)) ==
os.path.normcase(os.path.abspath(dst)))
def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise Error("`%s` and `%s` are the same file" % (src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
def copymode(src, dst):
"""Copy mode bits from src to dst"""
if hasattr(os, 'chmod'):
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
os.chmod(dst, mode)
def copystat(src, dst):
"""Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
if hasattr(os, 'utime'):
os.utime(dst, (st.st_atime, st.st_mtime))
if hasattr(os, 'chmod'):
os.chmod(dst, mode)
if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
try:
os.chflags(dst, st.st_flags)
except OSError, why:
for err in 'EOPNOTSUPP', 'ENOTSUP':
if hasattr(errno, err) and why.errno == getattr(errno, err):
break
else:
raise
def copy(src, dst):
"""Copy data and mode bits ("cp src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copymode(src, dst)
def copy2(src, dst):
"""Copy data and all stat info ("cp -p src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copystat(src, dst)
def ignore_patterns(*patterns):
"""Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files"""
def _ignore_patterns(path, names):
ignored_names = []
for pattern in patterns:
ignored_names.extend(fnmatch.filter(names, pattern))
return set(ignored_names)
return _ignore_patterns
def copytree(src, dst, symlinks=False, ignore=None):
"""Recursively copy a directory tree using copy2().
The destination directory must not already exist.
If exception(s) occur, an Error is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
it is false, the contents of the files pointed to by symbolic
links are copied.
The optional ignore argument is a callable. If given, it
is called with the `src` parameter, which is the directory
being visited by copytree(), and `names` which is the list of
`src` contents, as returned by os.listdir():
callable(src, names) -> ignored_names
Since copytree() is called recursively, the callable will be
called once for each directory that is copied. It returns a
list of names relative to the `src` directory that should
not be copied.
XXX Consider this example code rather than the ultimate tool.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
except EnvironmentError, why:
errors.append((srcname, dstname, str(why)))
try:
copystat(src, dst)
except OSError, why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.append((src, dst, str(why)))
if errors:
raise Error, errors
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete a directory tree.
If ignore_errors is set, errors are ignored; otherwise, if onerror
is set, it is called to handle the error with arguments (func,
path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
path is the argument to that function that caused it to fail; and
exc_info is a tuple returned by sys.exc_info(). If ignore_errors
is false and onerror is None, an exception is raised.
"""
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
try:
if os.path.islink(path):
# symlinks to directories are forbidden, see bug #1669
raise OSError("Cannot call rmtree on a symbolic link")
except OSError:
onerror(os.path.islink, path, sys.exc_info())
# can't continue even if onerror hook returns
return
names = []
try:
names = os.listdir(path)
except os.error, err:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = os.lstat(fullname).st_mode
except os.error:
mode = 0
if stat.S_ISDIR(mode):
rmtree(fullname, ignore_errors, onerror)
else:
try:
os.remove(fullname)
except os.error, err:
onerror(os.remove, fullname, sys.exc_info())
try:
os.rmdir(path)
except os.error:
onerror(os.rmdir, path, sys.exc_info())
def _basename(path):
# A basename() variant which first strips the trailing slash, if present.
# Thus we always get the last component of the path, even for directories.
sep = os.path.sep + (os.path.altsep or '')
return os.path.basename(path.rstrip(sep))
def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.
"""
real_dst = dst
if os.path.isdir(dst):
if _samefile(src, dst):
# We might be on a case insensitive filesystem,
# perform the rename anyway.
os.rename(src, dst)
return
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error, "Destination path '%s' already exists" % real_dst
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src)
def _destinsrc(src, dst):
src = abspath(src)
dst = abspath(dst)
if not src.endswith(os.path.sep):
src += os.path.sep
if not dst.endswith(os.path.sep):
dst += os.path.sep
return dst.startswith(src)
def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None
def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
return None
try:
result = getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None
def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
owner=None, group=None, logger=None):
"""Create a (possibly compressed) tar file from all the files under
'base_dir'.
'compress' must be "gzip" (the default), "bzip2", or None.
'owner' and 'group' can be used to define an owner and a group for the
archive that is being built. If not provided, the current owner and group
will be used.
The output tar file will be named 'base_name' + ".tar", possibly plus
the appropriate compression extension (".gz", or ".bz2").
Returns the output filename.
"""
if compress is None:
tar_compression = ''
elif _ZLIB_SUPPORTED and compress == 'gzip':
tar_compression = 'gz'
elif _BZ2_SUPPORTED and compress == 'bzip2':
tar_compression = 'bz2'
else:
raise ValueError("bad value for 'compress', or compression format not "
"supported : {0}".format(compress))
compress_ext = '.' + tar_compression if compress else ''
archive_name = base_name + '.tar' + compress_ext
archive_dir = os.path.dirname(archive_name)
if archive_dir and not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# creating the tarball
import tarfile # late import so Python build itself doesn't break
if logger is not None:
logger.info('Creating tar archive')
uid = _get_uid(owner)
gid = _get_gid(group)
def _set_uid_gid(tarinfo):
if gid is not None:
tarinfo.gid = gid
tarinfo.gname = group
if uid is not None:
tarinfo.uid = uid
tarinfo.uname = owner
return tarinfo
if not dry_run:
tar = tarfile.open(archive_name, 'w|%s' % tar_compression)
try:
tar.add(base_dir, filter=_set_uid_gid)
finally:
tar.close()
return archive_name
def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger):
# XXX see if we want to keep an external call here
if verbose:
zipoptions = "-r"
else:
zipoptions = "-rq"
cmd = ["zip", zipoptions, zip_filename, base_dir]
if logger is not None:
logger.info(' '.join(cmd))
if dry_run:
return
import subprocess
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
# XXX really should distinguish between "couldn't find
# external 'zip' command" and "zip failed".
raise ExecError, \
("unable to create zip file '%s': "
"could neither import the 'zipfile' module nor "
"find a standalone zip utility") % zip_filename
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
"""Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default search path). If neither tool is
available, raises ExecError. Returns the name of the output zip
file.
"""
zip_filename = base_name + ".zip"
archive_dir = os.path.dirname(base_name)
if archive_dir and not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# If zipfile module is not available, try spawning an external 'zip'
# command.
try:
import zlib
import zipfile
except ImportError:
zipfile = None
if zipfile is None:
_call_external_zip(base_dir, zip_filename, verbose, dry_run, logger)
else:
if logger is not None:
logger.info("creating '%s' and adding '%s' to it",
zip_filename, base_dir)
if not dry_run:
with zipfile.ZipFile(zip_filename, "w",
compression=zipfile.ZIP_DEFLATED) as zf:
path = os.path.normpath(base_dir)
if path != os.curdir:
zf.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
for dirpath, dirnames, filenames in os.walk(base_dir):
for name in sorted(dirnames):
path = os.path.normpath(os.path.join(dirpath, name))
zf.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
zf.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
return zip_filename
_ARCHIVE_FORMATS = {
'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
'zip': (_make_zipfile, [], "ZIP file")
}
if _ZLIB_SUPPORTED:
_ARCHIVE_FORMATS['gztar'] = (_make_tarball, [('compress', 'gzip')],
"gzip'ed tar-file")
if _BZ2_SUPPORTED:
_ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
"bzip2'ed tar-file")
def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats
def register_archive_format(name, function, extra_args=None, description=''):
"""Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function.
"""
if extra_args is None:
extra_args = []
if not isinstance(function, collections.Callable):
raise TypeError('The %s object is not callable' % function)
if not isinstance(extra_args, (tuple, list)):
raise TypeError('extra_args needs to be a sequence')
for element in extra_args:
if not isinstance(element, (tuple, list)) or len(element) !=2 :
raise TypeError('extra_args elements are : (arg_name, value)')
_ARCHIVE_FORMATS[name] = (function, extra_args, description)
def unregister_archive_format(name):
del _ARCHIVE_FORMATS[name]
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None, logger=None):
"""Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one of "zip", "tar", "gztar",
or "bztar". Or any other registered format.
'root_dir' is a directory that will be the root directory of the
archive; ie. we typically chdir into 'root_dir' before creating the
archive. 'base_dir' is the directory where we start archiving from;
ie. 'base_dir' will be the common prefix of all files and
directories in the archive. 'root_dir' and 'base_dir' both default
to the current directory. Returns the name of the archive file.
'owner' and 'group' are used when creating a tar archive. By default,
uses the current owner and group.
"""
save_cwd = os.getcwd()
if root_dir is not None:
if logger is not None:
logger.debug("changing into '%s'", root_dir)
base_name = os.path.abspath(base_name)
if not dry_run:
os.chdir(root_dir)
if base_dir is None:
base_dir = os.curdir
kwargs = {'dry_run': dry_run, 'logger': logger}
try:
format_info = _ARCHIVE_FORMATS[format]
except KeyError:
raise ValueError, "unknown archive format '%s'" % format
func = format_info[0]
for arg, val in format_info[1]:
kwargs[arg] = val
if format != 'zip':
kwargs['owner'] = owner
kwargs['group'] = group
try:
filename = func(base_name, base_dir, **kwargs)
finally:
if root_dir is not None:
if logger is not None:
logger.debug("changing back to '%s'", save_cwd)
os.chdir(save_cwd)
return filename
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_49_0 |
crossvul-python_data_bad_4204_7 | """
This module handles loading and using lookatme_contriba modules
Contrib modules are directly used
"""
import contextlib
from lookatme.exceptions import IgnoredByContrib
from . import terminal
from . import file_loader
CONTRIB_MODULES = [
terminal,
file_loader,
]
def load_contribs(contrib_names):
"""Load all contrib modules specified by ``contrib_names``. These should
all be namespaced packages under the ``lookatmecontrib`` namespace. E.g.
``lookatmecontrib.calendar`` would be an extension provided by a
contrib module, and would be added to an ``extensions`` list in a slide's
YAML header as ``calendar``.
"""
if contrib_names is None:
return
errors = []
for contrib_name in contrib_names:
module_name = f"lookatme.contrib.{contrib_name}"
try:
mod = __import__(module_name, fromlist=[contrib_name])
CONTRIB_MODULES.append(mod)
except Exception as e:
errors.append(str(e))
if len(errors) > 0:
raise Exception(
"Error loading one or more extensions:\n\n" + "\n".join(errors),
)
def contrib_first(fn):
"""A decorator that allows contrib modules to override default behavior
of lookatme. E.g., a contrib module may override how a table is displayed
to enable sorting, or enable displaying images rendered with ANSII color
codes and box drawing characters, etc.
Contrib modules may ignore chances to override default behavior by raising
the ``lookatme.contrib.IgnoredByContrib`` exception.
"""
fn_name = fn.__name__
@contextlib.wraps(fn)
def inner(*args, **kwargs):
for mod in CONTRIB_MODULES:
if not hasattr(mod, fn_name):
continue
try:
return getattr(mod, fn_name)(*args, **kwargs)
except IgnoredByContrib:
pass
return fn(*args, **kwargs)
return inner
def shutdown_contribs():
"""Call the shutdown function on all contrib modules
"""
for mod in CONTRIB_MODULES:
getattr(mod, "shutdown", lambda: 1)()
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_4204_7 |
crossvul-python_data_bad_49_0 | """Utility functions for copying and archiving files and directory trees.
XXX The functions here don't copy the resource fork or other metadata on Mac.
"""
import os
import sys
import stat
from os.path import abspath
import fnmatch
import collections
import errno
try:
import zlib
del zlib
_ZLIB_SUPPORTED = True
except ImportError:
_ZLIB_SUPPORTED = False
try:
import bz2
del bz2
_BZ2_SUPPORTED = True
except ImportError:
_BZ2_SUPPORTED = False
try:
from pwd import getpwnam
except ImportError:
getpwnam = None
try:
from grp import getgrnam
except ImportError:
getgrnam = None
__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
"copytree", "move", "rmtree", "Error", "SpecialFileError",
"ExecError", "make_archive", "get_archive_formats",
"register_archive_format", "unregister_archive_format",
"ignore_patterns"]
class Error(EnvironmentError):
pass
class SpecialFileError(EnvironmentError):
"""Raised when trying to do a kind of operation (e.g. copying) which is
not supported on a special file (e.g. a named pipe)"""
class ExecError(EnvironmentError):
"""Raised when a command could not be executed"""
try:
WindowsError
except NameError:
WindowsError = None
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
def _samefile(src, dst):
# Macintosh, Unix.
if hasattr(os.path, 'samefile'):
try:
return os.path.samefile(src, dst)
except OSError:
return False
# All other platforms: check for same pathname.
return (os.path.normcase(os.path.abspath(src)) ==
os.path.normcase(os.path.abspath(dst)))
def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise Error("`%s` and `%s` are the same file" % (src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
def copymode(src, dst):
"""Copy mode bits from src to dst"""
if hasattr(os, 'chmod'):
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
os.chmod(dst, mode)
def copystat(src, dst):
"""Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
if hasattr(os, 'utime'):
os.utime(dst, (st.st_atime, st.st_mtime))
if hasattr(os, 'chmod'):
os.chmod(dst, mode)
if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
try:
os.chflags(dst, st.st_flags)
except OSError, why:
for err in 'EOPNOTSUPP', 'ENOTSUP':
if hasattr(errno, err) and why.errno == getattr(errno, err):
break
else:
raise
def copy(src, dst):
"""Copy data and mode bits ("cp src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copymode(src, dst)
def copy2(src, dst):
"""Copy data and all stat info ("cp -p src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copystat(src, dst)
def ignore_patterns(*patterns):
"""Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files"""
def _ignore_patterns(path, names):
ignored_names = []
for pattern in patterns:
ignored_names.extend(fnmatch.filter(names, pattern))
return set(ignored_names)
return _ignore_patterns
def copytree(src, dst, symlinks=False, ignore=None):
"""Recursively copy a directory tree using copy2().
The destination directory must not already exist.
If exception(s) occur, an Error is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
it is false, the contents of the files pointed to by symbolic
links are copied.
The optional ignore argument is a callable. If given, it
is called with the `src` parameter, which is the directory
being visited by copytree(), and `names` which is the list of
`src` contents, as returned by os.listdir():
callable(src, names) -> ignored_names
Since copytree() is called recursively, the callable will be
called once for each directory that is copied. It returns a
list of names relative to the `src` directory that should
not be copied.
XXX Consider this example code rather than the ultimate tool.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
except EnvironmentError, why:
errors.append((srcname, dstname, str(why)))
try:
copystat(src, dst)
except OSError, why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.append((src, dst, str(why)))
if errors:
raise Error, errors
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete a directory tree.
If ignore_errors is set, errors are ignored; otherwise, if onerror
is set, it is called to handle the error with arguments (func,
path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
path is the argument to that function that caused it to fail; and
exc_info is a tuple returned by sys.exc_info(). If ignore_errors
is false and onerror is None, an exception is raised.
"""
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
try:
if os.path.islink(path):
# symlinks to directories are forbidden, see bug #1669
raise OSError("Cannot call rmtree on a symbolic link")
except OSError:
onerror(os.path.islink, path, sys.exc_info())
# can't continue even if onerror hook returns
return
names = []
try:
names = os.listdir(path)
except os.error, err:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = os.lstat(fullname).st_mode
except os.error:
mode = 0
if stat.S_ISDIR(mode):
rmtree(fullname, ignore_errors, onerror)
else:
try:
os.remove(fullname)
except os.error, err:
onerror(os.remove, fullname, sys.exc_info())
try:
os.rmdir(path)
except os.error:
onerror(os.rmdir, path, sys.exc_info())
def _basename(path):
# A basename() variant which first strips the trailing slash, if present.
# Thus we always get the last component of the path, even for directories.
sep = os.path.sep + (os.path.altsep or '')
return os.path.basename(path.rstrip(sep))
def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.
"""
real_dst = dst
if os.path.isdir(dst):
if _samefile(src, dst):
# We might be on a case insensitive filesystem,
# perform the rename anyway.
os.rename(src, dst)
return
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error, "Destination path '%s' already exists" % real_dst
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src)
def _destinsrc(src, dst):
src = abspath(src)
dst = abspath(dst)
if not src.endswith(os.path.sep):
src += os.path.sep
if not dst.endswith(os.path.sep):
dst += os.path.sep
return dst.startswith(src)
def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None
def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
return None
try:
result = getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None
def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
owner=None, group=None, logger=None):
"""Create a (possibly compressed) tar file from all the files under
'base_dir'.
'compress' must be "gzip" (the default), "bzip2", or None.
'owner' and 'group' can be used to define an owner and a group for the
archive that is being built. If not provided, the current owner and group
will be used.
The output tar file will be named 'base_name' + ".tar", possibly plus
the appropriate compression extension (".gz", or ".bz2").
Returns the output filename.
"""
if compress is None:
tar_compression = ''
elif _ZLIB_SUPPORTED and compress == 'gzip':
tar_compression = 'gz'
elif _BZ2_SUPPORTED and compress == 'bzip2':
tar_compression = 'bz2'
else:
raise ValueError("bad value for 'compress', or compression format not "
"supported : {0}".format(compress))
compress_ext = '.' + tar_compression if compress else ''
archive_name = base_name + '.tar' + compress_ext
archive_dir = os.path.dirname(archive_name)
if archive_dir and not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# creating the tarball
import tarfile # late import so Python build itself doesn't break
if logger is not None:
logger.info('Creating tar archive')
uid = _get_uid(owner)
gid = _get_gid(group)
def _set_uid_gid(tarinfo):
if gid is not None:
tarinfo.gid = gid
tarinfo.gname = group
if uid is not None:
tarinfo.uid = uid
tarinfo.uname = owner
return tarinfo
if not dry_run:
tar = tarfile.open(archive_name, 'w|%s' % tar_compression)
try:
tar.add(base_dir, filter=_set_uid_gid)
finally:
tar.close()
return archive_name
def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
# XXX see if we want to keep an external call here
if verbose:
zipoptions = "-r"
else:
zipoptions = "-rq"
from distutils.errors import DistutilsExecError
from distutils.spawn import spawn
try:
spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
except DistutilsExecError:
# XXX really should distinguish between "couldn't find
# external 'zip' command" and "zip failed".
raise ExecError, \
("unable to create zip file '%s': "
"could neither import the 'zipfile' module nor "
"find a standalone zip utility") % zip_filename
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
"""Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default search path). If neither tool is
available, raises ExecError. Returns the name of the output zip
file.
"""
zip_filename = base_name + ".zip"
archive_dir = os.path.dirname(base_name)
if archive_dir and not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# If zipfile module is not available, try spawning an external 'zip'
# command.
try:
import zlib
import zipfile
except ImportError:
zipfile = None
if zipfile is None:
_call_external_zip(base_dir, zip_filename, verbose, dry_run)
else:
if logger is not None:
logger.info("creating '%s' and adding '%s' to it",
zip_filename, base_dir)
if not dry_run:
with zipfile.ZipFile(zip_filename, "w",
compression=zipfile.ZIP_DEFLATED) as zf:
path = os.path.normpath(base_dir)
if path != os.curdir:
zf.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
for dirpath, dirnames, filenames in os.walk(base_dir):
for name in sorted(dirnames):
path = os.path.normpath(os.path.join(dirpath, name))
zf.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
zf.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
return zip_filename
_ARCHIVE_FORMATS = {
'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
'zip': (_make_zipfile, [], "ZIP file")
}
if _ZLIB_SUPPORTED:
_ARCHIVE_FORMATS['gztar'] = (_make_tarball, [('compress', 'gzip')],
"gzip'ed tar-file")
if _BZ2_SUPPORTED:
_ARCHIVE_FORMATS['bztar'] = (_make_tarball, [('compress', 'bzip2')],
"bzip2'ed tar-file")
def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats
def register_archive_format(name, function, extra_args=None, description=''):
"""Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function.
"""
if extra_args is None:
extra_args = []
if not isinstance(function, collections.Callable):
raise TypeError('The %s object is not callable' % function)
if not isinstance(extra_args, (tuple, list)):
raise TypeError('extra_args needs to be a sequence')
for element in extra_args:
if not isinstance(element, (tuple, list)) or len(element) !=2 :
raise TypeError('extra_args elements are : (arg_name, value)')
_ARCHIVE_FORMATS[name] = (function, extra_args, description)
def unregister_archive_format(name):
del _ARCHIVE_FORMATS[name]
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None, logger=None):
"""Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one of "zip", "tar", "gztar",
or "bztar". Or any other registered format.
'root_dir' is a directory that will be the root directory of the
archive; ie. we typically chdir into 'root_dir' before creating the
archive. 'base_dir' is the directory where we start archiving from;
ie. 'base_dir' will be the common prefix of all files and
directories in the archive. 'root_dir' and 'base_dir' both default
to the current directory. Returns the name of the archive file.
'owner' and 'group' are used when creating a tar archive. By default,
uses the current owner and group.
"""
save_cwd = os.getcwd()
if root_dir is not None:
if logger is not None:
logger.debug("changing into '%s'", root_dir)
base_name = os.path.abspath(base_name)
if not dry_run:
os.chdir(root_dir)
if base_dir is None:
base_dir = os.curdir
kwargs = {'dry_run': dry_run, 'logger': logger}
try:
format_info = _ARCHIVE_FORMATS[format]
except KeyError:
raise ValueError, "unknown archive format '%s'" % format
func = format_info[0]
for arg, val in format_info[1]:
kwargs[arg] = val
if format != 'zip':
kwargs['owner'] = owner
kwargs['group'] = group
try:
filename = func(base_name, base_dir, **kwargs)
finally:
if root_dir is not None:
if logger is not None:
logger.debug("changing back to '%s'", save_cwd)
os.chdir(save_cwd)
return filename
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_49_0 |
crossvul-python_data_bad_4204_6 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-78/py/bad_4204_6 |
crossvul-python_data_bad_4204_5 | #!/usr/bin/env python3
"""
This is the main CLI for lookatme
"""
import click
import logging
import io
import os
import pygments.styles
import sys
import tempfile
import lookatme.tui
import lookatme.log
import lookatme.config
from lookatme.pres import Presentation
from lookatme.schemas import StyleSchema
@click.command("lookatme")
@click.option("--debug", "debug", is_flag="True", default=False)
@click.option(
"-l",
"--log",
"log_path",
type=click.Path(writable=True),
default=os.path.join(tempfile.gettempdir(), "lookatme.log"),
)
@click.option(
"-t",
"--theme",
"theme",
type=click.Choice(["dark", "light"]),
default="dark",
)
@click.option(
"-s",
"--style",
"code_style",
default=None,
type=click.Choice(list(pygments.styles.get_all_styles())),
)
@click.option(
"--dump-styles",
help="Dump the resolved styles that will be used with the presentation to stdout",
is_flag=True,
default=False,
)
@click.option(
"--live",
"--live-reload",
"live_reload",
help="Watch the input filename for modifications and automatically reload",
is_flag=True,
default=False,
)
@click.option(
"-e",
"--exts",
"extensions",
help="A comma-separated list of extension names to automatically load"
" (LOOKATME_EXTS)",
envvar="LOOKATME_EXTS",
default="",
)
@click.option(
"--single",
"--one",
"single_slide",
help="Render the source as a single slide",
is_flag=True,
default=False
)
@click.version_option(lookatme.__version__)
@click.argument(
"input_files",
type=click.File("r"),
nargs=-1,
)
def main(debug, log_path, theme, code_style, dump_styles,
input_files, live_reload, extensions, single_slide):
"""lookatme - An interactive, terminal-based markdown presentation tool.
"""
if debug:
lookatme.config.LOG = lookatme.log.create_log(log_path)
else:
lookatme.config.LOG = lookatme.log.create_null_log()
if len(input_files) == 0:
input_files = [io.StringIO("")]
preload_exts = [x.strip() for x in extensions.split(',')]
preload_exts = list(filter(lambda x: x != '', preload_exts))
pres = Presentation(
input_files[0],
theme,
code_style,
live_reload=live_reload,
single_slide=single_slide,
preload_extensions=preload_exts,
)
if dump_styles:
print(StyleSchema().dumps(pres.styles))
return 0
try:
pres.run()
except Exception as e:
number = pres.tui.curr_slide.number + 1
click.echo(f"Error rendering slide {number}: {e}")
if not debug:
click.echo("Rerun with --debug to view the full traceback in logs")
else:
lookatme.config.LOG.exception(f"Error rendering slide {number}: {e}")
click.echo(f"See {log_path} for traceback")
raise click.Abort()
if __name__ == "__main__":
main()
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_4204_5 |
crossvul-python_data_bad_2926_1 | # Back In Time
# Copyright (C) 2008-2017 Oprea Dan, Bart de Koning, Richard Bailey, Germar Reitze
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os
import pluginmanager
import gettext
_=gettext.gettext
class NotifyPlugin( pluginmanager.Plugin ):
def __init__( self ):
self.user = ''
try:
self.user = os.getlogin()
except:
pass
if not self.user:
try:
user = os.environ['USER']
except:
pass
if not self.user:
try:
user = os.environ['LOGNAME']
except:
pass
def init( self, snapshots ):
return True
def is_gui( self ):
return True
def on_process_begins( self ):
pass
def on_process_ends( self ):
pass
def on_error( self, code, message ):
return
def on_new_snapshot( self, snapshot_id, snapshot_path ):
return
def on_message( self, profile_id, profile_name, level, message, timeout ):
if 1 == level:
cmd = "notify-send "
if timeout > 0:
cmd = cmd + " -t %s" % (1000 * timeout)
title = "Back In Time (%s) : %s" % (self.user, profile_name)
message = message.replace("\n", ' ')
message = message.replace("\r", '')
cmd = cmd + " \"%s\" \"%s\"" % (title, message)
print(cmd)
os.system(cmd)
return
| ./CrossVul/dataset_final_sorted/CWE-78/py/bad_2926_1 |
crossvul-python_data_good_4204_9 | """
This module defines a built-in contrib module that enables terminal embedding
within a slide.
"""
from marshmallow import fields, Schema
import os
import re
import shlex
import signal
import urwid
import yaml
import lookatme.render
from lookatme.exceptions import IgnoredByContrib
import lookatme.config
def user_warnings():
"""Provide warnings to the user that loading this extension may cause
shell commands specified in the markdown to be run.
"""
return [
"Code-blocks with a language starting with 'terminal' will cause shell",
" commands from the source markdown to be run",
"See https://lookatme.readthedocs.io/en/latest/builtin_extensions/terminal.html",
" for more details",
]
class YamlRender:
loads = lambda data: yaml.safe_load(data)
dumps = lambda data: yaml.safe_dump(data)
class TerminalExSchema(Schema):
"""The schema used for ``terminal-ex`` code blocks.
"""
command = fields.Str()
rows = fields.Int(default=10, missing=10)
init_text = fields.Str(default=None, missing=None)
init_wait = fields.Str(default=None, missing=None)
init_codeblock = fields.Bool(default=True, missing=True)
init_codeblock_lang = fields.Str(default="text", missing="text")
class Meta:
render_module = YamlRender
CREATED_TERMS = []
def render_code(token, body, stack, loop):
lang = token["lang"] or ""
numbered_term_match = re.match(r'terminal(\d+)', lang)
if lang != "terminal-ex" and numbered_term_match is None:
raise IgnoredByContrib
if numbered_term_match is not None:
term_data = TerminalExSchema().load({
"command": token["text"].strip(),
"rows": int(numbered_term_match.group(1)),
"init_codeblock": False,
})
else:
term_data = TerminalExSchema().loads(token["text"])
if term_data["init_text"] is not None and term_data["init_wait"] is not None:
orig_command = term_data["command"]
term_data["command"] = " ".join([shlex.quote(x) for x in [
"expect", "-c", ";".join([
'spawn -noecho {}'.format(term_data["command"]),
'expect {{{}}}'.format(term_data["init_wait"]),
'send {{{}}}'.format(term_data["init_text"]),
'interact',
'exit',
])
]])
term = urwid.Terminal(
shlex.split(term_data["command"].strip()),
main_loop=loop,
encoding="utf8",
)
CREATED_TERMS.append(term)
line_box = urwid.LineBox(urwid.BoxAdapter(term, height=term_data["rows"]))
line_box.no_cache = ["render"]
res = []
if term_data["init_codeblock"] is True:
fake_token = {
"text": term_data["init_text"],
"lang": term_data["init_codeblock_lang"],
}
res += lookatme.render.markdown_block.render_code(
fake_token, body, stack, loop
)
res += [
urwid.Divider(),
line_box,
urwid.Divider(),
]
return res
def shutdown():
for idx, term in enumerate(CREATED_TERMS):
lookatme.config.LOG.debug(f"Terminating terminal {idx+1}/{len(CREATED_TERMS)}")
if term.pid is not None:
term.terminate()
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_4204_9 |
crossvul-python_data_good_4204_3 | """
Defines a calendar extension that overrides code block rendering if the
language type is calendar
"""
import datetime
import calendar
import urwid
from lookatme.exceptions import IgnoredByContrib
def user_warnings():
"""No warnings exist for this extension. Anything you want to warn the
user about, such as security risks in processing untrusted markdown, should
go here.
"""
return []
def render_code(token, body, stack, loop):
lang = token["lang"] or ""
if lang != "calendar":
raise IgnoredByContrib()
today = datetime.datetime.utcnow()
return urwid.Text(calendar.month(today.year, today.month))
| ./CrossVul/dataset_final_sorted/CWE-78/py/good_4204_3 |
crossvul-python_data_good_1734_1 | ##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Basic user registration tool.
"""
from random import choice
import re
from AccessControl.requestmethod import postonly
from AccessControl.SecurityInfo import ClassSecurityInfo
from App.class_init import InitializeClass
from App.special_dtml import DTMLFile
from OFS.SimpleItem import SimpleItem
from zope.component import getUtility
from zope.interface import implements
from Products.CMFCore.interfaces import IMembershipTool
from Products.CMFCore.interfaces import IRegistrationTool
from Products.CMFCore.permissions import AddPortalMember
from Products.CMFCore.permissions import MailForgottenPassword
from Products.CMFCore.permissions import ManagePortal
from Products.CMFCore.utils import _checkPermission
from Products.CMFCore.utils import _dtmldir
from Products.CMFCore.utils import _limitGrantedRoles
from Products.CMFCore.utils import Message as _
from Products.CMFCore.utils import registerToolInterface
from Products.CMFCore.utils import UniqueObject
class RegistrationTool(UniqueObject, SimpleItem):
""" Create and modify users by making calls to portal_membership.
"""
implements(IRegistrationTool)
id = 'portal_registration'
meta_type = 'CMF Registration Tool'
member_id_pattern = ''
default_member_id_pattern = "^[A-Za-z][A-Za-z0-9_]*$"
_ALLOWED_MEMBER_ID_PATTERN = re.compile(default_member_id_pattern)
security = ClassSecurityInfo()
manage_options = ( ({'label': 'Overview',
'action': 'manage_overview'},
{'label': 'Configure',
'action': 'manage_configuration'})
+ SimpleItem.manage_options
)
#
# ZMI methods
#
security.declareProtected(ManagePortal, 'manage_overview')
manage_overview = DTMLFile( 'explainRegistrationTool', _dtmldir )
security.declareProtected(ManagePortal, 'manage_configuration')
manage_configuration = DTMLFile('configureRegistrationTool', _dtmldir)
security.declareProtected(ManagePortal, 'manage_editIDPattern')
def manage_editIDPattern(self, pattern, REQUEST=None):
"""Edit the allowable member ID pattern TTW"""
pattern.strip()
if len(pattern) > 0:
self.member_id_pattern = pattern
self._ALLOWED_MEMBER_ID_PATTERN = re.compile(pattern)
else:
self.member_id_pattern = ''
self._ALLOWED_MEMBER_ID_PATTERN = re.compile(
self.default_member_id_pattern)
if REQUEST is not None:
msg = 'Member ID Pattern changed'
return self.manage_configuration(manage_tabs_message=msg)
security.declareProtected(ManagePortal, 'getIDPattern')
def getIDPattern(self):
""" Return the currently-used member ID pattern """
return self.member_id_pattern
security.declareProtected(ManagePortal, 'getDefaultIDPattern')
def getDefaultIDPattern(self):
""" Return the currently-used member ID pattern """
return self.default_member_id_pattern
#
# 'portal_registration' interface methods
#
security.declarePublic('isRegistrationAllowed')
def isRegistrationAllowed(self, REQUEST):
'''Returns a boolean value indicating whether the user
is allowed to add a member to the portal.
'''
return _checkPermission(AddPortalMember, self.aq_inner.aq_parent)
security.declarePublic('testPasswordValidity')
def testPasswordValidity(self, password, confirm=None):
'''If the password is valid, returns None. If not, returns
a string explaining why.
'''
return None
security.declarePublic('testPropertiesValidity')
def testPropertiesValidity(self, new_properties, member=None):
'''If the properties are valid, returns None. If not, returns
a string explaining why.
'''
return None
security.declarePublic('generatePassword')
def generatePassword(self):
""" Generate a valid password.
"""
# we don't use these to avoid typos: OQ0Il1
chars = 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'
return ''.join( [ choice(chars) for i in range(6) ] )
security.declareProtected(AddPortalMember, 'addMember')
@postonly
def addMember(self, id, password, roles=('Member',), domains='',
properties=None, REQUEST=None):
# XXX Do not make this a normal method comment. Doing so makes
# this method publishable
# Creates a PortalMember and returns it. The properties argument
# can be a mapping with additional member properties. Raises an
# exception if the given id already exists, the password does not
# comply with the policy in effect, or the authenticated user is not
# allowed to grant one of the roles listed (where Member is a special
# role that can always be granted); these conditions should be
# detected before the fact so that a cleaner message can be printed.
if not self.isMemberIdAllowed(id):
raise ValueError(_(u'The login name you selected is already in '
u'use or is not valid. Please choose another.'))
failMessage = self.testPasswordValidity(password)
if failMessage is not None:
raise ValueError(failMessage)
if properties is not None:
failMessage = self.testPropertiesValidity(properties)
if failMessage is not None:
raise ValueError(failMessage)
# Limit the granted roles.
# Anyone is always allowed to grant the 'Member' role.
_limitGrantedRoles(roles, self, ('Member',))
mtool = getUtility(IMembershipTool)
mtool.addMember(id, password, roles, domains, properties)
member = mtool.getMemberById(id)
self.afterAdd(member, id, password, properties)
return member
security.declareProtected(AddPortalMember, 'isMemberIdAllowed')
def isMemberIdAllowed(self, id):
'''Returns 1 if the ID is not in use and is not reserved.
'''
if len(id) < 1 or id == 'Anonymous User':
return 0
if not self._ALLOWED_MEMBER_ID_PATTERN.match( id ):
return 0
mtool = getUtility(IMembershipTool)
if mtool.getMemberById(id) is not None:
return 0
return 1
security.declarePublic('afterAdd')
def afterAdd(self, member, id, password, properties):
'''Called by portal_registration.addMember()
after a member has been added successfully.'''
pass
security.declareProtected(MailForgottenPassword, 'mailPassword')
def mailPassword(self, forgotten_userid, REQUEST):
'''Email a forgotten password to a member. Raises an exception
if user ID is not found.
'''
raise NotImplementedError
InitializeClass(RegistrationTool)
registerToolInterface('portal_registration', IRegistrationTool)
| ./CrossVul/dataset_final_sorted/CWE-284/py/good_1734_1 |
crossvul-python_data_bad_1734_1 | ##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Basic user registration tool.
"""
from random import choice
import re
from AccessControl.requestmethod import postonly
from AccessControl.SecurityInfo import ClassSecurityInfo
from App.class_init import InitializeClass
from App.special_dtml import DTMLFile
from OFS.SimpleItem import SimpleItem
from zope.component import getUtility
from zope.interface import implements
from Products.CMFCore.interfaces import IMembershipTool
from Products.CMFCore.interfaces import IRegistrationTool
from Products.CMFCore.permissions import AddPortalMember
from Products.CMFCore.permissions import MailForgottenPassword
from Products.CMFCore.permissions import ManagePortal
from Products.CMFCore.utils import _checkPermission
from Products.CMFCore.utils import _dtmldir
from Products.CMFCore.utils import _limitGrantedRoles
from Products.CMFCore.utils import Message as _
from Products.CMFCore.utils import registerToolInterface
from Products.CMFCore.utils import UniqueObject
class RegistrationTool(UniqueObject, SimpleItem):
""" Create and modify users by making calls to portal_membership.
"""
implements(IRegistrationTool)
id = 'portal_registration'
meta_type = 'CMF Registration Tool'
member_id_pattern = ''
default_member_id_pattern = "^[A-Za-z][A-Za-z0-9_]*$"
_ALLOWED_MEMBER_ID_PATTERN = re.compile(default_member_id_pattern)
security = ClassSecurityInfo()
manage_options = ( ({'label': 'Overview',
'action': 'manage_overview'},
{'label': 'Configure',
'action': 'manage_configuration'})
+ SimpleItem.manage_options
)
#
# ZMI methods
#
security.declareProtected(ManagePortal, 'manage_overview')
manage_overview = DTMLFile( 'explainRegistrationTool', _dtmldir )
security.declareProtected(ManagePortal, 'manage_configuration')
manage_configuration = DTMLFile('configureRegistrationTool', _dtmldir)
security.declareProtected(ManagePortal, 'manage_editIDPattern')
def manage_editIDPattern(self, pattern, REQUEST=None):
"""Edit the allowable member ID pattern TTW"""
pattern.strip()
if len(pattern) > 0:
self.member_id_pattern = pattern
self._ALLOWED_MEMBER_ID_PATTERN = re.compile(pattern)
else:
self.member_id_pattern = ''
self._ALLOWED_MEMBER_ID_PATTERN = re.compile(
self.default_member_id_pattern)
if REQUEST is not None:
msg = 'Member ID Pattern changed'
return self.manage_configuration(manage_tabs_message=msg)
security.declareProtected(ManagePortal, 'getIDPattern')
def getIDPattern(self):
""" Return the currently-used member ID pattern """
return self.member_id_pattern
security.declareProtected(ManagePortal, 'getDefaultIDPattern')
def getDefaultIDPattern(self):
""" Return the currently-used member ID pattern """
return self.default_member_id_pattern
#
# 'portal_registration' interface methods
#
security.declarePublic('isRegistrationAllowed')
def isRegistrationAllowed(self, REQUEST):
'''Returns a boolean value indicating whether the user
is allowed to add a member to the portal.
'''
return _checkPermission(AddPortalMember, self.aq_inner.aq_parent)
security.declarePublic('testPasswordValidity')
def testPasswordValidity(self, password, confirm=None):
'''If the password is valid, returns None. If not, returns
a string explaining why.
'''
return None
security.declarePublic('testPropertiesValidity')
def testPropertiesValidity(self, new_properties, member=None):
'''If the properties are valid, returns None. If not, returns
a string explaining why.
'''
return None
security.declarePublic('generatePassword')
def generatePassword(self):
""" Generate a valid password.
"""
# we don't use these to avoid typos: OQ0Il1
chars = 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'
return ''.join( [ choice(chars) for i in range(6) ] )
security.declareProtected(AddPortalMember, 'addMember')
@postonly
def addMember(self, id, password, roles=('Member',), domains='',
properties=None, REQUEST=None):
'''Creates a PortalMember and returns it. The properties argument
can be a mapping with additional member properties. Raises an
exception if the given id already exists, the password does not
comply with the policy in effect, or the authenticated user is not
allowed to grant one of the roles listed (where Member is a special
role that can always be granted); these conditions should be
detected before the fact so that a cleaner message can be printed.
'''
if not self.isMemberIdAllowed(id):
raise ValueError(_(u'The login name you selected is already in '
u'use or is not valid. Please choose another.'))
failMessage = self.testPasswordValidity(password)
if failMessage is not None:
raise ValueError(failMessage)
if properties is not None:
failMessage = self.testPropertiesValidity(properties)
if failMessage is not None:
raise ValueError(failMessage)
# Limit the granted roles.
# Anyone is always allowed to grant the 'Member' role.
_limitGrantedRoles(roles, self, ('Member',))
mtool = getUtility(IMembershipTool)
mtool.addMember(id, password, roles, domains, properties)
member = mtool.getMemberById(id)
self.afterAdd(member, id, password, properties)
return member
security.declareProtected(AddPortalMember, 'isMemberIdAllowed')
def isMemberIdAllowed(self, id):
'''Returns 1 if the ID is not in use and is not reserved.
'''
if len(id) < 1 or id == 'Anonymous User':
return 0
if not self._ALLOWED_MEMBER_ID_PATTERN.match( id ):
return 0
mtool = getUtility(IMembershipTool)
if mtool.getMemberById(id) is not None:
return 0
return 1
security.declarePublic('afterAdd')
def afterAdd(self, member, id, password, properties):
'''Called by portal_registration.addMember()
after a member has been added successfully.'''
pass
security.declareProtected(MailForgottenPassword, 'mailPassword')
def mailPassword(self, forgotten_userid, REQUEST):
'''Email a forgotten password to a member. Raises an exception
if user ID is not found.
'''
raise NotImplementedError
InitializeClass(RegistrationTool)
registerToolInterface('portal_registration', IRegistrationTool)
| ./CrossVul/dataset_final_sorted/CWE-284/py/bad_1734_1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.