-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
373 lines (302 loc) · 9.33 KB
/
Copy pathserver.cpp
File metadata and controls
373 lines (302 loc) · 9.33 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
//standard import
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <vector>
using namespace std;
//import for to grab socket / ip includes necessaryq
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
//data structure import && creation
#include <unordered_map>
#define INITSIZE 4
//create a globally accessed map (not thread based)for all clients to access
std::unordered_map<std::string, std::string> store;
std::mutex tableMutex;
std::unordered_map<int, std::string> clientBuffer;
typedef struct HashEntry {
string key;
string val;
struct HashEntry *next;
} HashEntry;
typedef struct HashTable {
HashEntry **bucket;
int size;
int entryCount;
} HashTable;
HashTable *table;
/*
This program is fully developed and created by: Marcus Ruth
https://www.github.com/polter-dev/miniredis_cpp
Program Synopsis: client that connects and communicates to the server to simulate a redis like system
*/
int grabSocket(){
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1){
cout << "Could not grab server socket" << endl;
exit(errno);
}
return fd;
}
struct pollfd initPoll(int fd){
struct pollfd s;
s.fd = fd;
s.events = POLLIN;
s.revents = 0;
return s;
}
void initServerSocket(struct sockaddr_in *s1){
s1->sin_family = AF_INET;
s1->sin_port = htons(1234);
s1->sin_addr.s_addr = htonl(INADDR_ANY);
}
void bindSock(int fd, struct sockaddr_in *serverSocket){
int res = ::bind(fd, (struct sockaddr *)serverSocket, sizeof(*serverSocket));
if (res == -1){
cout << "Could not bind to socket!\n" << endl;
exit(-1);
}
}
void listenSocket(int fd){
int val = listen(fd, 1);
if (val == -1){
cout << "Something went wrong with listening\n" << endl;
exit(errno);
}
}
HashTable* initHashTable(){
HashTable *table = (HashTable*)malloc(sizeof(HashTable));
table->size = INITSIZE;
table->bucket = (HashEntry**)malloc(sizeof(HashEntry*) * INITSIZE);
for (int i = 0; i < INITSIZE; i++)
table->bucket[i] = NULL;
return table;
}
unsigned long hashFunction(const string &key) {
int size = key.length();
unsigned long hash = 5381; // djb2 starting val
for (int i = 0; i < size; i++)
hash = (hash * 33) + key[i];
return hash;
}
HashEntry *createHashNode(string key, string val){
HashEntry *node = (HashEntry*)malloc(sizeof(HashEntry));
node->next = NULL;
node ->key = key;
node->val = val;
return node;
}
HashEntry* checkDupes(HashTable* table, string key, unsigned long idx){
HashEntry *walker = table->bucket[idx];
while (walker){
if(walker->key == key)
return walker;
walker = walker->next;
}
return NULL;
}
HashEntry *lookupHash(HashTable *table, string key){
unsigned long idx = hashFunction(key) % table->size;
HashEntry *walker = table->bucket[idx];
while (walker){
if (walker->key == key)
return walker;
walker = walker->next;
}
return NULL;
}
void insertHash(HashTable *table, string key, string value){
unsigned long idx = hashFunction(key) % table->size;
HashEntry* duplicate = checkDupes(table, key, idx);
if (!duplicate){
HashEntry *newNode = createHashNode(key, value);
newNode->next = table->bucket[idx];
table->bucket[idx] = newNode;
table->entryCount++;
} else {
duplicate->val = value;
}
}
int acceptSocket(int fd, struct sockaddr_in *clientAddr){
socklen_t num =sizeof(*clientAddr);
int res = accept(fd, (struct sockaddr *)clientAddr, &num);
if (res == -1){
cout << "Connection could not be accepting through server\n" << endl;
exit(errno);
}
return res;
}
int sendMessage(int fd, const char *buffer, int size){
int sent = send(fd, buffer, size, 0);
if (sent == -1){
cout << "Could not send!\n" << endl;
return 0;
}
return 1;
}
int checkSize(int size){
if (size == -1){
cout << "Could not get total size\n" << endl;
return 0;
} else if (size == 0){
cout << "Client has disconnected!\n" << endl;
return 0;
}
return 1;
}
void storeSET(string wordOne, string wordTwo){
insertHash(table, wordOne, wordTwo);
}
int simpleStringResponse(int fd, const char *word){
int len = strlen(word);
int totalSize = len + 4;// \r\n and +1 for the null term
char buffer[totalSize];
int i;
for (i = 0; i < len; i++)
buffer[i + 1] = word[i];
buffer[0] = '+';
buffer[totalSize - 3] = '\r';
buffer[totalSize - 2] = '\n';
buffer[totalSize - 1] = '\0';
return sendMessage(fd, buffer, totalSize-1);
}
int sendBulkString(int fd, const char *word){
int len = strlen(word);
string response = "$" + std::to_string(len) + "\r\n" + word + "\r\n";
return sendMessage(fd, response.c_str(), response.length());
}
int sendNull(int fd){
string response = "_\r\n";
return sendMessage(fd, response.c_str(), response.length());
}
int sendSimpleError(int fd, const char *error){
//-Error message\r\n -> different message for each
string response = string("-") + error + "\r\n";
return sendMessage(fd, response.c_str(), response.length());
}
int grabGET(string key, int fd){
HashEntry *entry = lookupHash(table, key);
if (!entry)
return sendNull(fd);
else
return sendBulkString(fd, entry->val.c_str());
}
int findCompleteMessage(string &buffer){
if(buffer.find("\r\n") == std::string::npos){
return -1;
}
int index = buffer.find('\r');
string stringSize = buffer.substr(1, index-1);
int size = stoi(stringSize);
index = index + 2;
for (int i = 0; i < size; i++){
if(buffer.find("\r\n", index) == std::string::npos){
return -1;
}
int cmpIdx = buffer.find('\r', index);
string tempSize = buffer.substr(index+1, cmpIdx - index - 1);
int wordSize = stoi(tempSize);
if (buffer.size() < cmpIdx + 2 + wordSize + 2){
return -1;
}
index = cmpIdx + 2 + wordSize + 2;
}
return index;
}
std::vector <string> decodeClient(char* encoded){
std::vector<string> incoming;
int posi = 0;
char *finder = strchr(encoded + posi, '\r');
string temp(encoded + 1, finder);
int size = stoi(temp);
posi = (finder-encoded) + 2;
for (int i = 0; i < size; i++){
finder = strchr(encoded + posi, '\r');
string temp(encoded + posi + 1, finder);
int wordLen = stoi(temp);
posi = (finder - encoded) + 2;
string word(encoded + posi, wordLen);
posi = posi + wordLen + 2;
incoming.push_back(word);
}
return incoming;
}
int runCommands(int fd){
int x = 1;
int val;
int size = 1024;
char buffer[size];
int totalSize = recv(fd, buffer, size, 0);
x = checkSize(totalSize);
if (!x) return 0;
buffer[totalSize] = '\0';
clientBuffer[fd] += buffer;
bool processedAny = false;
while(1) {
val = findCompleteMessage(clientBuffer[fd]);
if (val == -1)
break;
cout << clientBuffer[fd] << endl;
std::vector<string> words = decodeClient((char*)clientBuffer[fd].c_str());
if (words.empty()) return sendSimpleError(fd, "ERR empty command");
if (words[0] == "PING"){
x = simpleStringResponse(fd, "PONG");
} else if (words[0] == "ECHO"){
x = sendBulkString(fd, words[1].c_str());
} else if (words[0] == "QUIT"){
x = 0;
} else if (words[0] == "SET"){
storeSET(words[1], words[2]);
x = simpleStringResponse(fd, "OK");
} else if (words[0] == "GET"){
x = grabGET(words[1], fd);
} else {
x = sendSimpleError(fd, "ERR unknown command");
}
clientBuffer[fd].erase(0, val);
processedAny = true;
}
if (!processedAny)
return -2;
return x;
}
//this function looks horrible i know
void runPolling(std::vector<pollfd> &fdArr, int fd, sockaddr_in &serverSocket){
while(1){
poll(fdArr.data(), fdArr.size(), -1);
for (int i = 0; i < fdArr.size(); i++) {
if(fdArr[i].revents){
if (!i){
int newFD = acceptSocket(fd, &serverSocket);
fdArr.push_back(initPoll(newFD));
} else {
int val = runCommands(fdArr[i].fd);
if (val == -2){
continue;
} else if (!val || val == -1){
clientBuffer.erase(fdArr[i].fd);
close(fdArr[i].fd);
fdArr.erase(fdArr.begin() + i);
i--;
}
}
}
}
}
}
int main(){
int fd = grabSocket();
struct sockaddr_in serverSocket; initServerSocket(&serverSocket);
bindSock(fd, &serverSocket);
listenSocket(fd);
table = initHashTable();
//creates a dynamic system of fd
std::vector<pollfd> fdArr;
fdArr.push_back(initPoll(fd));
runPolling(fdArr, fd, serverSocket);
close(fd);
return 0;
}