-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.cpp
531 lines (440 loc) · 13.8 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
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
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <vector>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/un.h>
#include <string.h>
#include <strings.h>
#include <netinet/in.h>
#include <mysql/mysql.h>
#include <arpa/inet.h>
#include <openssl/md5.h>
#define PORT 2908
#define MAX_SIZE 4096
#define MAX_CONNECTION_QUEUE 5
#define MD5_HASH_SIZE 33
#define CHECK_RET(value, msg) { if ((value) < 0) {perror(msg); return;} }
#define CHECK_EXIT(value, msg) { if ((value) < 0) {perror(msg); exit(-1);} }
#define CHECK_WARN(value, msg) { if ((value) < 0) {printf("Warning: "); printf(msg); fflush(stdout);} }
#define CHECK_CONTINUE(value, msg) { if ((value) < 0) {printf("Warning: "); printf(msg); fflush(stdout); continue;} }
#define INFINITE_LOOP while(1)
struct threadArgs
{
pthread_t threadId;
sockaddr_in client;
int clientSocket;
};
enum cmdType
{
CMD_SEARCH,
CMD_DOWNLOAD,
CMD_PUBLISH,
CMD_UNPUBLISH,
CMD_DISCONNECT,
CMD_DOWNLOCATION,
CMD_UNKNOWN
};
enum fileType
{
FILE_TXT,
FILE_AUDIO,
FILE_VIDEO,
FILE_GAME,
FILE_SOFTWARE,
FILE_OTHER,
FILE_UNKNOWN
};
struct publishedFile
{
char name[MAX_SIZE];
double size;
fileType type;
char hash[MD5_HASH_SIZE];
};
struct argsInfo
{
char name[MAX_SIZE];
double maxSize;
double minSize;
fileType type;
char hash[MD5_HASH_SIZE];
};
struct peerInfo
{
unsigned int ip;
int port;
};
enum responseType
{
RESPONSE_ERR = -1,
RESPONSE_OK
};
class DBManager
{
private:
MYSQL* con;
void db_error_warn()
{
fprintf(stderr, "%s\n", mysql_error(con));
}
void db_error_kill()
{
db_error_warn();
mysql_close(con);
mysql_thread_end();
pthread_exit(NULL);
}
public:
DBManager()
{
con = mysql_init(NULL);
if (con == NULL)
db_error_kill();
}
void connect(const char* user, const char* pass, const char* dbName)
{
if (mysql_real_connect(con, "localhost", user, pass, dbName, 0, NULL, 0) == NULL)
db_error_kill();
printf("Connected to the MySQL database\n");
fflush(stdout);
}
int insert_entry(const char* peerName, unsigned int ip, int port,
const char* fileName, fileType type, double size, const char* hash)
{
char command[MAX_SIZE];
const char* types[] = {"text", "audio", "video", "game", "software", "other", "unknown"};
int index = (int) type;
sprintf(command, "INSERT INTO published VALUES (\'%s\', %d, %d, \'%s\', \'%s\', %f, \'%s\')",
peerName, ip, port, fileName, types[index], size, hash);
if (mysql_query(con, command))
{
db_error_warn();
return -1;
}
return 0;
}
int delete_entries(unsigned int ip, int port, const char* fileName, const char* hash)
{
char command[MAX_SIZE];
sprintf(command, "DELETE FROM published WHERE ip=%d AND port=%d AND file=\'%s\' AND hash=\'%s\'",
ip, port, fileName, hash);
if (mysql_query(con, command))
{
db_error_warn();
return -1;
}
return 0;
}
int delete_entries(unsigned int ip, int port)
{
char command[MAX_SIZE];
sprintf(command, "DELETE FROM published WHERE ip=%d AND port=%d",
ip, port);
if (mysql_query(con, command))
{
db_error_warn();
return -1;
}
return 0;
}
int retrieve_entries(char output[], const argsInfo& searchInfo)
{
char command[2 * MAX_SIZE];
strcpy(output, "");
sprintf(command, "SELECT username, file, type, size, hash FROM published WHERE size >= %f",
searchInfo.minSize);
if (strcmp(searchInfo.name, "*") != 0)
{
char add[MAX_SIZE + 20];
sprintf(add, " AND file = \'%s\'", searchInfo.name);
strcat(command, add);
}
if (searchInfo.maxSize != -1)
{
char add[MAX_SIZE];
sprintf(add, " AND size <= %f", searchInfo.maxSize);
strcat(command, add);
}
if (searchInfo.type != FILE_UNKNOWN)
{
const char* types[] = {"text", "audio", "video", "game", "software", "other", "unknown"};
char add[MAX_SIZE];
sprintf(add, " AND type = \'%s\'", types[(int)searchInfo.type]);
strcat(command, add);
}
if (mysql_query(con, command))
{
db_error_warn();
return -1;
}
MYSQL_RES *result = mysql_store_result(con);
if (result == NULL)
{
db_error_warn();
return -1;
}
int num_fields = mysql_num_fields(result);
MYSQL_ROW row;
while ((row = mysql_fetch_row(result)))
{
for(int i = 0; i < num_fields; i++)
{
strcat(output, row[i] ? row[i] : "NULL");
strcat(output, " ");
}
strcat(output, "\n");
}
mysql_free_result(result);
return 0;
}
int retrieve_peer(peerInfo& peer, char fileName[MAX_SIZE], char hash[MD5_HASH_SIZE],
const argsInfo& searchInfo)
{
peer.ip = peer.port = 0;
char command[2 * MAX_SIZE];
sprintf(command, "SELECT * FROM published WHERE size >= %f",
searchInfo.minSize);
if (strcmp(searchInfo.name, "*") != 0)
{
char add[MAX_SIZE + 20];
sprintf(add, " AND file = \'%s\'", searchInfo.name);
strcat(command, add);
}
if (searchInfo.maxSize != -1)
{
char add[MAX_SIZE];
sprintf(add, " AND size <= %f", searchInfo.maxSize);
strcat(command, add);
}
if (searchInfo.type != FILE_UNKNOWN)
{
const char* types[] = {"text", "audio", "video", "game", "software", "other", "unknown"};
char add[MAX_SIZE];
sprintf(add, " AND type = \'%s\'", types[(int)searchInfo.type]);
strcat(command, add);
}
if (strlen(searchInfo.hash) > 0)
{
char add[MAX_SIZE];
sprintf(add, " AND hash = \'%s\'", searchInfo.hash);
strcat(command, add);
}
if (mysql_query(con, command))
{
db_error_warn();
return -1;
}
MYSQL_RES *result = mysql_store_result(con);
if (result == NULL)
{
db_error_warn();
return -1;
}
MYSQL_ROW row;
if ((row = mysql_fetch_row(result)))
{
peer.ip = atoi(row[1]);
peer.port = atoi(row[2]);
strcpy(fileName, row[3]);
strcpy(hash, row[6]);
}
mysql_free_result(result);
return 0;
}
};
void initServer(sockaddr_in& server, int& serverSocket)
{
CHECK_EXIT(serverSocket = socket(AF_INET, SOCK_STREAM, 0), "server socket");
int on = 1;
CHECK_WARN(setsockopt(serverSocket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)), "setsockopt");
bzero(&server, sizeof(server));
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(PORT);
server.sin_family = AF_INET;
CHECK_EXIT(bind(serverSocket, (sockaddr*) &server, sizeof(server)), "bind");
CHECK_EXIT(listen(serverSocket, MAX_CONNECTION_QUEUE), "listen");
}
void executeDisconnect(DBManager& db, const sockaddr_in& client, int openPeerPort)
{
//sterge inregistrarile din baza de date
db.delete_entries(client.sin_addr.s_addr, openPeerPort);
}
void writeResponse(int socket, responseType response)
{
write(socket, &response, sizeof(response));
}
void killThread(const char* message, const sockaddr_in& client, int openPeerPort, DBManager& db)
{
printf("%s\n", message);
executeDisconnect(db, client, openPeerPort);
mysql_thread_end();
pthread_exit(NULL);
}
int readFromClient(int socket, char buff[])
{
int msgLength, bytes;
bytes = read(socket, &msgLength, sizeof(msgLength));
if (bytes <= 0)
return -1;
bytes = read(socket, buff, msgLength);
if (bytes <= 0)
return -1;
buff[msgLength] = '\0';
return 0;
}
template<class T>
int readFromClient(int socket, T& data)
{
int dataSize, bytes;
bytes = read(socket, &dataSize, sizeof(dataSize));
if (bytes <= 0)
return -1;
bytes = read(socket, &data, dataSize);
if (bytes <= 0)
return -1;
return 0;
}
void writeToClient(int socket, char buff[])
{
int msgLength = strlen(buff);
write(socket, &msgLength, sizeof(msgLength));
write(socket, buff, msgLength);
}
template <class T>
void writeToClient(int socket, const T& data)
{
int dataSize = sizeof(data);
write(socket, &dataSize, sizeof(dataSize));
write(socket, &data, dataSize);
}
void executePublish(DBManager& db, int socket, const sockaddr_in& client,
const char* peerName, int openPeerPort)
{
//adauga in baza de date
publishedFile file;
if (readFromClient(socket, file) == -1)
killThread("Read error. Peer probably closed unexpectedly\n", client, openPeerPort, db);
responseType response;
response = (responseType) db.insert_entry(peerName, client.sin_addr.s_addr,
openPeerPort, file.name, file.type, file.size, file.hash);
writeResponse(socket, response);
}
void executeUnpublish(DBManager& db, int socket, const sockaddr_in& client,
const char* peerName, int openPeerPort)
{
//scoate fisierul din baza de date
publishedFile file;
if (readFromClient(socket, file) == -1)
killThread("Read error. Peer probably closed unexpectedly\n", client, openPeerPort, db);
responseType response;
response = (responseType) db.delete_entries(client.sin_addr.s_addr, openPeerPort, file.name, file.hash);
writeResponse(socket, response);
}
void executeSearch(DBManager& db, int socket, const sockaddr_in& client, int openPeerPort)
{
argsInfo searchInfo;
if (readFromClient(socket, searchInfo) == -1)
killThread("Read error. Peer probably closed unexpectedly\n", client, openPeerPort, db);
char searchResult[2 * MAX_SIZE];
responseType response;
response = (responseType) db.retrieve_entries(searchResult, searchInfo);
writeResponse(socket, response);
if (response == RESPONSE_OK)
writeToClient(socket, searchResult);
}
void executeDownload(DBManager& db, int socket, const sockaddr_in& client, int openPeerPort)
{
argsInfo searchInfo;
if (readFromClient(socket, searchInfo) == -1)
killThread("Read error. Peer probably closed unexpectedly\n", client, openPeerPort, db);
peerInfo peer;
char hash[MD5_HASH_SIZE];
char fileName[MAX_SIZE];
responseType response;
response = (responseType) db.retrieve_peer(peer, fileName, hash, searchInfo);
writeResponse(socket, response);
if (response == RESPONSE_OK)
{
writeToClient(socket, peer);
writeToClient(socket, hash);
writeToClient(socket, fileName);
}
}
void executeCommand(DBManager& db, int socket, const sockaddr_in& client, const char* peerName,
int openPeerPort, cmdType type)
{
switch(type)
{
case CMD_DISCONNECT:
executeDisconnect(db, client, openPeerPort);
break;
case CMD_PUBLISH:
executePublish(db, socket, client, peerName, openPeerPort);
break;
case CMD_UNPUBLISH:
executeUnpublish(db, socket, client, peerName, openPeerPort);
break;
case CMD_SEARCH:
executeSearch(db, socket, client, openPeerPort);
break;
case CMD_DOWNLOAD:
executeDownload(db, socket, client, openPeerPort);
default:
break;
}
}
void* runThread(void* arg)
{
pthread_detach(pthread_self());
threadArgs t = *( (threadArgs*)arg );
bool connected = true;
char peerName[MAX_SIZE];
int openPeerPort;
/* deschid o conexiune noua la baza de date pt fiecare thread
ca sa nu am data races */
mysql_thread_init();
DBManager db;
db.connect("test_user", "XRVSskp42ABC@!", "peers");
if (readFromClient(t.clientSocket, peerName) == -1)
killThread("Read error. Peer probably closed unexpectedly\n", t.client, openPeerPort, db);
if (readFromClient(t.clientSocket, openPeerPort) == -1)
killThread("Read error. Peer probably closed unexpectedly\n", t.client, openPeerPort, db);
printf("Connected to user %s sharing through port %d\n", peerName, openPeerPort);
while (connected)
{
cmdType command;
if (readFromClient(t.clientSocket, command) == -1)
killThread("Read error. Peer probably closed unexpectedly\n", t.client, openPeerPort, db);
executeCommand(db, t.clientSocket, t.client, peerName, openPeerPort, command);
if (command == CMD_DISCONNECT)
connected = false;
}
printf("Closing thread for user %s\n", peerName);
close(t.clientSocket);
mysql_thread_end();
return NULL;
}
int main(int argc, char* argv[])
{
sockaddr_in server;
int serverSocket;
initServer(server, serverSocket);
INFINITE_LOOP
{
int clientSocket;
sockaddr_in client;
socklen_t clientSize;
bzero(&client, sizeof(client));
CHECK_CONTINUE(clientSocket = accept(serverSocket, (sockaddr*) &client, &clientSize), "accept error");
threadArgs thread;
thread.clientSocket = clientSocket;
thread.client = client;
pthread_create(&thread.threadId, NULL, &runThread, &thread);
}
return 0;
}