We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
tests are stuck when running `make test`
I tried to use google's public dns as suggested by @sigmavirus24, but it didn't help.

``` shell
$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 brd 127.255.255.255 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: enp5s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    inet 192.168.0.17/24 brd 192.168.0.255 scope global enp5s0
       valid_lft forever preferred_lft forever
    inet6 fe80::beae:c5ff:fe65:dd71/64 scope link 
       valid_lft forever preferred_lft forever
$ cat /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4
```

strace:

``` shell
$ strace -p 12676
Process 12676 attached
futex(0xbf8dd0, FUTEX_WAIT_PRIVATE, 0, NULL
```

This is gentoo, wicd and python 2.7. I think I had the same problem with Fedora and NetworkManager.

Also, last couple of lines from output:

```
test_oldapi (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok
test_proxy_conn_fail (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok
test_proxy_pooling (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok
test_proxy_pooling_ext (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok
test_proxy_verified (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok
test_redirect (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok
test_multi_setcookie (test.with_dummyserver.test_socketlevel.TestCookies) ... Exception in thread Thread-8:
Traceback (most recent call last):
  File "/usr/lib64/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/home/tt/dev/urllib3/dummyserver/server.py", line 76, in run
    self.server = self._start_server()
  File "/home/tt/dev/urllib3/dummyserver/server.py", line 63, in _start_server
    sock.bind((self.host, 0))
  File "/usr/lib64/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: getsockaddrarg: bad family
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `dummyserver/server.py`
Content:
```
1 #!/usr/bin/env python
2 
3 """
4 Dummy server used for unit testing.
5 """
6 from __future__ import print_function
7 
8 import errno
9 import logging
10 import os
11 import random
12 import string
13 import sys
14 import threading
15 import socket
16 
17 from tornado.platform.auto import set_close_exec
18 import tornado.wsgi
19 import tornado.httpserver
20 import tornado.ioloop
21 import tornado.web
22 
23 
24 log = logging.getLogger(__name__)
25 
26 CERTS_PATH = os.path.join(os.path.dirname(__file__), 'certs')
27 DEFAULT_CERTS = {
28     'certfile': os.path.join(CERTS_PATH, 'server.crt'),
29     'keyfile': os.path.join(CERTS_PATH, 'server.key'),
30 }
31 NO_SAN_CERTS = {
32     'certfile': os.path.join(CERTS_PATH, 'server.no_san.crt'),
33     'keyfile': DEFAULT_CERTS['keyfile']
34 }
35 DEFAULT_CA = os.path.join(CERTS_PATH, 'cacert.pem')
36 DEFAULT_CA_BAD = os.path.join(CERTS_PATH, 'client_bad.pem')
37 NO_SAN_CA = os.path.join(CERTS_PATH, 'cacert.no_san.pem')
38 
39 
40 # Different types of servers we have:
41 
42 
43 class SocketServerThread(threading.Thread):
44     """
45     :param socket_handler: Callable which receives a socket argument for one
46         request.
47     :param ready_event: Event which gets set when the socket handler is
48         ready to receive requests.
49     """
50     def __init__(self, socket_handler, host='localhost', port=8081,
51                  ready_event=None):
52         threading.Thread.__init__(self)
53         self.daemon = True
54 
55         self.socket_handler = socket_handler
56         self.host = host
57         self.ready_event = ready_event
58 
59     def _start_server(self):
60         sock = socket.socket(socket.AF_INET6)
61         if sys.platform != 'win32':
62             sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
63         sock.bind((self.host, 0))
64         self.port = sock.getsockname()[1]
65 
66         # Once listen() returns, the server socket is ready
67         sock.listen(0)
68 
69         if self.ready_event:
70             self.ready_event.set()
71 
72         self.socket_handler(sock)
73         sock.close()
74 
75     def run(self):
76         self.server = self._start_server()
77 
78 
79 # FIXME: there is a pull request patching bind_sockets in Tornado directly.
80 # If it gets merged and released we can drop this and use
81 # `tornado.netutil.bind_sockets` again.
82 # https://github.com/facebook/tornado/pull/977
83 
84 def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128,
85                  flags=None):
86     """Creates listening sockets bound to the given port and address.
87 
88     Returns a list of socket objects (multiple sockets are returned if
89     the given address maps to multiple IP addresses, which is most common
90     for mixed IPv4 and IPv6 use).
91 
92     Address may be either an IP address or hostname.  If it's a hostname,
93     the server will listen on all IP addresses associated with the
94     name.  Address may be an empty string or None to listen on all
95     available interfaces.  Family may be set to either `socket.AF_INET`
96     or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
97     both will be used if available.
98 
99     The ``backlog`` argument has the same meaning as for
100     `socket.listen() <socket.socket.listen>`.
101 
102     ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
103     ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.
104     """
105     sockets = []
106     if address == "":
107         address = None
108     if not socket.has_ipv6 and family == socket.AF_UNSPEC:
109         # Python can be compiled with --disable-ipv6, which causes
110         # operations on AF_INET6 sockets to fail, but does not
111         # automatically exclude those results from getaddrinfo
112         # results.
113         # http://bugs.python.org/issue16208
114         family = socket.AF_INET
115     if flags is None:
116         flags = socket.AI_PASSIVE
117     binded_port = None
118     for res in set(socket.getaddrinfo(address, port, family,
119                                       socket.SOCK_STREAM, 0, flags)):
120         af, socktype, proto, canonname, sockaddr = res
121         try:
122             sock = socket.socket(af, socktype, proto)
123         except socket.error as e:
124             if e.args[0] == errno.EAFNOSUPPORT:
125                 continue
126             raise
127         set_close_exec(sock.fileno())
128         if os.name != 'nt':
129             sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
130         if af == socket.AF_INET6:
131             # On linux, ipv6 sockets accept ipv4 too by default,
132             # but this makes it impossible to bind to both
133             # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,
134             # separate sockets *must* be used to listen for both ipv4
135             # and ipv6.  For consistency, always disable ipv4 on our
136             # ipv6 sockets and use a separate ipv4 socket when needed.
137             #
138             # Python 2.x on windows doesn't have IPPROTO_IPV6.
139             if hasattr(socket, "IPPROTO_IPV6"):
140                 sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
141 
142         # automatic port allocation with port=None
143         # should bind on the same port on IPv4 and IPv6
144         host, requested_port = sockaddr[:2]
145         if requested_port == 0 and binded_port is not None:
146             sockaddr = tuple([host, binded_port] + list(sockaddr[2:]))
147 
148         sock.setblocking(0)
149         sock.bind(sockaddr)
150         binded_port = sock.getsockname()[1]
151         sock.listen(backlog)
152         sockets.append(sock)
153     return sockets
154 
155 
156 def run_tornado_app(app, io_loop, certs, scheme, host):
157     if scheme == 'https':
158         http_server = tornado.httpserver.HTTPServer(app, ssl_options=certs,
159                                                     io_loop=io_loop)
160     else:
161         http_server = tornado.httpserver.HTTPServer(app, io_loop=io_loop)
162 
163     sockets = bind_sockets(None, address=host)
164     port = sockets[0].getsockname()[1]
165     http_server.add_sockets(sockets)
166     return http_server, port
167 
168 
169 def run_loop_in_thread(io_loop):
170     t = threading.Thread(target=io_loop.start)
171     t.start()
172     return t
173 
174 
175 def get_unreachable_address():
176     while True:
177         host = ''.join(random.choice(string.ascii_lowercase)
178                        for _ in range(60))
179         sockaddr = (host, 54321)
180 
181         # check if we are really "lucky" and hit an actual server
182         try:
183             s = socket.create_connection(sockaddr)
184         except socket.error:
185             return sockaddr
186         else:
187             s.close()
188 
189 
190 if __name__ == '__main__':
191     # For debugging dummyserver itself - python -m dummyserver.server
192     from .testcase import TestingApp
193     host = '127.0.0.1'
194 
195     io_loop = tornado.ioloop.IOLoop()
196     app = tornado.wsgi.WSGIContainer(TestingApp())
197     server, port = run_tornado_app(app, io_loop, None,
198                                    'http', host)
199     server_thread = run_loop_in_thread(io_loop)
200 
201     print("Listening on http://{host}:{port}".format(host=host, port=port))
202
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/dummyserver/server.py b/dummyserver/server.py
--- a/dummyserver/server.py
+++ b/dummyserver/server.py
@@ -13,6 +13,9 @@
 import sys
 import threading
 import socket
