-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.cpp
553 lines (509 loc) · 15.1 KB
/
connection.cpp
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
#include "connection.h"
#include "ftp.h"
#include "utils.h"
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
std::string PermissionString(int permission);
ssize_t SendFile(int out_fd, int in_fd, off_t * offset, size_t count);
/**
* Generate random port for passive mode
*/
void GenPort(Port *port)
{
srand(time(NULL));
port->p1 = 128 + (rand() % 64);
port->p2 = rand() % 0xff;
}
void Connection::Run() {
Print("Connection start running...\n");
SendMessage("220 Welcome to ftp service built by dafeng & shukui. \r\n");
char buffer[kBufferSize] = {0};
Print("send mes done\n");
while (status_ != kClosed) {
int bytes_read = read(sock_, buffer, kBufferSize);
if (bytes_read == 0 || bytes_read < 0) {
Print("[socket read error]bytes read: %d\n", bytes_read);
break;
}
if(bytes_read > kBufferSize) {
Print("Server read error :(\n");
break;
}
buffer[kBufferSize - 1] = '\0';
Print("User %s sent command: %s\n",(username_ == 0)?"unknown":username_, buffer);
Command cmd(buffer);
/* Ignore non-ascii char. Ignores telnet command */
if(buffer[0]<=127 && buffer[0]>=0) {
Response(cmd);
}
memset(buffer, 0, sizeof buffer);
}
close(sock_);
Print("Closing... :)\n");
}
void Connection::Response(const Command& cmd) {
const char* arg = cmd.arg;
switch(LookUpCommand(cmd.command)) {
case ABOR: FtpAbor(arg); break;
case CWD: FtpCwd (arg); break;
case DELE: FtpDele(arg); break;
case LIST: FtpList(arg); break;
case MDTM: FtpMdtm(arg); break;
case MKD: FtpMkd (arg); break;
case NLST: FtpNlst(arg); break;
case NOOP: FtpNoop(arg); break;
case PASS: FtpPass(arg); break;
case PASV: FtpPasv(arg); break;
case PORT: FtpPort(arg); break;
case PWD: FtpPwd (arg); break;
case QUIT: FtpQuit(arg); break;
case RETR: FtpRetr(arg); break;
case RMD: FtpRmd (arg); break;
case RNFR: FtpRnfr(arg); break;
case RNTO: FtpRnto(arg); break;
case SITE: FtpSite(arg); break;
case SIZE: FtpSize(arg); break;
case STOR: FtpStor(arg); break;
case TYPE: FtpType(arg); break;
case USER: FtpUser(arg); break;
default: SendMessage("500 Unknown command\r\n");
}
}
void Connection::SendMessage(const char* message) {
int ret = write(sock_, message, strlen(message));
if (ret < 0) {
perror("[socket write error]\n");
exit(-1);
}
Print("%s\n", message);
}
/**
* ABOR command
* Incomplete
*/
void Connection::FtpAbor(const char* arg) {
if (!logged_in_) {
SendMessage("530 Please login with USER and PASS.\r\n");
return;
}
SendMessage("226 Closing data connection.\r\n");
}
/** CWD command */
void Connection::FtpCwd(const char* arg) {
if(logged_in_) {
if(chdir(arg) == 0){
SendMessage("250 Directory successfully changed.\r\n");
} else {
SendMessage("550 Failed to change directory.\r\n");
}
} else {
SendMessage("530 Please login with USER and PASS.\r\n");
}
}
/** DELE command */
void Connection::FtpDele(const char* arg) {
if (!logged_in_) {
SendMessage("530 Please login with USER and PASS.\r\n");
return;
}
if(unlink(arg) == -1) {
SendMessage("550 File unavailable.\r\n");
} else {
SendMessage("250 Requested file action okay, completed.\r\n");
}
}
/** LIST command */
void Connection::FtpList(const char* arg) {
if(logged_in_){
char current_dir[kBufferSize] = {0};
char original_dir[kBufferSize] = {0};
/* Later we want to go to the original path */
getcwd(original_dir, kBufferSize);
/* Just chdir to specified path */
if(strlen(arg) > 0 && arg[0]!='-'){
chdir(arg);
}
getcwd(current_dir, kBufferSize);
DIR *dir = opendir(current_dir);
if(!dir){
SendMessage("550 Failed to open directory.\r\n");
}else{
if(mode_ == kServer){
int data_connection = AcceptConnection(sock_pasv_);
SendMessage("150 Here comes the directory listing.\r\n");
dirent *entry;
while(entry = readdir(dir)) {
struct stat statbuf;
if(stat(entry->d_name, &statbuf) == -1) {
Print("FTP: Error reading file stats...\n");
} else{
/* Convert time_t to tm struct */
time_t rawtime = statbuf.st_mtime;
struct tm *time = localtime(&rawtime);
char timebuff[80] = {0};
strftime(timebuff, 80, "%b %d %H:%M", time);
std::string permission = PermissionString(statbuf.st_mode & ALLPERMS);
dprintf(data_connection,
"%c%s %5lu %4d %4d %8ld %s %s\r\n",
(entry->d_type==DT_DIR)?'d':'-',
permission.c_str(),
statbuf.st_nlink,
statbuf.st_uid,
statbuf.st_gid,
statbuf.st_size,
timebuff,
entry->d_name);
}
}
SendMessage("226 Directory send OK.\r\n");
mode_ = kNormal;
close(data_connection);
close(sock_pasv_);
sock_pasv_ = -1;
} else if(mode_ == kClient) {
SendMessage("502 PORT mode not implemented.\r\n");
} else {
SendMessage("425 Use PASV or PORT first.\r\n");
}
}
closedir(dir);
chdir(original_dir);
} else {
SendMessage("530 Please login with USER and PASS.\r\n");
}
mode_ = kNormal;
}
/** MDTM command */
void Connection::FtpMdtm(const char* arg) {
SendMessage("502 MDTM command not implemented yet\r\n");
}
/** MKD command */
void Connection::FtpMkd(const char* arg) {
if(logged_in_){
char current_dir[kBufferSize] = {0};
getcwd(current_dir, kBufferSize);
/* TODO: check if directory already exists with chdir? */
if(arg[0] == '/') { /* Absolute path */
if(mkdir(arg, S_IRWXU) == 0) {
char result[kBufferSize + 20] = {0};
sprintf(result, "257 \"%s\" new directory created.\r\n", arg);
SendMessage(result);
} else {
SendMessage("550 Failed to create directory. Check path or permissions.\r\n");
}
} else { /* Relative path */
if(mkdir(arg, S_IRWXU) == 0) {
char result[kBufferSize + 20] = {0};
sprintf(result,"257 \"%s/%s\" new directory created.\r\n", current_dir, arg);
SendMessage(result);
}else{
SendMessage("550 Failed to create directory. Check path or permissions.\r\n");
}
}
} else {
SendMessage("530 Please login with USER and PASS.\r\n");
}
}
/** NLST command*/
void Connection::FtpNlst(const char* arg) {
SendMessage("502 NLST command not implemented yet\r\n");
}
/** Noop command*/
void Connection::FtpNoop(const char* arg) {
SendMessage("200 Nice to NOOP you!\r\n");
}
/** PASS command */
void Connection::FtpPass(const char* arg) {
if(strlen(username_) > 0){
logged_in_ = true;
SendMessage("230 Login successful\r\n");
} else {
SendMessage("500 Invalid username or password\r\n");
}
}
/** PASV command */
void Connection::FtpPasv(const char* arg) {
if (logged_in_) {
int ip[4];
GetIp(sock_,ip);
Port port;
srv->GetPort(&port);
/* Close previous passive socket */
if (sock_pasv_ > 0) {
close(sock_pasv_);
}
/* Start listening here, but don't accept the connection */
sock_pasv_ = CreateSocket(256 * port.p1 + port.p2);
// 若端口被占用则重新分配
while(sock_pasv_ < 0) {
srv->GetPort(&port);
sock_pasv_ = CreateSocket(256 * port.p1 + port.p2);
}
char buff[255];
sprintf(buff, "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n",
ip[0], ip[1], ip[2], ip[3], port.p1, port.p2);
SendMessage(buff);
Print("%s\n", buff);
mode_ = kServer;
}
else {
SendMessage("530 Please login with USER and PASS.\r\n");
}
}
/** PORT command */
void Connection::FtpPort(const char* arg) {
SendMessage("502 PORT command not implemented yet\r\n");
}
/** PWD command */
void Connection::FtpPwd(const char* arg) {
if(logged_in_) {
char current_dir[kBufferSize];
char result[kBufferSize];
memset(result, 0, kBufferSize);
if (getcwd(current_dir, kBufferSize) != NULL){
sprintf(result, "257 \"%s\"\r\n", current_dir);
SendMessage(result);
} else {
SendMessage("550 Failed to get pwd.\n");
}
} else {
SendMessage("530 Please login with USER and PASS.\r\n");
}
}
/** QUIT command */
void Connection::FtpQuit(const char* arg) {
SendMessage("221 Goodbye, friend. Have a good night.\r\n");
status_ = kClosed;
}
/** RETR command */
void Connection::FtpRetr(const char* arg) {
if (!logged_in_) {
SendMessage("530 Please login with USER and PASS.\r\n");
return;
}
if (mode_ == kServer) { /* Passive mode */
int fd;
if(access(arg,R_OK) == 0 && (fd = open(arg,O_RDONLY))) {
struct stat stat_buf;
fstat(fd, &stat_buf);
SendMessage("150 Opening BINARY mode data connection.\r\n");
int data_connection = AcceptConnection(sock_pasv_);
close(sock_pasv_);
off_t offset = 0;
int sent_total = SendFile(data_connection, fd, &offset, stat_buf.st_size);
if(sent_total == stat_buf.st_size) {
SendMessage("226 File send OK.\r\n");
} else if (sent_total == 0) {
SendMessage("550 Failed to read file.\r\n");
} else {
SendMessage("550 Failed to send file.\r\n");
}
close(fd);
close(data_connection);
} else {
SendMessage("550 Failed to get file\r\n");
}
} else if (mode_ == kClient) {
SendMessage("550 Please use PASV instead of PORT.\r\n");
} else {
SendMessage("425 Use PASV or PORT first.\r\n");
}
}
/** RMD Command*/
void Connection::FtpRmd(const char* arg) {
if (!logged_in_) {
SendMessage("530 Please login with USER and PASS.\r\n");
return;
}
if(rmdir(arg) == 0) {
SendMessage("250 Requested file action okay, completed.\r\n");
} else {
SendMessage("550 Cannot delete directory.\r\n");
}
}
/** RNFR command */
void Connection::FtpRnfr(const char* arg) {
SendMessage("502 RNFR command not implemented yet\r\n");
}
/** RNTO command */
void Connection::FtpRnto(const char* arg) {
SendMessage("502 RNTO command not implemented yet\r\n");
}
/** SITE command */
void Connection::FtpSite(const char* arg) {
SendMessage("502 SITE command not implemented yet\r\n");
}
/** SIZE command*/
void Connection::FtpSize(const char* arg) {
if (!logged_in_) {
SendMessage("530 Please login with USER and PASS.\r\n");
return;
}
struct stat statbuf;
char filesize[128] = {0};
if(stat(arg, &statbuf) == 0) { /* Success */
sprintf(filesize, "213 %ld\r\n", statbuf.st_size);
SendMessage(filesize);
} else {
SendMessage("550 Could not get file size.\r\n");
}
}
/** STOR command */
void Connection::FtpStor(const char* arg) {
if (!logged_in_) {
SendMessage("530 Please login with USER and PASS.\r\n");
return;
}
if (mode_ == kNormal) {
SendMessage("425 Use PASV or PORT first.\r\n");
return;
}
FILE *file = fopen(arg,"w");
if (file == NULL) {
SendMessage("551 Cannot open file.\r\n");
return;
}
int fd = fileno(file);
if (mode_ == kServer) { /* Passive mode */
int data_connection = AcceptConnection(sock_pasv_);
close(sock_pasv_);
int pipefd[2];
if (pipe(pipefd) == -1) {
SendMessage("451 Local error: cannot open pipe.\r\n");
close(fd);
close(data_connection);
return;
}
SendMessage("125 Data connection already open; transfer starting.\r\n");
int res = 1;
const int buff_size = 8192;
while ((res = splice(data_connection, 0, pipefd[1], NULL, buff_size, SPLICE_F_MORE | SPLICE_F_MOVE)) > 0) {
splice(pipefd[0], NULL, fd, 0, buff_size, SPLICE_F_MORE | SPLICE_F_MOVE);
}
/* Internal error */
if(res == -1){
SendMessage("451 File send failed.\r\n");
}else{
SendMessage("226 File send OK.\r\n");
}
close(data_connection);
} else {
SendMessage("550 Please use PASV instead of PORT.\r\n");
}
mode_ = kNormal;
close(fd);
}
/**
* TYPE command.
* BINARY only at the moment.
*/
void Connection::FtpType(const char* arg) {
if (!logged_in_) {
SendMessage("530 Please login with USER and PASS.\r\n");
return;
}
if (arg[0] == 'I') {
SendMessage("200 Switching to Binary mode.\r\n");
} else if (arg[0] == 'A') {
SendMessage("200 Switching to ASCII mode.\r\n");
} else {
SendMessage("504 Command not implemented for that parameter.\r\n");
}
}
/** USER command */
void Connection::FtpUser(const char* arg) {
if(strlen(arg) < 30){
strcpy(username_, arg);
SendMessage("331 User name okay, need password\r\n");
}else{
SendMessage("530 Invalid username\r\n");
}
}
ssize_t SendFile(int out_fd, int in_fd, off_t * offset, size_t count)
{
const int BUF_SIZE = 8192;
off_t orig;
char buf[BUF_SIZE];
size_t toRead, numRead, numSent, totSent;
if (offset != NULL) {
/* Save current file offset and set offset to value in '*offset' */
orig = lseek(in_fd, 0, SEEK_CUR);
if (orig == -1)
return -1;
if (lseek(in_fd, *offset, SEEK_SET) == -1)
return -1;
}
totSent = 0;
while (count > 0) {
toRead = count < BUF_SIZE ? count : BUF_SIZE;
numRead = read(in_fd, buf, toRead);
if (numRead == -1)
return -1;
if (numRead == 0)
break; /* EOF */
numSent = write(out_fd, buf, numRead);
if (numSent == -1)
return -1;
if (numSent == 0) { /* Should never happen */
perror("sendfile: write() transferred 0 bytes");
exit(-1);
}
count -= numSent;
totSent += numSent;
}
if (offset != NULL) {
/* Return updated file offset in '*offset', and reset the file offset
to the value it had when we were called. */
*offset = lseek(in_fd, 0, SEEK_CUR);
if (*offset == -1)
return -1;
if (lseek(in_fd, orig, SEEK_SET) == -1)
return -1;
}
return totSent;
}
/* String mappings for cmdlist */
static const char *command_str[] = {
"ABOR", "CWD", "DELE", "LIST", "MDTM", "MKD", "NLST", "PASS", "PASV",
"PORT", "PWD", "QUIT", "RETR", "RMD", "RNFR", "RNTO", "SITE", "SIZE",
"STOR", "TYPE", "USER", "NOOP"
};
CommandType LookUpCommand(const char* cmd) {
static std::map<std::string, CommandType> mapping;
int count = sizeof(command_str) / sizeof(char*);
if (mapping.empty()) {
for (int i = 0; i < count; i++) {
mapping[command_str[i]] = static_cast<CommandType>(i);
}
}
return mapping.count(cmd) ? mapping[cmd] : Unknown;
}
/**
* Converts permissions to string. e.g. rwxrwxrwx
* @param perm Permissions mask
* @param str Pointer to string representation of permissions, should be empty
*/
std::string PermissionString(int permission) {
int curperm = 0;
int flag = 0;
int read = 0;
int write = 0;
int exec = 0;
/* Flags buffer */
char fbuff[3];
std::string result;
for(int i = 6; i >= 0; i -= 3){
/* Explode permissions of user, group, others; starting with users */
curperm = ((permission & ALLPERMS) >> i ) & 0x7;
memset(fbuff,0,3);
/* Check rwx flags for each*/
read = (curperm >> 2) & 0x1;
write = (curperm >> 1) & 0x1;
exec = (curperm >> 0) & 0x1;
sprintf(fbuff,"%c%c%c",read?'r':'-' ,write?'w':'-', exec?'x':'-');
result += fbuff;
}
return result;
}