# BRCM_VERSION=3
[bcm963xx.git] / userapps / opensource / ftpd / cwd.c
1 #include <stdio.h>
2 #include <string.h>
3 #include <unistd.h>
4 #include <errno.h>
5 #include <stdlib.h>
6 #include <pwd.h>
7 #include <sys/types.h>
8
9 #include "commands.h"
10 #include "cwd.h"
11 #include "logging.h"
12 #include "mystring.h"
13
14 char *cwd = NULL;
15
16 int bftpd_cwd_chdir(char *dir)
17 {
18         char *tmp = bftpd_cwd_mappath(dir);
19         if (chdir(tmp)) {
20                 free(tmp);
21                 return errno;
22         }
23         cwd = realloc(cwd, strlen(tmp) + 1);
24         strcpy(cwd, tmp);
25         new_umask();
26         free(tmp);
27         return 0;
28 }
29
30 char *bftpd_cwd_getcwd()
31 {
32         return strdup(cwd);
33 }
34
35 void appendpath(char *result, char *tmp)
36 {
37         if (!strcmp(tmp, "."))
38                 return;
39         if (!strcmp(tmp, "..")) {
40         if (strcmp(result, "/")) {
41             if (result[strlen(result) - 1] == '/')
42                 result[strlen(result) - 1] = '\0';
43             tmp = result;
44             while (strchr(tmp, '/'))
45                 tmp = strchr(tmp, '/') + 1;
46             *tmp = '\0';
47             if ((result[strlen(result) - 1] == '/') && (strlen(result) > 1))
48                 result[strlen(result) - 1] = '\0';
49         }
50         } else {
51                 if (result[strlen(result) - 1] != '/')
52                         strcat(result, "/");
53                 strcat(result, tmp);
54         }
55 }
56
57 char *bftpd_cwd_mappath(char *path)
58 {
59         char *result = malloc(strlen(path) + strlen(cwd) + 10);
60         char *path2 = strdup(path);
61         char *tmp;
62         if (path[0] == '/')
63                 strcpy(result, "/");
64         else
65                 strcpy(result, cwd);
66         while (strchr(path2, '/')) {
67                 tmp = strdup(path2);
68                 *strchr(tmp, '/') = '\0';
69                 cutto(path2, strlen(tmp) + 1);
70                 appendpath(result, tmp);
71                 free(tmp);
72         }
73         appendpath(result, path2);
74         free(path2);
75         return result;
76 }
77
78 void bftpd_cwd_init()
79 {
80         cwd = malloc(256);
81         getcwd(cwd, 255);
82 }
83
84 void bftpd_cwd_end()
85 {
86         if (cwd) {
87                 free(cwd);
88                 cwd = NULL;
89         }
90 }