Skip to content

Commit

Permalink
Issue #5480 - Safer temp directory management
Browse files Browse the repository at this point in the history
Signed-off-by: Joakim Erdfelt <joakim.erdfelt@gmail.com>
  • Loading branch information
joakime committed Oct 20, 2020
1 parent 6be6fae commit c7ae5b5
Showing 1 changed file with 22 additions and 4 deletions.
Expand Up @@ -354,8 +354,10 @@ public void configure(WebAppContext context) throws Exception
@Override
public void deconfigure(WebAppContext context) throws Exception
{
//if we're not persisting the temp dir contents delete it
if (!context.isPersistTempDirectory() && context.getTempDirectory() != null && context.getTempDirectory().exists())
File tempDirectory = context.getTempDirectory();

// if we're not persisting the temp dir contents delete it
if (!context.isPersistTempDirectory() && tempDirectory != null && tempDirectory.exists())
{
IO.delete(context.getTempDirectory());
}
Expand Down Expand Up @@ -504,13 +506,15 @@ public void makeTempDirectory(File parent, WebAppContext context)
//if it is to be persisted, make sure it will be the same name
//by not using File.createTempFile, which appends random digits
tmpDir = new File(parent, temp);
configureTempDirectory(tmpDir, context);
}
else
{
//ensure file will always be unique by appending random digits
// ensure dir will always be unique by having classlib generate random path name
tmpDir = Files.createTempDirectory(parent.toPath(), temp).toFile();
tmpDir.deleteOnExit();
ensureTempDirUsable(tmpDir);
}
configureTempDirectory(tmpDir, context);

if (LOG.isDebugEnabled())
LOG.debug("Set temp dir " + tmpDir);
Expand All @@ -522,6 +526,12 @@ public void configureTempDirectory(File dir, WebAppContext context)
if (dir == null)
throw new IllegalArgumentException("Null temp dir");

// if dir exists and we don't want it persisted, delete it
if (!context.isPersistTempDirectory() && dir.exists() && !IO.delete(dir))
{
throw new IllegalStateException("Failed to delete temp dir " + dir);
}

// if it doesn't exist make it
if (!dir.exists())
{
Expand All @@ -531,6 +541,14 @@ public void configureTempDirectory(File dir, WebAppContext context)
}
}

if (!context.isPersistTempDirectory())
dir.deleteOnExit();

ensureTempDirUsable(dir);
}

private void ensureTempDirUsable(File dir)
{
// is it useable
if (!dir.canWrite() || !dir.isDirectory())
throw new IllegalStateException("Temp dir " + dir + " not useable: writeable=" + dir.canWrite() + ", dir=" + dir.isDirectory());
Expand Down

0 comments on commit c7ae5b5

Please sign in to comment.