{
    "file_diffs": [
        {
            "old_file_content": "#\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\nimport concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\n\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\n\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n# Note that the naming of ssl.Purpose is confusing; the purpose\n# of a context is to authenticate the opposite side of the connection.\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\nif 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\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# Default backlog used when calling sock.listen()\n_DEFAULT_BACKLOG = 128\n\n\ndef bind_sockets(\n    port: int,\n    address: Optional[str] = None,\n    family: socket.AddressFamily = socket.AF_UNSPEC,\n    backlog: int = _DEFAULT_BACKLOG,\n    flags: Optional[int] = None,\n    reuse_port: bool = False,\n) -> List[socket.socket]:\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    unique_addresses = set()  # type: set\n    for res in sorted(\n        socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),\n        key=lambda x: x[0],\n    ):\n        if res in unique_addresses:\n            continue\n\n        unique_addresses.add(res)\n\n        af, socktype, proto, canonname, sockaddr = res\n        if (\n            sys.platform == \"darwin\"\n            and address == \"localhost\"\n            and af == socket.AF_INET6\n            and sockaddr[3] != 0\n        ):\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        if os.name != \"nt\":\n            try:\n                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            except socket.error as e:\n                if errno_from_exception(e) != errno.ENOPROTOOPT:\n                    # Hurd doesn't support SO_REUSEADDR.\n                    raise\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(False)\n        try:\n            sock.bind(sockaddr)\n        except OSError as e:\n            if (\n                errno_from_exception(e) == errno.EADDRNOTAVAIL\n                and address == \"localhost\"\n                and sockaddr[0] == \"::1\"\n            ):\n                # On some systems (most notably docker with default\n                # configurations), ipv6 is partially disabled:\n                # socket.has_ipv6 is true, we can create AF_INET6\n                # sockets, and getaddrinfo(\"localhost\", ...,\n                # AF_PASSIVE) resolves to ::1, but we get an error\n                # when binding.\n                #\n                # Swallow the error, but only for this specific case.\n                # If EADDRNOTAVAIL occurs in other situations, it\n                # might be a real problem like a typo in a\n                # configuration.\n                sock.close()\n                continue\n            else:\n                raise\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\n    def bind_unix_socket(\n        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG\n    ) -> socket.socket:\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        try:\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        except socket.error as e:\n            if errno_from_exception(e) != errno.ENOPROTOOPT:\n                # Hurd doesn't support SO_REUSEADDR\n                raise\n        sock.setblocking(False)\n        try:\n            st = os.stat(file)\n        except FileNotFoundError:\n            pass\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(\n    sock: socket.socket, callback: Callable[[socket.socket, Any], None]\n) -> Callable[[], None]:\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: socket.socket, events: int) -> None:\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 range(_DEFAULT_BACKLOG):\n            if removed[0]:\n                # The socket was probably closed\n                return\n            try:\n                connection, address = sock.accept()\n            except BlockingIOError:\n                # EWOULDBLOCK indicates we have accepted every\n                # connection that is available.\n                return\n            except ConnectionAbortedError:\n                # ECONNABORTED indicates that there was a connection\n                # but it was closed while still in the accept queue.\n                # (observed on FreeBSD).\n                continue\n            callback(connection, address)\n\n    def remove_handler() -> None:\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: str) -> bool:\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(\n            ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST\n        )\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\n    @classmethod\n    def configurable_base(cls) -> Type[\"Resolver\"]:\n        return Resolver\n\n    @classmethod\n    def configurable_default(cls) -> Type[\"Resolver\"]:\n        return DefaultExecutorResolver\n\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> Awaitable[List[Tuple[int, Any]]]:\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        .. versionchanged:: 6.0 The ``callback`` argument was removed.\n           Use the returned awaitable object instead.\n\n        \"\"\"\n        raise NotImplementedError()\n\n    def close(self) -> None:\n        \"\"\"Closes the `Resolver`, freeing any resources used.\n\n        .. versionadded:: 3.1\n\n        \"\"\"\n        pass\n\n\ndef _resolve_addr(\n    host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n) -> List[Tuple[int, Any]]:\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 fam, socktype, proto, canonname, address in addrinfo:\n        results.append((fam, address))\n    return results  # type: ignore\n\n\nclass DefaultExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using `.IOLoop.run_in_executor`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n\n    async def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> List[Tuple[int, Any]]:\n        result = await IOLoop.current().run_in_executor(\n            None, _resolve_addr, host, port, family\n        )\n        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\n    def initialize(\n        self,\n        executor: Optional[concurrent.futures.Executor] = None,\n        close_executor: bool = True,\n    ) -> None:\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) -> None:\n        if self.close_executor:\n            self.executor.shutdown()\n        self.executor = None  # type: ignore\n\n    @run_on_executor\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> List[Tuple[int, Any]]:\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\n    def initialize(self) -> None:  # type: ignore\n        super().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\n    _threadpool = None  # type: ignore\n    _threadpool_pid = None  # type: int\n\n    def initialize(self, num_threads: int = 10) -> None:  # type: ignore\n        threadpool = ThreadedResolver._create_threadpool(num_threads)\n        super().initialize(executor=threadpool, close_executor=False)\n\n    @classmethod\n    def _create_threadpool(\n        cls, num_threads: int\n    ) -> concurrent.futures.ThreadPoolExecutor:\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            cls._threadpool = concurrent.futures.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 be in three formats::\n\n        {\n            # Hostname to host or ip\n            \"example.com\": \"127.0.1.1\",\n\n            # Host+port to host+port\n            (\"login.example.com\", 443): (\"localhost\", 1443),\n\n            # Host+port+address family to host+port\n            (\"login.example.com\", 443, socket.AF_INET6): (\"::1\", 1443),\n        }\n\n    .. versionchanged:: 5.0\n       Added support for host-port-family triplets.\n    \"\"\"\n\n    def initialize(self, resolver: Resolver, mapping: dict) -> None:\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self) -> None:\n        self.resolver.close()\n\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> Awaitable[List[Tuple[int, Any]]]:\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)\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(\n    [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\n\ndef ssl_options_to_context(\n    ssl_options: Union[Dict[str, Any], ssl.SSLContext]\n) -> ssl.SSLContext:\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(ssl_options.get(\"ssl_version\", ssl.PROTOCOL_SSLv23))\n    if \"certfile\" in ssl_options:\n        context.load_cert_chain(\n            ssl_options[\"certfile\"], ssl_options.get(\"keyfile\", None)\n        )\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(\n    socket: socket.socket,\n    ssl_options: Union[Dict[str, Any], ssl.SSLContext],\n    server_hostname: Optional[str] = None,\n    **kwargs: Any\n) -> ssl.SSLSocket:\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, **kwargs)\n    else:\n        return context.wrap_socket(socket, **kwargs)\n",
            "new_file_content": "#\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\nimport concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\n\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\n\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n# Note that the naming of ssl.Purpose is confusing; the purpose\n# of a context is to authenticate the opposite side of the connection.\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\nif 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\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# Default backlog used when calling sock.listen()\n_DEFAULT_BACKLOG = 128\n\n\ndef bind_sockets(\n    port: int,\n    address: Optional[str] = None,\n    family: socket.AddressFamily = socket.AF_UNSPEC,\n    backlog: int = _DEFAULT_BACKLOG,\n    flags: Optional[int] = None,\n    reuse_port: bool = False,\n) -> List[socket.socket]:\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    unique_addresses = set()  # type: set\n    for res in sorted(\n        socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),\n        key=lambda x: x[0],\n    ):\n        if res in unique_addresses:\n            continue\n\n        unique_addresses.add(res)\n\n        af, socktype, proto, canonname, sockaddr = res\n        if (\n            sys.platform == \"darwin\"\n            and address == \"localhost\"\n            and af == socket.AF_INET6\n            and sockaddr[3] != 0\n        ):\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        if os.name != \"nt\":\n            try:\n                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            except socket.error as e:\n                if errno_from_exception(e) != errno.ENOPROTOOPT:\n                    # Hurd doesn't support SO_REUSEADDR.\n                    raise\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(False)\n        try:\n            sock.bind(sockaddr)\n        except OSError as e:\n            if (\n                errno_from_exception(e) == errno.EADDRNOTAVAIL\n                and address == \"localhost\"\n                and sockaddr[0] == \"::1\"\n            ):\n                # On some systems (most notably docker with default\n                # configurations), ipv6 is partially disabled:\n                # socket.has_ipv6 is true, we can create AF_INET6\n                # sockets, and getaddrinfo(\"localhost\", ...,\n                # AF_PASSIVE) resolves to ::1, but we get an error\n                # when binding.\n                #\n                # Swallow the error, but only for this specific case.\n                # If EADDRNOTAVAIL occurs in other situations, it\n                # might be a real problem like a typo in a\n                # configuration.\n                sock.close()\n                continue\n            else:\n                raise\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\n    def bind_unix_socket(\n        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG\n    ) -> socket.socket:\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        try:\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        except socket.error as e:\n            if errno_from_exception(e) != errno.ENOPROTOOPT:\n                # Hurd doesn't support SO_REUSEADDR\n                raise\n        sock.setblocking(False)\n        try:\n            st = os.stat(file)\n        except FileNotFoundError:\n            pass\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(\n    sock: socket.socket, callback: Callable[[socket.socket, Any], None]\n) -> Callable[[], None]:\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: socket.socket, events: int) -> None:\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 range(_DEFAULT_BACKLOG):\n            if removed[0]:\n                # The socket was probably closed\n                return\n            try:\n                connection, address = sock.accept()\n            except BlockingIOError:\n                # EWOULDBLOCK indicates we have accepted every\n                # connection that is available.\n                return\n            except ConnectionAbortedError:\n                # ECONNABORTED indicates that there was a connection\n                # but it was closed while still in the accept queue.\n                # (observed on FreeBSD).\n                continue\n            callback(connection, address)\n\n    def remove_handler() -> None:\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: str) -> bool:\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(\n            ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST\n        )\n        return bool(res)\n    except socket.gaierror as e:\n        if e.args[0] == socket.EAI_NONAME:\n            return False\n        raise\n    except UnicodeError:\n        # `socket.getaddrinfo` will raise a UnicodeError from the\n        # `idna` decoder if the input is longer than 63 characters,\n        # even for socket.AI_NUMERICHOST.  See\n        # https://bugs.python.org/issue32958 for discussion\n        return False\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\n    @classmethod\n    def configurable_base(cls) -> Type[\"Resolver\"]:\n        return Resolver\n\n    @classmethod\n    def configurable_default(cls) -> Type[\"Resolver\"]:\n        return DefaultExecutorResolver\n\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> Awaitable[List[Tuple[int, Any]]]:\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        .. versionchanged:: 6.0 The ``callback`` argument was removed.\n           Use the returned awaitable object instead.\n\n        \"\"\"\n        raise NotImplementedError()\n\n    def close(self) -> None:\n        \"\"\"Closes the `Resolver`, freeing any resources used.\n\n        .. versionadded:: 3.1\n\n        \"\"\"\n        pass\n\n\ndef _resolve_addr(\n    host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n) -> List[Tuple[int, Any]]:\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 fam, socktype, proto, canonname, address in addrinfo:\n        results.append((fam, address))\n    return results  # type: ignore\n\n\nclass DefaultExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using `.IOLoop.run_in_executor`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n\n    async def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> List[Tuple[int, Any]]:\n        result = await IOLoop.current().run_in_executor(\n            None, _resolve_addr, host, port, family\n        )\n        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\n    def initialize(\n        self,\n        executor: Optional[concurrent.futures.Executor] = None,\n        close_executor: bool = True,\n    ) -> None:\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) -> None:\n        if self.close_executor:\n            self.executor.shutdown()\n        self.executor = None  # type: ignore\n\n    @run_on_executor\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> List[Tuple[int, Any]]:\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\n    def initialize(self) -> None:  # type: ignore\n        super().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\n    _threadpool = None  # type: ignore\n    _threadpool_pid = None  # type: int\n\n    def initialize(self, num_threads: int = 10) -> None:  # type: ignore\n        threadpool = ThreadedResolver._create_threadpool(num_threads)\n        super().initialize(executor=threadpool, close_executor=False)\n\n    @classmethod\n    def _create_threadpool(\n        cls, num_threads: int\n    ) -> concurrent.futures.ThreadPoolExecutor:\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            cls._threadpool = concurrent.futures.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 be in three formats::\n\n        {\n            # Hostname to host or ip\n            \"example.com\": \"127.0.1.1\",\n\n            # Host+port to host+port\n            (\"login.example.com\", 443): (\"localhost\", 1443),\n\n            # Host+port+address family to host+port\n            (\"login.example.com\", 443, socket.AF_INET6): (\"::1\", 1443),\n        }\n\n    .. versionchanged:: 5.0\n       Added support for host-port-family triplets.\n    \"\"\"\n\n    def initialize(self, resolver: Resolver, mapping: dict) -> None:\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self) -> None:\n        self.resolver.close()\n\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> Awaitable[List[Tuple[int, Any]]]:\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)\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(\n    [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\n\ndef ssl_options_to_context(\n    ssl_options: Union[Dict[str, Any], ssl.SSLContext]\n) -> ssl.SSLContext:\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(ssl_options.get(\"ssl_version\", ssl.PROTOCOL_SSLv23))\n    if \"certfile\" in ssl_options:\n        context.load_cert_chain(\n            ssl_options[\"certfile\"], ssl_options.get(\"keyfile\", None)\n        )\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(\n    socket: socket.socket,\n    ssl_options: Union[Dict[str, Any], ssl.SSLContext],\n    server_hostname: Optional[str] = None,\n    **kwargs: Any\n) -> ssl.SSLSocket:\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, **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": "f8a30380",
                "new_commit_hash": "15eea970",
                "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": 301,
                            "length": 6
                        },
                        "new_range": {
                            "start": 301,
                            "length": 12
                        },
                        "section": "def is_valid_ip(ip: str) -> bool:"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        if e.args[0] == socket.EAI_NONAME:",
                                "type": "context"
                            },
                            {
                                "content": "            return False",
                                "type": "context"
                            },
                            {
                                "content": "        raise",
                                "type": "context"
                            },
                            {
                                "content": "    except UnicodeError:",
                                "type": "added"
                            },
                            {
                                "content": "        # `socket.getaddrinfo` will raise a UnicodeError from the",
                                "type": "added"
                            },
                            {
                                "content": "        # `idna` decoder if the input is longer than 63 characters,",
                                "type": "added"
                            },
                            {
                                "content": "        # even for socket.AI_NUMERICHOST.  See",
                                "type": "added"
                            },
                            {
                                "content": "        # https://bugs.python.org/issue32958 for discussion",
                                "type": "added"
                            },
                            {
                                "content": "        return False",
                                "type": "added"
                            },
                            {
                                "content": "    return True",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/netutil.py",
                            "type": "function",
                            "name": "is_valid_ip",
                            "content": "def is_valid_ip(ip: str) -> bool:\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(\n            ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST\n        )\n        return bool(res)\n    except socket.gaierror as e:\n        if e.args[0] == socket.EAI_NONAME:\n            return False\n        raise\n    except UnicodeError:\n        # `socket.getaddrinfo` will raise a UnicodeError from the\n        # `idna` decoder if the input is longer than 63 characters,\n        # even for socket.AI_NUMERICHOST.  See\n        # https://bugs.python.org/issue32958 for discussion\n        return False\n    return True",
                            "ast_type_str": "FunctionDef",
                            "start_lineno": 286,
                            "end_lineno": 310,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        },
        {
            "old_file_content": "import errno\nimport os\nimport signal\nimport socket\nfrom subprocess import Popen\nimport sys\nimport time\nimport unittest\n\nfrom tornado.netutil import (\n    BlockingResolver,\n    OverrideResolver,\n    ThreadedResolver,\n    is_valid_ip,\n    bind_sockets,\n)\nfrom tornado.testing import AsyncTestCase, gen_test, bind_unused_port\nfrom tornado.test.util import skipIfNoNetwork\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List  # noqa: F401\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    resolver = None  # type: typing.Any\n\n    @gen_test\n    def test_localhost(self: typing.Any):\n        addrinfo = yield self.resolver.resolve(\"localhost\", 80, socket.AF_UNSPEC)\n        self.assertIn((socket.AF_INET, (\"127.0.0.1\", 80)), 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    resolver = None  # type: typing.Any\n\n    @gen_test\n    def test_bad_host(self: typing.Any):\n        with self.assertRaises(IOError):\n            yield self.resolver.resolve(\"an invalid domain\", 80, 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().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().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().tearDown()\n\n\nclass OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().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): (\n                \"2a02:6b8:7c:40c:c51e:495f:e23a:3\",\n                80,\n            ),\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    @gen_test\n    def test_resolve_multiaddr(self):\n        result = yield self.resolver.resolve(\"google.com\", 80, socket.AF_INET)\n        self.assertIn((socket.AF_INET, (\"1.2.3.4\", 80)), result)\n\n        result = yield self.resolver.resolve(\"google.com\", 80, socket.AF_INET6)\n        self.assertIn(\n            (socket.AF_INET6, (\"2a02:6b8:7c:40c:c51e:495f:e23a:3\", 80, 0, 0)), result\n        )\n\n\n@skipIfNoNetwork\nclass ThreadedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().setUp()\n        self.resolver = ThreadedResolver()\n\n    def tearDown(self):\n        self.resolver.close()\n        super().tearDown()\n\n\nclass ThreadedResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super().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().tearDown()\n\n\n@skipIfNoNetwork\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 = [sys.executable, \"-c\", \"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\")\n@unittest.skipIf(sys.platform == \"win32\", \"pycares doesn't return loopback on windows\")\n@unittest.skipIf(sys.platform == \"darwin\", \"pycares doesn't return 127.0.0.1 on darwin\")\nclass CaresResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().setUp()\n        self.resolver = CaresResolver()\n\n\n# TwistedResolver produces consistent errors in our test cases so we\n# could test the regular and error cases in the same class. However,\n# in the error cases it appears that cleanup of socket objects is\n# handled asynchronously and occasionally results in \"unclosed socket\"\n# warnings if not given time to shut down (and there is no way to\n# explicitly shut it down). This makes the test flaky, so we do not\n# test error cases here.\n@skipIfNoNetwork\n@unittest.skipIf(twisted is None, \"twisted module not present\")\n@unittest.skipIf(\n    getattr(twisted, \"__version__\", \"0.0\") < \"12.1\", \"old version of twisted\"\n)\n@unittest.skipIf(sys.platform == \"win32\", \"twisted resolver hangs on windows\")\nclass TwistedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().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(0, \"localhost\")\n        try:\n            port = sockets[0].getsockname()[1]\n            self.assertTrue(all(s.getsockname()[1] == port for s in sockets[1:]))\n        finally:\n            for sock in sockets:\n                sock.close()\n\n    @unittest.skipIf(\n        not hasattr(socket, \"SO_REUSEPORT\"), \"SO_REUSEPORT is not supported\"\n    )\n    def test_reuse_port(self):\n        sockets = []  # type: List[socket.socket]\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": "import errno\nimport os\nimport signal\nimport socket\nfrom subprocess import Popen\nimport sys\nimport time\nimport unittest\n\nfrom tornado.netutil import (\n    BlockingResolver,\n    OverrideResolver,\n    ThreadedResolver,\n    is_valid_ip,\n    bind_sockets,\n)\nfrom tornado.testing import AsyncTestCase, gen_test, bind_unused_port\nfrom tornado.test.util import skipIfNoNetwork\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List  # noqa: F401\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    resolver = None  # type: typing.Any\n\n    @gen_test\n    def test_localhost(self: typing.Any):\n        addrinfo = yield self.resolver.resolve(\"localhost\", 80, socket.AF_UNSPEC)\n        self.assertIn((socket.AF_INET, (\"127.0.0.1\", 80)), 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    resolver = None  # type: typing.Any\n\n    @gen_test\n    def test_bad_host(self: typing.Any):\n        with self.assertRaises(IOError):\n            yield self.resolver.resolve(\"an invalid domain\", 80, 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().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().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().tearDown()\n\n\nclass OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().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): (\n                \"2a02:6b8:7c:40c:c51e:495f:e23a:3\",\n                80,\n            ),\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    @gen_test\n    def test_resolve_multiaddr(self):\n        result = yield self.resolver.resolve(\"google.com\", 80, socket.AF_INET)\n        self.assertIn((socket.AF_INET, (\"1.2.3.4\", 80)), result)\n\n        result = yield self.resolver.resolve(\"google.com\", 80, socket.AF_INET6)\n        self.assertIn(\n            (socket.AF_INET6, (\"2a02:6b8:7c:40c:c51e:495f:e23a:3\", 80, 0, 0)), result\n        )\n\n\n@skipIfNoNetwork\nclass ThreadedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().setUp()\n        self.resolver = ThreadedResolver()\n\n    def tearDown(self):\n        self.resolver.close()\n        super().tearDown()\n\n\nclass ThreadedResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super().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().tearDown()\n\n\n@skipIfNoNetwork\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 = [sys.executable, \"-c\", \"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\")\n@unittest.skipIf(sys.platform == \"win32\", \"pycares doesn't return loopback on windows\")\n@unittest.skipIf(sys.platform == \"darwin\", \"pycares doesn't return 127.0.0.1 on darwin\")\nclass CaresResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().setUp()\n        self.resolver = CaresResolver()\n\n\n# TwistedResolver produces consistent errors in our test cases so we\n# could test the regular and error cases in the same class. However,\n# in the error cases it appears that cleanup of socket objects is\n# handled asynchronously and occasionally results in \"unclosed socket\"\n# warnings if not given time to shut down (and there is no way to\n# explicitly shut it down). This makes the test flaky, so we do not\n# test error cases here.\n@skipIfNoNetwork\n@unittest.skipIf(twisted is None, \"twisted module not present\")\n@unittest.skipIf(\n    getattr(twisted, \"__version__\", \"0.0\") < \"12.1\", \"old version of twisted\"\n)\n@unittest.skipIf(sys.platform == \"win32\", \"twisted resolver hangs on windows\")\nclass TwistedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().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        self.assertTrue(not is_valid_ip(\"a\" * 100))\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(0, \"localhost\")\n        try:\n            port = sockets[0].getsockname()[1]\n            self.assertTrue(all(s.getsockname()[1] == port for s in sockets[1:]))\n        finally:\n            for sock in sockets:\n                sock.close()\n\n    @unittest.skipIf(\n        not hasattr(socket, \"SO_REUSEPORT\"), \"SO_REUSEPORT is not supported\"\n    )\n    def test_reuse_port(self):\n        sockets = []  # type: List[socket.socket]\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": "f36b7c27",
                "new_commit_hash": "3911be6a",
                "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": 204,
                            "length": 6
                        },
                        "new_range": {
                            "start": 204,
                            "length": 7
                        },
                        "section": "class IsValidIPTest(unittest.TestCase):"
                    },
                    "line_group": {
                        "all_lines": [
                            {
                                "content": "        self.assertTrue(not is_valid_ip(\" \"))",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertTrue(not is_valid_ip(\"\\n\"))",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertTrue(not is_valid_ip(\"\\x00\"))",
                                "type": "context"
                            },
                            {
                                "content": "        self.assertTrue(not is_valid_ip(\"a\" * 100))",
                                "type": "added"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            },
                            {
                                "content": "class TestPortAllocation(unittest.TestCase):",
                                "type": "context"
                            },
                            {
                                "content": "",
                                "type": "context"
                            }
                        ]
                    },
                    "modified_entities": [
                        {
                            "file_name": "tornado/test/netutil_test.py",
                            "type": "method",
                            "name": "IsValidIPTest.test_is_valid_ip",
                            "content": "class 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        self.assertTrue(not is_valid_ip(\"a\" * 100))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 194,
                            "end_lineno": 207,
                            "parent": {
                                "file_name": "tornado/test/netutil_test.py",
                                "type": "class",
                                "name": "IsValidIPTest",
                                "content": "class 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        self.assertTrue(not is_valid_ip(\"a\" * 100))",
                                "ast_type_str": "ClassDef",
                                "start_lineno": 193,
                                "end_lineno": 207,
                                "parent": null
                            }
                        },
                        {
                            "file_name": "tornado/test/netutil_test.py",
                            "type": "class",
                            "name": "IsValidIPTest",
                            "content": "class 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        self.assertTrue(not is_valid_ip(\"a\" * 100))",
                            "ast_type_str": "ClassDef",
                            "start_lineno": 193,
                            "end_lineno": 207,
                            "parent": null
                        }
                    ],
                    "added_entities": [],
                    "deleted_entities": []
                }
            ]
        }
    ],
    "old_commit_hash": "149159d19334fe5f7c1b553e8f6c92a8e3f04385^",
    "new_commit_hash": "149159d19334fe5f7c1b553e8f6c92a8e3f04385",
    "commit_message": "is_valid_ip: Do not raise exceptions on too-long input.\n\nis_valid_ip calls `socket.getaddrinfo` with `socket.AI_NUMERICHOST` on\nthe potential \"ip\"; even though IP addresses are not hostnames and do\nnot use the `idna` encoding, `socket.getaddrinfo` will raise\nUnicodeError if the potential \"ip\" is longer than 63 characters long,\nthe RFC-mandated max hostname length.\n\nCatch these UnicodeErrors and return false for too-long IPs, rather\nthan raising an exception.",
    "commit_date": "2021-05-09T17:00:55-10:00",
    "metadata": {}
}
{
    "repo_name": "tornado",
    "new_commit_hash": "149159d19334fe5f7c1b553e8f6c92a8e3f04385",
    "test_file_codes": [
        "import errno\nimport os\nimport signal\nimport socket\nfrom subprocess import Popen\nimport sys\nimport time\nimport unittest\n\nfrom tornado.netutil import (\n    BlockingResolver,\n    OverrideResolver,\n    ThreadedResolver,\n    is_valid_ip,\n    bind_sockets,\n)\nfrom tornado.testing import AsyncTestCase, gen_test, bind_unused_port\nfrom tornado.test.util import skipIfNoNetwork\n\nimport typing\n\nif typing.TYPE_CHECKING:\n    from typing import List  # noqa: F401\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    resolver = None  # type: typing.Any\n\n    @gen_test\n    def test_localhost(self: typing.Any):\n        addrinfo = yield self.resolver.resolve(\"localhost\", 80, socket.AF_UNSPEC)\n        self.assertIn((socket.AF_INET, (\"127.0.0.1\", 80)), 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    resolver = None  # type: typing.Any\n\n    @gen_test\n    def test_bad_host(self: typing.Any):\n        with self.assertRaises(IOError):\n            yield self.resolver.resolve(\"an invalid domain\", 80, 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().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().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().tearDown()\n\n\nclass OverrideResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().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): (\n                \"2a02:6b8:7c:40c:c51e:495f:e23a:3\",\n                80,\n            ),\n        }\n        self.resolver = OverrideResolver(BlockingResolver(), mapping)\n\n    @gen_test\n    def test_resolve_multiaddr(self):\n        result = yield self.resolver.resolve(\"google.com\", 80, socket.AF_INET)\n        self.assertIn((socket.AF_INET, (\"1.2.3.4\", 80)), result)\n\n        result = yield self.resolver.resolve(\"google.com\", 80, socket.AF_INET6)\n        self.assertIn(\n            (socket.AF_INET6, (\"2a02:6b8:7c:40c:c51e:495f:e23a:3\", 80, 0, 0)), result\n        )\n\n\n@skipIfNoNetwork\nclass ThreadedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().setUp()\n        self.resolver = ThreadedResolver()\n\n    def tearDown(self):\n        self.resolver.close()\n        super().tearDown()\n\n\nclass ThreadedResolverErrorTest(AsyncTestCase, _ResolverErrorTestMixin):\n    def setUp(self):\n        super().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().tearDown()\n\n\n@skipIfNoNetwork\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 = [sys.executable, \"-c\", \"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\")\n@unittest.skipIf(sys.platform == \"win32\", \"pycares doesn't return loopback on windows\")\n@unittest.skipIf(sys.platform == \"darwin\", \"pycares doesn't return 127.0.0.1 on darwin\")\nclass CaresResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().setUp()\n        self.resolver = CaresResolver()\n\n\n# TwistedResolver produces consistent errors in our test cases so we\n# could test the regular and error cases in the same class. However,\n# in the error cases it appears that cleanup of socket objects is\n# handled asynchronously and occasionally results in \"unclosed socket\"\n# warnings if not given time to shut down (and there is no way to\n# explicitly shut it down). This makes the test flaky, so we do not\n# test error cases here.\n@skipIfNoNetwork\n@unittest.skipIf(twisted is None, \"twisted module not present\")\n@unittest.skipIf(\n    getattr(twisted, \"__version__\", \"0.0\") < \"12.1\", \"old version of twisted\"\n)\n@unittest.skipIf(sys.platform == \"win32\", \"twisted resolver hangs on windows\")\nclass TwistedResolverTest(AsyncTestCase, _ResolverTestMixin):\n    def setUp(self):\n        super().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        self.assertTrue(not is_valid_ip(\"a\" * 100))\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(0, \"localhost\")\n        try:\n            port = sockets[0].getsockname()[1]\n            self.assertTrue(all(s.getsockname()[1] == port for s in sockets[1:]))\n        finally:\n            for sock in sockets:\n                sock.close()\n\n    @unittest.skipIf(\n        not hasattr(socket, \"SO_REUSEPORT\"), \"SO_REUSEPORT is not supported\"\n    )\n    def test_reuse_port(self):\n        sockets = []  # type: List[socket.socket]\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 845ms\nPrepared 1 package in 996ms\nInstalled 1 package in 0.67ms\n + tornado==6.2.dev1 (from file:///home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_149159d19334fe5f7c1b553e8f6c92a8e3f04385)\nResolved 29 packages in 16ms\nInstalled 29 packages in 142ms\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: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_149159d19334fe5f7c1b553e8f6c92a8e3f04385\n............\ncollected 12 items\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::BlockingResolverErrorTest::test_bad_host\nPASSED r2e_tests.test_1::BlockingResolverTest::test_localhost\nPASSED r2e_tests.test_1::CaresResolverTest::test_localhost\nPASSED r2e_tests.test_1::IsValidIPTest::test_is_valid_ip\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::ThreadedResolverImportTest::test_import\nPASSED r2e_tests.test_1::ThreadedResolverTest::test_localhost\nPASSED r2e_tests.test_1::TwistedResolverTest::test_localhost\n=================== 12 passed in 0.11s ===================\n",
    "new_commit_res_stderr": "",
    "old_commit_res_code": 1,
    "old_commit_res_stdout": "============================= test session starts =============================\nplatform linux -- Python 3.9.21\nrootdir: /home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_149159d19334fe5f7c1b553e8f6c92a8e3f04385\n............\ncollected 12 items\n\n=================================== ERRORS =====================================\n__________ IsValidIPTest.test_is_valid_ip __________\nTraceback (most recent call last):\n  File \"/home/gcpuser/.local/share/uv/python/cpython-3.9.21-linux-x86_64-gnu/lib/python3.9/encodings/idna.py\", line 165, in encode\n    raise UnicodeError(\"label too long\")\nUnicodeError: label too long\n\nThe above exception was the direct cause of the following exception:\n\nTraceback (most recent call last):\n  File \"/home/gcpuser/.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 \"/home/gcpuser/.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 \"/home/gcpuser/.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 \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_149159d19334fe5f7c1b553e8f6c92a8e3f04385/r2e_tests/test_1.py\", line 207, in test_is_valid_ip\n    self.assertTrue(not is_valid_ip(\"a\" * 100))\n  File \"/home/gcpuser/buckets/local_repoeval_bucket/repos/tornado_149159d19334fe5f7c1b553e8f6c92a8e3f04385/tornado/netutil.py\", line 296, in is_valid_ip\n    res = socket.getaddrinfo(\n  File \"/home/gcpuser/.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):\nUnicodeError: encoding with 'idna' codec failed (UnicodeError: label too long)\n\n==================== short test summary info ====================\nPASSED r2e_tests.test_1::BlockingResolverErrorTest::test_bad_host\nPASSED r2e_tests.test_1::BlockingResolverTest::test_localhost\nPASSED r2e_tests.test_1::CaresResolverTest::test_localhost\nERROR r2e_tests.test_1::IsValidIPTest::test_is_valid_ip\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::ThreadedResolverImportTest::test_import\nPASSED r2e_tests.test_1::ThreadedResolverTest::test_localhost\nPASSED r2e_tests.test_1::TwistedResolverTest::test_localhost\n=================== 1 error, 11 passed in 0.11s ===================\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:** `is_valid_ip` Raises `UnicodeError` for Overly Long IP Input Instead of Returning False

**Description:**
When providing a string longer than 63 characters to the `is_valid_ip` function, it unexpectedly raises a `UnicodeError` instead of returning `False`. This behavior occurs because `socket.getaddrinfo` is called with `socket.AI_NUMERICHOST`, and excessively long inputs trigger an encoding error.

**Example Code:**
```python
def test_is_valid_ip_with_too_long_input():
    long_ip = "a" * 100
    is_valid_ip(long_ip)
```

**Expected Behavior:**
The `is_valid_ip` function should return `False` when the input exceeds the maximum allowed length for an IP address, indicating that the input is not a valid IP without raising any exceptions.

**Actual Behavior:**
Instead of returning `False`, the function raises a `UnicodeError` with the message: 
```
UnicodeError: encoding with 'idna' codec failed (UnicodeError: label too long)
```
This interrupts the normal flow and does not gracefully handle the invalid input as expected.
[/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
#
# 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."""

import concurrent.futures
import errno
import os
import sys
import socket
import ssl
import stat

from tornado.concurrent import dummy_executor, run_on_executor
from tornado.ioloop import IOLoop
from tornado.util import Configurable, errno_from_exception

from typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional

# Note that the naming of ssl.Purpose is confusing; the purpose
# of a context is to authenticate 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

# 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")

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


def bind_sockets(
    port: int,
    address: Optional[str] = None,
    family: socket.AddressFamily = socket.AF_UNSPEC,
    backlog: int = _DEFAULT_BACKLOG,
    flags: Optional[int] = None,
    reuse_port: bool = False,
) -> List[socket.socket]:
    """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
    unique_addresses = set()  # type: set
    for res in sorted(
        socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),
        key=lambda x: x[0],
    ):
        if res in unique_addresses:
            continue

        unique_addresses.add(res)

        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
        if os.name != "nt":
            try:
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            except socket.error as e:
                if errno_from_exception(e) != errno.ENOPROTOOPT:
                    # Hurd doesn't support SO_REUSEADDR.
                    raise
        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(False)
        try:
            sock.bind(sockaddr)
        except OSError as e:
            if (
                errno_from_exception(e) == errno.EADDRNOTAVAIL
                and address == "localhost"
                and sockaddr[0] == "::1"
            ):
                # On some systems (most notably docker with default
                # configurations), ipv6 is partially disabled:
                # socket.has_ipv6 is true, we can create AF_INET6
                # sockets, and getaddrinfo("localhost", ...,
                # AF_PASSIVE) resolves to ::1, but we get an error
                # when binding.
                #
                # Swallow the error, but only for this specific case.
                # If EADDRNOTAVAIL occurs in other situations, it
                # might be a real problem like a typo in a
                # configuration.
                sock.close()
                continue
            else:
                raise
        bound_port = sock.getsockname()[1]
        sock.listen(backlog)
        sockets.append(sock)
    return sockets


if hasattr(socket, "AF_UNIX"):

    def bind_unix_socket(
        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG
    ) -> socket.socket:
        """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)
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except socket.error as e:
            if errno_from_exception(e) != errno.ENOPROTOOPT:
                # Hurd doesn't support SO_REUSEADDR
                raise
        sock.setblocking(False)
        try:
            st = os.stat(file)
        except FileNotFoundError:
            pass
        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: socket.socket, callback: Callable[[socket.socket, Any], None]
) -> Callable[[], None]:
    """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: socket.socket, events: int) -> None:
        # 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 range(_DEFAULT_BACKLOG):
            if removed[0]:
                # The socket was probably closed
                return
            try:
                connection, address = sock.accept()
            except BlockingIOError:
                # EWOULDBLOCK indicates we have accepted every
                # connection that is available.
                return
            except ConnectionAbortedError:
                # ECONNABORTED indicates that there was a connection
                # but it was closed while still in the accept queue.
                # (observed on FreeBSD).
                continue
            callback(connection, address)

    def remove_handler() -> None:
        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: str) -> bool:
    """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) -> Type["Resolver"]:
        return Resolver

    @classmethod
    def configurable_default(cls) -> Type["Resolver"]:
        return DefaultExecutorResolver

    def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> Awaitable[List[Tuple[int, Any]]]:
        """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`.

        .. versionchanged:: 6.0 The ``callback`` argument was removed.
           Use the returned awaitable object instead.

        """
        raise NotImplementedError()

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

        .. versionadded:: 3.1

        """
        pass


def _resolve_addr(
    host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
) -> List[Tuple[int, Any]]:
    # 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 fam, socktype, proto, canonname, address in addrinfo:
        results.append((fam, address))
    return results  # type: ignore


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

    .. versionadded:: 5.0
    """

    async def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> List[Tuple[int, Any]]:
        result = await IOLoop.current().run_in_executor(
            None, _resolve_addr, host, port, family
        )
        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: Optional[concurrent.futures.Executor] = None,
        close_executor: bool = True,
    ) -> None:
        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) -> None:
        if self.close_executor:
            self.executor.shutdown()
        self.executor = None  # type: ignore

    @run_on_executor
    def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> List[Tuple[int, Any]]:
        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) -> None:  # type: ignore
        super().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: int = 10) -> None:  # type: ignore
        threadpool = ThreadedResolver._create_threadpool(num_threads)
        super().initialize(executor=threadpool, close_executor=False)

    @classmethod
    def _create_threadpool(
        cls, num_threads: int
    ) -> concurrent.futures.ThreadPoolExecutor:
        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:
            cls._threadpool = concurrent.futures.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 be in three formats::

        {
            # Hostname to host or ip
            "example.com": "127.0.1.1",

            # Host+port to host+port
            ("login.example.com", 443): ("localhost", 1443),

            # Host+port+address family to host+port
            ("login.example.com", 443, socket.AF_INET6): ("::1", 1443),
        }

    .. versionchanged:: 5.0
       Added support for host-port-family triplets.
    """

    def initialize(self, resolver: Resolver, mapping: dict) -> None:
        self.resolver = resolver
        self.mapping = mapping

    def close(self) -> None:
        self.resolver.close()

    def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> Awaitable[List[Tuple[int, Any]]]:
        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, family)


# 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: Union[Dict[str, Any], ssl.SSLContext]
) -> ssl.SSLContext:
    """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: socket.socket,
    ssl_options: Union[Dict[str, Any], ssl.SSLContext],
    server_hostname: Optional[str] = None,
    **kwargs: Any
) -> ssl.SSLSocket:
    """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:** `is_valid_ip` Raises `UnicodeError` for Overly Long IP Input Instead of Returning False

**Description:**
When providing a string longer than 63 characters to the `is_valid_ip` function, it unexpectedly raises a `UnicodeError` instead of returning `False`. This behavior occurs because `socket.getaddrinfo` is called with `socket.AI_NUMERICHOST`, and excessively long inputs trigger an encoding error.

**Example Code:**
```python
def test_is_valid_ip_with_too_long_input():
    long_ip = "a" * 100
    is_valid_ip(long_ip)
```

**Expected Behavior:**
The `is_valid_ip` function should return `False` when the input exceeds the maximum allowed length for an IP address, indicating that the input is not a valid IP without raising any exceptions.

**Actual Behavior:**
Instead of returning `False`, the function raises a `UnicodeError` with the message: 
```
UnicodeError: encoding with 'idna' codec failed (UnicodeError: label too long)
```
This interrupts the normal flow and does not gracefully handle the invalid input as expected.
[/ISSUE]
{
    "BlockingResolverErrorTest.test_bad_host": "PASSED",
    "BlockingResolverTest.test_localhost": "PASSED",
    "CaresResolverTest.test_localhost": "FAILED",
    "IsValidIPTest.test_is_valid_ip": "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",
    "ThreadedResolverImportTest.test_import": "PASSED",
    "ThreadedResolverTest.test_localhost": "PASSED",
    "TwistedResolverTest.test_localhost": "PASSED"
}
diff --git a/tornado/netutil.py b/tornado/netutil.py
index f8a30380..15eea970 100644
--- a/tornado/netutil.py
+++ b/tornado/netutil.py
@@ -301,6 +301,12 @@ def is_valid_ip(ip: str) -> bool:
         if e.args[0] == socket.EAI_NONAME:
             return False
         raise
+    except UnicodeError:
+        # `socket.getaddrinfo` will raise a UnicodeError from the
+        # `idna` decoder if the input is longer than 63 characters,
+        # even for socket.AI_NUMERICHOST.  See
+        # https://bugs.python.org/issue32958 for discussion
+        return False
     return True
 
 

{"tornado/netutil.py": "#\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\nimport concurrent.futures\nimport errno\nimport os\nimport sys\nimport socket\nimport ssl\nimport stat\n\nfrom tornado.concurrent import dummy_executor, run_on_executor\nfrom tornado.ioloop import IOLoop\nfrom tornado.util import Configurable, errno_from_exception\n\nfrom typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional\n\n# Note that the naming of ssl.Purpose is confusing; the purpose\n# of a context is to authenticate the opposite side of the connection.\n_client_ssl_defaults = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)\n_server_ssl_defaults = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\nif 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\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# Default backlog used when calling sock.listen()\n_DEFAULT_BACKLOG = 128\n\n\ndef bind_sockets(\n    port: int,\n    address: Optional[str] = None,\n    family: socket.AddressFamily = socket.AF_UNSPEC,\n    backlog: int = _DEFAULT_BACKLOG,\n    flags: Optional[int] = None,\n    reuse_port: bool = False,\n) -> List[socket.socket]:\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    unique_addresses = set()  # type: set\n    for res in sorted(\n        socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),\n        key=lambda x: x[0],\n    ):\n        if res in unique_addresses:\n            continue\n\n        unique_addresses.add(res)\n\n        af, socktype, proto, canonname, sockaddr = res\n        if (\n            sys.platform == \"darwin\"\n            and address == \"localhost\"\n            and af == socket.AF_INET6\n            and sockaddr[3] != 0\n        ):\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        if os.name != \"nt\":\n            try:\n                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n            except socket.error as e:\n                if errno_from_exception(e) != errno.ENOPROTOOPT:\n                    # Hurd doesn't support SO_REUSEADDR.\n                    raise\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(False)\n        try:\n            sock.bind(sockaddr)\n        except OSError as e:\n            if (\n                errno_from_exception(e) == errno.EADDRNOTAVAIL\n                and address == \"localhost\"\n                and sockaddr[0] == \"::1\"\n            ):\n                # On some systems (most notably docker with default\n                # configurations), ipv6 is partially disabled:\n                # socket.has_ipv6 is true, we can create AF_INET6\n                # sockets, and getaddrinfo(\"localhost\", ...,\n                # AF_PASSIVE) resolves to ::1, but we get an error\n                # when binding.\n                #\n                # Swallow the error, but only for this specific case.\n                # If EADDRNOTAVAIL occurs in other situations, it\n                # might be a real problem like a typo in a\n                # configuration.\n                sock.close()\n                continue\n            else:\n                raise\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\n    def bind_unix_socket(\n        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG\n    ) -> socket.socket:\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        try:\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        except socket.error as e:\n            if errno_from_exception(e) != errno.ENOPROTOOPT:\n                # Hurd doesn't support SO_REUSEADDR\n                raise\n        sock.setblocking(False)\n        try:\n            st = os.stat(file)\n        except FileNotFoundError:\n            pass\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(\n    sock: socket.socket, callback: Callable[[socket.socket, Any], None]\n) -> Callable[[], None]:\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: socket.socket, events: int) -> None:\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 range(_DEFAULT_BACKLOG):\n            if removed[0]:\n                # The socket was probably closed\n                return\n            try:\n                connection, address = sock.accept()\n            except BlockingIOError:\n                # EWOULDBLOCK indicates we have accepted every\n                # connection that is available.\n                return\n            except ConnectionAbortedError:\n                # ECONNABORTED indicates that there was a connection\n                # but it was closed while still in the accept queue.\n                # (observed on FreeBSD).\n                continue\n            callback(connection, address)\n\n    def remove_handler() -> None:\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: str) -> bool:\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(\n            ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST\n        )\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\n    @classmethod\n    def configurable_base(cls) -> Type[\"Resolver\"]:\n        return Resolver\n\n    @classmethod\n    def configurable_default(cls) -> Type[\"Resolver\"]:\n        return DefaultExecutorResolver\n\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> Awaitable[List[Tuple[int, Any]]]:\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        .. versionchanged:: 6.0 The ``callback`` argument was removed.\n           Use the returned awaitable object instead.\n\n        \"\"\"\n        raise NotImplementedError()\n\n    def close(self) -> None:\n        \"\"\"Closes the `Resolver`, freeing any resources used.\n\n        .. versionadded:: 3.1\n\n        \"\"\"\n        pass\n\n\ndef _resolve_addr(\n    host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n) -> List[Tuple[int, Any]]:\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 fam, socktype, proto, canonname, address in addrinfo:\n        results.append((fam, address))\n    return results  # type: ignore\n\n\nclass DefaultExecutorResolver(Resolver):\n    \"\"\"Resolver implementation using `.IOLoop.run_in_executor`.\n\n    .. versionadded:: 5.0\n    \"\"\"\n\n    async def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> List[Tuple[int, Any]]:\n        result = await IOLoop.current().run_in_executor(\n            None, _resolve_addr, host, port, family\n        )\n        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\n    def initialize(\n        self,\n        executor: Optional[concurrent.futures.Executor] = None,\n        close_executor: bool = True,\n    ) -> None:\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) -> None:\n        if self.close_executor:\n            self.executor.shutdown()\n        self.executor = None  # type: ignore\n\n    @run_on_executor\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> List[Tuple[int, Any]]:\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\n    def initialize(self) -> None:  # type: ignore\n        super().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\n    _threadpool = None  # type: ignore\n    _threadpool_pid = None  # type: int\n\n    def initialize(self, num_threads: int = 10) -> None:  # type: ignore\n        threadpool = ThreadedResolver._create_threadpool(num_threads)\n        super().initialize(executor=threadpool, close_executor=False)\n\n    @classmethod\n    def _create_threadpool(\n        cls, num_threads: int\n    ) -> concurrent.futures.ThreadPoolExecutor:\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            cls._threadpool = concurrent.futures.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 be in three formats::\n\n        {\n            # Hostname to host or ip\n            \"example.com\": \"127.0.1.1\",\n\n            # Host+port to host+port\n            (\"login.example.com\", 443): (\"localhost\", 1443),\n\n            # Host+port+address family to host+port\n            (\"login.example.com\", 443, socket.AF_INET6): (\"::1\", 1443),\n        }\n\n    .. versionchanged:: 5.0\n       Added support for host-port-family triplets.\n    \"\"\"\n\n    def initialize(self, resolver: Resolver, mapping: dict) -> None:\n        self.resolver = resolver\n        self.mapping = mapping\n\n    def close(self) -> None:\n        self.resolver.close()\n\n    def resolve(\n        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC\n    ) -> Awaitable[List[Tuple[int, Any]]]:\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)\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(\n    [\"ssl_version\", \"certfile\", \"keyfile\", \"cert_reqs\", \"ca_certs\", \"ciphers\"]\n)\n\n\ndef ssl_options_to_context(\n    ssl_options: Union[Dict[str, Any], ssl.SSLContext]\n) -> ssl.SSLContext:\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(ssl_options.get(\"ssl_version\", ssl.PROTOCOL_SSLv23))\n    if \"certfile\" in ssl_options:\n        context.load_cert_chain(\n            ssl_options[\"certfile\"], ssl_options.get(\"keyfile\", None)\n        )\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(\n    socket: socket.socket,\n    ssl_options: Union[Dict[str, Any], ssl.SSLContext],\n    server_hostname: Optional[str] = None,\n    **kwargs: Any\n) -> ssl.SSLSocket:\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, **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:** `is_valid_ip` Raises `UnicodeError` for Overly Long IP Input Instead of Returning False

**Description:**
When providing a string longer than 63 characters to the `is_valid_ip` function, it unexpectedly raises a `UnicodeError` instead of returning `False`. This behavior occurs because `socket.getaddrinfo` is called with `socket.AI_NUMERICHOST`, and excessively long inputs trigger an encoding error.

**Example Code:**
```python
def test_is_valid_ip_with_too_long_input():
    long_ip = "a" * 100
    is_valid_ip(long_ip)
```

**Expected Behavior:**
The `is_valid_ip` function should return `False` when the input exceeds the maximum allowed length for an IP address, indicating that the input is not a valid IP without raising any exceptions.

**Actual Behavior:**
Instead of returning `False`, the function raises a `UnicodeError` with the message: 
```
UnicodeError: encoding with 'idna' codec failed (UnicodeError: label too long)
```
This interrupts the normal flow and does not gracefully handle the invalid input as expected.
[/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
#
# 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."""

