e35d8cf136
Signed-off-by: Chloe M. <chloe@mirocom.org>
79 lines
1.4 KiB
C
79 lines
1.4 KiB
C
/*
|
|
* Copyright (c) 2026, Chloe M.
|
|
* Provided under the BSD-3 clause
|
|
*/
|
|
|
|
#include <sys/stat.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <errno.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
#include <openssl/sha.h>
|
|
#include "blobchain/memlib.h"
|
|
#include "blobchain/stream.h"
|
|
|
|
int
|
|
stream_from_file(struct data_stream *stmp, const char *path)
|
|
{
|
|
struct stat sb;
|
|
void *p;
|
|
ssize_t readlen;
|
|
int error, fd;
|
|
|
|
if (stmp == NULL || path == NULL) {
|
|
errno = -EINVAL;
|
|
return -1;
|
|
}
|
|
|
|
error = stat(path, &sb);
|
|
if (error < 0) {
|
|
perror("stat");
|
|
return -1;
|
|
}
|
|
|
|
fd = open(path, O_RDONLY);
|
|
if (fd < 0) {
|
|
perror("open");
|
|
return -1;
|
|
}
|
|
|
|
/*
|
|
* Now we want to allocate a whole block of memory to
|
|
* contain the entire file.
|
|
*
|
|
* XXX: For this reason, it is a good idea to only work with
|
|
* one file at a time to avoid saturating all of your RAM...
|
|
*/
|
|
p = xmalloc(sb.st_size);
|
|
stmp->length = sb.st_size;
|
|
stmp->data = p;
|
|
|
|
readlen = read(fd, p, stmp->length);
|
|
if (readlen < 0) {
|
|
perror("read");
|
|
close(fd);
|
|
free(p);
|
|
return -1;
|
|
}
|
|
|
|
SHA256(stmp->data, stmp->length, stmp->hash);
|
|
return 0;
|
|
}
|
|
|
|
void
|
|
stream_destroy(struct data_stream *stmp)
|
|
{
|
|
if (stmp == NULL) {
|
|
return;
|
|
}
|
|
|
|
if (stmp->data == NULL) {
|
|
return;
|
|
}
|
|
|
|
free(stmp->data);
|
|
stmp->length = 0;
|
|
stmp->data = NULL;
|
|
}
|