Refactored file reading into finction.

This commit is contained in:
Heiko Reese
2021-09-08 03:34:12 +02:00
parent a82f6d388b
commit 0b01283cd9
3 changed files with 81 additions and 49 deletions

View File

@ -3,11 +3,8 @@
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sodium.h>
#include "common.c"
#define ENVVAR_PASSWORD_NAME "LIBEXIM_PASSWORD"
@ -38,8 +35,6 @@ int main(int argc, char *argv[]) {
size_t pwlen;
char *b64password;
char *password_env;
int fd;
char *endptr;
seen_args mode = NONE;
seen_args input = NONE;
@ -73,6 +68,7 @@ int main(int argc, char *argv[]) {
password_env = getenv(ENVVAR_PASSWORD_NAME);
if (password_env == NULL) {
fprintf(stderr, "[ERROR] Environment variable %s is undefined.\n\n", ENVVAR_PASSWORD_NAME);
exit(EXIT_FAILURE);
}
pwlen = strlen(password_env);
b64password = malloc(pwlen+1);
@ -80,46 +76,7 @@ int main(int argc, char *argv[]) {
mode |= PASSENV;
break;
case 'f':
// open file
fd = open(optarg, O_RDONLY, (mode_t)0600);
if (fd == -1) {
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);
// munmap and close file
if (munmap(map, fileInfo.st_size) == -1)
{
close(fd);
perror("Error un-mmapping the file");
exit(EXIT_FAILURE);
}
close(fd);
cipherstring = read_first_line(optarg);
input |= INFILE;
break;
}
@ -132,18 +89,30 @@ int main(int argc, char *argv[]) {
exit(EXIT_FAILURE);
}
// read first non-option argument as ciphertext
// read first non-option argument as ciphertext if present
if (optind < argc) {
size_t cipherstring_len = strlen(argv[optind])+1;
cipherstring = malloc(cipherstring_len+1);
strncpy(cipherstring, argv[optind], cipherstring_len);
input |= INSTRING;
}
// fail if neither argument nor filename is present
if (input == NONE) {
fprintf(stderr, "[ERROR] Please specify a ciphertext source.\n\n");
print_usage(prog_basename);
exit(EXIT_FAILURE);
}
printf("»%s«\n", cipherstring);
// base64-decode password
size_t password_len = strlen(b64password) / 4 * 3;
unsigned char * password = malloc(password_len);
int b64err = sodium_base642bin(password, password_len,
(const char *) b64password, strlen(b64password),
NULL, &password_len, NULL, sodium_base64_VARIANT_ORIGINAL);
if (b64err != 0) {
fprintf(stderr, "[ERROR] Unable to base64-decode the password\n");
exit(EXIT_FAILURE);
}
printf("»%s«\n", password);
}