IP-Geolocation-MMDB-1.013000755001750001750 014765463065 15241 5ustar00andreasandreas000000000000LICENSE100644001750001750 4644014765463065 16357 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013This software is copyright (c) 2025 by Andreas Vögele. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2025 by Andreas Vögele. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Perl Artistic License 1.0 --- This software is Copyright (c) 2025 by Andreas Vögele. This is free software, licensed under: The Perl Artistic License 1.0 The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whoever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End typemap100644001750001750 3714765463065 16664 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013IP::Geolocation::MMDB T_PTROBJ MMDB.xs100644001750001750 3450014765463065 16437 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/* * Read MaxMind DB files * * Copyright (C) 2025 Andreas Vögele * * This module is free software; you can redistribute it and/or modify it * under the same terms as Perl itself. */ /* SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later */ #define PERL_NO_GET_CONTEXT #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include #ifdef MULTIPLICITY #define storeTHX(var) (var) = aTHX #define dTHXfield(var) tTHX var; #else #define storeTHX(var) dNOOP #define dTHXfield(var) #endif #define is_ipv6_database(mmdb) (6 == (mmdb)->metadata.ip_version) typedef struct ip_geolocation_mmdb { MMDB_s mmdb; SV *file; SV *selfrv; dTHXfield(perl) } *IP__Geolocation__MMDB; typedef struct { IP__Geolocation__MMDB self; SV *data_callback; SV *node_callback; int max_depth; } iterate_data; static void init_iterate_data(iterate_data *data, IP__Geolocation__MMDB self, SV *data_callback, SV *node_callback) { data->self = self; data->data_callback = data_callback; data->node_callback = node_callback; data->max_depth = is_ipv6_database(&self->mmdb) ? 128 : 32; } static SV * to_bigint(IP__Geolocation__MMDB self, const char *bytes, size_t size) { dTHXa(self->perl); dSP; int count; SV *err_tmp; SV *retval; ENTER; SAVETMPS; PUSHMARK(SP); EXTEND(SP, 2); mPUSHs(newRV_inc(self->selfrv)); mPUSHp(bytes, size); PUTBACK; count = call_method("_to_bigint", G_SCALAR | G_EVAL); SPAGAIN; err_tmp = ERRSV; if (SvTRUE(err_tmp)) { (void) POPs; retval = newSVpvn(bytes, size); } else { if (1 == count) { retval = newSVsv(POPs); } else { retval = newSVpvn(bytes, size); } } PUTBACK; FREETMPS; LEAVE; return retval; } typedef struct { char bytes[16]; } numeric_ip; static void init_numeric_ip(numeric_ip *ipnum) { Zero(ipnum, sizeof(*ipnum), char); } static void numeric_ip_set_bit(numeric_ip *ipnum, int bit) { int quot = bit / (8 * sizeof(char)); int rem = bit % (8 * sizeof(char)); ipnum->bytes[15 - quot] |= (128 >> (7 - rem)); } static SV * numeric_ip_to_bigint(IP__Geolocation__MMDB self, const numeric_ip *ipnum) { return to_bigint(self, ipnum->bytes, sizeof(ipnum->bytes)); } #if MMDB_UINT128_IS_BYTE_ARRAY static SV * createSVu128(IP__Geolocation__MMDB self, uint8_t u[16]) { char bytes[16]; size_t n; for (n = 0; n < 16; ++n) { bytes[n] = (char) u[n]; } return to_bigint(self, bytes, sizeof(bytes)); } #else static SV * createSVu128(IP__Geolocation__MMDB self, mmdb_uint128_t u) { #ifdef WORDS_BIGENDIAN return to_bigint(self, (const char *) &u, sizeof(u)); #else char bytes[sizeof(u)]; size_t n; for (n = 0; n < sizeof(u); ++n) { bytes[n] = ((const char *) &u)[sizeof(u) - n - 1]; } return to_bigint(self, bytes, sizeof(bytes)); #endif } #endif #if UVSIZE >= 8 #define createSVu64(self, u) newSVuv(u) #else static SV * createSVu64(IP__Geolocation__MMDB self, uint64_t u) { #ifdef WORDS_BIGENDIAN return to_bigint(self, (const char *) &u, sizeof(u)); #else char bytes[sizeof(u)]; size_t n; for (n = 0; n < sizeof(u); ++n) { bytes[n] = ((const char *) &u)[sizeof(u) - n - 1]; } return to_bigint(self, bytes, sizeof(bytes)); #endif } #endif static MMDB_entry_data_list_s * decode_entry_data_list(IP__Geolocation__MMDB self, MMDB_entry_data_list_s *list, SV **sv, int *mmdb_error) { dTHXa(self->perl); MMDB_entry_data_s *data = &list->entry_data; switch (data->type) { case MMDB_DATA_TYPE_MAP: { uint32_t size = data->data_size; HV *hv = newHV(); hv_ksplit(hv, size); for (list = list->next; size > 0 && NULL != list; size--) { if (MMDB_DATA_TYPE_UTF8_STRING != list->entry_data.type) { *mmdb_error = MMDB_INVALID_DATA_ERROR; return NULL; } const char *key = list->entry_data.utf8_string; uint32_t key_size = list->entry_data.data_size; list = list->next; if (NULL == list) { *mmdb_error = MMDB_INVALID_DATA_ERROR; return NULL; } SV *val = &PL_sv_undef; list = decode_entry_data_list(self, list, &val, mmdb_error); if (MMDB_SUCCESS != *mmdb_error) { return NULL; } (void) hv_store(hv, key, key_size, val, 0); } *sv = newRV_noinc((SV *) hv); } break; case MMDB_DATA_TYPE_ARRAY: { uint32_t size = data->data_size; AV *av = newAV(); av_extend(av, size); for (list = list->next; size > 0 && NULL != list; size--) { SV *val = &PL_sv_undef; list = decode_entry_data_list(self, list, &val, mmdb_error); if (MMDB_SUCCESS != *mmdb_error) { return NULL; } av_push(av, val); } *sv = newRV_noinc((SV *) av); } break; case MMDB_DATA_TYPE_UTF8_STRING: *sv = newSVpvn_utf8(data->utf8_string, data->data_size, 1); list = list->next; break; case MMDB_DATA_TYPE_BYTES: *sv = newSVpvn((const char *) data->bytes, data->data_size); list = list->next; break; case MMDB_DATA_TYPE_DOUBLE: *sv = newSVnv(data->double_value); list = list->next; break; case MMDB_DATA_TYPE_FLOAT: *sv = newSVnv(data->float_value); list = list->next; break; case MMDB_DATA_TYPE_UINT16: *sv = newSVuv(data->uint16); list = list->next; break; case MMDB_DATA_TYPE_UINT32: *sv = newSVuv(data->uint32); list = list->next; break; case MMDB_DATA_TYPE_BOOLEAN: *sv = newSViv(data->boolean); list = list->next; break; case MMDB_DATA_TYPE_UINT64: *sv = createSVu64(self, data->uint64); list = list->next; break; case MMDB_DATA_TYPE_UINT128: *sv = createSVu128(self, data->uint128); list = list->next; break; case MMDB_DATA_TYPE_INT32: *sv = newSViv(data->int32); list = list->next; break; default: *mmdb_error = MMDB_INVALID_DATA_ERROR; return NULL; } *mmdb_error = MMDB_SUCCESS; return list; } static void call_node_callback(iterate_data *data, uint32_t node_num, MMDB_search_node_s *node) { IP__Geolocation__MMDB self = data->self; dTHXa(self->perl); if (!SvOK(data->node_callback)) { return; } dSP; SV *left_record = createSVu64(self, node->left_record); SV *right_record = createSVu64(self, node->right_record); ENTER; SAVETMPS; PUSHMARK(SP); EXTEND(SP, 3); mPUSHu(node_num); mPUSHs(left_record); mPUSHs(right_record); PUTBACK; (void) call_sv(data->node_callback, G_VOID); FREETMPS; LEAVE; } static void call_data_callback(iterate_data *data, numeric_ip ipnum, int depth, MMDB_entry_s *record_entry) { IP__Geolocation__MMDB self = data->self; dTHXa(self->perl); if (!SvOK(data->data_callback)) { return; } SV *decoded_entry = &PL_sv_undef; MMDB_entry_data_list_s *list = NULL; int mmdb_error = MMDB_get_entry_data_list(record_entry, &list); if (MMDB_SUCCESS == mmdb_error) { (void) decode_entry_data_list(self, list, &decoded_entry, &mmdb_error); } MMDB_free_entry_data_list(list); if (MMDB_SUCCESS != mmdb_error) { const char *error = MMDB_strerror(mmdb_error); croak("Entry data error looking at offset %u: %s", (unsigned int) record_entry->offset, error); } SV *ip = numeric_ip_to_bigint(self, &ipnum); dSP; ENTER; SAVETMPS; PUSHMARK(SP); EXTEND(SP, 3); mPUSHs(ip); mPUSHi(depth); mPUSHs(decoded_entry); PUTBACK; (void) call_sv(data->data_callback, G_VOID); FREETMPS; LEAVE; } static void iterate_search_nodes(iterate_data *, uint32_t, numeric_ip, int); static void iterate_record_entry(iterate_data *data, numeric_ip ipnum, int depth, uint64_t record, uint8_t record_type, MMDB_entry_s *record_entry) { switch (record_type) { case MMDB_RECORD_TYPE_INVALID: croak("%s", "Invalid record when reading node"); break; case MMDB_RECORD_TYPE_SEARCH_NODE: iterate_search_nodes(data, (uint32_t) record, ipnum, depth + 1); break; case MMDB_RECORD_TYPE_EMPTY: /* Empty branches are ignored. */ break; case MMDB_RECORD_TYPE_DATA: call_data_callback(data, ipnum, depth, record_entry); break; default: croak("Unknown record type: %u", (unsigned int) record_type); break; } } static void iterate_search_nodes(iterate_data *data, uint32_t node_num, numeric_ip ipnum, int depth) { MMDB_search_node_s node; int mmdb_error = MMDB_read_node(&data->self->mmdb, node_num, &node); if (MMDB_SUCCESS != mmdb_error) { const char *error = MMDB_strerror(mmdb_error); croak("Error reading node %u: %s", (unsigned int) node_num, error); } if (depth > data->max_depth) { croak("Invalid depth when reading node %u: %d", (unsigned int) node_num, depth); } call_node_callback(data, node_num, &node); iterate_record_entry(data, ipnum, depth, node.left_record, node.left_record_type, &node.left_record_entry); numeric_ip_set_bit(&ipnum, data->max_depth - depth); iterate_record_entry(data, ipnum, depth, node.right_record, node.right_record_type, &node.right_record_entry); } MODULE = IP::Geolocation::MMDB PACKAGE = IP::Geolocation::MMDB PROTOTYPES: DISABLE SV * new(klass, ...) SV *klass INIT: IP__Geolocation__MMDB self; SV *file = NULL; U32 flags = 0; I32 i; const char *key; SV *value; const char *filename; int mmdb_error; const char *error; CODE: if ((items - 1) % 2 != 0) { warn("Odd-length list passed to %" SVf " constructor", SVfARG(klass)); } for (i = 1; i < items; i += 2) { key = SvPV_nolen_const(ST(i)); value = ST(i + 1); if (strEQ(key, "file")) { file = value; } } if (NULL == file) { croak("The \"file\" parameter is mandatory"); } filename = SvPVbyte_nolen(file); Newxz(self, 1, struct ip_geolocation_mmdb); storeTHX(self->perl); self->file = SvREFCNT_inc(file); mmdb_error = MMDB_open(filename, flags, &self->mmdb); if (MMDB_SUCCESS != mmdb_error) { Safefree(self); error = MMDB_strerror(mmdb_error); croak("Error opening database file \"%" SVf "\": %s", SVfARG(file), error); } RETVAL = sv_bless(newRV_noinc(newSViv(PTR2IV(self))), gv_stashsv(klass, GV_ADD)); self->selfrv = SvRV(RETVAL); /* no inc */ OUTPUT: RETVAL void DESTROY(self) IP::Geolocation::MMDB self CODE: MMDB_close(&self->mmdb); SvREFCNT_dec(self->file); Safefree(self); void get(self, ...) IP::Geolocation::MMDB self ALIAS: record_for_address = 1 INIT: const char *ip_address; int gai_error, mmdb_error; const char *error; MMDB_lookup_result_s result; MMDB_entry_data_list_s *list; SV *data = &PL_sv_undef; int wants_prefix_length = 0; uint16_t prefix_length = 0; U8 gimme = GIMME_V; PPCODE: ip_address = NULL; if (items > 1) { ip_address = SvPVbyte_nolen(ST(1)); } if (NULL == ip_address || '\0' == *ip_address) { croak("%s", "You must provide an IP address to look up"); } result = MMDB_lookup_string(&self->mmdb, ip_address, &gai_error, &mmdb_error); if (0 != gai_error) { croak("The IP address you provided (%s) is not a valid IPv4 or IPv6 " "address", ip_address); } if (MMDB_SUCCESS != mmdb_error) { error = MMDB_strerror(mmdb_error); croak("Error looking up IP address \"%s\": %s", ip_address, error); } if (result.found_entry) { list = NULL; mmdb_error = MMDB_get_entry_data_list(&result.entry, &list); if (MMDB_SUCCESS == mmdb_error) { (void) decode_entry_data_list(self, list, &data, &mmdb_error); } MMDB_free_entry_data_list(list); if (MMDB_SUCCESS != mmdb_error) { error = MMDB_strerror(mmdb_error); croak("Entry data error looking up \"%s\": %s", ip_address, error); } if (0 == ix && G_SCALAR != gimme) { wants_prefix_length = 1; if (instr(ip_address, ".") && is_ipv6_database(&self->mmdb)) { prefix_length = result.netmask - 96; } else { prefix_length = result.netmask; } } } XPUSHs(sv_2mortal(data)); if (wants_prefix_length) { XPUSHs(sv_2mortal(newSVuv(prefix_length))); } void iterate_search_tree(self, ...) IP::Geolocation::MMDB self INIT: SV *data_callback; SV *node_callback; iterate_data data; numeric_ip ipnum; CODE: data_callback = &PL_sv_undef; node_callback = &PL_sv_undef; if (items > 1) { data_callback = ST(1); if (items > 2) { node_callback = ST(2); } } init_iterate_data(&data, self, data_callback, node_callback); init_numeric_ip(&ipnum); iterate_search_nodes(&data, 0, ipnum, 1); SV * _metadata(self) IP::Geolocation::MMDB self INIT: int mmdb_error; const char *error; MMDB_entry_data_list_s *list; CODE: RETVAL = &PL_sv_undef; list = NULL; mmdb_error = MMDB_get_metadata_as_entry_data_list(&self->mmdb, &list); if (MMDB_SUCCESS == mmdb_error) { (void) decode_entry_data_list(self, list, &RETVAL, &mmdb_error); } MMDB_free_entry_data_list(list); if (MMDB_SUCCESS != mmdb_error) { error = MMDB_strerror(mmdb_error); croak("Error getting metadata: %s", error); } OUTPUT: RETVAL SV * file(self) IP::Geolocation::MMDB self CODE: RETVAL = SvREFCNT_inc(self->file); OUTPUT: RETVAL const char * libmaxminddb_version() CODE: RETVAL = MMDB_lib_version(); OUTPUT: RETVAL Changes100644001750001750 434714765463065 16625 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013Revision history for IP::Geolocation::MMDB 1.013 2025-03-13 08:23:04 CET - Amend the library search path on old versions of Strawberry Perl - Support Perl 5.14 1.012 2025-02-20 09:00:30 CET - Use pkg-config if Alien::libmaxminddb is unavailable 1.011 2025-01-22 09:09:04 CET - Add a get method that returns the prefix length 1.010 2022-12-24 07:15:32 CET - Implement the file method - Move the constructor to the XS source 1.009 2022-08-05 14:32:53 CEST - Move the primary Git repository to GitHub 1.008 2022-06-07 16:58:48 CEST - Ensure that the module is subclassable. Fixed by Yujuan Jiang. 1.007 2022-04-01 21:00:13 CEST - Replace div() with arithmetic operators as GCC 11.2.0 may produce wrong values 1.006 2022-03-23 03:29:15 CET - Add Math::BigInt 1.999806 to the configuration requirements - Revert to checking the libmaxminddb version with a regular expression 1.005 2022-03-16 17:32:21 CET - Check if Math::BigInt actually works - Improve some error messages in the build and test scripts 1.004 2022-03-07 17:32:21 CET - Reintroduce the Windows support 1.003 2022-01-25 15:13:30 CET - Windows is no longer supported 1.002 2022-01-24 04:51:57 CET - Skip the tests if libmaxminddb is too old 1.001 2022-01-23 07:25:04 CET - Require libmaxminddb 1.2.0 or newer 1.000 2022-01-22 09:06:57 CET - Depend on Math::BigInt 1.999806 and use as_hex() instead of to_hex() - Add a safety check 0.009 2022-01-11 08:08:25 CET - Depend on Math::BigInt 1.999811 0.008 2022-01-10 15:07:38 CET - Implement iterate_search_tree - Fix the code for MMDB_UINT128_IS_BYTE_ARRAY 0.007 2022-01-03 13:19:29 CET - Implement IP::Geolocation::MMDB::Metadata 0.006 2022-01-02 04:14:40 CET - Remove loop initial declarations from MMDB.xs - _to_bigint is now a virtual method - Improved tests 0.005 2021-12-31 21:16:14 CET - Handle MMDB_UINT128_IS_BYTE_ARRAY 0.004 2021-12-31 17:00:26 CET - Store 64- and 128-bit integers in Math::BigInt objects 0.003 2021-12-30 10:04:58 CET - Don't call gai_strerror(), which may return UTF-16 on Windows - Add more tests 0.002 2021-12-29 01:16:55 CET - Skip the IPv6 tests on Windows 0.001 2021-12-27 08:03:18 CET - First version META.yml100644001750001750 225414765463066 16577 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013--- abstract: 'Read MaxMind DB files' author: - 'Andreas Vögele ' build_requires: Alien::libmaxminddb: '0' File::Spec::Functions: '0' Math::BigInt: '1.999806' Test::More: '0' configure_requires: Alien::libmaxminddb: '0' ExtUtils::MakeMaker: '0' Math::BigInt: '1.999806' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.032, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: IP-Geolocation-MMDB provides: IP::Geolocation::MMDB: file: lib/IP/Geolocation/MMDB.pm version: '1.013' IP::Geolocation::MMDB::Metadata: file: lib/IP/Geolocation/MMDB/Metadata.pm version: '1.013' requires: Math::BigInt: '1.999806' XSLoader: '0' perl: '5.014' utf8: '0' warnings: '0' resources: bugtracker: https://github.com/voegelas/IP-Geolocation-MMDB/issues homepage: https://github.com/voegelas/IP-Geolocation-MMDB/wiki repository: https://github.com/voegelas/IP-Geolocation-MMDB.git version: '1.013' x_generated_by_perl: v5.40.1 x_serialization_backend: 'YAML::Tiny version 1.74' x_spdx_expression: 'Artistic-1.0-Perl OR GPL-1.0-or-later' MANIFEST100644001750001750 56414765463066 16441 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.032. CONTRIBUTING.md Changes LICENSE MANIFEST MANIFEST.SKIP META.json META.yml MMDB.xs Makefile.PL README.md cpanfile dist.ini lib/IP/Geolocation/MMDB.pm lib/IP/Geolocation/MMDB/Metadata.pm t/author-pod-coverage.t t/author-pod-syntax.t t/data/Test-City.mmdb t/mmdb.t t/release-kwalitee.t typemap cpanfile100644001750001750 213214765463066 17025 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013# This file is generated by Dist::Zilla::Plugin::CPANFile v6.032 # Do not edit this file directly. To change prereqs, edit the `dist.ini` file. requires "Math::BigInt" => "1.999806"; requires "XSLoader" => "0"; requires "perl" => "5.014"; requires "utf8" => "0"; requires "warnings" => "0"; on 'build' => sub { requires "Alien::libmaxminddb" => "0"; requires "Math::BigInt" => "1.999806"; }; on 'test' => sub { requires "File::Spec::Functions" => "0"; requires "Test::More" => "0"; }; on 'configure' => sub { requires "Alien::libmaxminddb" => "0"; requires "ExtUtils::MakeMaker" => "0"; requires "Math::BigInt" => "1.999806"; }; on 'develop' => sub { requires "Dist::Zilla" => "0"; requires "Dist::Zilla::Plugin::CopyFilesFromBuild" => "0"; requires "Dist::Zilla::Plugin::MakeMaker::Awesome" => "0.27"; requires "Dist::Zilla::Plugin::MetaProvides::Package" => "0"; requires "Dist::Zilla::Plugin::Test::Kwalitee" => "0"; requires "Pod::Coverage::TrustPod" => "0"; requires "Test::Kwalitee" => "1.21"; requires "Test::Pod" => "1.41"; requires "Test::Pod::Coverage" => "1.08"; }; dist.ini100644001750001750 1247014765463066 17013 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013name = IP-Geolocation-MMDB version = 1.013 author = Andreas Vögele license = Perl_5 copyright_holder = Andreas Vögele [@Filter] -bundle = @Basic -remove = GatherDir -remove = MakeMaker -remove = Readme [MetaResources] homepage = https://github.com/voegelas/IP-Geolocation-MMDB/wiki bugtracker.web = https://github.com/voegelas/IP-Geolocation-MMDB/issues repository.url = https://github.com/voegelas/IP-Geolocation-MMDB.git repository.web = https://github.com/voegelas/IP-Geolocation-MMDB repository.type = git [CPANFile] [GatherDir] exclude_filename = cpanfile exclude_filename = LICENSE exclude_filename = Makefile.PL exclude_filename = META.json [CopyFilesFromBuild] copy = cpanfile copy = LICENSE copy = Makefile.PL copy = META.json [MetaProvides::Package] [MetaJSON] [PodCoverageTests] [PodSyntaxTests] [MakeMaker::Awesome] min_perl_version = 5.014 delimiter = | header = use Config; header = use File::Spec::Functions qw(devnull); header = use Math::BigInt; header = my @defines; header = my $byteorder = $Config{byteorder}; header = if (!defined $byteorder) { header = | warn "\$Config{byteorder} is undefined"; header = | die "OS unsupported\n"; header = } header = if ($byteorder == 4321 || $byteorder == 87654321) { header = | push @defines, '-DWORDS_BIGENDIAN'; header = } header = elsif (!($byteorder == 1234 || $byteorder == 12345678)) { header = | warn "Unknown byte order: $byteorder\n"; header = | die "OS unsupported\n"; header = } header = my $ccflags = ''; header = my $libs = ''; header = my $version; header = if (eval { require Alien::libmaxminddb }) { header = | $ccflags = Alien::libmaxminddb->cflags; header = | $libs = Alien::libmaxminddb->libs; header = | $version = Alien::libmaxminddb->version; header = } header = else { header = | my $devnull = devnull(); header = | for my $pkgconf (qw(pkgconf pkg-config)) { header = | my $output = `$pkgconf --version 2>$devnull`; header = | if ($? == 0) { header = | $ccflags = `$pkgconf --cflags libmaxminddb 2>$devnull`; header = | last if $? != 0; header = | $libs = `$pkgconf --libs libmaxminddb 2>$devnull`; header = | last if $? != 0; header = | $version = `$pkgconf --modversion libmaxminddb 2>$devnull`; header = | last if $? != 0; header = | chomp($ccflags, $libs, $version); header = | last; header = | } header = | } header = } header = if ($^O eq 'MSWin32' && $^V < 5.034) { header = | # Amend the library search path header = | my $libdir = 'C:\strawberry\c\x86_64-w64-mingw32\lib'; header = | if (-d $libdir) { header = | $libs = "-L$libdir $libs"; header = | } header = } WriteMakefile_arg = CCFLAGS => join(q{ }, $ccflags, $Config{ccflags}) WriteMakefile_arg = LIBS => [ $libs ] WriteMakefile_arg = DEFINE => join(q{ }, @defines) footer = package MY; footer = # Bail out if something is wrong footer = sub post_initialize { footer = | my $text = ''; footer = | if (!defined $version) { footer = | $text = <<'TEXT'; footer = |.PHONY: die footer = |die : footer = | $(NOECHO) $(ECHO) "Error: libmaxminddb not found" footer = | $(NOECHO) $(ECHO) "OS unsupported" footer = | $(FALSE) footer = |TEXT footer = | } footer = | elsif ($version =~ m{^(0|1\.[01])\.}) { footer = | $text = <<'TEXT'; footer = |.PHONY: die footer = |die : footer = | $(NOECHO) $(ECHO) "Error: libmaxminddb is too old" footer = | $(NOECHO) $(ECHO) "OS unsupported" footer = | $(FALSE) footer = |TEXT footer = | } footer = | elsif (!eval { Math::BigInt->from_bytes(pack 'C6', 0xff, 0xff, 0xb0, 0x09, 0x00, 0x00)->as_hex eq '0xffffb0090000' }) { footer = | # Some Math::BigInt versions fail on i386 if Perl is built with -Dusequadmath. footer = | $text = <<'TEXT'; footer = |.PHONY: die footer = |die : footer = | $(NOECHO) $(ECHO) "Error: Math::BigInt is too old or broken" footer = | $(NOECHO) $(ECHO) "OS unsupported" footer = | $(FALSE) footer = |TEXT footer = | } footer = | return $text; footer = } footer = sub const_loadlibs { footer = | my $text = shift->SUPER::const_loadlibs(@_); footer = | if ($^O eq 'MSWin32' && $^V < 5.034) { footer = | # Ignore unneeded libraries, which may contain invalid symbols footer = | my $filter = sub { footer = | my $list = shift; footer = | my $pattern = $list =~ m{"} ? qr{(?<=")\h+(?=")} : qr{\h+}; footer = | join q{ }, grep { m{ maxminddb | ws2_32 }x } split $pattern, $list; footer = | }; footer = | $text =~ s{ footer = | ^ ( (?: EXTRA | LDLOAD ) LIBS ) \h* = \h* (.*?) \h* $ footer = | } footer = | {sprintf '%s = %s', $1, $filter->($2)}egxm; footer = | } footer = | return $text; footer = } footer = sub const_config { footer = | my $text = shift->SUPER::const_config(@_); footer = | # Some BSDs prepend -L/usr/local/lib, which may contain an old library footer = | # version, to the library search path footer = | $text =~ s{ footer = | ^ ( LD(?:DL)?FLAGS \h* = .*? ) -L/usr/local/lib ( $ | \h+ (.*) $ ) footer = | } footer = | {$1$2}gxm; footer = | return $text; footer = } [Test::Kwalitee] [Encoding] encoding = bytes match = ^t/data/ [AutoPrereqs] [Prereqs / ConfigureRequires] Alien::libmaxminddb = 0 Math::BigInt = 1.999806 [Prereqs / BuildRequires] Alien::libmaxminddb = 0 Math::BigInt = 1.999806 [Prereqs / DevelopRequires] Dist::Zilla = 0 Dist::Zilla::Plugin::CopyFilesFromBuild = 0 Dist::Zilla::Plugin::MakeMaker::Awesome = 0.27 Dist::Zilla::Plugin::MetaProvides::Package = 0 Dist::Zilla::Plugin::Test::Kwalitee = 0 t000755001750001750 014765463066 15426 5ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013mmdb.t100644001750001750 1056714765463066 16723 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/t#!perl # SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later use 5.014; use warnings; use utf8; use Test::More; use File::Spec::Functions qw(catfile); use IP::Geolocation::MMDB; use Math::BigInt 1.999806; my $version = IP::Geolocation::MMDB::libmaxminddb_version; # Check if the module was linked against the wrong library version. if ($version =~ m{^(0|1\.[01])\.}) { plan skip_all => "libmaxminddb $version is too old"; } diag 'libmaxminddb version is ' . $version; ok !eval { IP::Geolocation::MMDB->new }, 'constructor without "file" parameter dies'; ok !eval { IP::Geolocation::MMDB->new(file => 'nonexistent') }, 'constructor with non-existing file dies'; my $file = catfile(qw(t data Test-City.mmdb)); # Ensure that the module is subclassable by using an empty subclass. @MaxMind::DB::Reader::ISA = qw(IP::Geolocation::MMDB); my $reader = new_ok 'MaxMind::DB::Reader' => [file => $file]; can_ok $reader, qw(get getcc record_for_address iterate_search_tree metadata file); is $reader->file, $file, 'file matches'; ok !eval { $reader->get('-1') }, 'invalid ip address throws exception'; ok !$reader->record_for_address('127.0.0.1'), 'no data for localhost'; my $uint64 = Math::BigInt->new('4702394921427289928'); my $uint128 = Math::BigInt->new('86743875649080753100636639643044826960'); my $r = $reader->get('176.9.54.163'); isa_ok $r, 'HASH'; is $reader->getcc('176.9.54.163'), 'DE', 'IPv4 address is in Germany'; my ($s, $prefix_length) = $reader->get('176.9.54.163'); is_deeply $r, $s, 'data matches'; cmp_ok $prefix_length, '==', 16, 'IPv4 prefix length is 16'; SKIP: { skip 'IPv6 tests on Windows', 3 if $^O eq 'MSWin32'; isa_ok $reader->record_for_address('2a01:4f8:150:74ab::2'), 'HASH'; is $reader->getcc('2a01:4f8:150:74ab::2'), 'DE', 'IPv6 address is in Germany'; my (undef, $prefix_length) = $reader->get('2a01:4f8:150:74ab::2'); cmp_ok $prefix_length, '==', 32, 'IPv6 prefix length is 32'; } is_deeply $r->{x_array}, [-1, 0, 1], 'array matches'; is_deeply $r->{x_map}, {red => 160, green => 32, blue => 240}, 'map matches'; ok $r->{x_boolean}, 'boolean is true'; is $r->{x_bytes}, pack('W*', ord 'A' .. ord 'Z'), 'bytes match'; cmp_ok $r->{x_double}, '>', 0.0, 'double is greater than zero'; cmp_ok $r->{x_float}, '<', 0.0, 'float is less than zero'; is $r->{x_int32}, -12500413, 'int32 matches'; is $r->{x_uint16}, 16706, 'uint16 matches'; is $r->{x_uint32}, 1094861636, 'uint32 matches'; is $r->{x_uint64}, $uint64, 'uint64 matches'; is $r->{x_uint128}, $uint128, 'uint128 matches'; is $r->{x_utf8_string}, 'Фалькенштайн', 'utf8_string matches'; my $m = $reader->metadata; can_ok $m, qw( binary_format_major_version binary_format_minor_version build_epoch database_type languages description ip_version node_count record_size ); cmp_ok $m->binary_format_major_version, '>=', 0, 'major version is set'; cmp_ok $m->binary_format_minor_version, '>=', 0, 'minor version is set'; cmp_ok $m->build_epoch, '>=', 0, 'build_epoch is set'; isnt $m->database_type, q{}, 'database type is not empty'; isa_ok $m->languages, 'ARRAY'; isa_ok $m->description, 'HASH'; cmp_ok $m->ip_version, '>=', 0, 'ip_version is set'; cmp_ok $m->node_count, '>=', 0, 'node_count is set'; cmp_ok $m->record_size, '>=', 0, 'record_size is set'; my %data_for; sub data_callback { my ($numeric_ip, $prefix_length, $data) = @_; my $address = $numeric_ip->as_hex . '/' . $prefix_length; $data_for{$address} = $data; return; } my %children_for; sub node_callback { my ($node_number, $left_node_number, $right_node_number) = @_; $children_for{$node_number} = [$left_node_number, $right_node_number]; return; } $reader->iterate_search_tree(\&data_callback, \&node_callback); cmp_ok scalar keys %data_for, '>', 0, 'data_callback was called'; cmp_ok scalar keys %children_for, '>', 0, 'node_callback was called'; ok exists $children_for{0}, 'node 0 exists'; isnt $children_for{0}->[0], $children_for{0}->[1], 'children differ'; my $ipv4_data = $data_for{'0xffffb0090000/112'}; my $ipv6_data = $data_for{'0x2a0104f8000000000000000000000000/32'}; ok defined $ipv4_data, 'IPv4 data exists'; ok defined $ipv6_data, 'IPv6 data exists'; ok exists $ipv4_data->{city}, 'city key exists'; ok exists $ipv6_data->{country}, 'country key exists'; done_testing; README.md100644001750001750 243714765463066 16610 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013# IP::Geolocation::MMDB A Perl module that reads MaxMind DB files and maps IP addresses to location information such as country and city names. use IP::Geolocation::MMDB; my $db = IP::Geolocation::MMDB->new(file => '/path/to/Country.mmdb'); my $metadata = $db->metadata; my $data = $db->get('1.2.3.4'); my $country_code = $db->getcc('2620:fe::9'); ## DEPENDENCIES Requires Math::BigInt version 1.999806, which is distributed with Perl 5.26 and newer. Requires libmaxminddb 1.2.0 or newer. Requires a database in the MaxMind DB file format from [MaxMind](https://www.maxmind.com/) or [DP-IP.com](https://db-ip.com/). Alien::libmaxminddb from CPAN is a build dependency. The built module does only depend on modules that are distributed with Perl. Install pkg-config and libmaxminddb-devel or libmaxminddb-dev if you would like to use your operating system's libmaxminddb library. ## INSTALLATION Run the following commands to install the software: perl Makefile.PL make make test make install Type the following command to see the module usage information: perldoc IP::Geolocation::MMDB ## LICENSE AND COPYRIGHT Copyright (C) 2025 Andreas Vögele This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. META.json100644001750001750 474314765463066 16754 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013{ "abstract" : "Read MaxMind DB files", "author" : [ "Andreas V\u00f6gele " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 6.032, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "IP-Geolocation-MMDB", "prereqs" : { "build" : { "requires" : { "Alien::libmaxminddb" : "0", "Math::BigInt" : "1.999806" } }, "configure" : { "requires" : { "Alien::libmaxminddb" : "0", "ExtUtils::MakeMaker" : "0", "Math::BigInt" : "1.999806" } }, "develop" : { "requires" : { "Dist::Zilla" : "0", "Dist::Zilla::Plugin::CopyFilesFromBuild" : "0", "Dist::Zilla::Plugin::MakeMaker::Awesome" : "0.27", "Dist::Zilla::Plugin::MetaProvides::Package" : "0", "Dist::Zilla::Plugin::Test::Kwalitee" : "0", "Pod::Coverage::TrustPod" : "0", "Test::Kwalitee" : "1.21", "Test::Pod" : "1.41", "Test::Pod::Coverage" : "1.08" } }, "runtime" : { "requires" : { "Math::BigInt" : "1.999806", "XSLoader" : "0", "perl" : "5.014", "utf8" : "0", "warnings" : "0" } }, "test" : { "requires" : { "File::Spec::Functions" : "0", "Test::More" : "0" } } }, "provides" : { "IP::Geolocation::MMDB" : { "file" : "lib/IP/Geolocation/MMDB.pm", "version" : "1.013" }, "IP::Geolocation::MMDB::Metadata" : { "file" : "lib/IP/Geolocation/MMDB/Metadata.pm", "version" : "1.013" } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/voegelas/IP-Geolocation-MMDB/issues" }, "homepage" : "https://github.com/voegelas/IP-Geolocation-MMDB/wiki", "repository" : { "type" : "git", "url" : "https://github.com/voegelas/IP-Geolocation-MMDB.git", "web" : "https://github.com/voegelas/IP-Geolocation-MMDB" } }, "version" : "1.013", "x_generated_by_perl" : "v5.40.1", "x_serialization_backend" : "Cpanel::JSON::XS version 4.39", "x_spdx_expression" : "Artistic-1.0-Perl OR GPL-1.0-or-later" } Makefile.PL100644001750001750 1070014765463066 17313 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013# This Makefile.PL for IP-Geolocation-MMDB was generated by # Dist::Zilla::Plugin::MakeMaker::Awesome 0.49. # Don't edit it but the dist.ini and plugins used to construct it. use strict; use warnings; use 5.014; use ExtUtils::MakeMaker; use Config; use File::Spec::Functions qw(devnull); use Math::BigInt; my @defines; my $byteorder = $Config{byteorder}; if (!defined $byteorder) { warn "\$Config{byteorder} is undefined"; die "OS unsupported\n"; } if ($byteorder == 4321 || $byteorder == 87654321) { push @defines, '-DWORDS_BIGENDIAN'; } elsif (!($byteorder == 1234 || $byteorder == 12345678)) { warn "Unknown byte order: $byteorder\n"; die "OS unsupported\n"; } my $ccflags = ''; my $libs = ''; my $version; if (eval { require Alien::libmaxminddb }) { $ccflags = Alien::libmaxminddb->cflags; $libs = Alien::libmaxminddb->libs; $version = Alien::libmaxminddb->version; } else { my $devnull = devnull(); for my $pkgconf (qw(pkgconf pkg-config)) { my $output = `$pkgconf --version 2>$devnull`; if ($? == 0) { $ccflags = `$pkgconf --cflags libmaxminddb 2>$devnull`; last if $? != 0; $libs = `$pkgconf --libs libmaxminddb 2>$devnull`; last if $? != 0; $version = `$pkgconf --modversion libmaxminddb 2>$devnull`; last if $? != 0; chomp($ccflags, $libs, $version); last; } } } if ($^O eq 'MSWin32' && $^V < 5.034) { # Amend the library search path my $libdir = 'C:\strawberry\c\x86_64-w64-mingw32\lib'; if (-d $libdir) { $libs = "-L$libdir $libs"; } } my %WriteMakefileArgs = ( "ABSTRACT" => "Read MaxMind DB files", "AUTHOR" => "Andreas V\x{f6}gele ", "BUILD_REQUIRES" => { "Alien::libmaxminddb" => 0, "Math::BigInt" => "1.999806" }, "CONFIGURE_REQUIRES" => { "Alien::libmaxminddb" => 0, "ExtUtils::MakeMaker" => 0, "Math::BigInt" => "1.999806" }, "DISTNAME" => "IP-Geolocation-MMDB", "LICENSE" => "perl", "MIN_PERL_VERSION" => "5.014", "NAME" => "IP::Geolocation::MMDB", "PREREQ_PM" => { "Math::BigInt" => "1.999806", "XSLoader" => 0, "utf8" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "File::Spec::Functions" => 0, "Test::More" => 0 }, "VERSION" => "1.013", "test" => { "TESTS" => "t/*.t" } ); %WriteMakefileArgs = ( %WriteMakefileArgs, CCFLAGS => join(q{ }, $ccflags, $Config{ccflags}), LIBS => [ $libs ], DEFINE => join(q{ }, @defines), ); my %FallbackPrereqs = ( "Alien::libmaxminddb" => 0, "File::Spec::Functions" => 0, "Math::BigInt" => "1.999806", "Test::More" => 0, "XSLoader" => 0, "utf8" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION('6.63_03') } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); package MY; # Bail out if something is wrong sub post_initialize { my $text = ''; if (!defined $version) { $text = <<'TEXT'; .PHONY: die die : $(NOECHO) $(ECHO) "Error: libmaxminddb not found" $(NOECHO) $(ECHO) "OS unsupported" $(FALSE) TEXT } elsif ($version =~ m{^(0|1\.[01])\.}) { $text = <<'TEXT'; .PHONY: die die : $(NOECHO) $(ECHO) "Error: libmaxminddb is too old" $(NOECHO) $(ECHO) "OS unsupported" $(FALSE) TEXT } elsif (!eval { Math::BigInt->from_bytes(pack 'C6', 0xff, 0xff, 0xb0, 0x09, 0x00, 0x00)->as_hex eq '0xffffb0090000' }) { # Some Math::BigInt versions fail on i386 if Perl is built with -Dusequadmath. $text = <<'TEXT'; .PHONY: die die : $(NOECHO) $(ECHO) "Error: Math::BigInt is too old or broken" $(NOECHO) $(ECHO) "OS unsupported" $(FALSE) TEXT } return $text; } sub const_loadlibs { my $text = shift->SUPER::const_loadlibs(@_); if ($^O eq 'MSWin32' && $^V < 5.034) { # Ignore unneeded libraries, which may contain invalid symbols my $filter = sub { my $list = shift; my $pattern = $list =~ m{"} ? qr{(?<=")\h+(?=")} : qr{\h+}; join q{ }, grep { m{ maxminddb | ws2_32 }x } split $pattern, $list; }; $text =~ s{ ^ ( (?: EXTRA | LDLOAD ) LIBS ) \h* = \h* (.*?) \h* $ } {sprintf '%s = %s', $1, $filter->($2)}egxm; } return $text; } sub const_config { my $text = shift->SUPER::const_config(@_); # Some BSDs prepend -L/usr/local/lib, which may contain an old library # version, to the library search path $text =~ s{ ^ ( LD(?:DL)?FLAGS \h* = .*? ) -L/usr/local/lib ( $ | \h+ (.*) $ ) } {$1$2}gxm; return $text; } MANIFEST.SKIP100644001750001750 2314765463066 17154 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013cover_db ~$ \.swp$ CONTRIBUTING.md100644001750001750 103014765463066 17546 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013# Contributing to IP::Geolocation::MMDB The code for this distribution is hosted at https://github.com/voegelas/IP-Geolocation-MMDB. Grab the latest version using the command: git clone https://github.com/voegelas/IP-Geolocation-MMDB.git You can submit code changes by forking the repository, pushing your code changes to your clone, and then submitting a pull request. The distribution is managed with [Dist::Zilla](https://dzil.org/). Once installed, here are some dzil commands you might try: dzil build dzil test release-kwalitee.t100644001750001750 50414765463066 21155 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/t BEGIN { unless ($ENV{RELEASE_TESTING}) { print qq{1..0 # SKIP these tests are for release candidate testing\n}; exit } } # this test was generated with Dist::Zilla::Plugin::Test::Kwalitee 2.12 use strict; use warnings; use Test::More 0.88; use Test::Kwalitee 1.21 'kwalitee_ok'; kwalitee_ok(); done_testing; data000755001750001750 014765463066 16337 5ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/tTest-City.mmdb100644001750001750 663114765463066 21173 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/t/data~:      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`awbkcdehfgijlmsnopqrtuvxyz{|}~`      !"#$%&'()*+,-./0123456789;<c=>?@ABCDEFbGHIJKLWMNOPQRSTUV`XYZ[\]^_`a`defghijklmnopqrstuvwxyz{|}DcityJconfidencedJgeoname_id,)EnamesBdeKFalkensteinBen -BlvMFalkenšteinaIcontinentDcodeBEU _r, #BdeFEuropaBenFEuropeBlvFEiropaGcountry d ,TTis_in_european_unionHiso_codeBDE #BdeKDeutschlandBenGGermanyBlvGVācijaHlocationOaccuracy_radius Naverage_income\Hlatitudeh@I 'Pod::Coverage::TrustPod' }); Geolocation000755001750001750 014765463066 20504 5ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/lib/IPMMDB.pm100644001750001750 1465114765463066 21750 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/lib/IP/Geolocationpackage IP::Geolocation::MMDB; # SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later use 5.014; use warnings; use utf8; our $VERSION = 1.013; use IP::Geolocation::MMDB::Metadata; use Math::BigInt 1.999806; require XSLoader; XSLoader::load(__PACKAGE__, $VERSION); sub getcc { my ($self, $ip_address) = @_; my $country_code; my $data = $self->record_for_address($ip_address); if (ref $data eq 'HASH') { if (exists $data->{country}) { my $country = $data->{country}; if (exists $country->{iso_code}) { $country_code = $country->{iso_code}; } } } return $country_code; } sub metadata { my ($self) = @_; return IP::Geolocation::MMDB::Metadata->new(%{$self->_metadata}); } ## no critic (Subroutines::ProhibitUnusedPrivateSubroutines) sub _to_bigint { my ($self, $bytes) = @_; return Math::BigInt->from_bytes($bytes); } 1; __END__ =encoding UTF-8 =head1 NAME IP::Geolocation::MMDB - Read MaxMind DB files =head1 VERSION version 1.013 =head1 SYNOPSIS use IP::Geolocation::MMDB; my $db = IP::Geolocation::MMDB->new(file => '/path/to/Country.mmdb'); my $metadata = $db->metadata; my $data = $db->get('1.2.3.4'); my $country_code = $db->getcc('2620:fe::9'); =head1 DESCRIPTION A Perl module that reads MaxMind DB files and maps IP addresses to location information such as country and city names. =head1 SUBROUTINES/METHODS =head2 new my $db = IP::Geolocation::MMDB->new(file => '/path/to/Country.mmdb'); Returns a new database object. Dies if the specified file cannot be read. =head2 get my $data = $db->get($ip_address); my ($data, $prefix_length) = $db->get($ip_address); Takes an IPv4 or IPv6 address as a string and returns the data associated with the IP address or the undefined value. In list context, the data and the network prefix length associated with the IP address are returned. Dies if the address is not a valid IP address. The returned data is usually a hash reference but could also be a an array reference or a scalar for custom databases. Here's an example from an IP to city database: { city => { geoname_id => 2950159, names => { en => "Berlin" } }, country => { geoname_id => 2921044, iso_code => "DE", names => { en => "Germany", fr => "Allemagne" } }, location => { latitude => 52.524, longitude => 13.411 } } =head2 getcc my $country_code = $db->getcc($ip_address); Takes an IPv4 or IPv6 address as a string and returns a two-letter country code or the undefined value. Dies if the address is not a valid IP address. =head2 record_for_address my $data = $db->record_for_address($ip_address); An alias for C that always returns a scalar. =head2 iterate_search_tree sub data_callback { my ($numeric_ip, $prefix_length, $data) = @_; } sub node_callback { my ($node_number, $left_node_number, $right_node_number) = @_; } $db->iterate_search_tree(\&data_callback, \&node_callback); Iterates over the entire search tree. Calls the provided callbacks for each data record and node in the tree. Both callbacks are optional. The data callback is called with a numeric IP address as a L object, a network prefix length and the data associated with the network. The node callback is called with the node's number in the tree and the children's node numbers. =head2 metadata my $metadata = $db->metadata; Returns an L object for the database. =head2 file my $file = $db->file; Returns the file path passed to the constructor. =head2 libmaxminddb_version my $version = IP::Geolocation::MMDB::libmaxminddb_version; Returns the libmaxminddb version. =head1 DIAGNOSTICS =over =item B<< The "file" parameter is mandatory >> The constructor was called without a database filename. =item B<< Error opening database file >> The database file could not be read. =item B<< The IP address you provided is not a valid IPv4 or IPv6 address >> A parameter did not contain a valid IP address. =item B<< Error looking up IP address >> A database error occurred while looking up an IP address. =item B<< Entry data error looking up >> A database error occurred while reading the data associated with an IP address. =item B<< Error getting metadata >> An error occurred while reading the database's metadata. =item B<< Invalid record when reading node >> Either an invalid node was looked up or the database is corrupt. =item B<< Unknown record type >> An unknown record type was found in the database. =item B<< Invalid depth when reading node >> An error occurred while traversing the search tree. =back =head1 CONFIGURATION AND ENVIRONMENT None. =head1 DEPENDENCIES Requires L version 1.999806, which is distributed with Perl 5.26 and newer. Requires libmaxminddb 1.2.0 or newer. Requires a database in the MaxMind DB file format from L or L. Alien::libmaxminddb from CPAN is a build dependency. The built module does only depend on modules that are distributed with Perl. Install C and C or C if you would like to use your operating system's libmaxminddb library. =head1 INCOMPATIBILITIES None. =head1 BUGS AND LIMITATIONS If your Perl interpreter does not support 64-bit integers, MMDB_DATA_TYPE_UINT64 values are put into Math::BigInt objects. MMDB_DATA_TYPE_UINT128 values are put into Math::BigInt objects. IP::Geolocation::MMDB can replace MaxMind::DB::Reader in many cases with the following differences: =over =item * The classes aren't Moo classes. =item * There is no replacement for MaxMind::DB::Reader::Decoder. =back Create the file F in your C<@INC> path if you want to try IP::Geolocation::MMDB as a replacement for MaxMind::DB::Reader: use IP::Geolocation::MMDB; @MaxMind::DB::Reader::ISA = qw(IP::Geolocation::MMDB); 1; =head1 SEE ALSO See L for object-oriented wrapper classes. =head1 ACKNOWLEDGEMENTS Thanks to all who have contributed patches and reported bugs: =over =item * Yujuan Jiang =back =head1 AUTHOR Andreas Vögele Evoegelas@cpan.orgE =head1 LICENSE AND COPYRIGHT Copyright (C) 2025 Andreas Vögele This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut MMDB000755001750001750 014765463066 21223 5ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/lib/IP/GeolocationMetadata.pm100644001750001750 714714765463066 23452 0ustar00andreasandreas000000000000IP-Geolocation-MMDB-1.013/lib/IP/Geolocation/MMDBpackage IP::Geolocation::MMDB::Metadata; # SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later use 5.014; use warnings; use utf8; our $VERSION = 1.013; sub new { my ($class, %attrs) = @_; my $self = bless \%attrs, $class; return $self; } sub binary_format_major_version { my ($self) = @_; return $self->{binary_format_major_version}; } sub binary_format_minor_version { my ($self) = @_; return $self->{binary_format_minor_version}; } sub build_epoch { my ($self) = @_; return $self->{build_epoch}; } sub database_type { my ($self) = @_; return $self->{database_type}; } sub languages { my ($self) = @_; return $self->{languages}; } sub description { my ($self) = @_; return $self->{description}; } sub ip_version { my ($self) = @_; return $self->{ip_version}; } sub node_count { my ($self) = @_; return $self->{node_count}; } sub record_size { my ($self) = @_; return $self->{record_size}; } 1; __END__ =encoding UTF-8 =head1 NAME IP::Geolocation::MMDB::Metadata - Metadata from a MaxMind DB file =head1 VERSION version 1.013 =head1 SYNOPSIS use IP::Geolocation::MMDB; my $db = IP::Geolocation::MMDB->new(file => '/path/to/City.mmdb'); my $metadata = $db->metadata; =head1 DESCRIPTION A class for metadata from a MaxMind DB file. =head1 SUBROUTINES/METHODS =head2 new my $metadata = IP::Geolocation::MMDB::Metadata->new( binary_format_major_version => 2, binary_format_minor_version => 0, build_epoch => time, database_type => 'City', languages => [qw(en fr pt-BR)], description => { en => 'IP to city', fr => 'IP vers ville', }, ip_version => 6, node_count => 3829268, record_size => 28, ); Returns a new metadata object. =head2 binary_format_major_version my $major_version = $metadata->binary_format_major_version; Returns the database format's major version number. =head2 binary_format_minor_version my $minor_version = $metadata->binary_format_minor_version; Returns the database format's minor version number. =head2 build_epoch my $t = gmtime $metadata->build_epoch; Returns the database's build timestamp as an epoch number. =head2 database_type my $database_type = $metadata->database_type; Returns a free-form string indicating the database type. =head2 languages for my $language (@{$metadata->languages}) { say $language; } Returns a reference to an array of locale codes indicating what languages this database has information for. =head2 description my %description_for = %{$metadata->description}; for my $language (keys %description_for) { my $description = $description_for{$language}; say "$language: $description"; } Returns a reference to a hash that maps locale codes to strings that describe the database content. =head2 ip_version my $ip_version = $metadata->ip_version; Returns 4 or 6. =head2 node_count my $node_count = $metadata->node_count; Returns the number of nodes in the database's search tree. =head2 record_size my $record_size = $metadata->record_size; Returns the record size for nodes in the database's search tree. =head1 DIAGNOSTICS None. =head1 CONFIGURATION AND ENVIRONMENT None. =head1 DEPENDENCIES None. =head1 INCOMPATIBILITIES None. =head1 BUGS AND LIMITATIONS None known. =head1 SEE ALSO L =head1 AUTHOR Andreas Vögele Evoegelas@cpan.orgE =head1 LICENSE AND COPYRIGHT Copyright (C) 2025 Andreas Vögele This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut