-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage_server.c
More file actions
505 lines (413 loc) · 15.1 KB
/
storage_server.c
File metadata and controls
505 lines (413 loc) · 15.1 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
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
#include "header_files.h"
#include "storage_server.h"
#include "file.h"
#include "directory.h"
#define NS_PORT 9090 // PORT for initializing connection with the NameServer
//Global pointers for beggining and last file in struct linked list
extern File* fileHead;
extern File* fileTail;
int ss_id; // Storage server ID
int clientPort; // PORT for communication with the client
int clientSocketID; //Main binded socket for accepting requests from clients
int nsSocketID; // Main socket for communication with the Name server
int nsPort; // PORT for communication with Name server (user-specified)
char nsIP[16]; // Assuming IPv4
char SS_Msg[ERROR_BUFFER_LENGTH];
char paths_file[50] = ".paths_SS.txt";
/* Close the sockets*/
void closeConnection(){
close(clientSocketID);
close(nsSocketID);
cleanUpFileStruct();
}
/* Signal handler in case Ctrl-Z or Ctrl-D is pressed -> so that the socket gets closed */
void handle_signal(int signum){
closeConnection();
exit(signum);
}
// Function to collect accessible paths from the user and store them in a file
// If paths_SS*.txt file already exists, then read the paths from there
void collectAccessiblePaths()
{
char path[PATH_BUFFER_SIZE];
char *filename = ".paths_SS.txt";
// Check if paths file exists
if (fileExists(filename))
{
printf("[+] Reading paths from %s\n", filename);
FILE *file = fopen(filename, "r");
if(file){
while (fgets(path, sizeof(path), file) != NULL)
{
char* index = strchr(path, '\n');
if(index) *index = '\0';
int type = checkFileType(path);
// Invalid path
if(type == -1)
printf("Invalid path\n");
// Path corresponds to a File
else if(type == 0) {
if(addFile(path, 1) != 0){
printf("[-] Error adding file to File struct\n");
}
}
}
fclose(file);
return;
}
}
FILE *file = fopen(paths_file, "w");
if (file == NULL){
perror("[-] Error opening .paths_SS.txt");
return;
}
while (1)
{
printf("Enter an accessible path (or 'exit' to stop): ");
fgets(path, sizeof(path), stdin);
if (strcmp(path, "exit\n") == 0)
break;
else{
char* index = strchr(path, '\n');
if(index) *index = '\0';
}
int type = checkFileType(path);
// Invalid path
if(type == -1)
printf("Invalid path\n");
// Path corresponds to a File
else if(type == 0) {
fprintf(file, "%s\n", path);
addFile(path, 1); // Store the path in a File struct
}
// Path corresponds to a directory
else if(type == 1){
fprintf(file, "%s\n", path); // Write the path to the Path file
}
else{
printf("Internal server error\n");
}
}
fclose(file);
}
/////////////////// FUNCTIONS FOR INITIALIZING THE CONNECTION WITH THE NAME SERVER /////////////////////
int sendInfoToNamingServer(const char *nsIP, int nsPort, int clientPort)
{
/* Function to send vital information to the Naming Server and receive the ss_id */
int nsSocket;
struct sockaddr_in nsAddress;
// Create a socket for communication with the Naming Server
if ((nsSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0){
perror("[-] Error: opening socket for Naming Server");
return -1;
}
memset(&nsAddress, 0, sizeof(nsAddress));
nsAddress.sin_family = AF_INET;
nsAddress.sin_port = htons(NS_PORT);
nsAddress.sin_addr.s_addr = inet_addr(nsIP);
// Connect to the Naming Server
if (connect(nsSocket, (struct sockaddr *)&nsAddress, sizeof(nsAddress)) < 0){
perror("[-] Error: connecting to Naming Server");
close(nsSocket);
return -1;
}
// Prepare the information to send
char infoBuffer[PATH_BUFFER_SIZE], tempBuffer[PATH_BUFFER_SIZE];
snprintf(infoBuffer, sizeof(infoBuffer), "SENDING|STORAGE|SERVER|INFORMATION");
strcat(infoBuffer, ":");
snprintf(tempBuffer, sizeof(infoBuffer), "%s;%d;%d", nsIP, nsPort, clientPort);
strcat(infoBuffer, tempBuffer);
strcat(infoBuffer, ":");
// Open the file for reading
FILE *pathFile = fopen(paths_file, "r");
if (pathFile == NULL){
perror("[-] Error opening path file");
close(nsSocket);
return -1;
}
// Read and concatenat each path specified
char path[PATH_BUFFER_SIZE];
while (fgets(path, sizeof(path), pathFile) != NULL)
{
if(path[strlen(path)-1] == '\n') path[strlen(path)-1] = '\0';
strcat(infoBuffer, path);
strcat(infoBuffer, ":");
}
// Concatenating a "COMPLETED" message
const char *completedMessage = "COMPLETED";
strcat(infoBuffer, completedMessage);
// Sending the information buffer and closing the file descriptor
if (send(nsSocket, infoBuffer, strlen(infoBuffer), 0) < 0){
perror("[-] Error: sending information to Naming Server");
fclose(pathFile);
close(nsSocket);
return -1;
}
fclose(pathFile);
// Connecting a Storage Server ID from the Naming Server on the user input
if((nsSocketID = (open_a_connection_port(nsPort, 1))) == -1){
printf("Error: opening a dedicated socket for communication with NameServer");
return -1;
}
// Receiving the Storage Server ID from NameServer
char responseBuffer[PATH_BUFFER_SIZE];
if (recv(nsSocket, responseBuffer, sizeof(responseBuffer), 0) < 0){
perror("[-] Error: receiving Storage Server ID from Naming Server");
return -1;
}
close(nsSocket);
ss_id = atoi(responseBuffer);
printf("[+] Assigned Storage Server ID: %d\n", ss_id);
printf("[+] Storage Server connected to Nameserver on PORT %d ...\n", nsPort);
return 0;
}
// Function to maintain a heart beat/pulse with the Name server
void* NameServerPulseHandler()
{
// Waiting for connection request from NameServer
int nsSocket = accept(nsSocketID, NULL, NULL);
if (nsSocket < 0){
perror("[-] Name Server accept failed...");
return NULL;
}
char buffer[BUFFER_LENGTH];
if(sendData(nsSocket, "SS") == -1){
printf("[-] Connection with Nameserver is broken\n");
close(nsSocket);
return NULL;
}
int not_received_count = 0;
while(not_received_count < NOT_RECEIVED_COUNT)
{
if(nonBlockingRecvPeriodic(nsSocket, buffer) == -1) {
not_received_count++;
printf("[-] Failed to receive Pulse from the Name server\n");
}
else{
if(strcmp(buffer, "NS") != 0) not_received_count++;
else not_received_count = 0;
}
clock_t start_time = clock();
if(sendData(nsSocket, "SS")) {
not_received_count++;
printf("[-] Failed to send Pulse to the Name server\n");
}
bzero(buffer, BUFFER_LENGTH);
sleep(PERIODIC_HEART_BEAT - ((double)(clock() - start_time)/ CLOCKS_PER_SEC));
}
printf("[-] Connection with Nameserver is broken\n");
close(nsSocket);
return NULL;
}
//////////////// FUNCTIONS TO HANDLE CLIENT BASED COMMUNICATION WITH NAMESERVER ///////////////////
void NameServerThreadHandler()
{
while(1){
int nsSocket = accept(nsSocketID, NULL, NULL);
if (nsSocket < 0) {
perror("[-] Error NameServerThreadHandler(): Nameserver thread accept failed");
continue;
}
printf("[+] Nameserver thread connection request accepted\n");
// Create a new thread for each new Nameserver thread
pthread_t nsThread;
if (pthread_create(&nsThread, NULL, (void*)handleNameServerThread, (void*)&nsSocket) < 0) {
perror("[-] Thread creation failed");
continue;
}
// Detach the thread
if (pthread_detach(nsThread) != 0) {
perror("[-] Error detaching Nameserver thread");
continue;
}
}
return;
}
// Function for communication between NS and SS for client functions
void* handleNameServerThread(void* args)
{
int nsSocket = *(int*)args;
// Receive the operation number and based on that path
int op = receiveOperationNumber(nsSocket);
if(op == -1) {
close(nsSocket);
return NULL;
}
printf("Operation number: %d\n", op);
// Receiving and sending confirmation for the first path
char path[BUFFER_LENGTH], response[100];
if(receivePath(nsSocket, path)){
close(nsSocket);
return NULL;
}
printf("Path: %s\n", path);
// Create File
if(op == atoi(CREATE_FILE)){
createFile(path, response);
if(sendData(nsSocket, response)){
printf("[-] Error sending createFile() response to Name server\n");
}
}
// Create Folder
else if(op == atoi(CREATE_DIRECTORY)){
createDirectory(path, response);
if(sendData(nsSocket, response)){
printf("[-] Error sending createDirectory() response to Name server\n");
}
}
// Delete File
else if(op == atoi(DELETE_FILE)){
deleteFile(path, response);
if(sendData(nsSocket, response)){
printf("[-] Error sending deleteFile() response to Name server\n");
}
}
// Delete Directory
else if(op == atoi(DELETE_DIRECTORY)){
deleteDirectory(path, response);
if(sendData(nsSocket, response)){
printf("[-] Error sending deleteDirectory() response to Name server\n");
}
}
// Copy File
else if(op == atoi(COPY_FILES)){
printf("Inside\n");
printf("Path: %s\n", path);
copyFile(path, response);
if(sendData(nsSocket, response)){
printf("[-] Error sending deleteFile() response to Name server\n");
}
}
// Copy Directory
else if(op == atoi(COPY_DIRECTORY)){
copyDirectory(path, response);
if(sendData(nsSocket, response)){
printf("[-] Error sending deleteDirectory() response to Name server\n");
}
}
close(nsSocket);
return NULL;
}
////////////////////// FUNCTIONS TO HANDLE COMMUNICATION WITH CLIENT /////////////////////////
void handleClients()
{
struct sockaddr_in client_address;
socklen_t address_size = sizeof(struct sockaddr_in);
while(1){
int clientSocket = accept(clientSocketID, (struct sockaddr*)&client_address, &address_size);
if (clientSocket < 0) {
perror("[-] Error handleClients(): Client accept failed");
continue;
}
printf("[+] Client connection request accepted from %s:%d\n", inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));
// Create a new thread for each new client
pthread_t clientThread;
if (pthread_create(&clientThread, NULL, (void*)handleClientRequest, (void*)&clientSocket) < 0) {
perror("[-] Thread creation failed");
continue;
}
// Detach the thread
if (pthread_detach(clientThread) != 0) {
perror("[-] Error detaching client thread");
continue;
}
}
return;
}
// Function (thread function) to handle individual client request
void* handleClientRequest(void* argument)
{
// Receiving and validating the Operation number from the client
int clientSocket = *(int*)argument;
int request_no = receiveOperationNumber(clientSocket);
if(request_no == -1) return NULL;
char filepath[MAX_PATH_LENGTH];
//READ FILE
if(request_no == atoi(READ_FILE)) {
if(receive_ValidateFilePath(clientSocket, filepath, READ_FILE, 1) == 0){
UploadFile(clientSocket, filepath);
decreaseReaderCount(filepath);
}
}
// WRITE FILE
else if(request_no == atoi(WRITE_FILE)){
if(receive_ValidateFilePath(clientSocket, filepath, WRITE_FILE, 1) == 0){
DownloadFile(clientSocket, filepath);
openWriteLock(filepath);
}
}
// GET PERMISSIONS
else if(request_no == atoi(GET_FILE_PERMISSIONS)){
if(receive_ValidateFilePath(clientSocket, filepath, GET_FILE_PERMISSIONS, 1) == 0){
getFileMetaData(filepath, clientSocket);
}
}
// COPY FILES
else if(request_no == atoi(COPY_FILES)){
if(receive_ValidateFilePath(clientSocket, filepath, COPY_FILES, 0) == 0){
char filename[BUFFER_LENGTH];
extractFileName(filepath, filename);
DownloadFile(clientSocket, filename);
}
}
close(clientSocket);
return NULL;
}
// Function to receive the "file" path from the client
int receive_ValidateFilePath(int clientSocket, char* filepath, char* operation_no, int check)
{
// Receiving the file path
if(nonBlockingRecv(clientSocket, filepath)){
perror("[-] Error receive_ValidateFilePath(): Unable to receive the file path");
return -1;
}
// Validating the filepath based on return value (ERROR_CODE)
int valid = 0;
if(check) {
valid = validateFilePath(filepath, operation_no);
}
char response[100];
sprintf(response, "%d", valid);
//Sending back the response
if(sendData(clientSocket, response)){
perror("[-] Error receive_validateRequestNo(): Unable to send reply to Path sent");
return -1;
}
return valid;
}
/////////////////////////// MAIN FUNCTION ///////////////////////////
int main(int argc, char *argv[])
{
// Signal handler for Ctrl+C and Ctrl+Z
signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);
// Ask the user for the Naming Server's IP and port and Client communication Port
printf("Enter the IP address of the Naming Server: ");
scanf("%s", nsIP);
printf("Enter the port to talk with the Naming Server: ");
scanf("%d", &nsPort);
printf("Enter the port to talk with the Client: ");
scanf("%d", &clientPort);
getchar(); //For linux users
fflush(stdin);
// Collect accessible paths from the user and store in a file
collectAccessiblePaths();
// Send vital information to the Naming Server and receive the Storage Server ID
int initialiazed = sendInfoToNamingServer(nsIP, nsPort, clientPort);
if (initialiazed == -1) {
printf("[-] Failed to send information to the Naming Server.\n");
return 0;
}
// Create a thread to communicate with the nameserver
pthread_t NameServerThread, NameServerPulseThread;;
pthread_create(&NameServerPulseThread, NULL, (void*)&NameServerPulseHandler, NULL);
pthread_create(&NameServerThread, NULL, (void*)&NameServerThreadHandler, NULL);
// Accepting request from clients - This will loop for ever
clientSocketID = open_a_connection_port(clientPort, MAX_CLIENT_CONNECTIONS);
printf("[+] Storage server listening for clients on PORT %d\n", clientPort);
handleClients();
// Closing connection - This part of the code is never reached
pthread_join(NameServerThread, NULL);
closeConnection();
return 0;
}