Repository navigation
Expand file tree
/
Copy pathServer.cpp
More file actions
639 lines (531 loc) · 14.2 KB
/
Copy pathServer.cpp
File metadata and controls
639 lines (531 loc) · 14.2 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
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
#include "Server.h"
#include "Returns .h"
#include "HashTable.h"
#include "ServerCommands.h"
constexpr const char* PublicLogPath = "PublicLog.txt";
bool Server::LoggedIn(SOCKET s)
{
//if socket is not found in map return false
return SocketToUser.find(s) != SocketToUser.end();
}
KReturn Server::ServerMessage(SOCKET s, std::string text)
{
if(text != "")
{
std::string out = "[SERVER]" + text;
send_packet(s, out.c_str());
return KReturn::SUCCESS;
}
return KReturn::UNKNOWN;
}
void Server::logPublic(const std::string& line)
{
if (!PublicLog.is_open()) return;
PublicLog << line << "\n";
PublicLog.flush();
}
void Server::StartBroadCast(uint16_t port, uint32_t intervalseconds)
{
AdvertisedServerPort = port;
UdpBroadcastRunning = true;
//Starts a new thread and runs my broad cast loop on it
UdpBroadcastThread = std::thread(&Server::BroadCastLoop, this, intervalseconds);
}
void Server::BroadCastPublic(SOCKET s, std::string& text)
{
const std::string user = SocketToUser.find(s)->second;
if (user.empty())
return;
std::string out = user + ": " + text + "\n";
for (const auto& kv : SocketToUser)
{
send_packet(kv.first, out.c_str());
}
logPublic(user + ": " + text);
}
std::string Server::BuildBroadcastMessage() const
{
return "KOS_COMS|TCP_PORT=" + std::to_string(AdvertisedServerPort);
}
void Server::StopBroadCast()
{
UdpBroadcastRunning = false;
if (UdpBroadcastThread.joinable())
{
UdpBroadcastThread.join();
}
}
KReturn Server::Init(uint16_t port, uint32_t ChatCap)
{
WSADATA WsaData;
int ErrCode = 0;
PublicLog.open(PublicLogPath, std::ios::app);
int resultTCP = WSAStartup(MAKEWORD(2, 2), &WsaData);
if (resultTCP < 0)
{
ErrCode = WSAGetLastError();
printf("Failed to start WSA. Error: %d", ErrCode);
return KReturn::FAILED;
}
//Created socket
SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket < 0)
{
ErrCode = WSAGetLastError();
printf("Failed to create listener socket. Error: %d", ErrCode);
return KReturn::FAILED;
}
//Binding socket to port
sockaddr_in serverAddr;
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.S_un.S_addr = INADDR_ANY;
serverAddr.sin_port = htons(port);
if(bind(ListenSocket, (sockaddr*)&serverAddr, sizeof(serverAddr)))
{
ErrCode = WSAGetLastError();
printf("Failed to bind socket to port. Error: %d", ErrCode);
return KReturn::FAILED;
}
//Awaiting connections
resultTCP = listen(ListenSocket, 0);
if (resultTCP < 0)
{
ErrCode = WSAGetLastError();
printf("Socket Error. Error: %d", ErrCode);
closesocket(ListenSocket);
WSACleanup();
return KReturn::FAILED;
}
printf("Server listening on port: %d \n", port);
StartBroadCast(port, 5);
//Setting up sets
//Clears the bitset
FD_ZERO(&MasterSet);
//adds the listening socket to the master_set. Select will now watch this socket
FD_SET(ListenSocket, &MasterSet);
//Starts tracking the highest socket id
MaxSocketNum = ListenSocket;
while (true)
{
//Copy master
ReadySet = MasterSet;
//Wait for activity
int activity = select(MaxSocketNum + 1, &ReadySet, NULL, NULL, NULL);
//Loop through all the ready sockets
for (int i = 0; i < ReadySet.fd_count; i++)
{
//The ready socket
SOCKET s = ReadySet.fd_array[i];
if (s == ListenSocket)
{
//accept the connection
SOCKET ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket < 0)
{
ErrCode = WSAGetLastError();
printf("accept Failed Error: %d\n", ErrCode);
closesocket(ClientSocket);
WSACleanup();
return KReturn::FAILED;
}
if (MasterSet.fd_count > ChatCap)
{
send_packet(ClientSocket, "Server is at capacity. Try again later.\n");
shutdown(ClientSocket, SD_BOTH);
closesocket(ClientSocket);
continue;
}
//add client socket to the master set
FD_SET(ClientSocket, &MasterSet);
send_packet(ClientSocket,
"Welcome to KOS COMS\n"
"Commands start with ~\n"
"Try ~help to get started!\n");
send_packet(ClientSocket, "Tip: ~register <username> <password> then ~login <username> <password>\n");
}
//Incoming data
else
{
char buffer[512];
int payload_size = recv_packet(s, buffer);
if (payload_size <= 0)
{
//close socket
closesocket(s);
//remove from master set
FD_CLR(s, &MasterSet);
}
else
{
server_commands(s, buffer);
}
}
}
}
PublicLog.close();
StopBroadCast();
WSACleanup();
return KReturn::SUCCESS;
}
void Server::BroadCastLoop(uint32_t intervalSeconds)
{
int ErrCode = 0;
// Create UDP socket
UdpBroadcastSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (UdpBroadcastSocket == INVALID_SOCKET)
{
ErrCode = WSAGetLastError();
printf("Failed to create UDP broadcast socket. Error: %d\n", ErrCode);
return;
}
//Allow broadcast packets
BOOL enableBroadCast = TRUE;
if (setsockopt(
UdpBroadcastSocket,
SOL_SOCKET, // The socket option
SO_BROADCAST, //congifures a socket for sending broadcast data
reinterpret_cast<const char*>(&enableBroadCast),
sizeof(enableBroadCast) == SOCKET_ERROR))
{
ErrCode = WSAGetLastError();
printf("Failed to enable SO_BROADCAST. Error: %d\n", ErrCode);
closesocket(UdpBroadcastSocket);
UdpBroadcastSocket = INVALID_SOCKET;
return;
}
// Build broadcast destination address
memset(&BroadcastAddr, 0, sizeof(BroadcastAddr));
BroadcastAddr.sin_family = AF_INET;
BroadcastAddr.sin_port = htons(AdvertisedServerPort);
// 255.255.255.255
BroadcastAddr.sin_addr.s_addr = INADDR_BROADCAST;
while (UdpBroadcastRunning)
{
std::string message = BuildBroadcastMessage();
int sent = sendto(
UdpBroadcastSocket,
message.c_str(),
static_cast<int>(message.size()),
0,
reinterpret_cast<sockaddr*>(&BroadcastAddr),
sizeof(BroadcastAddr));
if (sent == SOCKET_ERROR)
{
ErrCode = WSAGetLastError();
printf("UDP broadcast send failed. Error: %d\n", ErrCode);
}
std::this_thread::sleep_for(std::chrono::seconds(intervalSeconds));
}
closesocket(UdpBroadcastSocket);
UdpBroadcastSocket = INVALID_SOCKET;
}
int Server::send_all(SOCKET s, const char* msg, int len)
{
int bytesSent = 0;
//While the full msg hasnt been sent
while (bytesSent < len)
{
//Send one byte pre iteration
int result = send(s, msg + bytesSent, len - bytesSent, 0);
//Error
if (result < 0)
{
return result;
}
//Advance to the next byte
bytesSent += result;
}
//return the lenght of the msg
return bytesSent;
}
int Server::send_packet(SOCKET s, const char* msg)
{
//If there is no msg return error
if (!msg) return SOCKET_ERROR;
//Get the len of the message
size_t msg_len = strlen(msg);
//If msg lenght is bigger than 255
if (msg_len > 255)
{
printf("Msg is bigger than 255 bytes");
}
unsigned char len_bytes = (unsigned char)msg_len;
//Send the lenght of the message over
if (send_all(s, (const char*)&len_bytes, 1) == SOCKET_ERROR)
return SOCKET_ERROR;
//If there is a payload send that one byte at a time
if (msg_len > 0)
{
if (send_all(s, msg, (int)msg_len) == SOCKET_ERROR)
return SOCKET_ERROR;
}
return (int)(1 + msg_len);
}
int Server::revc_exact(SOCKET s, char* incomingMsg, int len)
{
int incomingBytes = 0;
//While the full msg hasnt been sent
while (incomingBytes < len)
{
//Send one byte pre iteration
int result = recv(s, incomingMsg + incomingBytes, len - incomingBytes, 0);
//client disconnect
if (result == 0)
{
return 0;
}
//Error
if (result == SOCKET_ERROR)
{
return SOCKET_ERROR;
}
//Advance to the next byte
incomingBytes += result;
}
//return the lenght of the msg
return incomingBytes;
}
int Server::recv_packet(SOCKET s, char incomingMsg[256])
{
unsigned char len_byte = 0;
//Get the message lenght
int result = revc_exact(s, (char*)&len_byte, 1);
if (result == 0) return 0; //disconnected
if (result == SOCKET_ERROR) return SOCKET_ERROR;
int payload_len = (int)len_byte;
//Read in the message
if (payload_len)
{
result = revc_exact(s, incomingMsg, payload_len);
if (result == 0) return 0;
if (result == SOCKET_ERROR) return SOCKET_ERROR;
}
//Adds a null terminate to the end of the string
incomingMsg[payload_len] = '\0';
return payload_len;
}
KReturn Server::server_commands(SOCKET s, const char* buffer)
{
if (!buffer) return KReturn::UNKNOWN;
//Data from the commandInput on the client side
std::string CommandInput(buffer);
if (CommandInput.empty() || CommandInput[0] != '~')
{
if (!LoggedIn(s))
{
send_packet(s, "You must ~login before sending messages");
return KReturn::UNKNOWN;
}
BroadCastPublic(s, CommandInput);
return KReturn::SUCCESS;
}
switch (CommandFromToken(buffer))
{
case ServerCommands::help:
{
send_packet(s,
"Commands:\n"
" ~help\n"
" ~register <username> <password>\n"
" ~login <username> <password>\n"
" ~logout\n"
" ~getlist\n"
" ~getlog\n"
" ~send <username> <message>\n");
return KReturn::SUCCESS;
}
case ServerCommands::signup:
{
//User is logged in
if (LoggedIn(s))
{
send_packet(s, "User is already login");
return KReturn::UNKNOWN;
}
//Read data from the CommandInput
std::istringstream StringStream(CommandInput);
std::string Command, Username, Password;
//Read in the data as it was passed in
StringStream >> Command >> Username >> Password;
//Check if only ~register was recviced
if (Username.empty() || Password.empty())
{
send_packet(s, "Enter: username password");
char CommandBuffer[256]{};
int InputRecv = recv_packet(s, CommandBuffer);
//If nothing recviced cancel command
if (InputRecv <= 1)
{
send_packet(s, "Registration cancelled");
return KReturn::UNKNOWN;
}
//Turn CommandBuffer into a stream and read in the username and password
std::istringstream StringStream2{ std::string(CommandBuffer) };
StringStream2 >> Username >> Password;
if (Username.empty() || Password.empty())
{
//Display usage if command
send_packet(s, "Usage: ~register username password");
return KReturn::UNKNOWN;
}
}
if (HashTableFind(Username.c_str()) != NULL)
{
send_packet(s, "Username already registered");
return KReturn::UNKNOWN;
}
ClientInfo* info = new ClientInfo();
//Set info memory to 0
memset(info, 0, sizeof(ClientInfo));
strcpy_s(info->username, MAX_USERNAME, Username.c_str());
strcpy_s(info->password, MAX_USERNAME, Password.c_str());
if (!HashTableInsert(info))
{
delete info;
send_packet(s, "Registration failed (username exists or table full).");
return KReturn::UNKNOWN;
}
send_packet(s, "Registration successful now ~login");
return KReturn::SUCCESS;
}
case ServerCommands::login:
{
if (LoggedIn(s))
{
send_packet(s, "User already logged in.");
return KReturn::UNKNOWN;
}
std::istringstream StringStream(CommandInput);
std::string cmd, username, password;
StringStream >> cmd >> username >> password;
if (username.empty() || password.empty())
{
send_packet(s,"Usage: ~login username password");
return KReturn::SUCCESS;
}
ClientInfo* info = HashTableFind(username.c_str());
if (info == NULL)
{
send_packet(s, "User not found, please use ~register command.");
return KReturn::UNKNOWN;
}
if (strcmp(info->password, password.c_str()) != 0)
{
send_packet(s, "Incorrect password.");
return KReturn::UNKNOWN;
}
SocketToUser[s] = username;
UserToSocket[username] = s;
send_packet(s, "Login successful. Welcome to KOS COMS");
return KReturn::SUCCESS;
}
case ServerCommands::getlist:
{
//if the users isnt logined in
if (!LoggedIn(s))
{
ServerMessage(s, "~Login first");
return KReturn::UNKNOWN;
}
std::string out = "Active clients(logged in):\n";
for (const auto& ActiveClients : SocketToUser)
out += " - " + ActiveClients.second + "\n";
ServerMessage(s, out);
return KReturn::SUCCESS;
}
case ServerCommands::logout:
{
//Erase users using logout
if (!LoggedIn(s))
{
ServerMessage(s, "~login first please");
return KReturn::UNKNOWN;
}
std::string out = "User logged out: ";
for (const auto& Client : SocketToUser)
{
if (Client.first == s)
{
out += Client.second;
break;
}
else
{
continue;
}
}
for (const auto& ActiveClients : SocketToUser)
{
ServerMessage(s, out);
}
FD_CLR(s, &MasterSet);
shutdown(s, SD_BOTH);
closesocket(s);
return KReturn::SUCCESS;
}
case ServerCommands::getlog:
{
if (!LoggedIn(s))
{
ServerMessage(s, "~login first please");
return KReturn::UNKNOWN;
}
std::ifstream in(PublicLogPath, std::ios::in);
if (!in.is_open())
{
ServerMessage(s, "No public log found yet.");
return KReturn::UNKNOWN;
}
std::ostringstream ss;
ss << in.rdbuf();
std::string content = ss.str();
if (content.empty())
{
content = "Public log is empty\n";
}
ServerMessage(s, "Public Message Log\n");
ServerMessage(s, content);
ServerMessage(s, "End of log\n");
return KReturn::SUCCESS;
}
case ServerCommands::send:
{
if (!LoggedIn(s))
{
ServerMessage(s, "~login first please");
return KReturn::UNKNOWN;
}
std::istringstream iss(CommandInput);
std::string cmd, target;
iss >> cmd >> target;
std::string message;
std::getline(iss, message);
if (!message.empty() && message[0] == ' ')
message.erase(0, 1);
if (target.empty() || message.empty())
{
ServerMessage(s, "Usage: ~send <username> <message>");
return KReturn::UNKNOWN;
}
auto ClientTo = UserToSocket.find(target);
if (ClientTo == UserToSocket.end())
{
ServerMessage(s, "User '" + target + "' is not online.");
return KReturn::UNKNOWN;
}
auto ClientFrom = SocketToUser.find(s);
std::string fromUser = ClientFrom->second;
SOCKET toSock = ClientTo->second;
std::string outToTarget = "[DM] " + fromUser + ": " + message + "\n";
send_packet(toSock, outToTarget.c_str());
ServerMessage(s, "DM sent to '" + target + "'.");
return KReturn::SUCCESS;
}
case ServerCommands::Unknown:
{
ServerMessage(s, "Unknown command sent to server, please use ~help to see the list of commands");
return KReturn::UNKNOWN;
}
}
return KReturn::UNKNOWN;
}