Last active
December 9, 2015 23:38
-
-
Save gdugas/4345360 to your computer and use it in GitHub Desktop.
return a absolute path jailed in a rootpath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
""" | |
return a absolute path jailed in a rootpath | |
example: | |
securejoin('/home/john/', 'path1/../../path2') | |
> /home/john/path2 | |
""" | |
def securejoin(rootpath, path): | |
path = os.path.join(path).split('/') | |
safe = [] | |
for i in range(len(path)): | |
if path[i] == '' or path[i] == '.': | |
continue | |
elif path[i] == '..': | |
if len(safe) > 0: | |
safe.pop() | |
else: | |
continue | |
else: | |
safe.append(path[i]) | |
return os.path.join(rootpath, '/'.join(safe)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment