"""Functions for builtin CherryPy tools."""

import logging
import re
from hashlib import md5

import six
from six.moves import urllib

import cherrypy
from cherrypy._cpcompat import text_or_bytes
from cherrypy.lib import httputil as _httputil
from cherrypy.lib import is_iterator


#                     Conditional HTTP request support                     #

def validate_etags(autotags=False, debug=False):
    """Validate the current ETag against If-Match, If-None-Match headers.

    If autotags is True, an ETag response-header value will be provided
    from an MD5 hash of the response body (unless some other code has
    already provided an ETag header). If False (the default), the ETag
    will not be automatic.

    WARNING: the autotags feature is not designed for URL's which allow
    methods other than GET. For example, if a POST to the same URL returns
    no content, the automatic ETag will be incorrect, breaking a fundamental
    use for entity tags in a possibly destructive fashion. Likewise, if you
    raise 304 Not Modified, the response body will be empty, the ETag hash
    will be incorrect, and your application will break.
    See :rfc:`2616` Section 14.24.
    """
    response = cherrypy.serving.response

    # Guard against being run twice.
    if hasattr(response, 'ETag'):
        return

    status, reason, msg = _httputil.valid_status(response.status)

    etag = response.headers.get('ETag')

    # Automatic ETag generation. See warning in docstring.
    if etag:
        if debug:
            cherrypy.log('ETag already set: %s' % etag, 'TOOLS.ETAGS')
    elif not autotags:
        if debug:
            cherrypy.log('Autotags off', 'TOOLS.ETAGS')
    elif status != 200:
        if debug:
            cherrypy.log('Status not 200', 'TOOLS.ETAGS')
    else:
        etag = response.collapse_body()
        etag = '"%s"' % md5(etag).hexdigest()
        if debug:
            cherrypy.log('Setting ETag: %s' % etag, 'TOOLS.ETAGS')
        response.headers['ETag'] = etag

    response.ETag = etag

    # "If the request would, without the If-Match header field, result in
    # anything other than a 2xx or 412 status, then the If-Match header
    # MUST be ignored."
    if debug:
        cherrypy.log('Status: %s' % status, 'TOOLS.ETAGS')
    if status >= 200 and status <= 299:
        request = cherrypy.serving.request

        conditions = request.headers.elements('If-Match') or []
        conditions = [str(x) for x in conditions]
        if debug:
            cherrypy.log('If-Match conditions: %s' % repr(conditions),
                         'TOOLS.ETAGS')
        if conditions and not (conditions == ['*'] or etag in conditions):
            raise cherrypy.HTTPError(412, 'If-Match failed: ETag %r did '
                                     'not match %r' % (etag, conditions))

        conditions = request.headers.elements('If-None-Match') or []
        conditions = [str(x) for x in conditions]
        if debug:
            cherrypy.log('If-None-Match conditions: %s' % repr(conditions),
                         'TOOLS.ETAGS')
        if conditions == ['*'] or etag in conditions:
            if debug:
                cherrypy.log('request.method: %s' %
                             request.method, 'TOOLS.ETAGS')
            if request.method in ('GET', 'HEAD'):
                raise cherrypy.HTTPRedirect([], 304)
            else:
                raise cherrypy.HTTPError(412, 'If-None-Match failed: ETag %r '
                                         'matched %r' % (etag, conditions))


def validate_since():
    """Validate the current Last-Modified against If-Modified-Since headers.

    If no code has set the Last-Modified response header, then no validation
    will be performed.
    """
    response = cherrypy.serving.response
    lastmod = response.headers.get('Last-Modified')
    if lastmod:
        status, reason, msg = _httputil.valid_status(response.status)

        request = cherrypy.serving.request

        since = request.headers.get('If-Unmodified-Since')
        if since and since != lastmod:
            if (status >= 200 and status <= 299) or status == 412:
                raise cherrypy.HTTPError(412)

        since = request.headers.get('If-Modified-Since')
        if since and since == lastmod:
            if (status >= 200 and status <= 299) or status == 304:
                if request.method in ('GET', 'HEAD'):
                    raise cherrypy.HTTPRedirect([], 304)
                else:
                    raise cherrypy.HTTPError(412)


#                                Tool code                                #

