rdata_python.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. #define PY_SSIZE_T_CLEAN
  15. #include <Python.h>
  16. #include <dns/rdata.h>
  17. #include <dns/messagerenderer.h>
  18. #include <dns/exceptions.h>
  19. #include <util/buffer.h>
  20. #include <util/python/pycppwrapper_util.h>
  21. #include "rdata_python.h"
  22. #include "rrtype_python.h"
  23. #include "rrclass_python.h"
  24. #include "messagerenderer_python.h"
  25. #include "name_python.h"
  26. using namespace isc::dns;
  27. using namespace isc::dns::python;
  28. using namespace isc::util;
  29. using namespace isc::util::python;
  30. using namespace isc::dns::rdata;
  31. namespace {
  32. typedef PyObject* method(PyObject* self, PyObject* args);
  33. // Wrap a method into an exception handling, converting C++ exceptions
  34. // to python ones. The params and return value is just passed through.
  35. PyObject*
  36. exception_wrap(method* method, PyObject* self, PyObject* args) {
  37. try {
  38. return (method(self, args));
  39. } catch (const std::exception& ex) {
  40. // FIXME: These exceptions are not tested, I don't know how or if
  41. // at all they can be triggered. But they are caught just in the case.
  42. PyErr_SetString(PyExc_Exception, (std::string("Unknown exception: ") +
  43. ex.what()).c_str());
  44. return (NULL);
  45. } catch (...) {
  46. PyErr_SetString(PyExc_Exception, "Unknown exception");
  47. return (NULL);
  48. }
  49. }
  50. class s_Rdata : public PyObject {
  51. public:
  52. isc::dns::rdata::ConstRdataPtr cppobj;
  53. };
  54. typedef CPPPyObjectContainer<s_Rdata, Rdata> RdataContainer;
  55. //
  56. // We declare the functions here, the definitions are below
  57. // the type definition of the object, since both can use the other
  58. //
  59. // General creation and destruction
  60. int Rdata_init(PyObject* self, PyObject* args, PyObject*);
  61. void Rdata_destroy(PyObject* self);
  62. // These are the functions we export
  63. PyObject* Rdata_toText(PyObject* self, PyObject*);
  64. // This is a second version of toText, we need one where the argument
  65. // is a PyObject*, for the str() function in python.
  66. PyObject* Rdata_str(PyObject* self);
  67. PyObject* Rdata_toWire(PyObject* self, PyObject* args);
  68. PyObject* RData_richcmp(PyObject* self, PyObject* other, int op);
  69. // This list contains the actual set of functions we have in
  70. // python. Each entry has
  71. // 1. Python method name
  72. // 2. Our static function here
  73. // 3. Argument type
  74. // 4. Documentation
  75. PyMethodDef Rdata_methods[] = {
  76. { "to_text", Rdata_toText, METH_NOARGS,
  77. "Returns the string representation" },
  78. { "to_wire", Rdata_toWire, METH_VARARGS,
  79. "Converts the Rdata object to wire format.\n"
  80. "The argument can be either a MessageRenderer or an object that "
  81. "implements the sequence interface. If the object is mutable "
  82. "(for instance a bytearray()), the wire data is added in-place.\n"
  83. "If it is not (for instance a bytes() object), a new object is "
  84. "returned" },
  85. { NULL, NULL, 0, NULL }
  86. };
  87. int
  88. Rdata_init(PyObject* self_p, PyObject* args, PyObject*) {
  89. PyObject* rrtype;
  90. PyObject* rrclass;
  91. const char* s;
  92. const char* data;
  93. Py_ssize_t len;
  94. s_Rdata* self(static_cast<s_Rdata*>(self_p));
  95. try {
  96. // Create from string
  97. if (PyArg_ParseTuple(args, "O!O!s", &rrtype_type, &rrtype,
  98. &rrclass_type, &rrclass,
  99. &s)) {
  100. self->cppobj = createRdata(PyRRType_ToRRType(rrtype),
  101. PyRRClass_ToRRClass(rrclass), s);
  102. return (0);
  103. } else if (PyArg_ParseTuple(args, "O!O!y#", &rrtype_type, &rrtype,
  104. &rrclass_type, &rrclass, &data, &len)) {
  105. PyErr_Clear();
  106. InputBuffer input_buffer(data, len);
  107. self->cppobj = createRdata(PyRRType_ToRRType(rrtype),
  108. PyRRClass_ToRRClass(rrclass),
  109. input_buffer, len);
  110. return (0);
  111. }
  112. } catch (const isc::dns::rdata::InvalidRdataText& irdt) {
  113. PyErr_SetString(po_InvalidRdataText, irdt.what());
  114. return (-1);
  115. } catch (const isc::dns::rdata::InvalidRdataLength& irdl) {
  116. PyErr_SetString(po_InvalidRdataLength, irdl.what());
  117. return (-1);
  118. } catch (const isc::dns::rdata::CharStringTooLong& cstl) {
  119. PyErr_SetString(po_CharStringTooLong, cstl.what());
  120. return (-1);
  121. } catch (const isc::dns::DNSMessageFORMERR& dmfe) {
  122. PyErr_SetString(po_DNSMessageFORMERR, dmfe.what());
  123. return (-1);
  124. } catch (const std::exception& ex) {
  125. // FIXME: These exceptions are not tested, I don't know how or if
  126. // at all they can be triggered. But they are caught just in the case.
  127. PyErr_SetString(PyExc_Exception, (std::string("Unknown exception: ") +
  128. ex.what()).c_str());
  129. return (-1);
  130. } catch (...) {
  131. PyErr_SetString(PyExc_Exception, "Unknown exception");
  132. return (-1);
  133. }
  134. return (-1);
  135. }
  136. void
  137. Rdata_destroy(PyObject* self) {
  138. // Clear the shared_ptr so that its reference count is zero
  139. // before we call tp_free() (there is no direct release())
  140. static_cast<s_Rdata*>(self)->cppobj.reset();
  141. Py_TYPE(self)->tp_free(self);
  142. }
  143. PyObject*
  144. Rdata_toText_internal(PyObject* self, PyObject*) {
  145. // Py_BuildValue makes python objects from native data
  146. return (Py_BuildValue("s", static_cast<const s_Rdata*>(self)->cppobj->
  147. toText().c_str()));
  148. }
  149. PyObject*
  150. Rdata_toText(PyObject* self, PyObject* args) {
  151. return (exception_wrap(&Rdata_toText_internal, self, args));
  152. }
  153. PyObject*
  154. Rdata_str(PyObject* self) {
  155. // Simply call the to_text method we already defined
  156. return (PyObject_CallMethod(self,
  157. const_cast<char*>("to_text"),
  158. const_cast<char*>("")));
  159. }
  160. PyObject*
  161. Rdata_toWire_internal(PyObject* self_p, PyObject* args) {
  162. PyObject* bytes;
  163. PyObject* mr;
  164. const s_Rdata* self(static_cast<const s_Rdata*>(self_p));
  165. if (PyArg_ParseTuple(args, "O", &bytes) && PySequence_Check(bytes)) {
  166. PyObject* bytes_o = bytes;
  167. OutputBuffer buffer(4);
  168. self->cppobj->toWire(buffer);
  169. PyObject* rd_bytes = PyBytes_FromStringAndSize(static_cast<const char*>(buffer.getData()), buffer.getLength());
  170. // Make sure exceptions from here are propagated.
  171. // The exception is already set, so we just return NULL
  172. if (rd_bytes == NULL) {
  173. return (NULL);
  174. }
  175. PyObject* result = PySequence_InPlaceConcat(bytes_o, rd_bytes);
  176. // We need to release the object we temporarily created here
  177. // to prevent memory leak
  178. Py_DECREF(rd_bytes);
  179. return (result);
  180. } else if (PyArg_ParseTuple(args, "O!", &messagerenderer_type, &mr)) {
  181. self->cppobj->toWire(PyMessageRenderer_ToMessageRenderer(mr));
  182. // If we return NULL it is seen as an error, so use this for
  183. // None returns
  184. Py_RETURN_NONE;
  185. }
  186. PyErr_Clear();
  187. PyErr_SetString(PyExc_TypeError,
  188. "toWire argument must be a sequence object or a MessageRenderer");
  189. return (NULL);
  190. }
  191. PyObject*
  192. Rdata_toWire(PyObject* self, PyObject* args) {
  193. return (exception_wrap(&Rdata_toWire_internal, self, args));
  194. }
  195. PyObject*
  196. RData_richcmp(PyObject* self_p, PyObject* other_p, int op) {
  197. try {
  198. bool c;
  199. const s_Rdata* self(static_cast<const s_Rdata*>(self_p)),
  200. * other(static_cast<const s_Rdata*>(other_p));
  201. // Check for null and if the types match. If different type,
  202. // simply return False
  203. if (!other || (self->ob_type != other->ob_type)) {
  204. Py_RETURN_FALSE;
  205. }
  206. switch (op) {
  207. case Py_LT:
  208. c = self->cppobj->compare(*other->cppobj) < 0;
  209. break;
  210. case Py_LE:
  211. c = self->cppobj->compare(*other->cppobj) < 0 ||
  212. self->cppobj->compare(*other->cppobj) == 0;
  213. break;
  214. case Py_EQ:
  215. c = self->cppobj->compare(*other->cppobj) == 0;
  216. break;
  217. case Py_NE:
  218. c = self->cppobj->compare(*other->cppobj) != 0;
  219. break;
  220. case Py_GT:
  221. c = self->cppobj->compare(*other->cppobj) > 0;
  222. break;
  223. case Py_GE:
  224. c = self->cppobj->compare(*other->cppobj) > 0 ||
  225. self->cppobj->compare(*other->cppobj) == 0;
  226. break;
  227. default:
  228. PyErr_SetString(PyExc_IndexError,
  229. "Unhandled rich comparison operator");
  230. return (NULL);
  231. }
  232. if (c) {
  233. Py_RETURN_TRUE;
  234. } else {
  235. Py_RETURN_FALSE;
  236. }
  237. } catch (const std::exception& ex) {
  238. // FIXME: These exceptions are not tested, I don't know how or if
  239. // at all they can be triggered. But they are caught just in the case.
  240. PyErr_SetString(PyExc_Exception, (std::string("Unknown exception: ") +
  241. ex.what()).c_str());
  242. return (NULL);
  243. } catch (...) {
  244. PyErr_SetString(PyExc_Exception, "Unknown exception");
  245. return (NULL);
  246. }
  247. }
  248. } // end of unnamed namespace
  249. namespace isc {
  250. namespace dns {
  251. namespace python {
  252. //
  253. // Declaration of the custom exceptions
  254. // Initialization and addition of these go in the initModulePart
  255. // function in pydnspp
  256. //
  257. PyObject* po_InvalidRdataLength;
  258. PyObject* po_InvalidRdataText;
  259. PyObject* po_CharStringTooLong;
  260. // This defines the complete type for reflection in python and
  261. // parsing of PyObject* to s_Rdata
  262. // Most of the functions are not actually implemented and NULL here.
  263. PyTypeObject rdata_type = {
  264. PyVarObject_HEAD_INIT(NULL, 0)
  265. "pydnspp.Rdata",
  266. sizeof(s_Rdata), // tp_basicsize
  267. 0, // tp_itemsize
  268. Rdata_destroy, // tp_dealloc
  269. NULL, // tp_print
  270. NULL, // tp_getattr
  271. NULL, // tp_setattr
  272. NULL, // tp_reserved
  273. NULL, // tp_repr
  274. NULL, // tp_as_number
  275. NULL, // tp_as_sequence
  276. NULL, // tp_as_mapping
  277. NULL, // tp_hash
  278. NULL, // tp_call
  279. Rdata_str, // tp_str
  280. NULL, // tp_getattro
  281. NULL, // tp_setattro
  282. NULL, // tp_as_buffer
  283. Py_TPFLAGS_DEFAULT, // tp_flags
  284. "The Rdata class is an abstract base class that provides "
  285. "a set of common interfaces to manipulate concrete RDATA objects.",
  286. NULL, // tp_traverse
  287. NULL, // tp_clear
  288. RData_richcmp, // tp_richcompare
  289. 0, // tp_weaklistoffset
  290. NULL, // tp_iter
  291. NULL, // tp_iternext
  292. Rdata_methods, // tp_methods
  293. NULL, // tp_members
  294. NULL, // tp_getset
  295. NULL, // tp_base
  296. NULL, // tp_dict
  297. NULL, // tp_descr_get
  298. NULL, // tp_descr_set
  299. 0, // tp_dictoffset
  300. Rdata_init, // tp_init
  301. NULL, // tp_alloc
  302. PyType_GenericNew, // tp_new
  303. NULL, // tp_free
  304. NULL, // tp_is_gc
  305. NULL, // tp_bases
  306. NULL, // tp_mro
  307. NULL, // tp_cache
  308. NULL, // tp_subclasses
  309. NULL, // tp_weaklist
  310. NULL, // tp_del
  311. 0 // tp_version_tag
  312. };
  313. PyObject*
  314. createRdataObject(ConstRdataPtr source) {
  315. s_Rdata* py_rdata =
  316. static_cast<s_Rdata*>(rdata_type.tp_alloc(&rdata_type, 0));
  317. if (py_rdata == NULL) {
  318. isc_throw(PyCPPWrapperException, "Unexpected NULL C++ object, "
  319. "probably due to short memory");
  320. }
  321. py_rdata->cppobj = source;
  322. return (py_rdata);
  323. }
  324. bool
  325. PyRdata_Check(PyObject* obj) {
  326. if (obj == NULL) {
  327. isc_throw(PyCPPWrapperException, "obj argument NULL in typecheck");
  328. }
  329. return (PyObject_TypeCheck(obj, &rdata_type));
  330. }
  331. const Rdata&
  332. PyRdata_ToRdata(const PyObject* rdata_obj) {
  333. if (rdata_obj == NULL) {
  334. isc_throw(PyCPPWrapperException,
  335. "obj argument NULL in Rdata PyObject conversion");
  336. }
  337. const s_Rdata* rdata = static_cast<const s_Rdata*>(rdata_obj);
  338. return (*rdata->cppobj);
  339. }
  340. } // end python namespace
  341. } // end dns namespace
  342. } // end isc namespace