Development of an internal social media platform with personalised dashboards for students
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.2KB

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