summaryrefslogtreecommitdiff
path: root/src/helper/tpax_path_copy.c
blob: 0df6c17beb851e1645db389b95e00fe6361b0d7a (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
/******************************************************/
/*  tpax: a topological pax implementation            */
/*  Copyright (C) 2020  Z. Gilboa                     */
/*  Released under GPLv2 and GPLv3; see COPYING.TPAX. */
/******************************************************/

#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>

#include <tpax/tpax.h>
#include "tpax_driver_impl.h"

int tpax_path_copy(
	char *          dstpath,
	const char *    srcpath,
	size_t          bufsize,
	uint32_t        flags,
	size_t *        nwritten)
{
	const char *    src;
	char *          dst;
	char *          cap;

	if (!bufsize) {
		errno = ENOBUFS;
		return -1;
	}

	src = srcpath;
	dst = dstpath;
	cap = &dst[bufsize];

	if ((src[0] == '/') && (src[1] == '/') && (src[2] != '/')) {
		*dst++ = *src++;
		*dst++ = *src++;
	}

	if (flags & TPAX_DRIVER_PURE_PATH_OUTPUT)
		if ((src[0] == '.') && (src[1] == '/'))
			for (++src; *src=='/'; src++)
				(void)0;

	for (; *src; ) {
		if ((src[0] == '.') && (src[1] == '.')) {
			if ((src[2] == '/') || (src[2] == '\0')) {
				if (flags & TPAX_DRIVER_STRICT_PATH_INPUT) {
					errno = EINVAL;
					return -1;
				}
			}
		}

		if (flags & TPAX_DRIVER_PURE_PATH_OUTPUT) {
			if ((src[0] == '.') && (src[1] == '/') && (src[-1] == '/')) {
				for (++src; *src=='/'; src++)
					(void)0;

			} else if ((src[0] == '/')) {
				for (src++; *src=='/'; src++)
					(void)0;

				*dst++ = '/';

			} else {
				*dst++ = *src++;
			}
		} else {
			*dst++ = *src++;
		}

		if (dst == cap) {
			errno = ENOBUFS;
			return -1;
		}
	}

	if (nwritten)
		*nwritten = dst - dstpath;

	*dst = '\0';

	return 0;
}