rrttl_python.cc 11 KB

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