rrset_python.cc 16.9 KB
Newer Older
1
// Copyright (C) 2010  Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

15 16 17 18
#include <Python.h>

#include <util/python/pycppwrapper_util.h>

19
#include <dns/rrset.h>
20 21
#include <dns/name.h>
#include <dns/messagerenderer.h>
22

23 24 25 26 27 28 29 30 31
#include "name_python.h"
#include "pydnspp_common.h"
#include "rrset_python.h"
#include "rrclass_python.h"
#include "rrtype_python.h"
#include "rrttl_python.h"
#include "rdata_python.h"
#include "messagerenderer_python.h"

32
using namespace std;
33
using namespace isc::dns;
34
using namespace isc::dns::python;
35
using namespace isc::util;
36
using namespace isc::util::python;
37

38
namespace {
39

40 41 42 43 44 45 46 47 48 49 50 51
// The s_* Class simply coverst one instantiation of the object

// Using a shared_ptr here should not really be necessary (PyObject
// is already reference-counted), however internally on the cpp side,
// not doing so might result in problems, since we can't copy construct
// rdata field, adding them to rrsets results in a problem when the
// rrset is destroyed later
class s_RRset : public PyObject {
public:
    isc::dns::RRsetPtr cppobj;
};

52 53 54
int RRset_init(s_RRset* self, PyObject* args);
void RRset_destroy(s_RRset* self);

55 56 57 58 59 60 61 62
PyObject* RRset_getRdataCount(PyObject* self, PyObject* args);
PyObject* RRset_getName(PyObject* self, PyObject* args);
PyObject* RRset_getClass(PyObject* self, PyObject* args);
PyObject* RRset_getType(PyObject* self, PyObject* args);
PyObject* RRset_getTTL(PyObject* self, PyObject* args);
PyObject* RRset_setName(PyObject* self, PyObject* args);
PyObject* RRset_setTTL(PyObject* self, PyObject* args);
PyObject* RRset_toText(PyObject* self, PyObject* args);
63
PyObject* RRset_str(PyObject* self);
64 65 66 67
PyObject* RRset_toWire(PyObject* self, PyObject* args);
PyObject* RRset_addRdata(PyObject* self, PyObject* args);
PyObject* RRset_getRdata(PyObject* po_self, PyObject* args);
PyObject* RRset_removeRRsig(PyObject* self, PyObject* args);
68

69
// TODO: iterator?
70

71
PyMethodDef RRset_methods[] = {
72
    { "get_rdata_count", RRset_getRdataCount, METH_NOARGS,
Jelte Jansen's avatar
Jelte Jansen committed
73
      "Returns the number of rdata fields." },
74
    { "get_name", RRset_getName, METH_NOARGS,
Jelte Jansen's avatar
Jelte Jansen committed
75
      "Returns the name of the RRset, as a Name object." },
76
    { "get_class", RRset_getClass, METH_NOARGS,
Jelte Jansen's avatar
Jelte Jansen committed
77
      "Returns the class of the RRset as an RRClass object." },
78
    { "get_type", RRset_getType, METH_NOARGS,
Jelte Jansen's avatar
Jelte Jansen committed
79
      "Returns the type of the RRset as an RRType object." },
80
    { "get_ttl", RRset_getTTL, METH_NOARGS,
Jelte Jansen's avatar
Jelte Jansen committed
81
      "Returns the TTL of the RRset as an RRTTL object." },
82
    { "set_name", RRset_setName, METH_VARARGS,
Jelte Jansen's avatar
Jelte Jansen committed
83
      "Sets the name of the RRset.\nTakes a Name object as an argument." },
84
    { "set_ttl", RRset_setTTL, METH_VARARGS,
Jelte Jansen's avatar
Jelte Jansen committed
85
      "Sets the TTL of the RRset.\nTakes an RRTTL object as an argument." },
86
    { "to_text", RRset_toText, METH_NOARGS,
Jelte Jansen's avatar
Jelte Jansen committed
87
      "Returns the text representation of the RRset as a string" },
88
    { "to_wire", RRset_toWire, METH_VARARGS,
Jelte Jansen's avatar
Jelte Jansen committed
89 90 91 92 93 94
      "Converts the RRset object to wire format.\n"
      "The argument can be either a MessageRenderer or an object that "
      "implements the sequence interface. If the object is mutable "
      "(for instance a bytearray()), the wire data is added in-place.\n"
      "If it is not (for instance a bytes() object), a new object is "
      "returned" },
95
    { "add_rdata", RRset_addRdata, METH_VARARGS,
Jelte Jansen's avatar
Jelte Jansen committed
96
      "Adds the rdata for one RR to the RRset.\nTakes an Rdata object as an argument" },
97
    { "get_rdata", RRset_getRdata, METH_NOARGS,
Jelte Jansen's avatar
Jelte Jansen committed
98
      "Returns a List containing all Rdata elements" },
99
    { "remove_rrsig", RRset_removeRRsig, METH_NOARGS,
100
      "Clears the list of RRsigs for this RRset" },
101 102 103
    { NULL, NULL, 0, NULL }
};

104
int
105
RRset_init(s_RRset* self, PyObject* args) {
106 107 108 109
    PyObject* name;
    PyObject* rrclass;
    PyObject* rrtype;
    PyObject* rrttl;
110 111 112 113 114 115

    if (PyArg_ParseTuple(args, "O!O!O!O!", &name_type, &name,
                                           &rrclass_type, &rrclass,
                                           &rrtype_type, &rrtype,
                                           &rrttl_type, &rrttl
       )) {
116 117 118 119
        self->cppobj = RRsetPtr(new RRset(PyName_ToName(name),
                                          PyRRClass_ToRRClass(rrclass),
                                          PyRRType_ToRRType(rrtype),
                                          PyRRTTL_ToRRTTL(rrttl)));
Jelte Jansen's avatar
Jelte Jansen committed
120
        return (0);
121 122
    }

123
    self->cppobj = RRsetPtr();
Jelte Jansen's avatar
Jelte Jansen committed
124
    return (-1);
125 126
}

127
void
128
RRset_destroy(s_RRset* self) {
Jelte Jansen's avatar
Jelte Jansen committed
129 130
    // Clear the shared_ptr so that its reference count is zero
    // before we call tp_free() (there is no direct release())
131
    self->cppobj.reset();
132 133 134
    Py_TYPE(self)->tp_free(self);
}

135
PyObject*
136 137 138
RRset_getRdataCount(PyObject* self, PyObject*) {
    return (Py_BuildValue("I", static_cast<const s_RRset*>(self)->cppobj->
                          getRdataCount()));
139 140
}

141
PyObject*
142
RRset_getName(PyObject* self, PyObject*) {
143
    try {
144 145
        return (createNameObject(static_cast<const s_RRset*>(self)->cppobj->
                                 getName()));
146 147 148 149 150 151 152 153 154 155
    } catch (const exception& ex) {
        const string ex_what =
            "Unexpected failure getting rrset Name: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
    } catch (...) {
        PyErr_SetString(PyExc_SystemError,
                        "Unexpected failure getting rrset Name");
    }
    return (NULL);
156 157
}

158
PyObject*
159
RRset_getClass(PyObject* self, PyObject*) {
160
    try {
161 162
        return (createRRClassObject(static_cast<const s_RRset*>(self)->cppobj->
                                    getClass()));
163 164 165 166 167 168 169 170 171 172
    } catch (const exception& ex) {
        const string ex_what =
            "Unexpected failure getting question RRClass: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
    } catch (...) {
        PyErr_SetString(PyExc_SystemError,
                        "Unexpected failure getting question RRClass");
    }
    return (NULL);
173 174
}

175
PyObject*
176
RRset_getType(PyObject* self, PyObject*) {
177
    try {
178 179
        return (createRRTypeObject(static_cast<const s_RRset*>(self)->cppobj->
                                   getType()));
180 181 182 183 184 185 186 187 188 189
    } catch (const exception& ex) {
        const string ex_what =
            "Unexpected failure getting question RRType: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
    } catch (...) {
        PyErr_SetString(PyExc_SystemError,
                        "Unexpected failure getting question RRType");
    }
    return (NULL);
190 191
}

192
PyObject*
193
RRset_getTTL(PyObject* self, PyObject*) {
194
    try {
195 196
        return (createRRTTLObject(static_cast<const s_RRset*>(self)->cppobj->
                                  getTTL()));
197 198 199 200 201 202 203 204 205 206
    } catch (const exception& ex) {
        const string ex_what =
            "Unexpected failure getting question TTL: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
    } catch (...) {
        PyErr_SetString(PyExc_SystemError,
                        "Unexpected failure getting question TTL");
    }
    return (NULL);
207 208
}

209
PyObject*
210
RRset_setName(PyObject* self, PyObject* args) {
211
    PyObject* name;
212
    if (!PyArg_ParseTuple(args, "O!", &name_type, &name)) {
Jelte Jansen's avatar
Jelte Jansen committed
213
        return (NULL);
214
    }
215
    static_cast<s_RRset*>(self)->cppobj->setName(PyName_ToName(name));
216 217 218
    Py_RETURN_NONE;
}

219
PyObject*
220
RRset_setTTL(PyObject* self, PyObject* args) {
221
    PyObject* rrttl;
222
    if (!PyArg_ParseTuple(args, "O!", &rrttl_type, &rrttl)) {
Jelte Jansen's avatar
Jelte Jansen committed
223
        return (NULL);
224
    }
225
    static_cast<s_RRset*>(self)->cppobj->setTTL(PyRRTTL_ToRRTTL(rrttl));
226 227 228
    Py_RETURN_NONE;
}

229
PyObject*
230
RRset_toText(PyObject* self, PyObject*) {
231
    try {
232 233
        return (Py_BuildValue("s", static_cast<const s_RRset*>(self)->cppobj->
                              toText().c_str()));
JINMEI Tatuya's avatar
JINMEI Tatuya committed
234
    } catch (const EmptyRRset& ers) {
235
        PyErr_SetString(po_EmptyRRset, ers.what());
Jelte Jansen's avatar
Jelte Jansen committed
236
        return (NULL);
237 238 239
    }
}

240
PyObject*
241
RRset_str(PyObject* self) {
242
    // Simply call the to_text method we already defined
JINMEI Tatuya's avatar
JINMEI Tatuya committed
243
    return (PyObject_CallMethod(self,
244
                                const_cast<char*>("to_text"),
JINMEI Tatuya's avatar
JINMEI Tatuya committed
245
                                const_cast<char*>("")));
246 247
}

248
PyObject*
249
RRset_toWire(PyObject* self_p, PyObject* args) {
250
    PyObject* bytes;
251
    PyObject* mr;
252
    const s_RRset* self(static_cast<const s_RRset*>(self_p));
253 254 255 256

    try {
        if (PyArg_ParseTuple(args, "O", &bytes) && PySequence_Check(bytes)) {
            PyObject* bytes_o = bytes;
257

258
            OutputBuffer buffer(4096);
259
            self->cppobj->toWire(buffer);
260
            PyObject* n = PyBytes_FromStringAndSize(static_cast<const char*>(buffer.getData()), buffer.getLength());
261 262 263 264
            PyObject* result = PySequence_InPlaceConcat(bytes_o, n);
            // We need to release the object we temporarily created here
            // to prevent memory leak
            Py_DECREF(n);
Jelte Jansen's avatar
Jelte Jansen committed
265
            return (result);
266
        } else if (PyArg_ParseTuple(args, "O!", &messagerenderer_type, &mr)) {
267
            self->cppobj->toWire(PyMessageRenderer_ToMessageRenderer(mr));
268 269 270 271
            // If we return NULL it is seen as an error, so use this for
            // None returns
            Py_RETURN_NONE;
        }
JINMEI Tatuya's avatar
JINMEI Tatuya committed
272
    } catch (const EmptyRRset& ers) {
273 274
        PyErr_Clear();
        PyErr_SetString(po_EmptyRRset, ers.what());
Jelte Jansen's avatar
Jelte Jansen committed
275
        return (NULL);
276 277 278 279
    }
    PyErr_Clear();
    PyErr_SetString(PyExc_TypeError,
                    "toWire argument must be a sequence object or a MessageRenderer");
Jelte Jansen's avatar
Jelte Jansen committed
280
    return (NULL);
281 282
}

283
PyObject*
284
RRset_addRdata(PyObject* self, PyObject* args) {
285
    PyObject* rdata;
286
    if (!PyArg_ParseTuple(args, "O!", &rdata_type, &rdata)) {
Jelte Jansen's avatar
Jelte Jansen committed
287
        return (NULL);
288 289
    }
    try {
290
        static_cast<s_RRset*>(self)->cppobj->addRdata(PyRdata_ToRdata(rdata));
291
        Py_RETURN_NONE;
JINMEI Tatuya's avatar
JINMEI Tatuya committed
292
    } catch (const std::bad_cast&) {
293 294 295
        PyErr_Clear();
        PyErr_SetString(PyExc_TypeError,
                        "Rdata type to add must match type of RRset");
Jelte Jansen's avatar
Jelte Jansen committed
296
        return (NULL);
297 298
    }
}
299

300
PyObject*
301 302
RRset_getRdata(PyObject* po_self, PyObject*) {
    const s_RRset* const self = static_cast<s_RRset*>(po_self);
303

304
    try {
305 306 307 308 309 310 311 312 313 314 315 316 317
        PyObjectContainer list_container(PyList_New(0));

        for (RdataIteratorPtr it = self->cppobj->getRdataIterator();
             !it->isLast(); it->next()) {
            if (PyList_Append(list_container.get(),
                              PyObjectContainer(
                                  createRdataObject(
                                      createRdata(self->cppobj->getType(),
                                                  self->cppobj->getClass(),
                                                  it->getCurrent()))).get())
                == -1) {
                isc_throw(PyCPPWrapperException, "PyList_Append failed, "
                          "probably due to short memory");
318 319
            }
        }
320
        return (list_container.release());
321 322 323 324 325 326 327 328
    } catch (const exception& ex) {
        const string ex_what =
            "Unexpected failure getting rrset Rdata: " +
            string(ex.what());
        PyErr_SetString(po_IscException, ex_what.c_str());
    } catch (...) {
        PyErr_SetString(PyExc_SystemError,
                        "Unexpected failure getting rrset Rdata");
329
    }
330
    return (NULL);
331 332
}

333
PyObject*
334 335
RRset_removeRRsig(PyObject* self, PyObject*) {
    static_cast<s_RRset*>(self)->cppobj->removeRRsig();
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417
    Py_RETURN_NONE;
}

} // end of unnamed namespace

