jid.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # -*- test-case-name: twisted.words.test.test_jabberjid -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. Jabber Identifier support.
  7. This module provides an object to represent Jabber Identifiers (JIDs) and
  8. parse string representations into them with proper checking for illegal
  9. characters, case folding and canonicalisation through
  10. L{stringprep<twisted.words.protocols.jabber.xmpp_stringprep>}.
  11. """
  12. from typing import Dict, Tuple, Union
  13. from twisted.words.protocols.jabber.xmpp_stringprep import (
  14. nameprep,
  15. nodeprep,
  16. resourceprep,
  17. )
  18. class InvalidFormat(Exception):
  19. """
  20. The given string could not be parsed into a valid Jabber Identifier (JID).
  21. """
  22. def parse(jidstring: str) -> Tuple[Union[str, None], str, Union[str, None]]:
  23. """
  24. Parse given JID string into its respective parts and apply stringprep.
  25. @param jidstring: string representation of a JID.
  26. @type jidstring: L{str}
  27. @return: tuple of (user, host, resource), each of type L{str} as
  28. the parsed and stringprep'd parts of the given JID. If the
  29. given string did not have a user or resource part, the respective
  30. field in the tuple will hold L{None}.
  31. @rtype: L{tuple}
  32. """
  33. user = None
  34. host = None
  35. resource = None
  36. # Search for delimiters
  37. user_sep = jidstring.find("@")
  38. res_sep = jidstring.find("/")
  39. if user_sep == -1:
  40. if res_sep == -1:
  41. # host
  42. host = jidstring
  43. else:
  44. # host/resource
  45. host = jidstring[0:res_sep]
  46. resource = jidstring[res_sep + 1 :] or None
  47. else:
  48. if res_sep == -1:
  49. # user@host
  50. user = jidstring[0:user_sep] or None
  51. host = jidstring[user_sep + 1 :]
  52. else:
  53. if user_sep < res_sep:
  54. # user@host/resource
  55. user = jidstring[0:user_sep] or None
  56. host = jidstring[user_sep + 1 : user_sep + (res_sep - user_sep)]
  57. resource = jidstring[res_sep + 1 :] or None
  58. else:
  59. # host/resource (with an @ in resource)
  60. host = jidstring[0:res_sep]
  61. resource = jidstring[res_sep + 1 :] or None
  62. return prep(user, host, resource)
  63. def prep(
  64. user: Union[str, None], host: str, resource: Union[str, None]
  65. ) -> Tuple[Union[str, None], str, Union[str, None]]:
  66. """
  67. Perform stringprep on all JID fragments.
  68. @param user: The user part of the JID.
  69. @type user: L{str}
  70. @param host: The host part of the JID.
  71. @type host: L{str}
  72. @param resource: The resource part of the JID.
  73. @type resource: L{str}
  74. @return: The given parts with stringprep applied.
  75. @rtype: L{tuple}
  76. """
  77. if user:
  78. try:
  79. user = nodeprep.prepare(str(user))
  80. except UnicodeError:
  81. raise InvalidFormat("Invalid character in username")
  82. else:
  83. user = None
  84. if not host:
  85. raise InvalidFormat("Server address required.")
  86. else:
  87. try:
  88. host = nameprep.prepare(str(host))
  89. except UnicodeError:
  90. raise InvalidFormat("Invalid character in hostname")
  91. if resource:
  92. try:
  93. resource = resourceprep.prepare(str(resource))
  94. except UnicodeError:
  95. raise InvalidFormat("Invalid character in resource")
  96. else:
  97. resource = None
  98. return (user, host, resource)
  99. __internJIDs: Dict[str, "JID"] = {}
  100. def internJID(jidstring):
  101. """
  102. Return interned JID.
  103. @rtype: L{JID}
  104. """
  105. if jidstring in __internJIDs:
  106. return __internJIDs[jidstring]
  107. else:
  108. j = JID(jidstring)
  109. __internJIDs[jidstring] = j
  110. return j
  111. class JID:
  112. """
  113. Represents a stringprep'd Jabber ID.
  114. JID objects are hashable so they can be used in sets and as keys in
  115. dictionaries.
  116. """
  117. def __init__(
  118. self,
  119. str: Union[str, None] = None,
  120. tuple: Union[Tuple[Union[str, None], str, Union[str, None]], None] = None,
  121. ):
  122. if str:
  123. user, host, res = parse(str)
  124. elif tuple:
  125. user, host, res = prep(*tuple)
  126. else:
  127. raise RuntimeError(
  128. "You must provide a value for either 'str' or 'tuple' arguments."
  129. )
  130. self.user = user
  131. self.host = host
  132. self.resource = res
  133. def userhost(self):
  134. """
  135. Extract the bare JID as a unicode string.
  136. A bare JID does not have a resource part, so this returns either
  137. C{user@host} or just C{host}.
  138. @rtype: L{str}
  139. """
  140. if self.user:
  141. return f"{self.user}@{self.host}"
  142. else:
  143. return self.host
  144. def userhostJID(self):
  145. """
  146. Extract the bare JID.
  147. A bare JID does not have a resource part, so this returns a
  148. L{JID} object representing either C{user@host} or just C{host}.
  149. If the object this method is called upon doesn't have a resource
  150. set, it will return itself. Otherwise, the bare JID object will
  151. be created, interned using L{internJID}.
  152. @rtype: L{JID}
  153. """
  154. if self.resource:
  155. return internJID(self.userhost())
  156. else:
  157. return self
  158. def full(self):
  159. """
  160. Return the string representation of this JID.
  161. @rtype: L{str}
  162. """
  163. if self.user:
  164. if self.resource:
  165. return f"{self.user}@{self.host}/{self.resource}"
  166. else:
  167. return f"{self.user}@{self.host}"
  168. else:
  169. if self.resource:
  170. return f"{self.host}/{self.resource}"
  171. else:
  172. return self.host
  173. def __eq__(self, other: object) -> bool:
  174. """
  175. Equality comparison.
  176. L{JID}s compare equal if their user, host and resource parts all
  177. compare equal. When comparing against instances of other types, it
  178. uses the default comparison.
  179. """
  180. if isinstance(other, JID):
  181. return (
  182. self.user == other.user
  183. and self.host == other.host
  184. and self.resource == other.resource
  185. )
  186. else:
  187. return NotImplemented
  188. def __hash__(self):
  189. """
  190. Calculate hash.
  191. L{JID}s with identical constituent user, host and resource parts have
  192. equal hash values. In combination with the comparison defined on JIDs,
  193. this allows for using L{JID}s in sets and as dictionary keys.
  194. """
  195. return hash((self.user, self.host, self.resource))
  196. def __unicode__(self):
  197. """
  198. Get unicode representation.
  199. Return the string representation of this JID as a unicode string.
  200. @see: L{full}
  201. """
  202. return self.full()
  203. __str__ = __unicode__
  204. def __repr__(self) -> str:
  205. """
  206. Get object representation.
  207. Returns a string that would create a new JID object that compares equal
  208. to this one.
  209. """
  210. return "JID(%r)" % self.full()