-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.c
142 lines (119 loc) · 2.42 KB
/
common.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
#include "common.h"
static const char commandlist[NCOMMANDS][10] =
{
"get",
"put",
"mget",
"mput",
"delete",
"cd",
"lcd",
"mgetwild",
"mputwild",
"dir",
"ldir",
"ls",
"lls",
"mkdir",
"lmkdir",
"rget",
"rput",
"pwd",
"lpwd",
"ascii",
"binary",
"open",
"help",
"quit",
"exit"
};
unsigned short login_time = 0;
bool server_connected = false;
char cmd_read[CMD_READ_BUFFER_SIZE];
void set0(char *p, size_t size)
{
memset(p, 0, size);
}
static void append_path(struct command* c, char* s)
{
c->npaths++;
char** temppaths = (char**) malloc(c->npaths * sizeof(char*));
if(c->npaths > 1)
memcpy(temppaths, c->paths, (c->npaths - 1) * sizeof(char*));
char* temps = (char*) malloc((strlen(s) + 1) * sizeof(char));
int i;
for(i = 0; *(temps + i) = *(s + i) == ':' ? ' ' : *(s + i); i++)
;
*(temppaths + c->npaths - 1) = temps;
c->paths = temppaths;
}
struct command* userinputtocommand(char s[LENUSERINPUT])
{
struct command* cmd = (struct command*) malloc(sizeof(struct command));
cmd->id = -1;
cmd->npaths = 0;
cmd->paths = NULL;
char* savestate;
char* token;
int i, j;
for(i = 0; ; i++, s = NULL)
{
token = strtok_r(s, " \t\n", &savestate);
if(token == NULL)
break;
if(cmd->id == -1)
for(j = 0; j < NCOMMANDS; j++)
{
if(!strcmp(token, commandlist[j]))
{
cmd->id = j;
break;
}
}// ommitting braces for the "for loop" here is \
disastrous because the else below gets \
associated with the "if inside the for loop". \
#BUGFIX
else
append_path(cmd, token);
}
if(cmd->id == MGET && !strcmp(*cmd->paths, "*"))
cmd->id = MGETWILD;
else if(cmd->id == MPUT && !strcmp(*cmd->paths, "*"))
cmd->id = MPUTWILD;
if(cmd->id != -1)
return cmd;
else
{
return NULL;
}
}
void printcommand(struct command* c)
{
printf("\t\tPrinting contents of the above command...\n");
printf("\t\tid = %d\n", c->id);
printf("\t\tnpaths = %d\n", c->npaths);
printf("\t\tpaths =\n");
int i;
for(i = 0; i < c->npaths; i++)
printf("\t\t\t%s\n", c->paths[i]);
printf("\n");
}
void freecommand(struct command* c)
{
if (c->npaths > 0)
{
int i;
// free strings
for(i = 0; i < c->npaths; i++)
free(c->paths[i]);
free(c->paths);
}
free(c);
}
// 客户端打开任意的本地端口 (N > 1024)
unsigned short get_rand_port()
{
srand((unsigned) time(NULL));
unsigned int number = rand() % 101 + 1; // 产生1-101的随机数
return number + 1024;
}