]> git.ipfire.org Git - people/ms/libloc.git/blob - src/perl/Location/Location.xs
6fbf2234395ab465142e9f5660d916666db6e787
[people/ms/libloc.git] / src / perl / Location / Location.xs
1 #define PERL_NO_GET_CONTEXT
2 #include "EXTERN.h"
3 #include "perl.h"
4 #include "XSUB.h"
5
6 #include <stdio.h>
7 #include <string.h>
8
9
10 #include <loc/libloc.h>
11 #include <loc/database.h>
12 #include <loc/network.h>
13
14
15 MODULE = Location PACKAGE = Location
16
17 struct loc_database *
18 init(file)
19 char* file;
20
21 CODE:
22 struct loc_ctx* ctx = NULL;
23
24 // Initialise location context
25 int err = loc_new(&ctx);
26 if (err < 0)
27 croak("Could not initialize libloc context: %d\n", err);
28
29 // Open the database file for reading
30 FILE* f = fopen(file, "r");
31 if (!f) {
32 loc_unref(ctx);
33
34 croak("Could not open file for reading: %s: %s\n",
35 file, strerror(errno));
36 }
37
38 // Parse the database
39 struct loc_database* db = NULL;
40 err = loc_database_new(ctx, &db, f);
41
42 // We can close the database file straight away
43 // because loc_database_new creates a copy of the file descriptor
44 fclose(f);
45
46 if (err) {
47 loc_unref(ctx);
48
49 croak("Could not read database: %s\n", file);
50 }
51
52 // Cleanup
53 loc_unref(ctx);
54
55 RETVAL = db;
56 OUTPUT:
57 RETVAL
58
59 char*
60 lookup_country_code(db, address)
61 struct loc_database* db;
62 char* address;
63
64 CODE:
65 // Lookup network
66 struct loc_network *network;
67 int err = loc_database_lookup_from_string(db, address, &network);
68 if (err) {
69 croak("Could not look up for %s\n", address);
70 }
71
72 // Extract the country code
73 const char* country_code = loc_network_get_country_code(network);
74 loc_network_unref(network);
75
76 if (country_code) {
77 RETVAL = strdup(country_code);
78 } else {
79 RETVAL = NULL;
80 }
81 OUTPUT:
82 RETVAL
83
84
85
86 const char*
87 get_vendor(db)
88 struct loc_database* db;
89
90 CODE:
91 // Get vendor
92 RETVAL = loc_database_get_vendor(db);
93 OUTPUT:
94 RETVAL
95
96 void
97 DESTROY(db)
98 struct loc_database* db;
99
100 CODE:
101 // Close database
102 loc_database_unref(db);