-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.c
More file actions
145 lines (119 loc) · 3.54 KB
/
client.c
File metadata and controls
145 lines (119 loc) · 3.54 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
#include <stdio.h>
#include "functions.h"
int parse_from_string(char *command)
{
if (!strcmp(command, "register"))
return 0;
if (!strcmp(command, "login"))
return 1;
if (!strcmp(command, "get_book"))
return 2;
if (!strcmp(command, "get_books"))
return 3;
if (!strcmp(command, "enter_library"))
return 4;
if (!strcmp(command, "add_book"))
return 5;
if (!strcmp(command, "delete_book"))
return 6;
if (!strcmp(command, "logout"))
return 7;
if (!strcmp(command, "exit"))
return 8;
return 9;
}
int main(void)
{
char command[NMAX];
char *cookie = NULL, *token = NULL;
while (fgets(command, NMAX, stdin)) {
size_t len = strlen(command);
if (len > 0 && command[len - 1] == '\n') {
command[len - 1] = '\0';
}
// open a new connection - HTTP is stateless
int sockfd = open_connection((char *)IP, PORT, AF_INET, SOCK_STREAM, 0);
// each command type
int command_type = parse_from_string(command);
switch (command_type) {
case 0:
if (cookie) {
printf("User is already logged in!\n");
} else {
register_user(sockfd);
}
break;
case 1:
if (!cookie) {
cookie = login(sockfd, cookie);
} else {
free(cookie);
cookie = login(sockfd, cookie);
}
break;
case 2:
if (!cookie) {
printf("User not logged in!\n");
} else {
get_book(sockfd, token);
}
break;
case 3:
if (!cookie) {
printf("User not logged in!\n");
} else {
get_books(sockfd, token);
}
break;
case 4:
if (!cookie) {
printf("User not logged in!\n");
} else {
char *tmp = enter_library(sockfd, cookie);
if (tmp) {
free(token);
token = tmp;
}
}
break;
case 5:
if (!cookie) {
printf("User not logged in!\n");
} else {
add_book(sockfd, token);
}
break;
case 6:
if (!cookie) {
printf("User not logged in!\n");
} else if (!token) {
printf("Invalid token!\n");
} else {
delete_book(sockfd, token);
}
break;
case 7:
if (!cookie) {
printf("User already logged out!\n");
} else {
logout(sockfd, cookie);
free(cookie);
free(token);
token = NULL;
cookie = NULL;
}
break;
case 8:
exit_client(sockfd);
break;
case 9:
break;
default:
printf("Unknown command!\n");
break;
}
// Close the connection on the TCP socket.
close_connection(sockfd);
}
return 0;
}