-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.cpp
310 lines (265 loc) · 10 KB
/
server.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
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <csignal>
#include <random>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <algorithm>
#include <cstring>
#define TOKEN_LENGTH 256
using namespace std;
class Server {
int PORT;
int server_socket;
int client_socket;
struct sockaddr_in address;
int address_length;
public:
Server(int port = 6969) : PORT(port) {
create_socket();
setup_address();
bind_socket();
listen_for_connections();
register_signal_handler();
}
~Server() {
close(server_socket);
}
void run() {
while (true) {
accept_connection();
handle_client();
}
}
private:
void create_socket() {
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("[ERROR] : Socket creation failed");
exit(EXIT_FAILURE);
}
cout << "[LOG] : Socket created successfully.\n";
}
void setup_address() {
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
address_length = sizeof(address);
}
void bind_socket() {
if (bind(server_socket, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("[ERROR] : Bind failed");
exit(EXIT_FAILURE);
}
cout << "[LOG] : Bind successful.\n";
}
void listen_for_connections() {
if (listen(server_socket, 3) < 0) {
perror("[ERROR] : Listen failed");
exit(EXIT_FAILURE);
}
cout << "[LOG] : Listening for connections (Max queue: 3)\n";
}
void accept_connection() {
if ((client_socket = accept(server_socket, (struct sockaddr *)&address, (socklen_t*)&address_length)) < 0) {
perror("[ERROR] : Accept failed");
exit(EXIT_FAILURE);
}
cout << "[LOG] : Connection accepted from client.\n";
}
void handle_client() {
flush_socket_buffer(client_socket);
string token = generate_random_string(TOKEN_LENGTH);
cout << "Token: " << token << '\n';
if (send(client_socket, token.c_str(), token.size() + 1, 0) == -1) { // include null terminator
perror("[ERROR] : Sending token to client failed");
close(client_socket);
return;
}
cout << "[LOG] : Token sent to client. Waiting for hash...\n";
flush_socket_buffer(client_socket);
string expected_hash = to_string(fnv1a_hash(token));
char received_hash[1024] = {0};
if (recv(client_socket, received_hash, sizeof(received_hash), 0) == -1) {
perror("[ERROR] : Receiving hash from client failed");
close(client_socket);
return;
}
cout << "[LOG] : Hash received from client. Checking hash...\n";
if (authenticate_client(string(received_hash), expected_hash)) {
cout << "[LOG] : Hash verified!\n";
send_message("Authentication successful\n");
string folder_name = create_timestamped_folder();
if (!folder_name.empty()) {
cout << "[LOG] : Folder created successfully.\n";
send_message("start");
receive_files(folder_name);
} else {
cout << "[ERROR] : Folder creation failed.\n";
}
} else {
cout << "[LOG] : Hash verification failed!\n";
}
close(client_socket);
}
void flush_socket_buffer(int socket) {
char buffer[1024];
int bytes_available = 0;
if (ioctl(socket, FIONREAD, &bytes_available) == -1) {
perror("[ERROR] : Checking socket buffer failed");
return;
}
while (bytes_available > 0) {
ssize_t bytes_received = recv(socket, buffer, sizeof(buffer), 0);
if (bytes_received <= 0) {
break;
}
bytes_available -= bytes_received;
}
}
string generate_random_string(size_t length) {
const string characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[]{}|;:',.<>?/~`";
random_device rd;
mt19937 generator(rd());
uniform_int_distribution<> distribution(0, characters.size() - 1);
string random_string;
for (size_t i = 0; i < length; ++i) {
random_string += characters[distribution(generator)];
}
return random_string;
}
size_t fnv1a_hash(const string& str) {
const size_t FNV_offset_basis = 14695981039346656037ULL;
const size_t FNV_prime = 1099511628211ULL;
size_t hash = FNV_offset_basis;
for (char c : str) {
hash ^= static_cast<size_t>(c);
hash *= FNV_prime;
}
return hash;
}
bool authenticate_client(const string& received_hash, const string& expected_hash) {
return received_hash == expected_hash;
}
bool create_folder(const string& folder_name) {
cout << "[DEBUG] : Trying to create folder: " << folder_name << endl;
if (folder_name == ".") {
cout << "[DEBUG] : Skipping creation of current directory.\n";
return true;
}
size_t pos = folder_name.find_last_of('/');
if (pos!= string::npos) {
string parent_folder = folder_name.substr(0, pos);
if (!create_folder(parent_folder)) {
return false;
}
}
if (mkdir(folder_name.c_str(), 0755) == -1) {
if (errno == EEXIST) { // Folder already exists, skip error
cout << "[DEBUG] : Folder already exists: " << folder_name << endl;
return true;
} else {
perror("[ERROR] : Creating folder failed");
cout << "[DEBUG] : Error creating folder: " << strerror(errno) << endl;
return false;
}
}
cout << "[DEBUG] : Folder created successfully: " << folder_name << endl;
return true;
}
string create_timestamped_folder() {
time_t now = time(0);
tm *ltm = localtime(&now);
string folder_name = to_string(1900 + ltm->tm_year) + "-" +
to_string(1 + ltm->tm_mon) + "-" +
to_string(ltm->tm_mday) + "_" +
to_string(ltm->tm_hour) + "-" +
to_string(ltm->tm_min) + "-" +
to_string(ltm->tm_sec);
return create_folder(folder_name) ? folder_name : "";
}
void receive_files(const string& folder_name) {
string full_folder_path = "./" + folder_name;
mkdir(full_folder_path.c_str(), 0755); // Create the folder here
string current_folder = full_folder_path; // Use the full folder path as the current folder
while (true) {
flush_socket_buffer(client_socket);
char filename[1024] = {0};
if (recv(client_socket, filename, sizeof(filename), 0) == -1) {
perror("[ERROR] : Receiving filename from client failed");
return;
}
// Check if filename is empty
if (strlen(filename) == 0) {
cerr << "[ERROR] : Received empty filename, skipping.\n";
continue;
}
if (strcmp(filename, "end_of_files") == 0) {
break;
}
if (strncmp(filename, "DIR:", 4) == 0) {
string dir_path = filename + 4; // Skip "DIR:"
dir_path = current_folder + "/" + dir_path;
if (!create_folder(dir_path)) {
perror("[ERROR] : Creating directory failed");
return;
}
cout << "[LOG] : Directory created: " << dir_path << endl;
} else {
cout << "[LOG] : Receiving file: " << filename << endl;
ssize_t filesize;
if (recv(client_socket, &filesize, sizeof(filesize), 0) == -1) {
perror("[ERROR] : Receiving file size from client failed");
return;
}
cout << "[LOG] : File size: " << filesize << " bytes\n";
if (filesize <= 0) {
perror("[ERROR] : Invalid file size received");
return;
}
string filepath = current_folder + "/" + string(filename);
ofstream file(filepath, ios::binary);
if (!file) {
perror("[ERROR] : Opening file for writing failed");
return;
}
char buffer[1024];
size_t bytes_received = 0;
while (bytes_received < filesize) {
ssize_t n = recv(client_socket, buffer, min(sizeof(buffer), filesize - bytes_received), 0);
if (n == -1) {
perror("[ERROR] : Receiving file data from client failed");
return;
}
file.write(buffer, n);
bytes_received += n;
}
cout << "[LOG] : File received and saved to " << filepath << endl;
send_message("File received: " + string(filename));
}
}
cout << "[LOG] : All files received.\n";
}
void send_message(const string& message) {
if (send(client_socket, message.c_str(), message.size() + 1, 0) == -1) { // include null terminator
perror("[ERROR] : Sending message to client failed");
}
}
static void signal_handler(int signum) {
cout << "\nInterrupt signal (" << signum << ") received. Shutting down...\n";
exit(signum);
}
void register_signal_handler() {
signal(SIGINT, signal_handler);
}
};
int main() {
Server server(6969);
server.run();
return 0;
}