IISHKO: Telegram bot, Mini App and gateway
Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1 @@
|
||||
"""Pinned Apache-2.0 MaxMind pure-Python reader; no extension or API loader."""
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Constants used in the API."""
|
||||
|
||||
from enum import IntEnum
|
||||
|
||||
|
||||
class Mode(IntEnum):
|
||||
"""Database open modes.
|
||||
|
||||
These modes control how the MaxMind DB file is opened and read.
|
||||
"""
|
||||
|
||||
AUTO = 0
|
||||
"""Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order. Default mode."""
|
||||
|
||||
MMAP_EXT = 1
|
||||
"""Use the C extension with memory map."""
|
||||
|
||||
MMAP = 2
|
||||
"""Read from memory map. Pure Python."""
|
||||
|
||||
FILE = 4
|
||||
"""Read database as standard file. Pure Python."""
|
||||
|
||||
MEMORY = 8
|
||||
"""Load database into memory. Pure Python."""
|
||||
|
||||
FD = 16
|
||||
"""Database is a file descriptor, not a path. This mode implies MODE_MEMORY."""
|
||||
|
||||
|
||||
# Backward compatibility: export both enum members and old-style constants
|
||||
MODE_AUTO = Mode.AUTO
|
||||
MODE_MMAP_EXT = Mode.MMAP_EXT
|
||||
MODE_MMAP = Mode.MMAP
|
||||
MODE_FILE = Mode.FILE
|
||||
MODE_MEMORY = Mode.MEMORY
|
||||
MODE_FD = Mode.FD
|
||||
|
||||
__all__ = [
|
||||
"MODE_AUTO",
|
||||
"MODE_FD",
|
||||
"MODE_FILE",
|
||||
"MODE_MEMORY",
|
||||
"MODE_MMAP",
|
||||
"MODE_MMAP_EXT",
|
||||
"Mode",
|
||||
]
|
||||
@@ -0,0 +1,356 @@
|
||||
# Vendored from MaxMind-DB-Reader-python v3.2.0 (Apache-2.0).
|
||||
# ENI modification: package imports made relative; reader/decoder behavior unchanged.
|
||||
"""Decoder for the MaxMind DB data section."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
try:
|
||||
import mmap
|
||||
except ImportError:
|
||||
mmap = None # type: ignore[assignment]
|
||||
|
||||
from .errors import InvalidDatabaseError
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .file import FileBuffer
|
||||
from .types import Record
|
||||
|
||||
|
||||
# Per-lookup value limit recommended by the MaxMind DB specification. It stops
|
||||
# pointer fan-out, where nested containers share targets that would otherwise
|
||||
# cost 2**depth decode operations. The root costs one value. Arrays charge each
|
||||
# Real records decode a few hundred values, leaving a wide margin.
|
||||
# An explicit depth limit catches container cycles and overly nested data.
|
||||
# Python's recursion limit may fire first, which decode converts to the same
|
||||
# error. The explicit limit also applies when callers raise Python's limit.
|
||||
_MAX_VALUES = 1 << 16
|
||||
_MAX_DEPTH = 512
|
||||
# Per-lookup limit on the total string and bytes payload materialized, matching
|
||||
# libmaxminddb and the Go reader. It stops a payload amplification, where many
|
||||
# pointers to one large value would otherwise materialize N * size bytes from a
|
||||
# small file. Each string or bytes value is charged its length wherever it is
|
||||
# decoded, so re-decoding a shared target through another pointer recharges.
|
||||
_MAX_PAYLOAD_BYTES = 1 << 21
|
||||
# The widest fixed-width integer the format defines is the 16-byte uint128; a
|
||||
# declared size past that is malformed and could copy attacker-controlled bytes.
|
||||
_MAX_UINT_BYTES = 16
|
||||
_MAX_INT32_BYTES = 4
|
||||
# Added to a pointer value, by pointer size. A 4-byte pointer adds nothing.
|
||||
_POINTER_VALUE_OFFSETS = (0, 0, 2048, 526336)
|
||||
_TOO_MANY_VALUES = (
|
||||
"The MaxMind DB file's data section exceeds the maximum number of values"
|
||||
)
|
||||
_TOO_DEEP = "The MaxMind DB file's data section exceeds the maximum depth"
|
||||
_TOO_LARGE = "The MaxMind DB file's data section exceeds the maximum payload size"
|
||||
_BAD_DATA = (
|
||||
"The MaxMind DB file's data section contains bad data "
|
||||
"(unknown data type or corrupt data)"
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class _DecodeBudget:
|
||||
"""Shared counters for one record or metadata decode."""
|
||||
|
||||
values_left: int
|
||||
depth: int
|
||||
payload_left: int
|
||||
|
||||
|
||||
class Decoder:
|
||||
"""Decoder for the data section of the MaxMind DB."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database_buffer: FileBuffer | mmap.mmap | bytes,
|
||||
pointer_base: int = 0,
|
||||
pointer_test: bool = False, # noqa: FBT001, FBT002
|
||||
) -> None:
|
||||
"""Create a Decoder for a MaxMind DB.
|
||||
|
||||
Arguments:
|
||||
database_buffer: an mmap'd MaxMind DB file.
|
||||
pointer_base: the base number to use when decoding a pointer
|
||||
pointer_test: used for internal unit testing of pointer code
|
||||
|
||||
"""
|
||||
self._pointer_test = pointer_test
|
||||
self._buffer = database_buffer
|
||||
self._pointer_base = pointer_base
|
||||
|
||||
def _decode_array(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
) -> tuple[list[Record], int]:
|
||||
remaining = budget.values_left - size
|
||||
if remaining < 0:
|
||||
raise InvalidDatabaseError(_TOO_MANY_VALUES)
|
||||
budget.values_left = remaining
|
||||
depth = budget.depth + 1
|
||||
if depth > _MAX_DEPTH:
|
||||
raise InvalidDatabaseError(_TOO_DEEP)
|
||||
budget.depth = depth
|
||||
array = []
|
||||
decode = self._decode
|
||||
for _ in range(size):
|
||||
(value, offset) = decode(offset, budget, False) # noqa: FBT003
|
||||
array.append(value)
|
||||
budget.depth -= 1
|
||||
return array, offset
|
||||
|
||||
def _decode_boolean(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[bool, int]:
|
||||
return size != 0, offset
|
||||
|
||||
def _decode_bytes(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
) -> tuple[bytes, int]:
|
||||
# Charge the payload before copying so a crafted size cannot force a
|
||||
# large allocation, and so pointers reusing one target recharge.
|
||||
remaining = budget.payload_left - size
|
||||
if remaining < 0:
|
||||
raise InvalidDatabaseError(_TOO_LARGE)
|
||||
budget.payload_left = remaining
|
||||
new_offset = offset + size
|
||||
return self._buffer[offset:new_offset], new_offset
|
||||
|
||||
def _decode_double(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[float, int]:
|
||||
self._verify_size(size, 8)
|
||||
new_offset = offset + size
|
||||
packed_bytes = self._buffer[offset:new_offset]
|
||||
(value,) = struct.unpack(b"!d", packed_bytes)
|
||||
return value, new_offset
|
||||
|
||||
def _decode_float(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[float, int]:
|
||||
self._verify_size(size, 4)
|
||||
new_offset = offset + size
|
||||
packed_bytes = self._buffer[offset:new_offset]
|
||||
(value,) = struct.unpack(b"!f", packed_bytes)
|
||||
return value, new_offset
|
||||
|
||||
def _decode_int32(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[int, int]:
|
||||
if size > _MAX_INT32_BYTES:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
if size == 0:
|
||||
return 0, offset
|
||||
new_offset = offset + size
|
||||
packed_bytes = self._buffer[offset:new_offset]
|
||||
|
||||
if size != 4:
|
||||
packed_bytes = packed_bytes.rjust(4, b"\x00")
|
||||
(value,) = struct.unpack(b"!i", packed_bytes)
|
||||
return value, new_offset
|
||||
|
||||
def _decode_map(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
) -> tuple[dict[str, Record], int]:
|
||||
remaining = budget.values_left - size * 2
|
||||
if remaining < 0:
|
||||
raise InvalidDatabaseError(_TOO_MANY_VALUES)
|
||||
budget.values_left = remaining
|
||||
depth = budget.depth + 1
|
||||
if depth > _MAX_DEPTH:
|
||||
raise InvalidDatabaseError(_TOO_DEEP)
|
||||
budget.depth = depth
|
||||
container: dict[str, Record] = {}
|
||||
decode = self._decode
|
||||
for _ in range(size):
|
||||
(key, offset) = decode(offset, budget, False) # noqa: FBT003
|
||||
(value, offset) = decode(offset, budget, False) # noqa: FBT003
|
||||
container[key] = value # type: ignore[index]
|
||||
budget.depth -= 1
|
||||
return container, offset
|
||||
|
||||
def _decode_pointer(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
) -> tuple[Record, int]:
|
||||
pointer_size = (size >> 3) + 1
|
||||
new_offset = offset + pointer_size
|
||||
pointer_bytes = self._buffer[offset:new_offset]
|
||||
if len(pointer_bytes) != pointer_size:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
pointer = int.from_bytes(pointer_bytes, "big")
|
||||
if pointer_size < 4:
|
||||
# The low three bits of the ctrl byte are the high bits of the
|
||||
# pointer, and sizes 2 and 3 add a fixed offset.
|
||||
pointer |= (size & 0x7) << (pointer_size << 3)
|
||||
pointer += _POINTER_VALUE_OFFSETS[pointer_size]
|
||||
pointer += self._pointer_base
|
||||
|
||||
if self._pointer_test:
|
||||
return pointer, new_offset
|
||||
|
||||
# The value at the pointer's position was charged by its containing
|
||||
# array or map, so the target costs nothing more. Only the depth changes.
|
||||
depth = budget.depth + 1
|
||||
if depth > _MAX_DEPTH:
|
||||
raise InvalidDatabaseError(_TOO_DEEP)
|
||||
budget.depth = depth
|
||||
(value, _) = self._decode(pointer, budget, True) # noqa: FBT003
|
||||
budget.depth -= 1
|
||||
return value, new_offset
|
||||
|
||||
def _decode_uint(
|
||||
self,
|
||||
size: int,
|
||||
offset: int,
|
||||
_budget: _DecodeBudget,
|
||||
) -> tuple[int, int]:
|
||||
# Reject a declared size past the widest defined unsigned integer before
|
||||
# copying, so a crafted size cannot force a large allocation.
|
||||
if size > _MAX_UINT_BYTES:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
new_offset = offset + size
|
||||
uint_bytes = self._buffer[offset:new_offset]
|
||||
return int.from_bytes(uint_bytes, "big"), new_offset
|
||||
|
||||
def decode(self, offset: int) -> tuple[Record, int]:
|
||||
"""Decode a section of the data section starting at offset.
|
||||
|
||||
Arguments:
|
||||
offset: the location of the data structure to decode
|
||||
|
||||
"""
|
||||
# Each call gets its own budget, shared by recursive calls. Charge the
|
||||
# root here.
|
||||
try:
|
||||
return self._decode(
|
||||
offset,
|
||||
_DecodeBudget(_MAX_VALUES - 1, 0, _MAX_PAYLOAD_BYTES),
|
||||
False, # noqa: FBT003
|
||||
)
|
||||
except RecursionError as ex:
|
||||
raise InvalidDatabaseError(_TOO_DEEP) from ex
|
||||
except (IndexError, struct.error) as ex:
|
||||
# Convert failed buffer indexing and fixed-width unpacking.
|
||||
raise InvalidDatabaseError(_BAD_DATA) from ex
|
||||
|
||||
# Keep type dispatch inline to avoid another call for every decoded value.
|
||||
# The positional booleans are intentional: keywords and omitted defaults
|
||||
# prevented CPython from using its fastest call path in our benchmarks.
|
||||
# pointer_target rejects pointers to other pointers.
|
||||
def _decode( # noqa: C901, PLR0911, PLR0912
|
||||
self,
|
||||
offset: int,
|
||||
budget: _DecodeBudget,
|
||||
pointer_target: bool, # noqa: FBT001
|
||||
) -> tuple[Record, int]:
|
||||
new_offset = offset + 1
|
||||
ctrl_byte = self._buffer[offset]
|
||||
type_num = ctrl_byte >> 5
|
||||
# Extended type
|
||||
if not type_num:
|
||||
(type_num, new_offset) = self._read_extended(new_offset)
|
||||
|
||||
size = ctrl_byte & 0x1F
|
||||
# Sizes under 29 are stored in the ctrl byte, and a pointer's size bits
|
||||
# are not a size. Skip the call for that common case.
|
||||
if size >= 29 and type_num != 1:
|
||||
(size, new_offset) = self._size_from_ctrl_byte(size, new_offset)
|
||||
# Put common types first to reduce comparisons during real lookups.
|
||||
match type_num:
|
||||
case 2:
|
||||
# Strings are most of the values in a real database. Decode them
|
||||
# here to save a method call.
|
||||
# Charge the payload before copying so a crafted size cannot force
|
||||
# a large allocation, and so pointers reusing one target recharge.
|
||||
remaining = budget.payload_left - size
|
||||
if remaining < 0:
|
||||
raise InvalidDatabaseError(_TOO_LARGE)
|
||||
budget.payload_left = remaining
|
||||
end = new_offset + size
|
||||
return self._buffer[new_offset:end].decode("utf-8"), end
|
||||
case 1:
|
||||
if pointer_target:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
return self._decode_pointer(size, new_offset, budget)
|
||||
case 7:
|
||||
return self._decode_map(size, new_offset, budget)
|
||||
case 6 | 5 | 9 | 10: # uint32, uint16, uint64, uint128
|
||||
return self._decode_uint(size, new_offset, budget)
|
||||
case 11:
|
||||
return self._decode_array(size, new_offset, budget)
|
||||
case 3:
|
||||
return self._decode_double(size, new_offset, budget)
|
||||
case 4:
|
||||
return self._decode_bytes(size, new_offset, budget)
|
||||
case 8:
|
||||
return self._decode_int32(size, new_offset, budget)
|
||||
case 14:
|
||||
return self._decode_boolean(size, new_offset, budget)
|
||||
case 15:
|
||||
return self._decode_float(size, new_offset, budget)
|
||||
case _:
|
||||
msg = f"Unexpected type number ({type_num}) encountered"
|
||||
raise InvalidDatabaseError(msg)
|
||||
|
||||
def _read_extended(self, offset: int) -> tuple[int, int]:
|
||||
next_byte = self._buffer[offset]
|
||||
type_num = next_byte + 7
|
||||
if type_num < 7:
|
||||
msg = (
|
||||
"Something went horribly wrong in the decoder. An "
|
||||
f"extended type resolved to a type number < 8 ({type_num})"
|
||||
)
|
||||
raise InvalidDatabaseError(
|
||||
msg,
|
||||
)
|
||||
return type_num, offset + 1
|
||||
|
||||
@staticmethod
|
||||
def _verify_size(expected: int, actual: int) -> None:
|
||||
if expected != actual:
|
||||
raise InvalidDatabaseError(_BAD_DATA)
|
||||
|
||||
def _size_from_ctrl_byte(self, size: int, offset: int) -> tuple[int, int]:
|
||||
# Called only for size codes 29 to 31, which are followed by size bytes.
|
||||
if size == 29:
|
||||
size = 29 + self._buffer[offset]
|
||||
return size, offset + 1
|
||||
|
||||
# Using unpack rather than int_from_bytes as it is faster
|
||||
# here and below.
|
||||
if size == 30:
|
||||
new_offset = offset + 2
|
||||
size_bytes = self._buffer[offset:new_offset]
|
||||
size = 285 + struct.unpack(b"!H", size_bytes)[0]
|
||||
return size, new_offset
|
||||
|
||||
new_offset = offset + 3
|
||||
size_bytes = self._buffer[offset:new_offset]
|
||||
size = struct.unpack(b"!I", b"\x00" + size_bytes)[0] + 65821
|
||||
return size, new_offset
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Typed errors thrown by this library."""
|
||||
|
||||
|
||||
class InvalidDatabaseError(RuntimeError):
|
||||
"""An error thrown when unexpected data is found in the database."""
|
||||
@@ -0,0 +1,74 @@
|
||||
"""For internal use only. It provides a slice-like file reader."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from typing import overload
|
||||
|
||||
try:
|
||||
from multiprocessing import Lock
|
||||
except ImportError:
|
||||
from threading import Lock # type: ignore[assignment]
|
||||
|
||||
|
||||
class FileBuffer:
|
||||
"""A slice-able file reader."""
|
||||
|
||||
def __init__(self, database: str) -> None:
|
||||
"""Create FileBuffer."""
|
||||
self._handle = open(database, "rb") # noqa: SIM115
|
||||
self._size = os.fstat(self._handle.fileno()).st_size
|
||||
if not hasattr(os, "pread"):
|
||||
self._lock = Lock()
|
||||
|
||||
@overload
|
||||
def __getitem__(self, index: int) -> int: ...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, index: slice) -> bytes: ...
|
||||
|
||||
def __getitem__(self, index: slice | int) -> bytes | int:
|
||||
"""Get item by index."""
|
||||
if isinstance(index, slice):
|
||||
return self._read(index.stop - index.start, index.start)
|
||||
if isinstance(index, int):
|
||||
return self._read(1, index)[0]
|
||||
msg = "Invalid argument type."
|
||||
raise TypeError(msg)
|
||||
|
||||
def rfind(self, needle: bytes, start: int) -> int:
|
||||
"""Reverse find needle from start."""
|
||||
pos = self._read(self._size - start - 1, start).rfind(needle)
|
||||
if pos == -1:
|
||||
return pos
|
||||
return start + pos
|
||||
|
||||
def size(self) -> int:
|
||||
"""Size of file."""
|
||||
return self._size
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close file."""
|
||||
self._handle.close()
|
||||
|
||||
if hasattr(os, "pread"): # type: ignore[attr-defined]
|
||||
|
||||
def _read(self, buffersize: int, offset: int) -> bytes:
|
||||
"""Read that uses pread."""
|
||||
return os.pread(self._handle.fileno(), buffersize, offset) # type: ignore[attr-defined]
|
||||
|
||||
else:
|
||||
|
||||
def _read(self, buffersize: int, offset: int) -> bytes:
|
||||
"""Read with a lock.
|
||||
|
||||
This lock is necessary as after a fork, the different processes
|
||||
will share the same file table entry, even if we dup the fd, and
|
||||
as such the same offsets. There does not appear to be a way to
|
||||
duplicate the file table entry and we cannot re-open based on the
|
||||
original path as that file may have replaced with another or
|
||||
unlinked.
|
||||
"""
|
||||
with self._lock:
|
||||
self._handle.seek(offset)
|
||||
return self._handle.read(buffersize)
|
||||
@@ -0,0 +1,98 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"project": "MaxMind-DB-Reader-python",
|
||||
"repository": "https://github.com/maxmind/MaxMind-DB-Reader-python",
|
||||
"release": "v3.2.0",
|
||||
"release_url": "https://github.com/maxmind/MaxMind-DB-Reader-python/releases/tag/v3.2.0",
|
||||
"release_published_at": "2026-09-10T22:11:26Z",
|
||||
"commit": "b6885a05eb5a4729bd213e760a2619c34e4184d2",
|
||||
"license": "Apache-2.0",
|
||||
"license_file": "LICENSE",
|
||||
"retrieved_at_utc": "2026-10-25",
|
||||
"python_requires": ">=3.10",
|
||||
"python_3_11_and_3_14_supported_upstream": true,
|
||||
"runtime_dependencies": "Python standard library only; typing_extensions is inside TYPE_CHECKING guards only",
|
||||
"source_inspection": "Inspected all included module imports, reader mmap/cleanup paths, decoder budgets and all dispatch branches before use. No HTTP, DNS, socket, pickle, subprocess, telemetry, updater or install hooks in included runtime source. FileBuffer fallback is included solely to satisfy upstream imports; application adapter only supplies a verified read-only mmap.",
|
||||
"included_modules": [
|
||||
"__init__.py",
|
||||
"const.py",
|
||||
"decoder.py",
|
||||
"errors.py",
|
||||
"file.py",
|
||||
"reader.py",
|
||||
"types.py"
|
||||
],
|
||||
"excluded": "No C extension, build/install files, tests, docs, API clients, downloaded executable or upstream package __init__ loader.",
|
||||
"local_adapter": "entry_geo._new_reader subclasses only _load_buffer to accept the already SHA256-verified mmap; no path re-open or alternate memory/file/network mode.",
|
||||
"files": {
|
||||
"const.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/const.py",
|
||||
"upstream_git_blob_sha1": "0f7e9826c510ab41da67fcb5dd69275f2ef43fd7",
|
||||
"upstream_sha256": "44e3afd67f2dd1932b962cb797fed53b76e9758dd78107829d9ca34c78f7de6c",
|
||||
"upstream_size_bytes": 986,
|
||||
"vendored_size_bytes": 986,
|
||||
"vendored_sha256": "44e3afd67f2dd1932b962cb797fed53b76e9758dd78107829d9ca34c78f7de6c",
|
||||
"modifications": []
|
||||
},
|
||||
"decoder.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/decoder.py",
|
||||
"upstream_git_blob_sha1": "9ef985abd276d14b42d8a46f4e2c21ae574b3cfb",
|
||||
"upstream_sha256": "cd05d6b9cac680b30636ce12036f884abc7654f741279a49700ac5d91bac6ddc",
|
||||
"upstream_size_bytes": 13289,
|
||||
"vendored_size_bytes": 13410,
|
||||
"vendored_sha256": "4d4171bcf373b4a051964b09109739e0f58a972534c825ea7604dd7808c85585",
|
||||
"modifications": [
|
||||
"Added prominent vendoring/modification notice",
|
||||
"Changed maxminddb.* imports to relative imports for isolated vendor_entry_geo package"
|
||||
]
|
||||
},
|
||||
"errors.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/errors.py",
|
||||
"upstream_git_blob_sha1": "b87bc8d4face8d5e906ae4a45b1d4f7accc42060",
|
||||
"upstream_sha256": "4422ad335e76e52420498e27733b5ff2d5ef790257e27274573038b9a20045eb",
|
||||
"upstream_size_bytes": 160,
|
||||
"vendored_size_bytes": 160,
|
||||
"vendored_sha256": "4422ad335e76e52420498e27733b5ff2d5ef790257e27274573038b9a20045eb",
|
||||
"modifications": []
|
||||
},
|
||||
"file.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/file.py",
|
||||
"upstream_git_blob_sha1": "1901d9ba6f6b2806080f3dfce30564f7ee95f26c",
|
||||
"upstream_sha256": "f233f4c8ce6ae854a9464530f14d6734951ca4962762981408d520bcfeb1a829",
|
||||
"upstream_size_bytes": 2401,
|
||||
"vendored_size_bytes": 2401,
|
||||
"vendored_sha256": "f233f4c8ce6ae854a9464530f14d6734951ca4962762981408d520bcfeb1a829",
|
||||
"modifications": []
|
||||
},
|
||||
"reader.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/reader.py",
|
||||
"upstream_git_blob_sha1": "32fe961b7ca8ee019cfa32457ffbcb3b71e51863",
|
||||
"upstream_sha256": "043b409c31dd18d205ec002cbeade355e065d1c29bb1e07382bfd2a3d5aaa87b",
|
||||
"upstream_size_bytes": 13578,
|
||||
"vendored_size_bytes": 13681,
|
||||
"vendored_sha256": "b04dd6ba6f0144f77d201adb0d305758b24cadaa6e8c5ca92a5259fcfe3bfc2e",
|
||||
"modifications": [
|
||||
"Added prominent vendoring/modification notice",
|
||||
"Changed maxminddb.* imports to relative imports for isolated vendor_entry_geo package"
|
||||
]
|
||||
},
|
||||
"types.py": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/maxminddb/types.py",
|
||||
"upstream_git_blob_sha1": "fa14eefa6416f5b2cefc2f861caa5069a4d41a5c",
|
||||
"upstream_sha256": "28d1737da3b3176f002187c3b3c0a9a9eb6e137361f4940dfa250e7d14ecf65a",
|
||||
"upstream_size_bytes": 429,
|
||||
"vendored_size_bytes": 429,
|
||||
"vendored_sha256": "28d1737da3b3176f002187c3b3c0a9a9eb6e137361f4940dfa250e7d14ecf65a",
|
||||
"modifications": []
|
||||
},
|
||||
"LICENSE": {
|
||||
"upstream_url": "https://raw.githubusercontent.com/maxmind/MaxMind-DB-Reader-python/b6885a05eb5a4729bd213e760a2619c34e4184d2/LICENSE",
|
||||
"upstream_git_blob_sha1": "d645695673349e3947e8e5ae42332d0ac3164cd7",
|
||||
"upstream_sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
|
||||
"upstream_size_bytes": 11358,
|
||||
"vendored_size_bytes": 11358,
|
||||
"vendored_sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30",
|
||||
"modifications": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
# Vendored from MaxMind-DB-Reader-python v3.2.0 (Apache-2.0).
|
||||
# ENI modification: package imports made relative; reader/decoder behavior unchanged.
|
||||
"""Pure-Python reader for the MaxMind DB file format."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
try:
|
||||
import mmap
|
||||
except ImportError:
|
||||
mmap = None # type: ignore[assignment]
|
||||
|
||||
import contextlib
|
||||
import ipaddress
|
||||
from dataclasses import dataclass
|
||||
from ipaddress import IPv4Address, IPv6Address
|
||||
from typing import IO, TYPE_CHECKING, Any, AnyStr
|
||||
|
||||
from .const import MODE_AUTO, MODE_FD, MODE_FILE, MODE_MEMORY, MODE_MMAP
|
||||
from .decoder import Decoder
|
||||
from .errors import InvalidDatabaseError
|
||||
from .file import FileBuffer
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
from os import PathLike
|
||||
|
||||
from typing_extensions import Self
|
||||
|
||||
from .types import Record
|
||||
|
||||
_IPV4_MAX_NUM = 2**32
|
||||
|
||||
|
||||
class Reader:
|
||||
"""A pure Python implementation of a reader for the MaxMind DB format.
|
||||
|
||||
IP addresses can be looked up using the ``get`` method.
|
||||
"""
|
||||
|
||||
_DATA_SECTION_SEPARATOR_SIZE = 16
|
||||
_METADATA_START_MARKER = b"\xab\xcd\xefMaxMind.com"
|
||||
|
||||
_buffer: bytes | FileBuffer | "mmap.mmap" # noqa: UP037
|
||||
_buffer_size: int
|
||||
closed: bool
|
||||
_decoder: Decoder
|
||||
_metadata: Metadata
|
||||
_record_size: int
|
||||
_ipv4_start: int
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database: AnyStr | int | PathLike | IO,
|
||||
mode: int = MODE_AUTO,
|
||||
) -> None:
|
||||
"""Reader for the MaxMind DB file format.
|
||||
|
||||
Arguments:
|
||||
database: A path to a valid MaxMind DB file such as a GeoIP database
|
||||
file, or a file descriptor in the case of MODE_FD.
|
||||
mode: mode to open the database with. Valid mode are:
|
||||
* MODE_MMAP - read from memory map.
|
||||
* MODE_FILE - read database as standard file.
|
||||
* MODE_MEMORY - load database into memory.
|
||||
* MODE_AUTO - tries MODE_MMAP and then MODE_FILE. Default.
|
||||
* MODE_FD - the param passed via database is a file descriptor, not
|
||||
a path. This mode implies MODE_MEMORY.
|
||||
|
||||
"""
|
||||
filename = self._load_buffer(database, mode)
|
||||
|
||||
# Include validation errors in this cleanup scope. TRY301 is suppressed
|
||||
# because the handler only closes the buffer and re-raises the error.
|
||||
try:
|
||||
metadata_start = self._buffer.rfind(
|
||||
self._METADATA_START_MARKER,
|
||||
max(0, self._buffer_size - 128 * 1024),
|
||||
)
|
||||
|
||||
if metadata_start == -1:
|
||||
msg = (
|
||||
f"Error opening database file ({filename}). "
|
||||
"Is this a valid MaxMind DB file?"
|
||||
)
|
||||
raise InvalidDatabaseError( # noqa: TRY301
|
||||
msg,
|
||||
)
|
||||
|
||||
metadata_start += len(self._METADATA_START_MARKER)
|
||||
metadata_decoder = Decoder(self._buffer, metadata_start)
|
||||
(metadata, _) = metadata_decoder.decode(metadata_start)
|
||||
|
||||
if not isinstance(metadata, dict):
|
||||
msg = f"Error reading metadata in database file ({filename})."
|
||||
raise InvalidDatabaseError( # noqa: TRY301
|
||||
msg,
|
||||
)
|
||||
|
||||
self._metadata = Metadata(**metadata)
|
||||
self._record_size = self._metadata.record_size
|
||||
if self._record_size not in (24, 28, 32):
|
||||
msg = f"Unknown record size: {self._record_size}"
|
||||
raise InvalidDatabaseError(msg) # noqa: TRY301
|
||||
if self._metadata.node_count < 0:
|
||||
msg = f"Invalid node count: {self._metadata.node_count}"
|
||||
raise InvalidDatabaseError(msg) # noqa: TRY301
|
||||
|
||||
# Traversal reads nodes below node_count. Once the tree fits, those
|
||||
# reads need no length checks of their own.
|
||||
tree_end = (
|
||||
self._metadata.search_tree_size + self._DATA_SECTION_SEPARATOR_SIZE
|
||||
)
|
||||
if tree_end > self._buffer_size:
|
||||
msg = (
|
||||
f"Error opening database file ({filename}). The search tree "
|
||||
"extends past the end of the file."
|
||||
)
|
||||
raise InvalidDatabaseError(msg) # noqa: TRY301
|
||||
|
||||
self._decoder = Decoder(
|
||||
self._buffer,
|
||||
self._metadata.search_tree_size + self._DATA_SECTION_SEPARATOR_SIZE,
|
||||
)
|
||||
self.closed = False
|
||||
|
||||
ipv4_start = 0
|
||||
if self._metadata.ip_version == 6:
|
||||
# We store the IPv4 starting node as an optimization for IPv4 lookups
|
||||
# in IPv6 trees. This allows us to skip over the first 96 nodes in
|
||||
# this case.
|
||||
node = 0
|
||||
for _ in range(96):
|
||||
if node >= self._metadata.node_count:
|
||||
break
|
||||
node = self._read_node(node, 0)
|
||||
ipv4_start = node
|
||||
self._ipv4_start = ipv4_start
|
||||
except BaseException:
|
||||
# Release the buffer on any initialization failure.
|
||||
self.close()
|
||||
raise
|
||||
|
||||
def metadata(self) -> Metadata:
|
||||
"""Return the metadata associated with the MaxMind DB file."""
|
||||
return self._metadata
|
||||
|
||||
def get(self, ip_address: str | IPv6Address | IPv4Address) -> Record | None:
|
||||
"""Return the record for the ip_address in the MaxMind DB.
|
||||
|
||||
Arguments:
|
||||
ip_address: an IP address in the standard string notation
|
||||
|
||||
"""
|
||||
(record, _) = self.get_with_prefix_len(ip_address)
|
||||
return record
|
||||
|
||||
def get_with_prefix_len(
|
||||
self,
|
||||
ip_address: str | IPv6Address | IPv4Address,
|
||||
) -> tuple[Record | None, int]:
|
||||
"""Return a tuple with the record and the associated prefix length.
|
||||
|
||||
Arguments:
|
||||
ip_address: an IP address in the standard string notation
|
||||
|
||||
"""
|
||||
if isinstance(ip_address, str):
|
||||
address = ipaddress.ip_address(ip_address)
|
||||
else:
|
||||
address = ip_address
|
||||
|
||||
try:
|
||||
packed_address = bytearray(address.packed)
|
||||
except AttributeError as ex:
|
||||
msg = "argument 1 must be a string or ipaddress object"
|
||||
raise TypeError(msg) from ex
|
||||
|
||||
if address.version == 6 and self._metadata.ip_version == 4:
|
||||
msg = (
|
||||
f"Error looking up {ip_address}. You attempted to look up "
|
||||
"an IPv6 address in an IPv4-only database."
|
||||
)
|
||||
raise ValueError(
|
||||
msg,
|
||||
)
|
||||
|
||||
(pointer, prefix_len) = self._find_address_in_tree(packed_address)
|
||||
|
||||
if pointer:
|
||||
return self._resolve_data_pointer(pointer), prefix_len
|
||||
return None, prefix_len
|
||||
|
||||
def __iter__(self) -> Iterator:
|
||||
return self._generate_children(0, 0, 0)
|
||||
|
||||
def _generate_children(self, node: int, depth: int, ip_acc: int) -> Iterator:
|
||||
if ip_acc != 0 and node == self._ipv4_start:
|
||||
# Skip nodes aliased to IPv4
|
||||
return
|
||||
|
||||
node_count = self._metadata.node_count
|
||||
if node > node_count:
|
||||
bits = 128 if self._metadata.ip_version == 6 else 32
|
||||
ip_acc <<= bits - depth
|
||||
if ip_acc <= _IPV4_MAX_NUM and bits == 128:
|
||||
depth -= 96
|
||||
yield (
|
||||
ipaddress.ip_network((ip_acc, depth)),
|
||||
self._resolve_data_pointer(
|
||||
node,
|
||||
),
|
||||
)
|
||||
elif node < node_count:
|
||||
left = self._read_node(node, 0)
|
||||
ip_acc <<= 1
|
||||
depth += 1
|
||||
yield from self._generate_children(left, depth, ip_acc)
|
||||
right = self._read_node(node, 1)
|
||||
yield from self._generate_children(right, depth, ip_acc | 1)
|
||||
|
||||
def _find_address_in_tree(self, packed: bytearray) -> tuple[int, int]:
|
||||
bit_count = len(packed) * 8
|
||||
node = self._start_node(bit_count)
|
||||
node_count = self._metadata.node_count
|
||||
|
||||
i = 0
|
||||
while i < bit_count and node < node_count:
|
||||
bit = 1 & (packed[i >> 3] >> 7 - (i % 8))
|
||||
node = self._read_node(node, bit)
|
||||
i = i + 1
|
||||
|
||||
if node == node_count:
|
||||
# Record is empty
|
||||
return 0, i
|
||||
if node > node_count:
|
||||
return node, i
|
||||
|
||||
msg = "Invalid node in search tree"
|
||||
raise InvalidDatabaseError(msg)
|
||||
|
||||
def _start_node(self, length: int) -> int:
|
||||
if self._metadata.ip_version == 6 and length == 32:
|
||||
return self._ipv4_start
|
||||
return 0
|
||||
|
||||
def _read_node(self, node_number: int, index: int) -> int:
|
||||
record_size = self._record_size
|
||||
if record_size == 28:
|
||||
# Two 28-bit records share the middle byte: its high nibble
|
||||
# belongs to the left record and its low nibble to the right.
|
||||
base_offset = node_number * 7
|
||||
if index:
|
||||
offset = base_offset + 3
|
||||
record = int.from_bytes(self._buffer[offset : offset + 4], "big")
|
||||
return record & 0x0FFFFFFF
|
||||
record = int.from_bytes(self._buffer[base_offset : base_offset + 4], "big")
|
||||
return (record >> 8) | ((record & 0xF0) << 20)
|
||||
if record_size == 24:
|
||||
offset = node_number * 6 + index * 3
|
||||
return int.from_bytes(self._buffer[offset : offset + 3], "big")
|
||||
if record_size == 32:
|
||||
offset = node_number * 8 + index * 4
|
||||
return int.from_bytes(self._buffer[offset : offset + 4], "big")
|
||||
msg = f"Unknown record size: {record_size}"
|
||||
raise InvalidDatabaseError(msg)
|
||||
|
||||
def _resolve_data_pointer(self, pointer: int) -> Record:
|
||||
resolved = pointer - self._metadata.node_count + self._metadata.search_tree_size
|
||||
|
||||
if resolved >= self._buffer_size:
|
||||
msg = "The MaxMind DB file's search tree is corrupt"
|
||||
raise InvalidDatabaseError(msg)
|
||||
|
||||
(data, _) = self._decoder.decode(resolved)
|
||||
return data
|
||||
|
||||
def _load_buffer(
|
||||
self, database: AnyStr | int | PathLike | IO, mode: int = MODE_AUTO
|
||||
) -> str:
|
||||
filename: Any
|
||||
if (mode == MODE_AUTO and mmap) or mode == MODE_MMAP:
|
||||
with open(database, "rb") as db_file: # type: ignore[arg-type]
|
||||
self._buffer = mmap.mmap(db_file.fileno(), 0, access=mmap.ACCESS_READ)
|
||||
self._buffer_size = self._buffer.size()
|
||||
filename = database
|
||||
elif mode in (MODE_AUTO, MODE_FILE):
|
||||
self._buffer = FileBuffer(database) # type: ignore[arg-type]
|
||||
self._buffer_size = self._buffer.size()
|
||||
filename = database
|
||||
elif mode == MODE_MEMORY:
|
||||
with open(database, "rb") as db_file: # type: ignore[arg-type]
|
||||
buf = db_file.read()
|
||||
self._buffer = buf
|
||||
self._buffer_size = len(buf)
|
||||
filename = database
|
||||
elif mode == MODE_FD:
|
||||
self._buffer = database.read() # type: ignore[union-attr]
|
||||
self._buffer_size = len(self._buffer) # type: ignore[arg-type]
|
||||
# io buffers are not guaranteed to have a name attribute
|
||||
if hasattr(database, "name"):
|
||||
filename = database.name # type: ignore[union-attr]
|
||||
else:
|
||||
filename = f"<{type(database)}>"
|
||||
else:
|
||||
msg = (
|
||||
f"Unsupported open mode ({mode}). Only MODE_AUTO, MODE_FILE, "
|
||||
"MODE_MEMORY and MODE_FD are supported by the pure Python "
|
||||
"Reader"
|
||||
)
|
||||
raise ValueError(
|
||||
msg,
|
||||
)
|
||||
|
||||
return filename
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the MaxMind DB file and returns the resources to the system.
|
||||
|
||||
Calling this method while reads are in progress may cause exceptions.
|
||||
"""
|
||||
with contextlib.suppress(AttributeError):
|
||||
self._buffer.close() # type: ignore[union-attr]
|
||||
|
||||
self.closed = True
|
||||
|
||||
def __exit__(self, *_) -> None: # noqa: ANN002
|
||||
self.close()
|
||||
|
||||
def __enter__(self) -> Self:
|
||||
if self.closed:
|
||||
msg = "Attempt to reopen a closed MaxMind DB"
|
||||
raise ValueError(msg)
|
||||
return self
|
||||
|
||||
|
||||
@dataclass(kw_only=True, frozen=True)
|
||||
class Metadata:
|
||||
"""Metadata for the MaxMind DB reader."""
|
||||
|
||||
binary_format_major_version: int
|
||||
"""
|
||||
The major version number of the binary format used when creating the
|
||||
database.
|
||||
"""
|
||||
|
||||
binary_format_minor_version: int
|
||||
"""
|
||||
The minor version number of the binary format used when creating the
|
||||
database.
|
||||
"""
|
||||
|
||||
build_epoch: int
|
||||
"""The Unix epoch for the build time of the database."""
|
||||
|
||||
database_type: str
|
||||
"""A string identifying the database type, e.g., "GeoIP2-City"."""
|
||||
|
||||
description: dict[str, str]
|
||||
"""A map from locales to text descriptions of the database."""
|
||||
|
||||
ip_version: int
|
||||
"""
|
||||
The IP version of the data in a database. A value of "4" means the
|
||||
database only supports IPv4. A database with a value of "6" may support
|
||||
both IPv4 and IPv6 lookups.
|
||||
"""
|
||||
|
||||
languages: list[str]
|
||||
"""A list of locale codes supported by the database."""
|
||||
|
||||
node_count: int
|
||||
"""The number of nodes in the database."""
|
||||
|
||||
record_size: int
|
||||
"""The bit size of a record in the search tree."""
|
||||
|
||||
@property
|
||||
def node_byte_size(self) -> int:
|
||||
"""The size of a node in bytes."""
|
||||
return self.record_size // 4
|
||||
|
||||
@property
|
||||
def search_tree_size(self) -> int:
|
||||
"""The size of the search tree."""
|
||||
return self.node_count * self.node_byte_size
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Types representing database records."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import AnyStr, TypeAlias
|
||||
|
||||
Primitive: TypeAlias = AnyStr | bool | float | int
|
||||
|
||||
RecordList: TypeAlias = list["Record"]
|
||||
"""RecordList is a type for lists in a database record."""
|
||||
|
||||
RecordDict: TypeAlias = dict[str, "Record"]
|
||||
"""RecordDict is a type for dicts in a database record."""
|
||||
|
||||
Record: TypeAlias = Primitive | RecordList | RecordDict
|
||||
Reference in New Issue
Block a user