-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsvr_func.c
718 lines (648 loc) · 20.7 KB
/
svr_func.c
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
/*------------------------------------------------------
*
* svr_func.c
*
* this file contains many functions that used in lyrebird server
*
* Project : LyreBird
* Name : Chong Guo
* Student ID : 301295753
* SFU username : armourg
* Lecture section : D1
* Instructor : Brain G.Booth
* TA : Scott Kristjanson
*
* Created by Armour on 25/09/2015
* Copyright (c) 2015 Armour. All rights reserved.
*
*------------------------------------------------------
*/
#include "svr_func.h"
#include "time.h"
#include "memwatch.h"
/*
* Function: Get_time
* -------------------
* This function is used to get current time in specify format
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void get_time(void) {
time_t raw_time; /* Used to generate output time */
struct tm *tmp_time; /* Used to generate output time */
time(&raw_time);
tmp_time = localtime(&raw_time);
strftime(out_time, TIME_MAXLENGTH, "%a %b %d %H:%M:%S %Y", tmp_time); /* Format time */
if (out_time[8] == '0')
out_time[8] = ' ';
}
/*
* Function: Send_socket_msg
* -------------------
* This function is used to send a message through socket with its length send first
*
* Parameters:
* socket: the socket file descriptor
* msg: the message that need to send
*
* Returns:
* void
*/
void send_socket_msg(int socket, char *msg) {
msg_len = htonl(strlen(msg));
send(socket, &msg_len, sizeof(uint32_t), 0); /* Send message length first */
send(socket, msg, ntohl(msg_len), 0); /* Send message content */
}
/*
* Function: Recv_socket_msg
* -------------------
* This function is used to receive a message through socket with its length at first
*
* Parameters:
* socket: the socket file descriptor
* msg: the message that need to receive
*
* Returns:
* void
*/
void recv_socket_msg(int socket, char *msg) {
recv(socket, &msg_len, sizeof(uint32_t), 0); /* Recv message length first */
recv(socket, msg, ntohl(msg_len), 0); /* Recv message content first */
msg[ntohl(msg_len)] = '\0';
}
/*
* Function: Init
* -------------------
* This function is used to init some variables,
* like malloc timestamp string, encrypt text string, etc.
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void init(void) {
out_time = (char *)malloc(sizeof(char) * TIME_MAXLENGTH);
enc_txt = (char *)malloc(sizeof(char) * FILE_MAXLENGTH);
dec_txt = (char *)malloc(sizeof(char) * FILE_MAXLENGTH);
init_cli_sock(); /* Init client socket array */
}
/*
* Function: Check_par
* -------------------
* This function is used to check the parameters in command
*
* Parameters:
* argc: the count of arguments
* argv: the command arguments
*
* Returns:
* void
*/
void check_par(int argc, char *argv[]) {
if (argc != 3) { /* Check if the arguments number is right or not */
get_time();
printf("[%s] (Process ID #%d) Arguments number is not right! Usage: %s <config_file> <log_file>\n", out_time, getpid(), argv[0]);
clean_up(CLEAN_TO_TIME);
exit(EXIT_FAILURE);
}
}
/*
* Function: Open_config
* -------------------
* This function is used to open config file and check if it failed
*
* Parameters:
* argv: the command arguments
*
* Returns:
* void
*/
void open_config(char *argv[]) {
fcfg = fopen(argv[1], "r+"); /* Input config file */
if (fcfg == NULL) { /* Check if the config file is exist or not */
get_time();
printf("[%s] (Process ID #%d) ERROR: Config file %s not exist!\n", out_time, getpid(), argv[1]);
clean_up(CLEAN_TO_TIME);
exit(EXIT_FAILURE);
}
}
/*
* Function: Open_log
* -------------------
* This function is used to open log file and check if it failed
*
* Parameters:
* argv: the command arguments
*
* Returns:
* void
*/
void open_log(char *argv[]) {
flog = fopen(argv[2], "w"); /* Output log file */
if (flog == NULL) { /* Check if the log file can be open or not */
get_time();
printf("[%s] (Process ID #%d) ERROR: Log file %s can not open!\n", out_time, getpid(), argv[2]);
clean_up(CLEAN_TO_CONFIG);
exit(EXIT_FAILURE);
}
}
/*
* Function: Get_host_by_sockfd
* -------------------
* This function is used to get host ip address through socket file descriptor
*
* Parameters:
* sockfd: a file descriptor
*
* Returns:
* a pointer to a host ip address
*/
char *get_host_by_sockfd(int sockfd) {
int i;
for (i = 0; i < CLIENT_MAXNUM; ++i) { /* Iterate each sockfd_cli to see if it matches sockfd */
if (sockfd_cli[i] == sockfd)
return ipaddr_cli[i];
}
return NULL;
}
/*
* Function: Get_ipaddr
* -------------------
* This function is used to get the ip address of server machine
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void get_ipaddr(void) {
int i;
if (getifaddrs(&ifaddr) == -1) { /* Get the ip address of this machine and check if it failed */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server can not get the interface address of this machine!\n", out_time, getpid());
clean_up(CLEAN_TO_LOG);
exit(EXIT_FAILURE);
}
addr_len = sizeof(struct sockaddr_in);
for (ifa = ifaddr, i = 0; ifa != NULL; ifa = ifa->ifa_next, i++) { /* Iterate each interface addresses and get the IP address */
if (ifa->ifa_addr == NULL)
continue;
if (ifa->ifa_addr->sa_family != AF_INET) /* If it is not the IPv4 interface */
continue;
if (getnameinfo(ifa->ifa_addr, addr_len, host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) != 0) { /* If can not get the address information of interface address */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server can not get the address information of interface address!\n", out_time, getpid());
clean_up(CLEAN_TO_IFADDR);
exit(EXIT_FAILURE);
}
if (strcmp(host, "0.0.0.0") == 0 || strcmp(host, "127.0.0.1") == 0) /* Filter the special ip address "0.0.0.0" and "127.0.0.1" */
continue;
break; /* If found a avaliable ip address, then we break */
}
if (strcmp(host, "0.0.0.0") == 0) /* 0.0.0.0 is not what we want */
strcpy(host, "ERROR!");
if (strcmp(host, "127.0.0.1") == 0) /* 127.0.0.1 is not what we want */
strcpy(host, "ERROR!");
}
/*
* Function: Create_socket
* -------------------
* This function is used to create a socket in server side
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void create_socket(void) {
int opt = TRUE; /* Used when set socket options */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { /* Create socket in server */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server can not create a new socket!\n", out_time, getpid());
clean_up(CLEAN_TO_IFADDR);
exit(EXIT_FAILURE);
}
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0) { /* Set socket option to reuseable address (not necessary but good) */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server can not set socket option!\n", out_time, getpid());
clean_up(CLEAN_TO_SOCKET);
exit(EXIT_FAILURE);
}
}
/*
* Function: Bind_socket
* -------------------
* This function is used to bind a socket in serve side
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void bind_socket(void) {
memset(&serv_addr, 0, addr_len); /* Initialize server address config */
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(0);
if (inet_pton(AF_INET, host, &(serv_addr.sin_addr)) <= 0) { /* Check IP address */
get_time();
printf("[%s] (Process ID #%d) ERROR: Host in inet_pton function is not a valid IP address!\n", out_time, getpid());
clean_up(CLEAN_TO_SOCKET);
exit(EXIT_FAILURE);
}
if (bind(sockfd, (struct sockaddr *)&serv_addr, addr_len) < 0) { /* Bind the server socket */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server bind socket failed!\n", out_time, getpid());
clean_up(CLEAN_TO_SOCKET);
exit(EXIT_FAILURE);
}
}
/*
* Function: Listen_socket
* -------------------
* This function is used to listen a socket in server side
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void listen_socket(void) {
if (listen(sockfd, CLIENT_MAXNUM) < 0) { /* Listen at the server socket */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server listen at socket failed!\n", out_time, getpid());
clean_up(CLEAN_TO_SOCKET);
exit(EXIT_FAILURE);
}
}
/*
* Function: Print_server_info
* -------------------
* This function is used to find out and print the info of server side
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void print_server_info(void) {
if (getsockname(sockfd, (struct sockaddr *)&serv_addr, &addr_len) < 0) { /* Find out the port number that used for lyrebird in server machine */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server get socket name failed!\n", out_time, getpid());
clean_up(CLEAN_TO_SOCKET);
exit(EXIT_FAILURE);
}
get_time(); /* Print out the server information */
printf("[%s] lyrebird.server: PID %d on host %s, port %d\n", out_time, getpid(), host, ntohs(serv_addr.sin_port));
}
/*
* Function: Init_cli_sock
* -------------------
* This function is used to init socket array for client side
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void init_cli_sock(void) {
int i;
for (i = 0; i < CLIENT_MAXNUM; ++i) { /* Init client socket array */
sockfd_cli[i] = 0;
}
}
/*
* Function: Init_select
* -------------------
* This function is used to init FD before each time's select
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void init_select(void) {
int i;
FD_ZERO(&rfds);
FD_SET(sockfd, &rfds); /* The server socket should also be include */
max_fds = sockfd;
for (i = 0; i < CLIENT_MAXNUM; i++) {
if (sockfd_cli[i] > 0) /* If this client socket exist */
FD_SET(sockfd_cli[i], &rfds);
if (sockfd_cli[i] > max_fds)
max_fds = sockfd_cli[i];
}
}
/*
* Function: Select_func
* -------------------
* This function is a wrapper for select function
*
* Parameters:
* no parameters
*
* Returns:
* 0 for success, -1 for failed
*/
int select_func(void) {
if (select(max_fds + 1, &rfds, NULL, NULL, NULL) == -1) { /* Check if select function failed */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server failed when run select function!\n", out_time, getpid());
main_flag = EXIT_FAILURE;
return -1;
}
return 0;
}
/*
* Function: Accept_new_cli
* -------------------
* This function is used to accept new client
*
* Parameters:
* no parameters
*
* Returns:
* 0 for success, -1 for failed
*/
int accept_new_cli(void) {
if ((sockfd_new = accept(sockfd, (struct sockaddr *)&cli_addr, &addr_len)) < 0) { /* Accept new connections from client machine */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server accept client socket failed!\n", out_time, getpid());
main_flag = EXIT_FAILURE;
return -1;
}
return 0;
}
/*
* Function: Check_connect
* -------------------
* This function is used to check if a client connect successfully with a message
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
int check_connect(void) {
recv_socket_msg(sockfd_new, recv_mark);
if (strcmp(recv_mark, CONNECT_MSG) != 0) { /* If is not the connect message */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server get client connect message failed!\n", out_time, getpid());
main_flag = EXIT_FAILURE;
return -1;
}
return 0;
}
/*
* Function: Print_client_info
* -------------------
* This function is used to find out and print the info of client side
*
* Parameters:
* no parameters
*
* Returns:
* 0 for success, -1 for failed
*/
int print_client_info(void) {
if (inet_ntop(AF_INET, &cli_addr.sin_addr, ip_buffer, sizeof(ip_buffer)) == NULL) { /* Check if get client ip address failed */
get_time();
printf("[%s] (Process ID #%d) ERROR: Server get client ip address by inet_ntop failed!\n", out_time, getpid());
main_flag = EXIT_FAILURE;
return -1;
}
get_time();
fprintf(flog, "[%s] Successfully connected to lyrebird client %s.\n", out_time, ip_buffer);
return 0;
}
/*
* Function: Store_client_ip
* -------------------
* This function is used to store the client ip address into sockfd_cli array
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void store_client_ip(void) {
int i;
for (i = 0; i < CLIENT_MAXNUM; ++i) {
if (sockfd_cli[i] == 0) { /* If find a empty place for storing client socket */
sockfd_cli[i] = sockfd_new;
memset(ipaddr_cli[i], 0, sizeof(ipaddr_cli[i]));
strcpy(ipaddr_cli[i], ip_buffer);
break;
}
}
}
/*
* Function: Handle_success
* -------------------
* This function is uead to handle success message
*
* Parameters:
* sock_num: the socket number that we need to handle with
*
* Returns:
* void
*/
void handle_success(int sock_num) {
char recv_pid[PID_MAXLENGTH]; /* This is the pid number that read from one socket to client side */
char recv_buffer[FILE_MAXLENGTH]; /* This is the buffer that we used to read message from socket */
recv_socket_msg(sock_num, recv_buffer);
recv_socket_msg(sock_num, recv_pid);
get_time();
fprintf(flog, "[%s] The lyrebird client %s has successfully decrypted %s in process %s.\n", out_time, client_ip, recv_buffer, recv_pid);
}
/*
* Function: Handle_dispatch
* -------------------
* This function is uead to handle dispatch message
*
* Parameters:
* sock_num: the socket number that we need to handle with
*
* Returns:
* void
*/
void handle_dispatch(int sock_num) {
strcpy(send_mark, CLIENT_WORK_MSG); /* Assign new task to client */
send_socket_msg(sock_num, send_mark);
send_socket_msg(sock_num, enc_txt);
send_socket_msg(sock_num, dec_txt);
get_time();
fprintf(flog, "[%s] The lyrebird client %s has been given the task of decrypting %s.\n", out_time, client_ip, enc_txt);
}
/*
* Function: Handle_failure
* -------------------
* This function is uead to handle failure message
*
* Parameters:
* sock_num: the socket number that we need to handle with
*
* Returns:
* void
*/
void handle_failure(int sock_num) {
char recv_buffer[ERROR_MAXLENGTH]; /* This is the buffer that we used to read message from socket */
recv_socket_msg(sock_num, recv_buffer);
get_time();
fprintf(flog, "[%s] The lyrebird client %s has encountered an error: %s", out_time, client_ip, recv_buffer);
}
/*
* Function: Handle_client_msg
* -------------------
* This function is used to handle different kinds of client message
*
* Parameters:
* sock_num: the socket number that we need to handle with
*
* Returns:
* void
*/
void handle_client_msg(int sock_num) {
int i;
int need_dispatch = 0; /* If set to 1, then means this time server need to dispatch new task to client */
int client_close = 0; /* If set to 1, then means recv the disconnect message from client with socket sock_num */
if (strcmp(recv_mark, SUCCESS_MSG) == 0) { /* If it is a success message */
handle_success(sock_num);
need_dispatch = 1;
} else if (strcmp(recv_mark, FAILURE_MSG) == 0) { /* If it is a failure message */
handle_failure(sock_num);
need_dispatch = 1;
} else if (strcmp(recv_mark, DISCONNECT_SUCC_MSG) == 0) { /* If it is a disconnect with success state message */
get_time();
fprintf(flog, "[%s] lyrebird client %s has disconnected expectedly.\n", out_time, client_ip);
client_close = 1;
} else if (strcmp(recv_mark, DISCONNECT_FAIL_MSG) == 0) { /* If it is a disconnect with failed state message */
get_time();
fprintf(flog, "[%s] lyrebird client %s has disconnected unexpectedly.\n", out_time, client_ip);
client_close = 1;
}
if (strcmp(recv_mark, DISPATCH_MSG) == 0 || (!finish_flag && need_dispatch == 1)) { /* If it is a dispatch message or need dispatch */
if (finish_flag) return;
handle_dispatch(sock_num);
read_flag = 1;
return;
}
if (client_close) {
for (i = 0; i < CLIENT_MAXNUM; ++i) { /* Close socket of this client */
if (sockfd_cli[i] == sock_num) {
close(sock_num);
sockfd_cli[i] = 0;
memset(ipaddr_cli[i], 0, sizeof(ipaddr_cli[i]));
break;
}
}
remained_cli--;
return;
}
if (finish_flag) return;
get_time();
printf("[%s] (Process ID #%d) ERROR: Server failed when checking message type from client machine!\n", out_time, getpid());
main_flag = EXIT_FAILURE;
}
/*
* Function: Ask_clients_quit
* -------------------
* This function is used to ask all clients quit
*
* Parameters:
* no parameters
*
* Returns:
* the number of the remained clients
*/
int ask_clients_quit(void) {
int i;
int remained_cli = 0;
for (i = 0; i < CLIENT_MAXNUM; ++i) {
if (sockfd_cli[i] > 0) { /* If this client still connected */
strcpy(send_mark, CLIENT_EXIT_MSG);
send_socket_msg(sockfd_cli[i], send_mark);
remained_cli++;
}
}
return remained_cli;
}
/*
* Function: Wait_clients_quit
* -------------------
* This function is used to wait all clients quit
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void wait_clients_quit(void) {
int i;
while (remained_cli) {
init_select();
if (select_func() == -1) break; /* Select */
for (i = 0; i < max_fds + 1; i++) {
if (FD_ISSET(i, &rfds)) {
client_ip = get_host_by_sockfd(i); /* Get the client's ip address */
recv_socket_msg(i, recv_mark); /* Get the response message from client side */
if (strcmp(recv_mark, CONNECT_MSG) != 0) /* Ignore new connect client */
handle_client_msg(i);
break;
}
}
}
}
/*
* Function: Quit_server
* -------------------
* This function is used to clean up everything and quit the server
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void quit_server(void) {
get_time(); /* Print out the server information */
printf("[%s] lyrebird.server: PID %d completed its tasks and is exiting successfully.\n", out_time, getpid());
clean_up(CLEAN_ALL); /* Always remember to free all and close file pointer! */
}
/*
* Function: Clean_up
* -------------------
* This function is used to free memory and close file pointer before program exit
*
* Parameters:
* no parameters
*
* Returns:
* void
*/
void clean_up(int step) {
if (step >= CLEAN_TO_TIME) {
free(enc_txt);
free(dec_txt);
free(out_time);
}
if (step >= CLEAN_TO_CONFIG) fclose(fcfg);
if (step >= CLEAN_TO_LOG) fclose(flog);
if (step >= CLEAN_TO_IFADDR) freeifaddrs(ifaddr);
if (step >= CLEAN_TO_SOCKET) close(sockfd);
}