Seitched mmap-based file reader against getline which also works with pipes.

This commit is contained in:
Heiko Reese
2021-09-11 14:40:43 +02:00
parent b6a350ef3a
commit a6c6169122
4 changed files with 26 additions and 54 deletions

View File

@ -1,67 +1,37 @@
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sodium.h>
#include "common.h"
char *read_first_line(const char *filename) {
int fd;
char *endptr;
FILE *stream;
char *cipherstring;
size_t len = 0;
ssize_t nread;
// open file
fd = open(filename, O_RDONLY, (mode_t) 0600);
if (fd == -1) {
stream = fopen(filename, "r");
if (stream == NULL) {
perror("Error opening file");
exit(EXIT_FAILURE);
}
// get length
struct stat fileInfo = {0};
if (fstat(fd, &fileInfo) == -1) {
perror("Error getting the file size");
exit(EXIT_FAILURE);
}
if (fileInfo.st_size == 0) {
fprintf(stderr, "Error: File is empty, nothing to do\n");
exit(EXIT_FAILURE);
}
// mmap file
char *map = mmap(0, fileInfo.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (map == MAP_FAILED)
{
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
// find first line
endptr = strchrnul(map, 0x0a);
size_t cipherstring_len = endptr - map;
cipherstring = malloc(cipherstring_len+1);
strncpy(cipherstring, map, cipherstring_len);
nread = getline(&cipherstring, &len, stream);
// munmap and close file
if (munmap(map, fileInfo.st_size) == -1) {
close(fd);
perror("Error un-mmapping the file");
exit(EXIT_FAILURE);
if (nread == -1) {
perror("getline: ");
}
close(fd);
fclose(stream);
return cipherstring;
}
void base64_decode_string(const char *input, unsigned char **outstring, size_t *outlen) {
int base64_decode_string(const char *input, unsigned char **outstring, size_t *outlen) {
size_t input_len = strlen(input);
size_t outmaxlen = input_len / 4 * 3;
*outstring = malloc(outmaxlen * sizeof(unsigned char));
fprintf(stderr, " Input: |%s| [%zu]\n", input, input_len);
int b64err = sodium_base642bin(*outstring, outmaxlen, (const char *) input, input_len,
NULL, outlen, NULL, sodium_base64_VARIANT_ORIGINAL);
if (b64err != 0) {
fprintf(stderr, "[ERROR] Unable to base64-decode the password\n");
exit(EXIT_FAILURE);
}
return sodium_base642bin(*outstring, outmaxlen, (const char *) input, input_len,
NULL, outlen, NULL, sodium_base64_VARIANT_ORIGINAL);
}