-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
96 lines (76 loc) · 2.39 KB
/
Copy pathclient.cpp
File metadata and controls
96 lines (76 loc) · 2.39 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
#include "client_lib.hpp"
int main() {
int rc;
// Deactivate buffered output.
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
// Create server address.
struct sockaddr_in addr;
memset((void *)&addr, 0, sizeof(addr));
// Fill in fields.
addr.sin_addr.s_addr = htonl(IP);
addr.sin_port = htons(PORT);
addr.sin_family = AF_INET;
// Hashtable for cookies.
unordered_map<string, string> cookies;
// Place to hold jwt.
char *jwt = NULL;
// Reading and receiving loop.
while (1) {
// Create a socket.
int fd = socket(AF_INET, SOCK_STREAM, 0);
DIE(fd < 0, "socket error");
// Connect to server.
rc = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
DIE(rc < 0, "connect error");
// Get input command.
char *command = get_input();
if (command == NULL) {
fprintf(stderr, "Broken input.\n");
continue;
}
// Convert to type.
int type = get_type(command);
if (type == -1) {
fprintf(stderr, "Command \"%s\" doesn't exist. Please try again.\n", command);
continue;
}
// Handle exit
if (type == CMD_EXIT) return 0;
// Handle separately because of how stupidly it is implemented
if (type == CMD_ADD_COLLECTION) {
handle_add_collection(fd, cookies, jwt);
continue;
}
// Build request.
char *req = get_req(type, cookies, jwt);
if (req == NULL) {
fprintf(stderr, "Error building request.\n");
continue;
}
// Send it to server.
send_to_server(fd, req);
// If we receive any logout command we need to clear the cookies and jwt.
if (type == CMD_LOGOUT || type == CMD_LOGOUT_ADMIN) {
if (jwt)
free(jwt);
jwt = NULL;
cookies.clear();
}
// Receive response.
ssize_t len;
char *resp = recv_resp(fd, len);
if (resp == NULL) {
fprintf(stderr, "Error receiving response.\n");
continue;
}
// Interpret response.
read_resp(resp, len, cookies, type, jwt);
// Free allocated buffs.
free(command);
free(req);
free(resp);
// Close socket.
close(fd);
}
return 0;
}