From 7a1b68ec2be737193bd9edee3ce3d935531ecf2e Mon Sep 17 00:00:00 2001 From: 5saviahv <49443574+5saviahv@users.noreply.github.com> Date: Thu, 27 Jun 2024 12:43:19 +0300 Subject: [PATCH] make all errors a function (#517) Co-authored-by: 5saviahv <5saviahv@users.noreply.github.com> --- adm-zip.js | 33 ++++++------ headers/entryHeader.js | 4 +- headers/mainHeader.js | 2 +- methods/zipcrypto.js | 3 +- .../large_directory_size.test.js | 3 +- util/errors.js | 37 ++++++++++++-- util/utils.js | 2 +- zipEntry.js | 51 ++++++++++--------- zipFile.js | 4 +- 9 files changed, 86 insertions(+), 53 deletions(-) diff --git a/adm-zip.js b/adm-zip.js index 97fdcce..4c5b9c8 100644 --- a/adm-zip.js +++ b/adm-zip.js @@ -59,7 +59,7 @@ module.exports = function (/**String*/ input, /** object */ options) { opts.filename = input; inBuffer = filetools.fs.readFileSync(input); } else { - throw new Error(Utils.Errors.INVALID_FILENAME); + throw Utils.Errors.INVALID_FILENAME(); } } @@ -316,7 +316,7 @@ module.exports = function (/**String*/ input, /** object */ options) { // add file into zip file this.addFile(zipPath, data, comment, _attr); } else { - throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); + throw Utils.Errors.FILE_NOT_FOUND(localPath); } }, @@ -398,7 +398,7 @@ module.exports = function (/**String*/ input, /** object */ options) { } } } else { - throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); + throw Utils.Errors.FILE_NOT_FOUND(localPath); } }, @@ -423,7 +423,7 @@ module.exports = function (/**String*/ input, /** object */ options) { var self = this; filetools.fs.open(localPath, "r", function (err) { if (err && err.code === "ENOENT") { - callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); + callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); } else if (err) { callback(undefined, err); } else { @@ -520,7 +520,7 @@ module.exports = function (/**String*/ input, /** object */ options) { filetools.fs.open(localPath, "r", function (err) { if (err && err.code === "ENOENT") { - callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); + callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath)); } else if (err) { callback(undefined, err); } else { @@ -675,7 +675,7 @@ module.exports = function (/**String*/ input, /** object */ options) { var item = getEntry(entry); if (!item) { - throw new Error(Utils.Errors.NO_ENTRY); + throw Utils.Errors.NO_ENTRY(); } var entryName = canonical(item.entryName); @@ -688,7 +688,7 @@ module.exports = function (/**String*/ input, /** object */ options) { if (child.isDirectory) return; var content = child.getData(); if (!content) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); + throw Utils.Errors.CANT_EXTRACT_FILE(); } var name = canonical(child.entryName); var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name)); @@ -700,10 +700,10 @@ module.exports = function (/**String*/ input, /** object */ options) { } var content = item.getData(_zip.password); - if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE); + if (!content) throw Utils.Errors.CANT_EXTRACT_FILE(); if (filetools.fs.existsSync(target) && !overwrite) { - throw new Error(Utils.Errors.CANT_OVERRIDE); + throw Utils.Errors.CANT_OVERRIDE(); } // The reverse operation for attr depend on method addFile() const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; @@ -751,9 +751,8 @@ module.exports = function (/**String*/ input, /** object */ options) { keepOriginalPermission = get_Bool(false, keepOriginalPermission); pass = get_Str(keepOriginalPermission, pass); overwrite = get_Bool(false, overwrite); - if (!_zip) { - throw new Error(Utils.Errors.NO_ZIP); - } + if (!_zip) throw Utils.Errors.NO_ZIP(); + _zip.entries.forEach(function (entry) { var entryName = sanitize(targetPath, canonical(entry.entryName)); if (entry.isDirectory) { @@ -762,7 +761,7 @@ module.exports = function (/**String*/ input, /** object */ options) { } var content = entry.getData(pass); if (!content) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); + throw Utils.Errors.CANT_EXTRACT_FILE(); } // The reverse operation for attr depend on method addFile() const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; @@ -770,7 +769,7 @@ module.exports = function (/**String*/ input, /** object */ options) { try { filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time); } catch (err) { - throw new Error(Utils.Errors.CANT_EXTRACT_FILE); + throw Utils.Errors.CANT_EXTRACT_FILE(); } }); }, @@ -801,7 +800,7 @@ module.exports = function (/**String*/ input, /** object */ options) { }); } if (!_zip) { - callback(new Error(Utils.Errors.NO_ZIP)); + callback(Utils.Errors.NO_ZIP()); return; } @@ -846,9 +845,9 @@ module.exports = function (/**String*/ input, /** object */ options) { const filePath = sanitize(targetPath, entryName); entry.getDataAsync(function (content, err_1) { if (err_1) { - next(new Error(err_1)); + next(err_1); } else if (!content) { - next(new Error(Utils.Errors.CANT_EXTRACT_FILE)); + next(Utils.Errors.CANT_EXTRACT_FILE()); } else { // The reverse operation for attr depend on method addFile() const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; diff --git a/headers/entryHeader.js b/headers/entryHeader.js index a44833e..48ecaed 100644 --- a/headers/entryHeader.js +++ b/headers/entryHeader.js @@ -212,7 +212,7 @@ module.exports = function () { var data = input.slice(_offset, _offset + Constants.LOCHDR); // 30 bytes and should start with "PK\003\004" if (data.readUInt32LE(0) !== Constants.LOCSIG) { - throw new Error(Utils.Errors.INVALID_LOC); + throw Utils.Errors.INVALID_LOC(); } // version needed to extract @@ -243,7 +243,7 @@ module.exports = function () { loadFromBinary: function (/*Buffer*/ data) { // data should be 46 bytes and start with "PK 01 02" if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) { - throw new Error(Utils.Errors.INVALID_CEN); + throw Utils.Errors.INVALID_CEN(); } // version made by _verMade = data.readUInt16LE(Constants.CENVEM); diff --git a/headers/mainHeader.js b/headers/mainHeader.js index ec430b1..bb3e8a3 100644 --- a/headers/mainHeader.js +++ b/headers/mainHeader.js @@ -56,7 +56,7 @@ module.exports = function () { (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG) ) { - throw new Error(Utils.Errors.INVALID_END); + throw Utils.Errors.INVALID_END(); } if (data.readUInt32LE(0) === Constants.ENDSIG) { diff --git a/methods/zipcrypto.js b/methods/zipcrypto.js index ec234ef..e1018f6 100644 --- a/methods/zipcrypto.js +++ b/methods/zipcrypto.js @@ -3,6 +3,7 @@ // node crypt, we use it for generate salt // eslint-disable-next-line node/no-unsupported-features/node-builtins const { randomFillSync } = require("crypto"); +const Errors = require("../util/errors"); // generate CRC32 lookup table const crctable = new Uint32Array(256).map((t, crc) => { @@ -124,7 +125,7 @@ function decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) { //3. does password meet expectations if (salt[11] !== verifyByte) { - throw "ADM-ZIP: Wrong Password"; + throw Errors.WRONG_PASSWORD(); } // 4. decode content diff --git a/test/large_directory_size/large_directory_size.test.js b/test/large_directory_size/large_directory_size.test.js index 1d896e2..fa2c547 100644 --- a/test/large_directory_size/large_directory_size.test.js +++ b/test/large_directory_size/large_directory_size.test.js @@ -3,6 +3,7 @@ const assert = require("assert"); const path = require("path"); const Zip = require("../../adm-zip"); +const Errors = require("../../util/errors"); describe("read zip file header with invalid large number of entries", () => { it("throws too large error", () => { @@ -11,6 +12,6 @@ describe("read zip file header with invalid large number of entries", () => { // assert that the following call throws an exception assert.throws(() => { zip.getEntries(); - }, new Error("Number of disk entries is too large")); + }, Errors.DISK_ENTRY_TOO_LARGE()); }); }); diff --git a/util/errors.js b/util/errors.js index b2bcafd..ad594ed 100644 --- a/util/errors.js +++ b/util/errors.js @@ -1,13 +1,18 @@ -module.exports = { +const errors = { /* Header error messages */ INVALID_LOC: "Invalid LOC header (bad signature)", INVALID_CEN: "Invalid CEN header (bad signature)", INVALID_END: "Invalid END header (bad signature)", + /* Descriptor */ + DESCRIPTOR_NOT_EXIST: "No descriptor present", + DESCRIPTOR_UNKNOWN: "Unknown descriptor format", + DESCRIPTOR_FAULTY: "Descriptor data is malformed", + /* ZipEntry error messages*/ NO_DATA: "Nothing to decompress", - BAD_CRC: "CRC32 checksum failed", - FILE_IN_THE_WAY: "There is a file in the way: %s", + BAD_CRC: "CRC32 checksum failed {0}", + FILE_IN_THE_WAY: "There is a file in the way: {0}", UNKNOWN_METHOD: "Invalid/unsupported compression method", /* Inflater error messages */ @@ -29,8 +34,30 @@ module.exports = { NO_ZIP: "No zip file was loaded", NO_ENTRY: "Entry doesn't exist", DIRECTORY_CONTENT_ERROR: "A directory cannot have content", - FILE_NOT_FOUND: "File not found: %s", + FILE_NOT_FOUND: 'File not found: "{0}"', NOT_IMPLEMENTED: "Not implemented", INVALID_FILENAME: "Invalid filename", - INVALID_FORMAT: "Invalid or unsupported zip format. No END header found" + INVALID_FORMAT: "Invalid or unsupported zip format. No END header found", + INVALID_PASS_PARAM: "Incompatible password parameter", + WRONG_PASSWORD: "Wrong Password", + + /* ADM-ZIP */ + COMMENT_TOO_LONG: "Comment is too long", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space) + EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error" }; + +// template +function E(message) { + return function (...args) { + if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number + message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || ''); + } + + return new Error('ADM-ZIP: ' + message); + }; +} + +// Init errors with template +for (const msg of Object.keys(errors)) { + exports[msg] = E(errors[msg]); +} diff --git a/util/utils.js b/util/utils.js index 368ca7c..dae14ea 100644 --- a/util/utils.js +++ b/util/utils.js @@ -51,7 +51,7 @@ Utils.prototype.makeDir = function (/*String*/ folder) { } catch (e) { self.fs.mkdirSync(resolvedPath); } - if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath); + if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`); }); } diff --git a/zipEntry.js b/zipEntry.js index 50082c2..39aed71 100644 --- a/zipEntry.js +++ b/zipEntry.js @@ -39,7 +39,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize; // no descriptor after compressed data, instead new local header if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) { - throw new Error("ADM-ZIP: No descriptor present"); + throw Utils.Errors.DESCRIPTOR_NOT_EXIST(); } // get decriptor data @@ -54,12 +54,12 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4); descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4); } else { - throw new Error("ADM-ZIP: Unknown descriptor format"); + throw Utils.Errors.DESCRIPTOR_UNKNOWN(); } // check data integrity if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) { - throw new Error("ADM-ZIP: Descriptor data is malformed"); + throw Utils.Errors.DESCRIPTOR_FAULTY(); } if (Utils.crc32(data) !== descriptor.crc) { return false; @@ -80,7 +80,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { } if (_isDirectory) { if (async && callback) { - callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error. + callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error. } return Buffer.alloc(0); } @@ -95,7 +95,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { if (_centralHeader.encrypted) { if ("string" !== typeof pass && !Buffer.isBuffer(pass)) { - throw new Error("ADM-ZIP: Incompatible password parameter"); + throw Utils.Errors.INVALID_PASS_PARAM(); } compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass); } @@ -106,8 +106,8 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { case Utils.Constants.STORED: compressedData.copy(data); if (!crc32OK(data)) { - if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error - throw new Error(Utils.Errors.BAD_CRC); + if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error + throw Utils.Errors.BAD_CRC(); } else { //si added otherwise did not seem to return data. if (async && callback) callback(data); @@ -119,7 +119,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { const result = inflater.inflate(data); result.copy(data, 0); if (!crc32OK(data)) { - throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString()); + throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`); } return data; } else { @@ -127,7 +127,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { result.copy(result, 0); if (callback) { if (!crc32OK(result)) { - callback(result, Utils.Errors.BAD_CRC); //si added error + callback(result, Utils.Errors.BAD_CRC()); //si added error } else { callback(result); } @@ -136,8 +136,8 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { } break; default: - if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD); - throw new Error(Utils.Errors.UNKNOWN_METHOD); + if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD()); + throw Utils.Errors.UNKNOWN_METHOD(); } } @@ -190,18 +190,22 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { } function parseExtra(data) { - var offset = 0; - var signature, size, part; - while (offset < data.length) { - signature = data.readUInt16LE(offset); - offset += 2; - size = data.readUInt16LE(offset); - offset += 2; - part = data.slice(offset, offset + size); - offset += size; - if (Constants.ID_ZIP64 === signature) { - parseZip64ExtendedInformation(part); + try { + var offset = 0; + var signature, size, part; + while (offset < data.length) { + signature = data.readUInt16LE(offset); + offset += 2; + size = data.readUInt16LE(offset); + offset += 2; + part = data.slice(offset, offset + size); + offset += size; + if (Constants.ID_ZIP64 === signature) { + parseZip64ExtendedInformation(part); + } } + } catch (error) { + throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR(); } } @@ -272,10 +276,11 @@ module.exports = function (/** object */ options, /*Buffer*/ input) { set comment(val) { _comment = Utils.toBuffer(val, decoder.encode); _centralHeader.commentLength = _comment.length; + if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG(); }, get name() { - var n = _entryName.toString(); + var n = decoder.decode(_entryName); return _isDirectory ? n .substr(n.length - 1) diff --git a/zipFile.js b/zipFile.js index 43e69fe..6b277bc 100644 --- a/zipFile.js +++ b/zipFile.js @@ -56,7 +56,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { loadedEntries = true; entryTable = {}; if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) { - throw new Error(Utils.Errors.DISK_ENTRY_TOO_LARGE); + throw Utils.Errors.DISK_ENTRY_TOO_LARGE(); } entryList = new Array(mainHeader.diskEntries); // total number of entries var index = mainHeader.offset; // offset of first CEN header @@ -120,7 +120,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) { } } - if (endOffset == -1) throw new Error(Utils.Errors.INVALID_FORMAT); + if (endOffset == -1) throw Utils.Errors.INVALID_FORMAT(); mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart)); if (mainHeader.commentLength) {