2 libloc - A library to determine the location of someone on the Internet
4 Copyright (C) 2024 IPFire Development Team <info@ipfire.org>
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
23 #include <libloc/database.h>
29 typedef struct database
{
30 struct loc_database
* db
;
33 static Database
* luaL_checkdatabase(lua_State
* L
, int i
) {
34 void* userdata
= luaL_checkudata(L
, i
, "location.Database");
36 // Throw an error if the argument doesn't match
37 luaL_argcheck(L
, userdata
, i
, "Database expected");
39 return (Database
*)userdata
;
42 static int Database_open(lua_State
* L
) {
43 const char* path
= NULL
;
48 path
= luaL_checkstring(L
, 1);
50 // Allocate a new object
51 Database
* self
= (Database
*)lua_newuserdata(L
, sizeof(*self
));
54 luaL_setmetatable(L
, "location.Database");
56 // Open the database file
59 return luaL_error(L
, "Could not open %s: %s\n", path
, strerror(errno
));
62 r
= loc_database_new(ctx
, &self
->db
, f
);
64 // Close the file descriptor
69 return luaL_error(L
, "Could not open database %s: %s\n", path
, strerror(errno
));
74 static int Database_gc(lua_State
* L
) {
75 Database
* self
= luaL_checkdatabase(L
, 1);
79 loc_database_unref(self
->db
);
86 static int Database_lookup(lua_State
* L
) {
87 struct loc_network
* network
= NULL
;
90 Database
* self
= luaL_checkdatabase(L
, 1);
93 const char* address
= luaL_checkstring(L
, 2);
96 r
= loc_database_lookup_from_string(self
->db
, address
, &network
);
98 return luaL_error(L
, "Could not lookup address %s: %s\n", address
, strerror(errno
));
100 // Create a network object
101 r
= create_network(L
, network
);
102 loc_network_unref(network
);
107 static const struct luaL_Reg database_functions
[] = {
108 { "open", Database_open
},
109 { "lookup", Database_lookup
},
110 { "__gc", Database_gc
},
114 int register_database(lua_State
* L
) {
115 return register_class(L
, "location.Database", database_functions
);