def allow(methods=None, debug=False):
    """Raise 405 if request.method not in methods (default ['GET', 'HEAD']).

    The given methods are case-insensitive, and may be in any order.
    If only one method is allowed, you may supply a single string;
    if more than one, supply a list of strings.

    Regardless of whether the current method is allowed or not, this
    also emits an 'Allow' response header, containing the given methods.
    """
    if not isinstance(methods, (tuple, list)):
        methods = [methods]
    methods = [m.upper() for m in methods if m]
    if not methods:
        methods = ['GET', 'HEAD']
    elif 'GET' in methods and 'HEAD' not in methods:
        methods.append('HEAD')

    cherrypy.response.headers['Allow'] = ', '.join(methods)
    if cherrypy.request.method not in methods:
        if debug:
            cherrypy.log('request.method %r not in methods %r' %
                         (cherrypy.request.method, methods), 'TOOLS.ALLOW')
        raise cherrypy.HTTPError(405)
    else:
        if debug:
            cherrypy.log('request.method %r in methods %r' %
                         (cherrypy.request.method, methods), 'TOOLS.ALLOW')


def proxy(base=None, local='X-Forwarded-Host', remote='X-Forwarded-For',
          scheme='X-Forwarded-Proto', debug=False):
    """Change the base URL (scheme://host[:port][/path]).

    For running a CP server behind Apache, lighttpd, or other HTTP server.

    For Apache and lighttpd, you should leave the 'local' argument at the
    default value of 'X-Forwarded-Host'. For Squid, you probably want to set
    tools.proxy.local = 'Origin'.

    If you want the new request.base to include path info (not just the host),
    you must explicitly set base to the full base path, and ALSO set 'local'
    to '', so that the X-Forwarded-Host request header (which never includes
    path info) does not override it. Regardless, the value for 'base' MUST
    NOT end in a slash.

    cherrypy.request.remote.ip (the IP address of the client) will be
    rewritten if the header specified by the 'remote' arg is valid.
    By default, 'remote' is set to 'X-Forwarded-For'. If you do not
    want to rewrite remote.ip, set the 'remote' arg to an empty string.
    """

    request = cherrypy.serving.request

    if scheme:
        s = request.headers.get(scheme, None)
        if debug:
            cherrypy.log('Testing scheme %r:%r' % (scheme, s), 'TOOLS.PROXY')
        if s == 'on' and 'ssl' in scheme.lower():
            # This handles e.g. webfaction's 'X-Forwarded-Ssl: on' header
            scheme = 'https'
        else:
            # This is for lighttpd/pound/Mongrel's 'X-Forwarded-Proto: https'
            scheme = s
    if not scheme:
        scheme = request.base[:request.base.find('://')]

    if local:
        lbase = request.headers.get(local, None)
        if debug:
            cherrypy.log('Testing local %r:%r' % (local, lbase), 'TOOLS.PROXY')
        if lbase is not None:
            base = lbase.split(',')[0]
    if not base:
        default = urllib.parse.urlparse(request.base).netloc
        base = request.headers.get('Host', default)

    if base.find('://') == -1:
        # add http:// or https:// if needed
        base = scheme + '://' + base

    request.base = base

    if remote:
        xff = request.headers.get(remote)
        if debug:
            cherrypy.log('Testing remote %r:%r' % (remote, xff), 'TOOLS.PROXY')
        if xff:
            if remote == 'X-Forwarded-For':
                # Grab the first IP in a comma-separated list. Ref #1268.
                xff = next(ip.strip() for ip in xff.split(','))
            request.remote.ip = xff


def ignore_headers(headers=('Range',), debug=False):
    """Delete request headers whose field names are included in 'headers'.

    This is a useful tool for working behind certain HTTP servers;
    for example, Apache duplicates the work that CP does for 'Range'
    headers, and will doubly-truncate the response.
    """
    request = cherrypy.serving.request
    for name in headers:
        if name in request.headers:
            if debug:
                cherrypy.log('Ignoring request header %r' % name,
                             'TOOLS.IGNORE_HEADERS')
            del request.headers[name]


def response_headers(headers=None, debug=False):
    """Set headers on the response."""
    if debug:
        cherrypy.log('Setting response headers: %s' % repr(headers),
                     'TOOLS.RESPONSE_HEADERS')
    for name, value in (headers or []):
        cherrypy.serving.response.headers[name] = value


response_headers.failsafe = True


def referer(pattern, accept=True, accept_missing=False, error=403,
            message='Forbidden Referer header.', debug=False):
    """Raise HTTPError if Referer header does/does not match the given pattern.

    pattern
        A regular expression pattern to test against the Referer.

    accept
        If True, the Referer must match the pattern; if False,
        the Referer must NOT match the pattern.

    accept_missing
        If True, permit requests with no Referer header.

    error
        The HTTP error code to return to the client on failure.

    message
        A string to include in the response body on failure.

    """
    try:
        ref = cherrypy.serving.request.headers['Referer']
        match = bool(re.match(pattern, ref))
        if debug:
            cherrypy.log('Referer %r matches %r' % (ref, pattern),
                         'TOOLS.REFERER')
        if accept == match:
            return
    except KeyError:
        if debug:
            cherrypy.log('No Referer header', 'TOOLS.REFERER')
        if accept_missing:
            return

    raise cherrypy.HTTPError(error, message)


class SessionAuth(object):

    """Assert that the user is logged in."""

    session_key = 'username'
    debug = False

    def check_username_and_password(self, username, password):
        pass

    def anonymous(self):
        """Provide a temporary user name for anonymous users."""
        pass

    def on_login(self, username):
        pass

    def on_logout(self, username):
        pass

    def on_check(self, username):
        pass

    def login_screen(self, from_page='..', username='', error_msg='',
                     **kwargs):
        return (six.text_type("""<html><body>
Message: %(error_msg)s
<form method="post" action="do_login">
    Login: <input type="text" name="username" value="%(username)s" size="10" />
    <br />
    Password: <input type="password" name="password" size="10" />
    <br />
    <input type="hidden" name="from_page" value="%(from_page)s" />
    <br />
    <input type="submit" />
</form>
</body></html>""") % vars()).encode('utf-8')

    def do_login(self, username, password, from_page='..', **kwargs):
        """Login. May raise redirect, or return True if request handled."""
        response = cherrypy.serving.response
        error_msg = self.check_username_and_password(username, password)
        if error_msg:
            body = self.login_screen(from_page, username, error_msg)
            response.body = body
            if 'Content-Length' in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers['Content-Length']
            return True
        else:
            cherrypy.serving.request.login = username
            cherrypy.session[self.session_key] = username
            self.on_login(username)
            raise cherrypy.HTTPRedirect(from_page or '/')

    def do_logout(self, from_page='..', **kwargs):
        """Logout. May raise redirect, or return True if request handled."""
        sess = cherrypy.session
        username = sess.get(self.session_key)
        sess[self.session_key] = None
        if username:
            cherrypy.serving.request.login = None
            self.on_logout(username)
        raise cherrypy.HTTPRedirect(from_page)

    def do_check(self):
        """Assert username. Raise redirect, or return True if request handled.
        """
        sess = cherrypy.session
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        username = sess.get(self.session_key)
        if not username:
            sess[self.session_key] = username = self.anonymous()
            self._debug_message('No session[username], trying anonymous')
        if not username:
            url = cherrypy.url(qs=request.query_string)
            self._debug_message(
                'No username, routing to login_screen with from_page %(url)r',
                locals(),
            )
            response.body = self.login_screen(url)
            if 'Content-Length' in response.headers:
                # Delete Content-Length header so finalize() recalcs it.
                del response.headers['Content-Length']
            return True
        self._debug_message('Setting request.login to %(username)r', locals())
        request.login = username
        self.on_check(username)

    def _debug_message(self, template, context={}):
        if not self.debug:
            return
        cherrypy.log(template % context, 'TOOLS.SESSAUTH')

    def run(self):
        request = cherrypy.serving.request
        response = cherrypy.serving.response

        path = request.path_info
        if path.endswith('login_screen'):
            self._debug_message('routing %(path)r to login_screen', locals())
            response.body = self.login_screen()
            return True
        elif path.endswith('do_login'):
            if request.method != 'POST':
                response.headers['Allow'] = 'POST'
                self._debug_message('do_login requires POST')
                raise cherrypy.HTTPError(405)
            self._debug_message('routing %(path)r to do_login', locals())
            return self.do_login(**request.params)
        elif path.endswith('do_logout'):
            if request.method != 'POST':
                response.headers['Allow'] = 'POST'
                raise cherrypy.HTTPError(405)
            self._debug_message('routing %(path)r to do_logout', locals())
            return self.do_logout(**request.params)
        else:
            self._debug_message('No special path, running do_check')
            return self.do_check()


def session_auth(**kwargs):
    sa = SessionAuth()
    for k, v in kwargs.items():
        setattr(sa, k, v)
    return sa.run()


session_auth.__doc__ = (
    """Session authentication hook.

    Any attribute of the SessionAuth class may be overridden via a keyword arg
    to this function:

    """ + '\n'.join(['%s: %s' % (k, type(getattr(SessionAuth, k)).__name__)
                     for k in dir(SessionAuth) if not k.startswith('__')])
)


def log_traceback(severity=logging.ERROR, debug=False):
    """Write the last error's traceback to the cherrypy error log."""
    cherrypy.log('', 'HTTP', severity=severity, traceback=True)


