aboutsummaryrefslogtreecommitdiff
path: root/lib/io/unix/istream.c
blob: f8cffadd34496d678e687df8cf4760259e86ccec (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
 * istream.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#include "../internal.h"

typedef struct {
	istream_t base;
	char *path;
	int fd;

	sqfs_u8 buffer[BUFSZ];
} file_istream_t;

static int file_precache(istream_t *strm)
{
	file_istream_t *file = (file_istream_t *)strm;
	ssize_t ret;
	size_t diff;

	while (strm->buffer_used < sizeof(file->buffer)) {
		diff = sizeof(file->buffer) - strm->buffer_used;

		ret = read(file->fd, strm->buffer + strm->buffer_used, diff);

		if (ret == 0) {
			strm->eof = true;
			break;
		}

		if (ret < 0) {
			if (errno == EINTR)
				continue;

			perror(file->path);
			return -1;
		}

		strm->buffer_used += ret;
	}

	return 0;
}

static const char *file_get_filename(istream_t *strm)
{
	file_istream_t *file = (file_istream_t *)strm;

	return file->path;
}

static void file_destroy(sqfs_object_t *obj)
{
	file_istream_t *file = (file_istream_t *)obj;

	if (file->fd != STDIN_FILENO)
		close(file->fd);

	free(file->path);
	free(file);
}

istream_t *istream_open_file(const char *path)
{
	file_istream_t *file = calloc(1, sizeof(*file));
	istream_t *strm = (istream_t *)file;

	if (file == NULL) {
		perror(path);
		return NULL;
	}

	sqfs_object_init(file, file_destroy, NULL);

	file->path = strdup(path);
	if (file->path == NULL) {
		perror(path);
		goto fail_free;
	}

	file->fd = open(path, O_RDONLY);
	if (file->fd < 0) {
		perror(path);
		goto fail_path;
	}

	strm->buffer = file->buffer;
	strm->precache = file_precache;
	strm->get_filename = file_get_filename;
	return strm;
fail_path:
	free(file->path);
fail_free:
	free(file);
	return NULL;
}

istream_t *istream_open_stdin(void)
{
	file_istream_t *file = calloc(1, sizeof(*file));
	istream_t *strm = (istream_t *)file;

	if (file == NULL)
		goto fail;

	sqfs_object_init(file, file_destroy, NULL);

	file->path = strdup("stdin");
	if (file->path == NULL)
		goto fail;

	file->fd = STDIN_FILENO;
	strm->buffer = file->buffer;
	strm->precache = file_precache;
	strm->get_filename = file_get_filename;
	return strm;
fail:
	perror("creating file wrapper for stdin");
	free(file);
	return NULL;
}