Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 29 additions & 31 deletions CadVlan/Util/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ def __str__(self):


class File():

BASE_PATH = os.path.abspath("./") # Define a base path

@staticmethod
def _sanitize_path(file_name):
'''
Create an absolute path and ensure it's within the BASE_PATH.
'''
abs_path = os.path.abspath(os.path.join(File.BASE_PATH, file_name))

if not abs_path.startswith(File.BASE_PATH):
raise FileError("Invalid file path")

return abs_path

@classmethod
def read(cls, file_name):
Expand All @@ -42,16 +56,10 @@ def read(cls, file_name):
:raise FileError: Failed to reading file
'''
try:

file_name = "./%s" % file_name

file_acl = open(file_name, "r")
content = file_acl.read()
file_acl.close()

return content

except Exception, e:
file_path = cls._sanitize_path(file_name)
with open(file_path, "r") as file_acl:
return file_acl.read()
except Exception as e:
logger.error(e)
raise FileError(e)

Expand All @@ -65,14 +73,10 @@ def write(cls, file_name, content):
:raise FileError: Failed to writing file
'''
try:

file_name = "./%s" % file_name

file_acl = open(file_name, "w")
file_acl.write(content)
file_acl.close()

except Exception, e:
file_path = cls._sanitize_path(file_name)
with open(file_path, "w") as file_acl:
file_acl.write(content)
except Exception as e:
logger.error(e)
raise FileError(e)

Expand All @@ -85,13 +89,10 @@ def create(cls, file_name):
:raise FileError: Failed to creating file
'''
try:

file_name = "./%s" % file_name

file_acl = open(file_name, "w")
file_acl.close()

except Exception, e:
file_path = cls._sanitize_path(file_name)
with open(file_path, "w") as file_acl:
pass
except Exception as e:
logger.error(e)
raise FileError(e)

Expand All @@ -104,11 +105,8 @@ def remove(cls, file_name):
:raise FileError: Failed to removing file
'''
try:

file_name = "./%s" % file_name

erro = os.system("rm %s" % file_name)

except Exception, e:
file_path = cls._sanitize_path(file_name)
os.remove(file_path) # Use os.remove() instead of unsafe os.system()
except Exception as e:
logger.error(e)
raise FileError(e)