def log_request_headers(debug=False):
    """Write request headers to the cherrypy error log."""
    h = ['  %s: %s' % (k, v) for k, v in cherrypy.serving.request.header_list]
    cherrypy.log('\nRequest Headers:\n' + '\n'.join(h), 'HTTP')


def log_hooks(debug=False):
    """Write request.hooks to the cherrypy error log."""
    request = cherrypy.serving.request

    msg = []
    # Sort by the standard points if possible.
    from cherrypy import _cprequest
    points = _cprequest.hookpoints
    for k in request.hooks.keys():
        if k not in points:
            points.append(k)

    for k in points:
        msg.append('    %s:' % k)
        v = request.hooks.get(k, [])
        v.sort()
        for h in v:
            msg.append('        %r' % h)
    cherrypy.log('\nRequest Hooks for ' + cherrypy.url() +
                 ':\n' + '\n'.join(msg), 'HTTP')


def redirect(url='', internal=True, debug=False):
    """Raise InternalRedirect or HTTPRedirect to the given url."""
    if debug:
        cherrypy.log('Redirecting %sto: %s' %
                     ({True: 'internal ', False: ''}[internal], url),
                     'TOOLS.REDIRECT')
    if internal:
        raise cherrypy.InternalRedirect(url)
    else:
        raise cherrypy.HTTPRedirect(url)


def trailing_slash(missing=True, extra=False, status=None, debug=False):
    """Redirect if path_info has (missing|extra) trailing slash."""
    request = cherrypy.serving.request
    pi = request.path_info

    if debug:
        cherrypy.log('is_index: %r, missing: %r, extra: %r, path_info: %r' %
                     (request.is_index, missing, extra, pi),
                     'TOOLS.TRAILING_SLASH')
    if request.is_index is True:
        if missing:
            if not pi.endswith('/'):
                new_url = cherrypy.url(pi + '/', request.query_string)
                raise cherrypy.HTTPRedirect(new_url, status=status or 301)
    elif request.is_index is False:
        if extra:
            # If pi == '/', don't redirect to ''!
            if pi.endswith('/') and pi != '/':
                new_url = cherrypy.url(pi[:-1], request.query_string)
                raise cherrypy.HTTPRedirect(new_url, status=status or 301)


def flatten(debug=False):
    """Wrap response.body in a generator that recursively iterates over body.

    This allows cherrypy.response.body to consist of 'nested generators';
    that is, a set of generators that yield generators.
    """
    def flattener(input):
        numchunks = 0
        for x in input:
            if not is_iterator(x):
                numchunks += 1
                yield x
            else:
                for y in flattener(x):
                    numchunks += 1
                    yield y
        if debug:
            cherrypy.log('Flattened %d chunks' % numchunks, 'TOOLS.FLATTEN')
    response = cherrypy.serving.response
    response.body = flattener(response.body)


def accept(media=None, debug=False):
    """Return the client's preferred media-type (from the given Content-Types).

    If 'media' is None (the default), no test will be performed.

    If 'media' is provided, it should be the Content-Type value (as a string)
    or values (as a list or tuple of strings) which the current resource
    can emit. The client's acceptable media ranges (as declared in the
    Accept request header) will be matched in order to these Content-Type
    values; the first such string is returned. That is, the return value
    will always be one of the strings provided in the 'media' arg (or None
    if 'media' is None).

    If no match is found, then HTTPError 406 (Not Acceptable) is raised.
    Note that most web browsers send */* as a (low-quality) acceptable
    media range, which should match any Content-Type. In addition, "...if
    no Accept header field is present, then it is assumed that the client
    accepts all media types."

    Matching types are checked in order of client preference first,
    and then in the order of the given 'media' values.

    Note that this function does not honor accept-params (other than "q").
    """
    if not media:
        return
    if isinstance(media, text_or_bytes):
        media = [media]
    request = cherrypy.serving.request

    # Parse the Accept request header, and try to match one
    # of the requested media-ranges (in order of preference).
    ranges = request.headers.elements('Accept')
    if not ranges:
        # Any media type is acceptable.
        if debug:
            cherrypy.log('No Accept header elements', 'TOOLS.ACCEPT')
        return media[0]
    else:
        # Note that 'ranges' is sorted in order of preference
        for element in ranges:
            if element.qvalue > 0:
                if element.value == '*/*':
                    # Matches any type or subtype
                    if debug:
                        cherrypy.log('Match due to */*', 'TOOLS.ACCEPT')
                    return media[0]
                elif element.value.endswith('/*'):
                    # Matches any subtype
                    mtype = element.value[:-1]  # Keep the slash
                    for m in media:
                        if m.startswith(mtype):
                            if debug:
                                cherrypy.log('Match due to %s' % element.value,
                                             'TOOLS.ACCEPT')
                            return m
                else:
                    # Matches exact value
                    if element.value in media:
                        if debug:
                            cherrypy.log('Match due to %s' % element.value,
                                         'TOOLS.ACCEPT')
                        return element.value

    # No suitable media-range found.
    ah = request.headers.get('Accept')
    if ah is None:
        msg = 'Your client did not send an Accept header.'
    else:
        msg = 'Your client sent this Accept header: %s.' % ah
    msg += (' But this resource only emits these media types: %s.' %
            ', '.join(media))
    raise cherrypy.HTTPError(406, msg)


