-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclient.cpp
More file actions
2071 lines (1851 loc) · 82.7 KB
/
client.cpp
File metadata and controls
2071 lines (1851 loc) · 82.7 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_common.hpp"
#include "lc_keymgr.hpp"
#include "lc_consts.hpp"
#include "lc_bufmgr.hpp"
#include "lc_strings.hpp"
#include "lc_long_msg.hpp"
#include "lc_ui_interface.hpp"
#include "lc_ui_qt.hpp"
#include <QApplication>
#include <memory>
#include <thread>
#include <iostream>
#include <sys/socket.h>
#include <unistd.h>
#include <sodium.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <utility>
#include <vector>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <unordered_map>
#include <chrono>
#include <stdexcept>
#include <iomanip>
#include <atomic>
#include <thread>
#include <functional>
#include <fcntl.h>
#include <errno.h>
#include <mutex>
std::atomic<bool> core_running(false);
std::atomic<bool> heartbeating(false);
std::atomic<bool> auto_signout(false);
std::atomic<bool> send_msg_req(false);
std::atomic<bool> send_gby_req(false);
std::atomic<bool> heartbeat_req(false);
std::atomic<bool> heartbeat_timeout(false);
std::atomic<time_t> last_heartbeat_sent(0);
std::atomic<time_t> last_heartbeat_recv(0);
std::atomic<time_t> last_lmsg_check(0);
std::string send_msg_body;
std::mutex mtx;
/**
* LiChat Client Core
*
* Modernized architecture with UI interface abstraction.
* The core is decoupled from specific UI implementations.
*
* UI implementations should implement lichat::ui_interface.
* See lc_ui_interface.hpp for the interface definition.
*
* Global state (for heartbeat and core control):
* - core_running: Controls main core loop
* - heartbeating: Controls heartbeat thread
* - heartbeat_timeout: Set when heartbeat fails
* - heartbeat_req: Request to send heartbeat
* - auto_signout: Set when signed out from another client
*/
enum client_errors {
NORMAL_RETURN = 0,
CLIENT_KEY_MGR_ERROR,
SOCK_FD_INVALID,
SOCK_SETOPT_FAILED,
HANDSHAKE_TIMEOUT,
MSG_SIGNING_FAILED,
SERVER_PK_MGR_ERROR,
HASH_PASSWORD_FAILED,
SESSION_PREP_FAILED,
UNBLOCK_SOCK_FAILED,
WINDOW_MGR_ERROR,
CORE_ERROR,
};
enum core_errors {
C_NORMAL_RETURN = 0,
C_SOCK_FD_INVALID,
C_HEARTBEAT_TIME_OUT,
C_GOODBYE_SENT_ERR,
C_HEARTBEAT_SENT_ERR,
C_SOCKET_RECV_ERR,
};
const std::string heartbeat_timeout_msg =
"\nHeartbeat failed. Press any key to exit.\n";
const std::string client_exit_msg =
"[CLIENT] Will notify the server and exit.\n";
const std::string signed_out_msg =
"[CLIENT] Signed out. Press any key to exit.\n";
const std::string auto_signout_msg =
"Signed in on another client. Signed out here.\nPress any key to exit.\n";
const std::string send_gdy_failed =
"Failed to notify the server. Force exit.\n";
const std::string lmsg_recv_failed =
"Failed to receive long message.\n";
class curr_user {
std::string unique_email;
std::string unique_name;
bool with_random_suffix;
public:
curr_user () : with_random_suffix(false) {}
void set_uemail (const std::string& str) {
unique_email = str;
}
void set_uname (const std::string& str) {
unique_name = str;
}
void set_suffix_flag (bool flag) {
with_random_suffix = flag;
}
const std::string& get_uemail () const {
return unique_email;
}
[[nodiscard]] const std::string& get_uname () const {
return unique_name;
}
[[nodiscard]] bool get_suffix_flag () const {
return with_random_suffix;
}
};
class client_server_pk_mgr {
std::string server_pk_dir;
std::array<uint8_t, crypto_box_PUBLICKEYBYTES> server_crypto_pk{};
std::array<uint8_t, crypto_sign_PUBLICKEYBYTES> server_sign_pk{};
bool status;
public:
client_server_pk_mgr () : server_pk_dir(default_key_dir), status(false) {}
explicit client_server_pk_mgr (std::string dir) : server_pk_dir(std::move(dir)),
status(false) {}
void set_dir (const std::string& dir) {
server_pk_dir = dir;
}
[[nodiscard]] const std::string& get_dir () const {
return server_pk_dir;
}
bool read_server_pk () {
std::vector<uint8_t> server_spk(crypto_sign_PUBLICKEYBYTES),
server_cpk(crypto_box_PUBLICKEYBYTES);
std::string server_spk_file = server_pk_dir +
"/client_server_sign.pub";
std::string server_cpk_file = server_pk_dir +
"/client_server_crypto.pub";
auto res1 = key_mgr_25519::read_key_file(server_cpk_file, server_cpk,
crypto_box_PUBLICKEYBYTES);
auto res2 = key_mgr_25519::read_key_file(server_spk_file, server_spk,
crypto_sign_PUBLICKEYBYTES);
if (res1 == 0 && res2 == 0) {
std::copy(server_spk.begin(), server_spk.end(),
server_sign_pk.begin());
std::copy(server_cpk.begin(), server_cpk.end(),
server_crypto_pk.begin());
status = true;
return true;
}
return false;
}
bool clear_stored_pk (void) {
std::string server_spk_file = server_pk_dir +
"/client_server_sign.pub";
std::string server_cpk_file = server_pk_dir +
"/client_server_crypto.pub";
std::ofstream out_spk(server_spk_file, std::ios::binary);
std::ofstream out_cpk(server_cpk_file, std::ios::binary);
if (!out_spk.is_open() || !out_cpk.is_open()) {
if (out_spk.is_open()) out_spk.close();
if (out_cpk.is_open()) out_cpk.close();
return false;
}
std::string inval("inval");
out_spk.write(inval.c_str(), inval.size());
out_cpk.write(inval.c_str(), inval.size());
out_spk.close();
out_cpk.close();
return true;
}
bool update_server_pk (
const std::array<uint8_t, crypto_sign_PUBLICKEYBYTES>& recved_spk,
const std::array<uint8_t, crypto_box_PUBLICKEYBYTES>& recved_cpk) {
std::string server_spk_file = server_pk_dir +
"/client_server_sign.pub";
std::string server_cpk_file = server_pk_dir +
"/client_server_crypto.pub";
std::ofstream out_spk(server_spk_file, std::ios::binary);
std::ofstream out_cpk(server_cpk_file, std::ios::binary);
if (!out_spk.is_open() || !out_cpk.is_open()) {
if (out_spk.is_open()) out_spk.close();
if (out_cpk.is_open()) out_cpk.close();
return false;
}
out_spk.write(reinterpret_cast<const char *>(recved_spk.data()),
recved_spk.size());
out_cpk.write(reinterpret_cast<const char *>(recved_cpk.data()),
recved_cpk.size());
out_spk.close();
out_cpk.close();
server_sign_pk = recved_spk;
server_crypto_pk = recved_cpk;
status = true;
return true;
}
const std::array<uint8_t, crypto_sign_PUBLICKEYBYTES>&
get_server_spk () const {
return server_sign_pk;
}
[[nodiscard]] const std::array<uint8_t, crypto_box_PUBLICKEYBYTES>&
get_server_cpk () const {
return server_crypto_pk;
}
[[nodiscard]] bool is_ready () const {
return status; // If true, good to go, othersize not.
}
};
class client_session {
// Generated
std::array<uint8_t, CID_BYTES> client_cid;
// Read / Received
std::array<uint8_t, crypto_aead_aes256gcm_KEYBYTES> aes256gcm_key;
// Received
std::array<uint8_t, SID_BYTES> server_sid;
uint64_t cinfo_hash;
std::array<uint8_t, CIF_BYTES> cinfo_hash_bytes;
struct sockaddr_in src_addr; // the updated source_ddress.
// 0 - Empty: cid generated
// 1 - Standby: client info sent, waiting for server response.
// 2 - Prepared: server response received and good, sent ok waiting for server ok.
// cid + server_pk + aes256gcm_key + server_sid + cinfo_hash
// 3 - Sent user credentials, waiting for server ok
// 4 - Activated.
int status;
bool is_server_key_req;
// Reliability: sequence number for 0x10 messages
uint16_t seq_counter;
public:
client_session () : status(0), is_server_key_req(false), seq_counter(0) {
randombytes_buf(client_cid.data(), client_cid.size());
}
void sent_cinfo (const bool server_key_req) {
status = 1;
is_server_key_req = server_key_req;
}
[[nodiscard]] bool requested_server_key () const {
return is_server_key_req;
}
void reset () {
randombytes_buf(client_cid.data(), client_cid.size());
status = 0;
seq_counter = 0;
}
uint16_t get_next_seq () {
return ++seq_counter; // Wraps at 65535
}
uint16_t get_current_seq () const {
return seq_counter;
}
int prepare (const client_server_pk_mgr& server_pk_mgr,
const key_mgr_25519& client_key,
const std::array<uint8_t, SID_BYTES>& sid,
const std::array<uint8_t, CIF_BYTES>& cif_bytes) {
if (status != 1)
return -1; // Not quite possible
if (!server_pk_mgr.is_ready() || !client_key.is_activated())
return -3; // key_mgr not activated
uint64_t cif_calc = lc_utils::hash_client_info(client_cid,
client_key.get_crypto_pk());
uint64_t cif_recv = lc_utils::bytes_to_u64(cif_bytes);
if (cif_calc != cif_recv)
return 1; // Need to report to server, msg error
if (crypto_box_beforenm(aes256gcm_key.data(),
server_pk_mgr.get_server_cpk().data(),
client_key.get_crypto_sk().data()) != 0)
return 3; // Need to report to server, msg error
server_sid = sid;
cinfo_hash = cif_recv;
cinfo_hash_bytes = cif_bytes;
status = 2;
return 0;
}
void activate () {
status = 3;
}
void sent_auth () {
status = 4;
}
void auth_ok () {
status = 5;
}
void set_status (int s) {
status = s;
}
const auto get_status () const {
return status;
}
const auto& get_client_cid () const {
return client_cid;
}
const auto& get_aes256gcm_key () const {
return aes256gcm_key;
}
const auto& get_server_sid () const {
return server_sid;
}
const auto& get_cinfo_hash () const {
return cinfo_hash;
}
const auto& get_cinfo_hash_bytes () const {
return cinfo_hash_bytes;
}
const auto& get_src_addr () const {
return src_addr;
}
void update_src_addr (const struct sockaddr_in& addr) {
src_addr = addr;
}
};
class user_list_mgr {
std::string user_list;
public:
user_list_mgr () {}
void receive (const std::string& ulist) {
user_list = ulist;
}
bool update_status (const std::string& user_name, const bool in) {
std::string user_signed_in = user_name + " (in)\n";
std::string not_signed_in = user_name + "\n";
if (in) { // If signed in.
auto find_pos = user_list.find(not_signed_in);
if (find_pos == std::string::npos)
return false;
user_list.replace(find_pos, not_signed_in.length(), user_signed_in);
return true;
}
auto find_pos = user_list.find(user_signed_in);
if (find_pos == std::string::npos)
return false;
user_list.replace(find_pos, user_signed_in.length(), not_signed_in);
return true;
}
void add_signin_user (const std::string& user_name) {
user_list += (user_name + " (in)\n");
}
size_t count_users () {
std::istringstream iss(user_list);
std::string line;
size_t count = 0;
while (std::getline(iss, line))
++ count;
return count;
}
const std::string& get_ulist () const {
return user_list;
}
};
class lichat_client {
uint16_t server_port;
struct sockaddr_in server_addr;
int client_fd;
client_server_pk_mgr server_pk_mgr;
std::string key_dir;
client_session session;
key_mgr_25519 client_key;
msg_buffer buffer;
std::vector<std::string> messages;
lmsg_send_pool lmsg_sends;
lmsg_recv_pool lmsg_recvs;
curr_user user;
std::unique_ptr<lichat::ui_interface> ui;
user_list_mgr ulist_mgr;
time_t heartbeat_interval_secs;
int last_error;
// Reliability: pending message tracking
struct pending_message {
uint16_t seq_num;
time_t timestamp;
std::vector<uint8_t> message_data; // Full encrypted message to retry
int retry_count;
pending_message(uint16_t seq, time_t ts, const std::vector<uint8_t>& data)
: seq_num(seq), timestamp(ts), message_data(data), retry_count(0) {}
};
std::unordered_map<uint16_t, pending_message> pending_messages;
std::mutex pending_mutex;
public:
// Set the UI implementation
void set_ui(std::unique_ptr<lichat::ui_interface> ui_ptr) {
ui = std::move(ui_ptr);
}
// Get the UI implementation (non-owning pointer)
lichat::ui_interface* get_ui() {
return ui.get();
}
lichat_client () :
client_fd(-1), server_pk_mgr(client_server_pk_mgr()),
key_dir(default_key_dir), session(client_session()),
client_key(key_mgr_25519(key_dir, "client_")), buffer(msg_buffer()),
user(curr_user()), ui(nullptr), ulist_mgr(user_list_mgr()),
heartbeat_interval_secs(DEFAULT_HEARTBEAT_INTERVAL_SECS),
last_error(0) {
server_port = DEFAULT_SERVER_PORT;
server_addr.sin_addr.s_addr = inet_addr(DEFAULT_SERVER_ADDR);
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(server_port);
// Store the initial addr to session.
session.update_src_addr(server_addr);
}
// The heartbeat interval should be 0 ~ (timeout / 3)
void set_heartbeat (const size_t interval_secs) {
if (interval_secs < HEARTBEAT_TIMEOUT_SECS / 3 && interval_secs > 0)
heartbeat_interval_secs = interval_secs;
}
static bool get_addr_info(std::string& addr_str,
std::array<char, INET_ADDRSTRLEN>& first_ipv4_addr) {
if (addr_str.empty())
return false;
struct addrinfo hints, *res = nullptr;
std::memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
std::memset(first_ipv4_addr.data(), 0, first_ipv4_addr.size());
auto status = getaddrinfo(addr_str.c_str(), nullptr, &hints, &res);
if (status != 0)
return false;
const auto *first = reinterpret_cast<sockaddr_in*>(res->ai_addr);
inet_ntop(AF_INET, &(first->sin_addr), first_ipv4_addr.data(),
lc_utils::lc_static_cast<socklen_t>(first_ipv4_addr.size()));
freeaddrinfo(res);
return true;
}
// This pass doesn't change the original pass string !
static bool pass_hash_dryrun (const 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);
return ret;
}
bool set_server_addr (std::string& addr_str, std::string& port_str) {
std::array<char, INET_ADDRSTRLEN> ipv4_addr{};
uint16_t port_num;
if (!get_addr_info(addr_str, ipv4_addr) ||
!lc_utils::string_to_u16(port_str, port_num))
return false;
server_port = port_num;
server_addr.sin_addr.s_addr = inet_addr(ipv4_addr.data());
server_addr.sin_port = htons(port_num);
session.update_src_addr(server_addr);
return true;
}
static std::string parse_server_auth_error (const uint8_t err_code) {
if (err_code == 1)
return "E-mail format error.";
else if (err_code == 3)
return "E-mail already signed up.";
else if (err_code == 5)
return "Username format error.";
else if (err_code == 7)
return "Password format error.";
else if (err_code == 9)
return "Failed to hash your password.";
else if (err_code == 11)
return "Failed to randomize your username.";
else if (err_code == 2)
return "E-mail not signed up.";
else if (err_code == 4)
return "Username not signed up.";
else if (err_code == 6)
return "Server internal error.";
else if (err_code == 8)
return "Password incorrect.";
else
return "Unknown server error.";
}
static std::string parse_core_err (const int& core_err) {
if (core_err == C_NORMAL_RETURN)
return "Thread exit normally / gracefully.";
else if (core_err == C_SOCK_FD_INVALID)
return "The provided socket fd is invalid";
else if (core_err == C_SOCKET_RECV_ERR)
return "Socket communication error.";
else if (core_err == C_HEARTBEAT_SENT_ERR)
return "Failed to send heartbeat packets.";
else if (core_err == C_GOODBYE_SENT_ERR)
return "Failed to send goodbye packet.";
else if (core_err == C_HEARTBEAT_TIME_OUT)
return "Heartbeat timeout.";
else
return "Unknown thread error. Possibly a bug.";
}
bool nonblock_socket () const {
int flags = fcntl(client_fd, F_GETFL, 0);
if (flags == -1)
return false;
flags |= O_NONBLOCK;
if (fcntl(client_fd, F_SETFL, flags) == -1)
return false;
return true;
}
static ssize_t simple_send_stc (const int fd, const client_session& curr_s,
const uint8_t *buf, size_t n) {
auto addr = curr_s.get_src_addr();
return sendto(fd, buf, n, 0, (const struct sockaddr*)(&addr),
sizeof(addr));
}
// Simplify the socket send function.
// Format : 1-byte header +
// cinfo_hash +
// aes_nonce +
// aes_gcm_encrypted (sid + msg_body)
static ssize_t simple_secure_send_stc (const int fd, const uint8_t header,
const client_session& curr_s, msg_buffer& buff,
const uint8_t *raw_msg, const size_t raw_n) {
if (curr_s.get_status() == 0 || curr_s.get_status() == 1)
return -1;
bool raw_msg_empty = false;
size_t raw_bytes = raw_n;
if (raw_msg == nullptr || raw_n == 0) {
raw_msg_empty = true;
raw_bytes = 0;
}
if ((1 + CIF_BYTES + crypto_aead_aes256gcm_NPUBBYTES + SID_BYTES +
raw_bytes + crypto_aead_aes256gcm_ABYTES) > BUFF_BYTES)
return -3;
auto aes_key = curr_s.get_aes256gcm_key();
auto cif = curr_s.get_cinfo_hash();
auto cif_bytes = lc_utils::u64_to_bytes(cif);
auto sid = curr_s.get_server_sid();
std::array<uint8_t, crypto_aead_aes256gcm_NPUBBYTES> client_aes_nonce{};
size_t offset = 0, aes_enc_len = 0;
// Padding the first byte
buff.send_buffer[0] = header;
++ offset;
// Padding the cinfo_hash
std::copy(cif_bytes.begin(), cif_bytes.end(),
buff.send_buffer.begin() + offset);
offset += cif_bytes.size();
// Padding the aes_nonce
lc_utils::generate_aes_nonce(client_aes_nonce);
std::copy(client_aes_nonce.begin(), client_aes_nonce.end(),
buff.send_buffer.begin() + offset);
offset += client_aes_nonce.size();
std::copy(sid.begin(), sid.end(), buff.send_aes_buffer.begin());
if (!raw_msg_empty) {
std::copy(raw_msg, raw_msg + raw_bytes,
buff.send_aes_buffer.begin() + sid.size());
}
// Record the buffer occupied size.
buff.send_aes_bytes = lc_utils::lc_static_cast<ssize_t>(sid.size() + raw_bytes);
// AES encrypt and padding to the send_buffer.
auto res = crypto_aead_aes256gcm_encrypt(
buff.send_buffer.data() + offset,
reinterpret_cast<unsigned long long *>(&aes_enc_len),
reinterpret_cast<const uint8_t *>(buff.send_aes_buffer.data()),
buff.send_aes_bytes,
nullptr, 0, nullptr,
client_aes_nonce.data(), aes_key.data()
);
buff.send_bytes = lc_utils::lc_static_cast<ssize_t>(offset + aes_enc_len);
if (res != 0)
return -5;
auto ret = simple_send_stc(fd, curr_s, buff.send_buffer.data(),
buff.send_bytes);
if (ret < 0)
return -7;
return ret;
}
static ssize_t simple_sign_send_stc (const int fd, const uint8_t header,
const client_session& curr_s, const key_mgr_25519& k, msg_buffer& buff,
const uint8_t *raw_msg, const size_t raw_n) {
bool raw_msg_empty = false;
size_t raw_bytes = raw_n;
if (raw_msg == nullptr || raw_n == 0) {
raw_msg_empty = true;
raw_bytes = 0;
}
if (curr_s.get_status() == 0 || curr_s.get_status() == 1)
return -1;
if ((1 + crypto_sign_BYTES + CIF_BYTES + raw_bytes) > BUFF_BYTES)
return -3;
auto cif = curr_s.get_cinfo_hash();
auto cif_bytes = lc_utils::u64_to_bytes(cif);
auto sign_sk = k.get_sign_sk();
size_t offset = 0;
unsigned long long sign_len = 0;
// Padding the first byte
buff.send_buffer[0] = header;
++ offset;
std::vector<uint8_t> cif_msg(CIF_BYTES + raw_bytes);
// Padding the cinfo_hash
std::copy(cif_bytes.begin(), cif_bytes.end(), cif_msg.begin());
if (!raw_msg_empty)
std::copy(raw_msg, raw_msg + raw_bytes, cif_msg.begin() + CIF_BYTES);
auto res = crypto_sign(buff.send_buffer.begin() + offset,
&sign_len, cif_msg.data(), cif_msg.size(), sign_sk.data());
buff.send_bytes = lc_utils::lc_static_cast<ssize_t>(offset + sign_len);
if (res != 0)
return -7;
auto ret = simple_send_stc(fd, curr_s, buff.send_buffer.data(),
buff.send_bytes);
return ret;
}
static bool pack_heartbeat (
const std::array<uint8_t, CIF_BYTES>& cif_bytes,
const std::array<uint8_t, crypto_sign_SECRETKEYBYTES>& client_sign_sk,
std::array<uint8_t, HEARTBEAT_BYTES>& packet) {
packet[0] = 0x1F;
unsigned long long sign_len = 0;
if (crypto_sign(packet.data() + 1, &sign_len, cif_bytes.data(),
cif_bytes.size(), client_sign_sk.data()) != 0)
return false;
return true;
}
static void thread_heartbeat (const time_t interval_secs) {
while (heartbeating) {
auto now = lc_utils::now_time();
if (now - last_heartbeat_recv >= HEARTBEAT_TIMEOUT_SECS) {
heartbeat_timeout.store(true);
return;
}
if (now >= last_heartbeat_sent + interval_secs)
heartbeat_req.store(true);
std::this_thread::sleep_for(
std::chrono::milliseconds(HEARTBEAT_THREAD_SLEEP_MS));
}
}
static bool pack_goodbye (
const std::array<uint8_t, CIF_BYTES>& cif_bytes,
const std::array<uint8_t, crypto_sign_SECRETKEYBYTES>& client_sign_sk,
std::array<uint8_t, GOODBYE_BYTES>& packet) {
packet[0] = 0x1F;
unsigned long long sign_len = 0;
std::array<uint8_t, CIF_BYTES + 1>raw_pack;
std::copy(cif_bytes.begin(), cif_bytes.end(), raw_pack.begin());
raw_pack[CIF_BYTES] = '!';
if (crypto_sign(packet.data() + 1, &sign_len, raw_pack.data(),
raw_pack.size(), client_sign_sk.data()) != 0)
return false;
return true;
}
// New version using UI interface (decoupled)
static void thread_run_core_ui (lichat::ui_interface* ui, const int fd, msg_buffer& buff,
client_session& s, const curr_user& u, user_list_mgr& ulm,
lmsg_send_pool& lm_s, lmsg_recv_pool& lm_r,
const client_server_pk_mgr& server_pk, const key_mgr_25519& client_k,
std::vector<std::string>& msg_vec, int& core_err,
std::unordered_map<uint16_t, pending_message>& pending_messages,
std::mutex& pending_mutex) {
core_err = C_NORMAL_RETURN;
if (fd < 0) {
core_err = C_SOCK_FD_INVALID;
return;
}
if (!ui) {
core_err = C_SOCK_FD_INVALID; // Reuse error code
return;
}
bool is_msg_recved = false, is_ulist_recved = false;
struct sockaddr_in src_addr;
auto addr_len = sizeof(src_addr);
size_t offset = 0;
unsigned long long unsign_len = 0, aes_dec_len = 0;
auto raw_beg = buff.recv_raw_buffer.data();
auto aes_beg = buff.recv_aes_buffer.data();
auto sid = s.get_server_sid();
auto cif = s.get_cinfo_hash_bytes();
std::array<uint8_t, crypto_aead_aes256gcm_NPUBBYTES> aes_nonce;
std::array<uint8_t, SID_BYTES> recved_sid;
std::array<uint8_t, CIF_BYTES> recved_cif;
std::array<uint8_t, HEARTBEAT_BYTES> hb_pack;
std::array<uint8_t, GOODBYE_BYTES> gby_pack;
// Notify UI of authentication
lichat::user_info user_info;
user_info.email = u.get_uemail();
user_info.username = u.get_uname();
ui->on_user_authenticated(user_info);
while (core_running) {
// Check for heartbeat timeout
if (heartbeat_timeout) {
ui->on_heartbeat_timeout();
core_err = C_HEARTBEAT_TIME_OUT;
return;
}
// Check for disconnect request from UI
if (ui->is_disconnect_requested()) {
ui->on_status_changed(client_exit_msg);
if (!pack_goodbye(s.get_cinfo_hash_bytes(),
client_k.get_sign_sk(), gby_pack)) {
core_err = C_GOODBYE_SENT_ERR;
return;
}
if (simple_send_stc(fd, s, gby_pack.data(),
gby_pack.size()) < 0) {
core_err = C_HEARTBEAT_SENT_ERR;
return;
}
ui->on_status_changed(signed_out_msg);
ui->clear_disconnect_request();
ui->on_user_disconnected();
return;
}
// Check for user input
if (ui->has_input()) {
std::string input = ui->get_input();
if (input == ":q!") {
ui->request_disconnect();
continue;
} else if (!input.empty()) {
// Format message with recipient prefix
// For now, default to broadcast (no prefix)
// Later, UI can specify recipients via a separate method
std::string formatted_msg = input; // Default: broadcast
// Send message with reliability (sequence number + ACK)
uint16_t seq = s.get_next_seq();
// Prepend sequence number to message: seq (2 bytes) + message
std::vector<uint8_t> msg_with_seq(SEQ_BYTES + formatted_msg.size());
msg_with_seq[0] = static_cast<uint8_t>((seq >> 8) & 0xFF); // High byte
msg_with_seq[1] = static_cast<uint8_t>(seq & 0xFF); // Low byte
std::copy(formatted_msg.begin(), formatted_msg.end(),
msg_with_seq.begin() + SEQ_BYTES);
// Send message and track for ACK
ssize_t send_result = simple_secure_send_stc(fd, 0x10, s, buff,
msg_with_seq.data(), msg_with_seq.size());
if (send_result >= 0) {
// Store encrypted message for retry if needed
std::vector<uint8_t> encrypted_msg(
buff.send_buffer.begin(),
buff.send_buffer.begin() + buff.send_bytes);
std::lock_guard<std::mutex> lock(pending_mutex);
pending_messages.emplace(seq,
pending_message(seq, lc_utils::now_time(), encrypted_msg));
}
}
}
// Check the long message receivers / senders.
auto now = lc_utils::now_time();
if (now - last_lmsg_check.load() >= LMSG_ALIVE_SECS) {
lm_r.check_all(now);
lm_s.check_all(now);
}
auto bytes = recvfrom(fd, buff.recv_raw_buffer.data(),
buff.recv_raw_buffer.size(), 0,
(struct sockaddr *)(&src_addr), (socklen_t *)&addr_len);
errno = 0;
is_msg_recved = false;
if (bytes < 0) {
// Handling sending workloads and heartbeat
if (!errno || errno == EWOULDBLOCK || errno == EAGAIN) {
if (heartbeat_req) {
if (!pack_heartbeat(s.get_cinfo_hash_bytes(),
client_k.get_sign_sk(), hb_pack)) {
core_err = C_HEARTBEAT_SENT_ERR;
return;
}
if (simple_send_stc(fd, s, hb_pack.data(),
hb_pack.size()) < 0) {
core_err = C_HEARTBEAT_SENT_ERR;
return;
}
last_heartbeat_sent.store(lc_utils::now_time());
heartbeat_req.store(false);
}
continue;
}
core_err = C_SOCKET_RECV_ERR;
return;
}
if (bytes < CLIENT_RECV_MIN_BYTES)
continue;
offset = 0;
auto header = buff.recv_raw_buffer[0];
if (header != 0x11 && header != 0x10 &&
header != 0x1F && header != 0x13 && header != 0x17)
continue;
// Handle ACK message (0x17) - encrypted ACK from server
if (header == 0x17) {
// ACK format: 0x17 + encrypted(seq_num, 2 bytes)
// Same format as 0x10: header + cif + nonce + encrypted(sid + seq_num)
ssize_t expected_min = 1 + CIF_BYTES +
crypto_aead_aes256gcm_NPUBBYTES + SID_BYTES + SEQ_BYTES +
crypto_aead_aes256gcm_ABYTES;
if (bytes < expected_min)
continue;
// Decrypt using same logic as 0x10
size_t dec_offset = 1; // Skip header
std::array<uint8_t, CIF_BYTES> recv_cif_bytes;
std::copy(raw_beg + dec_offset, raw_beg + dec_offset + CIF_BYTES,
recv_cif_bytes.begin());
dec_offset += CIF_BYTES;
if (std::memcmp(recv_cif_bytes.data(), cif.data(), CIF_BYTES) != 0)
continue; // Not for us
std::array<uint8_t, crypto_aead_aes256gcm_NPUBBYTES> recv_nonce;
std::copy(raw_beg + dec_offset,
raw_beg + dec_offset + crypto_aead_aes256gcm_NPUBBYTES,
recv_nonce.begin());
dec_offset += crypto_aead_aes256gcm_NPUBBYTES;
size_t encrypted_len = bytes - dec_offset;
unsigned long long dec_len = 0;
auto aes_key = s.get_aes256gcm_key();
if (crypto_aead_aes256gcm_decrypt(
buff.recv_aes_buffer.data(), &dec_len,
nullptr,
raw_beg + dec_offset, encrypted_len,
nullptr, 0,
recv_nonce.data(), aes_key.data()) != 0)
continue; // Decryption failed
buff.recv_aes_bytes = dec_len;
// Verify SID
if (dec_len < SID_BYTES + SEQ_BYTES)
continue;
if (std::memcmp(buff.recv_aes_buffer.data(), sid.data(), SID_BYTES) != 0)
continue;
// Extract sequence number
uint16_t acked_seq = (buff.recv_aes_buffer[SID_BYTES] << 8) |
buff.recv_aes_buffer[SID_BYTES + 1];
// Remove from pending messages (passed as parameter)
std::lock_guard<std::mutex> lock(pending_mutex);
pending_messages.erase(acked_seq);
continue;
}
if (header == 0x11 || header == 0x13) {
++ offset;
if (crypto_sign_open(nullptr, &unsign_len, raw_beg + offset,
bytes - 1, server_pk.get_server_spk().data()) != 0)
continue;
offset += crypto_sign_BYTES;
// Handle the 0x11 (short messages with signature but not cif)
if (header == 0x11) {
std::string msg_str(
reinterpret_cast<const char *>(raw_beg + offset),
bytes - offset);
msg_vec.push_back(msg_str);
is_msg_recved = true;
}
// Handle the 0x13 (long messages with signature and cif)
else {
ssize_t min_bytes = 1 + CIF_BYTES + MSG_ID_BYTES + 2;
if (bytes < min_bytes)
continue;
if (std::memcmp(raw_beg + offset, cif.data(), cif.size()) != 0)
continue;
offset += cif.size();
std::vector<uint8_t> chunk(bytes - offset);
std::copy(raw_beg + offset, raw_beg + bytes, chunk.begin());
auto msg_id = lmsg_receiver::get_chunk_msg_id(chunk);
auto msg_id_bytes = lc_utils::u64_to_bytes(msg_id);
lm_r.add_lmsg(chunk);
auto receiver = lm_r.get_receiver(msg_id);
if (!receiver) {
ui->on_error(lmsg_recv_failed);
continue;
}
if (receiver->recv_timeout()) {
ui->on_error(lmsg_recv_failed);
continue;
}
if (!receiver->recv_done()) {
if (!receiver->last_chunk_received())
continue;
receiver->check_missing_chunks();
if (!receiver->recv_done()) {
auto missed = receiver->missing_chunks_to_bytes();
if (1 + crypto_sign_BYTES + CIF_BYTES +
missed.size() > BUFF_BYTES)
continue;