]> git.scottworley.com Git - overonion/blame - reverse_lib.c
Accept a test data file as a command line argument
[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
a99e77b4 15void reverse_file(const char* input_filename, FILE* output_stream) {
b398ee5a 16 int fd = open(input_filename, O_RDONLY);
3a85da3a 17 if (fd == -1) err(EX_NOINPUT, "Could not open specified file");
b398ee5a
SW
18
19 struct stat stats;
3a85da3a 20 if (fstat(fd, &stats) == -1) err(EX_NOINPUT, "Could not stat input");
b398ee5a
SW
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);
3a85da3a 26 if (m == MAP_FAILED) err(EX_NOINPUT, "Could not mmap input");
b398ee5a 27
b398ee5a 28 for (off_t p = stats.st_size - 1; p >= 0; p--) {
a99e77b4 29 if (fputc(m[p], output_stream) == EOF) errx(EX_IOERR, "Could not write");
b398ee5a
SW
30 }
31
3a85da3a
SW
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");
b398ee5a 34}
a3915755 35
a3915755
SW
36/* Copy data from input to output until EOF is reached. */
37static 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
49void 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}