• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/router/accel-pptp/src/pppd/plugins/pptp/
1/* dirutil.c ... directory utilities.
2 *               C. Scott Ananian <cananian@alumni.princeton.edu>
3 *
4 * $Id: dirutil.c,v 1.2 2003/06/17 17:25:47 reink Exp $
5 */
6
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"
13
14/* Returned malloc'ed string representing basename */
15char *basenamex(char *pathname)
16{
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;
23}
24
25/* Return malloc'ed string representing directory name (no trailing slash) */
26char *dirnamex(char *pathname)
27{
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;
34}
35
36/* In-place modify a string to remove trailing slashes.  Returns arg.
37 * stripslash("/") returns "/";
38 */
39char *stripslash(char *pathname) {
40    int len = strlen(pathname);
41    while (len > 1 && pathname[len - 1] == '/')
42        pathname[--len] = '\0';
43    return pathname;
44}
45
46/* ensure dirname exists, creating it if necessary. */
47int make_valid_path(char *dir, mode_t mode)
48{
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. */
55    }
56    /* Directory doesn't exist.  Let's make it. */
57    /*   Make parent first. */
58    if (!make_valid_path(tmp = dirnamex(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;
63
64end:
65    if (tmp != NULL) free(tmp);
66    if (path != NULL) free(path);
67    return retval;
68}
69