{
    "file_diffs": [
        {
            "old_file_content": "#!/usr/bin/env python\n#\n# Copyright 2011 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Miscellaneous network utility code.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport errno\nimport os\nimport sys\nimport socket\nimport stat\n\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nfrom tornado.platform.auto import set_close_exec\nfrom tornado.util import PY3, Configurable, errno_from_exception\n\ntry:\n    import ssl\nexcept ImportError:\n    # ssl is not available on Google App Engine\n    ssl = None\n\nif PY3:\n    xrange = range\n\nif ssl is not None:\n    # Note that the naming of ssl.Purpose is confusing; the purpose\n    # of a context is to authentiate the opposite side of the connection.\n    _client_ssl_defaults = ssl.create_default_context(\n        ssl.Purpose.SERVER_AUTH)\n    _server_ssl_defaults = ssl.create_default_context(\n        ssl.Purpose.CLIENT_AUTH)\n    if hasattr(ssl, 'OP_NO_COMPRESSION'):\n        # See netutil.ssl_options_to_context\n        _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION\n        _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION\nelse:\n    # Google App Engine\n    _client_ssl_defaults = dict(cert_reqs=None,\n                                ca_certs=None)\n    _server_ssl_defaults = {}\n\n# ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode,\n# getaddrinfo attempts to import encodings.idna. If this is done at\n# module-import time, the import lock is already held by the main thread,\n# leading to deadlock. Avoid it by caching the idna encoder on the main\n# thread now.\nu'foo'.encode('idna')\n\n# For undiagnosed reasons, 'latin1' codec may also need to be preloaded.\nu'foo'.encode('latin1')\n\n# These errnos indicate that a non-blocking operation must be retried\n# at a later time.  On most platforms they're the same value, but on\n# some they differ.\n_ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)\n\nif hasattr(errno, \"WSAEWOULDBLOCK\"):\n    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)  # type: ignore\n\n# Default backlog used when calling sock.listen()\n_DEFAULT_BACKLOG = 128\n\n\ndef bind_sockets(port, address=None, family=socket.AF_UNSPEC,\n                 backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False):\n    \"\"\"Creates listening sockets bound to the given port and address.\n\n    Returns a list of socket objects (multiple sockets are returned if\n    the given address maps to multiple IP addresses, which is most common\n    for mixed IPv4 and IPv6 use).\n\n    Address may be either an IP address or hostname.  If it's a hostname,\n    the server will listen on all IP addresses associated with the\n    name.  Address may be an empty string or None to listen on all\n    available interfaces.  Family may be set to either `socket.AF_INET`\n    or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n    both will be used if available.\n\n    The ``backlog`` argument has the same meaning as for\n    `socket.listen() <socket.socket.listen>`.\n\n    ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like\n    ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.\n\n    ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket\n    in the list. If your platform doesn't support this option ValueError will\n    be raised.\n    \"\"\"\n    if reuse_port and not hasattr(socket, \"SO_REUSEPORT\"):\n        raise ValueError(\"the platform doesn't support SO_REUSEPORT\")\n\n    sockets = []\n    if address == \"\":\n        address = None\n    if not socket.has_ipv6 and family == socket.AF_UNSPEC:\n        # Python can be compiled with --disable-ipv6, which causes\n        # operations on AF_INET6 sockets to fail, but does not\n        # automatically exclude those results from getaddrinfo\n        # results.\n        # http://bugs.python.org/issue16208\n        family = socket.AF_INET\n    if flags is None:\n        flags = socket.AI_PASSIVE\n    bound_port = None\n    for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,\n                                      0, flags)):\n        af, socktype, proto, canonname, sockaddr = res\n        if (sys.platform == 'darwin' and address == 'localhost' and\n                af == socket.AF_INET6 and sockaddr[3] != 0):\n            # Mac OS X includes a link-local address fe80::1%lo0 in the\n            # getaddrinfo results for 'localhost'.  However, the firewall\n            # doesn't understand that this is a local address and will\n            # prompt for access (often repeatedly, due to an apparent\n            # bug in its ability to remember granting access to an\n            # application). Skip these addresses.\n            continue\n        try:\n            sock = socket.socket(af, socktype, proto)\n        except socket.error as e:\n            if errno_from_exception(e) == errno.EAFNOSUPPORT:\n                continue\n            raise\n        set_close_exec(sock.fileno())\n        if os.name != 'nt':\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        if reuse_port:\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n        if af == socket.AF_INET6:\n            # On linux, ipv6 sockets accept ipv4 too by default,\n            # but this makes it impossible to bind to both\n            # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,\n            # separate sockets *must* be used to listen for both ipv4\n            # and ipv6.  For consistency, always disable ipv4 on our\n            # ipv6 sockets and use a separate ipv4 socket when needed.\n            #\n            # Python 2.x on windows doesn't have IPPROTO_IPV6.\n            if hasattr(socket, \"IPPROTO_IPV6\"):\n                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)\n\n        # automatic port allocation with port=None\n        # should bind on the same port on IPv4 and IPv6\n        host, requested_port = sockaddr[:2]\n        if requested_port == 0 and bound_port is not None:\n            sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))\n\n        sock.setblocking(0)\n        sock.bind(sockaddr)\n        bound_port = sock.getsockname()[1]\n        sock.listen(backlog)\n        sockets.append(sock)\n    return sockets\n\n\nif hasattr(socket, 'AF_UNIX'):\n    def bind_unix_socket(file, mode=0o600, backlog=_DEFAULT_BACKLOG):\n        \"\"\"Creates a listening unix socket.\n\n        If a socket with the given name already exists, it will be deleted.\n        If any other file with that name exists, an exception will be\n        raised.\n\n        Returns a socket object (not a list of socket objects like\n        `bind_sockets`)\n        \"\"\"\n        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n        set_close_exec(sock.fileno())\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        sock.setblocking(0)\n        try:\n            st = os.stat(file)\n        except OSError as err:\n            if errno_from_exception(err) != errno.ENOENT:\n                raise\n        else:\n            if stat.S_ISSOCK(st.st_mode):\n                os.remove(file)\n            else:\n                raise ValueError(\"File %s exists and is not a socket\", file)\n        sock.bind(file)\n        os.chmod(file, mode)\n        sock.listen(backlog)\n        return sock\n\n\ndef add_accept_handler(sock, callback):\n    \"\"\"Adds an `.IOLoop` event handler to accept new connections on ``sock``.\n\n    When a connection is accepted, ``callback(connection, address)`` will\n    be run (``connection`` is a socket object, and ``address`` is the\n    address of the other end of the connection).  Note that this signature\n    is different from the ``callback(fd, events)`` signature used for\n    `.IOLoop` handlers.\n\n    A callable is returned which, when called, will remove the `.IOLoop`\n    event handler and stop processing further incoming connections.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.0\n       A callable is returned (``None`` was returned before).\n    \"\"\"\n    io_loop = IOLoop.current()\n    removed = [False]\n\n    def accept_handler(fd, events):\n        # More connections may come in while we're handling callbacks;\n        # to prevent starvation of other tasks we must limit the number\n        # of connections we accept at a time.  Ideally we would accept\n        # up to the number of connections that were waiting when we\n        # entered this method, but this information is not available\n        # (and rearranging this method to call accept() as many times\n        # as possible before running any callbacks would have adverse\n        # effects on load balancing in multiprocess configurations).\n        # Instead, we use the (default) listen backlog as a rough\n        # heuristic for the number of connections we can reasonably\n        # accept at once.\n        for i in xrange(_DEFAULT_BACKLOG):\n            if removed[0]:\n                # The socket was probably closed\n                return\n            try:\n                connection, address = sock.accept()\n            except socket.error as e:\n                # _ERRNO_WOULDBLOCK indicate we have accepted every\n                # connection that is available.\n                if errno_from_exception(e) in _ERRNO_WOULDBLOCK:\n                    return\n                # ECONNABORTED indicates that there was a connection\n                # but it was closed while still in the accept queue.\n                # (observed on FreeBSD).\n                if errno_from_exception(e) == errno.ECONNABORTED:\n                    continue\n                raise\n            set_close_exec(connection.fileno())\n            callback(connection, address)\n\n    def remove_handler():\n        io_loop.remove_handler(sock)\n        removed[0] = True\n\n    io_loop.add_handler(sock, accept_handler, IOLoop.READ)\n    return remove_handler\n\n\ndef is_valid_ip(ip):\n    \"\"\"Returns true if the given string is a well-formed IP address.\n\n    Supports IPv4 and IPv6.\n    \"\"\"\n    if not ip or '\\x00' in ip:\n        # getaddrinfo resolves empty strings to localhost, and truncates\n        # on zero bytes.\n        return False\n    try:\n        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,\n                                 socket.SOCK_STREAM,\n                                 0, socket.AI_NUMERICHOST)\n        return bool(res)\n    except socket.gaierror as e:\n        if e.args[0] == socket.EAI_NONAME:\n            return False\n        raise\n    return True\n\n\nclass Resolver(Configurable):\n    \"\"\"Configurable asynchronous DNS resolver interface.\n\n    By default, a blocking implementation is used (which simply calls\n    `socket.getaddrinfo`).  An alternative implementation can be\n    chosen with the `Resolver.configure <.Configurable.configure>`\n    class method::\n\n        Resolver.configure('tornado.netutil.ThreadedResolver')\n\n    The implementations of this interface included with Tornado are\n\n    * `tornado.netutil.DefaultExecutorResolver`\n    * `tornado.netutil.BlockingResolver` (deprecated)\n    * `tornado.netutil.ThreadedResolver` (deprecated)\n    * `tornado.netutil.OverrideResolver`\n    * `tornado.platform.twisted.TwistedResolver`\n    * `tornado.platform.caresresolver.CaresResolver`\n\n    .. versionchanged:: 5.0\n       The default implementation has changed from `BlockingResolver` to\n       `DefaultExecutorResolver`.\n    \"\"\"\n    @classmethod\n    def configurable_base(cls):\n        return Resolver\n\n    @classmethod\n    def configurable_default(cls):\n        return DefaultExecutorResolver\n\n    def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):\n        \"\"\"Resolves an address.\n\n        The ``host`` argument is a string which may be a hostname or a\n        literal IP address.\n\n        Returns a `.Future` whose result is a list of (family,\n        address) pairs, where address is a tuple suitable to pass to\n        `socket.connect <socket.socket.connect>` (i.e. a ``(host,\n        port)`` pair for IPv4; additional fields may be present for\n        IPv6). If a ``callback`` is passed, it will be run with the\n        result as an argument when it is complete.\n\n        :raises IOError: if the address cannot be resolved.\n\n        .. versionchanged:: 4.4\n           Standardized all implementations to raise `IOError`.\n        \"\"\"\n        raise NotImplementedError()\n\n    def close(self):\n        \"\"\"Closes the `Resolver`, freeing any resources used.\n\n        .. versionadded:: 3.1\n\n        \"\"\"\n        pass\n\n\ndef _resolve_addr(host, port, family=socket.AF_UNSPEC):\n    # On Solaris, getaddrinfo fails if the given port is not found\n    # in /etc/services and no socket type is given, so we must pass\n    # one here.  The socket type used here doesn't seem to actually\n    # matter (we discard the one we get back in the results),\n    # so the addresses we return should still be usable with SOCK_DGRAM.\n    addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)\n    results = []\n    for family, socktype, proto, canonname, address in addrinfo:\n        results.append((family, address))\n    return results\n\n\nclass DefaultExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using `.IOLoop.run_in_executor`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    @gen.coroutine\n    def resolve(self, host, port, family=socket.AF_UNSPEC):\n        result = yield IOLoop.current().run_in_executor(\n            None, _resolve_addr, host, port, family)\n        raise gen.Return(result)\n\n\nclass ExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using a `concurrent.futures.Executor`.\n\n    Use this instead of `ThreadedResolver` when you require additional\n    control over the executor being used.\n\n    The executor will be shut down when the resolver is closed unless\n    ``close_resolver=False``; use this if you want to reuse the same\n    executor elsewhere.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    def initialize(self, executor=None, close_executor=True):\n        self.io_loop = IOLoop.current()\n        if executor is not None:\n            self.executor = executor\n            self.close_executor = close_executor\n        else:\n            self.executor = dummy_executor\n            self.close_executor = False\n\n    def close(self):\n        if self.close_executor:\n            self.executor.shutdown()\n        self.executor = None\n\n    @run_on_executor\n    def resolve(self, host, port, family=socket.AF_UNSPEC):\n        return _resolve_addr(host, port, family)\n\n\nclass BlockingResolver(ExecutorResolver):\n    \"\"\"Default `Resolver` implementation, using `socket.getaddrinfo`.\n\n    The `.IOLoop` will be blocked during the resolution, although the\n    callback will not be run until the next `.IOLoop` iteration.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    def initialize(self):\n        super(BlockingResolver, self).initialize()\n\n\nclass ThreadedResolver(ExecutorResolver):\n    \"\"\"Multithreaded non-blocking `Resolver` implementation.\n\n    Requires the `concurrent.futures` package to be installed\n    (available in the standard library since Python 3.2,\n    installable with ``pip install futures`` in older versions).\n\n    The thread pool size can be configured with::\n\n        Resolver.configure('tornado.netutil.ThreadedResolver',\n                           num_threads=10)\n\n    .. versionchanged:: 3.1\n       All ``ThreadedResolvers`` share a single thread pool, whose\n       size is set by the first one to be created.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    _threadpool = None  # type: ignore\n    _threadpool_pid = None  # type: int\n\n    def initialize(self, num_threads=10):\n        threadpool = ThreadedResolver._create_threadpool(num_threads)\n        super(ThreadedResolver, self).initialize(\n            executor=threadpool, close_executor=False)\n\n    @classmethod\n    def _create_threadpool(cls, num_threads):\n        pid = os.getpid()\n        if cls._threadpool_pid != pid:\n            # Threads cannot survive after a fork, so if our pid isn't what it\n            # was when we created the pool then delete it.\n            cls._threadpool = None\n        if cls._threadpool is None:\n            from concurrent.futures import ThreadPoolExecutor\n            cls._threadpool = ThreadPoolExecutor(num_threads)\n            cls._threadpool_pid = pid\n        return cls._threadpool\n\n\nclass OverrideResolver(Resolver):\n    \"\"\"Wraps a resolver with a mapping of overrides.\n\n    This can be used to make local DNS changes (e.g. for testing)\n    without modifying system-wide settings.\n\n    The mapping can contain either host strings or host-port pairs.\n    \"\"\"\n    def initialize(self, resolver, mapping):\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self):\n        self.resolver.close()\n\n    def resolve(self, host, port, *args, **kwargs):\n        if (host, port) in self.mapping:\n            host, port = self.mapping[(host, port)]\n        elif host in self.mapping:\n            host = self.mapping[host]\n        return self.resolver.resolve(host, port, *args, **kwargs)\n\n\n# These are the keyword arguments to ssl.wrap_socket that must be translated\n# to their SSLContext equivalents (the other arguments are still passed\n# to SSLContext.wrap_socket).\n_SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile',\n                                   'cert_reqs', 'ca_certs', 'ciphers'])\n\n\ndef ssl_options_to_context(ssl_options):\n    \"\"\"Try to convert an ``ssl_options`` dictionary to an\n    `~ssl.SSLContext` object.\n\n    The ``ssl_options`` dictionary contains keywords to be passed to\n    `ssl.wrap_socket`.  In Python 2.7.9+, `ssl.SSLContext` objects can\n    be used instead.  This function converts the dict form to its\n    `~ssl.SSLContext` equivalent, and may be used when a component which\n    accepts both forms needs to upgrade to the `~ssl.SSLContext` version\n    to use features like SNI or NPN.\n    \"\"\"\n    if isinstance(ssl_options, ssl.SSLContext):\n        return ssl_options\n    assert isinstance(ssl_options, dict)\n    assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options\n    # Can't use create_default_context since this interface doesn't\n    # tell us client vs server.\n    context = ssl.SSLContext(\n        ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23))\n    if 'certfile' in ssl_options:\n        context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None))\n    if 'cert_reqs' in ssl_options:\n        context.verify_mode = ssl_options['cert_reqs']\n    if 'ca_certs' in ssl_options:\n        context.load_verify_locations(ssl_options['ca_certs'])\n    if 'ciphers' in ssl_options:\n        context.set_ciphers(ssl_options['ciphers'])\n    if hasattr(ssl, 'OP_NO_COMPRESSION'):\n        # Disable TLS compression to avoid CRIME and related attacks.\n        # This constant depends on openssl version 1.0.\n        # TODO: Do we need to do this ourselves or can we trust\n        # the defaults?\n        context.options |= ssl.OP_NO_COMPRESSION\n    return context\n\n\ndef ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):\n    \"\"\"Returns an ``ssl.SSLSocket`` wrapping the given socket.\n\n    ``ssl_options`` may be either an `ssl.SSLContext` object or a\n    dictionary (as accepted by `ssl_options_to_context`).  Additional\n    keyword arguments are passed to ``wrap_socket`` (either the\n    `~ssl.SSLContext` method or the `ssl` module function as\n    appropriate).\n    \"\"\"\n    context = ssl_options_to_context(ssl_options)\n    if ssl.HAS_SNI:\n        # In python 3.4, wrap_socket only accepts the server_hostname\n        # argument if HAS_SNI is true.\n        # TODO: add a unittest (python added server-side SNI support in 3.4)\n        # In the meantime it can be manually tested with\n        # python3 -m tornado.httpclient https://sni.velox.ch\n        return context.wrap_socket(socket, server_hostname=server_hostname,\n                                   **kwargs)\n    else:\n        return context.wrap_socket(socket, **kwargs)\n",
            "new_file_content": "#!/usr/bin/env python\n#\n# Copyright 2011 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Miscellaneous network utility code.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport errno\nimport os\nimport sys\nimport socket\nimport stat\n\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nfrom tornado.platform.auto import set_close_exec\nfrom tornado.util import PY3, Configurable, errno_from_exception\n\ntry:\n    import ssl\nexcept ImportError:\n    # ssl is not available on Google App Engine\n    ssl = None\n\nif PY3:\n    xrange = range\n\nif ssl is not None:\n    # Note that the naming of ssl.Purpose is confusing; the purpose\n    # of a context is to authentiate the opposite side of the connection.\n    _client_ssl_defaults = ssl.create_default_context(\n        ssl.Purpose.SERVER_AUTH)\n    _server_ssl_defaults = ssl.create_default_context(\n        ssl.Purpose.CLIENT_AUTH)\n    if hasattr(ssl, 'OP_NO_COMPRESSION'):\n        # See netutil.ssl_options_to_context\n        _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION\n        _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION\nelse:\n    # Google App Engine\n    _client_ssl_defaults = dict(cert_reqs=None,\n                                ca_certs=None)\n    _server_ssl_defaults = {}\n\n# ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode,\n# getaddrinfo attempts to import encodings.idna. If this is done at\n# module-import time, the import lock is already held by the main thread,\n# leading to deadlock. Avoid it by caching the idna encoder on the main\n# thread now.\nu'foo'.encode('idna')\n\n# For undiagnosed reasons, 'latin1' codec may also need to be preloaded.\nu'foo'.encode('latin1')\n\n# These errnos indicate that a non-blocking operation must be retried\n# at a later time.  On most platforms they're the same value, but on\n# some they differ.\n_ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)\n\nif hasattr(errno, \"WSAEWOULDBLOCK\"):\n    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)  # type: ignore\n\n# Default backlog used when calling sock.listen()\n_DEFAULT_BACKLOG = 128\n\n\ndef bind_sockets(port, address=None, family=socket.AF_UNSPEC,\n                 backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False):\n    \"\"\"Creates listening sockets bound to the given port and address.\n\n    Returns a list of socket objects (multiple sockets are returned if\n    the given address maps to multiple IP addresses, which is most common\n    for mixed IPv4 and IPv6 use).\n\n    Address may be either an IP address or hostname.  If it's a hostname,\n    the server will listen on all IP addresses associated with the\n    name.  Address may be an empty string or None to listen on all\n    available interfaces.  Family may be set to either `socket.AF_INET`\n    or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n    both will be used if available.\n\n    The ``backlog`` argument has the same meaning as for\n    `socket.listen() <socket.socket.listen>`.\n\n    ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like\n    ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.\n\n    ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket\n    in the list. If your platform doesn't support this option ValueError will\n    be raised.\n    \"\"\"\n    if reuse_port and not hasattr(socket, \"SO_REUSEPORT\"):\n        raise ValueError(\"the platform doesn't support SO_REUSEPORT\")\n\n    sockets = []\n    if address == \"\":\n        address = None\n    if not socket.has_ipv6 and family == socket.AF_UNSPEC:\n        # Python can be compiled with --disable-ipv6, which causes\n        # operations on AF_INET6 sockets to fail, but does not\n        # automatically exclude those results from getaddrinfo\n        # results.\n        # http://bugs.python.org/issue16208\n        family = socket.AF_INET\n    if flags is None:\n        flags = socket.AI_PASSIVE\n    bound_port = None\n    for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,\n                                      0, flags)):\n        af, socktype, proto, canonname, sockaddr = res\n        if (sys.platform == 'darwin' and address == 'localhost' and\n                af == socket.AF_INET6 and sockaddr[3] != 0):\n            # Mac OS X includes a link-local address fe80::1%lo0 in the\n            # getaddrinfo results for 'localhost'.  However, the firewall\n            # doesn't understand that this is a local address and will\n            # prompt for access (often repeatedly, due to an apparent\n            # bug in its ability to remember granting access to an\n            # application). Skip these addresses.\n            continue\n        try:\n            sock = socket.socket(af, socktype, proto)\n        except socket.error as e:\n            if errno_from_exception(e) == errno.EAFNOSUPPORT:\n                continue\n            raise\n        set_close_exec(sock.fileno())\n        if os.name != 'nt':\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        if reuse_port:\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n        if af == socket.AF_INET6:\n            # On linux, ipv6 sockets accept ipv4 too by default,\n            # but this makes it impossible to bind to both\n            # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,\n            # separate sockets *must* be used to listen for both ipv4\n            # and ipv6.  For consistency, always disable ipv4 on our\n            # ipv6 sockets and use a separate ipv4 socket when needed.\n            #\n            # Python 2.x on windows doesn't have IPPROTO_IPV6.\n            if hasattr(socket, \"IPPROTO_IPV6\"):\n                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)\n\n        # automatic port allocation with port=None\n        # should bind on the same port on IPv4 and IPv6\n        host, requested_port = sockaddr[:2]\n        if requested_port == 0 and bound_port is not None:\n            sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))\n\n        sock.setblocking(0)\n        sock.bind(sockaddr)\n        bound_port = sock.getsockname()[1]\n        sock.listen(backlog)\n        sockets.append(sock)\n    return sockets\n\n\nif hasattr(socket, 'AF_UNIX'):\n    def bind_unix_socket(file, mode=0o600, backlog=_DEFAULT_BACKLOG):\n        \"\"\"Creates a listening unix socket.\n\n        If a socket with the given name already exists, it will be deleted.\n        If any other file with that name exists, an exception will be\n        raised.\n\n        Returns a socket object (not a list of socket objects like\n        `bind_sockets`)\n        \"\"\"\n        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n        set_close_exec(sock.fileno())\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        sock.setblocking(0)\n        try:\n            st = os.stat(file)\n        except OSError as err:\n            if errno_from_exception(err) != errno.ENOENT:\n                raise\n        else:\n            if stat.S_ISSOCK(st.st_mode):\n                os.remove(file)\n            else:\n                raise ValueError(\"File %s exists and is not a socket\", file)\n        sock.bind(file)\n        os.chmod(file, mode)\n        sock.listen(backlog)\n        return sock\n\n\ndef add_accept_handler(sock, callback):\n    \"\"\"Adds an `.IOLoop` event handler to accept new connections on ``sock``.\n\n    When a connection is accepted, ``callback(connection, address)`` will\n    be run (``connection`` is a socket object, and ``address`` is the\n    address of the other end of the connection).  Note that this signature\n    is different from the ``callback(fd, events)`` signature used for\n    `.IOLoop` handlers.\n\n    A callable is returned which, when called, will remove the `.IOLoop`\n    event handler and stop processing further incoming connections.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.0\n       A callable is returned (``None`` was returned before).\n    \"\"\"\n    io_loop = IOLoop.current()\n    removed = [False]\n\n    def accept_handler(fd, events):\n        # More connections may come in while we're handling callbacks;\n        # to prevent starvation of other tasks we must limit the number\n        # of connections we accept at a time.  Ideally we would accept\n        # up to the number of connections that were waiting when we\n        # entered this method, but this information is not available\n        # (and rearranging this method to call accept() as many times\n        # as possible before running any callbacks would have adverse\n        # effects on load balancing in multiprocess configurations).\n        # Instead, we use the (default) listen backlog as a rough\n        # heuristic for the number of connections we can reasonably\n        # accept at once.\n        for i in xrange(_DEFAULT_BACKLOG):\n            if removed[0]:\n                # The socket was probably closed\n                return\n            try:\n                connection, address = sock.accept()\n            except socket.error as e:\n                # _ERRNO_WOULDBLOCK indicate we have accepted every\n                # connection that is available.\n                if errno_from_exception(e) in _ERRNO_WOULDBLOCK:\n                    return\n                # ECONNABORTED indicates that there was a connection\n                # but it was closed while still in the accept queue.\n                # (observed on FreeBSD).\n                if errno_from_exception(e) == errno.ECONNABORTED:\n                    continue\n                raise\n            set_close_exec(connection.fileno())\n            callback(connection, address)\n\n    def remove_handler():\n        io_loop.remove_handler(sock)\n        removed[0] = True\n\n    io_loop.add_handler(sock, accept_handler, IOLoop.READ)\n    return remove_handler\n\n\ndef is_valid_ip(ip):\n    \"\"\"Returns true if the given string is a well-formed IP address.\n\n    Supports IPv4 and IPv6.\n    \"\"\"\n    if not ip or '\\x00' in ip:\n        # getaddrinfo resolves empty strings to localhost, and truncates\n        # on zero bytes.\n        return False\n    try:\n        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,\n                                 socket.SOCK_STREAM,\n                                 0, socket.AI_NUMERICHOST)\n        return bool(res)\n    except socket.gaierror as e:\n        if e.args[0] == socket.EAI_NONAME:\n            return False\n        raise\n    return True\n\n\nclass Resolver(Configurable):\n    \"\"\"Configurable asynchronous DNS resolver interface.\n\n    By default, a blocking implementation is used (which simply calls\n    `socket.getaddrinfo`).  An alternative implementation can be\n    chosen with the `Resolver.configure <.Configurable.configure>`\n    class method::\n\n        Resolver.configure('tornado.netutil.ThreadedResolver')\n\n    The implementations of this interface included with Tornado are\n\n    * `tornado.netutil.DefaultExecutorResolver`\n    * `tornado.netutil.BlockingResolver` (deprecated)\n    * `tornado.netutil.ThreadedResolver` (deprecated)\n    * `tornado.netutil.OverrideResolver`\n    * `tornado.platform.twisted.TwistedResolver`\n    * `tornado.platform.caresresolver.CaresResolver`\n\n    .. versionchanged:: 5.0\n       The default implementation has changed from `BlockingResolver` to\n       `DefaultExecutorResolver`.\n    \"\"\"\n    @classmethod\n    def configurable_base(cls):\n        return Resolver\n\n    @classmethod\n    def configurable_default(cls):\n        return DefaultExecutorResolver\n\n    def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):\n        \"\"\"Resolves an address.\n\n        The ``host`` argument is a string which may be a hostname or a\n        literal IP address.\n\n        Returns a `.Future` whose result is a list of (family,\n        address) pairs, where address is a tuple suitable to pass to\n        `socket.connect <socket.socket.connect>` (i.e. a ``(host,\n        port)`` pair for IPv4; additional fields may be present for\n        IPv6). If a ``callback`` is passed, it will be run with the\n        result as an argument when it is complete.\n\n        :raises IOError: if the address cannot be resolved.\n\n        .. versionchanged:: 4.4\n           Standardized all implementations to raise `IOError`.\n        \"\"\"\n        raise NotImplementedError()\n\n    def close(self):\n        \"\"\"Closes the `Resolver`, freeing any resources used.\n\n        .. versionadded:: 3.1\n\n        \"\"\"\n        pass\n\n\ndef _resolve_addr(host, port, family=socket.AF_UNSPEC):\n    # On Solaris, getaddrinfo fails if the given port is not found\n    # in /etc/services and no socket type is given, so we must pass\n    # one here.  The socket type used here doesn't seem to actually\n    # matter (we discard the one we get back in the results),\n    # so the addresses we return should still be usable with SOCK_DGRAM.\n    addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)\n    results = []\n    for family, socktype, proto, canonname, address in addrinfo:\n        results.append((family, address))\n    return results\n\n\nclass DefaultExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using `.IOLoop.run_in_executor`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    @gen.coroutine\n    def resolve(self, host, port, family=socket.AF_UNSPEC):\n        result = yield IOLoop.current().run_in_executor(\n            None, _resolve_addr, host, port, family)\n        raise gen.Return(result)\n\n\nclass ExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using a `concurrent.futures.Executor`.\n\n    Use this instead of `ThreadedResolver` when you require additional\n    control over the executor being used.\n\n    The executor will be shut down when the resolver is closed unless\n    ``close_resolver=False``; use this if you want to reuse the same\n    executor elsewhere.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    def initialize(self, executor=None, close_executor=True):\n        self.io_loop = IOLoop.current()\n        if executor is not None:\n            self.executor = executor\n            self.close_executor = close_executor\n        else:\n            self.executor = dummy_executor\n            self.close_executor = False\n\n    def close(self):\n        if self.close_executor:\n            self.executor.shutdown()\n        self.executor = None\n\n    @run_on_executor\n    def resolve(self, host, port, family=socket.AF_UNSPEC):\n        return _resolve_addr(host, port, family)\n\n\nclass BlockingResolver(ExecutorResolver):\n    \"\"\"Default `Resolver` implementation, using `socket.getaddrinfo`.\n\n    The `.IOLoop` will be blocked during the resolution, although the\n    callback will not be run until the next `.IOLoop` iteration.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    def initialize(self):\n        super(BlockingResolver, self).initialize()\n\n\nclass ThreadedResolver(ExecutorResolver):\n    \"\"\"Multithreaded non-blocking `Resolver` implementation.\n\n    Requires the `concurrent.futures` package to be installed\n    (available in the standard library since Python 3.2,\n    installable with ``pip install futures`` in older versions).\n\n    The thread pool size can be configured with::\n\n        Resolver.configure('tornado.netutil.ThreadedResolver',\n                           num_threads=10)\n\n    .. versionchanged:: 3.1\n       All ``ThreadedResolvers`` share a single thread pool, whose\n       size is set by the first one to be created.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    _threadpool = None  # type: ignore\n    _threadpool_pid = None  # type: int\n\n    def initialize(self, num_threads=10):\n        threadpool = ThreadedResolver._create_threadpool(num_threads)\n        super(ThreadedResolver, self).initialize(\n            executor=threadpool, close_executor=False)\n\n    @classmethod\n    def _create_threadpool(cls, num_threads):\n        pid = os.getpid()\n        if cls._threadpool_pid != pid:\n            # Threads cannot survive after a fork, so if our pid isn't what it\n            # was when we created the pool then delete it.\n            cls._threadpool = None\n        if cls._threadpool is None:\n            from concurrent.futures import ThreadPoolExecutor\n            cls._threadpool = ThreadPoolExecutor(num_threads)\n            cls._threadpool_pid = pid\n        return cls._threadpool\n\n\nclass OverrideResolver(Resolver):\n    \"\"\"Wraps a resolver with a mapping of overrides.\n\n    This can be used to make local DNS changes (e.g. for testing)\n    without modifying system-wide settings.\n\n    The mapping can contain either host strings or host-port pairs or\n    host-port-family triplets.\n    \"\"\"\n    def initialize(self, resolver, mapping):\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self):\n        self.resolver.close()\n\n    def resolve(self, host, port, family=socket.AF_UNSPEC, *args, **kwargs):\n        if (host, port, family) in self.mapping:\n            host, port = self.mapping[(host, port, family)]\n        elif (host, port) in self.mapping:\n            host, port = self.mapping[(host, port)]\n        elif host in self.mapping:\n            host = self.mapping[host]\n        return self.resolver.resolve(host, port, family, *args, **kwargs)\n\n\n# These are the keyword arguments to ssl.wrap_socket that must be translated\n# to their SSLContext equivalents (the other arguments are still passed\n# to SSLContext.wrap_socket).\n_SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile',\n                                   'cert_reqs', 'ca_certs', 'ciphers'])\n\n\ndef ssl_options_to_context(ssl_options):\n    \"\"\"Try to convert an ``ssl_options`` dictionary to an\n    `~ssl.SSLContext` object.\n\n    The ``ssl_options`` dictionary contains keywords to be passed to\n    `ssl.wrap_socket`.  In Python 2.7.9+, `ssl.SSLContext` objects can\n    be used instead.  This function converts the dict form to its\n    `~ssl.SSLContext` equivalent, and may be used when a component which\n    accepts both forms needs to upgrade to the `~ssl.SSLContext` version\n    to use features like SNI or NPN.\n    \"\"\"\n    if isinstance(ssl_options, ssl.SSLContext):\n        return ssl_options\n    assert isinstance(ssl_options, dict)\n    assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options\n    # Can't use create_default_context since this interface doesn't\n    # tell us client vs server.\n    context = ssl.SSLContext(\n        ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23))\n    if 'certfile' in ssl_options:\n        context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None))\n    if 'cert_reqs' in ssl_options:\n        context.verify_mode = ssl_options['cert_reqs']\n    if 'ca_certs' in ssl_options:\n        context.load_verify_locations(ssl_options['ca_certs'])\n    if 'ciphers' in ssl_options:\n        context.set_ciphers(ssl_options['ciphers'])\n    if hasattr(ssl, 'OP_NO_COMPRESSION'):\n        # Disable TLS compression to avoid CRIME and related attacks.\n        # This constant depends on openssl version 1.0.\n        # TODO: Do we need to do this ourselves or can we trust\n        # the defaults?\n        context.options |= ssl.OP_NO_COMPRESSION\n    return context\n\n\ndef ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):\n    \"\"\"Returns an ``ssl.SSLSocket`` wrapping the given socket.\n\n    ``ssl_options`` may be either an `ssl.SSLContext` object or a\n    dictionary (as accepted by `ssl_options_to_context`).  Additional\n    keyword arguments are passed to ``wrap_socket`` (either the\n    `~ssl.SSLContext` method or the `ssl` module function as\n    appropriate).\n    \"\"\"\n    context = ssl_options_to_context(ssl_options)\n    if ssl.HAS_SNI:\n        # In python 3.4, wrap_socket only accepts the server_hostname\n        # argument if HAS_SNI is true.\n        # TODO: add a unittest (python added server-side SNI support in 3.4)\n        # In the meantime it can be manually tested with\n        # python3 -m tornado.httpclient https://sni.velox.ch\n        return context.wrap_socket(socket, server_hostname=server_hostname,\n                                   **kwargs)\n    else:\n        return context.wrap_socket(socket, **kwargs)\n",
            "header": {
                "file": {
                    "path": "tornado/netutil.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "caaa0909",
                "new_commit_hash": "45d9e36c",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/netutil.py"
            },
            "plus_file": {
                "path": "b/tornado/netutil.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 464,
                            "length": 7
                        },
                        "new_range": {
                            "start": 464,
                            "length": 8
                        },
                        "section": "class OverrideResolver(Resolver):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    This can be used to make local DNS changes (e.g. for testing)",
                                "type": "context"
                            },
                            {
                                "content": "    without modifying system-wide settings.",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    The mapping can contain either host strings or host-port pairs.",
                                "type": "deleted"
                            },
                            {
                                "content": "    The mapping can contain either host strings or host-port pairs or",
                                "type": "added"
                            },
                            {
                                "content": "    host-port-family triplets.",
                                "type": "added"
                            },
                            {
                                "content": "    \"\"\"",
                                "type": "context"
                            },
                            {
                                "content": "    def initialize(self, resolver, mapping):",
                                "type": "context"
                            },
                            {
                                "content": "        self.resolver = resolver",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/netutil.py",
                            "type": "class",
                            "name": "OverrideResolver",
                            "content": "class OverrideResolver(Resolver):\n    \"\"\"Wraps a resolver with a mapping of overrides.\n\n    This can be used to make local DNS changes (e.g. for testing)\n    without modifying system-wide settings.\n\n    The mapping can contain either host strings or host-port pairs.\n    \"\"\"\n    def initialize(self, resolver, mapping):\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self):\n        self.resolver.close()\n\n    def resolve(self, host, port, *args, **kwargs):\n        if (host, port) in self.mapping:\n            host, port = self.mapping[(host, port)]\n        elif host in self.mapping:\n            host = self.mapping[host]\n        return self.resolver.resolve(host, port, *args, **kwargs)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 461,
                            "end_lineno": 481,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 473,
                            "length": 12
                        },
                        "new_range": {
                            "start": 474,
                            "length": 14
                        },
                        "section": "class OverrideResolver(Resolver):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "    def close(self):",
                                "type": "context"
                            },
                            {
                                "content": "        self.resolver.close()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "    def resolve(self, host, port, *args, **kwargs):",
                                "type": "deleted"
                            },
                            {
                                "content": "        if (host, port) in self.mapping:",
                                "type": "deleted"
                            },
                            {
                                "content": "    def resolve(self, host, port, family=socket.AF_UNSPEC, *args, **kwargs):",
                                "type": "added"
                            },
                            {
                                "content": "        if (host, port, family) in self.mapping:",
                                "type": "added"
                            },
                            {
                                "content": "            host, port = self.mapping[(host, port, family)]",
                                "type": "added"
                            },
                            {
                                "content": "        elif (host, port) in self.mapping:",
                                "type": "added"
                            },
                            {
                                "content": "            host, port = self.mapping[(host, port)]",
                                "type": "context"
                            },
                            {
                                "content": "        elif host in self.mapping:",
                                "type": "context"
                            },
                            {
                                "content": "            host = self.mapping[host]",
                                "type": "context"
                            },
                            {
                                "content": "        return self.resolver.resolve(host, port, *args, **kwargs)",
                                "type": "deleted"
                            },
                            {
                                "content": "        return self.resolver.resolve(host, port, family, *args, **kwargs)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "# These are the keyword arguments to ssl.wrap_socket that must be translated",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/netutil.py",
                            "type": "method",
                            "name": "OverrideResolver.resolve",
                            "content": "class OverrideResolver(Resolver):\n    \"\"\"Wraps a resolver with a mapping of overrides.\n\n    This can be used to make local DNS changes (e.g. for testing)\n    without modifying system-wide settings.\n\n    The mapping can contain either host strings or host-port pairs.\n    \"\"\"\n    def initialize(self, resolver, mapping):\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self):\n        self.resolver.close()\n\n    def resolve(self, host, port, *args, **kwargs):\n        if (host, port) in self.mapping:\n            host, port = self.mapping[(host, port)]\n        elif host in self.mapping:\n            host = self.mapping[host]\n        return self.resolver.resolve(host, port, *args, **kwargs)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 476,
                            "end_lineno": 481,
                            "parent": {
                                "file_name": "tornado/netutil.py",
                                "type": "class",
                                "name": "OverrideResolver",
                                "content": "class OverrideResolver(Resolver):\n    \"\"\"Wraps a resolver with a mapping of overrides.\n\n    This can be used to make local DNS changes (e.g. for testing)\n    without modifying system-wide settings.\n\n    The mapping can contain either host strings or host-port pairs.\n    \"\"\"\n    def initialize(self, resolver, mapping):\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self):\n        self.resolver.close()\n\n    def resolve(self, host, port, *args, **kwargs):\n        if (host, port) in self.mapping:\n            host, port = self.mapping[(host, port)]\n        elif host in self.mapping:\n            host = self.mapping[host]\n        return self.resolver.resolve(host, port, *args, **kwargs)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 461,
                                "end_lineno": 481,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/netutil.py",
                            "type": "class",
                            "name": "OverrideResolver",
                            "content": "class OverrideResolver(Resolver):\n    \"\"\"Wraps a resolver with a mapping of overrides.\n\n    This can be used to make local DNS changes (e.g. for testing)\n    without modifying system-wide settings.\n\n    The mapping can contain either host strings or host-port pairs.\n    \"\"\"\n    def initialize(self, resolver, mapping):\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self):\n        self.resolver.close()\n\n    def resolve(self, host, port, *args, **kwargs):\n        if (host, port) in self.mapping:\n            host, port = self.mapping[(host, port)]\n        elif host in self.mapping:\n            host = self.mapping[host]\n        return self.resolver.resolve(host, port, *args, **kwargs)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 461,
                            "end_lineno": 481,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "from __future__ import absolute_import, division, print_function\n\nimport errno\nimport os\nimport signal\nimport socket\nfrom subprocess import Popen\nimport sys\nimport time\n\nfrom tornado.netutil import BlockingResolver, ThreadedResolver, is_valid_ip, bind_sockets\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.testing import AsyncTestCase, gen_test, bind_unused_port\nfrom tornado.test.util import unittest, skipIfNoNetwork\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import pycares  # type: ignore\nexcept ImportError:\n    pycares = None\nelse:\n    from tornado.platform.caresresolver import CaresResolver\n\ntry:\n    import twisted  # type: ignore\n    import twisted.names  # type: ignore\nexcept ImportError:\n    twisted = None\nelse:\n    from tornado.platform.twisted import TwistedResolver\n\n\nclass _ResolverTestMixin(object):\n    def test_localhost(self):\n        self.resolver.resolve('localhost', 80, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('127.0.0.1', 80)), result)\n\n    @gen_test\n    def test_future_interface(self):\n        addrinfo = yield self.resolver.resolve('localhost', 80,\n                                               socket.AF_UNSPEC)\n        self.assertIn((socket.AF_INET, ('127.0.0.1', 80)),\n                      addrinfo)\n\n\n# It is impossible to quickly and consistently generate an error in name\n# resolution, so test this case separately, using mocks as needed.\nclass _ResolverErrorTestMixin(object):\n    def test_bad_host(self):\n        def handler(exc_typ, exc_val, exc_tb):\n            self.stop(exc_val)\n            return True  # Halt propagation.\n\n        with ExceptionStackContext(handler):\n            self.resolver.resolve('an invalid domain', 80, callback=self.stop)\n\n        result = self.wait()\n        self.assertIsInstance(result, Exception)\n\n    @gen_test\n    def test_future_interface_bad_host(self):\n        with self.assertRaises(IOError):\n            yield self.resolver.resolve('an invalid domain', 80,\n                                        socket.AF_UNSPEC)\n\n\ndef _failing_getaddrinfo(*args):\n    \"\"\"Dummy implementation of getaddrinfo for use in mocks\"\"\"\n    raise socket.gaierror(errno.EIO, \"mock: lookup failed\")\n\n\n@skipIfNoNetwork\nclass BlockingResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(BlockingResolverTest, self).setUp()\n        self.resolver = BlockingResolver()\n\n\n# getaddrinfo-based tests need mocking to reliably generate errors;\n# some configurations are slow to produce errors and take longer than\n# our default timeout.\nclass BlockingResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super(BlockingResolverErrorTest, self).setUp()\n        self.resolver = BlockingResolver()\n        self.real_getaddrinfo = socket.getaddrinfo\n        socket.getaddrinfo = _failing_getaddrinfo\n\n    def tearDown(self):\n        socket.getaddrinfo = self.real_getaddrinfo\n        super(BlockingResolverErrorTest, self).tearDown()\n\n\n@skipIfNoNetwork\n@unittest.skipIf(futures is None, \"futures module not present\")\nclass ThreadedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(ThreadedResolverTest, self).setUp()\n        self.resolver = ThreadedResolver()\n\n    def tearDown(self):\n        self.resolver.close()\n        super(ThreadedResolverTest, self).tearDown()\n\n\nclass ThreadedResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super(ThreadedResolverErrorTest, self).setUp()\n        self.resolver = BlockingResolver()\n        self.real_getaddrinfo = socket.getaddrinfo\n        socket.getaddrinfo = _failing_getaddrinfo\n\n    def tearDown(self):\n        socket.getaddrinfo = self.real_getaddrinfo\n        super(ThreadedResolverErrorTest, self).tearDown()\n\n\n@skipIfNoNetwork\n@unittest.skipIf(futures is None, \"futures module not present\")\n@unittest.skipIf(sys.platform == 'win32', \"preexec_fn not available on win32\")\nclass ThreadedResolverImportTest(unittest.TestCase):\n    def test_import(self):\n        TIMEOUT = 5\n\n        # Test for a deadlock when importing a module that runs the\n        # ThreadedResolver at import-time. See resolve_test.py for\n        # full explanation.\n        command = [\n            sys.executable,\n            '-c',\n            'import tornado.test.resolve_test_helper']\n\n        start = time.time()\n        popen = Popen(command, preexec_fn=lambda: signal.alarm(TIMEOUT))\n        while time.time() - start < TIMEOUT:\n            return_code = popen.poll()\n            if return_code is not None:\n                self.assertEqual(0, return_code)\n                return  # Success.\n            time.sleep(0.05)\n\n        self.fail(\"import timed out\")\n\n\n# We do not test errors with CaresResolver:\n# Some DNS-hijacking ISPs (e.g. Time Warner) return non-empty results\n# with an NXDOMAIN status code.  Most resolvers treat this as an error;\n# C-ares returns the results, making the \"bad_host\" tests unreliable.\n# C-ares will try to resolve even malformed names, such as the\n# name with spaces used in this test.\n@skipIfNoNetwork\n@unittest.skipIf(pycares is None, \"pycares module not present\")\nclass CaresResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(CaresResolverTest, self).setUp()\n        self.resolver = CaresResolver()\n\n\n# TwistedResolver produces consistent errors in our test cases so we\n# can test the regular and error cases in the same class.\n@skipIfNoNetwork\n@unittest.skipIf(twisted is None, \"twisted module not present\")\n@unittest.skipIf(getattr(twisted, '__version__', '0.0') < \"12.1\", \"old version of twisted\")\nclass TwistedResolverTest(AsyncTestCase, _ResolverTestMixin,\n                          _ResolverErrorTestMixin):\n    def setUp(self):\n        super(TwistedResolverTest, self).setUp()\n        self.resolver = TwistedResolver()\n\n\nclass IsValidIPTest(unittest.TestCase):\n    def test_is_valid_ip(self):\n        self.assertTrue(is_valid_ip('127.0.0.1'))\n        self.assertTrue(is_valid_ip('4.4.4.4'))\n        self.assertTrue(is_valid_ip('::1'))\n        self.assertTrue(is_valid_ip('2620:0:1cfe:face:b00c::3'))\n        self.assertTrue(not is_valid_ip('www.google.com'))\n        self.assertTrue(not is_valid_ip('localhost'))\n        self.assertTrue(not is_valid_ip('4.4.4.4<'))\n        self.assertTrue(not is_valid_ip(' 127.0.0.1'))\n        self.assertTrue(not is_valid_ip(''))\n        self.assertTrue(not is_valid_ip(' '))\n        self.assertTrue(not is_valid_ip('\\n'))\n        self.assertTrue(not is_valid_ip('\\x00'))\n\n\nclass TestPortAllocation(unittest.TestCase):\n    def test_same_port_allocation(self):\n        if 'TRAVIS' in os.environ:\n            self.skipTest(\"dual-stack servers often have port conflicts on travis\")\n        sockets = bind_sockets(None, 'localhost')\n        try:\n            port = sockets[0].getsockname()[1]\n            self.assertTrue(all(s.getsockname()[1] == port\n                                for s in sockets[1:]))\n        finally:\n            for sock in sockets:\n                sock.close()\n\n    @unittest.skipIf(not hasattr(socket, \"SO_REUSEPORT\"), \"SO_REUSEPORT is not supported\")\n    def test_reuse_port(self):\n        sockets = []\n        socket, port = bind_unused_port(reuse_port=True)\n        try:\n            sockets = bind_sockets(port, '127.0.0.1', reuse_port=True)\n            self.assertTrue(all(s.getsockname()[1] == port for s in sockets))\n        finally:\n            socket.close()\n            for sock in sockets:\n                sock.close()\n",
            "new_file_content": "from __future__ import absolute_import, division, print_function\n\nimport errno\nimport os\nimport signal\nimport socket\nfrom subprocess import Popen\nimport sys\nimport time\n\nfrom tornado.netutil import BlockingResolver, OverrideResolver, ThreadedResolver, is_valid_ip, bind_sockets\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.testing import AsyncTestCase, gen_test, bind_unused_port\nfrom tornado.test.util import unittest, skipIfNoNetwork\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import pycares  # type: ignore\nexcept ImportError:\n    pycares = None\nelse:\n    from tornado.platform.caresresolver import CaresResolver\n\ntry:\n    import twisted  # type: ignore\n    import twisted.names  # type: ignore\nexcept ImportError:\n    twisted = None\nelse:\n    from tornado.platform.twisted import TwistedResolver\n\n\nclass _ResolverTestMixin(object):\n    def test_localhost(self):\n        self.resolver.resolve('localhost', 80, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('127.0.0.1', 80)), result)\n\n    @gen_test\n    def test_future_interface(self):\n        addrinfo = yield self.resolver.resolve('localhost', 80,\n                                               socket.AF_UNSPEC)\n        self.assertIn((socket.AF_INET, ('127.0.0.1', 80)),\n                      addrinfo)\n\n\n# It is impossible to quickly and consistently generate an error in name\n# resolution, so test this case separately, using mocks as needed.\nclass _ResolverErrorTestMixin(object):\n    def test_bad_host(self):\n        def handler(exc_typ, exc_val, exc_tb):\n            self.stop(exc_val)\n            return True  # Halt propagation.\n\n        with ExceptionStackContext(handler):\n            self.resolver.resolve('an invalid domain', 80, callback=self.stop)\n\n        result = self.wait()\n        self.assertIsInstance(result, Exception)\n\n    @gen_test\n    def test_future_interface_bad_host(self):\n        with self.assertRaises(IOError):\n            yield self.resolver.resolve('an invalid domain', 80,\n                                        socket.AF_UNSPEC)\n\n\ndef _failing_getaddrinfo(*args):\n    \"\"\"Dummy implementation of getaddrinfo for use in mocks\"\"\"\n    raise socket.gaierror(errno.EIO, \"mock: lookup failed\")\n\n\n@skipIfNoNetwork\nclass BlockingResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(BlockingResolverTest, self).setUp()\n        self.resolver = BlockingResolver()\n\n\n# getaddrinfo-based tests need mocking to reliably generate errors;\n# some configurations are slow to produce errors and take longer than\n# our default timeout.\nclass BlockingResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super(BlockingResolverErrorTest, self).setUp()\n        self.resolver = BlockingResolver()\n        self.real_getaddrinfo = socket.getaddrinfo\n        socket.getaddrinfo = _failing_getaddrinfo\n\n    def tearDown(self):\n        socket.getaddrinfo = self.real_getaddrinfo\n        super(BlockingResolverErrorTest, self).tearDown()\n\n\nclass OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(OverrideResolverTest, self).setUp()\n        mapping = {\n            ('google.com', 80): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    def test_resolve_multiaddr(self):\n        self.resolver.resolve('google.com', 80, socket.AF_INET, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('1.2.3.4', 80)), result)\n\n        self.resolver.resolve('google.com', 80, socket.AF_INET6, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET6, ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80, 0, 0)), result)\n\n\n@skipIfNoNetwork\n@unittest.skipIf(futures is None, \"futures module not present\")\nclass ThreadedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(ThreadedResolverTest, self).setUp()\n        self.resolver = ThreadedResolver()\n\n    def tearDown(self):\n        self.resolver.close()\n        super(ThreadedResolverTest, self).tearDown()\n\n\nclass ThreadedResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super(ThreadedResolverErrorTest, self).setUp()\n        self.resolver = BlockingResolver()\n        self.real_getaddrinfo = socket.getaddrinfo\n        socket.getaddrinfo = _failing_getaddrinfo\n\n    def tearDown(self):\n        socket.getaddrinfo = self.real_getaddrinfo\n        super(ThreadedResolverErrorTest, self).tearDown()\n\n\n@skipIfNoNetwork\n@unittest.skipIf(futures is None, \"futures module not present\")\n@unittest.skipIf(sys.platform == 'win32', \"preexec_fn not available on win32\")\nclass ThreadedResolverImportTest(unittest.TestCase):\n    def test_import(self):\n        TIMEOUT = 5\n\n        # Test for a deadlock when importing a module that runs the\n        # ThreadedResolver at import-time. See resolve_test.py for\n        # full explanation.\n        command = [\n            sys.executable,\n            '-c',\n            'import tornado.test.resolve_test_helper']\n\n        start = time.time()\n        popen = Popen(command, preexec_fn=lambda: signal.alarm(TIMEOUT))\n        while time.time() - start < TIMEOUT:\n            return_code = popen.poll()\n            if return_code is not None:\n                self.assertEqual(0, return_code)\n                return  # Success.\n            time.sleep(0.05)\n\n        self.fail(\"import timed out\")\n\n\n# We do not test errors with CaresResolver:\n# Some DNS-hijacking ISPs (e.g. Time Warner) return non-empty results\n# with an NXDOMAIN status code.  Most resolvers treat this as an error;\n# C-ares returns the results, making the \"bad_host\" tests unreliable.\n# C-ares will try to resolve even malformed names, such as the\n# name with spaces used in this test.\n@skipIfNoNetwork\n@unittest.skipIf(pycares is None, \"pycares module not present\")\nclass CaresResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(CaresResolverTest, self).setUp()\n        self.resolver = CaresResolver()\n\n\n# TwistedResolver produces consistent errors in our test cases so we\n# can test the regular and error cases in the same class.\n@skipIfNoNetwork\n@unittest.skipIf(twisted is None, \"twisted module not present\")\n@unittest.skipIf(getattr(twisted, '__version__', '0.0') < \"12.1\", \"old version of twisted\")\nclass TwistedResolverTest(AsyncTestCase, _ResolverTestMixin,\n                          _ResolverErrorTestMixin):\n    def setUp(self):\n        super(TwistedResolverTest, self).setUp()\n        self.resolver = TwistedResolver()\n\n\nclass IsValidIPTest(unittest.TestCase):\n    def test_is_valid_ip(self):\n        self.assertTrue(is_valid_ip('127.0.0.1'))\n        self.assertTrue(is_valid_ip('4.4.4.4'))\n        self.assertTrue(is_valid_ip('::1'))\n        self.assertTrue(is_valid_ip('2620:0:1cfe:face:b00c::3'))\n        self.assertTrue(not is_valid_ip('www.google.com'))\n        self.assertTrue(not is_valid_ip('localhost'))\n        self.assertTrue(not is_valid_ip('4.4.4.4<'))\n        self.assertTrue(not is_valid_ip(' 127.0.0.1'))\n        self.assertTrue(not is_valid_ip(''))\n        self.assertTrue(not is_valid_ip(' '))\n        self.assertTrue(not is_valid_ip('\\n'))\n        self.assertTrue(not is_valid_ip('\\x00'))\n\n\nclass TestPortAllocation(unittest.TestCase):\n    def test_same_port_allocation(self):\n        if 'TRAVIS' in os.environ:\n            self.skipTest(\"dual-stack servers often have port conflicts on travis\")\n        sockets = bind_sockets(None, 'localhost')\n        try:\n            port = sockets[0].getsockname()[1]\n            self.assertTrue(all(s.getsockname()[1] == port\n                                for s in sockets[1:]))\n        finally:\n            for sock in sockets:\n                sock.close()\n\n    @unittest.skipIf(not hasattr(socket, \"SO_REUSEPORT\"), \"SO_REUSEPORT is not supported\")\n    def test_reuse_port(self):\n        sockets = []\n        socket, port = bind_unused_port(reuse_port=True)\n        try:\n            sockets = bind_sockets(port, '127.0.0.1', reuse_port=True)\n            self.assertTrue(all(s.getsockname()[1] == port for s in sockets))\n        finally:\n            socket.close()\n            for sock in sockets:\n                sock.close()\n",
            "header": {
                "file": {
                    "path": "tornado/test/netutil_test.py"
                },
                "misc_line": null
            },
            "index_line": {
                "old_commit_hash": "be581764",
                "new_commit_hash": "fd284dad",
                "mode": "100644"
            },
            "is_binary_file": false,
            "binary_line": null,
            "minus_file": {
                "path": "a/tornado/test/netutil_test.py"
            },
            "plus_file": {
                "path": "b/tornado/test/netutil_test.py"
            },
            "hunks": [
                {
                    "descriptor": {
                        "old_range": {
                            "start": 8,
                            "length": 7
                        },
                        "new_range": {
                            "start": 8,
                            "length": 7
                        },
                        "section": "from subprocess import Popen"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "import sys",
                                "type": "context"
                            },
                            {
                                "content": "import time",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.netutil import BlockingResolver, ThreadedResolver, is_valid_ip, bind_sockets",
                                "type": "deleted"
                            },
                            {
                                "content": "from tornado.netutil import BlockingResolver, OverrideResolver, ThreadedResolver, is_valid_ip, bind_sockets",
                                "type": "added"
                            },
                            {
                                "content": "from tornado.stack_context import ExceptionStackContext",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.testing import AsyncTestCase, gen_test, bind_unused_port",
                                "type": "context"
                            },
                            {
                                "content": "from tornado.test.util import unittest, skipIfNoNetwork",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/netutil_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.netutil import BlockingResolver, OverrideResolver, ThreadedResolver, is_valid_ip, bind_sockets",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 11,
                            "end_lineno": 11,
                            "parent": null
                        }
                    ],
                    "deleted_entities": [
                        {
                            "file_name": "tornado/test/netutil_test.py",
                            "type": "statement",
                            "name": "",
                            "content": "from tornado.netutil import BlockingResolver, ThreadedResolver, is_valid_ip, bind_sockets",
                            "ast_type_str": "ImportFrom",
                            "start_lineno": 11,
                            "end_lineno": 11,
                            "parent": null
                        }
                    ]
                },
                {
                    "descriptor": {
                        "old_range": {
                            "start": 96,
                            "length": 6
                        },
                        "new_range": {
                            "start": 96,
                            "length": 26
                        },
                        "section": "class BlockingResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        super(BlockingResolverErrorTest, self).tearDown()",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):",
                                "type": "added"
                            },
                            {
                                "content": "    def setUp(self):",
                                "type": "added"
                            },
                            {
                                "content": "        super(OverrideResolverTest, self).setUp()",
                                "type": "added"
                            },
                            {
                                "content": "        mapping = {",
                                "type": "added"
                            },
                            {
                                "content": "            ('google.com', 80): ('1.2.3.4', 80),",
                                "type": "added"
                            },
                            {
                                "content": "            ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),",
                                "type": "added"
                            },
                            {
                                "content": "            ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)",
                                "type": "added"
                            },
                            {
                                "content": "        }",
                                "type": "added"
                            },
                            {
                                "content": "        self.resolver = OverrideResolver(BlockingResolver(), mapping)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "    def test_resolve_multiaddr(self):",
                                "type": "added"
                            },
                            {
                                "content": "        self.resolver.resolve('google.com', 80, socket.AF_INET, callback=self.stop)",
                                "type": "added"
                            },
                            {
                                "content": "        result = self.wait()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIn((socket.AF_INET, ('1.2.3.4', 80)), result)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "        self.resolver.resolve('google.com', 80, socket.AF_INET6, callback=self.stop)",
                                "type": "added"
                            },
                            {
                                "content": "        result = self.wait()",
                                "type": "added"
                            },
                            {
                                "content": "        self.assertIn((socket.AF_INET6, ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80, 0, 0)), result)",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "added"
                            },
                            {
                                "content": "@skipIfNoNetwork",
                                "type": "context"
                            },
                            {
                                "content": "@unittest.skipIf(futures is None, \"futures module not present\")",
                                "type": "context"
                            },
                            {
                                "content": "class ThreadedResolverTest(AsyncTestCase, _ResolverTestMixin):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [],
                    "added_entities": [
                        {
                            "file_name": "tornado/test/netutil_test.py",
                            "type": "method",
                            "name": "OverrideResolverTest.setUp",
                            "content": "class OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(OverrideResolverTest, self).setUp()\n        mapping = {\n            ('google.com', 80): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    def test_resolve_multiaddr(self):\n        self.resolver.resolve('google.com', 80, socket.AF_INET, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('1.2.3.4', 80)), result)\n\n        self.resolver.resolve('google.com', 80, socket.AF_INET6, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET6, ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80, 0, 0)), result)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 100,
                            "end_lineno": 107,
                            "parent": {
                                "file_name": "tornado/test/netutil_test.py",
                                "type": "class",
                                "name": "OverrideResolverTest",
                                "content": "class OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(OverrideResolverTest, self).setUp()\n        mapping = {\n            ('google.com', 80): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    def test_resolve_multiaddr(self):\n        self.resolver.resolve('google.com', 80, socket.AF_INET, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('1.2.3.4', 80)), result)\n\n        self.resolver.resolve('google.com', 80, socket.AF_INET6, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET6, ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80, 0, 0)), result)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 99,
                                "end_lineno": 116,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/netutil_test.py",
                            "type": "class",
                            "name": "OverrideResolverTest",
                            "content": "class OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(OverrideResolverTest, self).setUp()\n        mapping = {\n            ('google.com', 80): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    def test_resolve_multiaddr(self):\n        self.resolver.resolve('google.com', 80, socket.AF_INET, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('1.2.3.4', 80)), result)\n\n        self.resolver.resolve('google.com', 80, socket.AF_INET6, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET6, ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80, 0, 0)), result)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 99,
                            "end_lineno": 116,
                            "parent": null
                        },
                        {
                            "file_name": "tornado/test/netutil_test.py",
                            "type": "method",
                            "name": "OverrideResolverTest.test_resolve_multiaddr",
                            "content": "class OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(OverrideResolverTest, self).setUp()\n        mapping = {\n            ('google.com', 80): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    def test_resolve_multiaddr(self):\n        self.resolver.resolve('google.com', 80, socket.AF_INET, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('1.2.3.4', 80)), result)\n\n        self.resolver.resolve('google.com', 80, socket.AF_INET6, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET6, ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80, 0, 0)), result)",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 109,
                            "end_lineno": 116,
                            "parent": {
                                "file_name": "tornado/test/netutil_test.py",
                                "type": "class",
                                "name": "OverrideResolverTest",
                                "content": "class OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(OverrideResolverTest, self).setUp()\n        mapping = {\n            ('google.com', 80): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    def test_resolve_multiaddr(self):\n        self.resolver.resolve('google.com', 80, socket.AF_INET, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('1.2.3.4', 80)), result)\n\n        self.resolver.resolve('google.com', 80, socket.AF_INET6, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET6, ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80, 0, 0)), result)",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 99,
                                "end_lineno": 116,
                                "parent": null
                            }
                        }
                    ],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "58434a0419c8de02d08efe990e7aeaafedfbbeb0^",
    "new_commit_hash": "58434a0419c8de02d08efe990e7aeaafedfbbeb0",
    "commit_message": "Add family argument to OverrideResolver->resolve method (#2201)",
    "commit_date": "2017-12-26T18:05:28-05:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "58434a0419c8de02d08efe990e7aeaafedfbbeb0",
    "test_file_codes": [
        "from __future__ import absolute_import, division, print_function\n\nimport errno\nimport os\nimport signal\nimport socket\nfrom subprocess import Popen\nimport sys\nimport time\n\nfrom tornado.netutil import BlockingResolver, OverrideResolver, ThreadedResolver, is_valid_ip, bind_sockets\nfrom tornado.stack_context import ExceptionStackContext\nfrom tornado.testing import AsyncTestCase, gen_test, bind_unused_port\nfrom tornado.test.util import unittest, skipIfNoNetwork\n\ntry:\n    from concurrent import futures\nexcept ImportError:\n    futures = None\n\ntry:\n    import pycares  # type: ignore\nexcept ImportError:\n    pycares = None\nelse:\n    from tornado.platform.caresresolver import CaresResolver\n\ntry:\n    import twisted  # type: ignore\n    import twisted.names  # type: ignore\nexcept ImportError:\n    twisted = None\nelse:\n    from tornado.platform.twisted import TwistedResolver\n\n\nclass _ResolverTestMixin(object):\n    def test_localhost(self):\n        self.resolver.resolve('localhost', 80, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('127.0.0.1', 80)), result)\n\n    @gen_test\n    def test_future_interface(self):\n        addrinfo = yield self.resolver.resolve('localhost', 80,\n                                               socket.AF_UNSPEC)\n        self.assertIn((socket.AF_INET, ('127.0.0.1', 80)),\n                      addrinfo)\n\n\n# It is impossible to quickly and consistently generate an error in name\n# resolution, so test this case separately, using mocks as needed.\nclass _ResolverErrorTestMixin(object):\n    def test_bad_host(self):\n        def handler(exc_typ, exc_val, exc_tb):\n            self.stop(exc_val)\n            return True  # Halt propagation.\n\n        with ExceptionStackContext(handler):\n            self.resolver.resolve('an invalid domain', 80, callback=self.stop)\n\n        result = self.wait()\n        self.assertIsInstance(result, Exception)\n\n    @gen_test\n    def test_future_interface_bad_host(self):\n        with self.assertRaises(IOError):\n            yield self.resolver.resolve('an invalid domain', 80,\n                                        socket.AF_UNSPEC)\n\n\ndef _failing_getaddrinfo(*args):\n    \"\"\"Dummy implementation of getaddrinfo for use in mocks\"\"\"\n    raise socket.gaierror(errno.EIO, \"mock: lookup failed\")\n\n\n@skipIfNoNetwork\nclass BlockingResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(BlockingResolverTest, self).setUp()\n        self.resolver = BlockingResolver()\n\n\n# getaddrinfo-based tests need mocking to reliably generate errors;\n# some configurations are slow to produce errors and take longer than\n# our default timeout.\nclass BlockingResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super(BlockingResolverErrorTest, self).setUp()\n        self.resolver = BlockingResolver()\n        self.real_getaddrinfo = socket.getaddrinfo\n        socket.getaddrinfo = _failing_getaddrinfo\n\n    def tearDown(self):\n        socket.getaddrinfo = self.real_getaddrinfo\n        super(BlockingResolverErrorTest, self).tearDown()\n\n\nclass OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(OverrideResolverTest, self).setUp()\n        mapping = {\n            ('google.com', 80): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),\n            ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    def test_resolve_multiaddr(self):\n        self.resolver.resolve('google.com', 80, socket.AF_INET, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET, ('1.2.3.4', 80)), result)\n\n        self.resolver.resolve('google.com', 80, socket.AF_INET6, callback=self.stop)\n        result = self.wait()\n        self.assertIn((socket.AF_INET6, ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80, 0, 0)), result)\n\n\n@skipIfNoNetwork\n@unittest.skipIf(futures is None, \"futures module not present\")\nclass ThreadedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(ThreadedResolverTest, self).setUp()\n        self.resolver = ThreadedResolver()\n\n    def tearDown(self):\n        self.resolver.close()\n        super(ThreadedResolverTest, self).tearDown()\n\n\nclass ThreadedResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super(ThreadedResolverErrorTest, self).setUp()\n        self.resolver = BlockingResolver()\n        self.real_getaddrinfo = socket.getaddrinfo\n        socket.getaddrinfo = _failing_getaddrinfo\n\n    def tearDown(self):\n        socket.getaddrinfo = self.real_getaddrinfo\n        super(ThreadedResolverErrorTest, self).tearDown()\n\n\n@skipIfNoNetwork\n@unittest.skipIf(futures is None, \"futures module not present\")\n@unittest.skipIf(sys.platform == 'win32', \"preexec_fn not available on win32\")\nclass ThreadedResolverImportTest(unittest.TestCase):\n    def test_import(self):\n        TIMEOUT = 5\n\n        # Test for a deadlock when importing a module that runs the\n        # ThreadedResolver at import-time. See resolve_test.py for\n        # full explanation.\n        command = [\n            sys.executable,\n            '-c',\n            'import tornado.test.resolve_test_helper']\n\n        start = time.time()\n        popen = Popen(command, preexec_fn=lambda: signal.alarm(TIMEOUT))\n        while time.time() - start < TIMEOUT:\n            return_code = popen.poll()\n            if return_code is not None:\n                self.assertEqual(0, return_code)\n                return  # Success.\n            time.sleep(0.05)\n\n        self.fail(\"import timed out\")\n\n\n# We do not test errors with CaresResolver:\n# Some DNS-hijacking ISPs (e.g. Time Warner) return non-empty results\n# with an NXDOMAIN status code.  Most resolvers treat this as an error;\n# C-ares returns the results, making the \"bad_host\" tests unreliable.\n# C-ares will try to resolve even malformed names, such as the\n# name with spaces used in this test.\n@skipIfNoNetwork\n@unittest.skipIf(pycares is None, \"pycares module not present\")\nclass CaresResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super(CaresResolverTest, self).setUp()\n        self.resolver = CaresResolver()\n\n\n# TwistedResolver produces consistent errors in our test cases so we\n# can test the regular and error cases in the same class.\n@skipIfNoNetwork\n@unittest.skipIf(twisted is None, \"twisted module not present\")\n@unittest.skipIf(getattr(twisted, '__version__', '0.0') < \"12.1\", \"old version of twisted\")\nclass TwistedResolverTest(AsyncTestCase, _ResolverTestMixin,\n                          _ResolverErrorTestMixin):\n    def setUp(self):\n        super(TwistedResolverTest, self).setUp()\n        self.resolver = TwistedResolver()\n\n\nclass IsValidIPTest(unittest.TestCase):\n    def test_is_valid_ip(self):\n        self.assertTrue(is_valid_ip('127.0.0.1'))\n        self.assertTrue(is_valid_ip('4.4.4.4'))\n        self.assertTrue(is_valid_ip('::1'))\n        self.assertTrue(is_valid_ip('2620:0:1cfe:face:b00c::3'))\n        self.assertTrue(not is_valid_ip('www.google.com'))\n        self.assertTrue(not is_valid_ip('localhost'))\n        self.assertTrue(not is_valid_ip('4.4.4.4<'))\n        self.assertTrue(not is_valid_ip(' 127.0.0.1'))\n        self.assertTrue(not is_valid_ip(''))\n        self.assertTrue(not is_valid_ip(' '))\n        self.assertTrue(not is_valid_ip('\\n'))\n        self.assertTrue(not is_valid_ip('\\x00'))\n\n\nclass TestPortAllocation(unittest.TestCase):\n    def test_same_port_allocation(self):\n        if 'TRAVIS' in os.environ:\n            self.skipTest(\"dual-stack servers often have port conflicts on travis\")\n        sockets = bind_sockets(None, 'localhost')\n        try:\n            port = sockets[0].getsockname()[1]\n            self.assertTrue(all(s.getsockname()[1] == port\n                                for s in sockets[1:]))\n        finally:\n            for sock in sockets:\n                sock.close()\n\n    @unittest.skipIf(not hasattr(socket, \"SO_REUSEPORT\"), \"SO_REUSEPORT is not supported\")\n    def test_reuse_port(self):\n        sockets = []\n        socket, port = bind_unused_port(reuse_port=True)\n        try:\n            sockets = bind_sockets(port, '127.0.0.1', reuse_port=True)\n            self.assertTrue(all(s.getsockname()[1] == port for s in sockets))\n        finally:\n            socket.close()\n            for sock in sockets:\n                sock.close()\n",
        "#!/usr/bin/env python\nimport unittest\nimport sys\nimport time\nimport traceback\nimport platform\nimport os\n\n\nclass PytestLikeResult(unittest.TestResult):\n    def __init__(self, *args, **kwargs):\n        super().__init__(*args, **kwargs)\n        self.start_time = None\n        # Store (test, outcome, info) for each test:\n        #   outcome ∈ { \"passed\", \"failed\", \"error\", \"skipped\" }\n        #   info can hold the exception or skip reason, etc.\n        self.results = []\n\n    def startTestRun(self):\n        \"\"\"Called once before all tests.\"\"\"\n        self.start_time = time.time()\n        # Print a header similar to pytest\n        print(\"=\" * 29 + \" test session starts \" + \"=\" * 29)\n        # You can customize the platform/versions/paths as you like:\n        print(\n            f\"platform {platform.system().lower()} -- Python {platform.python_version()}\"\n        )\n        print(f\"rootdir: {os.path.abspath(os.curdir)}\")\n\n    def stopTestRun(self):\n        \"\"\"Called once after all tests are done.\"\"\"\n        elapsed = time.time() - self.start_time\n        print()  # blank line after final dot\n\n        # Summarize\n        ntests = len(self.results)\n        print(f\"collected {ntests} items\")\n\n        # Show details of failures/errors\n        failures = [r for r in self.results if r[1] == \"failed\"]\n        errors = [r for r in self.results if r[1] == \"error\"]\n\n        if failures:\n            print(\"\\n\" + \"=\" * 35 + \" FAILURES \" + \"=\" * 35)\n            for test, outcome, err_info in failures:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n        if errors:\n            print(\"\\n\" + \"=\" * 35 + \" ERRORS \" + \"=\" * 37)\n            for test, outcome, err_info in errors:\n                test = test.split(\"::\")\n                if len(test) == 3:\n                    test = f\"{test[1]}.{test[2]}\"\n                else:\n                    test = f\"{test[1]}\"\n                print(f\"__________ {test} __________\")\n                self._print_traceback(err_info)\n\n        # Optional short summary lines for passes/fails/skips\n        print(\"\\n==================== short test summary info ====================\")\n        for test, outcome, info in self.results:\n            if outcome in (\"passed\", \"failed\", \"error\", \"skipped\"):\n                print(f\"{outcome.upper()} {test}\")\n\n        # Final one-line summary: “1 failed, 1 errors, 10 passed in 2.04s”\n        passed_count = sum(1 for r in self.results if r[1] == \"passed\")\n        failed_count = len(failures)\n        error_count = len(errors)\n        skipped_count = sum(1 for r in self.results if r[1] == \"skipped\")\n\n        summary_bits = []\n        if failed_count:\n            summary_bits.append(f\"{failed_count} failed\")\n        if error_count:\n            summary_bits.append(f\"{error_count} error{'s' if error_count != 1 else ''}\")\n        if passed_count:\n            summary_bits.append(f\"{passed_count} passed\")\n        if skipped_count:\n            summary_bits.append(f\"{skipped_count} skipped\")\n\n        summary_str = \", \".join(summary_bits) if summary_bits else \"no tests run\"\n        print(\n            f\"=================== {summary_str} in {elapsed:.2f}s ===================\"\n        )\n\n    def startTest(self, test):\n        \"\"\"Called right before each test method.\"\"\"\n        super().startTest(test)\n        # Print a dot or some indicator\n        print(\".\", end=\"\", flush=True)\n\n    def addSuccess(self, test):\n        super().addSuccess(test)\n        self.results.append((self._test_id(test), \"passed\", None))\n\n    def addFailure(self, test, err):\n        super().addFailure(test, err)\n        self.results.append((self._test_id(test), \"failed\", err))\n\n    def addError(self, test, err):\n        super().addError(test, err)\n        self.results.append((self._test_id(test), \"error\", err))\n\n    def addSkip(self, test, reason):\n        super().addSkip(test, reason)\n        self.results.append((self._test_id(test), \"skipped\", reason))\n\n    def _print_traceback(self, err_info):\n        \"\"\"Helper to print the traceback like pytest does.\"\"\"\n        if isinstance(err_info, tuple) and len(err_info) == 3:\n            exc_type, exc_value, tb = err_info\n            traceback.print_exception(exc_type, exc_value, tb, file=sys.stdout)\n        else:\n            print(str(err_info))\n\n    def _test_id(self, test):\n        try:\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}::{test._testMethodName}\"\n        except AttributeError:\n            # Fallback for _ErrorHolder objects\n            return f\"{test.__class__.__module__}::{test.__class__.__name__}\"\n\n\nclass PytestLikeRunner(unittest.TextTestRunner):\n    \"\"\"A custom TextTestRunner that uses the PytestLikeResult.\"\"\"\n\n    resultclass = PytestLikeResult\n\n    def run(self, test):\n        result = self._makeResult()\n        # Overriding run to ensure we call startTestRun/stopTestRun\n        result.startTestRun()\n        test(result)\n        result.stopTestRun()\n        return result\n\n    def tearDown(self):\n        # Reset signal handlers\n        from twisted.internet import reactor\n\n        reactor.removeAll()\n        reactor.stop()\n        super().tearDown()\n\n\ndef main():\n    loader = unittest.TestLoader()\n    suite = loader.discover(\".\", pattern=\"test_*.py\")  # discover tests in r2e_tests/\n    runner = PytestLikeRunner(verbosity=0)\n    result = runner.run(suite)\n    # Exit with code 0 if all tests passed/skipped, 1 if there were fails/errors\n    sys.exit(not result.wasSuccessful())\n\n\nif __name__ == \"__main__\":\n    main()\n"
    ],
    "test_file_names": [
        "test_1.py",
        "tornado_unittest_runner.py"
    ],
    "setup_res_code": 0,
    "setup_res_stdout": "",
    "setup_res_stderr": "Using CPython 3.9.21\nCreating virtual environment at: .venv\nActivate with: source .venv/bin/activate\nResolved 1 package in 824ms\nPrepared 1 package in 1.16s\nInstalled 1 package in 1ms\n + tornado==5.0.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_58434a0419c8de02d08efe990e7aeaafedfbbeb0)\nResolved 29 packages in 15ms\nInstalled 29 packages in 111ms\n + attrs==24.3.0\n + automat==24.8.1\n + cachetools==5.5.0\n + cffi==1.17.1\n + chardet==5.2.0\n + colorama==0.4.6\n + constantly==23.10.4\n + distlib==0.3.9\n + exceptiongroup==1.2.2\n + filelock==3.16.1\n + hyperlink==21.0.0\n + idna==3.10\n + incremental==24.7.2\n + iniconfig==2.0.0\n + packaging==24.2\n + platformdirs==4.3.6\n + pluggy==1.5.0\n + pycares==4.5.0\n + pycparser==2.22\n + pycurl==7.45.4\n + pyproject-api==1.8.0\n + pytest==8.3.4\n + setuptools==75.6.0\n + tomli==2.2.1\n + tox==4.23.2\n + twisted==24.11.0\n + typing-extensions==4.12.2\n + virtualenv==20.28.0\n + zope-interface==7.2\n",
    "new_commit_res_code": 0,
    "new_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /testbed\n.....................\ncollected 21 items\n\n=================================== FAILURES ===================================\n__________ CaresResolverTest.test_future_interface __________\nTraceback (most recent call last):\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/testbed/tornado/testing.py\", line 124, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/testbed/tornado/testing.py\", line 523, in post_coroutine\n    return self.io_loop.run_sync(\n  File \"/testbed/tornado/ioloop.py\", line 571, in run_sync\n    return future_cell[0].result()\n  File \"/testbed/tornado/gen.py\", line 1103, in run\n    yielded = self.gen.send(value)\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/types.py\", line 215, in send\n    return self.__wrapped.send(val)\n  File \"/testbed/r2e_tests/test_1.py\", line 47, in test_future_interface\n    self.assertIn((socket.AF_INET, ('127.0.0.1', 80)),\nAssertionError: (<AddressFamily.AF_INET: 2>, ('127.0.0.1', 80)) not found in [(<AddressFamily.AF_INET6: 10>, ('::1', 80))]\n__________ CaresResolverTest.test_localhost __________\nTraceback (most recent call last):\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/testbed/tornado/testing.py\", line 124, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/testbed/r2e_tests/test_1.py\", line 41, in test_localhost\n    self.assertIn((socket.AF_INET, ('127.0.0.1', 80)), result)\nAssertionError: (<AddressFamily.AF_INET: 2>, ('127.0.0.1', 80)) not found in [(<AddressFamily.AF_INET6: 10>, ('::1', 80))]\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::BlockingResolverErrorTest::test_bad_host\nPASSED r2e_tests.test_1::BlockingResolverErrorTest::test_future_interface_bad_host\nPASSED r2e_tests.test_1::BlockingResolverTest::test_future_interface\nPASSED r2e_tests.test_1::BlockingResolverTest::test_localhost\nFAILED r2e_tests.test_1::CaresResolverTest::test_future_interface\nFAILED r2e_tests.test_1::CaresResolverTest::test_localhost\nPASSED r2e_tests.test_1::IsValidIPTest::test_is_valid_ip\nPASSED r2e_tests.test_1::OverrideResolverTest::test_future_interface\nPASSED r2e_tests.test_1::OverrideResolverTest::test_localhost\nPASSED r2e_tests.test_1::OverrideResolverTest::test_resolve_multiaddr\nPASSED r2e_tests.test_1::TestPortAllocation::test_reuse_port\nPASSED r2e_tests.test_1::TestPortAllocation::test_same_port_allocation\nPASSED r2e_tests.test_1::ThreadedResolverErrorTest::test_bad_host\nPASSED r2e_tests.test_1::ThreadedResolverErrorTest::test_future_interface_bad_host\nPASSED r2e_tests.test_1::ThreadedResolverImportTest::test_import\nPASSED r2e_tests.test_1::ThreadedResolverTest::test_future_interface\nPASSED r2e_tests.test_1::ThreadedResolverTest::test_localhost\nPASSED r2e_tests.test_1::TwistedResolverTest::test_bad_host\nPASSED r2e_tests.test_1::TwistedResolverTest::test_future_interface\nPASSED r2e_tests.test_1::TwistedResolverTest::test_future_interface_bad_host\nPASSED r2e_tests.test_1::TwistedResolverTest::test_localhost\n=================== 2 failed, 19 passed in 0.18s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 0,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /testbed\n.....................\ncollected 21 items\n\n=================================== FAILURES ===================================\n__________ CaresResolverTest.test_future_interface __________\nTraceback (most recent call last):\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/testbed/tornado/testing.py\", line 124, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/testbed/tornado/testing.py\", line 523, in post_coroutine\n    return self.io_loop.run_sync(\n  File \"/testbed/tornado/ioloop.py\", line 571, in run_sync\n    return future_cell[0].result()\n  File \"/testbed/tornado/gen.py\", line 1103, in run\n    yielded = self.gen.send(value)\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/types.py\", line 215, in send\n    return self.__wrapped.send(val)\n  File \"/testbed/r2e_tests/test_1.py\", line 47, in test_future_interface\n    self.assertIn((socket.AF_INET, ('127.0.0.1', 80)),\nAssertionError: (<AddressFamily.AF_INET: 2>, ('127.0.0.1', 80)) not found in [(<AddressFamily.AF_INET6: 10>, ('::1', 80))]\n__________ CaresResolverTest.test_localhost __________\nTraceback (most recent call last):\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/testbed/tornado/testing.py\", line 124, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/testbed/r2e_tests/test_1.py\", line 41, in test_localhost\n    self.assertIn((socket.AF_INET, ('127.0.0.1', 80)), result)\nAssertionError: (<AddressFamily.AF_INET: 2>, ('127.0.0.1', 80)) not found in [(<AddressFamily.AF_INET6: 10>, ('::1', 80))]\n\n=================================== ERRORS =====================================\n__________ OverrideResolverTest.test_resolve_multiaddr __________\nTraceback (most recent call last):\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 59, in testPartExecutor\n    yield\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 592, in run\n    self._callTestMethod(testMethod)\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/unittest/case.py\", line 550, in _callTestMethod\n    method()\n  File \"/testbed/tornado/testing.py\", line 124, in __call__\n    result = self.orig_method(*args, **kwargs)\n  File \"/testbed/r2e_tests/test_1.py\", line 115, in test_resolve_multiaddr\n    result = self.wait()\n  File \"/testbed/tornado/testing.py\", line 321, in wait\n    self.__rethrow()\n  File \"/testbed/tornado/testing.py\", line 257, in __rethrow\n    raise_exc_info(failure)\n  File \"<string>\", line 4, in raise_exc_info\n  File \"/testbed/tornado/stack_context.py\", line 316, in wrapped\n    ret = fn(*args, **kwargs)\n  File \"/testbed/tornado/concurrent.py\", line 425, in <lambda>\n    future, lambda future: callback(future.result()))\n  File \"/testbed/tornado/concurrent.py\", line 380, in submit\n    future_set_result_unless_cancelled(future, fn(*args, **kwargs))\n  File \"/testbed/tornado/netutil.py\", line 402, in resolve\n    return _resolve_addr(host, port, family)\n  File \"/testbed/tornado/netutil.py\", line 350, in _resolve_addr\n    addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)\n  File \"/root/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/socket.py\", line 966, in getaddrinfo\n    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):\nsocket.gaierror: [Errno -9] Address family for hostname not supported\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::BlockingResolverErrorTest::test_bad_host\nPASSED r2e_tests.test_1::BlockingResolverErrorTest::test_future_interface_bad_host\nPASSED r2e_tests.test_1::BlockingResolverTest::test_future_interface\nPASSED r2e_tests.test_1::BlockingResolverTest::test_localhost\nFAILED r2e_tests.test_1::CaresResolverTest::test_future_interface\nFAILED r2e_tests.test_1::CaresResolverTest::test_localhost\nPASSED r2e_tests.test_1::IsValidIPTest::test_is_valid_ip\nPASSED r2e_tests.test_1::OverrideResolverTest::test_future_interface\nPASSED r2e_tests.test_1::OverrideResolverTest::test_localhost\nERROR r2e_tests.test_1::OverrideResolverTest::test_resolve_multiaddr\nPASSED r2e_tests.test_1::TestPortAllocation::test_reuse_port\nPASSED r2e_tests.test_1::TestPortAllocation::test_same_port_allocation\nPASSED r2e_tests.test_1::ThreadedResolverErrorTest::test_bad_host\nPASSED r2e_tests.test_1::ThreadedResolverErrorTest::test_future_interface_bad_host\nPASSED r2e_tests.test_1::ThreadedResolverImportTest::test_import\nPASSED r2e_tests.test_1::ThreadedResolverTest::test_future_interface\nPASSED r2e_tests.test_1::ThreadedResolverTest::test_localhost\nPASSED r2e_tests.test_1::TwistedResolverTest::test_bad_host\nPASSED r2e_tests.test_1::TwistedResolverTest::test_future_interface\nPASSED r2e_tests.test_1::TwistedResolverTest::test_future_interface_bad_host\nPASSED r2e_tests.test_1::TwistedResolverTest::test_localhost\n=================== 2 failed, 1 error, 18 passed in 0.30s ===================\n",
    "old_commit_res_stderr": ""
}
tornado/netutil.py tornado/test/netutil_test.py
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `OverrideResolver.resolve` Raises `socket.gaierror` When Using Address Family Parameter

**Description:**
When using the `resolve` method of `OverrideResolver` with an address family parameter, a `socket.gaierror` is raised, indicating that the address family for the hostname is not supported.

**Example Code:**
```python
import socket
from tornado.netutil import BlockingResolver, OverrideResolver

mapping = {
    ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),
    ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)
}
resolver = OverrideResolver(BlockingResolver(), mapping)

# Attempt to resolve with IPv4
resolver.resolve('google.com', 80, socket.AF_INET, callback=lambda result: print(result))

# Attempt to resolve with IPv6
resolver.resolve('google.com', 80, socket.AF_INET6, callback=lambda result: print(result))
```

**Expected Behavior:**
The `OverrideResolver.resolve` method should successfully return the overridden IP address and port based on the specified address family (IPv4 or IPv6) without raising any errors.

**Actual Behavior:**
A `socket.gaierror` is raised with the message `[Errno -9] Address family for hostname not supported` when attempting to resolve with the address family parameter.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/netutil.py
#!/usr/bin/env python
#
# Copyright 2011 Facebook
#
# 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.

"""Miscellaneous network utility code."""

from __future__ import absolute_import, division, print_function

import errno
import os
import sys
import socket
import stat

from tornado.concurrent import dummy_executor, run_on_executor
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.platform.auto import set_close_exec
from tornado.util import PY3, Configurable, errno_from_exception

try:
    import ssl
except ImportError:
    # ssl is not available on Google App Engine
    ssl = None

if PY3:
    xrange = range

if ssl is not None:
    # Note that the naming of ssl.Purpose is confusing; the purpose
    # of a context is to authentiate the opposite side of the connection.
    _client_ssl_defaults = ssl.create_default_context(
        ssl.Purpose.SERVER_AUTH)
    _server_ssl_defaults = ssl.create_default_context(
        ssl.Purpose.CLIENT_AUTH)
    if hasattr(ssl, 'OP_NO_COMPRESSION'):
        # See netutil.ssl_options_to_context
        _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION
        _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION
else:
    # Google App Engine
    _client_ssl_defaults = dict(cert_reqs=None,
                                ca_certs=None)
    _server_ssl_defaults = {}

# ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode,
# getaddrinfo attempts to import encodings.idna. If this is done at
# module-import time, the import lock is already held by the main thread,
# leading to deadlock. Avoid it by caching the idna encoder on the main
# thread now.
u'foo'.encode('idna')

# For undiagnosed reasons, 'latin1' codec may also need to be preloaded.
u'foo'.encode('latin1')

# These errnos indicate that a non-blocking operation must be retried
# at a later time.  On most platforms they're the same value, but on
# some they differ.
_ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)

if hasattr(errno, "WSAEWOULDBLOCK"):
    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)  # type: ignore

# Default backlog used when calling sock.listen()
_DEFAULT_BACKLOG = 128


def bind_sockets(port, address=None, family=socket.AF_UNSPEC,
                 backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False):
    """Creates listening sockets bound to the given port and address.

    Returns a list of socket objects (multiple sockets are returned if
    the given address maps to multiple IP addresses, which is most common
    for mixed IPv4 and IPv6 use).

    Address may be either an IP address or hostname.  If it's a hostname,
    the server will listen on all IP addresses associated with the
    name.  Address may be an empty string or None to listen on all
    available interfaces.  Family may be set to either `socket.AF_INET`
    or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
    both will be used if available.

    The ``backlog`` argument has the same meaning as for
    `socket.listen() <socket.socket.listen>`.

    ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
    ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.

    ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket
    in the list. If your platform doesn't support this option ValueError will
    be raised.
    """
    if reuse_port and not hasattr(socket, "SO_REUSEPORT"):
        raise ValueError("the platform doesn't support SO_REUSEPORT")

    sockets = []
    if address == "":
        address = None
    if not socket.has_ipv6 and family == socket.AF_UNSPEC:
        # Python can be compiled with --disable-ipv6, which causes
        # operations on AF_INET6 sockets to fail, but does not
        # automatically exclude those results from getaddrinfo
        # results.
        # http://bugs.python.org/issue16208
        family = socket.AF_INET
    if flags is None:
        flags = socket.AI_PASSIVE
    bound_port = None
    for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,
                                      0, flags)):
        af, socktype, proto, canonname, sockaddr = res
        if (sys.platform == 'darwin' and address == 'localhost' and
                af == socket.AF_INET6 and sockaddr[3] != 0):
            # Mac OS X includes a link-local address fe80::1%lo0 in the
            # getaddrinfo results for 'localhost'.  However, the firewall
            # doesn't understand that this is a local address and will
            # prompt for access (often repeatedly, due to an apparent
            # bug in its ability to remember granting access to an
            # application). Skip these addresses.
            continue
        try:
            sock = socket.socket(af, socktype, proto)
        except socket.error as e:
            if errno_from_exception(e) == errno.EAFNOSUPPORT:
                continue
            raise
        set_close_exec(sock.fileno())
        if os.name != 'nt':
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if reuse_port:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        if af == socket.AF_INET6:
            # On linux, ipv6 sockets accept ipv4 too by default,
            # but this makes it impossible to bind to both
            # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,
            # separate sockets *must* be used to listen for both ipv4
            # and ipv6.  For consistency, always disable ipv4 on our
            # ipv6 sockets and use a separate ipv4 socket when needed.
            #
            # Python 2.x on windows doesn't have IPPROTO_IPV6.
            if hasattr(socket, "IPPROTO_IPV6"):
                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)

        # automatic port allocation with port=None
        # should bind on the same port on IPv4 and IPv6
        host, requested_port = sockaddr[:2]
        if requested_port == 0 and bound_port is not None:
            sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))

        sock.setblocking(0)
        sock.bind(sockaddr)
        bound_port = sock.getsockname()[1]
        sock.listen(backlog)
        sockets.append(sock)
    return sockets


