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.

70 lines
2.3 KiB

4 years ago
  1. # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
  2. # Copyright (C) 2003-2017 Nominum, Inc.
  3. #
  4. # Permission to use, copy, modify, and distribute this software and its
  5. # documentation for any purpose with or without fee is hereby granted,
  6. # provided that the above copyright notice and this permission notice
  7. # appear in all copies.
  8. #
  9. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  10. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  12. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. """DNS TTL conversion."""
  17. import dns.exception
  18. from ._compat import long
  19. class BadTTL(dns.exception.SyntaxError):
  20. """DNS TTL value is not well-formed."""
  21. def from_text(text):
  22. """Convert the text form of a TTL to an integer.
  23. The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported.
  24. *text*, a ``text``, the textual TTL.
  25. Raises ``dns.ttl.BadTTL`` if the TTL is not well-formed.
  26. Returns an ``int``.
  27. """
  28. if text.isdigit():
  29. total = long(text)
  30. else:
  31. if not text[0].isdigit():
  32. raise BadTTL
  33. total = long(0)
  34. current = long(0)
  35. for c in text:
  36. if c.isdigit():
  37. current *= 10
  38. current += long(c)
  39. else:
  40. c = c.lower()
  41. if c == 'w':
  42. total += current * long(604800)
  43. elif c == 'd':
  44. total += current * long(86400)
  45. elif c == 'h':
  46. total += current * long(3600)
  47. elif c == 'm':
  48. total += current * long(60)
  49. elif c == 's':
  50. total += current
  51. else:
  52. raise BadTTL("unknown unit '%s'" % c)
  53. current = 0
  54. if not current == 0:
  55. raise BadTTL("trailing integer")
  56. if total < long(0) or total > long(2147483647):
  57. raise BadTTL("TTL should be between 0 and 2^31 - 1 (inclusive)")
  58. return total