prompt: You will be provided with a partial code base and an issue statement explaining a problem to resolve.
  <issue>
  urllib3 attempts to use IPv6 even when IPv6 is disabled
  This is an issue when running on a server without IPv6 (must be disabled because the network does not support it). Example when connecting to https://graph.facebook.com using requests and IPv4 happens to fail:
  
  ```
  HTTPSConnectionPool(host='graph.facebook.com', port=443): Max retries exceeded with url: /v2.5/me/feed (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f4dbd158518>: Failed to establish a new connection: [Errno 97] Address family not supported by protocol',))
  Traceback (most recent call last):
    File "/home/lib/python3.4/site-packages/requests/packages/urllib3/connection.py", line 137, in _new_conn
      (self.host, self.port), self.timeout, **extra_kw)
    File "/home/lib/python3.4/site-packages/requests/packages/urllib3/util/connection.py", line 91, in create_connection
      raise err
    File "/home/lib/python3.4/site-packages/requests/packages/urllib3/util/connection.py", line 71, in create_connection
      sock = socket.socket(af, socktype, proto)
    File "/usr/lib/python3.4/socket.py", line 126, in __init__
      _socket.socket.__init__(self, family, type, proto, fileno)
  OSError: [Errno 97] Address family not supported by protocol
  ```
  
  urllib3 should throw an exception after exhausting all IPv4 options instead of trying (and invariably failing) IPv6.
  
  See closed issue https://github.com/kennethreitz/requests/issues/3084.
  
  
  </issue>
  <code>
  [start of urllib3/util/connection.py]
  1 from __future__ import absolute_import
  2 import socket
  3 try:
  4     from select import poll, POLLIN
  5 except ImportError:  # `poll` doesn't exist on OSX and other platforms
  6     poll = False
  7     try:
  8         from select import select
  9     except ImportError:  # `select` doesn't exist on AppEngine.
  10         select = False
  11 
  12 
  13 def is_connection_dropped(conn):  # Platform-specific
  14     """
  15     Returns True if the connection is dropped and should be closed.
  16 
  17     :param conn:
  18         :class:`httplib.HTTPConnection` object.
  19 
  20     Note: For platforms like AppEngine, this will always return ``False`` to
  21     let the platform handle connection recycling transparently for us.
  22     """
  23     sock = getattr(conn, 'sock', False)
  24     if sock is False:  # Platform-specific: AppEngine
  25         return False
  26     if sock is None:  # Connection already closed (such as by httplib).
  27         return True
  28 
  29     if not poll:
  30         if not select:  # Platform-specific: AppEngine
  31             return False
  32 
  33         try:
  34             return select([sock], [], [], 0.0)[0]
  35         except socket.error:
  36             return True
  37 
  38     # This version is better on platforms that support it.
  39     p = poll()
  40     p.register(sock, POLLIN)
  41     for (fno, ev) in p.poll(0.0):
  42         if fno == sock.fileno():
  43             # Either data is buffered (bad), or the connection is dropped.
  44             return True
  45 
  46 
  47 # This function is copied from socket.py in the Python 2.7 standard
  48 # library test suite. Added to its signature is only `socket_options`.
  49 def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  50                       source_address=None, socket_options=None):
  51     """Connect to *address* and return the socket object.
  52 
  53     Convenience function.  Connect to *address* (a 2-tuple ``(host,
  54     port)``) and return the socket object.  Passing the optional
  55     *timeout* parameter will set the timeout on the socket instance
  56     before attempting to connect.  If no *timeout* is supplied, the
  57     global default timeout setting returned by :func:`getdefaulttimeout`
  58     is used.  If *source_address* is set it must be a tuple of (host, port)
  59     for the socket to bind as a source address before making the connection.
  60     An host of '' or port 0 tells the OS to use the default.
  61     """
  62 
  63     host, port = address
  64     if host.startswith('['):
  65         host = host.strip('[]')
  66     err = None
  67     for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  68         af, socktype, proto, canonname, sa = res
  69         sock = None
  70         try:
  71             sock = socket.socket(af, socktype, proto)
  72 
  73             # If provided, set socket level options before connecting.
  74             # This is the only addition urllib3 makes to this function.
  75             _set_socket_options(sock, socket_options)
  76 
  77             if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  78                 sock.settimeout(timeout)
  79             if source_address:
  80                 sock.bind(source_address)
  81             sock.connect(sa)
  82             return sock
  83 
  84         except socket.error as e:
  85             err = e
  86             if sock is not None:
  87                 sock.close()
  88                 sock = None
  89 
  90     if err is not None:
  91         raise err
  92 
  93     raise socket.error("getaddrinfo returns an empty list")
  94 
  95 
  96 def _set_socket_options(sock, options):
  97     if options is None:
  98         return
  99 
  100     for opt in options:
  101         sock.setsockopt(*opt)
  102
  [end of urllib3/util/connection.py]
  </code>
  
  I need you to solve this issue by generating a single patch file that I can apply directly to this repository using git apply. Please respond with a single patch file in the following format.
  <patch>
  diff --git a/file.py b/file.py
  --- a/file.py
  +++ b/file.py
  @@ -1,27 +1,35 @@
   def euclidean(a, b):
  -    while b:
  -        a, b = b, a % b
  -    return a
  +    if b == 0:
  +        return a
  +    return euclidean(b, a % b)
   
   
   def bresenham(x0, y0, x1, y1):
       points = []
       dx = abs(x1 - x0)
       dy = abs(y1 - y0)
  -    sx = 1 if x0 < x1 else -1
  -    sy = 1 if y0 < y1 else -1
  -    err = dx - dy
  +    x, y = x0, y0
  +    sx = -1 if x0 > x1 else 1
  +    sy = -1 if y0 > y1 else 1
   
  -    while True:
  -        points.append((x0, y0))
  -        if x0 == x1 and y0 == y1:
  -            break
  -        e2 = 2 * err
  -        if e2 > -dy:
  -            err -= dy
  -            x0 += sx
  -        if e2 < dx:
  -            err += dx
  -            y0 += sy
  +    if dx > dy:
  +        err = dx / 2.0
  +        while x != x1:
  +            points.append((x, y))
  +            err -= dy
  +            if err < 0:
  +                y += sy
  +                err += dx
  +            x += sx
  +    else:
  +        err = dy / 2.0
  +        while y != y1:
  +            points.append((x, y))
  +            err -= dx
  +            if err < 0:
  +                x += sx
  +                err += dy
  +            y += sy
  +
  +    points.append((x, y))
       return points
  
  </patch>
