Tomato 1.28
[tomato.git] / release / src / router / pptp-client / dirutil.c
blobd736b828bed76ef3367d252832cfc22a460a9709
1 /* dirutil.c ... directory utilities.
2 * C. Scott Ananian <cananian@alumni.princeton.edu>
4 * $Id: dirutil.c,v 1.1.1.1 2002/07/25 06:52:39 honor 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) {
16 char *dup = strdup(pathname);
17 char *ptr = strrchr(stripslash(dup), '/');
18 if (ptr==NULL) return dup;
19 ptr = strdup(ptr+1);
20 free(dup);
21 return ptr;
23 /* Return malloc'ed string representing directory name (no trailing slash) */
24 char *dirname(char *pathname) {
25 char *dup = strdup(pathname);
26 char *ptr = strrchr(stripslash(dup), '/');
27 if (ptr==NULL) { free(dup); return strdup("."); }
28 if (ptr==dup && dup[0]=='/') ptr++;
29 *ptr = '\0';
30 return dup;
32 /* In-place modify a string to remove trailing slashes. Returns arg.
33 * stripslash("/") returns "/";
35 char *stripslash(char *pathname) {
36 int len = strlen(pathname);
37 while (len > 1 && pathname[len-1]=='/')
38 pathname[--len]='\0';
39 return pathname;
41 /* ensure dirname exists, creating it if necessary. */
42 int make_valid_path(char *dir, mode_t mode) {
43 struct stat st;
44 char *tmp=NULL, *path = stripslash(strdup(dir));
45 int retval;
46 if (stat(path, &st) == 0) { /* file exists */
47 if (S_ISDIR(st.st_mode)) { retval=1; goto end; }
48 else { retval=0; goto end; } /* not a directory. Oops. */
50 /* Directory doesn't exist. Let's make it. */
51 /* Make parent first. */
52 if (!make_valid_path(tmp = dirname(path), mode)) { retval=0; goto end; }
53 /* Now make this 'un. */
54 if (mkdir(path, mode) < 0) { retval=0; goto end; }
55 /* Success. */
56 retval=1;
58 end:
59 if (tmp!=NULL) free(tmp);
60 if (path!=NULL) free(path);
61 return retval;