Skip to content

Commit

Permalink
[fix] SQLiteIndexedTar: Avoid resource leak when constructor fails
Browse files Browse the repository at this point in the history
  • Loading branch information
mxmlnkn committed Oct 19, 2024
1 parent c8d1eb5 commit 7696280
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions core/ratarmountcore/SQLiteIndexedTar.py
Original file line number Diff line number Diff line change
Expand Up @@ -708,8 +708,10 @@ def __init__(
self._fileNameIsURL = re.match('[A-Za-z0-9]*://', self.tarFileName) is not None

# If no fileObject given, then self.tarFileName is the path to the archive to open.
self._fileObjectsToCloseOnDel: List[IO[bytes]] = []
if not fileObject:
fileObject = open(self.tarFileName, 'rb')
self._fileObjectsToCloseOnDel.append(fileObject)
fileObject.seek(0, io.SEEK_END)
fileSize = fileObject.tell()
fileObject.seek(0) # Even if not interested in the file size, seeking to the start might be useful.
Expand All @@ -729,10 +731,7 @@ def __init__(
printDebug=self.printDebug,
)
if not self.isTar and not self.rawFileObject:
fileObjectInfo = str(fileObject)
if not self.isFileObject:
fileObject.close()
raise RatarmountError(f"File object ({fileObjectInfo}) could not be opened as a TAR file!")
raise RatarmountError(f"File object ({str(fileObject)}) could not be opened as a TAR file!")

self.blockSize = 512
if self.rawFileObject:
Expand Down Expand Up @@ -859,6 +858,15 @@ def __init__(
"and is sized", os.stat( self.index.indexFilePath ).st_size, "B")
# fmt: on

def __del__(self):
if hasattr(self, '_fileObjectsToCloseOnDel'):
for fileObject in self._fileObjectsToCloseOnDel:
close = getattr(fileObject, 'close', None)
if close and callable(close):
close()
if hasattr(super(), '__del__'):
super().__del__()

def _detectGnuIncremental(self, fileObject: Any) -> bool:
"""Check for GNU incremental backup TARs."""
oldPos = fileObject.tell()
Expand Down

0 comments on commit 7696280

Please sign in to comment.