Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / pptp-client / dirutil.c
blob8469acb9a688d25c5270945d587f8b27163c09a8
1 /* dirutil.c ... directory utilities.
2 * C. Scott Ananian <cananian@alumni.princeton.edu>
4 * $Id: dirutil.c,v 1.2 2003/06/17 17:25:47 reink Exp $
5 */
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include "dirutil.h"
14 /* Returned malloc'ed string representing basename */
15 char *basenamex(char *pathname)
17 char *dup = strdup(pathname);
18 char *ptr = strrchr(stripslash(dup), '/');
19 if (ptr == NULL) return dup;
20 ptr = strdup(ptr+1);
21 free(dup);
22 return ptr;
25 /* Return malloc'ed string representing directory name (no trailing slash) */
26 char *dirname(char *pathname)
28 char *dup = strdup(pathname);
29 char *ptr = strrchr(stripslash(dup), '/');
30 if (ptr == NULL) { free(dup); return strdup("."); }
31 if (ptr == dup && dup[0] == '/') ptr++;
32 *ptr = '\0';
33 return dup;
36 /* In-place modify a string to remove trailing slashes. Returns arg.
37 * stripslash("/") returns "/";
39 char *stripslash(char *pathname) {
40 int len = strlen(pathname);
41 while (len > 1 && pathname[len - 1] == '/')
42 pathname[--len] = '\0';
43 return pathname;
46 /* ensure dirname exists, creating it if necessary. */
47 int make_valid_path(char *dir, mode_t mode)
49 struct stat st;
50 char *tmp = NULL, *path = stripslash(strdup(dir));
51 int retval;
52 if (stat(path, &st) == 0) { /* file exists */
53 if (S_ISDIR(st.st_mode)) { retval = 1; goto end; }
54 else { retval = 0; goto end; } /* not a directory. Oops. */
56 /* Directory doesn't exist. Let's make it. */
57 /* Make parent first. */
58 if (!make_valid_path(tmp = dirname(path), mode)) { retval = 0; goto end; }
59 /* Now make this 'un. */
60 if (mkdir(path, mode) < 0) { retval = 0; goto end; }
61 /* Success. */
62 retval = 1;
64 end:
65 if (tmp != NULL) free(tmp);
66 if (path != NULL) free(path);
67 return retval;