-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcwd.c
116 lines (103 loc) · 2.03 KB
/
cwd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <pwd.h>
#include <sys/types.h>
#include "commands.h"
#include "cwd.h"
#include "logging.h"
#include "mystring.h"
char *cwd = NULL;
int bftpd_cwd_chdir(char *dir)
{
char *tmp = bftpd_cwd_mappath(dir);
if (! tmp)
return -1;
if (chdir(tmp)) {
free(tmp);
return errno;
}
cwd = realloc(cwd, strlen(tmp) + 1);
if (! cwd)
{
free(tmp);
return -1;
}
strcpy(cwd, tmp);
new_umask();
free(tmp);
return 0;
}
char *bftpd_cwd_getcwd()
{
if (cwd)
return strdup(cwd);
else
return NULL;
}
void appendpath(char *result, char *tmp)
{
if (!strcmp(tmp, "."))
return;
if (!strcmp(tmp, "..")) {
if (strcmp(result, "/")) {
if (result[strlen(result) - 1] == '/')
result[strlen(result) - 1] = '\0';
tmp = result;
while (strchr(tmp, '/'))
tmp = strchr(tmp, '/') + 1;
*tmp = '\0';
if ((result[strlen(result) - 1] == '/') && (strlen(result) > 1))
result[strlen(result) - 1] = '\0';
}
} else {
if (result[strlen(result) - 1] != '/')
strcat(result, "/");
strcat(result, tmp);
}
}
char *bftpd_cwd_mappath(char *path)
{
char *result = malloc(strlen(path) + strlen(cwd) + 16);
char *path2;
char *tmp;
if (! result)
return NULL;
path2 = strdup(path);
if (! path2)
{
free(result);
return NULL;
}
if (path[0] == '/')
strcpy(result, "/");
else
strcpy(result, cwd);
while (strchr(path2, '/')) {
tmp = strdup(path2);
if (tmp)
{
*strchr(tmp, '/') = '\0';
cutto(path2, strlen(tmp) + 1);
appendpath(result, tmp);
free(tmp);
}
}
appendpath(result, path2);
free(path2);
return result;
}
void bftpd_cwd_init()
{
cwd = malloc(256);
getcwd(cwd, 255);
}
void bftpd_cwd_end()
{
if (cwd) {
free(cwd);
cwd = NULL;
}
}