diff --git a/index.js b/index.js index 8e33bbd0..2a5d5a74 100644 --- a/index.js +++ b/index.js @@ -4,6 +4,7 @@ var assert = require('assert'); var fs = require('fs'); var Reader = require('./lib/reader'); var ip = require('./lib/ip'); +var isGzip = require('./lib/is-gzip'); var utils = require('./lib/utils'); exports.Reader = Reader; @@ -15,6 +16,9 @@ exports.open = function(filepath, opts, cb) { fs.readFile(filepath, function(err, database) { if (err) return cb(err); + if (isGzip(database)) { + return cb(new Error('Looks like you are passing in a file in gzip format, please use mmdb database instead.')); + } var reader = new Reader(database, opts); if (opts && !!opts.watchForUpdates) { fs.watch(filepath, function() { diff --git a/lib/is-gzip.js b/lib/is-gzip.js new file mode 100644 index 00000000..dd648231 --- /dev/null +++ b/lib/is-gzip.js @@ -0,0 +1,9 @@ +'use strict'; + +module.exports = function(buf) { + if (!buf || buf.length < 3) { + return false; + } + + return buf[0] === 0x1f && buf[1] === 0x8b && buf[2] === 0x08; +}; diff --git a/test/databases/GeoIP2-City-Test.mmdb.gz b/test/databases/GeoIP2-City-Test.mmdb.gz new file mode 100644 index 00000000..1c769071 Binary files /dev/null and b/test/databases/GeoIP2-City-Test.mmdb.gz differ diff --git a/test/index.js b/test/index.js index 441f8ed6..ddfc9214 100644 --- a/test/index.js +++ b/test/index.js @@ -84,6 +84,15 @@ describe('index', function() { }, /Callback function must be provided/); }); + it('should return an error when gzip file attempted', function(done) { + var dbPath = path.join(__dirname, 'databases/GeoIP2-City-Test.mmdb.gz'); + maxmind.open(dbPath, function(err) { + assert.equal(err.message, + 'Looks like you are passing in a file in gzip format, please use mmdb database instead.'); + done(); + }); + }); + it('should check for an error when cannot read database on update', function(done) { var counter = 0; var cb = function(err, reader) { diff --git a/test/is-gzip.js b/test/is-gzip.js new file mode 100644 index 00000000..d2c74fda --- /dev/null +++ b/test/is-gzip.js @@ -0,0 +1,21 @@ +'use strict'; + +var assert = require('assert'); +var isGzip = require('../lib/is-gzip'); + +describe('lib/is-gzip', function() { + it('should return false for short buffers', function() { + assert.equal(isGzip(new Buffer([1, 2])), false); + }); + + it('should return false for string buffer', function() { + assert.equal(isGzip(new Buffer('kraken')), false); + }); + + it('should return false for string buffer', function() { + // gzipped "kraken" string + // shell: `echo "kraken" | gzip | base64` + var buffer = new Buffer('H4sIAGBDv1gAA8suSsxOzeMCAKjj9U8HAAAA', 'base64'); + assert.equal(isGzip(buffer), true); + }); +});