if hasattr(socket, 'AF_UNIX'):
    def bind_unix_socket(file, mode=0o600, backlog=_DEFAULT_BACKLOG):
        """Creates a listening unix socket.

        If a socket with the given name already exists, it will be deleted.
        If any other file with that name exists, an exception will be
        raised.

        Returns a socket object (not a list of socket objects like
        `bind_sockets`)
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        set_close_exec(sock.fileno())
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setblocking(0)
        try:
            st = os.stat(file)
        except OSError as err:
            if errno_from_exception(err) != errno.ENOENT:
                raise
        else:
            if stat.S_ISSOCK(st.st_mode):
                os.remove(file)
            else:
                raise ValueError("File %s exists and is not a socket", file)
        sock.bind(file)
        os.chmod(file, mode)
        sock.listen(backlog)
        return sock


def add_accept_handler(sock, callback):
    """Adds an `.IOLoop` event handler to accept new connections on ``sock``.

    When a connection is accepted, ``callback(connection, address)`` will
    be run (``connection`` is a socket object, and ``address`` is the
    address of the other end of the connection).  Note that this signature
    is different from the ``callback(fd, events)`` signature used for
    `.IOLoop` handlers.

    A callable is returned which, when called, will remove the `.IOLoop`
    event handler and stop processing further incoming connections.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.

    .. versionchanged:: 5.0
       A callable is returned (``None`` was returned before).
    """
    io_loop = IOLoop.current()
    removed = [False]

    def accept_handler(fd, events):
        # More connections may come in while we're handling callbacks;
        # to prevent starvation of other tasks we must limit the number
        # of connections we accept at a time.  Ideally we would accept
        # up to the number of connections that were waiting when we
        # entered this method, but this information is not available
        # (and rearranging this method to call accept() as many times
        # as possible before running any callbacks would have adverse
        # effects on load balancing in multiprocess configurations).
        # Instead, we use the (default) listen backlog as a rough
        # heuristic for the number of connections we can reasonably
        # accept at once.
        for i in xrange(_DEFAULT_BACKLOG):
            if removed[0]:
                # The socket was probably closed
                return
            try:
                connection, address = sock.accept()
            except socket.error as e:
                # _ERRNO_WOULDBLOCK indicate we have accepted every
                # connection that is available.
                if errno_from_exception(e) in _ERRNO_WOULDBLOCK:
                    return
                # ECONNABORTED indicates that there was a connection
                # but it was closed while still in the accept queue.
                # (observed on FreeBSD).
                if errno_from_exception(e) == errno.ECONNABORTED:
                    continue
                raise
            set_close_exec(connection.fileno())
            callback(connection, address)

    def remove_handler():
        io_loop.remove_handler(sock)
        removed[0] = True

    io_loop.add_handler(sock, accept_handler, IOLoop.READ)
    return remove_handler


def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True


class Resolver(Configurable):
    """Configurable asynchronous DNS resolver interface.

    By default, a blocking implementation is used (which simply calls
    `socket.getaddrinfo`).  An alternative implementation can be
    chosen with the `Resolver.configure <.Configurable.configure>`
    class method::

        Resolver.configure('tornado.netutil.ThreadedResolver')

    The implementations of this interface included with Tornado are

    * `tornado.netutil.DefaultExecutorResolver`
    * `tornado.netutil.BlockingResolver` (deprecated)
    * `tornado.netutil.ThreadedResolver` (deprecated)
    * `tornado.netutil.OverrideResolver`
    * `tornado.platform.twisted.TwistedResolver`
    * `tornado.platform.caresresolver.CaresResolver`

    .. versionchanged:: 5.0
       The default implementation has changed from `BlockingResolver` to
       `DefaultExecutorResolver`.
    """
    @classmethod
    def configurable_base(cls):
        return Resolver

    @classmethod
    def configurable_default(cls):
        return DefaultExecutorResolver

    def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.

        :raises IOError: if the address cannot be resolved.

        .. versionchanged:: 4.4
           Standardized all implementations to raise `IOError`.
        """
        raise NotImplementedError()

    def close(self):
        """Closes the `Resolver`, freeing any resources used.

        .. versionadded:: 3.1

        """
        pass


