rrttl_python.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <Python.h>
  15. #include <vector>
  16. #include <dns/rrttl.h>
  17. #include <dns/messagerenderer.h>
  18. #include <util/buffer.h>
  19. #include "rrttl_python.h"
  20. #include "pydnspp_common.h"
  21. #include "messagerenderer_python.h"
  22. using namespace std;
  23. using namespace isc::dns;
  24. using namespace isc::dns::python;
  25. using namespace isc::util;
  26. namespace {
  27. int RRTTL_init(s_RRTTL* self, PyObject* args);
  28. void RRTTL_destroy(s_RRTTL* self);
  29. PyObject* RRTTL_toText(s_RRTTL* self);
  30. // This is a second version of toText, we need one where the argument
  31. // is a PyObject*, for the str() function in python.
  32. PyObject* RRTTL_str(PyObject* self);
  33. PyObject* RRTTL_toWire(s_RRTTL* self, PyObject* args);
  34. PyObject* RRTTL_getValue(s_RRTTL* self);
  35. PyObject* RRTTL_richcmp(s_RRTTL* self, s_RRTTL* other, int op);
  36. // This list contains the actual set of functions we have in
  37. // python. Each entry has
  38. // 1. Python method name
  39. // 2. Our static function here
  40. // 3. Argument type
  41. // 4. Documentation
  42. PyMethodDef RRTTL_methods[] = {
  43. { "to_text", reinterpret_cast<PyCFunction>(RRTTL_toText), METH_NOARGS,
  44. "Returns the string representation" },
  45. { "to_wire", reinterpret_cast<PyCFunction>(RRTTL_toWire), METH_VARARGS,
  46. "Converts the RRTTL object to wire format.\n"
  47. "The argument can be either a MessageRenderer or an object that "
  48. "implements the sequence interface. If the object is mutable "
  49. "(for instance a bytearray()), the wire data is added in-place.\n"
  50. "If it is not (for instance a bytes() object), a new object is "
  51. "returned" },
  52. { "get_value", reinterpret_cast<PyCFunction>(RRTTL_getValue), METH_NOARGS,
  53. "Returns the TTL as an integer" },
  54. { NULL, NULL, 0, NULL }
  55. };
  56. int
  57. RRTTL_init(s_RRTTL* self, PyObject* args) {
  58. const char* s;
  59. long long i;
  60. PyObject* bytes = NULL;
  61. // The constructor argument can be a string ("1234"), an integer (1),
  62. // or a sequence of numbers between 0 and 255 (wire code)
  63. // Note that PyArg_ParseType can set PyError, and we need to clear
  64. // that if we try several like here. Otherwise the *next* python
  65. // call will suddenly appear to throw an exception.
  66. // (the way to do exceptions is to set PyErr and return -1)
  67. try {
  68. if (PyArg_ParseTuple(args, "s", &s)) {
  69. self->rrttl = new RRTTL(s);
  70. return (0);
  71. } else if (PyArg_ParseTuple(args, "L", &i)) {
  72. PyErr_Clear();
  73. if (i < 0 || i > 0xffffffff) {
  74. PyErr_SetString(PyExc_ValueError, "RR TTL number out of range");
  75. return (-1);
  76. }
  77. self->rrttl = new RRTTL(i);
  78. return (0);
  79. } else if (PyArg_ParseTuple(args, "O", &bytes) &&
  80. PySequence_Check(bytes)) {
  81. Py_ssize_t size = PySequence_Size(bytes);
  82. vector<uint8_t> data(size);
  83. int result = readDataFromSequence(&data[0], size, bytes);
  84. if (result != 0) {
  85. return (result);
  86. }
  87. InputBuffer ib(&data[0], size);
  88. self->rrttl = new RRTTL(ib);
  89. PyErr_Clear();
  90. return (0);
  91. }
  92. } catch (const IncompleteRRTTL& icc) {
  93. // Ok so one of our functions has thrown a C++ exception.
  94. // We need to translate that to a Python Exception
  95. // First clear any existing error that was set
  96. PyErr_Clear();
  97. // Now set our own exception
  98. PyErr_SetString(po_IncompleteRRTTL, icc.what());
  99. // And return negative
  100. return (-1);
  101. } catch (const InvalidRRTTL& ic) {
  102. PyErr_Clear();
  103. PyErr_SetString(po_InvalidRRTTL, ic.what());
  104. return (-1);
  105. }
  106. PyErr_Clear();
  107. PyErr_SetString(PyExc_TypeError,
  108. "no valid type in constructor argument");
  109. return (-1);
  110. }
  111. void
  112. RRTTL_destroy(s_RRTTL* self) {
  113. delete self->rrttl;
  114. self->rrttl = NULL;
  115. Py_TYPE(self)->tp_free(self);
  116. }
  117. PyObject*
  118. RRTTL_toText(s_RRTTL* self) {
  119. // Py_BuildValue makes python objects from native data
  120. return (Py_BuildValue("s", self->rrttl->toText().c_str()));
  121. }
  122. PyObject*
  123. RRTTL_str(PyObject* self) {
  124. // Simply call the to_text method we already defined
  125. return (PyObject_CallMethod(self,
  126. const_cast<char*>("to_text"),
  127. const_cast<char*>("")));
  128. }
  129. PyObject*
  130. RRTTL_toWire(s_RRTTL* self, PyObject* args) {
  131. PyObject* bytes;
  132. s_MessageRenderer* mr;
  133. if (PyArg_ParseTuple(args, "O", &bytes) && PySequence_Check(bytes)) {
  134. PyObject* bytes_o = bytes;
  135. OutputBuffer buffer(4);
  136. self->rrttl->toWire(buffer);
  137. PyObject* n = PyBytes_FromStringAndSize(static_cast<const char*>(buffer.getData()),
  138. buffer.getLength());
  139. PyObject* result = PySequence_InPlaceConcat(bytes_o, n);
  140. // We need to release the object we temporarily created here
  141. // to prevent memory leak
  142. Py_DECREF(n);
  143. return (result);
  144. } else if (PyArg_ParseTuple(args, "O!", &messagerenderer_type, &mr)) {
  145. self->rrttl->toWire(*mr->messagerenderer);
  146. // If we return NULL it is seen as an error, so use this for
  147. // None returns
  148. Py_RETURN_NONE;
  149. }
  150. PyErr_Clear();
  151. PyErr_SetString(PyExc_TypeError,
  152. "toWire argument must be a sequence object or a MessageRenderer");
  153. return (NULL);
  154. }
  155. PyObject*
  156. RRTTL_getValue(s_RRTTL* self) {
  157. return (Py_BuildValue("I", self->rrttl->getValue()));
  158. }
  159. PyObject*
  160. RRTTL_richcmp(s_RRTTL* self, s_RRTTL* other, int op) {
  161. bool c = false;
  162. // Check for null and if the types match. If different type,
  163. // simply return False
  164. if (!other || (self->ob_type != other->ob_type)) {
  165. Py_RETURN_FALSE;
  166. }
  167. switch (op) {
  168. case Py_LT:
  169. c = *self->rrttl < *other->rrttl;
  170. break;
  171. case Py_LE:
  172. c = *self->rrttl < *other->rrttl ||
  173. *self->rrttl == *other->rrttl;
  174. break;
  175. case Py_EQ:
  176. c = *self->rrttl == *other->rrttl;
  177. break;
  178. case Py_NE:
  179. c = *self->rrttl != *other->rrttl;
  180. break;
  181. case Py_GT:
  182. c = *other->rrttl < *self->rrttl;
  183. break;
  184. case Py_GE:
  185. c = *other->rrttl < *self->rrttl ||
  186. *self->rrttl == *other->rrttl;
  187. break;
  188. }
  189. if (c)
  190. Py_RETURN_TRUE;
  191. else
  192. Py_RETURN_FALSE;
  193. }
  194. } // end anonymous namespace
  195. namespace isc {
  196. namespace dns {
  197. namespace python {
  198. //
  199. // Declaration of the custom exceptions
  200. // Initialization and addition of these go in the initModulePart
  201. // function at the end of this file
  202. //
  203. PyObject* po_InvalidRRTTL;
  204. PyObject* po_IncompleteRRTTL;
  205. // This defines the complete type for reflection in python and
  206. // parsing of PyObject* to s_RRTTL
  207. // Most of the functions are not actually implemented and NULL here.
  208. PyTypeObject rrttl_type = {
  209. PyVarObject_HEAD_INIT(NULL, 0)
  210. "pydnspp.RRTTL",
  211. sizeof(s_RRTTL), // tp_basicsize
  212. 0, // tp_itemsize
  213. (destructor)RRTTL_destroy, // tp_dealloc
  214. NULL, // tp_print
  215. NULL, // tp_getattr
  216. NULL, // tp_setattr
  217. NULL, // tp_reserved
  218. NULL, // tp_repr
  219. NULL, // tp_as_number
  220. NULL, // tp_as_sequence
  221. NULL, // tp_as_mapping
  222. NULL, // tp_hash
  223. NULL, // tp_call
  224. RRTTL_str, // tp_str
  225. NULL, // tp_getattro
  226. NULL, // tp_setattro
  227. NULL, // tp_as_buffer
  228. Py_TPFLAGS_DEFAULT, // tp_flags
  229. "The RRTTL class encapsulates TTLs used in DNS resource records.\n\n"
  230. "This is a straightforward class; an RRTTL object simply maintains a "
  231. "32-bit unsigned integer corresponding to the TTL value. The main purpose "
  232. "of this class is to provide convenient interfaces to convert a textual "
  233. "representation into the integer TTL value and vice versa, and to handle "
  234. "wire-format representations.",
  235. NULL, // tp_traverse
  236. NULL, // tp_clear
  237. (richcmpfunc)RRTTL_richcmp, // tp_richcompare
  238. 0, // tp_weaklistoffset
  239. NULL, // tp_iter
  240. NULL, // tp_iternext
  241. RRTTL_methods, // tp_methods
  242. NULL, // tp_members
  243. NULL, // tp_getset
  244. NULL, // tp_base
  245. NULL, // tp_dict
  246. NULL, // tp_descr_get
  247. NULL, // tp_descr_set
  248. 0, // tp_dictoffset
  249. (initproc)RRTTL_init, // tp_init
  250. NULL, // tp_alloc
  251. PyType_GenericNew, // tp_new
  252. NULL, // tp_free
  253. NULL, // tp_is_gc
  254. NULL, // tp_bases
  255. NULL, // tp_mro
  256. NULL, // tp_cache
  257. NULL, // tp_subclasses
  258. NULL, // tp_weaklist
  259. NULL, // tp_del
  260. 0 // tp_version_tag
  261. };
  262. // Module Initialization, all statics are initialized here
  263. namespace internal {
  264. bool
  265. initModulePart_RRTTL(PyObject* mod) {
  266. // Add the exceptions to the module
  267. po_InvalidRRTTL = PyErr_NewException("pydnspp.InvalidRRTTL", NULL, NULL);
  268. PyModule_AddObject(mod, "InvalidRRTTL", po_InvalidRRTTL);
  269. po_IncompleteRRTTL = PyErr_NewException("pydnspp.IncompleteRRTTL", NULL, NULL);
  270. PyModule_AddObject(mod, "IncompleteRRTTL", po_IncompleteRRTTL);
  271. // We initialize the static description object with PyType_Ready(),
  272. // then add it to the module. This is not just a check! (leaving
  273. // this out results in segmentation faults)
  274. if (PyType_Ready(&rrttl_type) < 0) {
  275. return (false);
  276. }
  277. Py_INCREF(&rrttl_type);
  278. PyModule_AddObject(mod, "RRTTL",
  279. reinterpret_cast<PyObject*>(&rrttl_type));
  280. return (true);
  281. }
  282. } // end namespace internal
  283. } // namespace python
  284. } // namespace dns
  285. } // namespace isc