]> git.scottworley.com Git - overonion/blame_incremental - reverse_lib.c
Accept streams as input. Use a temp file
[overonion] / reverse_lib.c
... / ...
CommitLineData
1#define _GNU_SOURCE
2#define _FILE_OFFSET_BITS 64
3
4#include <err.h>
5#include <fcntl.h>
6#include <stdio.h>
7#include <stdlib.h>
8#include <sys/mman.h>
9#include <sys/stat.h>
10#include <sys/types.h>
11#include <sysexits.h>
12#include <unistd.h>
13
14void reverse_file(const char* input_filename, FILE* output_stream) {
15 int fd = open(input_filename, O_RDONLY);
16 if (fd == -1) err(EX_NOINPUT, "Could not open specified file");
17
18 struct stat stats;
19 if (fstat(fd, &stats) == -1) err(EX_NOINPUT, "Could not stat input");
20
21 long page_size = sysconf(_SC_PAGE_SIZE);
22 off_t pages = (stats.st_size - 1) / page_size + 1;
23 long map_size = pages * page_size;
24 char *m = mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd, 0);
25 if (m == MAP_FAILED) err(EX_NOINPUT, "Could not mmap input");
26
27 for (off_t p = stats.st_size - 1; p >= 0; p--) {
28 if (fputc(m[p], output_stream) == EOF) errx(EX_IOERR, "Could not write");
29 }
30
31 if (munmap(m, map_size) == -1) err(EX_IOERR, "Could not unmap input");
32 if (close(fd) == -1) err(EX_IOERR, "Could not close input");
33}
34
35/* Create a temporary file in $TMPDIR, or /tmp if TMPDIR is not set.
36 * Caller must free temp_filename and fclose temp_file. Succeeds or terminates
37 * the process. */
38static void make_temporary_file(char** temp_filename, FILE** temp_file) {
39 char* TMPDIR = getenv("TMPDIR");
40 if (TMPDIR == NULL) {
41 TMPDIR = "/tmp";
42 }
43 if (asprintf(temp_filename, "%s/reverse.XXXXXX", TMPDIR) == -1) {
44 errx(EX_OSERR, "Could not assemble temporary filename");
45 }
46 int fd = mkstemp(*temp_filename);
47 if (fd == -1) err(EX_IOERR, "Could not make a temporary file");
48 *temp_file = fdopen(fd, "w");
49 if (*temp_file == NULL) err(EX_IOERR, "Could not open temporary file");
50}
51
52/* Copy data from input to output until EOF is reached. */
53static void copy(FILE* input, FILE* output) {
54 for (;;) {
55 int c = fgetc(input);
56 if (c == EOF) {
57 if (ferror(input)) errx(EX_IOERR, "Could not read");
58 if (!feof(input)) errx(EX_IOERR, "Unexpected end of file");
59 break;
60 }
61 if (fputc(c, output) == EOF) errx(EX_IOERR, "Could not write");
62 }
63}
64
65void reverse_stream(FILE* input_stream, FILE* output_stream) {
66 char* temp_filename;
67 FILE* temp_file;
68 make_temporary_file(&temp_filename, &temp_file);
69
70 copy(input_stream, temp_file);
71 if (fclose(temp_file) != 0) err(EX_IOERR, "Could not close temporary file");
72
73 reverse_file(temp_filename, output_stream);
74
75 if (unlink(temp_filename) == -1) err(EX_IOERR, "Could not remove temporary file");
76 free(temp_filename);
77}