address.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Address objects for network connections.
  5. """
  6. import os
  7. from typing import Optional, Union
  8. from warnings import warn
  9. from zope.interface import implementer
  10. import attr
  11. from typing_extensions import Literal
  12. from twisted.internet.interfaces import IAddress
  13. from twisted.python.filepath import _asFilesystemBytes, _coerceToFilesystemEncoding
  14. from twisted.python.runtime import platform
  15. @implementer(IAddress)
  16. @attr.s(hash=True, auto_attribs=True)
  17. class IPv4Address:
  18. """
  19. An L{IPv4Address} represents the address of an IPv4 socket endpoint.
  20. @ivar type: A string describing the type of transport, either 'TCP' or
  21. 'UDP'.
  22. @ivar host: A string containing a dotted-quad IPv4 address; for example,
  23. "127.0.0.1".
  24. @type host: C{str}
  25. @ivar port: An integer representing the port number.
  26. @type port: C{int}
  27. """
  28. type: Union[Literal["TCP"], Literal["UDP"]] = attr.ib(
  29. validator=attr.validators.in_(["TCP", "UDP"])
  30. )
  31. host: str
  32. port: int
  33. @implementer(IAddress)
  34. @attr.s(hash=True, auto_attribs=True)
  35. class IPv6Address:
  36. """
  37. An L{IPv6Address} represents the address of an IPv6 socket endpoint.
  38. @ivar type: A string describing the type of transport, either 'TCP' or
  39. 'UDP'.
  40. @ivar host: A string containing a colon-separated, hexadecimal formatted
  41. IPv6 address; for example, "::1".
  42. @type host: C{str}
  43. @ivar port: An integer representing the port number.
  44. @type port: C{int}
  45. @ivar flowInfo: the IPv6 flow label. This can be used by QoS routers to
  46. identify flows of traffic; you may generally safely ignore it.
  47. @type flowInfo: L{int}
  48. @ivar scopeID: the IPv6 scope identifier - roughly analagous to what
  49. interface traffic destined for this address must be transmitted over.
  50. @type scopeID: L{int} or L{str}
  51. """
  52. type: Union[Literal["TCP"], Literal["UDP"]] = attr.ib(
  53. validator=attr.validators.in_(["TCP", "UDP"])
  54. )
  55. host: str
  56. port: int
  57. flowInfo: int = 0
  58. scopeID: Union[str, int] = 0
  59. @implementer(IAddress)
  60. class _ProcessAddress:
  61. """
  62. An L{interfaces.IAddress} provider for process transports.
  63. """
  64. @attr.s(hash=True, auto_attribs=True)
  65. @implementer(IAddress)
  66. class HostnameAddress:
  67. """
  68. A L{HostnameAddress} represents the address of a L{HostnameEndpoint}.
  69. @ivar hostname: A hostname byte string; for example, b"example.com".
  70. @type hostname: L{bytes}
  71. @ivar port: An integer representing the port number.
  72. @type port: L{int}
  73. """
  74. hostname: bytes
  75. port: int
  76. @attr.s(hash=False, repr=False, eq=False, auto_attribs=True)
  77. @implementer(IAddress)
  78. class UNIXAddress:
  79. """
  80. Object representing a UNIX socket endpoint.
  81. @ivar name: The filename associated with this socket.
  82. @type name: C{bytes}
  83. """
  84. name: Optional[bytes] = attr.ib(
  85. converter=attr.converters.optional(_asFilesystemBytes)
  86. )
  87. if getattr(os.path, "samefile", None) is not None:
  88. def __eq__(self, other: object) -> bool:
  89. """
  90. Overriding C{attrs} to ensure the os level samefile
  91. check is done if the name attributes do not match.
  92. """
  93. if not isinstance(other, self.__class__):
  94. return NotImplemented
  95. res = self.name == other.name
  96. if not res and self.name and other.name:
  97. try:
  98. return os.path.samefile(self.name, other.name)
  99. except OSError:
  100. pass
  101. except (TypeError, ValueError) as e:
  102. # On Linux, abstract namespace UNIX sockets start with a
  103. # \0, which os.path doesn't like.
  104. if not platform.isLinux():
  105. raise e
  106. return res
  107. else:
  108. def __eq__(self, other: object) -> bool:
  109. if isinstance(other, self.__class__):
  110. return self.name == other.name
  111. return NotImplemented
  112. def __repr__(self) -> str:
  113. name = self.name
  114. show = _coerceToFilesystemEncoding("", name) if name is not None else None
  115. return f"UNIXAddress({show!r})"
  116. def __hash__(self):
  117. if self.name is None:
  118. return hash((self.__class__, None))
  119. try:
  120. s1 = os.stat(self.name)
  121. return hash((s1.st_ino, s1.st_dev))
  122. except OSError:
  123. return hash(self.name)
  124. # These are for buildFactory backwards compatibility due to
  125. # stupidity-induced inconsistency.
  126. class _ServerFactoryIPv4Address(IPv4Address):
  127. """Backwards compatibility hack. Just like IPv4Address in practice."""
  128. def __eq__(self, other: object) -> bool:
  129. if isinstance(other, tuple):
  130. warn(
  131. "IPv4Address.__getitem__ is deprecated. " "Use attributes instead.",
  132. category=DeprecationWarning,
  133. stacklevel=2,
  134. )
  135. return (self.host, self.port) == other
  136. elif isinstance(other, IPv4Address):
  137. a = (self.type, self.host, self.port)
  138. b = (other.type, other.host, other.port)
  139. return a == b
  140. return NotImplemented