Chore: improove error handling and logging

This commit is contained in:
Dorian Zedler 2022-07-12 22:53:17 +02:00
parent 21d351c7e2
commit 82f3f7efa8
Signed by: dorian
GPG Key ID: 989DE36109AFA354
3 changed files with 20 additions and 11 deletions

View File

@ -3,19 +3,20 @@
bool open_file(const char* path, FILE** file, struct stat* file_stat) {
(*file) = fopen(path, "r");
if ((*file) == NULL) {
printf("Fopen error: %d\n", errno);
if (errno == 0) errno = EIO;
return false;
}
int status = fstat(fileno((*file)), file_stat);
if (status == -1) {
printf("Fstat error: %d\n", errno);
if (errno == 0) errno = EIO;
fclose((*file));
return false;
};
if ((file_stat->st_mode & S_IFMT) != S_IFREG) {
printf("File is not a regular file!\n");
errno = ENOENT;
fclose((*file));
return false;
}
@ -38,8 +39,8 @@ uint8_t* read_file(const char* path, size_t* size) {
fread(data, statOfFile.st_blksize, statOfFile.st_blocks, f);
// size_t bytesRead = fread(data, sizeof(uint8_t), statOfFile.st_size, f);
if (bytesRead != 0 && !feof(f)) {
printf("Error reading file!\n");
fclose(f);
if (errno == 0) errno = EIO;
return NULL;
}

View File

@ -74,10 +74,11 @@ bool calculate_hash(struct configuration c, char* hash) {
}
if (data == NULL) {
printf("Error reading file %s!", c.filename);
printf("Error reading file %s!\n", c.filename);
return false;
}
errno = 0;
uint8_t out[16];
if (c.doBenchmark) {
double duration =
@ -88,6 +89,10 @@ bool calculate_hash(struct configuration c, char* hash) {
md2_hash(len, data, out);
}
if (errno != 0) {
return false;
}
md2_encode_hash(out, hash);
if (c.implementationToUse != 2) free(data);
@ -120,7 +125,7 @@ int main(int argc, char** argv) {
c.implementationToUse, c.doBenchmark, c.benchmarkingCycles);
if (c.runTests && c.implementationToUse == 2) {
fprintf(stderr, "Cannot run tests on implementation 2!");
fprintf(stderr, "Cannot run tests on implementation 2!\n");
return EXIT_FAILURE;
}
@ -132,8 +137,14 @@ int main(int argc, char** argv) {
printf("Hashing file %s...\n\n", c.filename);
char hash[32];
calculate_hash(c, hash);
if (!calculate_hash(c, hash)) {
if (errno != 0) {
fprintf(stderr, "\n\033[0;31mAn error occured: %s\033[0m\n",
strerror(errno));
}
return EXIT_FAILURE;
}
printf("Hash: %s\n", hash);
return 0;
return EXIT_SUCCESS;
}

View File

@ -36,8 +36,6 @@ void apply_padding(size_t len, uint8_t buf[16]) {
buf[len - paddingNeeded] = originalPadding;
paddingNeeded--;
}
printf("buf with padding: ");
md2_print_buf(len, buf);
}
// unused!
@ -47,7 +45,6 @@ void md2_hash_2(size_t len, const uint8_t buf[len], uint8_t out[16]) {
FILE* file;
struct stat file_stat;
if (!open_file((char*)buf, &file, &file_stat)) {
fprintf(stderr, "Error opening the file!\n");
return;
}
@ -67,7 +64,7 @@ void md2_hash_2(size_t len, const uint8_t buf[len], uint8_t out[16]) {
fread(data, 1, bytes_left_to_process, file);
if (ferror(file) || feof(file)) {
fprintf(stderr, "Error reading the file!");
if (errno == 0) errno = EIO;
return;
}