connection.py 4.5 KB

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