-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathserver.cpp
More file actions
2124 lines (1909 loc) · 82.9 KB
/
server.cpp
File metadata and controls
2124 lines (1909 loc) · 82.9 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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2022-present Zhenrong WANG
* This code is distributed under the license: MIT License
* mailto: zhenrongwang@live.com | X/Twitter: wangzhr4
*/
#include "lc_keymgr.hpp"
#include "lc_consts.hpp"
#include "lc_bufmgr.hpp"
#include "lc_common.hpp"
#include "lc_long_msg.hpp"
#include "lc_db.hpp"
#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <vector>
#include <sodium.h> // For libsodium
#include <cstring> // For C string
#include <algorithm> // For std::find_if
#include <sstream> // For stringstream
#include <unordered_map>
#include <chrono>
#include <thread>
#include <thread>
#include <ctime>
#include <fstream>
#include <regex>
#include <random>
#include <iomanip>
/**
* The headers (up to 2024-12-28)
* ----------
* 0x00: initial handshake
* 0x01: initial handshake
* 0x02: AES validation
* ----------
* 0x10: encrypted message between server and client (with sequence number)
* 0x11: signed broadcasting from server to all clients
* 0x12: signed message from server to a specific client (currently not in use)
* ----------
* 0x17: encrypted ACK message (server->client, acknowledges 0x10 message)
* ----------
* 0x1F: signed heartbeat / goodbye message
* ----------
* 0x13: signed long message send / recv
* 0x14: signed long message recv retry request
* 0x15: encrypted long message send / recv
* 0x16: encrypted long message recv retry request
* ----------
*/
enum SERVER_ERRORS {
NORMAL_RETURN = 0,
KEYMGR_FAILED,
USERDB_PRECHECK_FAILED,
SOCK_FD_INVALID,
SOCK_BIND_FAILED,
SET_TIMEOUT_FAILED,
INTERNAL_FATAL,
MSG_SIGNING_FAILED
};
// We use AES256-GCM algorithm here
class session_item {
// Received
std::array<uint8_t, CID_BYTES> client_cid;
std::array<uint8_t, crypto_box_PUBLICKEYBYTES> client_public_key;
std::array<uint8_t, crypto_sign_PUBLICKEYBYTES> client_sign_key;
// Generated
uint64_t cinfo_hash; // Will be the unique key for unordered_map.
std::array<uint8_t, SID_BYTES> server_sid;
std::array<uint8_t, crypto_aead_aes256gcm_KEYBYTES> aes256gcm_key;
struct sockaddr_in src_addr; // the updated source_ddress.
time_t last_heartbeat;
// 0 - empty
// 1 - prepared: cid + public_key + real cinfo_hash + server_sid + AES_key
// 2 - activated
int status;
public:
// Disable the default constructor
session_item () : status(0) {}
// Provide a random cinfo_hash but no client info.
session_item (const uint64_t& precalc_cinfo_hash) : status(0) {
cinfo_hash = precalc_cinfo_hash;
}
const struct sockaddr_in& get_src_addr () const {
return src_addr;
}
void set_src_addr (const sockaddr_in& addr) {
src_addr = addr;
}
const std::array<uint8_t, crypto_aead_aes256gcm_KEYBYTES>&
get_aes_gcm_key () const {
return aes256gcm_key;
}
const std::array<uint8_t, CID_BYTES>& get_client_cid () const {
return client_cid;
}
const std::array<uint8_t, SID_BYTES>& get_server_sid () const {
return server_sid;
}
const std::array<uint8_t, crypto_box_PUBLICKEYBYTES>&
get_client_public_key () const {
return client_public_key;
}
const std::array<uint8_t, crypto_sign_PUBLICKEYBYTES>&
get_client_sign_key () const {
return client_sign_key;
}
const int& get_status () const {
return status;
}
int prepare (std::array<uint8_t, CID_BYTES>& recv_client_cid,
std::array<uint8_t, crypto_box_PUBLICKEYBYTES>& recv_client_public_key,
std::array<uint8_t, crypto_sign_PUBLICKEYBYTES>& recv_client_sign_key,
const key_mgr_25519& key_mgr, bool is_precalc_hash) {
if (!key_mgr.is_activated())
return -1;
if (status != 0)
return 1;
std::array<uint8_t, crypto_aead_aes256gcm_KEYBYTES> aes_key;
if (lc_utils::calc_aes_key(aes_key, recv_client_public_key,
key_mgr.get_crypto_sk()) != 0)
return 3;
client_cid = recv_client_cid;
client_public_key = recv_client_public_key;
client_sign_key = recv_client_sign_key;
aes256gcm_key = aes_key;
if (!is_precalc_hash)
cinfo_hash = lc_utils::hash_client_info(recv_client_cid,
recv_client_public_key);
randombytes_buf(server_sid.data(), server_sid.size());
status = 1;
return 0;
}
bool activate () {
if (status != 1)
return false;
status = 2;
return true;
}
const time_t& get_last_heartbeat () {
return last_heartbeat;
}
void set_last_heartbeat (time_t t) {
last_heartbeat = t;
}
bool is_inactive () {
if (lc_utils::now_time() > last_heartbeat + HEARTBEAT_TIMEOUT_SECS)
return true;
else
return false;
}
bool is_inactive (time_t now) {
if (now - last_heartbeat > HEARTBEAT_TIMEOUT_SECS)
return true;
else
return false;
}
};
struct session_pool_stats {
size_t total = 0;
size_t empty = 0;
size_t recycled = 0;
size_t prepared = 0;
size_t active = 0;
};
class session_pool {
std::unordered_map<uint64_t, session_item> sessions;
session_pool_stats stats;
uint64_t gen_64bit_key () {
std::array<uint8_t, 8> hash_key;
randombytes_buf(hash_key.data(), hash_key.size());
uint64_t ret = 0;
for (uint8_t i = 0; i < 8; ++ i)
ret |= (static_cast<uint64_t>(hash_key[i]) << (i * 8));
return ret;
}
public:
session_pool () : stats({0, 0, 0, 0, 0}) {};
int prepare_add_session(std::array<uint8_t, CID_BYTES>& recv_client_cid,
std::array<uint8_t, crypto_box_PUBLICKEYBYTES>& recv_client_public_key,
std::array<uint8_t, crypto_sign_PUBLICKEYBYTES>& recv_client_sign_key,
const key_mgr_25519& key_mgr) {
if (!key_mgr.is_activated())
return -1;
uint64_t key = lc_utils::hash_client_info(recv_client_cid,
recv_client_public_key);
if (sessions.find(key) != sessions.end())
return 1;
session_item session(key);
session.prepare(recv_client_cid, recv_client_public_key,
recv_client_sign_key, key_mgr, true);
sessions.insert({key, session});
++ stats.total;
++ stats.prepared;
return 0;
}
session_item* get_session (uint64_t key) {
auto it = sessions.find(key);
if (it != sessions.end())
return &(*it).second;
return nullptr;
}
bool is_session_stored (uint64_t key) {
return (get_session(key) != nullptr);
}
void update_stats_at_session_delete (int status) {
-- stats.total;
if (status == 0 || status == 1)
-- stats.empty;
else if (status == 2)
-- stats.prepared;
else if (status == 3)
-- stats.active;
else
-- stats.recycled;
}
bool delete_session (uint64_t key) {
auto ptr = get_session(key);
if (ptr == nullptr)
return false;
auto status = ptr->get_status();
sessions.erase(key);
update_stats_at_session_delete(status);
return true;
}
int activate_session (uint64_t key) {
auto ptr = get_session(key);
if (ptr == nullptr)
return -1;
if (ptr->activate()) {
++ stats.active;
-- stats.prepared;
return 0;
}
return 1;
}
std::unordered_map<uint64_t, session_item>& get_session_map () {
return sessions;
}
struct session_pool_stats& get_stats () {
return stats;
}
};
// Connection Context contains an addr, a bind/empty uid, and a status
class ctx_item {
std::string ctx_uid; // Binded/Empty user unique ID
int ctx_status; // Status
// 0 - empty, wait for option (signup, signin, signout)
// 1 - signup or signin, auth info received (userid, password)
// public_msg + encrypted_msg(0 - signup, 1 - signin, 2 - signout)
// 2 - signup or singin OK, good for messaging
// Reliability: duplicate detection using sliding window
// Track last 64 sequence numbers to detect duplicates (replay protection)
std::array<bool, 64> seq_window; // Bitmap for sequence numbers
uint16_t seq_window_base; // Base sequence number for the window
public:
ctx_item () : ctx_status(0), seq_window_base(0) {
ctx_uid.clear();
seq_window.fill(false);
}
[[nodiscard]] const std::string& get_bind_uid () const {
return ctx_uid;
}
[[nodiscard]] int get_status () const {
return ctx_status;
}
void set_bind_uid (const std::string& uid) {
ctx_uid = uid;
}
void set_status (int status) {
ctx_status = status;
}
void reset_ctx () { // Go back to status 1
ctx_uid.clear();
ctx_status = 1;
}
void clear_ctx () { // Clear everything
ctx_uid.clear();
ctx_status = 0;
seq_window.fill(false);
seq_window_base = 0;
}
// Check if sequence number is duplicate (within sliding window)
// Returns true if duplicate, false if new
bool is_duplicate_seq(uint16_t seq) {
// Calculate distance from base
uint16_t distance;
if (seq >= seq_window_base) {
distance = seq - seq_window_base;
} else {
// Handle wrap-around: seq < base means it wrapped
distance = static_cast<uint16_t>((65535U - seq_window_base) + seq + 1);
}
// If too far from base, advance window
if (distance >= 64) {
// Advance window to include this sequence number
uint16_t new_base = (seq >= 32) ? static_cast<uint16_t>(seq - 32) :
static_cast<uint16_t>(65535U - (32 - seq));
seq_window.fill(false);
seq_window_base = new_base;
distance = (seq >= new_base) ? (seq - new_base) :
static_cast<uint16_t>((65535U - new_base) + seq + 1);
}
// Check if already seen
if (distance < 64 && seq_window[distance]) {
return true; // Duplicate
}
// Mark as seen
if (distance < 64) {
seq_window[distance] = true;
}
return false; // New sequence number
}
};
class ctx_pool {
std::unordered_map<uint64_t, ctx_item> contexts;
public:
ctx_pool () {};
ctx_item *get_ctx (const uint64_t& key) {
auto it = contexts.find(key);
if (it == contexts.end())
return nullptr;
return &(*it).second;
}
std::unordered_map<uint64_t, ctx_item>& get_ctx_map () {
return contexts;
}
bool add_ctx (uint64_t& key) {
if (contexts.find(key) != contexts.end())
return false;
contexts.emplace(key, ctx_item());
return true;
}
bool delete_ctx (uint64_t& key) {
if (contexts.find(key) == contexts.end())
return false;
contexts.erase(key);
return true;
}
bool is_valid_ctx (uint64_t& key) {
return (contexts.find(key) != contexts.end());
}
bool clear_ctx_by_uid (const uint64_t& this_cif, const std::string& uid,
uint64_t& cif) {
for (auto& elem : contexts) {
if (elem.second.get_bind_uid() == uid && elem.first != this_cif) {
elem.second.clear_ctx();
cif = elem.first;
return true;
}
}
return false;
}
};
// Each user entry include a unique id and a hashed password
// This approach is not secure enough because we just used ordinary
// SHA-256 to hash the password. Please use more secure one for serious
// purposes.
struct user_item {
std::string unique_email; // Original unique email address provided by user, the main key
std::string unique_name; // User self specified id. e.g.
std::array<char, crypto_pwhash_STRBYTES> pass_hash; // Hashed password
uint8_t user_status; // Currently, 0 - not in, 1 - signed in.
uint64_t bind_cif;
};
// User management using SQLite database for persistence
// In-memory cache for frequently accessed data (status, bind_cif)
class user_mgr {
std::unique_ptr<lichat_db::database> db_;
std::string db_file_path;
// In-memory cache for fast lookups of frequently changing data
// key: unique_email
// value: user_item (status and bind_cif are cached)
std::unordered_map<std::string, struct user_item> user_cache;
// key: unique_unames
// value: unique_email
std::unordered_map<std::string, std::string> uname_uemail;
public:
user_mgr () {}
user_mgr (const std::string& path) : db_file_path(path) {
// Convert binary file path to SQLite path
if (db_file_path.empty()) {
db_file_path = default_user_db_path;
}
// Change extension from .db to .sqlite
size_t last_dot = db_file_path.find_last_of('.');
if (last_dot != std::string::npos) {
db_file_path = db_file_path.substr(0, last_dot) + ".sqlite";
} else {
db_file_path += ".sqlite";
}
db_ = std::make_unique<lichat_db::database>(db_file_path);
}
static bool pass_hash_secure (std::string& password,
std::array<char, crypto_pwhash_STRBYTES>& hashed_pwd) {
auto ret =
(crypto_pwhash_str(
hashed_pwd.data(),
password.c_str(),
password.size(),
crypto_pwhash_OPSLIMIT_INTERACTIVE,
crypto_pwhash_MEMLIMIT_INTERACTIVE
) == 0);
password.clear(); // For security reasons, we clean the string after hashing.
return ret;
}
// Return 0: database is good to use
// Return 1 or 3: database initialization failed
int precheck_user_db () {
if (!db_) {
return 1; // Database not initialized
}
if (!db_->open()) {
return 1; // Failed to open database
}
if (!db_->create_schema()) {
return 3; // Failed to create schema
}
return 0; // Database is ready
}
int preload_user_db (size_t& loaded) {
if (user_cache.size() > 0)
return 1; // This operation is only valid at the beginning of the running.
if (precheck_user_db() != 0)
return 3; // Failed to precheck the db file.
// Load all users from database into cache
// We'll load them on-demand, but preload the username->email mapping
// for fast lookups
loaded = db_->get_user_count();
// Preload username->email mapping by querying all users
// (This is done on-demand in practice, but we count them here)
return 0;
}
bool is_email_registered (const std::string& email) {
if (!db_ || !db_->is_open()) {
return false;
}
return db_->user_exists_by_email(email);
}
static std::string email_to_uid (const std::string& valid_email) {
uint8_t sha256_hash[crypto_hash_sha256_BYTES];
crypto_hash_sha256(sha256_hash,
reinterpret_cast<const unsigned char *>(valid_email.c_str()),
valid_email.size());
char b64_cstr[crypto_hash_sha256_BYTES * 2];
sodium_bin2base64(b64_cstr, crypto_hash_sha256_BYTES * 2, sha256_hash,
crypto_hash_sha256_BYTES,
sodium_base64_VARIANT_ORIGINAL);
return std::string(b64_cstr);
}
// If the provided username is duplicated, try randomize it with a suffix
// The suffix comes from a random 6-byte block (2 ^ 48 possibilities)
// If the username is still duplicate after randomization, return false
// else return true.
bool randomize_username (std::string& uname) {
uint8_t random_suffix3[3], random_suffix6[6], random_suffix9[9];
auto check = [](std::string& str, uint8_t *bytes, size_t n) {
size_t b64_size = sodium_base64_encoded_len(n,
sodium_base64_VARIANT_URLSAFE_NO_PADDING);
std::vector<char> b64_cstr(b64_size);
std::string new_name;
randombytes_buf(bytes, n);
sodium_bin2base64(b64_cstr.data(), b64_size,
bytes, n, sodium_base64_VARIANT_URLSAFE_NO_PADDING);
if (str.size() + 1 + b64_size > UNAME_MAX_BYTES) {
auto pos = UNAME_MAX_BYTES - 1 - b64_size;
new_name = str.substr(0, pos) + "-" + std::string(b64_cstr.data());
}
else {
new_name = str + "-" + std::string(b64_cstr.data());
}
return new_name;
};
// First try.
std::string new_name;
new_name = check(uname, random_suffix3, sizeof(random_suffix3));
if (!is_username_occupied(new_name)) {
uname = new_name;
return true;
}
new_name = check(uname, random_suffix6, sizeof(random_suffix6));
if (!is_username_occupied(new_name)) {
uname = new_name;
return true;
}
new_name = check(uname, random_suffix9, sizeof(random_suffix9));
if (!is_username_occupied(new_name)) {
uname = new_name;
return true;
}
return false;
}
bool is_username_occupied (const std::string& uname) {
// Check cache first
if (uname_uemail.find(uname) != uname_uemail.end()) {
return true;
}
// Check database
if (!db_ || !db_->is_open()) {
return false;
}
bool exists = db_->user_exists_by_username(uname);
if (exists) {
// Cache the mapping
std::string email;
std::array<char, crypto_pwhash_STRBYTES> passhash;
if (db_->get_user_by_username(uname, email, passhash)) {
uname_uemail[uname] = email;
}
}
return exists;
}
// Have to use pointer to avoid exception handling.
const std::string* get_uemail_by_uname (const std::string& uname) {
// Check cache first
auto it = uname_uemail.find(uname);
if (it != uname_uemail.end()) {
return &(it->second);
}
// Query database
if (!db_ || !db_->is_open()) {
return nullptr;
}
std::string email;
std::array<char, crypto_pwhash_STRBYTES> passhash;
if (db_->get_user_by_username(uname, email, passhash)) {
uname_uemail[uname] = email;
return &(uname_uemail[uname]);
}
return nullptr;
}
// Have to use pointer to avoid exception handling.
const std::string* get_uname_by_uemail (const std::string& uemail) {
// Check cache first
auto it = user_cache.find(uemail);
if (it != user_cache.end()) {
return &(it->second.unique_name);
}
// Query database
if (!db_ || !db_->is_open()) {
return nullptr;
}
std::string username;
std::array<char, crypto_pwhash_STRBYTES> passhash;
if (db_->get_user_by_email(uemail, username, passhash)) {
// Cache it
user_item cached_user;
cached_user.unique_email = uemail;
cached_user.unique_name = username;
cached_user.pass_hash = passhash;
cached_user.user_status = 0;
cached_user.bind_cif = 0;
user_cache[uemail] = cached_user;
uname_uemail[username] = uemail;
return &(user_cache[uemail].unique_name);
}
return nullptr;
}
user_item* get_user_item_by_uemail (const std::string& uemail) {
// Check cache first
auto it = user_cache.find(uemail);
if (it != user_cache.end()) {
return &(it->second);
}
// Query database
if (!db_ || !db_->is_open()) {
return nullptr;
}
std::string username;
std::array<char, crypto_pwhash_STRBYTES> passhash;
if (db_->get_user_by_email(uemail, username, passhash)) {
// Cache it
user_item cached_user;
cached_user.unique_email = uemail;
cached_user.unique_name = username;
cached_user.pass_hash = passhash;
cached_user.user_status = 0;
cached_user.bind_cif = 0;
user_cache[uemail] = cached_user;
uname_uemail[username] = uemail;
return &(user_cache[uemail]);
}
return nullptr;
}
user_item* get_user_item_by_uname (const std::string& uname) {
auto uemail_ptr = get_uemail_by_uname(uname);
if (uemail_ptr == nullptr)
return nullptr;
return get_user_item_by_uemail(*uemail_ptr);
}
auto get_total_user_num () {
if (!db_ || !db_->is_open()) {
return user_cache.size();
}
return db_->get_user_count();
}
bool add_user (const std::string& uemail, std::string& uname,
std::string& user_password, uint8_t& err, bool& is_uname_randomized) {
err = 0;
is_uname_randomized = false;
if (!db_ || !db_->is_open()) {
err = 1;
return false;
}
if (lc_utils::email_fmt_check(uemail) != 0) {
err = 1;
return false;
}
if (is_email_registered(uemail)) {
err = 3;
return false;
}
if (lc_utils::user_name_fmt_check(uname) != 0) {
err = 5;
return false;
}
if (lc_utils::pass_fmt_check(user_password) != 0) {
err = 7;
return false;
}
std::array<char, crypto_pwhash_STRBYTES> hashed_pass;
if (!pass_hash_secure(user_password, hashed_pass)) {
err = 9;
return false;
}
if (is_username_occupied(uname)) {
if (!randomize_username(uname)) {
err = 11;
return false;
}
is_uname_randomized = true;
}
// Add to database
if (!db_->add_user(uemail, uname, hashed_pass)) {
err = 13;
return false;
}
// Cache it
struct user_item new_user;
new_user.unique_email = uemail;
new_user.unique_name = uname;
new_user.pass_hash = hashed_pass;
new_user.user_status = 0;
new_user.bind_cif = 0;
user_cache.insert({uemail, new_user});
uname_uemail.insert({uname, uemail});
return true;
}
// type = 0: uemail + password
// type = 1 (or others): uname + password
bool user_pass_check (const uint8_t type, const std::string& str,
std::string& password, uint8_t& err) {
user_item *ptr_item = nullptr;
err = 0;
if (type == 0x00) {
if (!is_email_registered(str)) {
err = 2;
password.clear();
return false;
}
ptr_item = get_user_item_by_uemail(str);
}
else {
if (!is_username_occupied(str)) {
err = 4;
password.clear();
return false;
}
ptr_item = get_user_item_by_uname(str);
}
if (ptr_item == nullptr) {
err = 6;
password.clear();
return false;
}
auto ret = (crypto_pwhash_str_verify(
(ptr_item->pass_hash).data(),
password.c_str(),
password.size()) == 0);
password.clear();
if (!ret) err = 8;
return ret;
}
std::string user_list_to_str (bool show_status) {
if (!db_ || !db_->is_open()) {
// Fallback to cache
std::string u_list;
for (auto it : user_cache) {
auto u = it.second;
if (show_status) {
u_list += u.unique_name +
((u.user_status == 1) ? (" (in)\n") : ("\n"));
}
else {
u_list += u.unique_name + "\n";
}
}
return u_list;
}
return db_->get_user_list_string(show_status);
}
user_item *get_user_item (const uint8_t type, const std::string& str) {
if (type == 0x00)
return get_user_item_by_uemail(str);
else
return get_user_item_by_uname(str);
}
// type = 0: uemail
// type = 1 (or others): uname
bool bind_user_ctx (const uint8_t type, const std::string& str,
const uint64_t& cif) {
auto ptr_user = get_user_item(type, str);
if (ptr_user == nullptr)
return false;
// Update cache
ptr_user->user_status = 1;
ptr_user->bind_cif = cif;
// Update database
if (db_ && db_->is_open()) {
std::string email = (type == 0) ? str : *get_uemail_by_uname(str);
if (!email.empty()) {
db_->update_user_status(email, 1);
db_->update_user_bind_cif(email, cif);
}
}
return true;
}
bool unbind_user_ctx (const uint8_t type, const std::string& str) {
user_item *ptr_item = get_user_item(type, str);
if (ptr_item == nullptr)
return false;
// Update cache
ptr_item->user_status = 0;
ptr_item->bind_cif = 0;
// Update database
if (db_ && db_->is_open()) {
std::string email = (type == 0) ? str : *get_uemail_by_uname(str);
if (!email.empty()) {
db_->update_user_status(email, 0);
db_->update_user_bind_cif(email, 0);
}
}
return true;
}
bool get_bind_cif (const uint8_t type, const std::string& str,
uint64_t& cif) {
auto ptr_user = get_user_item(type, str);
if (ptr_user == nullptr)
return false;
if (ptr_user->user_status == 0)
return false;
cif = ptr_user->bind_cif;
return true;
}
std::pair<size_t, size_t> get_user_stat () {
size_t total = get_total_user_num();
size_t in = 0;
// Count signed-in users from cache
for (auto& it : user_cache) {
if (it.second.user_status == 1)
++ in;
}
// Also check database for users not in cache
if (db_ && db_->is_open()) {
// Query database for users with status = 1
// For now, we rely on cache. In production, you might want to query DB directly.
}
return std::make_pair(total, in);
}
};
// The main class.
class lichat_server {
struct sockaddr_in server_addr; // socket addr
uint16_t server_port; // port number
int server_fd; // generated server_fd
std::string key_dir; // Key directory
key_mgr_25519 key_mgr; // key manager
msg_buffer buffer; // Message core processor
user_mgr users; // all users
session_pool conns; // all sessions.
ctx_pool clients; // all clients(contexts).
lmsg_send_pool lmsg_sends; // send long messages.
lmsg_recv_pool lmsg_recvs; // receive long messages
int last_error; // error code
public:
// A simple constructor
lichat_server () {
server_port = DEFAULT_SERVER_PORT;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
server_fd = -1;
key_dir = default_key_dir;
key_mgr = key_mgr_25519(key_dir, "server_");
buffer = msg_buffer();
users = user_mgr(default_user_db_path);
conns = session_pool();
clients = ctx_pool();
last_error = 0;
}
void set_port (uint16_t port) {
server_port = port;
server_addr.sin_port = htons(server_port);
}
void set_key_dir (const std::string& dir) {
key_dir = default_key_dir;
key_mgr.set_key_dir(dir);
}
// Close server and possible FD
bool close_server (int err) {
last_error = err;
if (server_fd != -1) {
close(server_fd);
server_fd = -1;
}
return err == 0;
}
// Get last error code
int get_last_error (void) {
return last_error;
}
// Start the server and handle possible failures
bool start_server (void) {
if (key_mgr.key_mgr_init() != 0) {
std::cout << "Key manager not activated." << std::endl;
return close_server(KEYMGR_FAILED);
}
if (users.precheck_user_db() != 0) {
std::cout << "User database precheck failed. "
<< users.precheck_user_db() << std::endl;
return close_server(USERDB_PRECHECK_FAILED);
}
server_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (server_fd == -1)
return close_server(SOCK_FD_INVALID);
if (bind(server_fd, (sockaddr *)&server_addr, (socklen_t)sizeof(server_addr)))
return close_server(SOCK_BIND_FAILED);
std::cout << "LightChat (LiChat) Service started." << std::endl
<< "UDP Listening Port: " << server_port << std::endl;
return true;
}
bool is_session_valid (const uint64_t& cinfo_hash) {
return (conns.get_session(cinfo_hash) != nullptr);
}
// Simplify the socket send function.
ssize_t simple_send (const uint64_t& cinfo_hash, const uint8_t *msg, size_t n) {
auto p_conn = conns.get_session(cinfo_hash);
if (p_conn == nullptr)
return -3; // Invalid cinfo_hash
auto addr = p_conn->get_src_addr();
return sendto(server_fd, msg, n, MSG_CONFIRM, (struct sockaddr *)&addr,
sizeof(addr));
}
// Simplify the socket send function.
ssize_t simple_send (const struct sockaddr_in& addr, const uint8_t *msg,
size_t n) const {
return sendto(server_fd, msg, n, MSG_CONFIRM,
(struct sockaddr *)&addr, sizeof(addr));
}
// Simplify the socket send function.
ssize_t simple_send (uint8_t header, const struct sockaddr_in& addr,
const uint8_t *msg, size_t n) {
if (n + 1 > buffer.send_buffer.size()) {
return -3;
}
buffer.send_buffer[0] = header;
std::copy(msg, msg + n, buffer.send_buffer.begin() + 1);
buffer.send_bytes = n + 1;
return sendto(server_fd, buffer.send_buffer.data(), buffer.send_bytes,
MSG_CONFIRM, (struct sockaddr *)&addr, sizeof(addr));
}
// Simplify the socket send function.
// Format : 1-byte header +
// if 0x00 header, add a 32byte pubkey, otherwise skip +
// aes_nonce +
// aes_gcm_encrypted (sid + cinfo_hash + msg_body)
ssize_t simple_secure_send (const uint8_t header, const uint64_t cif,
const uint8_t *raw_msg, size_t raw_n) {
auto server_aes_nonce =
std::array<uint8_t, crypto_aead_aes256gcm_NPUBBYTES>{};
ssize_t offset = 0;
size_t aes_encrypted_len = 0;
auto conn = conns.get_session(cif);
if (conn == nullptr)
return -1;
auto cif_bytes = lc_utils::u64_to_bytes(cif);
auto sid = conn->get_server_sid();
auto aes_key = conn->get_aes_gcm_key();
auto addr = conn->get_src_addr();
// Padding the first byte
buffer.send_buffer[0] = header;