]> git.ipfire.org Git - people/ms/libloc.git/blob - src/perl/Location/Location.xs
496fc43e100282fd05f09d003eb922664be02d8a
[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 #
60 # Database functions
61 #
62 const char*
63 get_vendor(db)
64 struct loc_database* db;
65
66 CODE:
67 // Get vendor
68 RETVAL = loc_database_get_vendor(db);
69 OUTPUT:
70 RETVAL
71
72 const char*
73 get_description(db)
74 struct loc_database* db;
75
76 CODE:
77 // Get database description
78 RETVAL = loc_database_get_description(db);
79 OUTPUT:
80 RETVAL
81
82 #
83 # Lookup functions
84 #
85 char*
86 lookup_country_code(db, address)
87 struct loc_database* db;
88 char* address;
89
90 CODE:
91 // Lookup network
92 struct loc_network *network;
93 int err = loc_database_lookup_from_string(db, address, &network);
94 if (err) {
95 croak("Could not look up for %s\n", address);
96 }
97
98 // Extract the country code
99 const char* country_code = loc_network_get_country_code(network);
100 loc_network_unref(network);
101
102 if (country_code) {
103 RETVAL = strdup(country_code);
104 } else {
105 RETVAL = NULL;
106 }
107 OUTPUT:
108 RETVAL
109
110 void
111 DESTROY(db)
112 struct loc_database* db;
113
114 CODE:
115 // Close database
116 loc_database_unref(db);