endpoint.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. import re
  17. logger = logging.getLogger(__name__)
  18. def parse_server_name(server_name):
  19. """Split a server name into host/port parts.
  20. Args:
  21. server_name (str): server name to parse
  22. Returns:
  23. Tuple[str, int|None]: host/port parts.
  24. Raises:
  25. ValueError if the server name could not be parsed.
  26. """
  27. try:
  28. if server_name[-1] == "]":
  29. # ipv6 literal, hopefully
  30. return server_name, None
  31. domain_port = server_name.rsplit(":", 1)
  32. domain = domain_port[0]
  33. port = int(domain_port[1]) if domain_port[1:] else None
  34. return domain, port
  35. except Exception:
  36. raise ValueError("Invalid server name '%s'" % server_name)
  37. VALID_HOST_REGEX = re.compile("\\A[0-9a-zA-Z.-]+\\Z")
  38. def parse_and_validate_server_name(server_name):
  39. """Split a server name into host/port parts and do some basic validation.
  40. Args:
  41. server_name (str): server name to parse
  42. Returns:
  43. Tuple[str, int|None]: host/port parts.
  44. Raises:
  45. ValueError if the server name could not be parsed.
  46. """
  47. host, port = parse_server_name(server_name)
  48. # these tests don't need to be bulletproof as we'll find out soon enough
  49. # if somebody is giving us invalid data. What we *do* need is to be sure
  50. # that nobody is sneaking IP literals in that look like hostnames, etc.
  51. # look for ipv6 literals
  52. if host[0] == "[":
  53. if host[-1] != "]":
  54. raise ValueError("Mismatched [...] in server name '%s'" % (server_name,))
  55. return host, port
  56. # otherwise it should only be alphanumerics.
  57. if not VALID_HOST_REGEX.match(host):
  58. raise ValueError(
  59. "Server name '%s' contains invalid characters" % (server_name,)
  60. )
  61. return host, port