Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.4KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. from __future__ import annotations
  2. import socket
  3. import typing
  4. from ..exceptions import LocationParseError
  5. from .timeout import _DEFAULT_TIMEOUT, _TYPE_TIMEOUT
  6. _TYPE_SOCKET_OPTIONS = typing.Sequence[typing.Tuple[int, int, typing.Union[int, bytes]]]
  7. if typing.TYPE_CHECKING:
  8. from .._base_connection import BaseHTTPConnection
  9. def is_connection_dropped(conn: BaseHTTPConnection) -> bool: # Platform-specific
  10. """
  11. Returns True if the connection is dropped and should be closed.
  12. :param conn: :class:`urllib3.connection.HTTPConnection` object.
  13. """
  14. return not conn.is_connected
  15. # This function is copied from socket.py in the Python 2.7 standard
  16. # library test suite. Added to its signature is only `socket_options`.
  17. # One additional modification is that we avoid binding to IPv6 servers
  18. # discovered in DNS if the system doesn't have IPv6 functionality.
  19. def create_connection(
  20. address: tuple[str, int],
  21. timeout: _TYPE_TIMEOUT = _DEFAULT_TIMEOUT,
  22. source_address: tuple[str, int] | None = None,
  23. socket_options: _TYPE_SOCKET_OPTIONS | None = None,
  24. ) -> socket.socket:
  25. """Connect to *address* and return the socket object.
  26. Convenience function. Connect to *address* (a 2-tuple ``(host,
  27. port)``) and return the socket object. Passing the optional
  28. *timeout* parameter will set the timeout on the socket instance
  29. before attempting to connect. If no *timeout* is supplied, the
  30. global default timeout setting returned by :func:`socket.getdefaulttimeout`
  31. is used. If *source_address* is set it must be a tuple of (host, port)
  32. for the socket to bind as a source address before making the connection.
  33. An host of '' or port 0 tells the OS to use the default.
  34. """
  35. host, port = address
  36. if host.startswith("["):
  37. host = host.strip("[]")
  38. err = None
  39. # Using the value from allowed_gai_family() in the context of getaddrinfo lets
  40. # us select whether to work with IPv4 DNS records, IPv6 records, or both.
  41. # The original create_connection function always returns all records.
  42. family = allowed_gai_family()
  43. try:
  44. host.encode("idna")
  45. except UnicodeError:
  46. raise LocationParseError(f"'{host}', label empty or too long") from None
  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 _DEFAULT_TIMEOUT:
  55. sock.settimeout(timeout)
  56. if source_address:
  57. sock.bind(source_address)
  58. sock.connect(sa)
  59. # Break explicitly a reference cycle
  60. err = None
  61. return sock
  62. except OSError as _:
  63. err = _
  64. if sock is not None:
  65. sock.close()
  66. if err is not None:
  67. try:
  68. raise err
  69. finally:
  70. # Break explicitly a reference cycle
  71. err = None
  72. else:
  73. raise OSError("getaddrinfo returns an empty list")
  74. def _set_socket_options(
  75. sock: socket.socket, options: _TYPE_SOCKET_OPTIONS | None
  76. ) -> None:
  77. if options is None:
  78. return
  79. for opt in options:
  80. sock.setsockopt(*opt)
  81. def allowed_gai_family() -> socket.AddressFamily:
  82. """This function is designed to work in the context of
  83. getaddrinfo, where family=socket.AF_UNSPEC is the default and
  84. will perform a DNS search for both IPv6 and IPv4 records."""
  85. family = socket.AF_INET
  86. if HAS_IPV6:
  87. family = socket.AF_UNSPEC
  88. return family
  89. def _has_ipv6(host: str) -> bool:
  90. """Returns True if the system can bind an IPv6 address."""
  91. sock = None
  92. has_ipv6 = False
  93. if socket.has_ipv6:
  94. # has_ipv6 returns true if cPython was compiled with IPv6 support.
  95. # It does not tell us if the system has IPv6 support enabled. To
  96. # determine that we must bind to an IPv6 address.
  97. # https://github.com/urllib3/urllib3/pull/611
  98. # https://bugs.python.org/issue658327
  99. try:
  100. sock = socket.socket(socket.AF_INET6)
  101. sock.bind((host, 0))
  102. has_ipv6 = True
  103. except Exception:
  104. pass
  105. if sock:
  106. sock.close()
  107. return has_ipv6
  108. HAS_IPV6 = _has_ipv6("::1")