Skip to content

Commit

Permalink
#2305 Ensure file is closed
Browse files Browse the repository at this point in the history
  • Loading branch information
To-om committed Jan 24, 2022
1 parent 5e42814 commit 226a60b
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
2 changes: 1 addition & 1 deletion ScalliGraph
16 changes: 11 additions & 5 deletions thehive/app/org/thp/thehive/controllers/v0/AttachmentCtrl.scala
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@ import play.api.mvc._

import java.nio.file.Files
import javax.inject.{Inject, Singleton}
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Try}

@Singleton
class AttachmentCtrl @Inject() (
entrypoint: Entrypoint,
appConfig: ApplicationConfig,
attachmentSrv: AttachmentSrv,
db: Database
db: Database,
ec: ExecutionContext
) {
val forbiddenChar: Seq[Char] = Seq('/', '\n', '\r', '\t', '\u0000', '\f', '`', '?', '*', '\\', '<', '>', '|', '\"', ':', ';')

Expand Down Expand Up @@ -76,8 +78,12 @@ class AttachmentCtrl @Inject() (
zipParams.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD)
zipParams.setFileNameInZip(filename)
// zipParams.setSourceExternalStream(true)
zipFile.addStream(attachmentSrv.stream(attachment), zipParams)

val is = attachmentSrv.stream(attachment)
try zipFile.addStream(is, zipParams)
finally is.close()
val source = FileIO.fromPath(f).mapMaterializedValue { fut =>
fut.andThen { case _ => Files.delete(f) }(ec)
}
Result(
header = ResponseHeader(
200,
Expand All @@ -88,8 +94,8 @@ class AttachmentCtrl @Inject() (
"Content-Length" -> Files.size(f).toString
)
),
body = HttpEntity.Streamed(FileIO.fromPath(f), Some(Files.size(f)), Some("application/zip"))
) // FIXME remove temporary file (but when ?)
body = HttpEntity.Streamed(source, Some(Files.size(f)), Some("application/zip"))
)
}
}
.recoverWith {
Expand Down
5 changes: 4 additions & 1 deletion thehive/app/org/thp/thehive/services/AttachmentSrv.scala
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,10 @@ class AttachmentSrv @Inject() (configuration: Configuration, storageSrv: Storage
case Some(a) => (a.size, a.hashes)
case None =>
val s = storageSrv.getSize("attachment", attachmentId).getOrElse(throw NotFoundError(s"Attachment $attachmentId not found"))
val hs = hashers.fromInputStream(storageSrv.loadBinary("attachment", attachmentId))
val is = storageSrv.loadBinary("attachment", attachmentId)
val hs =
try hashers.fromInputStream(is)
finally is.close()
(s, hs)
}
createEntity(Attachment(filename, size, contentType, hashes, attachmentId))
Expand Down

0 comments on commit 226a60b

Please sign in to comment.