golden_diff: diff --git a/urllib3/util/connection.py b/urllib3/util/connection.py
  --- a/urllib3/util/connection.py
  +++ b/urllib3/util/connection.py
  @@ -46,6 +46,8 @@
   
   # This function is copied from socket.py in the Python 2.7 standard
   # library test suite. Added to its signature is only `socket_options`.
  +# One additional modification is that we avoid binding to IPv6 servers
  +# discovered in DNS if the system doesn't have IPv6 functionality.
   def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                         source_address=None, socket_options=None):
       """Connect to *address* and return the socket object.
  @@ -64,14 +66,19 @@
       if host.startswith('['):
           host = host.strip('[]')
       err = None
  -    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  +
  +    # Using the value from allowed_gai_family() in the context of getaddrinfo lets
  +    # us select whether to work with IPv4 DNS records, IPv6 records, or both.
  +    # The original create_connection function always returns all records.
  +    family = allowed_gai_family()
  +
  +    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
           af, socktype, proto, canonname, sa = res
           sock = None
           try:
               sock = socket.socket(af, socktype, proto)
   
               # If provided, set socket level options before connecting.
  -            # This is the only addition urllib3 makes to this function.
               _set_socket_options(sock, socket_options)
   
               if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  @@ -99,3 +106,39 @@
   
       for opt in options:
           sock.setsockopt(*opt)
  +
  +
  +def allowed_gai_family():
  +    """This function is designed to work in the context of
  +    getaddrinfo, where family=socket.AF_UNSPEC is the default and
  +    will perform a DNS search for both IPv6 and IPv4 records."""
  +
  +    family = socket.AF_INET
  +    if HAS_IPV6:
  +        family = socket.AF_UNSPEC
  +    return family
  +
  +
  +def _has_ipv6(host):
  +    """ Returns True if the system can bind an IPv6 address. """
  +    sock = None
  +    has_ipv6 = False
  +
  +    if socket.has_ipv6:
  +        # has_ipv6 returns true if cPython was compiled with IPv6 support.
  +        # It does not tell us if the system has IPv6 support enabled. To
  +        # determine that we must bind to an IPv6 address.
  +        # https://github.com/shazow/urllib3/pull/611
  +        # https://bugs.python.org/issue658327
  +        try:
  +            sock = socket.socket(socket.AF_INET6)
  +            sock.bind((host, 0))
  +            has_ipv6 = True
  +        except Exception:
  +            pass
  +
  +    if sock:
  +        sock.close()
  +    return has_ipv6
  +
  +HAS_IPV6 = _has_ipv6('::1')
  
verification_info: {"golden_diff": "diff --git a/urllib3/util/connection.py b/urllib3/util/connection.py\n--- a/urllib3/util/connection.py\n+++ b/urllib3/util/connection.py\n@@ -46,6 +46,8 @@\n \n # This function is copied from socket.py in the Python 2.7 standard\n # library test suite. Added to its signature is only `socket_options`.\n+# One additional modification is that we avoid binding to IPv6 servers\n+# discovered in DNS if the system doesn't have IPv6 functionality.\n def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,\n                       source_address=None, socket_options=None):\n     \"\"\"Connect to *address* and return the socket object.\n@@ -64,14 +66,19 @@\n     if host.startswith('['):\n         host = host.strip('[]')\n     err = None\n-    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):\n+\n+    # Using the value from allowed_gai_family() in the context of getaddrinfo lets\n+    # us select whether to work with IPv4 DNS records, IPv6 records, or both.\n+    # The original create_connection function always returns all records.\n+    family = allowed_gai_family()\n+\n+    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):\n         af, socktype, proto, canonname, sa = res\n         sock = None\n         try:\n             sock = socket.socket(af, socktype, proto)\n \n             # If provided, set socket level options before connecting.\n-            # This is the only addition urllib3 makes to this function.\n             _set_socket_options(sock, socket_options)\n \n             if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:\n@@ -99,3 +106,39 @@\n \n     for opt in options:\n         sock.setsockopt(*opt)\n+\n+\n+def allowed_gai_family():\n+    \"\"\"This function is designed to work in the context of\n+    getaddrinfo, where family=socket.AF_UNSPEC is the default and\n+    will perform a DNS search for both IPv6 and IPv4 records.\"\"\"\n+\n+    family = socket.AF_INET\n+    if HAS_IPV6:\n+        family = socket.AF_UNSPEC\n+    return family\n+\n+\n+def _has_ipv6(host):\n+    \"\"\" Returns True if the system can bind an IPv6 address. \"\"\"\n+    sock = None\n+    has_ipv6 = False\n+\n+    if socket.has_ipv6:\n+        # has_ipv6 returns true if cPython was compiled with IPv6 support.\n+        # It does not tell us if the system has IPv6 support enabled. To\n+        # determine that we must bind to an IPv6 address.\n+        # https://github.com/shazow/urllib3/pull/611\n+        # https://bugs.python.org/issue658327\n+        try:\n+            sock = socket.socket(socket.AF_INET6)\n+            sock.bind((host, 0))\n+            has_ipv6 = True\n+        except Exception:\n+            pass\n+\n+    if sock:\n+        sock.close()\n+    return has_ipv6\n+\n+HAS_IPV6 = _has_ipv6('::1')\n", "issue": "urllib3 attempts to use IPv6 even when IPv6 is disabled\nThis is an issue when running on a server without IPv6 (must be disabled because the network does not support it). Example when connecting to https://graph.facebook.com using requests and IPv4 happens to fail:\n\n```\nHTTPSConnectionPool(host='graph.facebook.com', port=443): Max retries exceeded with url: /v2.5/me/feed (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x7f4dbd158518>: Failed to establish a new connection: [Errno 97] Address family not supported by protocol',))\nTraceback (most recent call last):\n  File \"/home/lib/python3.4/site-packages/requests/packages/urllib3/connection.py\", line 137, in _new_conn\n    (self.host, self.port), self.timeout, **extra_kw)\n  File \"/home/lib/python3.4/site-packages/requests/packages/urllib3/util/connection.py\", line 91, in create_connection\n    raise err\n  File \"/home/lib/python3.4/site-packages/requests/packages/urllib3/util/connection.py\", line 71, in create_connection\n    sock = socket.socket(af, socktype, proto)\n  File \"/usr/lib/python3.4/socket.py\", line 126, in __init__\n    _socket.socket.__init__(self, family, type, proto, fileno)\nOSError: [Errno 97] Address family not supported by protocol\n```\n\nurllib3 should throw an exception after exhausting all IPv4 options instead of trying (and invariably failing) IPv6.\n\nSee closed issue https://github.com/kennethreitz/requests/issues/3084.\n\n", "before_files": [{"content": "from __future__ import absolute_import\nimport socket\ntry:\n    from select import poll, POLLIN\nexcept ImportError:  # `poll` doesn't exist on OSX and other platforms\n    poll = False\n    try:\n        from select import select\n    except ImportError:  # `select` doesn't exist on AppEngine.\n        select = False\n\n\ndef is_connection_dropped(conn):  # Platform-specific\n    \"\"\"\n    Returns True if the connection is dropped and should be closed.\n\n    :param conn:\n        :class:`httplib.HTTPConnection` object.\n\n    Note: For platforms like AppEngine, this will always return ``False`` to\n    let the platform handle connection recycling transparently for us.\n    \"\"\"\n    sock = getattr(conn, 'sock', False)\n    if sock is False:  # Platform-specific: AppEngine\n        return False\n    if sock is None:  # Connection already closed (such as by httplib).\n        return True\n\n    if not poll:\n        if not select:  # Platform-specific: AppEngine\n            return False\n\n        try:\n            return select([sock], [], [], 0.0)[0]\n        except socket.error:\n            return True\n\n    # This version is better on platforms that support it.\n    p = poll()\n    p.register(sock, POLLIN)\n    for (fno, ev) in p.poll(0.0):\n        if fno == sock.fileno():\n            # Either data is buffered (bad), or the connection is dropped.\n            return True\n\n\n# This function is copied from socket.py in the Python 2.7 standard\n# library test suite. Added to its signature is only `socket_options`.\ndef create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,\n                      source_address=None, socket_options=None):\n    \"\"\"Connect to *address* and return the socket object.\n\n    Convenience function.  Connect to *address* (a 2-tuple ``(host,\n    port)``) and return the socket object.  Passing the optional\n    *timeout* parameter will set the timeout on the socket instance\n    before attempting to connect.  If no *timeout* is supplied, the\n    global default timeout setting returned by :func:`getdefaulttimeout`\n    is used.  If *source_address* is set it must be a tuple of (host, port)\n    for the socket to bind as a source address before making the connection.\n    An host of '' or port 0 tells the OS to use the default.\n    \"\"\"\n\n    host, port = address\n    if host.startswith('['):\n        host = host.strip('[]')\n    err = None\n    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):\n        af, socktype, proto, canonname, sa = res\n        sock = None\n        try:\n            sock = socket.socket(af, socktype, proto)\n\n            # If provided, set socket level options before connecting.\n            # This is the only addition urllib3 makes to this function.\n            _set_socket_options(sock, socket_options)\n\n            if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:\n                sock.settimeout(timeout)\n            if source_address:\n                sock.bind(source_address)\n            sock.connect(sa)\n            return sock\n\n        except socket.error as e:\n            err = e\n            if sock is not None:\n                sock.close()\n                sock = None\n\n    if err is not None:\n        raise err\n\n    raise socket.error(\"getaddrinfo returns an empty list\")\n\n\ndef _set_socket_options(sock, options):\n    if options is None:\n        return\n\n    for opt in options:\n        sock.setsockopt(*opt)\n", "path": "urllib3/util/connection.py"}]}