ArchiveManager.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /* eslint-disable
  2. node/handle-callback-err,
  3. max-len,
  4. no-return-assign,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS101: Remove unnecessary use of Array.from
  11. * DS102: Remove unnecessary code created because of implicit returns
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. const logger = require('logger-sharelatex')
  16. const OError = require('@overleaf/o-error')
  17. const metrics = require('@overleaf/metrics')
  18. const fs = require('fs')
  19. const Path = require('path')
  20. const fse = require('fs-extra')
  21. const yauzl = require('yauzl')
  22. const Settings = require('@overleaf/settings')
  23. const {
  24. InvalidZipFileError,
  25. EmptyZipFileError,
  26. ZipContentsTooLargeError,
  27. } = require('./ArchiveErrors')
  28. const _ = require('underscore')
  29. const { promisifyAll } = require('../../util/promises')
  30. const ONE_MEG = 1024 * 1024
  31. const ArchiveManager = {
  32. _isZipTooLarge(source, callback) {
  33. if (callback == null) {
  34. callback = function () {}
  35. }
  36. callback = _.once(callback)
  37. let totalSizeInBytes = null
  38. return yauzl.open(source, { lazyEntries: true }, function (err, zipfile) {
  39. if (err != null) {
  40. return callback(new InvalidZipFileError().withCause(err))
  41. }
  42. if (
  43. Settings.maxEntitiesPerProject != null &&
  44. zipfile.entryCount > Settings.maxEntitiesPerProject
  45. ) {
  46. return callback(null, true) // too many files in zip file
  47. }
  48. zipfile.on('error', callback)
  49. // read all the entries
  50. zipfile.readEntry()
  51. zipfile.on('entry', function (entry) {
  52. totalSizeInBytes += entry.uncompressedSize
  53. return zipfile.readEntry()
  54. }) // get the next entry
  55. // no more entries to read
  56. return zipfile.on('end', function () {
  57. if (totalSizeInBytes == null || isNaN(totalSizeInBytes)) {
  58. logger.warn(
  59. { source, totalSizeInBytes },
  60. 'error getting bytes of zip'
  61. )
  62. return callback(
  63. new InvalidZipFileError({ info: { totalSizeInBytes } })
  64. )
  65. }
  66. const isTooLarge = totalSizeInBytes > ONE_MEG * 300
  67. return callback(null, isTooLarge)
  68. })
  69. })
  70. },
  71. _checkFilePath(entry, destination, callback) {
  72. // transform backslashes to forwardslashes to accommodate badly-behaved zip archives
  73. if (callback == null) {
  74. callback = function () {}
  75. }
  76. const transformedFilename = entry.fileName.replace(/\\/g, '/')
  77. // check if the entry is a directory
  78. const endsWithSlash = /\/$/
  79. if (endsWithSlash.test(transformedFilename)) {
  80. return callback() // don't give a destfile for directory
  81. }
  82. // check that the file does not use a relative path
  83. for (const dir of Array.from(transformedFilename.split('/'))) {
  84. if (dir === '..') {
  85. return callback(new Error('relative path'))
  86. }
  87. }
  88. // check that the destination file path is normalized
  89. const dest = `${destination}/${transformedFilename}`
  90. if (dest !== Path.normalize(dest)) {
  91. return callback(new Error('unnormalized path'))
  92. } else {
  93. return callback(null, dest)
  94. }
  95. },
  96. _writeFileEntry(zipfile, entry, destFile, callback) {
  97. if (callback == null) {
  98. callback = function () {}
  99. }
  100. callback = _.once(callback)
  101. return zipfile.openReadStream(entry, function (err, readStream) {
  102. if (err != null) {
  103. return callback(err)
  104. }
  105. readStream.on('error', callback)
  106. readStream.on('end', callback)
  107. const errorHandler = function (err) {
  108. // clean up before calling callback
  109. readStream.unpipe()
  110. readStream.destroy()
  111. return callback(err)
  112. }
  113. return fse.ensureDir(Path.dirname(destFile), function (err) {
  114. if (err != null) {
  115. return errorHandler(err)
  116. }
  117. const writeStream = fs.createWriteStream(destFile)
  118. writeStream.on('error', errorHandler)
  119. return readStream.pipe(writeStream)
  120. })
  121. })
  122. },
  123. _extractZipFiles(source, destination, callback) {
  124. if (callback == null) {
  125. callback = function () {}
  126. }
  127. callback = _.once(callback)
  128. return yauzl.open(source, { lazyEntries: true }, function (err, zipfile) {
  129. if (err != null) {
  130. return callback(err)
  131. }
  132. zipfile.on('error', callback)
  133. // read all the entries
  134. zipfile.readEntry()
  135. let entryFileCount = 0
  136. zipfile.on('entry', function (entry) {
  137. return ArchiveManager._checkFilePath(
  138. entry,
  139. destination,
  140. function (err, destFile) {
  141. if (err != null) {
  142. logger.warn(
  143. { err, source, destination },
  144. 'skipping bad file path'
  145. )
  146. zipfile.readEntry() // bad path, just skip to the next file
  147. return
  148. }
  149. if (destFile != null) {
  150. // only write files
  151. return ArchiveManager._writeFileEntry(
  152. zipfile,
  153. entry,
  154. destFile,
  155. function (err) {
  156. if (err != null) {
  157. OError.tag(err, 'error unzipping file entry', {
  158. source,
  159. destFile,
  160. })
  161. zipfile.close() // bail out, stop reading file entries
  162. return callback(err)
  163. } else {
  164. entryFileCount++
  165. return zipfile.readEntry()
  166. }
  167. }
  168. ) // continue to the next file
  169. } else {
  170. // if it's a directory, continue
  171. return zipfile.readEntry()
  172. }
  173. }
  174. )
  175. })
  176. // no more entries to read
  177. return zipfile.on('end', () => {
  178. if (entryFileCount > 0) {
  179. callback()
  180. } else {
  181. callback(new EmptyZipFileError())
  182. }
  183. })
  184. })
  185. },
  186. extractZipArchive(source, destination, _callback) {
  187. if (_callback == null) {
  188. _callback = function () {}
  189. }
  190. const callback = function (...args) {
  191. _callback(...Array.from(args || []))
  192. return (_callback = function () {})
  193. }
  194. return ArchiveManager._isZipTooLarge(source, function (err, isTooLarge) {
  195. if (err != null) {
  196. OError.tag(err, 'error checking size of zip file')
  197. return callback(err)
  198. }
  199. if (isTooLarge) {
  200. return callback(new ZipContentsTooLargeError())
  201. }
  202. const timer = new metrics.Timer('unzipDirectory')
  203. logger.log({ source, destination }, 'unzipping file')
  204. return ArchiveManager._extractZipFiles(
  205. source,
  206. destination,
  207. function (err) {
  208. timer.done()
  209. if (err != null) {
  210. OError.tag(err, 'unzip failed', {
  211. source,
  212. destination,
  213. })
  214. return callback(err)
  215. } else {
  216. return callback()
  217. }
  218. }
  219. )
  220. })
  221. },
  222. findTopLevelDirectory(directory, callback) {
  223. if (callback == null) {
  224. callback = function () {}
  225. }
  226. return fs.readdir(directory, function (error, files) {
  227. if (error != null) {
  228. return callback(error)
  229. }
  230. if (files.length === 1) {
  231. const childPath = Path.join(directory, files[0])
  232. return fs.stat(childPath, function (error, stat) {
  233. if (error != null) {
  234. return callback(error)
  235. }
  236. if (stat.isDirectory()) {
  237. return callback(null, childPath)
  238. } else {
  239. return callback(null, directory)
  240. }
  241. })
  242. } else {
  243. return callback(null, directory)
  244. }
  245. })
  246. },
  247. }
  248. ArchiveManager.promises = promisifyAll(ArchiveManager)
  249. module.exports = ArchiveManager