-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserverw24.c
More file actions
714 lines (643 loc) · 21.6 KB
/
serverw24.c
File metadata and controls
714 lines (643 loc) · 21.6 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
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#define PORT 8081
// Max Number of Spaces in runCommand
#define MAX_CMD_LEN 1000
// Max File Size of
#define MAX_OUTPUT_SIZE 10000000
// Used in split string function
#define MAX_NO_ARGUMENTS 400
int numberOfClients = 0;
// Helper method to remove spaces from a string
char* stripSpaces(char* word)
{
// Skip leading spaces
while (isspace(*word))
word++;
if (*word == '\0') // If the string is empty or contains only spaces
return word;
// Trim trailing spaces
char* end = word + strlen(word) - 1;
while (end > word && isspace(*end))
end--;
// Null-terminate the trimmed string
*(end + 1) = '\0';
return word;
}
// helper method to remove special characters
void remove_special_chars(char* str)
{
int i, j = 0;
for (i = 0; str[i] != '\0'; i++)
{
// If the character is alphanumeric, keep it
if (isalnum((unsigned char)str[i]))
{
str[j++] = str[i];
}
}
str[j] = '\0'; // Null terminate the resulting string
}
// Helper method to split a given string by the specified delimeter
// eg: ("ls -1", " ") -> ["ls","-1"]
char** splitString(char* str, char* delimenter)
{
int count = 0;
char** tokens = (char**)malloc(MAX_NO_ARGUMENTS * sizeof(char*));
if (tokens == NULL)
{
printf("Memory allocation error\n");
return NULL;
}
// tokenize the string
char* token = strtok(str, delimenter);
while (token != NULL)
{
// allocate memory
tokens[count] = (char*)malloc((strlen(token) + 1) * sizeof(char));
if (tokens[count] == NULL)
{
fprintf(stderr, "Memory allocation error\n");
for (int i = 0; i < count; i++)
free(tokens[i]);
free(tokens);
return NULL;
}
// remove any extra spaces
strcpy(tokens[count], stripSpaces(token));
count++;
token = strtok(NULL, delimenter);
}
// add NULL to indicate end
tokens[count] = NULL;
return tokens;
}
// helper method to split strings
char** split_string(const char* input, char* option)
{
char** words = malloc(4 * sizeof(char*));
if (words == NULL)
{
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
char* copy = strdup(input);
if (copy == NULL)
{
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
char* token = strtok(copy, " ");
int i = 0;
while (token != NULL && i < 4)
{
// Allocate memory for the word with "*." prefix
words[i] = malloc(strlen(token) + 3); // 3 for "*." and null terminator
if (words[i] == NULL)
{
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
remove_special_chars(token); // Remove special characters if needed
if (strcmp(option,"fileExtension")==0)
{
strcpy(words[i], "*."); // Add ".*" before the word
}
if (strcmp(option,"fileSize")==0)
{
strcpy(words[i], ""); // Add ".*" before the word
}
strcat(words[i], token); // Concatenate the word itself
token = strtok(NULL, " ");
i++;
}
// Fill remaining elements with NULL
while (i < 4)
{
words[i] = "";
i++;
}
free(copy);
return words;
}
// helper method to tokenize extensions for w24ft
void tokenize_extensions(const char* str, char* a, char* b, char* c)
{
// Tokenize the input string
char* token;
char* str_copy = strdup(str); // Create a copy for tokenization
token = strtok(str_copy, " ");
// Skip the first token
token = strtok(NULL, " ");
// Assign remaining tokens to variables a, b, c
if (token != NULL)
{
strcpy(a, "*.");
strcat(a, token);
token = strtok(NULL, " ");
}
else
{
strcpy(a, "");
}
if (token != NULL)
{
strcpy(b, "*.");
strcat(b, token);
token = strtok(NULL, " ");
}
else
{
strcpy(b, "");
}
if (token != NULL)
{
strcpy(c, "*.");
strcat(c, token);
}
else
{
strcpy(c, "");
}
free(str_copy);
}
// helper method for escape sequence space to cleanup the string
char* resolve_paths(const char* paths)
{
int length = strlen(paths);
char* resolved_paths = (char*)malloc(3 * length + 1); // Allocate memory for resolved paths
if (resolved_paths == NULL)
{
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
int i = 0, j = 0;
while (i < length)
{
if (paths[i] == ' ' || paths[i] == '(' || paths[i] == ')')
{
resolved_paths[j++] = '\\'; // Escape space or parentheses with "\"
resolved_paths[j++] = paths[i++];
}
else if (paths[i] == '\n')
{
resolved_paths[j++] = ' '; // Replace newline with space
i++;
}
else
{
resolved_paths[j++] = paths[i++]; // Copy other characters as is
}
}
resolved_paths[j] = '\0'; // Null-terminate the resolved paths
return resolved_paths;
}
// helper method to multiple piping commands.
char* commandHelper(char* s) {
char* args[] = { "bash", "-c", s, NULL };
// Create a pipe
int p[2];
if (pipe(p) < 0) {
perror("Pipe creation failed");
exit(EXIT_FAILURE);
}
// Fork a child process
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
}
else if (pid == 0) { // Child process
close(p[0]); // Close reading end of pipe
dup2(p[1], STDOUT_FILENO); // Redirect stdout to the pipe write end
close(p[1]); // Close the write end of the pipe in the child
if (execvp(args[0], args) == -1) {
perror("Execution failed");
exit(EXIT_FAILURE);
}
}
else { // Parent process
close(p[1]); // Close the write end of the pipe in the parent
char* result = (char*)malloc(MAX_OUTPUT_SIZE);
ssize_t total_read = 0;
ssize_t bytes_read;
while ((bytes_read = read(p[0], result + total_read, MAX_OUTPUT_SIZE - total_read)) > 0) {
total_read += bytes_read;
}
if (bytes_read < 0) {
return "\0";
}
close(p[0]); // Close the read end of the pipe in the parent
// Ensure null-termination
result[total_read] = '\0';
return strdup(result);
}
}
// method to create tarfile in serverside with unique id
void createTheTar(char* temp1, char* tarFile)
{
// printf("%s\n",tarFile);
// printf("%s\n",temp1);
char* temp;
asprintf(&temp, "tar -czvf %s --transform='s|.*/||' %s 2>/dev/null",tarFile, temp1);
commandHelper(temp);
}
// Update Log
void updateLog() {
char* temp;
asprintf(&temp, "echo %d > server.txt", numberOfClients);
commandHelper(temp);
}
// ONLY IN SERVER CODE
int totalNumberOfClients = 0;
char* whichServerToConnect() {
totalNumberOfClients += 1;
int serverNumber;
char* temp;
asprintf(&temp, "echo %d > count.txt", totalNumberOfClients);
commandHelper(temp);
// Assign server based on the current number of clients
if (totalNumberOfClients <= 3) {
serverNumber = 8081;
}
else if (totalNumberOfClients <= 6) {
serverNumber = 8082;
}
else if (totalNumberOfClients <= 9) {
serverNumber = 8083;
}
else {
// Round-robin assignment after the first 9 clients
int remainingClients = totalNumberOfClients - 10;
serverNumber = 8081 + (remainingClients % 3);
}
// Convert server number to string and return
static char server[5];
sprintf(server, "%d", serverNumber);
return server;
}
// END ONLY IN SERVER CODE
// helper method to to make 32bit integer
char* addZeros(int num)
{
char* num_str = (char*)malloc(33 * sizeof(char)); // Allocate memory for string, including null terminator
sprintf(num_str, "%032d", num); // Format the integer with leading zeros
return num_str;
}
// helper method to get fileSize
int getFileSize(char* filePath)
{
int input_fd = open(filePath, O_RDONLY);
if (input_fd == -1)
{
perror("Error opening input file");
exit(EXIT_FAILURE);
}
int c = lseek(input_fd, 0, SEEK_END);
close(input_fd);
return c;
}
// helper method to send file from server to client
void sendFile(int client_socket, char* tarFile)
{
// printf("SEND FILE TARFILE NAME : %s \n",tarFile);
sleep(2);
char buffer[1024] = { 0 };
// Sending Start of file byte sequence
// char* fileName = "./temp.tar.gz";
char* fileName = tarFile;
// Calculating file size to send to client
int fileSize = getFileSize(fileName);
// Convert the file size to binary string
char* fileSizeString = addZeros(fileSize);
// Logging size and binary
// printf("%d File size %s", fileSize, fileSizeString);
// opening the file to read
int input_fd = open(fileName, O_RDONLY);
if (input_fd == -1)
{
perror("Error opening input file");
exit(EXIT_FAILURE);
}
// Sending the file size
send(client_socket, fileSizeString, 32, 0);
// Sending File Data
char* tempBuffer[1024] = { 0 };
for (int i = 0; i < fileSize; i++)
{
int br = read(input_fd, tempBuffer, 1);
send(client_socket, tempBuffer, 1, 0);
}
close(input_fd);
unlink(tarFile);
}
// Helper method to send a String from the client to server
void sendString(int client_socket, char* s)
{
int lenght = strlen(s);
// printf("Lenght of s %d\n", lenght);
// Conver the lenght to a string of lenght 8 to send to the client
char* lenghtString = addZeros(lenght);
// Send Length
send(client_socket, lenghtString, 32, 0);
// Send data one byte at a time
for (int i = 0; i < lenght; i++)
{
send(client_socket, &s[i], 1, 0);
}
}
// Helper method to search for a given File
char* searchFiles(char* fileName)
{
char* command;
asprintf(&command, "find ~/ -name %s", fileName);
char* temp = commandHelper(command);
// printf("File Found DAta %s %s\n", command, temp);
if (strlen(temp) == 0)
return strdup("-1");
char* token = strtok(temp, "\n");
return strdup(token);
}
// use the stat command to return details of the file
void getStatOfFile(int client_socket, char* filePath)
{
char* command;
asprintf(&command, "stat -c '%%n\n%%s\n%%w\n%%A' %s", filePath);
// printf("Running this command %s\n", command);
char** result = splitString(commandHelper(command), "\n");
char* output;
asprintf(&output, "FilePath: %s\nFile Size(Bytes): %s\nBirth Time: %s\nAccess Rights: %s\n", result[0], result[1], result[2], result[3]);
sendString(client_socket, output);
}
// helper method to check null condition
int checkCondition(char * command, char * subString){
char* temp = strdup(command);
return strstr(temp, subString)!= NULL;
}
// helper method to check client request for further processing
void crequest(int new_socket)
{
printf("New Client Connected \n");
// Function to handle client requests
char buffer[1024] = { 0 };
int valread;
while (1)
{
// Clear the buffer
memset(buffer, 0, sizeof(buffer));
// Read the lenght of the command that the client is going to send
read(new_socket, buffer, 32);
int sizeofCommand = atoi(buffer);
memset(buffer, 0, sizeof(buffer));
// Get command from the client
int n = read(new_socket, buffer, sizeofCommand);
if (n == 0)
{
break;
}
char* command = strdup(buffer);
printf("Client Request : %s \n", command);
memset(buffer, 0, sizeof(buffer));
// Run the appropriate functions based on the command
if (strcmp(command, "quitc\n") == 0)
{
// If the client sends "quitc", exit the loop and close the connection
// printf("Sever Died\n");
break;
}
else if (checkCondition(command, "w24fn"))
{
// return details of the file if found
char* fileName = strchr(command, ' ') + 1;
char* filePath = searchFiles(fileName);
char* command; // Adjust the size according to your needs
// Construct the command with the filepath enclosed in double quotes
asprintf(&command, "\"%s\"", filePath);
// printf("File Path %s", filePath);
if (strcmp("-1", filePath) == 0)
{
sendString(new_socket, "File not found");
}
else
{
getStatOfFile(new_socket, command);
}
}
else if (strcmp(command, "dirlist -a\n") == 0)
{
char* temp = commandHelper("find ~/ -maxdepth 1 -type d -not -path '*/.*' -print0 | xargs -0 -I{} basename {} | sort");
sendString(new_socket, temp);
free(temp);
}
else if (strcmp(command, "dirlist -t\n") == 0)
{
char* temp = commandHelper("find ~/ -maxdepth 1 -type d -not -path '*/.*' -print0 | xargs -0 -I{} stat --format='%W*{}' {} | sort -t '*' -k 1 | awk -F '*' '{print $2}' | xargs -I{} basename {}");
sendString(new_socket, temp);
free(temp);
}
else if (checkCondition(command, "w24ft"))
{
char** result = split_string(command,"fileExtension");
char *temp2;
asprintf(&temp2, "find ~/ -type f -not -path '*/.*' \\( -name '%s' -o -name '%s' -o -name '%s' \\)", result[1], result[2], result[3]);
// printf("\n Final Command to Run is %s \n", temp2);
if(strlen(commandHelper(strdup(temp2))) == 0){
sendString(new_socket, "no");
continue;
}
sendString(new_socket, "yes");
srand(time(NULL));
char* unique_string = (char*)malloc(100 * sizeof(char));
// Generate random number
int random_number = 100000000 + rand() % 900000000;
// Concatenate random number with the specified format
snprintf(unique_string, 100, "%d.tar.gz", random_number);
createTheTar(resolve_paths(commandHelper(strdup(temp2))),strdup(unique_string));
sendFile(new_socket,strdup(unique_string));
// free(unique_string);
}
else if (checkCondition(command, "w24fz"))
{
char** result = split_string(command,"fileSize");
char *temp2;
asprintf(&temp2, "find ~/ -type f -not -path '*/.*' -size +%dc -size -%dc", atoi(result[1]) - 1, atoi(result[2]) + 1);
// asprintf(&temp2, "find ~/ -type f -not -path '*/.*' \\( -name '%s' -o -name '%s' -o -name '%s' \\)", result[1], result[2], result[3]);
// printf("\n Final Command to Run is %s \n", temp2);
if(strlen(commandHelper(strdup(temp2))) == 0){
sendString(new_socket, "no");
continue;
}
sendString(new_socket, "yes");
srand(time(NULL));
char* unique_string = (char*)malloc(100 * sizeof(char));
// Generate random number
int random_number = 100000000 + rand() % 900000000;
// Concatenate random number with the specified format
snprintf(unique_string, 100, "%d.tar.gz", random_number);
createTheTar(resolve_paths(commandHelper(strdup(temp2))),strdup(unique_string));
sendFile(new_socket,strdup(unique_string));
// free(unique_string);
}
else if (checkCondition(command, "w24fda"))
{
char** result = split_string(command,"fileSize");
char *temp2;
asprintf(&temp2, "find ~/ -type f ! -path '*/.*' -print0 | xargs -0 -I{} stat -c '%%W*{}' {} | awk -v date=$(date -d %s +%%s) -F'*' '$1 > date' | awk -F '*' '{print $2}'", result[1]);
// asprintf(&temp2, "find ~/ -type f -not -path '*/.*' \\( -name '%s' -o -name '%s' -o -name '%s' \\)", result[1], result[2], result[3]);
// printf("\n Final Command to Run is %s \n", temp2);
if(strlen(commandHelper(strdup(temp2))) == 0){
sendString(new_socket, "no");
continue;
}
sendString(new_socket, "yes");
srand(time(NULL));
char* unique_string = (char*)malloc(100 * sizeof(char));
// Generate random number
int random_number = 100000000 + rand() % 900000000;
// Concatenate random number with the specified format
snprintf(unique_string, 100, "%d.tar.gz", random_number);
createTheTar(resolve_paths(commandHelper(strdup(temp2))),strdup(unique_string));
sendFile(new_socket,strdup(unique_string));
// free(unique_string);
}
else if (checkCondition(command, "w24fdb"))
{
char** result = split_string(command,"fileSize");
char *temp2;
asprintf(&temp2, "find ~/ -type f ! -path '*/.*' -print0 | xargs -0 -I{} stat -c '%%W*{}' {} | awk -v date=$(date -d %s +%%s) -F'*' '$1 < date' | awk -F '*' '{print $2}'", result[1]);
// asprintf(&temp2, "find ~/ -type f -not -path '*/.*' \\( -name '%s' -o -name '%s' -o -name '%s' \\)", result[1], result[2], result[3]);
// printf("\n Final Command to Run is %s \n", temp2);
if(strlen(commandHelper(strdup(temp2))) == 0){
sendString(new_socket, "no");
continue;
}
sendString(new_socket, "yes");
srand(time(NULL));
char* unique_string = (char*)malloc(100 * sizeof(char));
// Generate random number
int random_number = 100000000 + rand() % 900000000;
// Concatenate random number with the specified format
snprintf(unique_string, 100, "%d.tar.gz", random_number);
createTheTar(resolve_paths(commandHelper(strdup(temp2))),strdup(unique_string));
sendFile(new_socket,strdup(unique_string));
// free(unique_string);
}
else{
printf("No matches found\n");
}
}
kill(getppid(), SIGFPE);
printf("client disconnected\n");
}
// siginthandler
void sigChildHandler() {
numberOfClients -= 1;
updateLog();
}
int main()
{
signal(SIGFPE, sigChildHandler);
int server_fd, new_socket, valread;
// Socket Address Object(Struct)
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
// Creating socket file descriptor
// Aruments(Address Family [AF_INET/AP_UNIX] , TCP/UDP [SOCK_STREAM/ SOCK_DGRAM], 0 -> Default protocol of next layer)
// Create Raw TCP Socket
// Changed from == to 0 to < 0
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// SKI{}
// Forcefully attaching socket to the port 8081
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
// Before using bind we need to make changes to socket address object
// Setting Socket Family
address.sin_family = AF_INET;
// Setting the ip address
// INADDR_ANY -> Gives me the current IP address of the system
// Convert Host Byte order to Network Byte order
// Host to network long
address.sin_addr.s_addr = htonl(INADDR_ANY);
// Setting the port Number
// Host to network Short (because 16 bits)
address.sin_port = htons(PORT);
// Bind
// ARGS (listening socket fd, server address object, sizeof the address object)
if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
// The server is now ready to listen to client connection
// ARGS (listening socket description, queue lenght)
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
while (1)
{
// Accept the incoming connection
// ARGS (listening socket FD,)
// Need to debug this
if ((new_socket = accept(server_fd, (struct sockaddr*)&address,
(socklen_t*)&addrlen)) < 0)
{
perror("accept");
exit(EXIT_FAILURE);
}
// START ONLY IN SERVER CODE
char buffer[2] = { 0 };
read(new_socket, buffer, 1);
// printf("Server Received %s\n", buffer);
if (strstr(buffer, "0") != NULL) {
sendString(new_socket, whichServerToConnect());
continue;
}
// END ONLY IN SERVER CODE
numberOfClients += 1;
updateLog();
// Fork a child process to handle the client request
int pid = fork();
if (pid < 0)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
// Child process
// Close the listening socket in the child process
close(server_fd);
crequest(new_socket);
exit(0); // Exit the child process
}
else
{
// Parent process
// Close the new socket in the parent process
close(new_socket);
}
}
return 0;
}