mirror of
https://gitlab.kit.edu/kit/scc/sys/mail/exim-encrypt-dlfunc.git
synced 2025-12-06 08:03:55 +01:00
53 lines
1.3 KiB
C
53 lines
1.3 KiB
C
#include <sys/mman.h>
|
|
#include <sys/stat.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include "common.h"
|
|
|
|
char * read_first_line(const char * filename) {
|
|
int fd;
|
|
char *endptr;
|
|
char *cipherstring;
|
|
|
|
// open file
|
|
fd = open(filename, 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);
|
|
|
|
return cipherstring;
|
|
} |