#include "readline_cssm.h"
#include "security_tool.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *
readline(char *buffer, int buffer_size)
{
int ix = 0, bytes_malloced = 0;
if (!buffer)
{
bytes_malloced = 64;
buffer = (char *)malloc(bytes_malloced);
buffer_size = bytes_malloced;
}
for (;;++ix)
{
int ch;
if (ix == buffer_size - 1)
{
if (!bytes_malloced)
break;
bytes_malloced += bytes_malloced;
buffer = (char *)realloc(buffer, bytes_malloced);
buffer_size = bytes_malloced;
}
ch = getchar();
if (ch == EOF)
{
if (bytes_malloced)
free(buffer);
return NULL;
}
if (ch == '\n')
break;
buffer[ix] = ch;
}
buffer[ix] = '\0';
return buffer;
}
int
read_file(const char *name, CSSM_DATA *outData)
{
int fd = -1, result;
char *buffer = NULL;
off_t length;
ssize_t bytes_read;
do {
fd = open(name, O_RDONLY, 0);
} while (fd == -1 && errno == EINTR);
if (fd == -1)
{
sec_error("open %s: %s", name, strerror(errno));
result = -1;
goto loser;
}
length = lseek(fd, 0, SEEK_END);
if (length == -1)
{
sec_error("lseek %s, SEEK_END: %s", name, strerror(errno));
result = -1;
goto loser;
}
buffer = malloc((size_t)length);
do {
bytes_read = pread(fd, buffer, (size_t) length, 0);
} while (bytes_read == -1 && errno == EINTR);
if (bytes_read == -1)
{
sec_error("pread %s: %s", name, strerror(errno));
result = -1;
goto loser;
}
if (bytes_read != (ssize_t)length)
{
sec_error("read %s: only read %d of %qu bytes", name, bytes_read, length);
result = -1;
goto loser;
}
result = close(fd);
if (result) {
sec_error("close");
goto loser;
}
outData->Data = (uint8 *)buffer;
outData->Length = (uint32)length;
return result;
loser:
if (fd != -1) {
close(fd);
}
if (buffer) {
free(buffer);
}
return result;
}