def _resolve_addr(host, port, family=socket.AF_UNSPEC):
    # On Solaris, getaddrinfo fails if the given port is not found
    # in /etc/services and no socket type is given, so we must pass
    # one here.  The socket type used here doesn't seem to actually
    # matter (we discard the one we get back in the results),
    # so the addresses we return should still be usable with SOCK_DGRAM.
    addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
    results = []
    for family, socktype, proto, canonname, address in addrinfo:
        results.append((family, address))
    return results


class DefaultExecutorResolver(Resolver):
    """Resolver implementation using `.IOLoop.run_in_executor`.

    .. versionadded:: 5.0
    """
    @gen.coroutine
    def resolve(self, host, port, family=socket.AF_UNSPEC):
        result = yield IOLoop.current().run_in_executor(
            None, _resolve_addr, host, port, family)
        raise gen.Return(result)


class ExecutorResolver(Resolver):
    """Resolver implementation using a `concurrent.futures.Executor`.

    Use this instead of `ThreadedResolver` when you require additional
    control over the executor being used.

    The executor will be shut down when the resolver is closed unless
    ``close_resolver=False``; use this if you want to reuse the same
    executor elsewhere.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.

    .. deprecated:: 5.0
       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
       of this class.
    """
    def initialize(self, executor=None, close_executor=True):
        self.io_loop = IOLoop.current()
        if executor is not None:
            self.executor = executor
            self.close_executor = close_executor
        else:
            self.executor = dummy_executor
            self.close_executor = False

    def close(self):
        if self.close_executor:
            self.executor.shutdown()
        self.executor = None

    @run_on_executor
    def resolve(self, host, port, family=socket.AF_UNSPEC):
        return _resolve_addr(host, port, family)


