summaryrefslogtreecommitdiffstats
path: root/src/io.c
blob: a8dfa2fad455c14c88aeeb336cc7277cb4583c05 (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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include "io.h"

int stream_open(struct stream *in)
{
	struct stat st;
	mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP;
	char *dname = NULL;
	int ret = 0;

	if (!in || in->fd > 0 || !in->name) {
		ret = EINVAL;
		goto err;
	}

	if (in->out) {
		char *tmp[2];

		tmp[0] = strdup(in->name);
		tmp[1] = dirname(tmp[0]);
		dname = strdup(tmp[1]);
		free(tmp[0]);

		if (stat(dname, &st)) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}

		if(!(st.st_mode & S_IFDIR)) {
			ret = EINVAL;
			/* TODO: error message */
			goto err;
		}

		if (!stat(in->name, &st)) {
			if (!(st.st_mode & S_IFREG)) {
				ret = EINVAL;
				/* TODO: error message */
				goto err;
			}
			mode = st.st_mode;
		}
	} else if (stat(in->name, &st)) {
		ret = errno;
		/* TODO: error message */
		goto err;
	} else if (!(st.st_mode & S_IFREG) || !st.st_size || (st.st_size % in->stride)) {
		ret = EINVAL;
		/* TODO: error message */
		goto err;
	} else {
		in->n = st.st_size / in->stride;
	}

	if (in->out) {
		in->fd = open(dname, O_TMPFILE | O_WRONLY, mode);
		if (in->fd < 0) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}

		if (ftruncate(in->fd, in->stride * in->n)) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}
	} else {
		in->fd = open(in->name, O_RDONLY | O_NOATIME);
		if (in->fd < 0) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}
	}

err:
	free(dname);
	return ret;
}

int stream_close(struct stream *in)
{
	int ret = 0;

	if (!in || in->fd < 0) {
		ret = EINVAL;
		goto early_err;
	}

	if (!in->out) {
		goto out;
	}

	if (in->name) {
		char path[PATH_MAX];
		struct stat st;

		snprintf(path, PATH_MAX, "/proc/self/fd/%i", in->fd);

		if (!stat(in->name, &st)) {
			if (st.st_mode & S_IFREG) {
				unlink(in->name);
			} else {
				ret = EINVAL;
				/* TODO: error message */
				goto err;
			}
		}

		if (linkat(AT_FDCWD, path, AT_FDCWD, in->name, AT_SYMLINK_FOLLOW)) {
			ret = errno;
			/* TODO: error message */
			goto err;
		}
	} else {
		ret = EINVAL;
		goto err;
	}

out:
err:
	close(in->fd);
	in->fd = -1;
early_err:
	return ret;
}