mmdb-lib
Version:
Maxmind DB (MMDB) Library
58 lines (57 loc) • 2.41 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isLegacyFormat = exports.parseMetadata = void 0;
const decoder_1 = __importDefault(require("./decoder"));
const utils_1 = __importDefault(require("./utils"));
const METADATA_START_MARKER = Buffer.from('ABCDEF4D61784D696E642E636F6D', 'hex');
const parseMetadata = (db) => {
const offset = findStart(db);
const decoder = new decoder_1.default(db, offset);
const metadata = decoder.decode(offset).value;
if (!metadata) {
throw new Error((0, exports.isLegacyFormat)(db)
? utils_1.default.legacyErrorMessage
: 'Cannot parse binary database');
}
utils_1.default.assert([24, 28, 32].indexOf(metadata.record_size) > -1, 'Unsupported record size');
return {
binaryFormatMajorVersion: metadata.binary_format_major_version,
binaryFormatMinorVersion: metadata.binary_format_minor_version,
buildEpoch: new Date(Number(metadata.build_epoch) * 1000),
databaseType: metadata.database_type,
description: metadata.description,
ipVersion: metadata.ip_version,
languages: metadata.languages,
nodeByteSize: metadata.record_size / 4,
nodeCount: metadata.node_count,
recordSize: metadata.record_size,
searchTreeSize: (metadata.node_count * metadata.record_size) / 4,
// Depth depends on the IP version, it's 32 for IPv4 and 128 for IPv6.
treeDepth: Math.pow(2, metadata.ip_version + 1),
};
};
exports.parseMetadata = parseMetadata;
const findStart = (db) => {
let found = 0;
let fsize = db.length - 1;
const mlen = METADATA_START_MARKER.length - 1;
while (found <= mlen && fsize-- > 0) {
found += db[fsize] === METADATA_START_MARKER[mlen - found] ? 1 : -found;
}
return fsize + found;
};
const isLegacyFormat = (db) => {
const structureInfoMaxSize = 20;
for (let i = 0; i < structureInfoMaxSize; i++) {
const delim = db.slice(db.length - 3 - i, db.length - i);
// Look for [0xff, 0xff, 0xff] metadata delimiter
if (delim[0] === 255 && delim[1] === 255 && delim[2] === 255) {
return true;
}
}
return false;
};
exports.isLegacyFormat = isLegacyFormat;