namespace isc {
namespace dns {
namespace python {

//
// Declaration of the custom exceptions
// Initialization and addition of these go in the module init at the
// end
//
PyObject* po_EmptyRRset;

PyTypeObject rrset_type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "pydnspp.RRset",
    sizeof(s_RRset),                    // tp_basicsize
    0,                                  // tp_itemsize
    (destructor)RRset_destroy,          // tp_dealloc
    NULL,                               // tp_print
    NULL,                               // tp_getattr
    NULL,                               // tp_setattr
    NULL,                               // tp_reserved
    NULL,                               // tp_repr
    NULL,                               // tp_as_number
    NULL,                               // tp_as_sequence
    NULL,                               // tp_as_mapping
    NULL,                               // tp_hash
    NULL,                               // tp_call
    RRset_str,                          // tp_str
    NULL,                               // tp_getattro
    NULL,                               // tp_setattro
    NULL,                               // tp_as_buffer
    Py_TPFLAGS_DEFAULT,                 // tp_flags
    "The AbstractRRset class is an abstract base class that "
    "models a DNS RRset.\n\n"
    "An object of (a specific derived class of) AbstractRRset "
    "models an RRset as described in the DNS standard:\n"
    "A set of DNS resource records (RRs) of the same type and class. "
    "The standard requires the TTL of all RRs in an RRset be the same; "
    "this class follows that requirement.\n\n"
    "Note about duplicate RDATA: RFC2181 states that it's meaningless that an "
    "RRset contains two identical RRs and that name servers should suppress "
    "such duplicates.\n"
    "This class is not responsible for ensuring this requirement: For example, "
    "addRdata() method doesn't check if there's already RDATA identical "
    "to the one being added.\n"
    "This is because such checks can be expensive, and it's often easy to "
    "ensure the uniqueness requirement at the %data preparation phase "
    "(e.g. when loading a zone).",
    NULL,                               // tp_traverse
    NULL,                               // tp_clear
    NULL,                               // tp_richcompare
    0,                                  // tp_weaklistoffset
    NULL,                               // tp_iter
    NULL,                               // tp_iternext
    RRset_methods,                      // tp_methods
    NULL,                               // tp_members
    NULL,                               // tp_getset
    NULL,                               // tp_base
    NULL,                               // tp_dict
    NULL,                               // tp_descr_get
    NULL,                               // tp_descr_set
    0,                                  // tp_dictoffset
    (initproc)RRset_init,               // tp_init
    NULL,                               // tp_alloc
    PyType_GenericNew,                  // tp_new
    NULL,                               // tp_free
    NULL,                               // tp_is_gc
    NULL,                               // tp_bases
    NULL,                               // tp_mro
    NULL,                               // tp_cache
    NULL,                               // tp_subclasses
    NULL,                               // tp_weaklist
    NULL,                               // tp_del
    0                                   // tp_version_tag
};

PyObject*
418
createRRsetObject(const AbstractRRset& source) {
419 420 421

    // RRsets are noncopyable, so as a workaround we recreate a new one
    // and copy over all content
422 423 424
    RRsetPtr new_rrset = isc::dns::RRsetPtr(
        new isc::dns::RRset(source.getName(), source.getClass(),
                            source.getType(), source.getTTL()));
425

426 427 428 429
    isc::dns::RdataIteratorPtr rdata_it(source.getRdataIterator());
    for (rdata_it->first(); !rdata_it->isLast(); rdata_it->next()) {
        new_rrset->addRdata(rdata_it->getCurrent());
    }
430

431 432 433 434 435 436 437
    isc::dns::RRsetPtr sigs = source.getRRsig();
    if (sigs) {
        new_rrset->addRRsig(sigs);
    }
    s_RRset* py_rrset =
        static_cast<s_RRset*>(rrset_type.tp_alloc(&rrset_type, 0));
    if (py_rrset == NULL) {
438 439 440
        isc_throw(PyCPPWrapperException, "Unexpected NULL C++ object, "
                  "probably due to short memory");
    }
441 442
    py_rrset->cppobj = new_rrset;
    return (py_rrset);
443 444 445 446
}

bool
PyRRset_Check(PyObject* obj) {
447 448 449
    if (obj == NULL) {
        isc_throw(PyCPPWrapperException, "obj argument NULL in typecheck");
    }
450 451 452
    return (PyObject_TypeCheck(obj, &rrset_type));
}

453
AbstractRRset&
454 455
PyRRset_ToRRset(PyObject* rrset_obj) {
    s_RRset* rrset = static_cast<s_RRset*>(rrset_obj);
456
    return (*rrset->cppobj);
457 458
}

459 460
RRsetPtr
PyRRset_ToRRsetPtr(PyObject* rrset_obj) {
461 462 463 464
    if (rrset_obj == NULL) {
        isc_throw(PyCPPWrapperException,
                  "obj argument NULL in RRset PyObject conversion");
    }
465 466 467
    s_RRset* rrset = static_cast<s_RRset*>(rrset_obj);
    return (rrset->cppobj);
}
468 469 470 471 472


} // end python namespace
} // end dns namespace
} // end isc namespace