You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

connection.py 4.1KB

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