Mercurial > trustbridge
diff ui/listutil.c @ 4:9849250f50f2
Start implementation of certificatelist parser
author | Andre Heinecke <aheinecke@intevation.de> |
---|---|
date | Tue, 11 Feb 2014 16:46:02 +0000 |
parents | |
children | 992c0ec57660 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/listutil.c Tue Feb 11 16:46:02 2014 +0000 @@ -0,0 +1,133 @@ +#include "listutil.h" + +#include <stdio.h> +#include <stdlib.h> +#include <errno.h> +#include <fcntl.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> + +#define MAX_FILESIZE_KB 1024 + +void handle_errno() +{ + printf("Error: %s \n", strerror(errno)); +} + +list_status_t readList(char *fileName, void *data, size_t *size) +{ + int fd = -1; + struct stat fileStat; + int rc = 0; + ssize_t bRead = 0; + list_status_t retval = UnknownError; + + fd = open(fileName, O_RDONLY); + if (fd == -1) { + handle_errno(); + retval = StatFailed; + goto failure; + } + + rc = fstat(fd, &fileStat); + if (rc < 0) { + printf ("Stat failed with rc: %i\n", rc); + retval = StatFailed; + goto failure; + } + + // Check the size of the file + if (fileStat.st_size) { + printf("Size zero\n"); + retval = StatFailed; + goto failure; + } + + if (fileStat.st_size / 1024 > MAX_FILESIZE_KB || + fileStat.st_size >= (size_t)-1) { + printf("File too large\n"); + retval = TooLarge; + goto failure; + } + + // We can cast here as we already checked + // that this size is not too large for size_t + *size = (size_t) fileStat.st_size; + + data = malloc(*size); + + if (data == NULL) { + printf("Malloc failed\n"); + retval = UnknownError; + goto failure; + } + + bRead = read(fd, data, *size); + + if (bRead != *size) { + printf("Read failed"); + if (bRead == -1) { + handle_errno(); + } + retval = UnknownError; + *size = 0; + if (data) { + free(data); + data = NULL; + } + goto failure; + } + + retval = Unknown; +failure: + + if (fd && fd != -1) { + close(fd); + fd = -1; + } + + return retval; +} + +list_status_t readAndVerifyList(char *fileName, void *data, size_t *size) +{ + int validSig = 0; + char * firstChar = NULL; + int i = 0; + + list_status_t retval = UnknownError; + data = NULL; + size = NULL; + + retval = readList(fileName, data, size); + + if (retval != Unknown) { + return retval; + } + + if (!data || !size) { + // should not have happend if readList works as specified + return UnknownError; + } + + firstChar = (char*) data; + + if (*firstChar != 'S') { + printf("Does not start with S\n"); + retval = InvalidFormat; + } + + for (i=0; i < *size; i++) { + printf("%c", firstChar + i); + } + +failure: + if (retval != Valid && data) { + free(data); + data = NULL; + *size = 0; + } + return retval; +} +