ctidb-bin 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ctidb_bin/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """Packed Binary — IP intelligence binary format (CTIDB v2, read-only)."""
2
+ from .format import HotRecord, RangeEntry, License, Flags, Plan
3
+ from .reader import PackedReader, Metadata
4
+ from .name_table import NameTableReader
5
+
6
+ __version__ = "0.0.1"
7
+ __all__ = [
8
+ "PackedReader",
9
+ "HotRecord", "RangeEntry", "License", "Flags", "Plan",
10
+ "Metadata",
11
+ "NameTableReader",
12
+ ]
ctidb_bin/format.py ADDED
@@ -0,0 +1,213 @@
1
+ """Packed Binary 포맷 — 구조체/상수 정의.
2
+
3
+ docs/FORMAT.md 와 1:1 매칭. 모든 struct fmt 가 little-endian (`<`).
4
+ """
5
+ from __future__ import annotations
6
+ import struct
7
+ from dataclasses import dataclass
8
+ from enum import IntFlag
9
+
10
+ # ─────────────────────── 시그니처 / 상수 ───────────────────────
11
+ MAGIC_HEADER = b"CTIDBV2\x00"
12
+ MAGIC_FOOTER = b"\x00PACKED\x00"
13
+ FORMAT_VERSION_MAJOR = 1
14
+ FORMAT_VERSION_MINOR = 2 # v1.2: cold_offset uint64 (Plan 4 4GB+ cold section 지원)
15
+
16
+ # Section offsets / fixed sizes
17
+ HEADER_SIZE = 16
18
+ LICENSE_BLOB_SIZE = 256
19
+ LICENSE_SIG_SIZE = 256
20
+ LICENSE_SECT_SIZE = LICENSE_BLOB_SIZE + LICENSE_SIG_SIZE # 512
21
+ RANGE_TABLE_OFFSET = HEADER_SIZE + LICENSE_SECT_SIZE # 528
22
+ RANGE_ENTRY_SIZE = 16 # v1.0/1.1 legacy (uint32 x 4)
23
+ RANGE_ENTRY_SIZE_V12 = 20 # v1.2: uint32 x 3 + uint64 (cold_offset)
24
+ HOT_RECORD_SIZE = 8
25
+ FOOTER_SIZE = 16 # v1.0 (legacy)
26
+ FOOTER_SIZE_V11 = 24 # v1.1/1.2: +8 byte name_table_offset
27
+
28
+
29
+ # ─────────────────────── struct format strings ───────────────────────
30
+ # Header
31
+ HEADER_FMT = "<8sHHI" # magic(8) + ver_major(2) + ver_minor(2) + range_count(4) = 16
32
+ assert struct.calcsize(HEADER_FMT) == HEADER_SIZE
33
+
34
+ # Range entry
35
+ RANGE_FMT = "<IIII" # v1.0/1.1: start(4) + end(4) + hot_off(4) + cold_off_u32(4) = 16
36
+ RANGE_FMT_V12 = "<IIIQ" # v1.2: start(4) + end(4) + hot_off(4) + cold_off_u64(8) = 20
37
+ assert struct.calcsize(RANGE_FMT) == RANGE_ENTRY_SIZE
38
+ assert struct.calcsize(RANGE_FMT_V12) == RANGE_ENTRY_SIZE_V12
39
+
40
+ # Hot record — 24-bit asn_id 는 4 byte 단위 align 위해 3B + 1B padding 안 쓰고
41
+ # 그냥 1+3+1+1+2 = 8 byte 명시. asn_id 는 uint32 의 하위 24비트만 사용.
42
+ HOT_FMT = "<BBBB BBH"
43
+ # = country(1) + asn_lo(1) + asn_mid(1) + asn_hi(1) + score(1) + score_inbound(1) + flags(2)
44
+ assert struct.calcsize(HOT_FMT) == HOT_RECORD_SIZE
45
+
46
+ # License blob (256B)
47
+ LICENSE_FMT = "<32s16s B Q Q I 187s"
48
+ # license_key(32) + customer_id(16) + plan(1) + issued(8) + expire(8) + permissions(4) + reserved(187) = 256
49
+ assert struct.calcsize(LICENSE_FMT) == LICENSE_BLOB_SIZE
50
+
51
+ # Footer — v1.0 legacy (magic + crc + fv = 16B)
52
+ FOOTER_FMT = "<8sII" # magic(8) + crc32(4) + format_ver(4) = 16
53
+ assert struct.calcsize(FOOTER_FMT) == FOOTER_SIZE
54
+
55
+ # Footer — v1.1 (magic + crc + fv + name_table_offset = 24B)
56
+ FOOTER_FMT_V11 = "<8sIIQ"
57
+ assert struct.calcsize(FOOTER_FMT_V11) == FOOTER_SIZE_V11
58
+
59
+
60
+ # ─────────────────────── Flags bitfield ───────────────────────
61
+ class Flags(IntFlag):
62
+ IS_VPN = 1 << 0
63
+ IS_TOR = 1 << 1
64
+ IS_CDN = 1 << 2
65
+ IS_PROXY = 1 << 3
66
+ IS_HOSTING = 1 << 4
67
+ IS_CLOUD = 1 << 5
68
+ IS_C2 = 1 << 6
69
+ IS_HONEYPOT = 1 << 7
70
+ HAS_ABUSE = 1 << 8
71
+ HAS_CVE = 1 << 9
72
+ IS_MOBILE = 1 << 10
73
+
74
+
75
+ # ─────────────────────── Plan IDs ───────────────────────
76
+ class Plan(IntFlag):
77
+ GEOLOCATION = 1
78
+ TI_C2 = 2
79
+ FRAUD = 3
80
+ FULL = 4
81
+ PRIVACY = 5
82
+
83
+
84
+ # ─────────────────────── Dataclasses (in-memory representation) ───────────────────────
85
+ @dataclass(frozen=True)
86
+ class HotRecord:
87
+ country_code_id: int # uint8
88
+ asn_id: int # uint24 — 16M 까지
89
+ score: int # uint8 (0-100)
90
+ score_inbound: int # uint8 (0-100)
91
+ flags: int # uint16 bitfield
92
+
93
+ def pack(self) -> bytes:
94
+ a = self.asn_id & 0xFFFFFF
95
+ return struct.pack(
96
+ HOT_FMT,
97
+ self.country_code_id & 0xFF,
98
+ a & 0xFF,
99
+ (a >> 8) & 0xFF,
100
+ (a >> 16) & 0xFF,
101
+ self.score & 0xFF,
102
+ self.score_inbound & 0xFF,
103
+ self.flags & 0xFFFF,
104
+ )
105
+
106
+ @classmethod
107
+ def unpack_from(cls, buf, offset: int) -> "HotRecord":
108
+ cc, a_lo, a_mid, a_hi, sc, sc_in, fl = struct.unpack_from(HOT_FMT, buf, offset)
109
+ return cls(
110
+ country_code_id=cc,
111
+ asn_id=(a_hi << 16) | (a_mid << 8) | a_lo,
112
+ score=sc,
113
+ score_inbound=sc_in,
114
+ flags=fl,
115
+ )
116
+
117
+
118
+ @dataclass(frozen=True)
119
+ class RangeEntry:
120
+ start_ip: int # uint32 (host endian, little-endian on x86)
121
+ end_ip: int
122
+ hot_offset: int # uint32 (offset within Hot Records section)
123
+ cold_idx: int # uint32 (0 = no cold record)
124
+
125
+ def pack(self) -> bytes:
126
+ return struct.pack(RANGE_FMT, self.start_ip, self.end_ip, self.hot_offset, self.cold_idx)
127
+
128
+ @classmethod
129
+ def unpack_from(cls, buf, offset: int) -> "RangeEntry":
130
+ s, e, h, c = struct.unpack_from(RANGE_FMT, buf, offset)
131
+ return cls(start_ip=s, end_ip=e, hot_offset=h, cold_idx=c)
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class License:
136
+ license_key: str
137
+ customer_id: str
138
+ plan: int
139
+ issued_at: int # unix ts
140
+ expire_at: int
141
+ permissions: int # bitfield
142
+
143
+ def pack(self) -> bytes:
144
+ return struct.pack(
145
+ LICENSE_FMT,
146
+ self.license_key.encode("ascii")[:32],
147
+ self.customer_id.encode("ascii")[:16],
148
+ self.plan & 0xFF,
149
+ self.issued_at & 0xFFFFFFFFFFFFFFFF,
150
+ self.expire_at & 0xFFFFFFFFFFFFFFFF,
151
+ self.permissions & 0xFFFFFFFF,
152
+ b"", # reserved (zero-padded by struct)
153
+ )
154
+
155
+ @classmethod
156
+ def unpack(cls, blob: bytes) -> "License":
157
+ k, c, p, iss, exp, perm, _ = struct.unpack(LICENSE_FMT, blob)
158
+ return cls(
159
+ license_key=k.rstrip(b"\x00").decode("ascii"),
160
+ customer_id=c.rstrip(b"\x00").decode("ascii"),
161
+ plan=p,
162
+ issued_at=iss,
163
+ expire_at=exp,
164
+ permissions=perm,
165
+ )
166
+
167
+
168
+ # ─────────────────────── Header / Footer helpers ───────────────────────
169
+ def pack_header(range_count: int) -> bytes:
170
+ return struct.pack(
171
+ HEADER_FMT,
172
+ MAGIC_HEADER,
173
+ FORMAT_VERSION_MAJOR,
174
+ FORMAT_VERSION_MINOR,
175
+ range_count,
176
+ )
177
+
178
+
179
+ def unpack_header(buf: bytes) -> tuple[int, int, int]:
180
+ """returns (ver_major, ver_minor, range_count)"""
181
+ magic, vmaj, vmin, rcount = struct.unpack(HEADER_FMT, buf[:HEADER_SIZE])
182
+ if magic != MAGIC_HEADER:
183
+ raise ValueError(f"bad magic: {magic!r}")
184
+ return vmaj, vmin, rcount
185
+
186
+
187
+ def pack_footer(crc32: int, name_table_offset: int | None = None) -> bytes:
188
+ """v1.1: name_table_offset 를 명시적으로 저장 (24 byte).
189
+ v1.0 legacy: name_table_offset=None 이면 16 byte footer.
190
+ """
191
+ fv = (FORMAT_VERSION_MAJOR << 16) | FORMAT_VERSION_MINOR
192
+ if name_table_offset is None:
193
+ return struct.pack(FOOTER_FMT, MAGIC_FOOTER, crc32 & 0xFFFFFFFF, fv)
194
+ return struct.pack(
195
+ FOOTER_FMT_V11, MAGIC_FOOTER, crc32 & 0xFFFFFFFF, fv,
196
+ name_table_offset & 0xFFFFFFFFFFFFFFFF,
197
+ )
198
+
199
+
200
+ def unpack_footer(buf: bytes) -> tuple[int, int, int | None]:
201
+ """dual-mode: buf 는 file 끝의 24 byte 이상.
202
+ 반환: (crc32, format_version, name_table_offset_or_None)
203
+ - v1.1 (24B): name_table_offset explicit
204
+ - v1.0 (16B): None (호출부에서 heuristic 계산)
205
+ """
206
+ tail = bytes(buf)
207
+ if len(tail) >= FOOTER_SIZE_V11 and tail[-FOOTER_SIZE_V11:-FOOTER_SIZE_V11+8] == MAGIC_FOOTER:
208
+ magic, crc, fv, name_off = struct.unpack(FOOTER_FMT_V11, tail[-FOOTER_SIZE_V11:])
209
+ return crc, fv, name_off
210
+ magic, crc, fv = struct.unpack(FOOTER_FMT, tail[-FOOTER_SIZE:])
211
+ if magic != MAGIC_FOOTER:
212
+ raise ValueError(f"bad footer magic: {magic!r}")
213
+ return crc, fv, None
@@ -0,0 +1,84 @@
1
+ """Name Table — string ↔ uint32 ID 양방향 매핑.
2
+
3
+ writer 단계: string add → ID 할당 (dedup)
4
+ reader 단계: mmap 위에서 ID → string lookup (zero-copy 가능한 곳은)
5
+ """
6
+ from __future__ import annotations
7
+ import array
8
+ import struct
9
+ from typing import Iterator
10
+
11
+
12
+ # ─────────────────────── Writer 측 ───────────────────────
13
+ class NameTableBuilder:
14
+ """writer 가 record 만들면서 string 마다 ID 할당 + dedup."""
15
+
16
+ def __init__(self) -> None:
17
+ self._str_to_id: dict[str, int] = {}
18
+ self._id_to_str: list[str] = []
19
+ # ID 0 = empty string (sentinel)
20
+ self._add_internal("")
21
+
22
+ def _add_internal(self, s: str) -> int:
23
+ i = len(self._id_to_str)
24
+ self._str_to_id[s] = i
25
+ self._id_to_str.append(s)
26
+ return i
27
+
28
+ def add(self, s: str | None) -> int:
29
+ """string 추가 → ID 반환. 같은 string 은 동일 ID."""
30
+ if not s:
31
+ return 0
32
+ i = self._str_to_id.get(s)
33
+ if i is not None:
34
+ return i
35
+ return self._add_internal(s)
36
+
37
+ def __len__(self) -> int:
38
+ return len(self._id_to_str)
39
+
40
+ def serialize(self) -> bytes:
41
+ """디스크 포맷: [count:uint32] [len:uint16][bytes] × N"""
42
+ parts: list[bytes] = [struct.pack("<I", len(self._id_to_str))]
43
+ for s in self._id_to_str:
44
+ b = s.encode("utf-8")
45
+ if len(b) > 65535:
46
+ raise ValueError(f"string too long ({len(b)} bytes, max 65535)")
47
+ parts.append(struct.pack("<H", len(b)))
48
+ parts.append(b)
49
+ return b"".join(parts)
50
+
51
+
52
+ # ─────────────────────── Reader 측 ───────────────────────
53
+ class NameTableReader:
54
+ """mmap buffer 의 name_table section 을 ID → string 조회."""
55
+
56
+ def __init__(self, buf, offset: int) -> None:
57
+ self._buf = buf
58
+ self._base = offset
59
+ (count,) = struct.unpack_from("<I", buf, offset)
60
+ self._count = count
61
+ # 각 string 의 file offset. list[int](Python int 28B/개) 대신 array.array('Q')(8B/개)
62
+ # → 40M names 기준 ~1.1GB → 320MB (mmap 리더 메모리 폭식 완화).
63
+ offsets = array.array('Q', bytes(8 * count)) # 0으로 preallocate
64
+ cur = offset + 4
65
+ for i in range(count):
66
+ (l,) = struct.unpack_from("<H", buf, cur)
67
+ offsets[i] = cur + 2
68
+ cur += 2 + l
69
+ self._offsets = offsets
70
+
71
+ def get(self, str_id: int) -> str:
72
+ if str_id == 0 or str_id >= self._count:
73
+ return ""
74
+ off = self._offsets[str_id]
75
+ # length prefix 는 off-2 위치
76
+ (l,) = struct.unpack_from("<H", self._buf, off - 2)
77
+ return bytes(self._buf[off:off + l]).decode("utf-8", errors="replace")
78
+
79
+ def __len__(self) -> int:
80
+ return self._count
81
+
82
+ def __iter__(self) -> Iterator[str]:
83
+ for i in range(self._count):
84
+ yield self.get(i)
ctidb_bin/py.typed ADDED
File without changes
ctidb_bin/reader.py ADDED
@@ -0,0 +1,343 @@
1
+ """Packed Binary Reader — mmap + binary search + zero-copy decode.
2
+
3
+ Example:
4
+ with PackedReader.open("/path/cti.bin") as r:
5
+ rec = r.get("8.8.8.8")
6
+ print(r.metadata.license_key, rec)
7
+ """
8
+ from __future__ import annotations
9
+ import sys
10
+ import array
11
+ import mmap
12
+ import struct
13
+ import ipaddress
14
+ import bisect
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+
18
+ from .format import (
19
+ HEADER_SIZE, LICENSE_BLOB_SIZE, LICENSE_SECT_SIZE, RANGE_TABLE_OFFSET,
20
+ RANGE_ENTRY_SIZE, RANGE_ENTRY_SIZE_V12, HOT_RECORD_SIZE,
21
+ FOOTER_SIZE, FOOTER_SIZE_V11,
22
+ HotRecord, RangeEntry, License, Flags,
23
+ unpack_header, unpack_footer,
24
+ )
25
+ from .name_table import NameTableReader
26
+
27
+
28
+ def _ip_to_int(ip: str) -> int:
29
+ return int(ipaddress.IPv4Address(ip))
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Metadata:
34
+ version: tuple[int, int]
35
+ range_count: int
36
+ license: License
37
+ file_size: int
38
+
39
+
40
+ class PackedReader:
41
+ """zero-copy mmap reader. close() 또는 with 로 닫기."""
42
+
43
+ def __init__(self, mm: mmap.mmap, file_size: int, with_cold: bool = True) -> None:
44
+ self._mm = mm
45
+ self._file_size = file_size
46
+ self._with_cold = with_cold
47
+
48
+ # Header
49
+ vmaj, vmin, range_count = unpack_header(bytes(mm[:HEADER_SIZE]))
50
+ self._range_count = range_count
51
+
52
+ # ver_major=2 → 컬럼형(col) 레이아웃. 별도 파서로 분기 (range table 아님).
53
+ self._col = (vmaj == 2)
54
+ if self._col:
55
+ self._init_col(mm, file_size, vmin)
56
+ return
57
+
58
+ # License
59
+ license_blob = bytes(mm[HEADER_SIZE:HEADER_SIZE + LICENSE_BLOB_SIZE])
60
+ self._license = License.unpack(license_blob)
61
+ # signature 는 다음 256B (verify 는 license.py 의 verify_signature() 별도)
62
+
63
+ # v1.2: RANGE_ENTRY_SIZE 20 (cold_offset uint64). v1.0/1.1: 16.
64
+ # Header 의 minor version 으로 결정.
65
+ if vmin >= 2:
66
+ self._range_entry_size = RANGE_ENTRY_SIZE_V12
67
+ self._range_fmt = "<IIIQ"
68
+ else:
69
+ self._range_entry_size = RANGE_ENTRY_SIZE
70
+ self._range_fmt = "<IIII"
71
+
72
+ # Range table — start_ip 배열만 별도로 두면 binary search 빠름
73
+ self._range_offset = RANGE_TABLE_OFFSET
74
+ self._hot_offset = self._range_offset + range_count * self._range_entry_size
75
+
76
+ # start_ip 만 모은 정렬 배열 + max(hot_off) 추적
77
+ # v1.0.3: Python list[int] (28 byte/elem) → array.array('I') (4 byte/elem) — 7배 memory 절감
78
+ self._start_ips = array.array('I', [0] * range_count)
79
+ max_hot_off = 0
80
+ for i in range(range_count):
81
+ off = self._range_offset + i * self._range_entry_size
82
+ s, _e, hoff, _c = struct.unpack_from(self._range_fmt, mm, off)
83
+ self._start_ips[i] = s
84
+ if hoff > max_hot_off:
85
+ max_hot_off = hoff
86
+ # hot section 의 byte size = max_hot_off + 1 record
87
+ self._hot_size = max_hot_off + HOT_RECORD_SIZE
88
+
89
+ # Footer 파싱 — v1.0 legacy 16B, v1.1/1.2 확장 24B (name_table_offset explicit).
90
+ tail = bytes(mm[-FOOTER_SIZE_V11:]) if file_size >= FOOTER_SIZE_V11 else bytes(mm[-FOOTER_SIZE:])
91
+ crc, fv, name_off_explicit = unpack_footer(tail)
92
+ self._crc = crc
93
+ self._format_ver_packed = fv
94
+ if name_off_explicit is not None:
95
+ # v1.1: writer 가 저장한 정확한 offset
96
+ self._name_table_offset = name_off_explicit
97
+ self._footer_offset = file_size - FOOTER_SIZE_V11
98
+ else:
99
+ # v1.0 legacy: cold 없다는 가정 (cold 있으면 offset 어긋남 — 옛 spec 한계)
100
+ self._name_table_offset = self._hot_offset + self._hot_size
101
+ self._footer_offset = file_size - FOOTER_SIZE
102
+
103
+ try:
104
+ self._names = NameTableReader(mm, self._name_table_offset)
105
+ except Exception:
106
+ # v1.0 파일 + cold 있어서 offset 어긋남 — name lookup 은 empty 로 처리
107
+ self._names = None # type: ignore
108
+
109
+ self._metadata = Metadata(
110
+ version=(vmaj, vmin),
111
+ range_count=range_count,
112
+ license=self._license,
113
+ file_size=file_size,
114
+ )
115
+
116
+ # ─────────────────── public API ───────────────────
117
+ @classmethod
118
+ def open(cls, path: str, with_cold: bool = True) -> "PackedReader":
119
+ f = open(path, "rb")
120
+ size = f.seek(0, 2)
121
+ f.seek(0)
122
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
123
+ f.close()
124
+ return cls(mm, file_size=size, with_cold=with_cold)
125
+
126
+ def close(self) -> None:
127
+ self._mm.close()
128
+
129
+ def __enter__(self):
130
+ return self
131
+
132
+ def __exit__(self, *_):
133
+ self.close()
134
+
135
+ @property
136
+ def metadata(self) -> Metadata:
137
+ return self._metadata
138
+
139
+ def get(self, ip: str) -> dict[str, Any] | None:
140
+ ip_int = _ip_to_int(ip)
141
+ if self._col:
142
+ return self._col_get(ip_int)
143
+ # binary search — bisect_right - 1 은 start_ip <= ip_int 인 가장 큰 idx
144
+ idx = bisect.bisect_right(self._start_ips, ip_int) - 1
145
+ if idx < 0:
146
+ return None
147
+ # v1.0.9: K=1024 (parquet /32 밀집 대역에서 GeoIP2 base range 놓침 방지).
148
+ # 넓은 base range 를 찾으면 즉시 break (더 뒤로 갈수록 base 발견 확률 감소).
149
+ best_hot = None
150
+ best_width = -1
151
+ LOOKBACK_LIMIT = 1024
152
+ for _ in range(LOOKBACK_LIMIT):
153
+ if idx < 0:
154
+ break
155
+ off = self._range_offset + idx * self._range_entry_size
156
+ s, e, hot_off, cold_off = struct.unpack_from(self._range_fmt, self._mm, off)
157
+ if s <= ip_int <= e:
158
+ w = e - s
159
+ if best_hot is None or w < best_width:
160
+ best_hot = hot_off
161
+ best_width = w
162
+ if w == 0:
163
+ break # /32 최소 — 더 좁을 수 없음
164
+ idx -= 1
165
+ if best_hot is None:
166
+ return None
167
+ return self._decode_hot(best_hot)
168
+
169
+ def get_with_cold(self, ip: str) -> dict[str, Any] | None:
170
+ """hot + cold 둘 다. cold 는 lazy mmap (fault-in)."""
171
+ # 현재 v1 은 cold 위치 정보 없음 — hot only
172
+ return self.get(ip)
173
+
174
+ # ─────────────────── internal ───────────────────
175
+ def _decode_hot(self, hot_off: int) -> dict[str, Any]:
176
+ abs_off = self._hot_offset + hot_off
177
+ hr = HotRecord.unpack_from(self._mm, abs_off)
178
+ out: dict[str, Any] = {
179
+ "country_code": self._name(hr.country_code_id),
180
+ "as_name": self._name(hr.asn_id),
181
+ "score": hr.score,
182
+ "score_inbound": hr.score_inbound,
183
+ }
184
+ # flags 분해
185
+ f = hr.flags
186
+ for key, mask in [
187
+ ("is_vpn", Flags.IS_VPN),
188
+ ("is_tor", Flags.IS_TOR),
189
+ ("is_cdn", Flags.IS_CDN),
190
+ ("is_proxy", Flags.IS_PROXY),
191
+ ("is_hosting", Flags.IS_HOSTING),
192
+ ("is_cloud", Flags.IS_CLOUD),
193
+ ("is_c2", Flags.IS_C2),
194
+ ("is_honeypot", Flags.IS_HONEYPOT),
195
+ ("is_mobile", Flags.IS_MOBILE),
196
+ ]:
197
+ if f & mask:
198
+ out[key] = True
199
+ return out
200
+
201
+ def _name(self, str_id: int) -> str:
202
+ if self._names is None or str_id == 0:
203
+ return ""
204
+ return self._names.get(str_id)
205
+
206
+ # ─────────────────── columnar (ver_major=2) ───────────────────
207
+ # L1 range(country·asn·city) / L2 flags(비겹침 range 리스트) / L3 out·in score(0~5, C·D)
208
+ _COL_FLAG_KEY = {
209
+ 0: "is_vpn", 1: "is_tor", 2: "is_cdn", 3: "is_proxy", 4: "is_hosting",
210
+ 5: "is_cloud", 6: "is_c2", 7: "is_honeypot", 10: "is_mobile",
211
+ }
212
+
213
+ @staticmethod
214
+ def _le(arr: "array.array") -> "array.array":
215
+ # frombytes 는 native 바이트오더 — 디스크는 LE. big-endian 호스트에서만 swap.
216
+ if sys.byteorder != "little":
217
+ arr.byteswap()
218
+ return arr
219
+
220
+ def _init_col(self, mm: mmap.mmap, file_size: int, vmin: int) -> None:
221
+ self._names = None
222
+ self._mm = mm
223
+ product_id, section_count = struct.unpack_from("<HH", mm, 12)
224
+ self._col_product = product_id
225
+ secs = {}
226
+ for i in range(section_count):
227
+ typ, _codec, _rsv, off, ln = struct.unpack_from("<BBHQQ", mm, HEADER_SIZE + i * 20)
228
+ secs[typ] = (off, ln)
229
+ self._col_sections = secs
230
+ self._col_names: list[str] = []
231
+ # 메모리: list[tuple] 대신 array('I') (4byte/elem) — 761MB bin 이 8Gi OOM 나던 것 해소.
232
+ self._col_l1_flat = array.array("I") # [s,e,cid,aid,cityid] * cnt
233
+ self._col_l1_starts = array.array("I") # bisect 용 start 컬럼
234
+ self._col_l1_cnt = 0
235
+ self._col_l2: dict[int, "array.array"] = {} # fid -> [s,e]*rc
236
+ self._col_l2_starts: dict[int, "array.array"] = {} # fid -> start 컬럼
237
+ # L3 는 수천만 range(56M+) — materialize 하면 startup 15s+/560MB. mmap 위 key-bisect 로 무적재.
238
+ self._col_l3_off = 0
239
+ self._col_l3_cnt = 0
240
+ self._parse_col_l1(mm)
241
+ self._parse_col_l2(mm)
242
+ self._parse_col_l3(mm)
243
+ lic_off = secs.get(9, (0, 0))[0]
244
+ try:
245
+ self._license = License.unpack(bytes(mm[lic_off:lic_off + LICENSE_BLOB_SIZE])) if lic_off else None
246
+ except Exception:
247
+ self._license = None
248
+ self._metadata = Metadata(version=(2, vmin), range_count=self._col_l1_cnt, license=self._license, file_size=file_size)
249
+
250
+ def _parse_col_l1(self, mm: mmap.mmap) -> None:
251
+ if 1 not in self._col_sections:
252
+ return
253
+ off = self._col_sections[1][0]
254
+ cnt = struct.unpack_from("<I", mm, off)[0]
255
+ p = off + 4
256
+ flat = array.array("I")
257
+ flat.frombytes(memoryview(mm)[p:p + cnt * 20]) # 제로카피 벌크 로드
258
+ self._le(flat)
259
+ self._col_l1_flat = flat
260
+ self._col_l1_starts = flat[0::5] # compact start 컬럼(array 복사)
261
+ self._col_l1_cnt = cnt
262
+ p += cnt * 20
263
+ ncnt = struct.unpack_from("<I", mm, p)[0]
264
+ p += 4
265
+ for _ in range(ncnt):
266
+ ln = struct.unpack_from("<H", mm, p)[0]
267
+ p += 2
268
+ self._col_names.append(bytes(mm[p:p + ln]).decode("utf-8", "replace"))
269
+ p += ln
270
+
271
+ def _parse_col_l2(self, mm: mmap.mmap) -> None:
272
+ if 2 not in self._col_sections:
273
+ return
274
+ off = self._col_sections[2][0]
275
+ fc = struct.unpack_from("<I", mm, off)[0]
276
+ dir_off = off + 4
277
+ blob_off = dir_off + fc * 9
278
+ for i in range(fc):
279
+ fid, rel, rc = struct.unpack_from("<BII", mm, dir_off + i * 9)
280
+ rp = blob_off + rel
281
+ flat = array.array("I")
282
+ flat.frombytes(memoryview(mm)[rp:rp + rc * 8]) # [s,e]*rc
283
+ self._le(flat)
284
+ self._col_l2[fid] = flat
285
+ self._col_l2_starts[fid] = flat[0::2]
286
+
287
+ def _parse_col_l3(self, mm: mmap.mmap) -> None:
288
+ # 무적재: offset/cnt 만. 조회 시 mmap 위에서 key-bisect (아래 _col_get).
289
+ if 3 not in self._col_sections:
290
+ return
291
+ off = self._col_sections[3][0]
292
+ self._col_l3_cnt = struct.unpack_from("<I", mm, off)[0]
293
+ self._col_l3_off = off + 4 # entry i: <IIBB> at off+4 + i*10
294
+
295
+ def _col_name(self, i: int) -> str:
296
+ return self._col_names[i] if 0 <= i < len(self._col_names) else ""
297
+
298
+ def _col_flag(self, fid: int, n: int) -> bool:
299
+ starts = self._col_l2_starts.get(fid)
300
+ if not starts:
301
+ return False
302
+ i = bisect.bisect_right(starts, n) - 1
303
+ if i < 0:
304
+ return False
305
+ return n <= self._col_l2[fid][i * 2 + 1] # end
306
+
307
+ def _col_get(self, n: int) -> dict[str, Any] | None:
308
+ i = bisect.bisect_right(self._col_l1_starts, n) - 1
309
+ if i < 0:
310
+ return None
311
+ flat = self._col_l1_flat
312
+ base = i * 5
313
+ if n > flat[base + 1]: # end
314
+ return None
315
+ out: dict[str, Any] = {
316
+ "country_code": self._col_name(flat[base + 2]),
317
+ "as_name": self._col_name(flat[base + 3]),
318
+ "score": 0,
319
+ "score_inbound": 0,
320
+ }
321
+ for fid, key in self._COL_FLAG_KEY.items():
322
+ if self._col_flag(fid, n):
323
+ out[key] = True
324
+ if self._col_l3_cnt:
325
+ j = self._col_l3_bisect(n) # start <= n 인 마지막 range (mmap 직접, 무적재)
326
+ if j >= 0:
327
+ s, e, so, si = struct.unpack_from("<IIBB", self._mm, self._col_l3_off + j * 10)
328
+ if n <= e:
329
+ out["score"] = so
330
+ out["score_inbound"] = si
331
+ return out
332
+
333
+ def _col_l3_bisect(self, n: int) -> int:
334
+ """L3 start 컬럼(mmap, 10byte stride) 위 bisect_right-1. 버전 무관 수동 이진탐색(~26회)."""
335
+ mm, base = self._mm, self._col_l3_off
336
+ lo, hi = 0, self._col_l3_cnt
337
+ while lo < hi:
338
+ mid = (lo + hi) >> 1
339
+ if n < struct.unpack_from("<I", mm, base + mid * 10)[0]:
340
+ hi = mid
341
+ else:
342
+ lo = mid + 1
343
+ return lo - 1
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctidb-bin
3
+ Version: 0.0.1
4
+ Summary: CriminalIP packed binary CTI DB reader (v2/v3 format)
5
+ Project-URL: Homepage, https://github.com/aispera/ctidb-bin
6
+ Author-email: AI Spera <infra@aispera.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: criminalip,ctidb,packed-binary,threat-intelligence
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Security
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.9
15
+ Provides-Extra: dev
16
+ Requires-Dist: mypy; extra == 'dev'
17
+ Requires-Dist: pytest; extra == 'dev'
18
+ Requires-Dist: ruff; extra == 'dev'
19
+ Provides-Extra: fast
20
+ Requires-Dist: pyroaring>=1.0; extra == 'fast'
21
+ Requires-Dist: zstandard>=0.22; extra == 'fast'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # ctidb-bin
25
+
26
+ **CriminalIP packed binary CTI DB reader** — packed BIN v2/v3 포맷 전용 리더 (read-only, zero-copy mmap).
27
+
28
+ > 기존 MMDB 포맷 리더가 필요하면 [`ctidb`](https://pypi.org/project/ctidb/) 패키지를 사용하세요.
29
+ > `ctidb-bin`은 신규 packed binary 포맷(v2/v3) 전용입니다.
30
+
31
+ ## 설치
32
+
33
+ ```bash
34
+ pip install ctidb-bin
35
+ ```
36
+
37
+ 코어는 순수 파이썬(무의존)입니다. v3 가속 기능(L2 bitmap / cold record 압축)은 선택 설치:
38
+
39
+ ```bash
40
+ pip install "ctidb-bin[fast]" # pyroaring, zstandard
41
+ ```
42
+
43
+ ## 사용법
44
+
45
+ ```python
46
+ from ctidb_bin import PackedReader
47
+
48
+ # with 구문 (권장 — 자동 close)
49
+ with PackedReader.open("criminalip.ctidb.c.bin") as reader:
50
+ rec = reader.get("8.8.8.8")
51
+ if rec:
52
+ print(rec["country_code"], rec["as_name"])
53
+ print("hosting:", rec.get("is_hosting"), "cloud:", rec.get("is_cloud"))
54
+ print("score in/out:", rec.get("score_inbound"), rec.get("score"))
55
+ else:
56
+ print("not found") # DB에 없는 IP
57
+ ```
58
+
59
+ `get(ip)`는 IP 레코드를 `dict`로 반환하며, DB에 없으면 `None`입니다.
60
+
61
+ ## 반환 필드 (예시)
62
+
63
+ | 필드 | 설명 |
64
+ |---|---|
65
+ | `country_code`, `as_name` | 지리/AS 정보 |
66
+ | `is_vpn`·`is_tor`·`is_proxy`·`is_hosting`·`is_cloud`·`is_mobile` | etcs 태그 |
67
+ | `score`·`score_inbound` | outbound/inbound 위협 점수 (0–5) |
68
+ | `is_c2`, `abuse_record`, `ssl_cn` | 부가 신호 |
69
+
70
+ ## 지원 포맷
71
+
72
+ - **v2 (columnar)** — 현행 col 레이아웃
73
+ - **v3** — L2 bitmap / cold record (`[fast]` extras 권장)
74
+ - v1.x range-table 레이아웃도 하위호환 읽기 지원
75
+
76
+ ## 라이선스
77
+
78
+ Apache-2.0 · © AI Spera
@@ -0,0 +1,9 @@
1
+ ctidb_bin/__init__.py,sha256=aQh2n00Pl8TIDt6C18sKfa801kJbHntXF9oa5wPRh64,379
2
+ ctidb_bin/format.py,sha256=q0F8KuBab1OtNnsELUp_CsW2V07ZArlmqZJ7uTx0JMI,8130
3
+ ctidb_bin/name_table.py,sha256=NTFT8PjPv8wvbQGlE1YryViM7bnoCK0IK0QZPFsIMF4,3085
4
+ ctidb_bin/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ ctidb_bin/reader.py,sha256=PJgyJmk6n2Fw_q6vd0EjOWJZjYMDuurkPQeXVw1XRV8,13542
6
+ ctidb_bin-0.0.1.dist-info/METADATA,sha256=By10ySYLomVF44WPNnu9yJL5l_Hwieufx6t-O97plmc,2453
7
+ ctidb_bin-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
8
+ ctidb_bin-0.0.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ ctidb_bin-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.