class BlockingResolver(ExecutorResolver):
    """Default `Resolver` implementation, using `socket.getaddrinfo`.

    The `.IOLoop` will be blocked during the resolution, although the
    callback will not be run until the next `.IOLoop` iteration.

    .. deprecated:: 5.0
       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
       of this class.
    """
    def initialize(self):
        super(BlockingResolver, self).initialize()


class ThreadedResolver(ExecutorResolver):
    """Multithreaded non-blocking `Resolver` implementation.

    Requires the `concurrent.futures` package to be installed
    (available in the standard library since Python 3.2,
    installable with ``pip install futures`` in older versions).

    The thread pool size can be configured with::

        Resolver.configure('tornado.netutil.ThreadedResolver',
                           num_threads=10)

    .. versionchanged:: 3.1
       All ``ThreadedResolvers`` share a single thread pool, whose
       size is set by the first one to be created.

    .. deprecated:: 5.0
       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
       of this class.
    """
    _threadpool = None  # type: ignore
    _threadpool_pid = None  # type: int

    def initialize(self, num_threads=10):
        threadpool = ThreadedResolver._create_threadpool(num_threads)
        super(ThreadedResolver, self).initialize(
            executor=threadpool, close_executor=False)

    @classmethod
    def _create_threadpool(cls, num_threads):
        pid = os.getpid()
        if cls._threadpool_pid != pid:
            # Threads cannot survive after a fork, so if our pid isn't what it
            # was when we created the pool then delete it.
            cls._threadpool = None
        if cls._threadpool is None:
            from concurrent.futures import ThreadPoolExecutor
            cls._threadpool = ThreadPoolExecutor(num_threads)
            cls._threadpool_pid = pid
        return cls._threadpool


