connection.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. from __future__ import absolute_import
  2. import socket
  3. from ..contrib import _appengine_environ
  4. from ..exceptions import LocationParseError
  5. from ..packages import six
  6. from .wait import NoWayToWaitForSocketError, wait_for_read
  7. def is_connection_dropped(conn): # Platform-specific
  8. """
  9. Returns True if the connection is dropped and should be closed.
  10. :param conn:
  11. :class:`http.client.HTTPConnection` object.
  12. Note: For platforms like AppEngine, this will always return ``False`` to
  13. let the platform handle connection recycling transparently for us.
  14. """
  15. sock = getattr(conn, "sock", False)
  16. if sock is False: # Platform-specific: AppEngine
  17. return False
  18. if sock is None: # Connection already closed (such as by httplib).
  19. return True
  20. try:
  21. # Returns True if readable, which here means it's been dropped
  22. return wait_for_read(sock, timeout=0.0)
  23. except NoWayToWaitForSocketError: # Platform-specific: AppEngine
  24. return False
  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(
  30. address,
  31. timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
  32. source_address=None,
  33. socket_options=None,
  34. ):
  35. """Connect to *address* and return the socket object.
  36. Convenience function. Connect to *address* (a 2-tuple ``(host,
  37. port)``) and return the socket object. Passing the optional
  38. *timeout* parameter will set the timeout on the socket instance
  39. before attempting to connect. If no *timeout* is supplied, the
  40. global default timeout setting returned by :func:`socket.getdefaulttimeout`
  41. is used. If *source_address* is set it must be a tuple of (host, port)
  42. for the socket to bind as a source address before making the connection.
  43. An host of '' or port 0 tells the OS to use the default.
  44. """
  45. host, port = address
  46. if host.startswith("["):
  47. host = host.strip("[]")
  48. err = None
  49. # Using the value from allowed_gai_family() in the context of getaddrinfo lets
  50. # us select whether to work with IPv4 DNS records, IPv6 records, or both.
  51. # The original create_connection function always returns all records.
  52. family = allowed_gai_family()
  53. try:
  54. host.encode("idna")
  55. except UnicodeError:
  56. return six.raise_from(
  57. LocationParseError(u"'%s', label empty or too long" % host), None
  58. )
  59. for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  60. af, socktype, proto, canonname, sa = res
  61. sock = None
  62. try:
  63. sock = socket.socket(af, socktype, proto)
  64. # If provided, set socket level options before connecting.
  65. _set_socket_options(sock, socket_options)
  66. if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
  67. sock.settimeout(timeout)
  68. if source_address:
  69. sock.bind(source_address)
  70. sock.connect(sa)
  71. return sock
  72. except socket.error as e:
  73. err = e
  74. if sock is not None:
  75. sock.close()
  76. sock = None
  77. if err is not None:
  78. raise err
  79. raise socket.error("getaddrinfo returns an empty list")
  80. def _set_socket_options(sock, options):
  81. if options is None:
  82. return
  83. for opt in options:
  84. sock.setsockopt(*opt)
  85. def allowed_gai_family():
  86. """This function is designed to work in the context of
  87. getaddrinfo, where family=socket.AF_UNSPEC is the default and
  88. will perform a DNS search for both IPv6 and IPv4 records."""
  89. family = socket.AF_INET
  90. if HAS_IPV6:
  91. family = socket.AF_UNSPEC
  92. return family
  93. def _has_ipv6(host):
  94. """Returns True if the system can bind an IPv6 address."""
  95. sock = None
  96. has_ipv6 = False
  97. # App Engine doesn't support IPV6 sockets and actually has a quota on the
  98. # number of sockets that can be used, so just early out here instead of
  99. # creating a socket needlessly.
  100. # See https://github.com/urllib3/urllib3/issues/1446
  101. if _appengine_environ.is_appengine_sandbox():
  102. return False
  103. if socket.has_ipv6:
  104. # has_ipv6 returns true if cPython was compiled with IPv6 support.
  105. # It does not tell us if the system has IPv6 support enabled. To
  106. # determine that we must bind to an IPv6 address.
  107. # https://github.com/urllib3/urllib3/pull/611
  108. # https://bugs.python.org/issue658327
  109. try:
  110. sock = socket.socket(socket.AF_INET6)
  111. sock.bind((host, 0))
  112. has_ipv6 = True
  113. except Exception:
  114. pass
  115. if sock:
  116. sock.close()
  117. return has_ipv6
  118. HAS_IPV6 = _has_ipv6("::1")