class MonitoredHeaderMap(_httputil.HeaderMap):

    def transform_key(self, key):
        self.accessed_headers.add(key)
        return super(MonitoredHeaderMap, self).transform_key(key)

    def __init__(self):
        self.accessed_headers = set()
        super(MonitoredHeaderMap, self).__init__()


def autovary(ignore=None, debug=False):
    """Auto-populate the Vary response header based on request.header access.
    """
    request = cherrypy.serving.request

    req_h = request.headers
    request.headers = MonitoredHeaderMap()
    request.headers.update(req_h)
    if ignore is None:
        ignore = set(['Content-Disposition', 'Content-Length', 'Content-Type'])

    def set_response_header():
        resp_h = cherrypy.serving.response.headers
        v = set([e.value for e in resp_h.elements('Vary')])
        if debug:
            cherrypy.log(
                'Accessed headers: %s' % request.headers.accessed_headers,
                'TOOLS.AUTOVARY')
        v = v.union(request.headers.accessed_headers)
        v = v.difference(ignore)
        v = list(v)
        v.sort()
        resp_h['Vary'] = ', '.join(v)
    request.hooks.attach('before_finalize', set_response_header, 95)


def convert_params(exception=ValueError, error=400):
    """Convert request params based on function annotations, with error handling.

    exception
        Exception class to catch.

    status
        The HTTP error code to return to the client on failure.
    """
    request = cherrypy.serving.request
    types = request.handler.callable.__annotations__
    with cherrypy.HTTPError.handle(exception, error):
        for key in set(types).intersection(request.params):
            request.params[key] = types[key](request.params[key])