class OverrideResolver(Resolver):
    """Wraps a resolver with a mapping of overrides.

    This can be used to make local DNS changes (e.g. for testing)
    without modifying system-wide settings.

    The mapping can contain either host strings or host-port pairs.
    """
    def initialize(self, resolver, mapping):
        self.resolver = resolver
        self.mapping = mapping

    def close(self):
        self.resolver.close()

    def resolve(self, host, port, *args, **kwargs):
        if (host, port) in self.mapping:
            host, port = self.mapping[(host, port)]
        elif host in self.mapping:
            host = self.mapping[host]
        return self.resolver.resolve(host, port, *args, **kwargs)


# These are the keyword arguments to ssl.wrap_socket that must be translated
# to their SSLContext equivalents (the other arguments are still passed
# to SSLContext.wrap_socket).
_SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile',
                                   'cert_reqs', 'ca_certs', 'ciphers'])


def ssl_options_to_context(ssl_options):
    """Try to convert an ``ssl_options`` dictionary to an
    `~ssl.SSLContext` object.

    The ``ssl_options`` dictionary contains keywords to be passed to
    `ssl.wrap_socket`.  In Python 2.7.9+, `ssl.SSLContext` objects can
    be used instead.  This function converts the dict form to its
    `~ssl.SSLContext` equivalent, and may be used when a component which
    accepts both forms needs to upgrade to the `~ssl.SSLContext` version
    to use features like SNI or NPN.
    """
    if isinstance(ssl_options, ssl.SSLContext):
        return ssl_options
    assert isinstance(ssl_options, dict)
    assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options
    # Can't use create_default_context since this interface doesn't
    # tell us client vs server.
    context = ssl.SSLContext(
        ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23))
    if 'certfile' in ssl_options:
        context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None))
    if 'cert_reqs' in ssl_options:
        context.verify_mode = ssl_options['cert_reqs']
    if 'ca_certs' in ssl_options:
        context.load_verify_locations(ssl_options['ca_certs'])
    if 'ciphers' in ssl_options:
        context.set_ciphers(ssl_options['ciphers'])
    if hasattr(ssl, 'OP_NO_COMPRESSION'):
        # Disable TLS compression to avoid CRIME and related attacks.
        # This constant depends on openssl version 1.0.
        # TODO: Do we need to do this ourselves or can we trust
        # the defaults?
        context.options |= ssl.OP_NO_COMPRESSION
    return context


