2 Copyright (C) 2015-2019 "IoT.bzh"
4 author: José Bollo <jose.bollo@iot.bzh>
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
10 http://www.apache.org/licenses/LICENSE-2.0
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
30 #include <sys/types.h>
36 /* a valid subpath is a relative path not looking deeper than root using .. */
37 int subpath_is_valid(const char *path)
41 /* absolute path is not valid */
45 /* inspect the path */
55 if (path[i++] == '.') {
60 if (path[i++] == '/') {
66 while(path[i] && path[i] != '/')
78 * Return the path or NULL is not valid.
79 * Ensure that the path doesn't start with '/' and that
80 * it does not contains sequence of '..' going deeper than
82 * Returns the path or NULL in case of
85 const char *subpath(const char *path)
87 return path && subpath_is_valid(path) ? (path[0] ? path : ".") : NULL;
91 * Normalizes and checks the 'path'.
92 * Removes any starting '/' and checks that 'path'
93 * does not contains sequence of '..' going deeper than
95 * Returns the normalized path or NULL in case of
98 const char *subpath_force(const char *path)
100 while(path && *path == '/')
102 return subpath(path);
105 #if defined(TEST_subpath)
107 void t(const char *subpath, int validity) {
108 printf("%s -> %d = %d, %s\n", subpath, validity, subpath_is_valid(subpath), subpath_is_valid(subpath)==validity ? "ok" : "NOT OK");
120 t("a/b/c/../../..",1);
121 t("a/b/c/../../../.",1);
122 t("./..a/././..b/..c/./.././.././../.",1);
123 t("./..a/././..b/..c/./.././.././.././..",0);
124 t("./..a//.//./..b/..c/./.././/./././///.././.././a/a/a/a/a",1);