[((40, 26, 40, 65), 'cherrypy.lib.httputil.valid_status', '_httputil.valid_status', ({(40, 49, 40, 64): 'response.status'}, {}), '(response.status)', True, 'from cherrypy.lib import httputil as _httputil\n'), ((282, 10, 282, 44), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(282, 29, 282, 34): 'error', (282, 36, 282, 43): 'message'}, {}), '(error, message)', False, 'import cherrypy\n'), ((428, 4, 428, 63), 'cherrypy.log', 'cherrypy.log', (), '', False, 'import cherrypy\n'), ((587, 10, 587, 38), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(587, 29, 587, 32): '(406)', (587, 34, 587, 37): 'msg'}, {}), '(406, msg)', False, 'import cherrypy\n'), ((67, 8, 67, 58), 'cherrypy.log', 'cherrypy.log', ({(67, 21, 67, 42): "('Status: %s' % status)", (67, 44, 67, 57): '"""TOOLS.ETAGS"""'}, {}), "('Status: %s' % status, 'TOOLS.ETAGS')", False, 'import cherrypy\n'), ((105, 30, 105, 69), 'cherrypy.lib.httputil.valid_status', '_httputil.valid_status', ({(105, 53, 105, 68): 'response.status'}, {}), '(response.status)', True, 'from cherrypy.lib import httputil as _httputil\n'), ((148, 14, 148, 37), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(148, 33, 148, 36): '(405)'}, {}), '(405)', False, 'import cherrypy\n'), ((348, 14, 348, 46), 'cherrypy.HTTPRedirect', 'cherrypy.HTTPRedirect', ({(348, 36, 348, 45): 'from_page'}, {}), '(from_page)', False, 'import cherrypy\n'), ((379, 8, 379, 58), 'cherrypy.log', 'cherrypy.log', ({(379, 21, 379, 39): '(template % context)', (379, 41, 379, 57): '"""TOOLS.SESSAUTH"""'}, {}), "(template % context, 'TOOLS.SESSAUTH')", False, 'import cherrypy\n'), ((462, 8, 464, 38), 'cherrypy.log', 'cherrypy.log', ({(462, 21, 463, 68): "('Redirecting %sto: %s' % ({(True): 'internal ', (False): ''}[internal], url))", (464, 21, 464, 37): '"""TOOLS.REDIRECT"""'}, {}), "('Redirecting %sto: %s' % ({(True): 'internal ', (False): ''}[\n    internal], url), 'TOOLS.REDIRECT')", False, 'import cherrypy\n'), ((466, 14, 466, 44), 'cherrypy.InternalRedirect', 'cherrypy.InternalRedirect', ({(466, 40, 466, 43): 'url'}, {}), '(url)', False, 'import cherrypy\n'), ((468, 14, 468, 40), 'cherrypy.HTTPRedirect', 'cherrypy.HTTPRedirect', ({(468, 36, 468, 39): 'url'}, {}), '(url)', False, 'import cherrypy\n'), ((477, 8, 479, 44), 'cherrypy.log', 'cherrypy.log', ({(477, 21, 478, 59): "('is_index: %r, missing: %r, extra: %r, path_info: %r' % (request.is_index,\n    missing, extra, pi))", (479, 21, 479, 43): '"""TOOLS.TRAILING_SLASH"""'}, {}), "('is_index: %r, missing: %r, extra: %r, path_info: %r' % (\n    request.is_index, missing, extra, pi), 'TOOLS.TRAILING_SLASH')", False, 'import cherrypy\n'), ((638, 9, 638, 52), 'cherrypy.HTTPError.handle', 'cherrypy.HTTPError.handle', ({(638, 35, 638, 44): 'exception', (638, 46, 638, 51): 'error'}, {}), '(exception, error)', False, 'import cherrypy\n'), ((47, 12, 47, 70), 'cherrypy.log', 'cherrypy.log', ({(47, 25, 47, 54): "('ETag already set: %s' % etag)", (47, 56, 47, 69): '"""TOOLS.ETAGS"""'}, {}), "('ETag already set: %s' % etag, 'TOOLS.ETAGS')", False, 'import cherrypy\n'), ((77, 18, 78, 73), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(77, 37, 77, 40): '(412)', (77, 42, 78, 72): "('If-Match failed: ETag %r did not match %r' % (etag, conditions))"}, {}), "(412, 'If-Match failed: ETag %r did not match %r' % (etag,\n    conditions))", False, 'import cherrypy\n'), ((146, 12, 147, 75), 'cherrypy.log', 'cherrypy.log', ({(146, 25, 147, 59): "('request.method %r not in methods %r' % (cherrypy.request.method, methods))", (147, 61, 147, 74): '"""TOOLS.ALLOW"""'}, {}), "('request.method %r not in methods %r' % (cherrypy.request.\n    method, methods), 'TOOLS.ALLOW')", False, 'import cherrypy\n'), ((151, 12, 152, 75), 'cherrypy.log', 'cherrypy.log', ({(151, 25, 152, 59): "('request.method %r in methods %r' % (cherrypy.request.method, methods))", (152, 61, 152, 74): '"""TOOLS.ALLOW"""'}, {}), "('request.method %r in methods %r' % (cherrypy.request.method,\n    methods), 'TOOLS.ALLOW')", False, 'import cherrypy\n'), ((182, 12, 182, 77), 'cherrypy.log', 'cherrypy.log', ({(182, 25, 182, 61): "('Testing scheme %r:%r' % (scheme, s))", (182, 63, 182, 76): '"""TOOLS.PROXY"""'}, {}), "('Testing scheme %r:%r' % (scheme, s), 'TOOLS.PROXY')", False, 'import cherrypy\n'), ((195, 12, 195, 79), 'cherrypy.log', 'cherrypy.log', ({(195, 25, 195, 63): "('Testing local %r:%r' % (local, lbase))", (195, 65, 195, 78): '"""TOOLS.PROXY"""'}, {}), "('Testing local %r:%r' % (local, lbase), 'TOOLS.PROXY')", False, 'import cherrypy\n'), ((199, 18, 199, 53), 'six.moves.urllib.parse.urlparse', 'urllib.parse.urlparse', ({(199, 40, 199, 52): 'request.base'}, {}), '(request.base)', False, 'from six.moves import urllib\n'), ((211, 12, 211, 79), 'cherrypy.log', 'cherrypy.log', ({(211, 25, 211, 63): "('Testing remote %r:%r' % (remote, xff))", (211, 65, 211, 78): '"""TOOLS.PROXY"""'}, {}), "('Testing remote %r:%r' % (remote, xff), 'TOOLS.PROXY')", False, 'import cherrypy\n'), ((270, 21, 270, 43), 're.match', 're.match', ({(270, 30, 270, 37): 'pattern', (270, 39, 270, 42): 'ref'}, {}), '(pattern, ref)', False, 'import re\n'), ((272, 12, 273, 41), 'cherrypy.log', 'cherrypy.log', ({(272, 25, 272, 65): "('Referer %r matches %r' % (ref, pattern))", (273, 25, 273, 40): '"""TOOLS.REFERER"""'}, {}), "('Referer %r matches %r' % (ref, pattern), 'TOOLS.REFERER')", False, 'import cherrypy\n'), ((338, 18, 338, 57), 'cherrypy.HTTPRedirect', 'cherrypy.HTTPRedirect', ({(338, 40, 338, 56): "(from_page or '/')"}, {}), "(from_page or '/')", False, 'import cherrypy\n'), ((362, 18, 362, 55), 'cherrypy.url', 'cherrypy.url', (), '', False, 'import cherrypy\n'), ((510, 12, 510, 76), 'cherrypy.log', 'cherrypy.log', ({(510, 25, 510, 58): "('Flattened %d chunks' % numchunks)", (510, 60, 510, 75): '"""TOOLS.FLATTEN"""'}, {}), "('Flattened %d chunks' % numchunks, 'TOOLS.FLATTEN')", False, 'import cherrypy\n'), ((551, 12, 551, 69), 'cherrypy.log', 'cherrypy.log', ({(551, 25, 551, 52): '"""No Accept header elements"""', (551, 54, 551, 68): '"""TOOLS.ACCEPT"""'}, {}), "('No Accept header elements', 'TOOLS.ACCEPT')", False, 'import cherrypy\n'), ((616, 12, 618, 33), 'cherrypy.log', 'cherrypy.log', ({(617, 16, 617, 73): "('Accessed headers: %s' % request.headers.accessed_headers)", (618, 16, 618, 32): '"""TOOLS.AUTOVARY"""'}, {}), "('Accessed headers: %s' % request.headers.accessed_headers,\n    'TOOLS.AUTOVARY')", False, 'import cherrypy\n'), ((50, 12, 50, 55), 'cherrypy.log', 'cherrypy.log', ({(50, 25, 50, 39): '"""Autotags off"""', (50, 41, 50, 54): '"""TOOLS.ETAGS"""'}, {}), "('Autotags off', 'TOOLS.ETAGS')", False, 'import cherrypy\n'), ((87, 16, 88, 59), 'cherrypy.log', 'cherrypy.log', ({(87, 29, 88, 43): "('request.method: %s' % request.method)", (88, 45, 88, 58): '"""TOOLS.ETAGS"""'}, {}), "('request.method: %s' % request.method, 'TOOLS.ETAGS')", False, 'import cherrypy\n'), ((90, 22, 90, 52), 'cherrypy.HTTPRedirect', 'cherrypy.HTTPRedirect', ({(90, 44, 90, 46): '[]', (90, 48, 90, 51): '(304)'}, {}), '([], 304)', False, 'import cherrypy\n'), ((92, 22, 93, 75), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(92, 41, 92, 44): '(412)', (92, 46, 93, 74): "('If-None-Match failed: ETag %r matched %r' % (etag, conditions))"}, {}), "(412, 'If-None-Match failed: ETag %r matched %r' % (etag,\n    conditions))", False, 'import cherrypy\n'), ((112, 22, 112, 45), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(112, 41, 112, 44): '(412)'}, {}), '(412)', False, 'import cherrypy\n'), ((230, 16, 231, 52), 'cherrypy.log', 'cherrypy.log', ({(230, 29, 230, 64): "('Ignoring request header %r' % name)", (231, 29, 231, 51): '"""TOOLS.IGNORE_HEADERS"""'}, {}), "('Ignoring request header %r' % name, 'TOOLS.IGNORE_HEADERS')", False, 'import cherrypy\n'), ((278, 12, 278, 62), 'cherrypy.log', 'cherrypy.log', ({(278, 25, 278, 44): '"""No Referer header"""', (278, 46, 278, 61): '"""TOOLS.REFERER"""'}, {}), "('No Referer header', 'TOOLS.REFERER')", False, 'import cherrypy\n'), ((483, 26, 483, 70), 'cherrypy.url', 'cherrypy.url', ({(483, 39, 483, 47): "pi + '/'", (483, 49, 483, 69): 'request.query_string'}, {}), "(pi + '/', request.query_string)", False, 'import cherrypy\n'), ((484, 22, 484, 74), 'cherrypy.HTTPRedirect', 'cherrypy.HTTPRedirect', (), '', False, 'import cherrypy\n'), ((502, 19, 502, 33), 'cherrypy.lib.is_iterator', 'is_iterator', ({(502, 31, 502, 32): 'x'}, {}), '(x)', False, 'from cherrypy.lib import is_iterator\n'), ((53, 12, 53, 57), 'cherrypy.log', 'cherrypy.log', ({(53, 25, 53, 41): '"""Status not 200"""', (53, 43, 53, 56): '"""TOOLS.ETAGS"""'}, {}), "('Status not 200', 'TOOLS.ETAGS')", False, 'import cherrypy\n'), ((58, 12, 58, 66), 'cherrypy.log', 'cherrypy.log', ({(58, 25, 58, 50): "('Setting ETag: %s' % etag)", (58, 52, 58, 65): '"""TOOLS.ETAGS"""'}, {}), "('Setting ETag: %s' % etag, 'TOOLS.ETAGS')", False, 'import cherrypy\n'), ((118, 26, 118, 56), 'cherrypy.HTTPRedirect', 'cherrypy.HTTPRedirect', ({(118, 48, 118, 50): '[]', (118, 52, 118, 55): '(304)'}, {}), '([], 304)', False, 'import cherrypy\n'), ((120, 26, 120, 49), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(120, 45, 120, 48): '(412)'}, {}), '(412)', False, 'import cherrypy\n'), ((310, 16, 321, 18), 'six.text_type', 'six.text_type', ({(310, 30, 321, 17): '"""<html><body>\nMessage: %(error_msg)s\n<form method="post" action="do_login">\n    Login: <input type="text" name="username" value="%(username)s" size="10" />\n    <br />\n    Password: <input type="password" name="password" size="10" />\n    <br />\n    <input type="hidden" name="from_page" value="%(from_page)s" />\n    <br />\n    <input type="submit" />\n</form>\n</body></html>"""'}, {}), '(\n    """<html><body>\nMessage: %(error_msg)s\n<form method="post" action="do_login">\n    Login: <input type="text" name="username" value="%(username)s" size="10" />\n    <br />\n    Password: <input type="password" name="password" size="10" />\n    <br />\n    <input type="hidden" name="from_page" value="%(from_page)s" />\n    <br />\n    <input type="submit" />\n</form>\n</body></html>"""\n    )', False, 'import six\n'), ((394, 22, 394, 45), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(394, 41, 394, 44): '(405)'}, {}), '(405)', False, 'import cherrypy\n'), ((455, 42, 455, 56), 'cherrypy.url', 'cherrypy.url', ({}, {}), '()', False, 'import cherrypy\n'), ((489, 26, 489, 69), 'cherrypy.url', 'cherrypy.url', ({(489, 39, 489, 46): 'pi[:-1]', (489, 48, 489, 68): 'request.query_string'}, {}), '(pi[:-1], request.query_string)', False, 'import cherrypy\n'), ((490, 22, 490, 74), 'cherrypy.HTTPRedirect', 'cherrypy.HTTPRedirect', (), '', False, 'import cherrypy\n'), ((400, 22, 400, 45), 'cherrypy.HTTPError', 'cherrypy.HTTPError', ({(400, 41, 400, 44): '(405)'}, {}), '(405)', False, 'import cherrypy\n'), ((560, 24, 560, 72), 'cherrypy.log', 'cherrypy.log', ({(560, 37, 560, 55): '"""Match due to */*"""', (560, 57, 560, 71): '"""TOOLS.ACCEPT"""'}, {}), "('Match due to */*', 'TOOLS.ACCEPT')", False, 'import cherrypy\n'), ((56, 24, 56, 33), 'hashlib.md5', 'md5', ({(56, 28, 56, 32): 'etag'}, {}), '(etag)', False, 'from hashlib import md5\n'), ((575, 28, 576, 56), 'cherrypy.log', 'cherrypy.log', ({(575, 41, 575, 74): "('Match due to %s' % element.value)", (576, 41, 576, 55): '"""TOOLS.ACCEPT"""'}, {}), "('Match due to %s' % element.value, 'TOOLS.ACCEPT')", False, 'import cherrypy\n'), ((568, 32, 569, 60), 'cherrypy.log', 'cherrypy.log', ({(568, 45, 568, 78): "('Match due to %s' % element.value)", (569, 45, 569, 59): '"""TOOLS.ACCEPT"""'}, {}), "('Match due to %s' % element.value, 'TOOLS.ACCEPT')", False, 'import cherrypy\n')]