]> git.scottworley.com Git - overonion/blame - reverse_lib.c
set -e doesn't catch failures inside <()
[overonion] / reverse_lib.c
CommitLineData
b398ee5a
SW
1#define _FILE_OFFSET_BITS 64
2
2377b838
SW
3#include "temp_file.h"
4
b398ee5a 5#include <err.h>
3adfbe9d 6#include <fcntl.h>
a99e77b4 7#include <stdio.h>
a3915755 8#include <stdlib.h>
3adfbe9d
SW
9#include <sys/mman.h>
10#include <sys/stat.h>
11#include <sys/types.h>
b398ee5a 12#include <sysexits.h>
3adfbe9d 13#include <unistd.h>
b398ee5a 14
639fe3c8
SW
15static off_t ceil_div(off_t dividend, off_t divisor) {
16 return (dividend - 1) / divisor + 1;
17}
18
a99e77b4 19void reverse_file(const char* input_filename, FILE* output_stream) {
639fe3c8
SW
20 const off_t mmap_chunk_size = 512 << 20;
21
b398ee5a 22 int fd = open(input_filename, O_RDONLY);
3a85da3a 23 if (fd == -1) err(EX_NOINPUT, "Could not open specified file");
b398ee5a
SW
24
25 struct stat stats;
3a85da3a 26 if (fstat(fd, &stats) == -1) err(EX_NOINPUT, "Could not stat input");
b398ee5a
SW
27
28 long page_size = sysconf(_SC_PAGE_SIZE);
639fe3c8
SW
29 off_t num_chunks = ceil_div(stats.st_size, mmap_chunk_size);
30 for (off_t chunk = num_chunks - 1; chunk >= 0; chunk--) {
31 off_t start_offset = chunk * mmap_chunk_size;
32 off_t end_offset = (chunk + 1) * mmap_chunk_size;
33 if (end_offset > stats.st_size) {
34 end_offset = stats.st_size;
35 }
36 off_t pages = ceil_div(end_offset - start_offset, page_size);
37 long map_size = pages * page_size;
38 char *m = mmap(NULL, map_size, PROT_READ, MAP_SHARED, fd, start_offset);
39 if (m == MAP_FAILED) err(EX_NOINPUT, "Could not mmap chunk %lld of %lld", chunk, num_chunks);
40
41 for (off_t p = (end_offset - start_offset) - 1; p >= 0; p--) {
42 if (fputc(m[p], output_stream) == EOF) errx(EX_IOERR, "Could not write");
43 }
b398ee5a 44
639fe3c8 45 if (munmap(m, map_size) == -1) err(EX_IOERR, "Could not unmap chunk %lld of %lld", chunk, num_chunks);
b398ee5a
SW
46 }
47
3a85da3a 48 if (close(fd) == -1) err(EX_IOERR, "Could not close input");
b398ee5a 49}
a3915755 50
a3915755
SW
51/* Copy data from input to output until EOF is reached. */
52static void copy(FILE* input, FILE* output) {
53 for (;;) {
54 int c = fgetc(input);
55 if (c == EOF) {
56 if (ferror(input)) errx(EX_IOERR, "Could not read");
57 if (!feof(input)) errx(EX_IOERR, "Unexpected end of file");
58 break;
59 }
60 if (fputc(c, output) == EOF) errx(EX_IOERR, "Could not write");
61 }
62}
63
64void reverse_stream(FILE* input_stream, FILE* output_stream) {
65 char* temp_filename;
66 FILE* temp_file;
67 make_temporary_file(&temp_filename, &temp_file);
68
69 copy(input_stream, temp_file);
70 if (fclose(temp_file) != 0) err(EX_IOERR, "Could not close temporary file");
71
72 reverse_file(temp_filename, output_stream);
73
74 if (unlink(temp_filename) == -1) err(EX_IOERR, "Could not remove temporary file");
75 free(temp_filename);
76}