index.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /*
  2. Copyright 2016 Mark Lee
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. 'use strict'
  14. const debug = require('debug')('sumchecker')
  15. const crypto = require('crypto')
  16. const fs = require('fs')
  17. const path = require('path')
  18. const Promise = global.Promise || require('es6-promise').Promise
  19. const CHECKSUM_LINE = /^([\da-fA-F]+) ([ *])(.+)$/
  20. class ErrorWithFilename extends Error {
  21. constructor (filename) {
  22. super()
  23. this.filename = filename
  24. }
  25. }
  26. class ChecksumMismatchError extends ErrorWithFilename {
  27. constructor (filename) {
  28. super(filename)
  29. this.message = `Generated checksum for "${filename}" did not match expected checksum.`
  30. }
  31. }
  32. class ChecksumParseError extends Error {
  33. constructor (lineNumber, line) {
  34. super()
  35. this.lineNumber = lineNumber
  36. this.line = line
  37. this.message = `Could not parse checksum file at line ${lineNumber}: ${line}`
  38. }
  39. }
  40. class NoChecksumFoundError extends ErrorWithFilename {
  41. constructor (filename) {
  42. super(filename)
  43. this.message = `No checksum found in checksum file for "${filename}".`
  44. }
  45. }
  46. class ChecksumValidator {
  47. constructor (algorithm, checksumFilename, options) {
  48. this.algorithm = algorithm
  49. this.checksumFilename = checksumFilename
  50. this.checksums = null
  51. if (options && options.defaultTextEncoding) {
  52. this.defaultTextEncoding = options.defaultTextEncoding
  53. } else {
  54. this.defaultTextEncoding = 'utf8'
  55. }
  56. }
  57. encoding (binary) {
  58. return binary ? 'binary' : this.defaultTextEncoding
  59. }
  60. parseChecksumFile (data) {
  61. let that = this
  62. return new Promise((resolve, reject) => {
  63. debug('Parsing checksum file')
  64. that.checksums = {}
  65. let lineNumber = 0
  66. data.trim().split(/[\r\n]+/).forEach(line => {
  67. lineNumber += 1
  68. let result = CHECKSUM_LINE.exec(line)
  69. if (result === null) {
  70. debug(`Could not parse line number ${lineNumber}`)
  71. reject(new ChecksumParseError(lineNumber, line))
  72. } else {
  73. // destructuring isn't available until Node 6
  74. let filename = result[3]
  75. let isBinary = result[2] === '*'
  76. let checksum = result[1]
  77. that.checksums[filename] = [checksum, isBinary]
  78. }
  79. })
  80. debug('Parsed checksums:', that.checksums)
  81. resolve()
  82. })
  83. }
  84. readFile (filename, binary) {
  85. debug(`Reading "${filename} (binary mode: ${binary})"`)
  86. return new Promise((resolve, reject) => {
  87. fs.readFile(filename, this.encoding(binary), (err, data) => {
  88. if (err) {
  89. reject(err)
  90. } else {
  91. resolve(data)
  92. }
  93. })
  94. })
  95. }
  96. validate (baseDir, filesToCheck) {
  97. if (typeof filesToCheck === 'string') {
  98. filesToCheck = [filesToCheck]
  99. }
  100. return this.readFile(this.checksumFilename, false)
  101. .then(this.parseChecksumFile.bind(this))
  102. .then(() => {
  103. return this.validateFiles(baseDir, filesToCheck)
  104. })
  105. }
  106. validateFile (baseDir, filename) {
  107. return new Promise((resolve, reject) => {
  108. debug(`validateFile: ${filename}`)
  109. let metadata = this.checksums[filename]
  110. if (!metadata) {
  111. return reject(new NoChecksumFoundError(filename))
  112. }
  113. // destructuring isn't available until Node 6
  114. let checksum = metadata[0]
  115. let binary = metadata[1]
  116. let fullPath = path.resolve(baseDir, filename)
  117. debug(`Reading file with "${this.encoding(binary)}" encoding`)
  118. let stream = fs.createReadStream(fullPath, {encoding: this.encoding(binary)})
  119. let hasher = crypto.createHash(this.algorithm, {defaultEncoding: 'binary'})
  120. hasher.on('readable', () => {
  121. let data = hasher.read()
  122. if (data) {
  123. let calculated = data.toString('hex')
  124. debug(`Expected checksum: ${checksum}; Actual: ${calculated}`)
  125. if (calculated === checksum) {
  126. resolve()
  127. } else {
  128. reject(new ChecksumMismatchError(filename))
  129. }
  130. }
  131. })
  132. stream.pipe(hasher)
  133. })
  134. }
  135. validateFiles (baseDir, filesToCheck) {
  136. let that = this
  137. return Promise.all(filesToCheck.map((filename) => {
  138. return that.validateFile(baseDir, filename)
  139. }))
  140. }
  141. }
  142. let sumchecker = function sumchecker (algorithm, checksumFilename, baseDir, filesToCheck) {
  143. return new ChecksumValidator(algorithm, checksumFilename).validate(baseDir, filesToCheck)
  144. }
  145. sumchecker.ChecksumMismatchError = ChecksumMismatchError
  146. sumchecker.ChecksumParseError = ChecksumParseError
  147. sumchecker.ChecksumValidator = ChecksumValidator
  148. sumchecker.NoChecksumFoundError = NoChecksumFoundError
  149. module.exports = sumchecker