Blob Blame History Raw
From ef2e21690c5072fda8cdb30f87225e0fa6ee4fb0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Zbigniew=20J=C4=99drzejewski-Szmek?= <zbyszek@in.waw.pl>
Date: Thu, 2 Jul 2015 12:35:14 -0400
Subject: [PATCH] Do not use a predicatable directory name for the scratch dir

If the user did not configure a scratch dir, /tmp/music21 would be
used if it exists. Unfortunately this allows other users of the
machine to trick music21 into writing into an arbitrary directory on
the filesystem, and to access and overwrite arbitrary files,
by precreating the directory.

Under Python 2 the behaviour will be similar to before: temporary
directory will not be deleted. Under Python 3 it will be deleted
when the module is destroyed.
---
 music21/environment.py | 27 ++++++++++++++-------------
 1 file changed, 14 insertions(+), 13 deletions(-)

diff --git a/music21/environment.py b/music21/environment.py
index bf9416a3d5..3f0ef7e9d1 100644
--- a/music21/environment.py
+++ b/music21/environment.py
@@ -97,6 +97,7 @@ class _EnvironmentCore(object):
         self._ref = {}
         # define all settings that are paths
         # store names of all values that are keys; check for validity
+        self._roottmpdir = None
         self._keysToPaths = []
         self._keysToPaths.append('braillePath')
         self._keysToPaths.append('graphicsPath')
@@ -378,21 +379,21 @@ class _EnvironmentCore(object):
 
         >>> import os
         >>> e = environment.Environment()
-        >>> e.getDefaultRootTempDir() == os.path.join(t, 'music21')
-        True
+        >>> t = e.getDefaultRootTempDir()
+        >>> #_DOCS_SHOW t
+        '/var/folders/x5/rymq2tx16lqbpytwb1n_cc4c0000gn/T/music21-426ypie'
         '''
-        # this returns the root temp dir; this does not create a new dir
-        dstDir = os.path.join(tempfile.gettempdir(), 'music21')
-        # if this path already exists, we have nothing more to do
-        if os.path.exists(dstDir):
-            return dstDir
-        else:
-            # make this directory as a temp directory
+        if not self._roottmpdir:
             try:
-                os.mkdir(dstDir)
-            except OSError:  # cannot make the directory
-                dstDir = tempfile.gettempdir()
-            return dstDir
+                # This creates a new temporary directory which will be removed
+                # when the returned object is deleted.
+                self._roottmpdir_object = tempfile.TemporaryDirectory(prefix='music21-')
+                self._roottmpdir = self._roottmpdir_object.name
+            except AttributeError:
+                # Python 2.x
+                # The directory will not be deleted afterwards.
+                self._roottmpdir = tempfile.mkdtemp(prefix='music21-')
+        return self._roottmpdir
 
     def getKeysToPaths(self):
         '''
-- 
2.5.0