Blame src/helper/tpax_path_copy.c

5874a9
/**************************************************************/
5874a9
/*  tpax: a topological pax implementation                    */
5874a9
/*  Copyright (C) 2020--2021  SysDeer Technologies, LLC       */
5874a9
/*  Released under GPLv2 and GPLv3; see COPYING.TPAX.         */
5874a9
/**************************************************************/
8fb8f9
8fb8f9
#include <stdint.h>
8fb8f9
#include <stdlib.h>
8fb8f9
#include <string.h>
8fb8f9
#include <errno.h>
8fb8f9
#include <sys/stat.h>
8fb8f9
8fb8f9
#include <tpax/tpax.h>
8fb8f9
#include "tpax_driver_impl.h"
8fb8f9
8fb8f9
int tpax_path_copy(
8fb8f9
	char *          dstpath,
8fb8f9
	const char *    srcpath,
8fb8f9
	size_t          bufsize,
8fb8f9
	uint32_t        flags,
8fb8f9
	size_t *        nwritten)
8fb8f9
{
8fb8f9
	const char *    src;
8fb8f9
	char *          dst;
8fb8f9
	char *          cap;
8fb8f9
8fb8f9
	if (!bufsize) {
8fb8f9
		errno = ENOBUFS;
8fb8f9
		return -1;
8fb8f9
	}
8fb8f9
8fb8f9
	src = srcpath;
8fb8f9
	dst = dstpath;
8fb8f9
	cap = &dst[bufsize];
8fb8f9
8fb8f9
	if ((src[0] == '/') && (src[1] == '/') && (src[2] != '/')) {
8fb8f9
		*dst++ = *src++;
8fb8f9
		*dst++ = *src++;
8fb8f9
	}
8fb8f9
8fb8f9
	if (flags & TPAX_DRIVER_PURE_PATH_OUTPUT)
8fb8f9
		if ((src[0] == '.') && (src[1] == '/'))
8fb8f9
			for (++src; *src=='/'; src++)
8fb8f9
				(void)0;
8fb8f9
8fb8f9
	for (; *src; ) {
8fb8f9
		if ((src[0] == '.') && (src[1] == '.')) {
8fb8f9
			if ((src[2] == '/') || (src[2] == '\0')) {
8fb8f9
				if (flags & TPAX_DRIVER_STRICT_PATH_INPUT) {
8fb8f9
					errno = EINVAL;
8fb8f9
					return -1;
8fb8f9
				}
8fb8f9
			}
8fb8f9
		}
8fb8f9
8fb8f9
		if (flags & TPAX_DRIVER_PURE_PATH_OUTPUT) {
8fb8f9
			if ((src[0] == '.') && (src[1] == '/') && (src[-1] == '/')) {
8fb8f9
				for (++src; *src=='/'; src++)
8fb8f9
					(void)0;
8fb8f9
8fb8f9
			} else if ((src[0] == '/')) {
8fb8f9
				for (src++; *src=='/'; src++)
8fb8f9
					(void)0;
8fb8f9
8fb8f9
				*dst++ = '/';
8fb8f9
8fb8f9
			} else {
8fb8f9
				*dst++ = *src++;
8fb8f9
			}
8fb8f9
		} else {
8fb8f9
			*dst++ = *src++;
8fb8f9
		}
8fb8f9
8fb8f9
		if (dst == cap) {
8fb8f9
			errno = ENOBUFS;
8fb8f9
			return -1;
8fb8f9
		}
8fb8f9
	}
8fb8f9
8fb8f9
	if (nwritten)
8fb8f9
		*nwritten = dst - dstpath;
8fb8f9
8fb8f9
	*dst = '\0';
8fb8f9
8fb8f9
	return 0;
8fb8f9
}