Fix hash and hash_str

* file_t.hash is now a buffer and not a pointer
* add exception checking to file_t_md5_gen
This commit is contained in:
Pradana Aumars 2021-06-01 00:08:30 +02:00
parent a6227b8481
commit ea37ce1732
2 changed files with 16 additions and 13 deletions

View File

@ -1,7 +1,6 @@
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <openssl/md5.h> /* md5sum */
#include <fcntl.h> #include <fcntl.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <errno.h> #include <errno.h>
@ -46,9 +45,8 @@ file_init(const char *filename, filepath_t FILEPATH, exception_t *e)
} }
file_t *f; file_t *f;
f = malloc(sizeof(file_t*)); f = malloc(sizeof(file_t));
f->name = (char*) path; f->name = (char*) path;
f->hash = NULL;
f->hash_str = NULL; f->hash_str = NULL;
return f; return f;
} }
@ -76,7 +74,10 @@ file_md5_gen(file_t *f, exception_t *e)
file_buffer = (unsigned char*) mmap(0, file_size, PROT_READ, MAP_SHARED, file_descript, 0); file_buffer = (unsigned char*) mmap(0, file_size, PROT_READ, MAP_SHARED, file_descript, 0);
/* Computes the MD5 checksum to result */ /* Computes the MD5 checksum to result */
MD5(file_buffer, file_size, f->hash); if (MD5(file_buffer, file_size, f->hash) == NULL) {
e->type = MD5SUM_GEN_FAIL;
e->msg = "No hash!";
}
/* Removes fime_buffer and file_size */ /* Removes fime_buffer and file_size */
munmap(file_buffer, file_size); munmap(file_buffer, file_size);
@ -88,14 +89,14 @@ char*
file_md5_str(file_t *f, exception_t *e) file_md5_str(file_t *f, exception_t *e)
{ {
static const char digits[] = "0123456789abcdef"; static const char digits[] = "0123456789abcdef";
f->hash_str = malloc (MD5_DIGEST_LENGTH+1); f->hash_str = malloc (2*MD5_DIGEST_LENGTH+1);
size_t si = 0;
for (size_t i = 0; i < MD5_DIGEST_LENGTH; i+=2) for (size_t i = si; i < MD5_DIGEST_LENGTH; i++)
{ {
f->hash_str[i] += digits[f->hash[i] / MD5_DIGEST_LENGTH]; f->hash_str[si++] = digits[f->hash[i] / MD5_DIGEST_LENGTH];
f->hash_str[i+1] += digits[f->hash[i+1] % MD5_DIGEST_LENGTH]; f->hash_str[si++] = digits[f->hash[i] % MD5_DIGEST_LENGTH];
} }
f->hash_str[MD5_DIGEST_LENGTH] = '\0'; f->hash_str[2*MD5_DIGEST_LENGTH] = '\0';
return f->hash_str; return f->hash_str;
} }

View File

@ -1,6 +1,8 @@
#ifndef FILE_T_H #ifndef FILE_T_H
#define FILE_T_H #define FILE_T_H
#include <openssl/md5.h> /* md5sum */
#include "exception_t.h" #include "exception_t.h"
typedef enum filepath_t { typedef enum filepath_t {
@ -13,7 +15,7 @@ typedef enum filepath_t {
*/ */
typedef struct file_t { typedef struct file_t {
char *name; /**< Absolute path to file */ char *name; /**< Absolute path to file */
unsigned char *hash; /**< MD5sum hash */ unsigned char hash[MD5_DIGEST_LENGTH]; /**< MD5sum hash */
char *hash_str; /**< MD5sum hash as char* */ char *hash_str; /**< MD5sum hash as char* */
} file_t; } file_t;