aboutsummaryrefslogblamecommitdiffstats
path: root/libexec_recv_document.c
blob: 8eb0be6e908245371e2d1fe8e33e55ed1c4d61e4 (plain) (tree)




















































                                                                                          
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST


int
libexec_recv_document(struct libexec_document *doc)
{
	ssize_t r;
	void *new;
	size_t new_size;

	if (!doc) {
		errno = EINVAL;
		return -1;
	}

	for (;;) {
		if (doc->length == doc->alloc_size) {
			new_size = doc->alloc_size + 8096;
			new = realloc(doc->text, new_size);
			if (!new)
				return -1;
			doc->text = new;
			doc->alloc_size = new_size;
		}
		r = read(doc->fd, &doc->text[doc->length], doc->alloc_size - doc->length);
		if (r <= 0) {
			if (!r)
				goto done;
			return -1;
		}
		doc->length += (size_t)r;
	}
	return 0;

done:
	if (doc->length == doc->alloc_size) {
		new_size = doc->alloc_size + 1;
		new = realloc(doc->text, new_size);
		if (!new)
			return -1;
		doc->text = new;
		doc->alloc_size = new_size;
	}
	doc->text[doc->length] = '\0';
	return 1;
}


#else
LIBEXEC_CONST__ int main(void) {return 0;} /* TODO test */
#endif