Repository navigation
Expand file tree
/
Copy pathserver.c
More file actions
75 lines (60 loc) · 2.36 KB
/
Copy pathserver.c
File metadata and controls
75 lines (60 loc) · 2.36 KB
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
#include "ftp.h"
typedef struct {
int socket;
struct sockaddr_in address;
} client_info_t;
int list_directory(char* buffer, size_t buffer_size) {
FILE* fp = popen("ls", "r");
if (!fp) return -1;
size_t bytes_read = fread(buffer, 1, buffer_size - 1, fp);
buffer[bytes_read] = '\0';
pclose(fp);
return bytes_read;
}
void* handle_client(void* arg) {
client_info_t* client = (client_info_t*)arg;
int client_socket = client->socket;
char buffer[BUFFER_SIZE];
char command[64], filename[MAX_FILENAME];
printf("Client connected from %s\n", inet_ntoa(client->address.sin_addr));
send_response(client_socket, RESP_OK, "FTP Server Ready");
while (1) {
memset(buffer, 0, sizeof(buffer));
if (recv(client_socket, buffer, sizeof(buffer) - 1, 0) <= 0) break;
if (sscanf(buffer, "%63s %255s", command, filename) < 1) {
send_response(client_socket, RESP_ERROR, "Invalid command");
continue;
}
printf("Command: %s\n", command);
if (strcmp(command, CMD_LIST) == 0) {
char file_list[BUFFER_SIZE];
if (list_directory(file_list, sizeof(file_list)) >= 0) {
send_response(client_socket, RESP_OK, "File list follows");
send(client_socket, file_list, strlen(file_list), 0);
} else {
send_response(client_socket, RESP_ERROR, "Cannot list directory");
}
} else if (strcmp(command, CMD_GET) == 0) {
if (access(filename, F_OK) == 0) {
send_response(client_socket, RESP_OK, "Sending file");
send_file(client_socket, filename);
} else {
send_response(client_socket, RESP_NOT_FOUND, "File not found");
}
} else if (strcmp(command, CMD_PUT) == 0) {
send_response(client_socket, RESP_OK, "Ready to receive");
if (receive_file(client_socket, filename) == 0) {
printf("File %s uploaded successfully\n", filename);
}
} else if (strcmp(command, CMD_QUIT) == 0) {
send_response(client_socket, RESP_OK, "Goodbye");
break;
} else {
send_response(client_socket, RESP_ERROR, "Unknown command");
}
}
printf("Client disconnected\n");
close(client_socket);
free(client);
return NULL;
}