summaryrefslogtreecommitdiffstats
path: root/src/lib/buffer-istream.c
blob: 3898fd0cd57fbe9c03b5fb1bf70de1e06955783a (plain)
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
/* Copyright (c) 2020 Dovecot authors, see the included COPYING file */

#include "lib.h"
#include "buffer.h"
#include "eacces-error.h"
#include "istream.h"

enum buffer_append_result
buffer_append_full_istream(buffer_t *buf, struct istream *is, size_t max_read_size,
			   const char **error_r)
{
	const unsigned char *data;
	size_t size;
	ssize_t ret;

	while ((ret = i_stream_read_more(is, &data, &size)) > 0) {
		if (max_read_size == 0)
			return BUFFER_APPEND_READ_MAX_SIZE;
		size = I_MIN(max_read_size, size);
		buffer_append(buf, data, size);
		i_stream_skip(is, size);
		max_read_size -= size;
	}

	if (ret == 0)
		return BUFFER_APPEND_READ_MORE;

	i_assert(is->eof);

	if (is->stream_errno != 0) {
		*error_r = i_stream_get_error(is);
		return BUFFER_APPEND_READ_ERROR;
	}
	return BUFFER_APPEND_OK;
}

enum buffer_append_result
buffer_append_full_file(buffer_t *buf, const char *file, size_t max_read_size,
			const char **error_r)
{
	struct istream *is = i_stream_create_file(file, IO_BLOCK_SIZE);
	enum buffer_append_result res =
		buffer_append_full_istream(buf, is, max_read_size, error_r);
	if (is->stream_errno == EACCES)
		*error_r = eacces_error_get("open", file);
	i_stream_unref(&is);
	i_assert(res != BUFFER_APPEND_READ_MORE);
	return res;
}