def openPersistenceFile(fileName, flags): """This function opens the given persistence file. When O_CREAT was specified, the function will attempt to create the directories too.""" if isinstance(fileName, str): fileName = fileName.encode() try: fd = SecureOSFunctions.secureOpenFile(fileName, flags) return fd except OSError as openOsError: if ((flags&os.O_CREAT) == 0) or (openOsError.errno != errno.ENOENT): raise openOsError # Find out, which directory is missing by stating our way up. dirNameLength = fileName.rfind(b'/') if dirNameLength > 0: os.makedirs(fileName[:dirNameLength]) return SecureOSFunctions.secureOpenFile(fileName, flags)
def open(self, reopenFlag=False): """Open the given resource. @param reopenFlag when True, attempt to reopen the same resource and check if it differs from the previously opened one. @raise Exception if valid logStreamFd was already provided, is still open and reopenFlag is False. @raise OSError when opening failed with unexpected error. @return True if the resource was really opened or False if opening was not yet possible but should be attempted again.""" if not reopenFlag and (self.logFileFd != -1): raise Exception( 'Cannot reopen stream still open when not instructed to do so') logFileFd = -1 statData = None try: logFileFd = SecureOSFunctions.secureOpenFile( self.logResourceName[7:], os.O_RDONLY) statData = os.fstat(logFileFd) except OSError as openOsError: if logFileFd != -1: os.close(logFileFd) if openOsError.errno == errno.ENOENT: return False raise if not stat.S_ISREG(statData.st_mode): os.close(logFileFd) raise Exception('Attempting to open non-regular file %s ' \ 'as file' % encodeByteStringAsString(self.logResourceName)) if (reopenFlag and (self.statData != None) and (statData.st_ino == self.statData.st_ino) and (statData.st_dev == self.statData.st_dev)): # Reopening was requested, but we would reopen the file already # opened, which is of no use. os.close(logFileFd) return False # This is a new file or a successful reopen attempt. self.logFileFd = logFileFd self.statData = statData return True