rdata_python.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. InputBuffer input_buffer(data, len);
  106. self->cppobj = createRdata(PyRRType_ToRRType(rrtype),
  107. PyRRClass_ToRRClass(rrclass),
  108. input_buffer, len);
  109. return (0);
  110. }
  111. } catch (const isc::dns::rdata::InvalidRdataText& irdt) {
  112. PyErr_SetString(po_InvalidRdataText, irdt.what());
  113. return (-1);
  114. } catch (const isc::dns::rdata::InvalidRdataLength& irdl) {
  115. PyErr_SetString(po_InvalidRdataLength, irdl.what());
  116. return (-1);
  117. } catch (const isc::dns::rdata::CharStringTooLong& cstl) {
  118. PyErr_SetString(po_CharStringTooLong, cstl.what());
  119. return (-1);
  120. } catch (const isc::dns::DNSMessageFORMERR& dmfe) {
  121. PyErr_SetString(po_DNSMessageFORMERR, dmfe.what());
  122. return (-1);
  123. } catch (const std::exception& ex) {
  124. // FIXME: These exceptions are not tested, I don't know how or if
  125. // at all they can be triggered. But they are caught just in the case.
  126. PyErr_SetString(PyExc_Exception, (std::string("Unknown exception: ") +
  127. ex.what()).c_str());
  128. return (-1);
  129. } catch (...) {
  130. PyErr_SetString(PyExc_Exception, "Unknown exception");
  131. return (-1);
  132. }
  133. return (-1);
  134. }
  135. void
  136. Rdata_destroy(PyObject* self) {
  137. // Clear the shared_ptr so that its reference count is zero
  138. // before we call tp_free() (there is no direct release())
  139. static_cast<s_Rdata*>(self)->cppobj.reset();
  140. Py_TYPE(self)->tp_free(self);
  141. }
  142. PyObject*
  143. Rdata_toText_internal(PyObject* self, PyObject*) {
  144. // Py_BuildValue makes python objects from native data
  145. return (Py_BuildValue("s", static_cast<const s_Rdata*>(self)->cppobj->
  146. toText().c_str()));
  147. }
  148. PyObject*
  149. Rdata_toText(PyObject* self, PyObject* args) {
  150. return (exception_wrap(&Rdata_toText_internal, self, args));
  151. }
  152. PyObject*
  153. Rdata_str(PyObject* self) {
  154. // Simply call the to_text method we already defined
  155. return (PyObject_CallMethod(self,
  156. const_cast<char*>("to_text"),
  157. const_cast<char*>("")));
  158. }
  159. PyObject*
  160. Rdata_toWire_internal(PyObject* self_p, PyObject* args) {
  161. PyObject* bytes;
  162. PyObject* mr;
  163. const s_Rdata* self(static_cast<const s_Rdata*>(self_p));
  164. if (PyArg_ParseTuple(args, "O", &bytes) && PySequence_Check(bytes)) {
  165. PyObject* bytes_o = bytes;
  166. OutputBuffer buffer(4);
  167. self->cppobj->toWire(buffer);
  168. PyObject* rd_bytes = PyBytes_FromStringAndSize(static_cast<const char*>(buffer.getData()), buffer.getLength());
  169. // Make sure exceptions from here are propagated.
  170. // The exception is already set, so we just return NULL
  171. if (rd_bytes == NULL) {
  172. return (NULL);
  173. }
  174. PyObject* result = PySequence_InPlaceConcat(bytes_o, rd_bytes);
  175. // We need to release the object we temporarily created here
  176. // to prevent memory leak
  177. Py_DECREF(rd_bytes);
  178. return (result);
  179. } else if (PyArg_ParseTuple(args, "O!", &messagerenderer_type, &mr)) {
  180. self->cppobj->toWire(PyMessageRenderer_ToMessageRenderer(mr));
  181. // If we return NULL it is seen as an error, so use this for
  182. // None returns
  183. Py_RETURN_NONE;
  184. }
  185. PyErr_Clear();
  186. PyErr_SetString(PyExc_TypeError,
  187. "toWire argument must be a sequence object or a MessageRenderer");
  188. return (NULL);
  189. }
  190. PyObject*
  191. Rdata_toWire(PyObject* self, PyObject* args) {
  192. return (exception_wrap(&Rdata_toWire_internal, self, args));
  193. }
  194. PyObject*
  195. RData_richcmp(PyObject* self_p, PyObject* other_p, int op) {
  196. try {
  197. bool c;
  198. const s_Rdata* self(static_cast<const s_Rdata*>(self_p)),
  199. * other(static_cast<const s_Rdata*>(other_p));
  200. // Check for null and if the types match. If different type,
  201. // simply return False
  202. if (!other || (self->ob_type != other->ob_type)) {
  203. Py_RETURN_FALSE;
  204. }
  205. switch (op) {
  206. case Py_LT:
  207. c = self->cppobj->compare(*other->cppobj) < 0;
  208. break;
  209. case Py_LE:
  210. c = self->cppobj->compare(*other->cppobj) < 0 ||
  211. self->cppobj->compare(*other->cppobj) == 0;
  212. break;
  213. case Py_EQ:
  214. c = self->cppobj->compare(*other->cppobj) == 0;
  215. break;
  216. case Py_NE:
  217. c = self->cppobj->compare(*other->cppobj) != 0;
  218. break;
  219. case Py_GT:
  220. c = self->cppobj->compare(*other->cppobj) > 0;
  221. break;
  222. case Py_GE:
  223. c = self->cppobj->compare(*other->cppobj) > 0 ||
  224. self->cppobj->compare(*other->cppobj) == 0;
  225. break;
  226. default:
  227. PyErr_SetString(PyExc_IndexError,
  228. "Unhandled rich comparison operator");
  229. return (NULL);
  230. }
  231. if (c) {
  232. Py_RETURN_TRUE;
  233. } else {
  234. Py_RETURN_FALSE;
  235. }
  236. } catch (const std::exception& ex) {
  237. // FIXME: These exceptions are not tested, I don't know how or if
  238. // at all they can be triggered. But they are caught just in the case.
  239. PyErr_SetString(PyExc_Exception, (std::string("Unknown exception: ") +
  240. ex.what()).c_str());
  241. return (NULL);
  242. } catch (...) {
  243. PyErr_SetString(PyExc_Exception, "Unknown exception");
  244. return (NULL);
  245. }
  246. }
  247. } // end of unnamed namespace
  248. namespace isc {
  249. namespace dns {
  250. namespace python {
  251. //
  252. // Declaration of the custom exceptions
  253. // Initialization and addition of these go in the initModulePart
  254. // function in pydnspp
  255. //
  256. PyObject* po_InvalidRdataLength;
  257. PyObject* po_InvalidRdataText;
  258. PyObject* po_CharStringTooLong;
  259. // This defines the complete type for reflection in python and
  260. // parsing of PyObject* to s_Rdata
  261. // Most of the functions are not actually implemented and NULL here.
  262. PyTypeObject rdata_type = {
  263. PyVarObject_HEAD_INIT(NULL, 0)
  264. "pydnspp.Rdata",
  265. sizeof(s_Rdata), // tp_basicsize
  266. 0, // tp_itemsize
  267. Rdata_destroy, // tp_dealloc
  268. NULL, // tp_print
  269. NULL, // tp_getattr
  270. NULL, // tp_setattr
  271. NULL, // tp_reserved
  272. NULL, // tp_repr
  273. NULL, // tp_as_number
  274. NULL, // tp_as_sequence
  275. NULL, // tp_as_mapping
  276. NULL, // tp_hash
  277. NULL, // tp_call
  278. Rdata_str, // tp_str
  279. NULL, // tp_getattro
  280. NULL, // tp_setattro
  281. NULL, // tp_as_buffer
  282. Py_TPFLAGS_DEFAULT, // tp_flags
  283. "The Rdata class is an abstract base class that provides "
  284. "a set of common interfaces to manipulate concrete RDATA objects.",
  285. NULL, // tp_traverse
  286. NULL, // tp_clear
  287. RData_richcmp, // tp_richcompare
  288. 0, // tp_weaklistoffset
  289. NULL, // tp_iter
  290. NULL, // tp_iternext
  291. Rdata_methods, // tp_methods
  292. NULL, // tp_members
  293. NULL, // tp_getset
  294. NULL, // tp_base
  295. NULL, // tp_dict
  296. NULL, // tp_descr_get
  297. NULL, // tp_descr_set
  298. 0, // tp_dictoffset
  299. Rdata_init, // tp_init
  300. NULL, // tp_alloc
  301. PyType_GenericNew, // tp_new
  302. NULL, // tp_free
  303. NULL, // tp_is_gc
  304. NULL, // tp_bases
  305. NULL, // tp_mro
  306. NULL, // tp_cache
  307. NULL, // tp_subclasses
  308. NULL, // tp_weaklist
  309. NULL, // tp_del
  310. 0 // tp_version_tag
  311. };
  312. PyObject*
  313. createRdataObject(ConstRdataPtr source) {
  314. s_Rdata* py_rdata =
  315. static_cast<s_Rdata*>(rdata_type.tp_alloc(&rdata_type, 0));
  316. if (py_rdata == NULL) {
  317. isc_throw(PyCPPWrapperException, "Unexpected NULL C++ object, "
  318. "probably due to short memory");
  319. }
  320. py_rdata->cppobj = source;
  321. return (py_rdata);
  322. }
  323. bool
  324. PyRdata_Check(PyObject* obj) {
  325. if (obj == NULL) {
  326. isc_throw(PyCPPWrapperException, "obj argument NULL in typecheck");
  327. }
  328. return (PyObject_TypeCheck(obj, &rdata_type));
  329. }
  330. const Rdata&
  331. PyRdata_ToRdata(const PyObject* rdata_obj) {
  332. if (rdata_obj == NULL) {
  333. isc_throw(PyCPPWrapperException,
  334. "obj argument NULL in Rdata PyObject conversion");
  335. }
  336. const s_Rdata* rdata = static_cast<const s_Rdata*>(rdata_obj);
  337. return (*rdata->cppobj);
  338. }
  339. } // end python namespace
  340. } // end dns namespace
  341. } // end isc namespace