From 31edab76bb3a2a76ae87596f73371befb228ce56 Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Mon, 8 Jan 2018 16:42:46 +0000 Subject: [PATCH] python: Make lookup function available Signed-off-by: Michael Tremer --- src/libloc.sym | 1 + src/python/database.c | 33 +++++++++++++++++++++++++++++++++ src/python/network.c | 9 +++++++++ src/python/network.h | 2 ++ 4 files changed, 45 insertions(+) diff --git a/src/libloc.sym b/src/libloc.sym index 628fca4..9a28e05 100644 --- a/src/libloc.sym +++ b/src/libloc.sym @@ -27,6 +27,7 @@ global: loc_network_get_country_code; loc_network_new; loc_network_new_from_string; + loc_network_ref; loc_network_set_asn; loc_network_set_country_code; loc_network_str; diff --git a/src/python/database.c b/src/python/database.c index 69399b3..931b54d 100644 --- a/src/python/database.c +++ b/src/python/database.c @@ -22,6 +22,7 @@ #include "locationmodule.h" #include "as.h" #include "database.h" +#include "network.h" static PyObject* Database_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { DatabaseObject* self = (DatabaseObject*)type->tp_alloc(type, 0); @@ -100,6 +101,32 @@ static PyObject* Database_get_as(DatabaseObject* self, PyObject* args) { Py_RETURN_NONE; } +static PyObject* Database_lookup(DatabaseObject* self, PyObject* args) { + struct loc_network* network = NULL; + const char* address = NULL; + + if (!PyArg_ParseTuple(args, "s", &address)) + return NULL; + + // Try to retrieve a matching network + int r = loc_database_lookup_from_string(self->db, address, &network); + + // We got a network + if (r == 0) { + PyObject* obj = new_network(&NetworkType, network); + loc_network_unref(network); + + return obj; + + // Nothing found + } else if (r == 1) { + Py_RETURN_NONE; + } + + // Unexpected error + return NULL; +} + static struct PyMethodDef Database_methods[] = { { "get_as", @@ -107,6 +134,12 @@ static struct PyMethodDef Database_methods[] = { METH_VARARGS, NULL, }, + { + "lookup", + (PyCFunction)Database_lookup, + METH_VARARGS, + NULL, + }, { NULL }, }; diff --git a/src/python/network.c b/src/python/network.c index ae7b298..f36b339 100644 --- a/src/python/network.c +++ b/src/python/network.c @@ -24,6 +24,15 @@ #include "locationmodule.h" #include "network.h" +PyObject* new_network(PyTypeObject* type, struct loc_network* network) { + NetworkObject* self = (NetworkObject*)type->tp_alloc(type, 0); + if (self) { + self->network = loc_network_ref(network); + } + + return (PyObject*)self; +} + static PyObject* Network_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { NetworkObject* self = (NetworkObject*)type->tp_alloc(type, 0); diff --git a/src/python/network.h b/src/python/network.h index 4a4b263..43665ba 100644 --- a/src/python/network.h +++ b/src/python/network.h @@ -28,4 +28,6 @@ typedef struct { extern PyTypeObject NetworkType; +PyObject* new_network(PyTypeObject* type, struct loc_network* network); + #endif /* PYTHON_LOCATION_NETWORK_H */ -- 2.39.2