def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):
    """Returns an ``ssl.SSLSocket`` wrapping the given socket.

    ``ssl_options`` may be either an `ssl.SSLContext` object or a
    dictionary (as accepted by `ssl_options_to_context`).  Additional
    keyword arguments are passed to ``wrap_socket`` (either the
    `~ssl.SSLContext` method or the `ssl` module function as
    appropriate).
    """
    context = ssl_options_to_context(ssl_options)
    if ssl.HAS_SNI:
        # In python 3.4, wrap_socket only accepts the server_hostname
        # argument if HAS_SNI is true.
        # TODO: add a unittest (python added server-side SNI support in 3.4)
        # In the meantime it can be manually tested with
        # python3 -m tornado.httpclient https://sni.velox.ch
        return context.wrap_socket(socket, server_hostname=server_hostname,
                                   **kwargs)
    else:
        return context.wrap_socket(socket, **kwargs)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
[ISSUE]
**Title:** `OverrideResolver.resolve` Raises `socket.gaierror` When Using Address Family Parameter

**Description:**
When using the `resolve` method of `OverrideResolver` with an address family parameter, a `socket.gaierror` is raised, indicating that the address family for the hostname is not supported.

**Example Code:**
```python
import socket
from tornado.netutil import BlockingResolver, OverrideResolver

mapping = {
    ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),
    ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)
}
resolver = OverrideResolver(BlockingResolver(), mapping)

# Attempt to resolve with IPv4
resolver.resolve('google.com', 80, socket.AF_INET, callback=lambda result: print(result))

# Attempt to resolve with IPv6
resolver.resolve('google.com', 80, socket.AF_INET6, callback=lambda result: print(result))
```

**Expected Behavior:**
The `OverrideResolver.resolve` method should successfully return the overridden IP address and port based on the specified address family (IPv4 or IPv6) without raising any errors.

**Actual Behavior:**
A `socket.gaierror` is raised with the message `[Errno -9] Address family for hostname not supported` when attempting to resolve with the address family parameter.

[/ISSUE]
{
    "BlockingResolverErrorTest.test_bad_host": "PASSED",
    "BlockingResolverErrorTest.test_future_interface_bad_host": "PASSED",
    "BlockingResolverTest.test_future_interface": "PASSED",
    "BlockingResolverTest.test_localhost": "PASSED",
    "CaresResolverTest.test_future_interface": "FAILED",
    "CaresResolverTest.test_localhost": "FAILED",
    "IsValidIPTest.test_is_valid_ip": "PASSED",
    "OverrideResolverTest.test_future_interface": "PASSED",
    "OverrideResolverTest.test_localhost": "PASSED",
    "OverrideResolverTest.test_resolve_multiaddr": "PASSED",
    "TestPortAllocation.test_reuse_port": "PASSED",
    "TestPortAllocation.test_same_port_allocation": "PASSED",
    "ThreadedResolverErrorTest.test_bad_host": "PASSED",
    "ThreadedResolverErrorTest.test_future_interface_bad_host": "PASSED",
    "ThreadedResolverImportTest.test_import": "PASSED",
    "ThreadedResolverTest.test_future_interface": "PASSED",
    "ThreadedResolverTest.test_localhost": "PASSED",
    "TwistedResolverTest.test_bad_host": "PASSED",
    "TwistedResolverTest.test_future_interface": "PASSED",
    "TwistedResolverTest.test_future_interface_bad_host": "PASSED",
    "TwistedResolverTest.test_localhost": "PASSED"
}
diff --git a/tornado/netutil.py b/tornado/netutil.py
index caaa0909..45d9e36c 100644
--- a/tornado/netutil.py
+++ b/tornado/netutil.py
@@ -464,7 +464,8 @@ class OverrideResolver(Resolver):
     This can be used to make local DNS changes (e.g. for testing)
     without modifying system-wide settings.
 
