]> git.scottworley.com Git - overonion/blob - reverse_lib.c
f217b1cf2a46bf4c9c5eea4f53b68b16bd0adceb
[overonion] / reverse_lib.c
1 #define _FILE_OFFSET_BITS 64
2
3 #include "temp_file.h"
4
5 #include <err.h>
6 #include <fcntl.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <sys/mman.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <sysexits.h>
13 #include <unistd.h>
14
15 void reverse_file(const char* input_filename, FILE* output_stream) {
16 int fd = open(input_filename, O_RDONLY);
17 if (fd == -1) err(EX_NOINPUT, "Could not open specified file");
18
19 struct stat stats;
20 if (fstat(fd, &stats) == -1) err(EX_NOINPUT, "Could not stat input");
21
22 long page_size = sysconf(_SC_PAGE_SIZE);
23 off_t pages = (stats.st_size - 1) / page_size + 1;
24 long map_size = pages * page_size;
25 char *m = mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd, 0);
26 if (m == MAP_FAILED) err(EX_NOINPUT, "Could not mmap input");
27
28 for (off_t p = stats.st_size - 1; p >= 0; p--) {
29 if (fputc(m[p], output_stream) == EOF) errx(EX_IOERR, "Could not write");
30 }
31
32 if (munmap(m, map_size) == -1) err(EX_IOERR, "Could not unmap input");
33 if (close(fd) == -1) err(EX_IOERR, "Could not close input");
34 }
35
36 /* Copy data from input to output until EOF is reached. */
37 static void copy(FILE* input, FILE* output) {
38 for (;;) {
39 int c = fgetc(input);
40 if (c == EOF) {
41 if (ferror(input)) errx(EX_IOERR, "Could not read");
42 if (!feof(input)) errx(EX_IOERR, "Unexpected end of file");
43 break;
44 }
45 if (fputc(c, output) == EOF) errx(EX_IOERR, "Could not write");
46 }
47 }
48
49 void reverse_stream(FILE* input_stream, FILE* output_stream) {
50 char* temp_filename;
51 FILE* temp_file;
52 make_temporary_file(&temp_filename, &temp_file);
53
54 copy(input_stream, temp_file);
55 if (fclose(temp_file) != 0) err(EX_IOERR, "Could not close temporary file");
56
57 reverse_file(temp_filename, output_stream);
58
59 if (unlink(temp_filename) == -1) err(EX_IOERR, "Could not remove temporary file");
60 free(temp_filename);
61 }