ttl.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose with or without fee is hereby granted,
  5. # provided that the above copyright notice and this permission notice
  6. # appear in all copies.
  7. #
  8. # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
  9. # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
  11. # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  14. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. """DNS TTL conversion."""
  16. import dns.exception
  17. from ._compat import long
  18. class BadTTL(dns.exception.SyntaxError):
  19. """DNS TTL value is not well-formed."""
  20. def from_text(text):
  21. """Convert the text form of a TTL to an integer.
  22. The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported.
  23. @param text: the textual TTL
  24. @type text: string
  25. @raises dns.ttl.BadTTL: the TTL is not well-formed
  26. @rtype: 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