-    The mapping can contain either host strings or host-port pairs.
+    The mapping can contain either host strings or host-port pairs or
+    host-port-family triplets.
     """
     def initialize(self, resolver, mapping):
         self.resolver = resolver
@@ -473,12 +474,14 @@ class OverrideResolver(Resolver):
     def close(self):
         self.resolver.close()
 
-    def resolve(self, host, port, *args, **kwargs):
-        if (host, port) in self.mapping:
+    def resolve(self, host, port, family=socket.AF_UNSPEC, *args, **kwargs):
+        if (host, port, family) in self.mapping:
+            host, port = self.mapping[(host, port, family)]
+        elif (host, port) in self.mapping:
             host, port = self.mapping[(host, port)]
         elif host in self.mapping:
             host = self.mapping[host]
-        return self.resolver.resolve(host, port, *args, **kwargs)
+        return self.resolver.resolve(host, port, family, *args, **kwargs)
 
 
 # These are the keyword arguments to ssl.wrap_socket that must be translated

{"tornado/netutil.py": "#!/usr/bin/env python\n#\n# Copyright 2011 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Miscellaneous network utility code.\"\"\"\n\nfrom __future__ import absolute_import, division, print_function\n\nimport errno\nimport os\nimport sys\nimport socket\nimport stat\n\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado import gen\nfrom tornado.ioloop import IOLoop\nfrom tornado.platform.auto import set_close_exec\nfrom tornado.util import PY3, Configurable, errno_from_exception\n\ntry:\n    import ssl\nexcept ImportError:\n    # ssl is not available on Google App Engine\n    ssl = None\n\nif PY3:\n    xrange = range\n\nif ssl is not None:\n    # Note that the naming of ssl.Purpose is confusing; the purpose\n    # of a context is to authentiate the opposite side of the connection.\n    _client_ssl_defaults = ssl.create_default_context(\n        ssl.Purpose.SERVER_AUTH)\n    _server_ssl_defaults = ssl.create_default_context(\n        ssl.Purpose.CLIENT_AUTH)\n    if hasattr(ssl, 'OP_NO_COMPRESSION'):\n        # See netutil.ssl_options_to_context\n        _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION\n        _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION\nelse:\n    # Google App Engine\n    _client_ssl_defaults = dict(cert_reqs=None,\n                                ca_certs=None)\n    _server_ssl_defaults = {}\n\n# ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode,\n# getaddrinfo attempts to import encodings.idna. If this is done at\n# module-import time, the import lock is already held by the main thread,\n# leading to deadlock. Avoid it by caching the idna encoder on the main\n# thread now.\nu'foo'.encode('idna')\n\n# For undiagnosed reasons, 'latin1' codec may also need to be preloaded.\nu'foo'.encode('latin1')\n\n# These errnos indicate that a non-blocking operation must be retried\n# at a later time.  On most platforms they're the same value, but on\n# some they differ.\n_ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)\n\nif hasattr(errno, \"WSAEWOULDBLOCK\"):\n    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)  # type: ignore\n\n# Default backlog used when calling sock.listen()\n_DEFAULT_BACKLOG = 128\n\n\ndef bind_sockets(port, address=None, family=socket.AF_UNSPEC,\n                 backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False):\n    \"\"\"Creates listening sockets bound to the given port and address.\n\n    Returns a list of socket objects (multiple sockets are returned if\n    the given address maps to multiple IP addresses, which is most common\n    for mixed IPv4 and IPv6 use).\n\n    Address may be either an IP address or hostname.  If it's a hostname,\n    the server will listen on all IP addresses associated with the\n    name.  Address may be an empty string or None to listen on all\n    available interfaces.  Family may be set to either `socket.AF_INET`\n    or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise\n    both will be used if available.\n\n    The ``backlog`` argument has the same meaning as for\n    `socket.listen() <socket.socket.listen>`.\n\n    ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like\n    ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.\n\n    ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket\n    in the list. If your platform doesn't support this option ValueError will\n    be raised.\n    \"\"\"\n    if reuse_port and not hasattr(socket, \"SO_REUSEPORT\"):\n        raise ValueError(\"the platform doesn't support SO_REUSEPORT\")\n\n    sockets = []\n    if address == \"\":\n        address = None\n    if not socket.has_ipv6 and family == socket.AF_UNSPEC:\n        # Python can be compiled with --disable-ipv6, which causes\n        # operations on AF_INET6 sockets to fail, but does not\n        # automatically exclude those results from getaddrinfo\n        # results.\n        # http://bugs.python.org/issue16208\n        family = socket.AF_INET\n    if flags is None:\n        flags = socket.AI_PASSIVE\n    bound_port = None\n    for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,\n                                      0, flags)):\n        af, socktype, proto, canonname, sockaddr = res\n        if (sys.platform == 'darwin' and address == 'localhost' and\n                af == socket.AF_INET6 and sockaddr[3] != 0):\n            # Mac OS X includes a link-local address fe80::1%lo0 in the\n            # getaddrinfo results for 'localhost'.  However, the firewall\n            # doesn't understand that this is a local address and will\n            # prompt for access (often repeatedly, due to an apparent\n            # bug in its ability to remember granting access to an\n            # application). Skip these addresses.\n            continue\n        try:\n            sock = socket.socket(af, socktype, proto)\n        except socket.error as e:\n            if errno_from_exception(e) == errno.EAFNOSUPPORT:\n                continue\n            raise\n        set_close_exec(sock.fileno())\n        if os.name != 'nt':\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        if reuse_port:\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)\n        if af == socket.AF_INET6:\n            # On linux, ipv6 sockets accept ipv4 too by default,\n            # but this makes it impossible to bind to both\n            # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,\n            # separate sockets *must* be used to listen for both ipv4\n            # and ipv6.  For consistency, always disable ipv4 on our\n            # ipv6 sockets and use a separate ipv4 socket when needed.\n            #\n            # Python 2.x on windows doesn't have IPPROTO_IPV6.\n            if hasattr(socket, \"IPPROTO_IPV6\"):\n                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)\n\n        # automatic port allocation with port=None\n        # should bind on the same port on IPv4 and IPv6\n        host, requested_port = sockaddr[:2]\n        if requested_port == 0 and bound_port is not None:\n            sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))\n\n        sock.setblocking(0)\n        sock.bind(sockaddr)\n        bound_port = sock.getsockname()[1]\n        sock.listen(backlog)\n        sockets.append(sock)\n    return sockets\n\n\nif hasattr(socket, 'AF_UNIX'):\n    def bind_unix_socket(file, mode=0o600, backlog=_DEFAULT_BACKLOG):\n        \"\"\"Creates a listening unix socket.\n\n        If a socket with the given name already exists, it will be deleted.\n        If any other file with that name exists, an exception will be\n        raised.\n\n        Returns a socket object (not a list of socket objects like\n        `bind_sockets`)\n        \"\"\"\n        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n        set_close_exec(sock.fileno())\n        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        sock.setblocking(0)\n        try:\n            st = os.stat(file)\n        except OSError as err:\n            if errno_from_exception(err) != errno.ENOENT:\n                raise\n        else:\n            if stat.S_ISSOCK(st.st_mode):\n                os.remove(file)\n            else:\n                raise ValueError(\"File %s exists and is not a socket\", file)\n        sock.bind(file)\n        os.chmod(file, mode)\n        sock.listen(backlog)\n        return sock\n\n\ndef add_accept_handler(sock, callback):\n    \"\"\"Adds an `.IOLoop` event handler to accept new connections on ``sock``.\n\n    When a connection is accepted, ``callback(connection, address)`` will\n    be run (``connection`` is a socket object, and ``address`` is the\n    address of the other end of the connection).  Note that this signature\n    is different from the ``callback(fd, events)`` signature used for\n    `.IOLoop` handlers.\n\n    A callable is returned which, when called, will remove the `.IOLoop`\n    event handler and stop processing further incoming connections.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. versionchanged:: 5.0\n       A callable is returned (``None`` was returned before).\n    \"\"\"\n    io_loop = IOLoop.current()\n    removed = [False]\n\n    def accept_handler(fd, events):\n        # More connections may come in while we're handling callbacks;\n        # to prevent starvation of other tasks we must limit the number\n        # of connections we accept at a time.  Ideally we would accept\n        # up to the number of connections that were waiting when we\n        # entered this method, but this information is not available\n        # (and rearranging this method to call accept() as many times\n        # as possible before running any callbacks would have adverse\n        # effects on load balancing in multiprocess configurations).\n        # Instead, we use the (default) listen backlog as a rough\n        # heuristic for the number of connections we can reasonably\n        # accept at once.\n        for i in xrange(_DEFAULT_BACKLOG):\n            if removed[0]:\n                # The socket was probably closed\n                return\n            try:\n                connection, address = sock.accept()\n            except socket.error as e:\n                # _ERRNO_WOULDBLOCK indicate we have accepted every\n                # connection that is available.\n                if errno_from_exception(e) in _ERRNO_WOULDBLOCK:\n                    return\n                # ECONNABORTED indicates that there was a connection\n                # but it was closed while still in the accept queue.\n                # (observed on FreeBSD).\n                if errno_from_exception(e) == errno.ECONNABORTED:\n                    continue\n                raise\n            set_close_exec(connection.fileno())\n            callback(connection, address)\n\n    def remove_handler():\n        io_loop.remove_handler(sock)\n        removed[0] = True\n\n    io_loop.add_handler(sock, accept_handler, IOLoop.READ)\n    return remove_handler\n\n\ndef is_valid_ip(ip):\n    \"\"\"Returns true if the given string is a well-formed IP address.\n\n    Supports IPv4 and IPv6.\n    \"\"\"\n    if not ip or '\\x00' in ip:\n        # getaddrinfo resolves empty strings to localhost, and truncates\n        # on zero bytes.\n        return False\n    try:\n        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,\n                                 socket.SOCK_STREAM,\n                                 0, socket.AI_NUMERICHOST)\n        return bool(res)\n    except socket.gaierror as e:\n        if e.args[0] == socket.EAI_NONAME:\n            return False\n        raise\n    return True\n\n\nclass Resolver(Configurable):\n    \"\"\"Configurable asynchronous DNS resolver interface.\n\n    By default, a blocking implementation is used (which simply calls\n    `socket.getaddrinfo`).  An alternative implementation can be\n    chosen with the `Resolver.configure <.Configurable.configure>`\n    class method::\n\n        Resolver.configure('tornado.netutil.ThreadedResolver')\n\n    The implementations of this interface included with Tornado are\n\n    * `tornado.netutil.DefaultExecutorResolver`\n    * `tornado.netutil.BlockingResolver` (deprecated)\n    * `tornado.netutil.ThreadedResolver` (deprecated)\n    * `tornado.netutil.OverrideResolver`\n    * `tornado.platform.twisted.TwistedResolver`\n    * `tornado.platform.caresresolver.CaresResolver`\n\n    .. versionchanged:: 5.0\n       The default implementation has changed from `BlockingResolver` to\n       `DefaultExecutorResolver`.\n    \"\"\"\n    @classmethod\n    def configurable_base(cls):\n        return Resolver\n\n    @classmethod\n    def configurable_default(cls):\n        return DefaultExecutorResolver\n\n    def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):\n        \"\"\"Resolves an address.\n\n        The ``host`` argument is a string which may be a hostname or a\n        literal IP address.\n\n        Returns a `.Future` whose result is a list of (family,\n        address) pairs, where address is a tuple suitable to pass to\n        `socket.connect <socket.socket.connect>` (i.e. a ``(host,\n        port)`` pair for IPv4; additional fields may be present for\n        IPv6). If a ``callback`` is passed, it will be run with the\n        result as an argument when it is complete.\n\n        :raises IOError: if the address cannot be resolved.\n\n        .. versionchanged:: 4.4\n           Standardized all implementations to raise `IOError`.\n        \"\"\"\n        raise NotImplementedError()\n\n    def close(self):\n        \"\"\"Closes the `Resolver`, freeing any resources used.\n\n        .. versionadded:: 3.1\n\n        \"\"\"\n        pass\n\n\ndef _resolve_addr(host, port, family=socket.AF_UNSPEC):\n    # On Solaris, getaddrinfo fails if the given port is not found\n    # in /etc/services and no socket type is given, so we must pass\n    # one here.  The socket type used here doesn't seem to actually\n    # matter (we discard the one we get back in the results),\n    # so the addresses we return should still be usable with SOCK_DGRAM.\n    addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)\n    results = []\n    for family, socktype, proto, canonname, address in addrinfo:\n        results.append((family, address))\n    return results\n\n\nclass DefaultExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using `.IOLoop.run_in_executor`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n    @gen.coroutine\n    def resolve(self, host, port, family=socket.AF_UNSPEC):\n        result = yield IOLoop.current().run_in_executor(\n            None, _resolve_addr, host, port, family)\n        raise gen.Return(result)\n\n\nclass ExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using a `concurrent.futures.Executor`.\n\n    Use this instead of `ThreadedResolver` when you require additional\n    control over the executor being used.\n\n    The executor will be shut down when the resolver is closed unless\n    ``close_resolver=False``; use this if you want to reuse the same\n    executor elsewhere.\n\n    .. versionchanged:: 5.0\n       The ``io_loop`` argument (deprecated since version 4.1) has been removed.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    def initialize(self, executor=None, close_executor=True):\n        self.io_loop = IOLoop.current()\n        if executor is not None:\n            self.executor = executor\n            self.close_executor = close_executor\n        else:\n            self.executor = dummy_executor\n            self.close_executor = False\n\n    def close(self):\n        if self.close_executor:\n            self.executor.shutdown()\n        self.executor = None\n\n    @run_on_executor\n    def resolve(self, host, port, family=socket.AF_UNSPEC):\n        return _resolve_addr(host, port, family)\n\n\nclass BlockingResolver(ExecutorResolver):\n    \"\"\"Default `Resolver` implementation, using `socket.getaddrinfo`.\n\n    The `.IOLoop` will be blocked during the resolution, although the\n    callback will not be run until the next `.IOLoop` iteration.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    def initialize(self):\n        super(BlockingResolver, self).initialize()\n\n\nclass ThreadedResolver(ExecutorResolver):\n    \"\"\"Multithreaded non-blocking `Resolver` implementation.\n\n    Requires the `concurrent.futures` package to be installed\n    (available in the standard library since Python 3.2,\n    installable with ``pip install futures`` in older versions).\n\n    The thread pool size can be configured with::\n\n        Resolver.configure('tornado.netutil.ThreadedResolver',\n                           num_threads=10)\n\n    .. versionchanged:: 3.1\n       All ``ThreadedResolvers`` share a single thread pool, whose\n       size is set by the first one to be created.\n\n    .. deprecated:: 5.0\n       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead\n       of this class.\n    \"\"\"\n    _threadpool = None  # type: ignore\n    _threadpool_pid = None  # type: int\n\n    def initialize(self, num_threads=10):\n        threadpool = ThreadedResolver._create_threadpool(num_threads)\n        super(ThreadedResolver, self).initialize(\n            executor=threadpool, close_executor=False)\n\n    @classmethod\n    def _create_threadpool(cls, num_threads):\n        pid = os.getpid()\n        if cls._threadpool_pid != pid:\n            # Threads cannot survive after a fork, so if our pid isn't what it\n            # was when we created the pool then delete it.\n            cls._threadpool = None\n        if cls._threadpool is None:\n            from concurrent.futures import ThreadPoolExecutor\n            cls._threadpool = ThreadPoolExecutor(num_threads)\n            cls._threadpool_pid = pid\n        return cls._threadpool\n\n\nclass OverrideResolver(Resolver):\n    \"\"\"Wraps a resolver with a mapping of overrides.\n\n    This can be used to make local DNS changes (e.g. for testing)\n    without modifying system-wide settings.\n\n    The mapping can contain either host strings or host-port pairs.\n    \"\"\"\n    def initialize(self, resolver, mapping):\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self):\n        self.resolver.close()\n\n    def resolve(self, host, port, *args, **kwargs):\n        if (host, port) in self.mapping:\n            host, port = self.mapping[(host, port)]\n        elif host in self.mapping:\n            host = self.mapping[host]\n        return self.resolver.resolve(host, port, *args, **kwargs)\n\n\n# These are the keyword arguments to ssl.wrap_socket that must be translated\n# to their SSLContext equivalents (the other arguments are still passed\n# to SSLContext.wrap_socket).\n_SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile',\n                                   'cert_reqs', 'ca_certs', 'ciphers'])\n\n\ndef ssl_options_to_context(ssl_options):\n    \"\"\"Try to convert an ``ssl_options`` dictionary to an\n    `~ssl.SSLContext` object.\n\n    The ``ssl_options`` dictionary contains keywords to be passed to\n    `ssl.wrap_socket`.  In Python 2.7.9+, `ssl.SSLContext` objects can\n    be used instead.  This function converts the dict form to its\n    `~ssl.SSLContext` equivalent, and may be used when a component which\n    accepts both forms needs to upgrade to the `~ssl.SSLContext` version\n    to use features like SNI or NPN.\n    \"\"\"\n    if isinstance(ssl_options, ssl.SSLContext):\n        return ssl_options\n    assert isinstance(ssl_options, dict)\n    assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options\n    # Can't use create_default_context since this interface doesn't\n    # tell us client vs server.\n    context = ssl.SSLContext(\n        ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23))\n    if 'certfile' in ssl_options:\n        context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None))\n    if 'cert_reqs' in ssl_options:\n        context.verify_mode = ssl_options['cert_reqs']\n    if 'ca_certs' in ssl_options:\n        context.load_verify_locations(ssl_options['ca_certs'])\n    if 'ciphers' in ssl_options:\n        context.set_ciphers(ssl_options['ciphers'])\n    if hasattr(ssl, 'OP_NO_COMPRESSION'):\n        # Disable TLS compression to avoid CRIME and related attacks.\n        # This constant depends on openssl version 1.0.\n        # TODO: Do we need to do this ourselves or can we trust\n        # the defaults?\n        context.options |= ssl.OP_NO_COMPRESSION\n    return context\n\n\ndef ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):\n    \"\"\"Returns an ``ssl.SSLSocket`` wrapping the given socket.\n\n    ``ssl_options`` may be either an `ssl.SSLContext` object or a\n    dictionary (as accepted by `ssl_options_to_context`).  Additional\n    keyword arguments are passed to ``wrap_socket`` (either the\n    `~ssl.SSLContext` method or the `ssl` module function as\n    appropriate).\n    \"\"\"\n    context = ssl_options_to_context(ssl_options)\n    if ssl.HAS_SNI:\n        # In python 3.4, wrap_socket only accepts the server_hostname\n        # argument if HAS_SNI is true.\n        # TODO: add a unittest (python added server-side SNI support in 3.4)\n        # In the meantime it can be manually tested with\n        # python3 -m tornado.httpclient https://sni.velox.ch\n        return context.wrap_socket(socket, server_hostname=server_hostname,\n                                   **kwargs)\n    else:\n        return context.wrap_socket(socket, **kwargs)\n"}
A user will ask you to solve a task. You should first draft your thinking process (inner monologue). Then, generate the solution.

Your response format must follow the template below:
<think>
Your thoughts or/and draft, like working through an exercise on scratch paper. Be as casual and as long as you want until you are confident to generate a correct solution.
</think>
<solution>
Final solution presented to the user.
</solution>
system
We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
[ISSUE]
**Title:** `OverrideResolver.resolve` Raises `socket.gaierror` When Using Address Family Parameter

**Description:**
When using the `resolve` method of `OverrideResolver` with an address family parameter, a `socket.gaierror` is raised, indicating that the address family for the hostname is not supported.

**Example Code:**
```python
import socket
from tornado.netutil import BlockingResolver, OverrideResolver

mapping = {
    ('google.com', 80, socket.AF_INET): ('1.2.3.4', 80),
    ('google.com', 80, socket.AF_INET6): ('2a02:6b8:7c:40c:c51e:495f:e23a:3', 80)
}
resolver = OverrideResolver(BlockingResolver(), mapping)

# Attempt to resolve with IPv4
resolver.resolve('google.com', 80, socket.AF_INET, callback=lambda result: print(result))

# Attempt to resolve with IPv6
resolver.resolve('google.com', 80, socket.AF_INET6, callback=lambda result: print(result))
```

**Expected Behavior:**
The `OverrideResolver.resolve` method should successfully return the overridden IP address and port based on the specified address family (IPv4 or IPv6) without raising any errors.

**Actual Behavior:**
A `socket.gaierror` is raised with the message `[Errno -9] Address family for hostname not supported` when attempting to resolve with the address family parameter.

[/ISSUE]
--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.

--- BEGIN FILE ---
```
### tornado/netutil.py
#!/usr/bin/env python
#
# Copyright 2011 Facebook
#
# 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.

"""Miscellaneous network utility code."""

from __future__ import absolute_import, division, print_function

import errno
import os
import sys
import socket
import stat

from tornado.concurrent import dummy_executor, run_on_executor
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.platform.auto import set_close_exec
from tornado.util import PY3, Configurable, errno_from_exception

try:
    import ssl
except ImportError:
    # ssl is not available on Google App Engine
    ssl = None

if PY3:
    xrange = range

if ssl is not None:
    # Note that the naming of ssl.Purpose is confusing; the purpose
    # of a context is to authentiate the opposite side of the connection.
    _client_ssl_defaults = ssl.create_default_context(
        ssl.Purpose.SERVER_AUTH)
    _server_ssl_defaults = ssl.create_default_context(
        ssl.Purpose.CLIENT_AUTH)
    if hasattr(ssl, 'OP_NO_COMPRESSION'):
        # See netutil.ssl_options_to_context
        _client_ssl_defaults.options |= ssl.OP_NO_COMPRESSION
        _server_ssl_defaults.options |= ssl.OP_NO_COMPRESSION
else:
    # Google App Engine
    _client_ssl_defaults = dict(cert_reqs=None,
                                ca_certs=None)
    _server_ssl_defaults = {}

# ThreadedResolver runs getaddrinfo on a thread. If the hostname is unicode,
# getaddrinfo attempts to import encodings.idna. If this is done at
# module-import time, the import lock is already held by the main thread,
# leading to deadlock. Avoid it by caching the idna encoder on the main
# thread now.
u'foo'.encode('idna')

# For undiagnosed reasons, 'latin1' codec may also need to be preloaded.
u'foo'.encode('latin1')

# These errnos indicate that a non-blocking operation must be retried
# at a later time.  On most platforms they're the same value, but on
# some they differ.
_ERRNO_WOULDBLOCK = (errno.EWOULDBLOCK, errno.EAGAIN)

if hasattr(errno, "WSAEWOULDBLOCK"):
    _ERRNO_WOULDBLOCK += (errno.WSAEWOULDBLOCK,)  # type: ignore

# Default backlog used when calling sock.listen()
_DEFAULT_BACKLOG = 128


def bind_sockets(port, address=None, family=socket.AF_UNSPEC,
                 backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False):
    """Creates listening sockets bound to the given port and address.

    Returns a list of socket objects (multiple sockets are returned if
    the given address maps to multiple IP addresses, which is most common
    for mixed IPv4 and IPv6 use).

    Address may be either an IP address or hostname.  If it's a hostname,
    the server will listen on all IP addresses associated with the
    name.  Address may be an empty string or None to listen on all
    available interfaces.  Family may be set to either `socket.AF_INET`
    or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
    both will be used if available.

    The ``backlog`` argument has the same meaning as for
    `socket.listen() <socket.socket.listen>`.

    ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
    ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.

    ``reuse_port`` option sets ``SO_REUSEPORT`` option for every socket
    in the list. If your platform doesn't support this option ValueError will
    be raised.
    """
    if reuse_port and not hasattr(socket, "SO_REUSEPORT"):
        raise ValueError("the platform doesn't support SO_REUSEPORT")

    sockets = []
    if address == "":
        address = None
    if not socket.has_ipv6 and family == socket.AF_UNSPEC:
        # Python can be compiled with --disable-ipv6, which causes
        # operations on AF_INET6 sockets to fail, but does not
        # automatically exclude those results from getaddrinfo
        # results.
        # http://bugs.python.org/issue16208
        family = socket.AF_INET
    if flags is None:
        flags = socket.AI_PASSIVE
    bound_port = None
    for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,
                                      0, flags)):
        af, socktype, proto, canonname, sockaddr = res
        if (sys.platform == 'darwin' and address == 'localhost' and
                af == socket.AF_INET6 and sockaddr[3] != 0):
            # Mac OS X includes a link-local address fe80::1%lo0 in the
            # getaddrinfo results for 'localhost'.  However, the firewall
            # doesn't understand that this is a local address and will
            # prompt for access (often repeatedly, due to an apparent
            # bug in its ability to remember granting access to an
            # application). Skip these addresses.
            continue
        try:
            sock = socket.socket(af, socktype, proto)
        except socket.error as e:
            if errno_from_exception(e) == errno.EAFNOSUPPORT:
                continue
            raise
        set_close_exec(sock.fileno())
        if os.name != 'nt':
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if reuse_port:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
        if af == socket.AF_INET6:
            # On linux, ipv6 sockets accept ipv4 too by default,
            # but this makes it impossible to bind to both
            # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,
            # separate sockets *must* be used to listen for both ipv4
            # and ipv6.  For consistency, always disable ipv4 on our
            # ipv6 sockets and use a separate ipv4 socket when needed.
            #
            # Python 2.x on windows doesn't have IPPROTO_IPV6.
            if hasattr(socket, "IPPROTO_IPV6"):
                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)

        # automatic port allocation with port=None
        # should bind on the same port on IPv4 and IPv6
        host, requested_port = sockaddr[:2]
        if requested_port == 0 and bound_port is not None:
            sockaddr = tuple([host, bound_port] + list(sockaddr[2:]))

        sock.setblocking(0)
        sock.bind(sockaddr)
        bound_port = sock.getsockname()[1]
        sock.listen(backlog)
        sockets.append(sock)
    return sockets


if hasattr(socket, 'AF_UNIX'):
    def bind_unix_socket(file, mode=0o600, backlog=_DEFAULT_BACKLOG):
        """Creates a listening unix socket.

        If a socket with the given name already exists, it will be deleted.
        If any other file with that name exists, an exception will be
        raised.

        Returns a socket object (not a list of socket objects like
        `bind_sockets`)
        """
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        set_close_exec(sock.fileno())
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setblocking(0)
        try:
            st = os.stat(file)
        except OSError as err:
            if errno_from_exception(err) != errno.ENOENT:
                raise
        else:
            if stat.S_ISSOCK(st.st_mode):
                os.remove(file)
            else:
                raise ValueError("File %s exists and is not a socket", file)
        sock.bind(file)
        os.chmod(file, mode)
        sock.listen(backlog)
        return sock


def add_accept_handler(sock, callback):
    """Adds an `.IOLoop` event handler to accept new connections on ``sock``.

    When a connection is accepted, ``callback(connection, address)`` will
    be run (``connection`` is a socket object, and ``address`` is the
    address of the other end of the connection).  Note that this signature
    is different from the ``callback(fd, events)`` signature used for
    `.IOLoop` handlers.

    A callable is returned which, when called, will remove the `.IOLoop`
    event handler and stop processing further incoming connections.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.

    .. versionchanged:: 5.0
       A callable is returned (``None`` was returned before).
    """
    io_loop = IOLoop.current()
    removed = [False]

    def accept_handler(fd, events):
        # More connections may come in while we're handling callbacks;
        # to prevent starvation of other tasks we must limit the number
        # of connections we accept at a time.  Ideally we would accept
        # up to the number of connections that were waiting when we
        # entered this method, but this information is not available
        # (and rearranging this method to call accept() as many times
        # as possible before running any callbacks would have adverse
        # effects on load balancing in multiprocess configurations).
        # Instead, we use the (default) listen backlog as a rough
        # heuristic for the number of connections we can reasonably
        # accept at once.
        for i in xrange(_DEFAULT_BACKLOG):
            if removed[0]:
                # The socket was probably closed
                return
            try:
                connection, address = sock.accept()
            except socket.error as e:
                # _ERRNO_WOULDBLOCK indicate we have accepted every
                # connection that is available.
                if errno_from_exception(e) in _ERRNO_WOULDBLOCK:
                    return
                # ECONNABORTED indicates that there was a connection
                # but it was closed while still in the accept queue.
                # (observed on FreeBSD).
                if errno_from_exception(e) == errno.ECONNABORTED:
                    continue
                raise
            set_close_exec(connection.fileno())
            callback(connection, address)

    def remove_handler():
        io_loop.remove_handler(sock)
        removed[0] = True

    io_loop.add_handler(sock, accept_handler, IOLoop.READ)
    return remove_handler


def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True


class Resolver(Configurable):
    """Configurable asynchronous DNS resolver interface.

    By default, a blocking implementation is used (which simply calls
    `socket.getaddrinfo`).  An alternative implementation can be
    chosen with the `Resolver.configure <.Configurable.configure>`
    class method::

        Resolver.configure('tornado.netutil.ThreadedResolver')

    The implementations of this interface included with Tornado are

    * `tornado.netutil.DefaultExecutorResolver`
    * `tornado.netutil.BlockingResolver` (deprecated)
    * `tornado.netutil.ThreadedResolver` (deprecated)
    * `tornado.netutil.OverrideResolver`
    * `tornado.platform.twisted.TwistedResolver`
    * `tornado.platform.caresresolver.CaresResolver`

    .. versionchanged:: 5.0
       The default implementation has changed from `BlockingResolver` to
       `DefaultExecutorResolver`.
    """
    @classmethod
    def configurable_base(cls):
        return Resolver

    @classmethod
    def configurable_default(cls):
        return DefaultExecutorResolver

    def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.

        :raises IOError: if the address cannot be resolved.

        .. versionchanged:: 4.4
           Standardized all implementations to raise `IOError`.
        """
        raise NotImplementedError()

    def close(self):
        """Closes the `Resolver`, freeing any resources used.

        .. versionadded:: 3.1

        """
        pass


