| 1 | # Copyright (C) 2003-2007, 2009, 2010 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 |
|
|---|
| 16 | """DNS TTL conversion."""
|
|---|
| 17 |
|
|---|
| 18 | import dns.exception
|
|---|
| 19 |
|
|---|
| 20 | class BadTTL(dns.exception.SyntaxError):
|
|---|
| 21 | pass
|
|---|
| 22 |
|
|---|
| 23 | def from_text(text):
|
|---|
| 24 | """Convert the text form of a TTL to an integer.
|
|---|
| 25 |
|
|---|
| 26 | The BIND 8 units syntax for TTLs (e.g. '1w6d4h3m10s') is supported.
|
|---|
| 27 |
|
|---|
| 28 | @param text: the textual TTL
|
|---|
| 29 | @type text: string
|
|---|
| 30 | @raises dns.ttl.BadTTL: the TTL is not well-formed
|
|---|
| 31 | @rtype: int
|
|---|
| 32 | """
|
|---|
| 33 |
|
|---|
| 34 | if text.isdigit():
|
|---|
| 35 | total = long(text)
|
|---|
| 36 | else:
|
|---|
| 37 | if not text[0].isdigit():
|
|---|
| 38 | raise BadTTL
|
|---|
| 39 | total = 0L
|
|---|
| 40 | current = 0L
|
|---|
| 41 | for c in text:
|
|---|
| 42 | if c.isdigit():
|
|---|
| 43 | current *= 10
|
|---|
| 44 | current += long(c)
|
|---|
| 45 | else:
|
|---|
| 46 | c = c.lower()
|
|---|
| 47 | if c == 'w':
|
|---|
| 48 | total += current * 604800L
|
|---|
| 49 | elif c == 'd':
|
|---|
| 50 | total += current * 86400L
|
|---|
| 51 | elif c == 'h':
|
|---|
| 52 | total += current * 3600L
|
|---|
| 53 | elif c == 'm':
|
|---|
| 54 | total += current * 60L
|
|---|
| 55 | elif c == 's':
|
|---|
| 56 | total += current
|
|---|
| 57 | else:
|
|---|
| 58 | raise BadTTL("unknown unit '%s'" % c)
|
|---|
| 59 | current = 0
|
|---|
| 60 | if not current == 0:
|
|---|
| 61 | raise BadTTL("trailing integer")
|
|---|
| 62 | if total < 0L or total > 2147483647L:
|
|---|
| 63 | raise BadTTL("TTL should be between 0 and 2^31 - 1 (inclusive)")
|
|---|
| 64 | return total
|
|---|