Added missing file (again).
[uftps.git] / apply_path.c
blobc8e22db75d5fca89a516d41363808c6587158fa8
1 /*
2 * User FTP Server, Share folders over FTP without being root.
3 * Copyright (C) 2008 Isaac Jurado
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU General Public License as published by the Free Software
7 * Foundation; either version 2 of the License, or (at your option) any later
8 * version.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 * details.
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
20 #include "uftps.h"
21 #include <string.h>
25 * Apply new path components to an existing working directory. The working
26 * directory is contained (full path) in wd, which is a buffer with a capacity
27 * of size bytes. This working directory path length is len bytes (counting the
28 * null ending).
30 * The function returns the length of the resulting path after walking the path
31 * argument from the working directory. In case the working directory would
32 * exceed size bytes (at any stage), -1 is returning.
34 int apply_path (const char *path, char *wd, int len)
36 int i;
38 if (*path == '/')
40 /* Absolute path, truncate wd */
41 wd[0] = '.';
42 wd[1] = '/';
43 wd[2] = '\0';
44 len = 3;
47 do {
48 /* Combine delimiters */
49 while (*path == '/')
50 path++;
52 if (*path == '\0')
53 /* No more components to apply */
54 break;
56 /* Isolate next component */
57 i = 0;
58 while (path[i] != '/' && path[i] != '\0')
59 i++;
61 if (i == 2 && path[0] == '.' && path[1] == '.')
63 /* Return to parent directory, found ".." */
64 while (wd[len] != '/')
65 len--;
66 if (len == 1)
67 len++; /* Root reached, fix */
68 wd[len] = '\0';
69 len++;
71 else if (i != 1 || path[0] != '.')
73 if (len + i >= LINE_SIZE)
74 return -1;
76 /* Apply component, because it is different than "." */
77 if (len > 3)
78 wd[len - 1] = '/';
79 else
80 len--; /* Skip delimiter at root */
82 memcpy(wd + len, path, i);
83 len += i + 1;
84 wd[len - 1] = '\0';
87 /* Now skip to the next component */
88 path += i;
89 } while (1);
91 return len;