Skip to content

Commit

Permalink
make all errors a function (#517)
Browse files Browse the repository at this point in the history
Co-authored-by: 5saviahv <5saviahv@users.noreply.github.com>
  • Loading branch information
5saviahv and 5saviahv authored Jun 27, 2024
1 parent d59de3e commit 7a1b68e
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 53 deletions.
33 changes: 16 additions & 17 deletions adm-zip.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}

Expand Down Expand Up @@ -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);
}
},

Expand Down Expand Up @@ -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);
}
},

Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
Expand All @@ -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));
Expand All @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -762,15 +761,15 @@ 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;
filetools.writeFileTo(entryName, content, overwrite, fileAttr);
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();
}
});
},
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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;
Expand Down
4 changes: 2 additions & 2 deletions headers/entryHeader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion headers/mainHeader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
3 changes: 2 additions & 1 deletion methods/zipcrypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion test/large_directory_size/large_directory_size.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand All @@ -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());
});
});
37 changes: 32 additions & 5 deletions util/errors.js
Original file line number Diff line number Diff line change
@@ -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 */
Expand All @@ -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]);
}
2 changes: 1 addition & 1 deletion util/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}"`);
});
}

Expand Down
51 changes: 28 additions & 23 deletions zipEntry.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand All @@ -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);
}
Expand All @@ -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);
}
Expand All @@ -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);
Expand All @@ -119,15 +119,15 @@ 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 {
inflater.inflateAsync(function (result) {
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);
}
Expand All @@ -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();
}
}

Expand Down Expand Up @@ -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();
}
}

Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions zipFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit 7a1b68e

Please sign in to comment.