GNUTLS: Rework datum loading code

This commit is contained in:
Aaron Jones 2016-09-16 17:52:50 +00:00
parent 25ecd3cc86
commit 4fc76590b9
No known key found for this signature in database
GPG key ID: EC6F86EE9CD840B5

View file

@ -375,33 +375,66 @@ rb_init_ssl(void)
} }
static void static void
rb_free_datum_t(gnutls_datum_t * d) rb_free_datum_t(gnutls_datum_t *const datum)
{ {
rb_free(d->data); if(datum == NULL)
rb_free(d); return;
rb_free(datum->data);
rb_free(datum);
} }
static gnutls_datum_t * static gnutls_datum_t *
rb_load_file_into_datum_t(const char *file) rb_load_file_into_datum_t(const char *const file)
{ {
FILE *f; const int datum_fd = open(file, O_RDONLY);
gnutls_datum_t *datum; if(datum_fd < 0)
return NULL;
struct stat fileinfo; struct stat fileinfo;
if((f = fopen(file, "r")) == NULL) if(fstat(datum_fd, &fileinfo) != 0)
{
(void) close(datum_fd);
return NULL; return NULL;
if(fstat(fileno(f), &fileinfo)) }
const size_t datum_size = (fileinfo.st_size < 131072) ? (size_t) fileinfo.st_size : 131072;
if(datum_size == 0)
{
(void) close(datum_fd);
return NULL; return NULL;
}
datum = rb_malloc(sizeof(gnutls_datum_t)); gnutls_datum_t *datum;
if((datum = rb_malloc(sizeof *datum)) == NULL)
{
(void) close(datum_fd);
return NULL;
}
if((datum->data = rb_malloc(datum_size + 1)) == NULL)
{
rb_free(datum);
(void) close(datum_fd);
return NULL;
}
if(fileinfo.st_size > 131072) /* deal with retards */ for(size_t data_read = 0; data_read < datum_size; )
datum->size = 131072; {
else ssize_t ret = read(datum_fd, ((unsigned char *)datum->data) + data_read, datum_size - data_read);
datum->size = fileinfo.st_size;
datum->data = rb_malloc(datum->size + 1); if(ret <= 0)
fread(datum->data, datum->size, 1, f); {
fclose(f); rb_free_datum_t(datum);
(void) close(datum_fd);
return NULL;
}
data_read += (size_t) ret;
}
(void) close(datum_fd);
datum->data[datum_size] = '\0';
datum->size = (unsigned int) datum_size;
return datum; return datum;
} }