ArchiveManager.mjs 7.8 KB

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