aboutsummaryrefslogtreecommitdiffstats
path: root/libexec_recv_document.c
blob: 8eb0be6e908245371e2d1fe8e33e55ed1c4d61e4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/* 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