aboutsummaryrefslogtreecommitdiff
path: root/lib/sqfs/src/io/unix.c
blob: 2e97394542138fc4d8790c6e839701a54787131e (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
/* SPDX-License-Identifier: LGPL-3.0-or-later */
/*
 * unix.c
 *
 * Copyright (C) 2019 David Oberhollenzer <goliath@infraroot.at>
 */
#define SQFS_BUILDING_DLL
#include "config.h"

#include "sqfs/io.h"
#include "sqfs/error.h"

#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

int sqfs_native_file_open(sqfs_file_handle_t *out, const char *filename,
			  sqfs_u32 flags)
{
	int open_mode;

	*out = -1;

	if (flags & ~SQFS_FILE_OPEN_ALL_FLAGS)
		return SQFS_ERROR_UNSUPPORTED;

	if (flags & SQFS_FILE_OPEN_READ_ONLY) {
		open_mode = O_RDONLY;
	} else {
		open_mode = O_CREAT | O_RDWR;

		if (flags & SQFS_FILE_OPEN_OVERWRITE) {
			open_mode |= O_TRUNC;
		} else {
			open_mode |= O_EXCL;
		}
	}

	*out = open(filename, open_mode, 0644);

	return (*out < 0) ? SQFS_ERROR_IO : 0;
}

void sqfs_native_file_close(sqfs_file_handle_t fd)
{
	while (close(fd) != 0 && errno == EINTR)
		;
}

int sqfs_native_file_duplicate(sqfs_file_handle_t in, sqfs_file_handle_t *out)
{
	*out = dup(in);
	return (*out < 0) ? SQFS_ERROR_IO : 0;
}

int sqfs_native_file_seek(sqfs_file_handle_t fd,
			  sqfs_s64 offset, sqfs_u32 flags)
{
	int whence;
	off_t off;

	switch (flags & SQFS_FILE_SEEK_TYPE_MASK) {
	case SQFS_FILE_SEEK_START:   whence = SEEK_SET; break;
	case SQFS_FILE_SEEK_CURRENT: whence = SEEK_CUR; break;
	case SQFS_FILE_SEEK_END:     whence = SEEK_END; break;
	default:                     return SQFS_ERROR_UNSUPPORTED;
	}

	if (flags & ~(SQFS_FILE_SEEK_FLAG_MASK | SQFS_FILE_SEEK_TYPE_MASK))
		return SQFS_ERROR_UNSUPPORTED;

	off = lseek(fd, offset, whence);
	if (off == ((off_t)-1)) {
		if (errno == ESPIPE)
			return SQFS_ERROR_UNSUPPORTED;
		return SQFS_ERROR_IO;
	}

	if (flags & SQFS_FILE_SEEK_TRUNCATE) {
		while (ftruncate(fd, off) != 0) {
			if (errno != EINTR)
				return SQFS_ERROR_IO;
		}
	}

	return 0;
}