-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2020202096_semaphore_server.c
More file actions
2888 lines (2588 loc) · 127 KB
/
2020202096_semaphore_server.c
File metadata and controls
2888 lines (2588 loc) · 127 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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define _GNU_SOURCE
///////////////////////////////////////////////////////////////////////
// File Name : 2020202096_semaphore_server.c //
// Date : 2023/05/31 //
// Os : Ubuntu 16.04 LTS 64bits //
// Author : Woo Sung Won //
// Student ID : 2020202096 //
// ----------------------------------------------------------------- //
// Title : System Programming Assignment #3-3 //
// Description : Make semaphore server //
///////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <string.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#include <grp.h>
#include <glob.h>
#include <fnmatch.h>
#include <sys/wait.h>
#include <signal.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/time.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <fcntl.h>
#define URL_LEN 256
#define BUFFSIZE 10240
#define PORTNO 40000
#define MAXCLIENT 10
#define SHM_KEY 40000
void sizeBubbleSort(unsigned int *sizeary, char *str[], int height, int weight, int isRflag);
char *extractNonHidden(char *origin);
char *extractRelativeDir(char *origin);
void initHeightWeight(int *w, int *h, char *dir, int isShowHidden);
void list_directory(int isBackward, FILE *stream, char *dir_path, int isShowHidden, int isHflag, int isSflag, int isRflag);
void optNotEqualPrint(int isBackward, FILE *stream, int a_flag, int l_flag, int foldercnt, int filecnt, char **folderarray, char **filearray, int optcnt, int isHflag, int isSflag, int isRflag);
void printAllOption(FILE *stream, char *directory, int isShowHidden);
void printLFiles(FILE *stream, char *dir, int isHflag, int isSflag, int isRflag);
void bubbleSort(char *str[], int height, int weight);
const char *get_mimetype(const char *filename);
int maxChilds = 0;
int maxIdleNum = 0;
int minIdleNum = 0;
int startProcess = 0;
int maxHistory = 0;
// Declare a client struct
typedef struct client
{
int no; // client number
char ip[INET_ADDRSTRLEN]; // IP address of the client
int port; // port number of the client
int pid; // process ID of the client
time_t time; // time when the client connected
} client;
//client client_list[10][MAXCLIENT]; // array to store the clients
time_t cur_time;
char *c_time;
typedef struct {
int historycount;
client history[10];
int idleprocesscount;
pid_t idlepids[10];
int nonidlecount;
} SharedMemory;
SharedMemory *shared_memory;
pthread_mutex_t mutex;
FILE* log_file;
sem_t* semaphore;
///////////////////////////////////////////////////////////////////////
// initialize_shared_memory //
// ================================================================= //
// Output: void //
// Purpose: Initializes shared memory for interprocess communication //
// and sets initial values. This function uses System V shared memory//
// API for creating shared memory segment. //
///////////////////////////////////////////////////////////////////////
void initialize_shared_memory() {
int shmid = shmget(SHM_KEY, sizeof(SharedMemory) + sizeof(client) * 10, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(1);
}
shared_memory = shmat(shmid, NULL, 0);
if (shared_memory == (SharedMemory *) -1) {
perror("shmat");
exit(1);
}
shared_memory->historycount = 0;
shared_memory->idleprocesscount=0;
shared_memory->nonidlecount=0;
}
///////////////////////////////////////////////////////////////////////
// cleanup_shared_memory //
// ================================================================= //
// Output: void //
// Purpose: Releases and removes shared memory from the system. This //
// function uses System V shared memory API for removing shared //
// memory segment. //
///////////////////////////////////////////////////////////////////////
void cleanup_shared_memory() {
shmdt(shared_memory);
shmctl(SHM_KEY, IPC_RMID, NULL);
}
///////////////////////////////////////////////////////////////////////
// add_history //
// ================================================================= //
// Input: client new_client //
// -> New client data that should be added to history //
// Output: void //
// Purpose: Adds a new client's data to the history in shared memory //
// The function also manages history size to not exceed maximum //
// allowed size. //
///////////////////////////////////////////////////////////////////////
void add_history(client new_client) {
pthread_mutex_lock(&mutex);
// Increase the no of existing clients
for (int i = 0; i < shared_memory->historycount; i++) {
shared_memory->history[i].no++;
}
// Check if the history is full
if (shared_memory->historycount >= maxHistory) {
// Remove the oldest client
for (int i = 0; i < maxHistory - 1; i++) {
shared_memory->history[i] = shared_memory->history[i + 1];
}
shared_memory->historycount = maxHistory - 1; // Decrease the count
}
// Add new client at the start of the history with no 1
new_client.no = 1;
shared_memory->history[shared_memory->historycount++] = new_client;
pthread_mutex_unlock(&mutex);
}
///////////////////////////////////////////////////////////////////////
// print_history //
// ================================================================= //
// Output: void //
// Purpose: Prints connection history from shared memory. The //
// function prints history in reverse order, i.e., most recent //
// connections are printed first. //
///////////////////////////////////////////////////////////////////////
void print_history() {
pthread_mutex_lock(&mutex);
printf("========== Connection History ==========\n");
printf("No.\tIP\t\tPort\tPID\tTime\n");
for (int i = shared_memory->historycount - 1; i >= 0; i--) {
client c = shared_memory->history[i];
printf("%d\t%s\t%d\t%d\t%s", c.no, c.ip, c.port, c.pid, ctime(&c.time));
}
printf("========================================\n");
pthread_mutex_unlock(&mutex);
}
///////////////////////////////////////////////////////////////////////
// add_write //
// ================================================================= //
// Input: void* arg //
// -> Pointer to the log message to write into the log file //
// Output: void* //
// -> Not used in this function //
// Purpose: Adds a log message to the log file. The function uses //
// semaphore for synchronization to prevent concurrent writes to the //
// log file. //
///////////////////////////////////////////////////////////////////////
void* add_write(void* arg){
char* log_message = (char*)arg;
semaphore=sem_open("semaphore",O_RDWR);
sem_wait(semaphore); // 세마,포어 대기
// 로그 파일에 클라이언트 연결 정보 작성
fprintf(log_file, "%s", log_message);
fflush(log_file); // 버퍼 비우기
sem_post(semaphore); // 세마포어 신호
}
///////////////////////////////////////////////////////////////////////
// alarm_handler //
// ================================================================= //
// Input: int signo //
// -> The signal number of the signal that triggered the handler //
// Output: void //
// -> This function does not return a value //
// Purpose: To print connection history every time a signal is //
// received and set a new alarm for the next signal //
///////////////////////////////////////////////////////////////////////
void alarm_handler(int signo)
{
// print the connection history
print_history();
// set the alarm to trigger after 10 seconds
alarm(10);
}
//////////////////////////////////////////////////////////////////////////
// is_accessible //
// =====================================================================//
// Input: const char *ip //
// -> The IP address that needs to be checked for accessibility //
// Output: int //
// -> Returns 1 if the IP is accessible, 0 otherwise //
// Purpose: Check if the given IP is listed as accessible in a specific //
// file ("accessible.usr") //
//////////////////////////////////////////////////////////////////////////
int is_accessible(const char *ip)
{
// open the file "accessible.usr" for reading
FILE *file = fopen("accessible.usr", "r");
if (file == NULL)
{
// print an error message if the file could not be opened
perror("fopen");
return 0;
}
char line[INET_ADDRSTRLEN];
// read the file line by line
while (fgets(line, sizeof(line), file) != NULL)
{
// remove the newline character from the line
line[strcspn(line, "\n")] = '\0';
// use the fnmatch function to match the line with the IP
// if the line matches with the IP, return 1
if (fnmatch(line, ip, 0) == 0)
{
fclose(file);
return 1;
}
}
// close the file and return 0 if no match was found
fclose(file);
return 0;
}
///////////////////////////////////////////////////////////////////////
// read_childproc //
// ================================================================= //
// Input: int sig //
// -> The signal number of the signal that triggered the handler //
// Output: void //
// -> This function does not return a value //
// Purpose: To reap child processes that have terminated to prevent //
// zombie processes. This function is used as a signal handler for //
// the SIGCHLD signal. //
///////////////////////////////////////////////////////////////////////
void read_childproc(int sig)
{
// Declare variables to hold the process ID of the child process
// and the status information of the child process
pid_t pid;
int status;
// The waitpid call waits for any child process to end, returning immediately if none have with the WNOHANG option.
pid = waitpid(-1, &status, WNOHANG);
}
///////////////////////////////////////////////////////////////////////
// sigint_handler //
// ================================================================= //
// Input: int sig //
// -> The signal number of the signal that triggered the function //
// Output: void //
// -> This function does not return a value //
// Purpose: To terminate all child processes and the server itself //
// when a SIGINT signal (Ctrl+C) is received //
///////////////////////////////////////////////////////////////////////
void sigint_handler(int sig)
{
printf("check\n");
pthread_mutex_lock(&mutex);
cur_time = time(NULL);
c_time = ctime(&(cur_time));
c_time[strlen(c_time) - 1] = '\0';
for (int i = 0; i < shared_memory->idleprocesscount; i++) // Iterate through the child processes
{
printf("[%s] %ld process is terminated.\n", c_time, (long)shared_memory->idlepids[i]); // Print a message indicating the termination of a process
kill(shared_memory->idlepids[i], SIGTERM); // Send SIGTERM signal to the child process to terminate it
waitpid(shared_memory->idlepids[i], NULL, 0); // Wait for the child process to terminate
}
pthread_mutex_unlock(&mutex);
printf("[%s] Server is terminated.\n", c_time); // Print a message indicating the termination of the server
exit(0); // Exit the program
}
///////////////////////////////////////////////////////////////////////
// term_exit //
// ================================================================= //
// Input: int sig //
// -> The signal number of the signal that triggered the function //
// Output: void //
// -> This function does not return a value //
// Purpose: To terminate the program when a specific signal is //
// received //
///////////////////////////////////////////////////////////////////////
void term_exit(int sig)
{
exit(0); // Exit the program
}
///////////////////////////////////////////////////////////////////////
// addIdleProcess //
// ================================================================= //
// Input: pid_t pid //
// -> Process ID of the child process to add to idle processes list //
// Output: void //
// Purpose: Adds a process to the idle processes list in shared //
// memory. The function also manages size of idle processes list to //
// not exceed maximum allowed size. //
///////////////////////////////////////////////////////////////////////
void addIdleProcess(pid_t pid) {
pthread_mutex_lock(&mutex);
cur_time = time(NULL);
c_time = ctime(&(cur_time));
c_time[strlen(c_time) - 1] = '\0';
char buffer_thread[1024];
shared_memory->idlepids[shared_memory->idleprocesscount] = pid;
shared_memory->idleprocesscount++;
printf("[%s] IdleProcessCount : %d\n",c_time,shared_memory->idleprocesscount);
sprintf(buffer_thread,"[%s] IdleProcessCount : %d\n",c_time,shared_memory->idleprocesscount);
add_write(buffer_thread);
if (shared_memory->idleprocesscount > maxIdleNum)
{
while (shared_memory->idleprocesscount > 5)
{
// Kill the first process in the array
kill(shared_memory->idlepids[0], SIGKILL);
printf("[%s] %d idleprocess is terminated.\n", c_time, shared_memory->idlepids[0]);
sprintf(buffer_thread, "[%s] %d idleprocess is terminated.\n", c_time, shared_memory->idlepids[0]);
add_write(buffer_thread);
// Shift the remaining elements of the array
for (int i = 0; i < shared_memory->idleprocesscount - 1; i++)
shared_memory->idlepids[i] = shared_memory->idlepids[i + 1];
shared_memory->idleprocesscount--;
printf("[%s] IdleProcessCount : %d\n", c_time, shared_memory->idleprocesscount);
sprintf(buffer_thread, "[%s] IdleProcessCount : %d\n", c_time, shared_memory->idleprocesscount);
add_write(buffer_thread);
}
}
pthread_mutex_unlock(&mutex);
}
///////////////////////////////////////////////////////////////////////
// removeIdleProcess //
// ================================================================= //
// Input: pid_t pid //
// -> Process ID of the child process to remove from idle processes //
// list //
// Output: void //
// Purpose: Removes a process from the idle processes list in shared //
// memory. //
///////////////////////////////////////////////////////////////////////
void removeIdleProcess(pid_t pid) {
pthread_mutex_lock(&mutex);
cur_time = time(NULL);
c_time = ctime(&(cur_time));
c_time[strlen(c_time) - 1] = '\0';
char buffer_thread[1024];
for (int i = 0; i < shared_memory->idleprocesscount; i++) {
if (shared_memory->idlepids[i] == pid) {
// Shift idle pids to remove the specified pid
for (int j = i; j < shared_memory->idleprocesscount - 1; j++) {
shared_memory->idlepids[j] = shared_memory->idlepids[j + 1];
}
shared_memory->idleprocesscount--;
printf("[%s] IdleProcessCount : %d\n",c_time,shared_memory->idleprocesscount);
sprintf(buffer_thread, "[%s] IdleProcessCount : %d\n", c_time, shared_memory->idleprocesscount);
add_write(buffer_thread);
break;
}
}
pthread_mutex_unlock(&mutex);
}
///////////////////////////////////////////////////////////////////////
// isForkNeeded //
// ================================================================= //
// Output: int //
// -> Returns 1 if forking of a new process is needed, 0 otherwise //
// Purpose: Checks if there is a need for forking a new process //
// based on the current number of idle processes. //
///////////////////////////////////////////////////////////////////////
int isForkNeeded(){
pthread_mutex_lock(&mutex);
if ((minIdleNum > shared_memory->idleprocesscount) )
{
printf("true\n");
return 1;
}
else
{
return 0;
}
pthread_mutex_unlock(&mutex);
}
///////////////////////////////////////////////////////////////////////
// get_idle_process_count //
// ================================================================= //
// Output: int //
// -> Returns the current number of idle processes //
// Purpose: To provide a way to get the current number of idle //
// processes. //
///////////////////////////////////////////////////////////////////////
int get_idle_process_count() {
pthread_mutex_lock(&mutex);
int count = shared_memory->idleprocesscount;
pthread_mutex_unlock(&mutex);
return count;
}
///////////////////////////////////////////////////////////////////////
// get_idle_process_count //
// ================================================================= //
// Output: int //
// -> Returns the current number of idle processes //
// Purpose: To provide a way to get the current number of idle //
// processes. //
///////////////////////////////////////////////////////////////////////
void addNonIdleCount() {
pthread_mutex_lock(&mutex);
shared_memory->nonidlecount++;
pthread_mutex_unlock(&mutex);
}
///////////////////////////////////////////////////////////////////////
// removeNonIdleCount //
// ================================================================= //
// Output: void //
// Purpose: Decreases the count of non-idle processes. This function //
// is thread-safe. //
///////////////////////////////////////////////////////////////////////
void removeNonIdleCount() {
pthread_mutex_lock(&mutex);
shared_memory->nonidlecount--;
pthread_mutex_unlock(&mutex);
}
// Main Function
int main(int argc, char *argv[])
{
pthread_t thread_id;
FILE *file = fopen("httpd.conf", "r");
if (file == NULL) {
perror("fopen");
exit(1);
}
// 로그 파일 열기
log_file = fopen("server_log.txt", "a");
// 세마포어 초기화
semaphore = sem_open("semaphore", O_CREAT, 0644, 1);
sem_close(semaphore);
if (semaphore == SEM_FAILED) {
perror("sem_open");
return 1;
}
if (log_file == NULL) {
perror("Failed to open log file");
exit(EXIT_FAILURE);
}
char line[256];
while (fgets(line, sizeof(line), file) != NULL) {
if (strncmp(line, "MaxChilds:", 10) == 0) {
maxChilds = atoi(line + 10);
} else if (strncmp(line, "MaxIdleNum:", 11) == 0) {
maxIdleNum = atoi(line + 11);
} else if (strncmp(line, "MinIdleNum:", 11) == 0) {
minIdleNum = atoi(line + 11);
} else if (strncmp(line, "StartProcess:", 13) == 0) {
startProcess = atoi(line + 13);
} else if (strncmp(line, "MaxHistory:", 11) == 0) {
maxHistory = atoi(line + 11);
}
}
fclose(file);
char buffer_thread[1024];
// Declare variables
struct sockaddr_in server_addr, client_addr;
int server_fd, client_fd;
int len, len_out;
int opt = 1;
struct stat checkstat;
cur_time = time(NULL);
c_time = ctime(&(cur_time));
c_time[strlen(c_time) - 1] = '\0';
pid_t pid;
struct sigaction act;
int state;
// Create a socket
if ((server_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
{
printf("server: Can't open stream socket.");
return 0;
}
// Assign the signal handler function (read_childproc) to the sa_handler field of the sigaction struct
act.sa_handler = read_childproc;
// Clear all bits in the signal set represented by sa_mask, so no signals are blocked during execution of the signal handler
sigemptyset(&act.sa_mask);
// Set the sa_flags field of the sigaction struct to 0, meaning no special behavior is specified
act.sa_flags = 0;
// Install the signal handler for the SIGCHLD signal using the sigaction function
// If successful, sigaction returns 0, and the state variable will hold this value
state = sigaction(SIGCHLD, &act, 0);
// Set socket options
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
// Clear server address
memset(&server_addr, 0, sizeof(server_addr));
// Set server address
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORTNO);
// Bind socket to server address
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
{
perror("server: can't bind local addres\n");
return 0;
}else{
printf("[%s] Server is started\n", c_time);
sprintf(buffer_thread,"[%s] Server is started\n", c_time);
pthread_t server_start;
pthread_create(&server_start, NULL, add_write, buffer_thread);
pthread_join(server_start, NULL);
}
// Listen for connections
listen(server_fd, 5);
len = sizeof(client_addr);
initialize_shared_memory();
pthread_mutex_init(&mutex, NULL);
// Add Signal for Alarm that print history every 10 seconds
signal(SIGALRM, alarm_handler);
alarm(10);
signal(SIGINT, sigint_handler);
// Pre-forking routine
for (int i = 0; i < startProcess; i++)
{
int client_count = 0;
if ((pid = fork()) > 0)
{
printf("[%s] %ld process is forked.\n", c_time, (long)pid);
sprintf(buffer_thread,"[%s] %d process is forked.\n", c_time, pid);
pthread_t add_parent_fork;
pthread_create(&add_parent_fork, NULL, add_write, buffer_thread);
pthread_join(add_parent_fork, NULL);
addIdleProcess(pid);
}
else if (pid == 0)
{
pid_t childpid = getpid();
// Handle incoming connections
signal(SIGUSR1, print_history);
signal(SIGTERM, term_exit);
signal(SIGINT, SIG_IGN);
while (1)
{
// Declare variables
struct in_addr inet_client_address;
char *buffer = NULL;
size_t buffer_size = 0;
FILE *stream = open_memstream(&buffer, &buffer_size);
char buf[BUFFSIZE] = {
0,
};
char tmp[BUFFSIZE] = {
0,
};
char *url = NULL;
char method[BUFFSIZE] = {
0,
};
char *tok = NULL;
char tempbuf[BUFFSIZE] = {
0,
};
// Accept a new connection
len = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &len);
read(client_fd, buf, BUFFSIZE);
strcpy(tempbuf, buf);
char *testok = strtok(tempbuf, " ");
// If accept fails, skip this iteration
if (client_fd < 0)
{
continue;
}
// If IP is accessible, create and set up a new client
if (is_accessible(inet_ntoa(client_addr.sin_addr)) && testok != NULL)
{
// time
cur_time = time(NULL);
c_time = ctime(&(cur_time));
c_time[strlen(c_time) - 1] = '\0';
client new_client;
new_client.no = shared_memory->historycount + 1;
strcpy(new_client.ip, inet_ntoa(client_addr.sin_addr));
new_client.port = ntohs(client_addr.sin_port);
new_client.pid = getpid();
new_client.time = cur_time;
// Add new client to shared memory history
add_history(new_client);
// Get client IP address and print a message
inet_client_address.s_addr = client_addr.sin_addr.s_addr;
// Read client request
// Declare variables
char curdir[10000];
int isBackward = 0;
// Get current working directory
if (getcwd(curdir, sizeof(curdir)) == NULL)
{
perror("getcwd() error");
}
// Copy request to temporary buffer
strcpy(tmp, buf);
// Parse request method and URL
tok = strtok(tmp, " ");
strcpy(method, tok);
if (strcmp(method, "GET") == 0)
{
tok = strtok(NULL, " ");
url = extractNonHidden(tok);
if (*(url + strlen(url) - 1) == '/')
{
*(url + strlen(url) - 1) = '\0';
isBackward = 1;
}
}
// Create a title for the HTML response
int len = strlen(inet_ntoa(inet_client_address)) + strlen("40000") + strlen(url) + 2;
char *title = (char *)malloc(len * sizeof(char));
snprintf(title, len, "%s:%s%s", inet_ntoa(inet_client_address), "40000", url);
if (url[0] == '\0') // if the requested URL is empty
{
url = "."; // set it to the current directory
}
printf("\n========== New Client ==========\n");
printf("TIME : [%s]\n", c_time);
printf("URL : %s\n",url);
printf("IP: %s\n", new_client.ip);
printf("Port: %d\n", new_client.port);
printf("================================\n");
char buffer_thread[1024];
int offset = 0;
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "\n========== New Client ==========\n");
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "TIME : [%s]\n", c_time);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "URL : %s\n",url);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "IP: %s\n", new_client.ip);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "Port: %d\n", new_client.port);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "================================\n");
struct timeval start, end;
gettimeofday(&start, NULL); // 연결 시작 시간 기록
pthread_t add_parent_fork;
pthread_create(&add_parent_fork, NULL, add_write, buffer_thread);
pthread_join(add_parent_fork, NULL);
removeIdleProcess(childpid);
addNonIdleCount();
if (lstat(url, &checkstat) == -1) // check the status of the requested URL
{
// perror("404 Not Found\n"); // print an error message
fprintf(stream,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n");
fprintf(stream, "<html>\n<head>\n");
fprintf(stream, "<link rel=\"icon\" href=\"data:,\">\n"); // add a favicon
fprintf(stream, "<title>%s</title>\n", curdir); // set the page title to the current directory
fprintf(stream, "</head>\n<body>\n");
fprintf(stream, "<h1>");
fprintf(stream, "Not Found");
fprintf(stream, "</h1>");
fprintf(stream, "<b>The request URL %s was not found on this server<br></b>", url);
fprintf(stream, "<b>HTTP 404 - Not Page Found</b>");
}
else // if the requested URL exists
{
if ((strcmp(url, ".")) == 0) // if the requested URL is the current directory
{
argc = 3;
argv[0] = "ls";
argv[1] = "-l";
argv[2] = url; // set arguments to list the files in the directory
}
else // if the requested URL is a file or directory
{
if (S_ISDIR(checkstat.st_mode)) // if the requested URL is a directory
{
argc = 3;
argv[0] = "ls";
argv[1] = "-al";
argv[2] = url; // set arguments to list the files in the directory
}
else // if the requested URL is a file
{
char *mimestream_buffer = NULL;
size_t mimestream_buffer_size = 0;
const char *mimetype = get_mimetype(url); // get the MIME type of the requested file
FILE *mimestream = open_memstream(&mimestream_buffer, &mimestream_buffer_size);
// find whether if filename is a symbolic link file
int symlink = 0;
struct stat file_stat;
if (lstat(url, &file_stat) == 0)
{
symlink = S_ISLNK(file_stat.st_mode);
}
if (symlink) // If the file is a symbolic link
{
char target[PATH_MAX];
ssize_t len = readlink(url, target, sizeof(target) - 1);
if (len != -1)
{
target[len] = '\0';
mimetype = get_mimetype(target);
url = target;
}
}
if (mimetype)
{
fprintf(mimestream, "HTTP/1.1 200 OK\n");
fprintf(mimestream, "Content-Type: %s\n\n", mimetype); // set the MIME type header
FILE *file = fopen(url, "rb");
if (file)
{
char buffer[1024];
size_t bytes;
while ((bytes = fread(buffer, 1, sizeof(buffer), file)) > 0)
{
fwrite(buffer, 1, bytes, mimestream); // write the file contents to the stream
}
fclose(file);
}
else // if the file cannot be opened
{
fprintf(mimestream, "HTTP/1.1 404 Not Found\n");
fprintf(mimestream, "Content-Type: text/html\n\n");
fprintf(mimestream, "<html><body><h1>404 Not Found</h1></body></html>\n"); // print an error message
}
}
else // if the MIME type is not supported
{
fprintf(mimestream, "HTTP/1.1 Unsupported Media Type\n");
fprintf(mimestream, "Content-Type: text/html\n\n");
fprintf(mimestream, "<html><body><h1>Unsupported Media Type</h1></body></html>\n");
}
fclose(mimestream); // Close mimestream
cur_time = time(NULL);
c_time = ctime(&(cur_time));
c_time[strlen(c_time) - 1] = '\0';
// 연결 종료 시간 기록
gettimeofday(&end, NULL);
long long elapsed_time = (end.tv_sec - start.tv_sec) * 1000000LL + (end.tv_usec - start.tv_usec);
printf("\n====== Disconnected Client =======\n");
printf("TIME : [%s]\n", c_time);
printf("URL : %s\n",url);
printf("IP: %s\n", new_client.ip);
printf("Port: %d\n", new_client.port);
printf("CONNECTING TIME: %lld \n", elapsed_time);
printf("==================================\n");
char buffer_thread[1024];
int offset = 0;
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "\n====== Disconnected Client =======\n");
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "TIME : [%s]\n", c_time);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "URL : %s\n",url);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "IP: %s\n", new_client.ip);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "Port: %d\n", new_client.port);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "CONNECTING TIME: %lld \n", elapsed_time);
offset += snprintf(buffer_thread + offset, sizeof(buffer_thread) - offset, "==================================\n");
pthread_t add_parent_fork;
pthread_create(&add_parent_fork, NULL, add_write, buffer_thread);
pthread_join(add_parent_fork, NULL);
// Write mimestream_buffer to client_fd; print error if necessary
if (write(client_fd, mimestream_buffer, (mimestream_buffer_size)) == -1)
{
perror("write error");
};
close(client_fd); // Close client file descriptor
sleep(5);
addIdleProcess(childpid);
removeNonIdleCount();
continue; // Go to next iteration
}
}
// Send HTTP response header
fprintf(stream,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n");
// Start HTML structure
fprintf(stream, "<html>\n<head>\n");
fprintf(stream, "<link rel=\"icon\" href=\"data:,\">\n");
fprintf(stream, "<title>%s</title>\n", curdir);
fprintf(stream, "</head>\n<body>\n");
fprintf(stream, "<h1>");
if ((strcmp(url, ".")) == 0) // if the requested URL is the current directory
{
fprintf(stream, "Welcome to System Programming Http");
}
else
{
fprintf(stream, "System Programming Http");
}
fprintf(stream, "</h1>");
// Declaring variables
int a_flag = 0;
int l_flag = 0;
int h_flag = 0, S_flag = 0, r_flag = 0;
struct stat file_stat;
glob_t pglob;
// Declaring pointers for storing arguments and options
char **optarr;
char **folderarray;
char **filearray;
// Initializing variables
int optcnt = 0;
int maxoptlen = 0;
int filecnt = 0;
int foldercnt = 0;
// Allocating memory for optarr
optarr = (char **)malloc(sizeof(char *) * argc);
optind = 1;
// Parsing command line options using getopt()
while ((opt = getopt(argc, argv, "alhSr")) != -1)
{
switch (opt)
{
case 'a': // If -a option is provided
a_flag = 1;
break;
case 'l': // If -l option is provided
l_flag = 1;
break;
case 'h': // If -h option is provided
h_flag = 1;
break;
case 'S': // If -S option is provided
S_flag = 1;
break;
case 'r': // If -r option is provided
r_flag = 1;
break;
default: // If invalid option is detected
printf("Invalid option detected\n");
}
}
// Storing non-option arguments in optarr
for (int i = optind; i < argc; i++)
{
char *arg = argv[i];
if (arg != NULL && (lstat(arg, &file_stat) != -1))
{
// Finding max option length
if (maxoptlen < strlen(arg) + 1)
{
maxoptlen = strlen(arg) + 1;
}
// Allocating memory for optarr
optarr[optcnt] = (char *)malloc(sizeof(char) * (maxoptlen));
// Copying the argument to optarr
strcpy(optarr[optcnt], arg);
optcnt++;
}
// If argument is not an option and is not a valid file path
else if (arg[0] != '-' && (access(arg, F_OK) != 0))
{
// If argument contains wildcard characters
if (strchr(arg, '*') != NULL || strchr(arg, '?') != NULL || strchr(arg, '[') != NULL || strchr(arg, ']') != NULL)
{
// Set flags for globbing
int flags;
flags = GLOB_MARK | GLOB_TILDE;
// Perform globbing to get list of matching files
int status = glob(arg, flags, NULL, &pglob);
if (status != 0 && status != 3)
{
// Print error message if globbing fails