def _resolve_addr(host, port, family=socket.AF_UNSPEC):
    # On Solaris, getaddrinfo fails if the given port is not found
    # in /etc/services and no socket type is given, so we must pass
    # one here.  The socket type used here doesn't seem to actually
    # matter (we discard the one we get back in the results),
    # so the addresses we return should still be usable with SOCK_DGRAM.
    addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
    results = []
    for family, socktype, proto, canonname, address in addrinfo:
        results.append((family, address))
    return results


class DefaultExecutorResolver(Resolver):
    """Resolver implementation using `.IOLoop.run_in_executor`.

    .. versionadded:: 5.0
    """
    @gen.coroutine
    def resolve(self, host, port, family=socket.AF_UNSPEC):
        result = yield IOLoop.current().run_in_executor(
            None, _resolve_addr, host, port, family)
        raise gen.Return(result)


class ExecutorResolver(Resolver):
    """Resolver implementation using a `concurrent.futures.Executor`.

    Use this instead of `ThreadedResolver` when you require additional
    control over the executor being used.

    The executor will be shut down when the resolver is closed unless
    ``close_resolver=False``; use this if you want to reuse the same
    executor elsewhere.

    .. versionchanged:: 5.0
       The ``io_loop`` argument (deprecated since version 4.1) has been removed.

    .. deprecated:: 5.0
       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
       of this class.
    """
    def initialize(self, executor=None, close_executor=True):
        self.io_loop = IOLoop.current()
        if executor is not None:
            self.executor = executor
            self.close_executor = close_executor
        else:
            self.executor = dummy_executor
            self.close_executor = False

    def close(self):
        if self.close_executor:
            self.executor.shutdown()
        self.executor = None

    @run_on_executor
    def resolve(self, host, port, family=socket.AF_UNSPEC):
        return _resolve_addr(host, port, family)


class BlockingResolver(ExecutorResolver):
    """Default `Resolver` implementation, using `socket.getaddrinfo`.

    The `.IOLoop` will be blocked during the resolution, although the
    callback will not be run until the next `.IOLoop` iteration.

    .. deprecated:: 5.0
       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
       of this class.
    """
    def initialize(self):
        super(BlockingResolver, self).initialize()


class ThreadedResolver(ExecutorResolver):
    """Multithreaded non-blocking `Resolver` implementation.

    Requires the `concurrent.futures` package to be installed
    (available in the standard library since Python 3.2,
    installable with ``pip install futures`` in older versions).

    The thread pool size can be configured with::

        Resolver.configure('tornado.netutil.ThreadedResolver',
                           num_threads=10)

    .. versionchanged:: 3.1
       All ``ThreadedResolvers`` share a single thread pool, whose
       size is set by the first one to be created.

    .. deprecated:: 5.0
       The default `Resolver` now uses `.IOLoop.run_in_executor`; use that instead
       of this class.
    """
    _threadpool = None  # type: ignore
    _threadpool_pid = None  # type: int

    def initialize(self, num_threads=10):
        threadpool = ThreadedResolver._create_threadpool(num_threads)
        super(ThreadedResolver, self).initialize(
            executor=threadpool, close_executor=False)

    @classmethod
    def _create_threadpool(cls, num_threads):
        pid = os.getpid()
        if cls._threadpool_pid != pid:
            # Threads cannot survive after a fork, so if our pid isn't what it
            # was when we created the pool then delete it.
            cls._threadpool = None
        if cls._threadpool is None:
            from concurrent.futures import ThreadPoolExecutor
            cls._threadpool = ThreadPoolExecutor(num_threads)
            cls._threadpool_pid = pid
        return cls._threadpool


class OverrideResolver(Resolver):
    """Wraps a resolver with a mapping of overrides.

    This can be used to make local DNS changes (e.g. for testing)
    without modifying system-wide settings.

    The mapping can contain either host strings or host-port pairs.
    """
    def initialize(self, resolver, mapping):
        self.resolver = resolver
        self.mapping = mapping

    def close(self):
        self.resolver.close()

    def resolve(self, host, port, *args, **kwargs):
        if (host, port) in self.mapping:
            host, port = self.mapping[(host, port)]
        elif host in self.mapping:
            host = self.mapping[host]
        return self.resolver.resolve(host, port, *args, **kwargs)


# These are the keyword arguments to ssl.wrap_socket that must be translated
# to their SSLContext equivalents (the other arguments are still passed
# to SSLContext.wrap_socket).
_SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile',
                                   'cert_reqs', 'ca_certs', 'ciphers'])


def ssl_options_to_context(ssl_options):
    """Try to convert an ``ssl_options`` dictionary to an
    `~ssl.SSLContext` object.

    The ``ssl_options`` dictionary contains keywords to be passed to
    `ssl.wrap_socket`.  In Python 2.7.9+, `ssl.SSLContext` objects can
    be used instead.  This function converts the dict form to its
    `~ssl.SSLContext` equivalent, and may be used when a component which
    accepts both forms needs to upgrade to the `~ssl.SSLContext` version
    to use features like SNI or NPN.
    """
    if isinstance(ssl_options, ssl.SSLContext):
        return ssl_options
    assert isinstance(ssl_options, dict)
    assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options
    # Can't use create_default_context since this interface doesn't
    # tell us client vs server.
    context = ssl.SSLContext(
        ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23))
    if 'certfile' in ssl_options:
        context.load_cert_chain(ssl_options['certfile'], ssl_options.get('keyfile', None))
    if 'cert_reqs' in ssl_options:
        context.verify_mode = ssl_options['cert_reqs']
    if 'ca_certs' in ssl_options:
        context.load_verify_locations(ssl_options['ca_certs'])
    if 'ciphers' in ssl_options:
        context.set_ciphers(ssl_options['ciphers'])
    if hasattr(ssl, 'OP_NO_COMPRESSION'):
        # Disable TLS compression to avoid CRIME and related attacks.
        # This constant depends on openssl version 1.0.
        # TODO: Do we need to do this ourselves or can we trust
        # the defaults?
        context.options |= ssl.OP_NO_COMPRESSION
    return context


def ssl_wrap_socket(socket, ssl_options, server_hostname=None, **kwargs):
    """Returns an ``ssl.SSLSocket`` wrapping the given socket.

    ``ssl_options`` may be either an `ssl.SSLContext` object or a
    dictionary (as accepted by `ssl_options_to_context`).  Additional
    keyword arguments are passed to ``wrap_socket`` (either the
    `~ssl.SSLContext` method or the `ssl` module function as
    appropriate).
    """
    context = ssl_options_to_context(ssl_options)
    if ssl.HAS_SNI:
        # In python 3.4, wrap_socket only accepts the server_hostname
        # argument if HAS_SNI is true.
        # TODO: add a unittest (python added server-side SNI support in 3.4)
        # In the meantime it can be manually tested with
        # python3 -m tornado.httpclient https://sni.velox.ch
        return context.wrap_socket(socket, server_hostname=server_hostname,
                                   **kwargs)
    else:
        return context.wrap_socket(socket, **kwargs)

```
--- END FILE ---

Please first localize the bug based on the issue statement, and then generate *SEARCH/REPLACE* edits to fix the issue.

Every *SEARCH/REPLACE* edit must use this format:
1. The file path
2. The start of search block: <<<<<<< SEARCH
3. A contiguous chunk of lines to search for in the existing source code
4. The dividing line: =======
5. The lines to replace into the source code
6. The end of the replace block: >>>>>>> REPLACE

Here is an example:

```python
### mathweb/flask/app.py
<<<<<<< SEARCH
from flask import Flask
=======
import math
from flask import Flask
>>>>>>> REPLACE
```
</solution>

Please note that the *SEARCH/REPLACE* edit REQUIRES PROPER INDENTATION. If you would like to add the line '        print(x)', you must fully write that out, with all those spaces before the code!
Wrap each *SEARCH/REPLACE* edit in a code block as shown in the example above. If you have multiple *SEARCH/REPLACE* edits, use a separate code block for each one.
user