1 /* path.c - Routines for manipulating path strings
2 * Copyright (C) 2008 Bruce Guenter <bruce@untroubled.org>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 */
18 #include <errno.h>
19 #include <string.h>
20 #include <unistd.h>
21 #include "twoftpd.h"
22 #include "backend.h"
23 #include <bglibs/path.h>
24
25 str fullpath;
26
validate_fullpath(void)27 static int validate_fullpath(void)
28 {
29 errno = EPERM;
30 if (lockhome) {
31 unsigned long homelen = strlen(home);
32 if (memcmp(fullpath.s, home, homelen) != 0 ||
33 (fullpath.s[homelen] != 0 && fullpath.s[homelen] != '/'))
34 return 0;
35 }
36 if (nodotfiles) {
37 long i;
38 if (fullpath.s[0] == '.') return 0;
39 if (fullpath.s[0] == '/' && fullpath.s[1] == '.') return 0;
40 for (i = str_findlast(&fullpath, '/'); i > 0;
41 i = str_findprev(&fullpath, '/', i-1))
42 if (fullpath.s[i+1] == '.') return 0;
43 }
44 errno = 0;
45 return 1;
46 }
47
qualify(const char * path)48 static int qualify(const char* path)
49 {
50 if (!str_copy(&fullpath, &cwd)) return 0;
51 if (!path_merge(&fullpath, path)) return 0;
52 return 1;
53 }
54
qualify_validate(const char * path)55 int qualify_validate(const char* path)
56 {
57 if (!qualify(path)) {
58 respond_internal_error();
59 return 0;
60 }
61 if (!validate_fullpath()) {
62 respond_permission_denied();
63 return 0;
64 }
65 return 1;
66 }
67
open_fd(const char * filename,int flags,int mode)68 int open_fd(const char* filename, int flags, int mode)
69 {
70 int fd;
71 struct stat st;
72 if (!qualify(filename)) return -1;
73 if (!validate_fullpath()) return -1;
74 if ((fd = open(fullpath.s+1, flags, mode)) == -1) return -1;
75 if (fstat(fd, &st) == 0) {
76 if (S_ISREG(st.st_mode))
77 return fd;
78 else
79 errno = EPERM;
80 }
81 close(fd);
82 return -1;
83 }
84