+import warnings
+
+from urllib3.exceptions import HTTPWarning
 
 from tornado.platform.auto import set_close_exec
 import tornado.wsgi
@@ -40,6 +43,11 @@
 # Different types of servers we have:
 
 
+class NoIPv6Warning(HTTPWarning):
+    "IPv6 is not available"
+    pass
+
+
 class SocketServerThread(threading.Thread):
     """
     :param socket_handler: Callable which receives a socket argument for one
@@ -57,7 +65,12 @@
         self.ready_event = ready_event
 
     def _start_server(self):
-        sock = socket.socket(socket.AF_INET6)
+        if socket.has_ipv6:
+            sock = socket.socket(socket.AF_INET6)
+        else:
+            warnings.warn("No IPv6 support. Falling back to IPv4.",
+                          NoIPv6Warning)
+            sock = socket.socket(socket.AF_INET)
         if sys.platform != 'win32':
             sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
         sock.bind((self.host, 0))

{"golden_diff": "diff --git a/dummyserver/server.py b/dummyserver/server.py\n--- a/dummyserver/server.py\n+++ b/dummyserver/server.py\n@@ -13,6 +13,9 @@\n import sys\n import threading\n import socket\n+import warnings\n+\n+from urllib3.exceptions import HTTPWarning\n \n from tornado.platform.auto import set_close_exec\n import tornado.wsgi\n@@ -40,6 +43,11 @@\n # Different types of servers we have:\n \n \n+class NoIPv6Warning(HTTPWarning):\n+    \"IPv6 is not available\"\n+    pass\n+\n+\n class SocketServerThread(threading.Thread):\n     \"\"\"\n     :param socket_handler: Callable which receives a socket argument for one\n@@ -57,7 +65,12 @@\n         self.ready_event = ready_event\n \n     def _start_server(self):\n-        sock = socket.socket(socket.AF_INET6)\n+        if socket.has_ipv6:\n+            sock = socket.socket(socket.AF_INET6)\n+        else:\n+            warnings.warn(\"No IPv6 support. Falling back to IPv4.\",\n+                          NoIPv6Warning)\n+            sock = socket.socket(socket.AF_INET)\n         if sys.platform != 'win32':\n             sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n         sock.bind((self.host, 0))\n", "issue": "tests are stuck when running `make test`\nI tried to use google's public dns as suggested by @sigmavirus24, but it didn't help.\n\n``` shell\n$ ip a\n1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default \n    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00\n    inet 127.0.0.1/8 brd 127.255.255.255 scope host lo\n       valid_lft forever preferred_lft forever\n    inet6 ::1/128 scope host \n       valid_lft forever preferred_lft forever\n2: enp5s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000\n    inet 192.168.0.17/24 brd 192.168.0.255 scope global enp5s0\n       valid_lft forever preferred_lft forever\n    inet6 fe80::beae:c5ff:fe65:dd71/64 scope link \n       valid_lft forever preferred_lft forever\n$ cat /etc/resolv.conf\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n```\n\nstrace:\n\n``` shell\n$ strace -p 12676\nProcess 12676 attached\nfutex(0xbf8dd0, FUTEX_WAIT_PRIVATE, 0, NULL\n```\n\nThis is gentoo, wicd and python 2.7. I think I had the same problem with Fedora and NetworkManager.\n\nAlso, last couple of lines from output:\n\n```\ntest_oldapi (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok\ntest_proxy_conn_fail (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok\ntest_proxy_pooling (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok\ntest_proxy_pooling_ext (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok\ntest_proxy_verified (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok\ntest_redirect (test.with_dummyserver.test_proxy_poolmanager.TestHTTPProxyManager) ... ok\ntest_multi_setcookie (test.with_dummyserver.test_socketlevel.TestCookies) ... Exception in thread Thread-8:\nTraceback (most recent call last):\n  File \"/usr/lib64/python2.7/threading.py\", line 810, in __bootstrap_inner\n    self.run()\n  File \"/home/tt/dev/urllib3/dummyserver/server.py\", line 76, in run\n    self.server = self._start_server()\n  File \"/home/tt/dev/urllib3/dummyserver/server.py\", line 63, in _start_server\n    sock.bind((self.host, 0))\n  File \"/usr/lib64/python2.7/socket.py\", line 224, in meth\n    return getattr(self._sock,name)(*args)\nerror: getsockaddrarg: bad family\n```\n\n", "before_files": [{"content": "#!/usr/bin/env python\n\n\"\"\"\nDummy server used for unit testing.\n\"\"\"\nfrom __future__ import print_function\n\nimport errno\nimport logging\nimport os\nimport random\nimport string\nimport sys\nimport threading\nimport socket\n\nfrom tornado.platform.auto import set_close_exec\nimport tornado.wsgi\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\n\n\nlog = logging.getLogger(__name__)\n\nCERTS_PATH = os.path.join(os.path.dirname(__file__), 'certs')\nDEFAULT_CERTS = {\n    'certfile': os.path.join(CERTS_PATH, 'server.crt'),\n    'keyfile': os.path.join(CERTS_PATH, 'server.key'),\n}\nNO_SAN_CERTS = {\n    'certfile': os.path.join(CERTS_PATH, 'server.no_san.crt'),\n    'keyfile': DEFAULT_CERTS['keyfile']\n}\nDEFAULT_CA = os.path.join(CERTS_PATH, 'cacert.pem')\nDEFAULT_CA_BAD = os.path.join(CERTS_PATH, 'client_bad.pem')\nNO_SAN_CA = os.path.join(CERTS_PATH, 'cacert.no_san.pem')\n\n\n# Different types of servers we have:\n\n\nclass SocketServerThread(threading.Thread):\n    \"\"\"\n    :param socket_handler: Callable which receives a socket argument for one\n        request.\n    :param ready_event: Event which gets set when the socket handler is\n        ready to receive requests.\n    \"\"\"\n    def __init__(self, socket_handler, host='localhost', port=8081,\n                 ready_event=None):\n        threading.Thread.__init__(self)\n        self.daemon = True\n\n        self.socket_handler = socket_handler\n        self.host = host\n        self.ready_event = ready_event\n\n    def _start_server(self):\n        sock = socket.socket(socket.AF_INET6)\n        if sys.platform != 'win32':\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        sock.bind((self.host, 0))\n        self.port = sock.getsockname()[1]\n\n        # Once listen() returns, the server socket is ready\n        sock.listen(0)\n\n        if self.ready_event:\n            self.ready_event.set()\n\n        self.socket_handler(sock)\n        sock.close()\n\n    def run(self):\n        self.server = self._start_server()\n\n\n# FIXME: there is a pull request patching bind_sockets in Tornado directly.\n# If it gets merged and released we can drop this and use\n# `tornado.netutil.bind_sockets` again.\n# https://github.com/facebook/tornado/pull/977\n\ndef bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128,\n                 flags=None):\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    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    binded_port = None\n    for res in set(socket.getaddrinfo(address, port, family,\n                                      socket.SOCK_STREAM, 0, flags)):\n        af, socktype, proto, canonname, sockaddr = res\n        try:\n            sock = socket.socket(af, socktype, proto)\n        except socket.error as e:\n            if e.args[0] == errno.EAFNOSUPPORT:\n                continue\n            raise\n        set_close_exec(sock.fileno())\n        if os.name != 'nt':\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        if 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 binded_port is not None:\n            sockaddr = tuple([host, binded_port] + list(sockaddr[2:]))\n\n        sock.setblocking(0)\n        sock.bind(sockaddr)\n        binded_port = sock.getsockname()[1]\n        sock.listen(backlog)\n        sockets.append(sock)\n    return sockets\n\n\ndef run_tornado_app(app, io_loop, certs, scheme, host):\n    if scheme == 'https':\n        http_server = tornado.httpserver.HTTPServer(app, ssl_options=certs,\n                                                    io_loop=io_loop)\n    else:\n        http_server = tornado.httpserver.HTTPServer(app, io_loop=io_loop)\n\n    sockets = bind_sockets(None, address=host)\n    port = sockets[0].getsockname()[1]\n    http_server.add_sockets(sockets)\n    return http_server, port\n\n\ndef run_loop_in_thread(io_loop):\n    t = threading.Thread(target=io_loop.start)\n    t.start()\n    return t\n\n\ndef get_unreachable_address():\n    while True:\n        host = ''.join(random.choice(string.ascii_lowercase)\n                       for _ in range(60))\n        sockaddr = (host, 54321)\n\n        # check if we are really \"lucky\" and hit an actual server\n        try:\n            s = socket.create_connection(sockaddr)\n        except socket.error:\n            return sockaddr\n        else:\n            s.close()\n\n\nif __name__ == '__main__':\n    # For debugging dummyserver itself - python -m dummyserver.server\n    from .testcase import TestingApp\n    host = '127.0.0.1'\n\n    io_loop = tornado.ioloop.IOLoop()\n    app = tornado.wsgi.WSGIContainer(TestingApp())\n    server, port = run_tornado_app(app, io_loop, None,\n                                   'http', host)\n    server_thread = run_loop_in_thread(io_loop)\n\n    print(\"Listening on http://{host}:{port}\".format(host=host, port=port))\n", "path": "dummyserver/server.py"}], "after_files": [{"content": "#!/usr/bin/env python\n\n\"\"\"\nDummy server used for unit testing.\n\"\"\"\nfrom __future__ import print_function\n\nimport errno\nimport logging\nimport os\nimport random\nimport string\nimport sys\nimport threading\nimport socket\nimport warnings\n\nfrom urllib3.exceptions import HTTPWarning\n\nfrom tornado.platform.auto import set_close_exec\nimport tornado.wsgi\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\n\n\nlog = logging.getLogger(__name__)\n\nCERTS_PATH = os.path.join(os.path.dirname(__file__), 'certs')\nDEFAULT_CERTS = {\n    'certfile': os.path.join(CERTS_PATH, 'server.crt'),\n    'keyfile': os.path.join(CERTS_PATH, 'server.key'),\n}\nNO_SAN_CERTS = {\n    'certfile': os.path.join(CERTS_PATH, 'server.no_san.crt'),\n    'keyfile': DEFAULT_CERTS['keyfile']\n}\nDEFAULT_CA = os.path.join(CERTS_PATH, 'cacert.pem')\nDEFAULT_CA_BAD = os.path.join(CERTS_PATH, 'client_bad.pem')\nNO_SAN_CA = os.path.join(CERTS_PATH, 'cacert.no_san.pem')\n\n\n# Different types of servers we have:\n\n\nclass NoIPv6Warning(HTTPWarning):\n    \"IPv6 is not available\"\n    pass\n\n\nclass SocketServerThread(threading.Thread):\n    \"\"\"\n    :param socket_handler: Callable which receives a socket argument for one\n        request.\n    :param ready_event: Event which gets set when the socket handler is\n        ready to receive requests.\n    \"\"\"\n    def __init__(self, socket_handler, host='localhost', port=8081,\n                 ready_event=None):\n        threading.Thread.__init__(self)\n        self.daemon = True\n\n        self.socket_handler = socket_handler\n        self.host = host\n        self.ready_event = ready_event\n\n    def _start_server(self):\n        if socket.has_ipv6:\n            sock = socket.socket(socket.AF_INET6)\n        else:\n            warnings.warn(\"No IPv6 support. Falling back to IPv4.\",\n                          NoIPv6Warning)\n            sock = socket.socket(socket.AF_INET)\n        if sys.platform != 'win32':\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        sock.bind((self.host, 0))\n        self.port = sock.getsockname()[1]\n\n        # Once listen() returns, the server socket is ready\n        sock.listen(0)\n\n        if self.ready_event:\n            self.ready_event.set()\n\n        self.socket_handler(sock)\n        sock.close()\n\n    def run(self):\n        self.server = self._start_server()\n\n\n# FIXME: there is a pull request patching bind_sockets in Tornado directly.\n# If it gets merged and released we can drop this and use\n# `tornado.netutil.bind_sockets` again.\n# https://github.com/facebook/tornado/pull/977\n\ndef bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128,\n                 flags=None):\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    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    binded_port = None\n    for res in set(socket.getaddrinfo(address, port, family,\n                                      socket.SOCK_STREAM, 0, flags)):\n        af, socktype, proto, canonname, sockaddr = res\n        try:\n            sock = socket.socket(af, socktype, proto)\n        except socket.error as e:\n            if e.args[0] == errno.EAFNOSUPPORT:\n                continue\n            raise\n        set_close_exec(sock.fileno())\n        if os.name != 'nt':\n            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        if 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 binded_port is not None:\n            sockaddr = tuple([host, binded_port] + list(sockaddr[2:]))\n\n        sock.setblocking(0)\n        sock.bind(sockaddr)\n        binded_port = sock.getsockname()[1]\n        sock.listen(backlog)\n        sockets.append(sock)\n    return sockets\n\n\ndef run_tornado_app(app, io_loop, certs, scheme, host):\n    if scheme == 'https':\n        http_server = tornado.httpserver.HTTPServer(app, ssl_options=certs,\n                                                    io_loop=io_loop)\n    else:\n        http_server = tornado.httpserver.HTTPServer(app, io_loop=io_loop)\n\n    sockets = bind_sockets(None, address=host)\n    port = sockets[0].getsockname()[1]\n    http_server.add_sockets(sockets)\n    return http_server, port\n\n\ndef run_loop_in_thread(io_loop):\n    t = threading.Thread(target=io_loop.start)\n    t.start()\n    return t\n\n\ndef get_unreachable_address():\n    while True:\n        host = ''.join(random.choice(string.ascii_lowercase)\n                       for _ in range(60))\n        sockaddr = (host, 54321)\n\n        # check if we are really \"lucky\" and hit an actual server\n        try:\n            s = socket.create_connection(sockaddr)\n        except socket.error:\n            return sockaddr\n        else:\n            s.close()\n\n\nif __name__ == '__main__':\n    # For debugging dummyserver itself - python -m dummyserver.server\n    from .testcase import TestingApp\n    host = '127.0.0.1'\n\n    io_loop = tornado.ioloop.IOLoop()\n    app = tornado.wsgi.WSGIContainer(TestingApp())\n    server, port = run_tornado_app(app, io_loop, None,\n                                   'http', host)\n    server_thread = run_loop_in_thread(io_loop)\n\n    print(\"Listening on http://{host}:{port}\".format(host=host, port=port))\n", "path": "dummyserver/server.py"}]}