rdata_python.cc 14 KB

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