connection.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # SPDX-License-Identifier: MIT
  2. from __future__ import absolute_import
  3. import socket
  4. from .wait import wait_for_read
  5. from .selectors import HAS_SELECT, SelectorError
  6. def is_connection_dropped(conn): # Platform-specific
  7. """
  8. Returns True if the connection is dropped and should be closed.
  9. :param conn:
  10. :class:`httplib.HTTPConnection` object.
  11. Note: For platforms like AppEngine, this will always return ``False`` to
  12. let the platform handle connection recycling transparently for us.
  13. """
  14. sock = getattr(conn, 'sock', False)
  15. if sock is False: # Platform-specific: AppEngine
  16. return False
  17. if sock is None: # Connection already closed (such as by httplib).
  18. return True
  19. if not HAS_SELECT:
  20. return False
  21. try:
  22. return bool(wait_for_read(sock, timeout=0.0))
  23. except SelectorError:
  24. return True
  25. # This function is copied from socket.py in the Python 2.7 standard
  26. # library test suite. Added to its signature is only `socket_options`.
  27. # One additional modification is that we avoid binding to IPv6 servers
  28. # discovered in DNS if the system doesn't have IPv6 functionality.
  29. def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  30. source_address=None, socket_options=None):
  31. """Connect to *address* and return the socket object.
  32. Convenience function. Connect to *address* (a 2-tuple ``(host,
  33. port)``) and return the socket object. Passing the optional
  34. *timeout* parameter will set the timeout on the socket instance
  35. before attempting to connect. If no *timeout* is supplied, the
  36. global default timeout setting returned by :func:`getdefaulttimeout`
  37. is used. If *source_address* is set it must be a tuple of (host, port)
  38. for the socket to bind as a source address before making the connection.
  39. An host of '' or port 0 tells the OS to use the default.
  40. """
  41. host, port = address
  42. if host.startswith('['):
  43. host = host.strip('[]')
  44. err = None
  45. # Using the value from allowed_gai_family() in the context of getaddrinfo lets
  46. # us select whether to work with IPv4 DNS records, IPv6 records, or both.
  47. # The original create_connection function always returns all records.
  48. family = allowed_gai_family()
  49. for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  50. af, socktype, proto, canonname, sa = res
  51. sock = None
  52. try:
  53. sock = socket.socket(af, socktype, proto)
  54. # If provided, set socket level options before connecting.
  55. _set_socket_options(sock, socket_options)
  56. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  57. sock.settimeout(timeout)
  58. if source_address:
  59. sock.bind(source_address)
  60. sock.connect(sa)
  61. return sock
  62. except socket.error as e:
  63. err = e
  64. if sock is not None:
  65. sock.close()
  66. sock = None
  67. if err is not None:
  68. raise err
  69. raise socket.error("getaddrinfo returns an empty list")
  70. def _set_socket_options(sock, options):
  71. if options is None:
  72. return
  73. for opt in options:
  74. sock.setsockopt(*opt)
  75. def allowed_gai_family():
  76. """This function is designed to work in the context of
  77. getaddrinfo, where family=socket.AF_UNSPEC is the default and
  78. will perform a DNS search for both IPv6 and IPv4 records."""
  79. family = socket.AF_INET
  80. if HAS_IPV6:
  81. family = socket.AF_UNSPEC
  82. return family
  83. def _has_ipv6(host):
  84. """ Returns True if the system can bind an IPv6 address. """
  85. sock = None
  86. has_ipv6 = False
  87. if socket.has_ipv6:
  88. # has_ipv6 returns true if cPython was compiled with IPv6 support.
  89. # It does not tell us if the system has IPv6 support enabled. To
  90. # determine that we must bind to an IPv6 address.
  91. # https://github.com/shazow/urllib3/pull/611
  92. # https://bugs.python.org/issue658327
  93. try:
  94. sock = socket.socket(socket.AF_INET6)
  95. sock.bind((host, 0))
  96. has_ipv6 = True
  97. except Exception:
  98. pass
  99. if sock:
  100. sock.close()
  101. return has_ipv6
  102. HAS_IPV6 = _has_ipv6('::1')