-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
118 lines (98 loc) · 3.07 KB
/
server.c
File metadata and controls
118 lines (98 loc) · 3.07 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
#include "common.h"
#include "auth.h"
#include "customer.h"
#include "employee.h"
#include "manager.h"
#include "admin.h"
#include "utils.h"
#include "user_controller.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/stat.h>
void* handle_client(void *arg) {
int sock = *(int*)arg;
free(arg);
char buffer[BUFFER_SIZE];
while (1) {
send_message(sock,
"International Institute of Information and Technology"
"\n***************** Banking System *****************\n"
"1. Customer\n"
"2. Employee\n"
"3. Manager\n"
"4. Admin\n"
"5. Exit\n"
"Select role: ");
if (!read_input(sock, buffer, BUFFER_SIZE)) break;
int role = atoi(buffer);
if (role == 5) {
send_message(sock, "Goodbye!\n");
break;
}
if (role < 1 || role > 4) {
send_message(sock, "Invalid role!\n");
continue;
}
send_message(sock, "Username: ");
if (!read_input(sock, buffer, BUFFER_SIZE)) break;
char username[50];
strcpy(username, buffer);
send_message(sock, "Password: ");
if (!read_input(sock, buffer, BUFFER_SIZE)) break;
char password[50];
strcpy(password, buffer);
int user_id;
if (authenticate(role, username, password, &user_id)) {
send_message(sock, "\n✓ Login successful!\n");
// Use switch statement instead of function pointers
switch (role) {
case ROLE_CUSTOMER:
handle_customer(sock, user_id);
break;
case ROLE_EMPLOYEE:
handle_employee(sock, user_id);
break;
case ROLE_MANAGER:
handle_manager(sock, user_id);
break;
case ROLE_ADMIN:
handle_admin(sock, user_id);
break;
}
logout_user(role, user_id);
send_message(sock, "\nLogged out.\n");
} else {
send_message(sock, "\n✗ Authentication failed!\n");
}
}
close(sock);
return NULL;
}
int main() {
mkdir(DATA_DIR, 0755);
init_user_controller();
int server_sock = socket(AF_INET, SOCK_STREAM, 0);
int opt = 1;
setsockopt(server_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
struct sockaddr_in addr = {0};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(PORT);
bind(server_sock, (struct sockaddr*)&addr, sizeof(addr));
listen(server_sock, 10);
printf("Server listening on port %d\n", PORT);
while (1) {
int client_sock = accept(server_sock, NULL, NULL);
int *sock_ptr = malloc(sizeof(int));
*sock_ptr = client_sock;
pthread_t tid;
pthread_create(&tid, NULL, handle_client, sock_ptr);
pthread_detach(tid);
}
return 0;
}