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.

128 lines
4.8 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. """Common DNS Exceptions.
  17. Dnspython modules may also define their own exceptions, which will
  18. always be subclasses of ``DNSException``.
  19. """
  20. class DNSException(Exception):
  21. """Abstract base class shared by all dnspython exceptions.
  22. It supports two basic modes of operation:
  23. a) Old/compatible mode is used if ``__init__`` was called with
  24. empty *kwargs*. In compatible mode all *args* are passed
  25. to the standard Python Exception class as before and all *args* are
  26. printed by the standard ``__str__`` implementation. Class variable
  27. ``msg`` (or doc string if ``msg`` is ``None``) is returned from ``str()``
  28. if *args* is empty.
  29. b) New/parametrized mode is used if ``__init__`` was called with
  30. non-empty *kwargs*.
  31. In the new mode *args* must be empty and all kwargs must match
  32. those set in class variable ``supp_kwargs``. All kwargs are stored inside
  33. ``self.kwargs`` and used in a new ``__str__`` implementation to construct
  34. a formatted message based on the ``fmt`` class variable, a ``string``.
  35. In the simplest case it is enough to override the ``supp_kwargs``
  36. and ``fmt`` class variables to get nice parametrized messages.
  37. """
  38. msg = None # non-parametrized message
  39. supp_kwargs = set() # accepted parameters for _fmt_kwargs (sanity check)
  40. fmt = None # message parametrized with results from _fmt_kwargs
  41. def __init__(self, *args, **kwargs):
  42. self._check_params(*args, **kwargs)
  43. if kwargs:
  44. self.kwargs = self._check_kwargs(**kwargs)
  45. self.msg = str(self)
  46. else:
  47. self.kwargs = dict() # defined but empty for old mode exceptions
  48. if self.msg is None:
  49. # doc string is better implicit message than empty string
  50. self.msg = self.__doc__
  51. if args:
  52. super(DNSException, self).__init__(*args)
  53. else:
  54. super(DNSException, self).__init__(self.msg)
  55. def _check_params(self, *args, **kwargs):
  56. """Old exceptions supported only args and not kwargs.
  57. For sanity we do not allow to mix old and new behavior."""
  58. if args or kwargs:
  59. assert bool(args) != bool(kwargs), \
  60. 'keyword arguments are mutually exclusive with positional args'
  61. def _check_kwargs(self, **kwargs):
  62. if kwargs:
  63. assert set(kwargs.keys()) == self.supp_kwargs, \
  64. 'following set of keyword args is required: %s' % (
  65. self.supp_kwargs)
  66. return kwargs
  67. def _fmt_kwargs(self, **kwargs):
  68. """Format kwargs before printing them.
  69. Resulting dictionary has to have keys necessary for str.format call
  70. on fmt class variable.
  71. """
  72. fmtargs = {}
  73. for kw, data in kwargs.items():
  74. if isinstance(data, (list, set)):
  75. # convert list of <someobj> to list of str(<someobj>)
  76. fmtargs[kw] = list(map(str, data))
  77. if len(fmtargs[kw]) == 1:
  78. # remove list brackets [] from single-item lists
  79. fmtargs[kw] = fmtargs[kw].pop()
  80. else:
  81. fmtargs[kw] = data
  82. return fmtargs
  83. def __str__(self):
  84. if self.kwargs and self.fmt:
  85. # provide custom message constructed from keyword arguments
  86. fmtargs = self._fmt_kwargs(**self.kwargs)
  87. return self.fmt.format(**fmtargs)
  88. else:
  89. # print *args directly in the same way as old DNSException
  90. return super(DNSException, self).__str__()
  91. class FormError(DNSException):
  92. """DNS message is malformed."""
  93. class SyntaxError(DNSException):
  94. """Text input is malformed."""
  95. class UnexpectedEnd(SyntaxError):
  96. """Text input ended unexpectedly."""
  97. class TooBig(DNSException):
  98. """The DNS message is too big."""
  99. class Timeout(DNSException):
  100. """The DNS operation timed out."""
  101. supp_kwargs = {'timeout'}
  102. fmt = "The DNS operation timed out after {timeout} seconds"