Skip to content
Permalink
Browse files
add read_file_to_str_from_fifo which is used by read_file_to_str
if the file happens to be one.

change file_status() to return FN_FILE if st_mode matches S_IFIFO
so that init_key_from_file() will read from a FIFO.
  • Loading branch information
meejah committed Sep 13, 2012
1 parent 99cb969 commit a90a93e0dce0cade00931b1e12c8d551f17eb072
Showing with 70 additions and 1 deletion.
  1. +45 −1 src/common/util.c
  2. +2 −0 src/common/util.h
  3. +23 −0 src/test/test_util.c
@@ -1805,7 +1805,7 @@ file_status(const char *fname)
}
if (st.st_mode & S_IFDIR)
return FN_DIR;
else if (st.st_mode & S_IFREG)
else if (st.st_mode & (S_IFREG | S_IFIFO))
return FN_FILE;
else
return FN_ERROR;
@@ -2237,6 +2237,42 @@ write_bytes_to_new_file(const char *fname, const char *str, size_t len,
(bin?O_BINARY:O_TEXT));
}

/**
* Read the contents of the open file <b>fd</b> presuming it is a FIFO
* (or similar) file descriptor for which the size of the file isn't
* known ahead of time. NULL is returned if this fails for some reason.
*/

char *
read_file_to_str_from_fifo(int fd)
{
ssize_t r;
size_t pos = 0;
char *string = 0;
char buf[256];
string = NULL;

do {
r = read(fd, buf, 256);
if (r < 0) {
if (string)
tor_free(string);
return NULL;
}

if (r == 0)
break;

string = tor_realloc(string, pos + (size_t)r + 1);

memcpy(string+pos, buf, r);
pos += r;
} while (r > 0);

string[pos] = '\0';
return string;
}

/** Read the contents of <b>filename</b> into a newly allocated
* string; return the string on success or NULL on failure.
*
@@ -2285,6 +2321,14 @@ read_file_to_str(const char *filename, int flags, struct stat *stat_out)
return NULL;
}

if (S_ISFIFO(statbuf.st_mode)) {
string = read_file_to_str_from_fifo(fd);
if (string && stat_out) {
memcpy(stat_out, &statbuf, sizeof(struct stat));
}
return string;
}

if ((uint64_t)(statbuf.st_size)+1 >= SIZE_T_CEILING)
return NULL;

@@ -360,6 +360,8 @@ struct stat;
#endif
char *read_file_to_str(const char *filename, int flags, struct stat *stat_out)
ATTR_MALLOC;
char *read_file_to_str_from_fifo(int fd)
ATTR_MALLOC;
const char *parse_config_line_from_str(const char *line,
char **key_out, char **value_out);
char *expand_filename(const char *filename);
@@ -18,6 +18,28 @@
#include <tchar.h>
#endif

static void
test_util_read_file_fifo(void)
{
#ifndef _WIN32
char fifo_name[64];
strcpy(fifo_name, "/tmp/tor_test_fifo.XXXXXX");
int fd = mkstemp(fifo_name);
test_neq(fd, -1);
test_eq(write(fd, "somethingsomething", 19), 19);
close(fd);

int read_fd = open(fifo_name, O_RDONLY);
char *str = read_file_to_str_from_fifo(read_fd);
close(read_fd);

test_eq(strcmp(str, "somethingsomething"), 0);

done:
unlink(fifo_name);
#endif
}

static void
test_util_time(void)
{
@@ -3191,6 +3213,7 @@ struct testcase_t util_tests[] = {
UTIL_TEST(envnames, 0),
UTIL_TEST(make_environment, 0),
UTIL_TEST(set_env_var_in_sl, 0),
UTIL_TEST(read_file_fifo, 0),
END_OF_TESTCASES
};

0 comments on commit a90a93e

Please sign in to comment.