| 206 | |
| 207 | |
| 208 | class Evidence: |
| 209 | def __init__(self, path, args): |
| 210 | self.path = os.path.abspath(path) |
| 211 | self.args = args |
| 212 | self.records = [] |
| 213 | self.uncertainty = [] |
| 214 | self.converted_bytes = 0 |
| 215 | self.captured_bytes = 0 |
| 216 | self.allowed_suites = set() |
| 217 | self.directory = None |
| 218 | parent, name = os.path.split(self.path) |
| 219 | if not name: |
| 220 | _error("input", "output must name a fresh directory") |
| 221 | fd = _directory(parent) |
| 222 | try: |
| 223 | os.mkdir(name, 0o700, dir_fd=fd) |
| 224 | self.directory = os.open(name, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, |
| 225 | dir_fd=fd) |
| 226 | finally: |
| 227 | os.close(fd) |
| 228 | try: |
| 229 | self.directory_identity = os.fstat(self.directory) |
| 230 | for name in ("evidence", "raw"): |
| 231 | os.mkdir(name, 0o700, dir_fd=self.directory) |
| 232 | except BaseException: |
| 233 | self.close() |
| 234 | raise |
| 235 | |
| 236 | def close(self): |
| 237 | if self.directory is not None: |
| 238 | os.close(self.directory) |
| 239 | self.directory = None |
| 240 | |
| 241 | def check(self): |
| 242 | fd = _directory(self.path) |
| 243 | try: |
| 244 | actual = os.fstat(fd) |
| 245 | if (actual.st_dev, actual.st_ino) != (self.directory_identity.st_dev, |
| 246 | self.directory_identity.st_ino): |
| 247 | _error("identity", "owned output directory was replaced") |
| 248 | finally: |
| 249 | os.close(fd) |
| 250 | |
| 251 | def write(self, relative, data): |
| 252 | self.check() |
| 253 | parent, name = os.path.split(relative) |
| 254 | fd = _directory(os.path.join(self.path, parent)) |
| 255 | try: |
| 256 | target = os.open(name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, |
| 257 | 0o600, dir_fd=fd) |
| 258 | try: |
| 259 | with os.fdopen(target, "wb") as stream: |
| 260 | stream.write(data) |
| 261 | stream.flush() |
| 262 | os.fsync(stream.fileno()) |
| 263 | except BaseException: |
| 264 | # Partial evidence remains; no marker is created on this path. |
| 265 | raise |