| 1 | #define _GNU_SOURCE |
| 2 | #include <dlfcn.h> |
| 3 | #include <errno.h> |
| 4 | #include <stdlib.h> |
| 5 | #include <string.h> |
| 6 | #include <unistd.h> |
| 7 | |
| 8 | static int archive_fd = -1; |
| 9 | static int finished; |
| 10 | static ssize_t (*original_write)(int, const void *, size_t); |
| 11 | static off64_t (*original_seek)(int, off64_t, int); |
| 12 | |
| 13 | __attribute__((constructor)) static void initialize(void) { |
| 14 | original_write = dlsym(RTLD_NEXT, "write"); |
| 15 | original_seek = dlsym(RTLD_NEXT, "lseek64"); |
| 16 | } |
| 17 | |
| 18 | ssize_t write(int fd, const void *data, size_t count) { |
| 19 | const unsigned char *bytes = data; |
| 20 | if (archive_fd < 0 && count == 32 && !memcmp(bytes, (unsigned char[32]){0}, 32)) { |
| 21 | archive_fd = fd; |
| 22 | return original_write(fd, data, count); |
| 23 | } |
| 24 | const char *fault = getenv("ZIPELO_7Z_FAULT"); |
| 25 | if (fd == archive_fd && fault) { |
| 26 | if (!strcmp(fault, "encode-full")) { errno = ENOSPC; return -1; } |
| 27 | if (count == 1 && bytes[0] == 0) { |
| 28 | finished = 1; |
| 29 | if (!strcmp(fault, "finish-full")) { errno = ENOSPC; return -1; } |
| 30 | } |
| 31 | if (!strcmp(fault, "header-write") && finished && count > 1 && bytes[0] == 1) { |
| 32 | errno = EIO; return -1; |
| 33 | } |
| 34 | if (!strcmp(fault, "header-patch") && count == 32 && !memcmp(bytes, "7z", 2)) { |
| 35 | errno = EIO; return -1; |
| 36 | } |
| 37 | } |
| 38 | return original_write(fd, data, count); |
| 39 | } |
| 40 | |
| 41 | off64_t lseek64(int fd, off64_t offset, int whence) { |
| 42 | const char *fault = getenv("ZIPELO_7Z_FAULT"); |
| 43 | if (fd == archive_fd && finished && fault && !strcmp(fault, "header-seek") && offset == 0 && whence == SEEK_SET) { |
| 44 | errno = EIO; return -1; |
| 45 | } |
| 46 | return original_seek(fd, offset, whence); |
| 47 | } |