import concurrent.futures
import errno
import os
import sys
import socket
import ssl
import stat

from tornado.concurrent import dummy_executor, run_on_executor
from tornado.ioloop import IOLoop
from tornado.util import Configurable, errno_from_exception

from typing import List, Callable, Any, Type, Dict, Union, Tuple, Awaitable, Optional

# Note that the naming of ssl.Purpose is confusing; the purpose
# of a context is to authenticate 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

# 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")

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


def bind_sockets(
    port: int,
    address: Optional[str] = None,
    family: socket.AddressFamily = socket.AF_UNSPEC,
    backlog: int = _DEFAULT_BACKLOG,
    flags: Optional[int] = None,
    reuse_port: bool = False,
) -> List[socket.socket]:
    """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
    unique_addresses = set()  # type: set
    for res in sorted(
        socket.getaddrinfo(address, port, family, socket.SOCK_STREAM, 0, flags),
        key=lambda x: x[0],
    ):
        if res in unique_addresses:
            continue

        unique_addresses.add(res)

        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
        if os.name != "nt":
            try:
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            except socket.error as e:
                if errno_from_exception(e) != errno.ENOPROTOOPT:
                    # Hurd doesn't support SO_REUSEADDR.
                    raise
        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(False)
        try:
            sock.bind(sockaddr)
        except OSError as e:
            if (
                errno_from_exception(e) == errno.EADDRNOTAVAIL
                and address == "localhost"
                and sockaddr[0] == "::1"
            ):
                # On some systems (most notably docker with default
                # configurations), ipv6 is partially disabled:
                # socket.has_ipv6 is true, we can create AF_INET6
                # sockets, and getaddrinfo("localhost", ...,
                # AF_PASSIVE) resolves to ::1, but we get an error
                # when binding.
                #
                # Swallow the error, but only for this specific case.
                # If EADDRNOTAVAIL occurs in other situations, it
                # might be a real problem like a typo in a
                # configuration.
                sock.close()
                continue
            else:
                raise
        bound_port = sock.getsockname()[1]
        sock.listen(backlog)
        sockets.append(sock)
    return sockets


if hasattr(socket, "AF_UNIX"):

    def bind_unix_socket(
        file: str, mode: int = 0o600, backlog: int = _DEFAULT_BACKLOG
    ) -> socket.socket:
        """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)
        try:
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        except socket.error as e:
            if errno_from_exception(e) != errno.ENOPROTOOPT:
                # Hurd doesn't support SO_REUSEADDR
                raise
        sock.setblocking(False)
        try:
            st = os.stat(file)
        except FileNotFoundError:
            pass
        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: socket.socket, callback: Callable[[socket.socket, Any], None]
) -> Callable[[], None]:
    """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: socket.socket, events: int) -> None:
        # 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 range(_DEFAULT_BACKLOG):
            if removed[0]:
                # The socket was probably closed
                return
            try:
                connection, address = sock.accept()
            except BlockingIOError:
                # EWOULDBLOCK indicates we have accepted every
                # connection that is available.
                return
            except ConnectionAbortedError:
                # ECONNABORTED indicates that there was a connection
                # but it was closed while still in the accept queue.
                # (observed on FreeBSD).
                continue
            callback(connection, address)

    def remove_handler() -> None:
        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: str) -> bool:
    """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) -> Type["Resolver"]:
        return Resolver

    @classmethod
    def configurable_default(cls) -> Type["Resolver"]:
        return DefaultExecutorResolver

    def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> Awaitable[List[Tuple[int, Any]]]:
        """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`.

        .. versionchanged:: 6.0 The ``callback`` argument was removed.
           Use the returned awaitable object instead.

        """
        raise NotImplementedError()

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

        .. versionadded:: 3.1

        """
        pass


def _resolve_addr(
    host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
) -> List[Tuple[int, Any]]:
    # 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 fam, socktype, proto, canonname, address in addrinfo:
        results.append((fam, address))
    return results  # type: ignore


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

    .. versionadded:: 5.0
    """

    async def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> List[Tuple[int, Any]]:
        result = await IOLoop.current().run_in_executor(
            None, _resolve_addr, host, port, family
        )
        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: Optional[concurrent.futures.Executor] = None,
        close_executor: bool = True,
    ) -> None:
        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) -> None:
        if self.close_executor:
            self.executor.shutdown()
        self.executor = None  # type: ignore

    @run_on_executor
    def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> List[Tuple[int, Any]]:
        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) -> None:  # type: ignore
        super().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: int = 10) -> None:  # type: ignore
        threadpool = ThreadedResolver._create_threadpool(num_threads)
        super().initialize(executor=threadpool, close_executor=False)

    @classmethod
    def _create_threadpool(
        cls, num_threads: int
    ) -> concurrent.futures.ThreadPoolExecutor:
        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:
            cls._threadpool = concurrent.futures.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 be in three formats::

        {
            # Hostname to host or ip
            "example.com": "127.0.1.1",

            # Host+port to host+port
            ("login.example.com", 443): ("localhost", 1443),

            # Host+port+address family to host+port
            ("login.example.com", 443, socket.AF_INET6): ("::1", 1443),
        }

    .. versionchanged:: 5.0
       Added support for host-port-family triplets.
    """

    def initialize(self, resolver: Resolver, mapping: dict) -> None:
        self.resolver = resolver
        self.mapping = mapping

    def close(self) -> None:
        self.resolver.close()

    def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> Awaitable[List[Tuple[int, Any]]]:
        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, family)


# 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: Union[Dict[str, Any], ssl.SSLContext]
) -> ssl.SSLContext:
    """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: socket.socket,
    ssl_options: Union[Dict[str, Any], ssl.SSLContext],
    server_hostname: Optional[str] = None,
    **kwargs: Any
) -> ssl.SSLSocket:
    """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