-
Notifications
You must be signed in to change notification settings - Fork 0
/
bindy.cpp
2005 lines (1662 loc) · 67.8 KB
/
bindy.cpp
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
/// @file
/// @mainpage Bindy API Reference
///
/// @section intro_sec Introduction
/// Bindy synopsis
///
#include <algorithm>
#include <cassert>
#include <cryptopp/cryptlib.h>
#include <cryptopp/gcm.h>
#include <cryptopp/hex.h>
#include <cryptopp/osrng.h>
#include <cryptopp/socketft.h>
#include <cstring>
#include <fstream>
#include <sstream>
#include <zf_log.h>
#include "bindy-static.h"
#include "bindy-config.h"
#include "bindy_log_helper.h"
#include "sqlite/sqlite3.h"
#include "tinythread.h"
#include "utils.h"
#include "sole/sole.hpp"
using CryptoPP::StringSink;
using CryptoPP::StringSource;
using CryptoPP::ArraySink;
using CryptoPP::AES;
using CryptoPP::Socket;
#undef min
#undef max
// conditional includes for different platforms
#if defined(WIN32) || defined(WIN64)
#include <mstcpip.h>
#endif
// ------------------------------------------------------------------------------------
// Implementation
namespace bindy {
static tthread::mutex *stdout_mutex = new tthread::mutex();
static user_t predefined_users[4] = { {
{ { 116, 101, 115, 116, 45, 117, 115, 101, 114, 45, 48, 49, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
"test-user-01", { { 95, 130, 29, 163, 182, 24, 32, 62, 32, 121, 37, 138, 164, 165, 117, 178 } }, 2 },
{ { { 116, 101, 115, 116, 45, 117, 115, 101, 114, 45, 48, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
"test-user-02", { { 116, 151, 7, 58, 45, 200, 115, 165, 199, 104, 143, 162, 208, 160, 23, 119 } }, 2 },
{ { { 116, 101, 115, 116, 45, 117, 115, 101, 114, 45, 48, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
"test-user-03", { { 151, 187, 241, 12, 218, 139, 248, 123, 217, 138, 135, 86, 154, 186, 54, 136 } }, 2 },
{ { {114, 111, 111, 116, 45, 117, 115, 101, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
"root-user", { { 32, 87, 139, 134, 41, 227, 202, 19, 235, 29, 48, 119, 189, 61, 211, 135 } }, 1 }
};
bindy_log_helper log_helper; // log-helper initialization
/* * new debug macro
*/
// to satisfy multiple variants of Bindy using
#define DEBUG(text) {if (ZF_LOG_ON_DEBUG) {stdout_mutex->lock(); log_helper << text; ZF_LOGD("%s", log_helper.buffer()); log_helper.clear(); stdout_mutex->unlock();}}
/*! TCP KeepAlive option: Keepalive probe send interval in seconds. */
#define KEEPINTVL 5
/*! TCP KeepAlive option: Socket idle time before keepalive probes are sent, in seconds. */
#define KEEPIDLE 10
/*! TCP KeepAlive option: Keepalive probe count. */
#define KEEPCNT 3
/*!
* Crossplatform sleep.
* @param[in] ms Sleep time in msec.
*/
void sleep_ms(size_t ms) {
#if defined(WIN32) || defined(WIN64)
Sleep((DWORD)ms);
#else
usleep(1000 * ms);
#endif
}
/*! Acknowledgement identifier */
typedef sole::uuid ack_id_t;
/*!
* Header type for the Message class. Contains information about message contents.
*/
typedef struct {
/*! Packet length in bytes, excluding the header size. */
uint32_t data_length;
/*! Packet type. */
link_pkt packet_type;
/*! Reserved for future use. */
uint8_t reserved1;
/*! Reserved for future use. */
uint8_t reserved2;
/*! Reserved for future use. */
uint8_t reserved3;
} header_t;
/*! A helper type which contains a single message (type + content) to be encrypted and sent over the TCP socket. */
struct Message {
link_pkt type;
std::vector<uint8_t> content;
};
/*! Acknowldegement callback */
typedef std::function<void(const std::vector<uint8_t>)> ack_callback_t;
/*! Lock guard short type definition. */
typedef tthread::lock_guard<tthread::mutex> tlock;
/* Broadcast data struct definition */
typedef struct bcast_data_t {
std::vector<uint8_t> data;
std::string addr;
} bcast_data_t;
/*! This function takes a pointer to an array of chars and its size and returns its representation in hex as a string. */
std::string hex_encode(const char *s, size_t size) {
std::string encoded;
StringSource(reinterpret_cast<const uint8_t *>(s), size, true,
new CryptoPP::HexEncoder(
new StringSink(encoded), true, 2, " "
) // HexEncoder
); // StringSource
return encoded;
}
std::string hex_encode(std::string s) {
return hex_encode(s.c_str(), s.size());
}
std::string hex_encode(std::vector<uint8_t> v) {
return hex_encode((const char *) &v[0], v.size());
}
/*! Helper function for CryptoPP encode/decode functions which require an std::string as parameter. Copies characters into the string. */
void string_set(std::string *str, char *buf, int size) {
str->resize(size);
for(int i = 0; i < size; i++) {
str->at(i) = buf[i];
}
}
void string_set(std::string *str, uint8_t *buf, int size) {
string_set(str, reinterpret_cast<char *>(buf), size);
}
class BindyState {
public:
void (*m_datasink)(conn_id_t conn_id, std::vector<uint8_t> data);
void (*m_discnotify)(conn_id_t conn_id);
// std::map<std::string, aes_key_t> login_key_map;
tthread::thread *main_thread;
tthread::thread *bcast_thread;
std::map<conn_id_t, SuperConnection *> connections;
tthread::mutex mutex; // global mutex
tthread::mutex interlock_mutex; // mutex to sync betweern listening TCP and UDP threads
std::string nodename; // name of this node
// user_t master; // root key
sqlite3 *sql_conn;
BindyState() : main_thread(nullptr), bcast_thread(nullptr), sql_conn(nullptr) {}
~BindyState() {}
BindyState(const BindyState &) = delete;
BindyState &operator=(const BindyState &) = delete;
};
class Countable {
public:
explicit Countable(conn_id_t id) : conn_id(id) {
tlock lock(global_mutex);
if(map.count(conn_id) == 0) {
map[conn_id] = 0;
}
++map[conn_id];
mutexes[conn_id] = new tthread::mutex();
}
Countable(Countable const &) = delete;
Countable &operator=(Countable const &) = delete;
virtual ~Countable() {
tlock lock(global_mutex);
if(map.count(conn_id) == 1 && map[conn_id] > 1) {
--map[conn_id];
} else {
map.erase(conn_id);
delete mutexes[conn_id];
mutexes.erase(conn_id);
}
}
unsigned int count() {
tlock lock(global_mutex);
return map[conn_id];
}
tthread::mutex * mutex() {
tlock lock(global_mutex);
return mutexes[conn_id];
}
private:
conn_id_t conn_id;
static std::map<conn_id_t, unsigned int> map;
static std::map<conn_id_t, tthread::mutex *> mutexes;
static tthread::mutex global_mutex;
};
std::map<conn_id_t, unsigned int> Countable::map;
std::map<conn_id_t, tthread::mutex *> Countable::mutexes;
tthread::mutex Countable::global_mutex;
int listen_conn_id = conn_id_invalid; // used in tcp- and udp-listen thread functions
bool set_socket_broadcast(Socket *s) {
bool ok = true;
#ifdef __linux__
int optval = 1;
ok = (0 == setsockopt(*s, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)));
#endif
return ok;
}
bool set_socket_reuseaddr(Socket *s) {
bool ok = true;
#ifdef __linux__
int optval = 1;
ok = (0 == setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)));
#endif
return ok;
}
/*!
* Class which contains information about a single connection.
*/
class Connection : public Countable {
public:
Connection(Bindy *bindy, Socket *_socket, conn_id_t conn_id, bool inits);
~Connection();
explicit Connection(Connection *other);
/*!
* Encrypts and sends a single message into this connection.
*/
void send_packet(const link_pkt type, const std::vector<uint8_t> content);
/*!
* Encrypts and sends a single message into this connection, then waits for acknowledgement message.
*/
void send_packet_ack(const link_pkt type, std::vector<uint8_t> &content, ack_callback_t &success, ack_callback_t &failure);
/*!
* Decrypts and returns a single packet read from the socket of this connection.
*/
Message recv_packet();
/*!
* Returns buffer size of this connection.
*/
unsigned int buffer_size();
/*!
* Reads up to "size" bytes of data from this connection buffer and puts them to the memory pointed to by "p". Returns amount of bytes read.
*/
int buffer_read(uint8_t *p, int size);
/*!
* Writes data into the buffer of this connection to be sent to the other party.
*/
void buffer_write(std::vector<uint8_t> data);
/*!
* Sends callback data from thread to the Bindy class through the Connection class intermediary.
*/
void callback_data(std::vector<uint8_t> data);
/*!
* Helper method to establish connection.
*/
void initial_exchange(bcast_data_t bcast_data);
private:
Connection(const Connection &other);
Connection &operator=(const Connection &other);
Bindy *bindy;
Socket *sock;
CryptoPP::SecByteBlock *send_key;
CryptoPP::SecByteBlock *recv_key;
CryptoPP::SecByteBlock *send_iv;
CryptoPP::SecByteBlock *recv_iv;
tthread::mutex *send_mutex;
tthread::mutex *recv_mutex;
tthread::mutex *ack_mutex;
std::deque<uint8_t> *buffer;
conn_id_t conn_id;
bool inits_connect;
std::map<ack_id_t, std::pair<ack_callback_t, ack_callback_t>> *ack_callbacks;
void disconnect_self();
in_addr get_ip();
friend class Bindy;
friend void socket_thread_function(void *arg);
};
void socket_thread_function(void *arg);
class SuperConnection : public Connection {
public:
SuperConnection(Bindy *_bindy, Socket *_socket, conn_id_t conn_id, bool _inits_connect, bcast_data_t bcast_data);
};
SuperConnection::SuperConnection(
Bindy *_bindy,
Socket *_socket,
conn_id_t conn_id,
bool _inits_connect,
bcast_data_t bcast_data
):
Connection(_bindy, _socket, conn_id, _inits_connect)
{
initial_exchange(bcast_data);
std::thread socket_thread(socket_thread_function, this);
socket_thread.detach();
}
Connection::Connection(Bindy *_bindy, Socket *_socket, conn_id_t conn_id, bool _inits_connect) :
Countable(conn_id) {
if(count() == 1) {
this->inits_connect = _inits_connect;
this->bindy = _bindy;
this->sock = _socket;
this->conn_id = conn_id;
this->send_key = new CryptoPP::SecByteBlock(AES::DEFAULT_KEYLENGTH);
this->recv_key = new CryptoPP::SecByteBlock(AES::DEFAULT_KEYLENGTH);
this->send_iv = new CryptoPP::SecByteBlock(AES::BLOCKSIZE);
this->recv_iv = new CryptoPP::SecByteBlock(AES::BLOCKSIZE);
this->send_mutex = new tthread::mutex();
this->recv_mutex = new tthread::mutex();
this->ack_mutex = new tthread::mutex();
this->buffer = new std::deque<uint8_t>();
this->ack_callbacks = new std::map<ack_id_t, std::pair<ack_callback_t, ack_callback_t>>();
}
}
Connection::Connection(Connection *other) :
Countable(other->conn_id) {
if(count() > 1) {
this->inits_connect = other->inits_connect;
this->bindy = other->bindy;
this->sock = other->sock;
this->conn_id = other->conn_id;
this->send_key = other->send_key;
this->recv_key = other->recv_key;
this->send_iv = other->send_iv;
this->recv_iv = other->recv_iv;
this->send_mutex = other->send_mutex;
this->recv_mutex = other->recv_mutex;
this->ack_mutex = other->ack_mutex;
this->buffer = other->buffer;
this->ack_callbacks = other->ack_callbacks;
}
}
Connection::~Connection() {
tlock lock(*mutex());
if(count() == 2) {
int how;
#ifdef _MSC_VER
how = SD_BOTH;
#else
how = SHUT_RDWR;
#endif
if(sock) {
try {
sock->ShutDown(how);
}
#if (ZF_LOG_ENABLED_DEBUG)
catch(CryptoPP::Socket::Err &e) {
DEBUG("Socket shutdown failed for reason " << e.what() <<
". Likely the other side closed connection first.");
}
#else
catch(...) {
}
#endif
}
}
else if(count() == 1) {
if(sock) {
sock->CloseSocket();
delete sock;
}
delete buffer;
delete send_key;
delete recv_key;
delete send_iv;
delete recv_iv;
delete send_mutex;
delete recv_mutex;
delete ack_mutex;
delete ack_callbacks;
}
}
void Connection::send_packet_ack(const link_pkt type, std::vector<uint8_t> &content, ack_callback_t &success, ack_callback_t &failure) {
ack_id_t request_id = sole::uuid1();
unsigned long orig_size = (unsigned long)content.size();
content.resize(content.size() + sizeof(ack_id_t));
std::memcpy(content.data() + orig_size, &request_id, sizeof(ack_id_t));
ack_mutex->lock();
ack_callbacks->insert(
std::make_pair(request_id, std::make_pair(success, failure))
);
ack_mutex->unlock();
send_packet(type, content);
}
// Sends "message" data into the connection. Modifies connection IV in preparation for the next packet.
void Connection::send_packet(link_pkt type, const std::vector<uint8_t> content) {
tlock lock(*send_mutex);
header_t header{static_cast<uint32_t>(content.size()), type, 0, 0, 0};
std::string cipher_header, cipher_body, cipher_all,
plain_header(reinterpret_cast<const char *>(&header), sizeof(header));
CryptoPP::GCM<AES>::Encryption e;
try {
e.SetKeyWithIV(*send_key, send_key->size(), *send_iv, send_iv->size());
StringSource(plain_header, true,
new CryptoPP::AuthenticatedEncryptionFilter(e,
new StringSink(cipher_header)
) // StreamTransformationFilter
); // StringSource
send_iv->Assign(reinterpret_cast<const uint8_t *>(cipher_header.substr(cipher_header.length() - AES::BLOCKSIZE,
AES::BLOCKSIZE).data()), AES::BLOCKSIZE);
e.SetKeyWithIV(*send_key, send_key->size(), *send_iv, send_iv->size());
StringSource(content.data(), header.data_length, true,
new CryptoPP::AuthenticatedEncryptionFilter(e,
new StringSink(cipher_body)
) // StreamTransformationFilter
); // StringSource
send_iv->Assign(reinterpret_cast<const uint8_t *>(cipher_body.substr(cipher_body.length() - AES::BLOCKSIZE,
AES::BLOCKSIZE).data()), AES::BLOCKSIZE);
} catch(CryptoPP::Exception &e) {
std::cerr << "Caught exception (encryption): " << e.what() << std::endl;
throw e;
}
cipher_all.append(cipher_header);
cipher_all.append(cipher_body);
size_t to_send = cipher_all.length();
try {
#if (ZF_LOG_ENABLED_DEBUG)
int sent = sock->Send(reinterpret_cast<const uint8_t *>(cipher_all.data()), to_send, 0);
DEBUG("to send (w/headers): " << to_send << "; sent = " << sent);
#else
sock->Send(reinterpret_cast<const uint8_t *>(cipher_all.data()), to_send, 0);
#endif
} catch(CryptoPP::Exception &e) {
std::cerr << "Caught exception (net): " << e.what() << " Thread Id: " << std::this_thread::get_id() << std::endl;
throw e;
}
}
// Receives message from connection. Modifies connection IV in preparation for the next packet.
Message Connection::recv_packet() {
tlock lock(*recv_mutex);
int get, rcv;
CryptoPP::GCM<AES>::Decryption d;
// header data recv
const int head_enc_size = (sizeof(header_t)) + AES::BLOCKSIZE;
get = 0;
rcv = 0;
unsigned char buf_head[head_enc_size];
memset(buf_head, 0, head_enc_size);
do {
get = sock->Receive(&buf_head[rcv], head_enc_size - rcv, 0);
if(get == 0) { // The other side closed the connection
throw std::runtime_error("Error receiving packet.");
}
rcv += get;
} while(head_enc_size - rcv > 0);
// header decrypt
std::string cipher_head, recovered_head;
string_set(&cipher_head, buf_head, head_enc_size);
d.SetKeyWithIV(*recv_key, recv_key->size(), *recv_iv, recv_iv->size());
try {
StringSource s(cipher_head, true,
new CryptoPP::AuthenticatedDecryptionFilter(d,
new StringSink(recovered_head)
) // StreamTransformationFilter
); // StringSource
}
catch(const CryptoPP::Exception &e) {
std::cerr << "Caught exception (decryption): " << e.what() << std::endl;
throw e;
}
header_t header;
std::memcpy(&header, recovered_head.c_str(), (sizeof(header_t)));
// body data recv
int body_enc_size = header.data_length + AES::BLOCKSIZE;
get = 0;
rcv = 0;
uint8_t *p_body = new uint8_t[header.data_length + CryptoPP::AES::BLOCKSIZE];
do {
get = sock->Receive(p_body + rcv, body_enc_size - rcv, 0);
if(get == 0) { // The other side closed the connection
delete[] p_body;
throw std::runtime_error("Error receiving packet.");
}
rcv += get;
} while(body_enc_size - rcv > 0);
// body decrypt
std::string cipher_body;
std::vector<uint8_t> recovered_body(header.data_length);
string_set(&cipher_body, p_body, rcv);
delete[] p_body;
recv_iv->Assign(reinterpret_cast<const uint8_t *>(cipher_head.substr(cipher_head.length() - AES::BLOCKSIZE,
AES::BLOCKSIZE).data()), AES::BLOCKSIZE);
d.SetKeyWithIV(*recv_key, recv_key->size(), *recv_iv, recv_iv->size());
try {
StringSource s(cipher_body, true,
new CryptoPP::AuthenticatedDecryptionFilter(d,
new ArraySink(recovered_body.data(),
header.data_length)
) // StreamTransformationFilter
); // StringSource
}
catch(const CryptoPP::Exception &e) {
std::cerr << "Caught exception (decryption): " << e.what() << std::endl;
throw e;
}
recv_iv->Assign(reinterpret_cast<const uint8_t *>(cipher_body.substr(cipher_body.length() - AES::BLOCKSIZE,
AES::BLOCKSIZE).data()), AES::BLOCKSIZE);
assert(header.data_length == recovered_body.size());
// Message message(header, recovered_body.c_str());
return {header.packet_type, std::move(recovered_body)};
}
unsigned int Connection::buffer_size() {
return (unsigned int)buffer->size();
}
int Connection::buffer_read(uint8_t *p, int size) {
int i = 0;
while(i < size && !buffer->empty()) {
*(p + i) = buffer->front();
buffer->pop_front();
i++;
}
return i;
}
void Connection::buffer_write(std::vector<uint8_t> data) {
for(unsigned int i = 0; i < data.size(); i++) {
buffer->push_back(data[i]);
}
}
void Connection::callback_data(std::vector<uint8_t> data) {
bindy->callback_data(this->conn_id, data);
}
user_vector_t extract_from_old_config(std::string filename) {
std::ifstream is (filename.data(), std::ifstream::binary);
if(is.good()) {
is.seekg (0, is.end);
//std::streampos length = is.tellg();
is.seekg (0, is.beg);
} else {
throw std::runtime_error("bad binary config file");
}
user_vector_t users;
int count = 0;
while(true) {
user_t user;
memset(&user.uid, 0, sizeof(user_id_t));
is.read(reinterpret_cast<char *>(&user.uid), AUTH_DATA_LENGTH);
user.name = std::string(reinterpret_cast<char *>(&user.uid));
is.read(reinterpret_cast<char *>(&user.key), AES_KEY_LENGTH);
user.role = static_cast<role_id_t>(count == 0 ? 1 : 2);
if(is.good()) {
users.push_back(std::move(user));
} else {
break;
}
count++;
}
is.close();
return users;
}
void Connection::initial_exchange(bcast_data_t bcast_data) {
bool use_bcast = (sock == nullptr);
if(!inits_connect) { // this party accepts the connection
// Initial exchange
uint8_t auth_data[AUTH_DATA_LENGTH];
memset(auth_data, 0, AUTH_DATA_LENGTH);
if(use_bcast) {
std::memcpy(auth_data, reinterpret_cast<const void *>(&bcast_data.data.at(0)), AUTH_DATA_LENGTH);
}
else {
sock->Receive(auth_data, AUTH_DATA_LENGTH, 0);
}
// Authorization happens here
user_id_t uid;
std::memcpy(&uid, auth_data, sizeof(user_id_t));
aes_key_t key = bindy->key_by_uid(uid);
send_key->Assign(key.bytes, AES_KEY_LENGTH);
recv_key->Assign(key.bytes, AES_KEY_LENGTH);
if(use_bcast) {
std::memcpy(recv_iv->BytePtr(), reinterpret_cast<const void *>(&bcast_data.data.at(AUTH_DATA_LENGTH)),
AES_KEY_LENGTH);
}
else {
sock->Receive(recv_iv->BytePtr(), AES_KEY_LENGTH, 0);
}
send_iv->Assign(*recv_iv);
// The tcp socket is still null, connect it first
if(use_bcast) {
sock = new Socket();
sock->Create(SOCK_STREAM);
DEBUG("Connecting to " << bcast_data.addr);
if(!sock->Connect(bcast_data.addr.c_str(), bindy->port())) {
DEBUG("Connect fail");
}
else {
DEBUG("Connect ok");
}
}
auto m_recv1 = recv_packet();
// remote_nodename = m_recv1.second();
std::string nodename = bindy->get_nodename();
send_packet(link_pkt::PacketInitReply, {nodename.begin(), nodename.end()});
auto m_recv2 = recv_packet();
send_packet(link_pkt::PacketLinkInfo, {});
} else { // this party initiates the connection
CryptoPP::AutoSeededRandomPool prng;
prng.GenerateBlock(*send_iv, send_iv->size());
recv_iv->Assign(*send_iv);
// Authorize ourselves here
user_t master = bindy->get_master();
send_key->Assign(master.key.bytes, AES_KEY_LENGTH);
recv_key->Assign(master.key.bytes, AES_KEY_LENGTH);
uint8_t auth_data[AUTH_DATA_LENGTH];
memset(auth_data, 0, AUTH_DATA_LENGTH);
// std::string mname = bindy->get_master_login_username();
std::memcpy(auth_data, &master.uid, sizeof(user_id_t));
if(use_bcast) {
uint8_t bc_packet[AUTH_DATA_LENGTH + AES_KEY_LENGTH];
std::memcpy(bc_packet, auth_data, AUTH_DATA_LENGTH);
std::memcpy(bc_packet + AUTH_DATA_LENGTH, send_iv->BytePtr(), AES_KEY_LENGTH);
// accept incoming connection(s?) from server(s?) who will hear our broadcast and want to talk back
Socket listen_sock;
listen_sock.Create(SOCK_STREAM);
set_socket_reuseaddr(&listen_sock);
listen_sock.Bind(bindy->port_, NULL);
listen_sock.Listen();
// send a broadcast itself
Socket bcast_sock;
bcast_sock.Create(SOCK_DGRAM);
set_socket_broadcast(&bcast_sock);
std::string addr("255.255.255.255"); // todo check: does this properly route on lin & win?
if(!bcast_sock.Connect(addr.c_str(), bindy->port_)) {
throw std::runtime_error("Error establishing connection.");
}
bcast_sock.Send(bc_packet, sizeof(bc_packet), 0);
bcast_sock.CloseSocket();
// wait for reply
timeval t;
t.tv_sec = 5;
t.tv_usec = 0;
if(listen_sock.ReceiveReady(&t)) {
sock = new Socket();
sock->Create(SOCK_STREAM);
listen_sock.Accept(*sock); // The sock is now connected, use it to continue exchange
}
else { // we timed out and no one wanted to talk to us
throw std::runtime_error("Timeout waiting for broadcast reply.");
}
listen_sock.CloseSocket();
}
else {
sock->Send(auth_data, AUTH_DATA_LENGTH, 0);
sock->Send((const uint8_t *) (send_iv->BytePtr()), AES_KEY_LENGTH, 0);
}
std::string nodename = bindy->get_nodename();
send_packet(link_pkt::PacketInitRequest, {nodename.begin(), nodename.end()});
auto m_recv1 = recv_packet();
// remote_nodename = m_recv1.data_string();
send_packet(link_pkt::PacketLinkInfo, {});
auto m_recv2 = recv_packet();
}
}
in_addr Connection::get_ip() {
in_addr ip;
sockaddr psa;
CryptoPP::socklen_t psaLen = sizeof(psa);
sock->GetPeerName(&psa, &psaLen);
if(psa.sa_family == AF_INET)
ip = ((sockaddr_in *) &psa)->sin_addr;
else
ip.s_addr = INADDR_NONE;
return ip;
}
void Connection::disconnect_self() {
bindy->disconnect(conn_id);
}
Message ack_failure_from(const std::string &text) {
return Message{link_pkt::PacketAckFailure, {text.begin(), text.end()}};
}
Message on_add_user_remote(conn_id_t, Bindy &bindy, std::vector<uint8_t> &request) {
if(request.size() != USERNAME_LENGTH + AES_KEY_LENGTH) {
return ack_failure_from("incorrect message length");
}
uint8_t *request_cursor = request.data();
std::string username;
aes_key_t key;
// we assume that names are either null-terminated or occupy whole USERNAME_LENGTH
unsigned int name_length = 0;
while(request_cursor[name_length] != '\0' && name_length < USERNAME_LENGTH) {
name_length++;
}
username = std::string(reinterpret_cast<const char *>(request_cursor), name_length);
request_cursor += USERNAME_LENGTH;
std::memcpy(key.bytes, request_cursor, AES_KEY_LENGTH);
request_cursor += AES_KEY_LENGTH;
try {
user_id_t uid = bindy.add_user_local(username, key);
std::vector<uint8_t> reply;
reply.resize(sizeof(user_id_t));
uint8_t *reply_cursor = reply.data();
std::memcpy(reply_cursor, &uid, sizeof(user_id_t));
reply_cursor += sizeof(user_id_t);
return Message{link_pkt::PacketAckSuccess, std::move(reply)};
} catch(std::runtime_error &e) {
return ack_failure_from(e.what());
} catch(...) {
return ack_failure_from("unknow generic error");
}
}
Message on_del_user_remote(conn_id_t, Bindy &bindy, std::vector<uint8_t> &request) {
if(request.size() != sizeof(user_id_t))
return ack_failure_from("incorrect message length");
uint8_t *request_cursor = request.data();
user_id_t uid;
std::memcpy(&uid, request_cursor, sizeof(user_id_t));
request_cursor += sizeof(user_id_t);
try {
bindy.delete_user_local(uid);
return Message{link_pkt::PacketAckSuccess, {}};
} catch(std::runtime_error &e) {
return ack_failure_from(e.what());
} catch(...) {
return ack_failure_from("unknow generic error");
}
}
Message on_change_key_remote(conn_id_t, Bindy &bindy, std::vector<uint8_t> &request) {
if(request.size() != sizeof(user_id_t) + AES_KEY_LENGTH)
return ack_failure_from("incorrect message length");
uint8_t *request_cursor = request.data();
user_id_t uid;
aes_key_t key;
std::memcpy(&uid, request_cursor, sizeof(user_id_t));
request_cursor += sizeof(user_id_t);
std::memcpy(key.bytes, request_cursor, AES_KEY_LENGTH);
request_cursor += AES_KEY_LENGTH;
try {
bindy.change_key_local(uid, key);
return Message{link_pkt::PacketAckSuccess, {}};
} catch(std::runtime_error &e) {
return ack_failure_from(e.what());
} catch(...) {
return ack_failure_from("unknow generic error");
}
}
Message on_list_users_remote(conn_id_t, Bindy &bindy, std::vector<uint8_t> &request) {
if(request.size() != 0) {
return ack_failure_from("incorrect message length");
}
try {
user_vector_t users = bindy.list_users_local();
size_t user_size = sizeof(user_id_t) + USERNAME_LENGTH + AES_KEY_LENGTH + sizeof(role_id_t);
std::vector<uint8_t> reply(user_size * users.size());
uint8_t *reply_cursor = reply.data();
for(unsigned int i = 0; i < users.size(); i++) {
user_t &user = users[i];
std::memcpy(reply_cursor, &user.uid, sizeof(user_id_t));
reply_cursor += sizeof(user_id_t);
std::memcpy(reply_cursor, user.name.data(), USERNAME_LENGTH);
reply_cursor += USERNAME_LENGTH;
std::memcpy(reply_cursor, &user.key, AES_KEY_LENGTH);
reply_cursor += AES_KEY_LENGTH;
std::memcpy(reply_cursor, &user.role, sizeof(role_id_t));
reply_cursor += sizeof(role_id_t);
}
return Message{link_pkt::PacketAckSuccess, std::move(reply)};
} catch(std::runtime_error &e) {
return ack_failure_from(e.what());
} catch(...) {
return ack_failure_from("unknow generic error");
}
}
Message on_set_master_remote(conn_id_t, Bindy &bindy, std::vector<uint8_t> &request) {
if(request.size() != sizeof(user_id_t))
return ack_failure_from("incorrect message length");
uint8_t *request_cursor = request.data();
user_id_t uid;
std::memcpy(&uid, request_cursor, sizeof(user_id_t));
request_cursor += sizeof(user_id_t);
try {
bindy.set_master_local(uid);
return Message{link_pkt::PacketAckSuccess, {}};
} catch(std::runtime_error &e) {
return ack_failure_from(e.what());
} catch(...) {
return ack_failure_from("unknow generic error");
}
}
void socket_thread_function(void *arg) {
Connection *conn = nullptr;
try {
conn = new Connection((Connection *) arg);
while(true) {
Message request(conn->recv_packet());
if(request.type == link_pkt::PacketTermRequest) {
// FIXME: cleaner solution for connection termination?
throw std::runtime_error("Connection close request received");
} else if(request.type == link_pkt::PacketData) {
conn->callback_data(request.content);
// Internal administration protocol handling
} else {
// we assume that last bytes are message uid
ack_id_t msg_id;
unsigned long orig_request_size = (unsigned long)(request.content.size() - sizeof(ack_id_t));
std::memcpy(&msg_id, request.content.data() + orig_request_size, sizeof(ack_id_t));
request.content.resize(orig_request_size);
if(request.type == link_pkt::PacketAckSuccess || request.type == link_pkt::PacketAckFailure) {
Message &reply = request;
// don't execute callback under mutex
conn->ack_mutex->lock();
auto handlers = std::move(conn->ack_callbacks->at(msg_id));
conn->ack_callbacks->erase(msg_id);
conn->ack_mutex->unlock();
request.type == link_pkt::PacketAckSuccess ? handlers.first(reply.content) : handlers.second(reply.content);
} else {
// link_pkt reply_type;
Message reply;
if(request.type == link_pkt::PacketAddUser) {
reply = on_add_user_remote(conn->conn_id, *conn->bindy, request.content);
} else if(request.type == link_pkt::PacketDelUser) {
reply = on_del_user_remote(conn->conn_id, *conn->bindy, request.content);
} else if(request.type == link_pkt::PacketChangeKey) {
reply = on_change_key_remote(conn->conn_id, *conn->bindy, request.content);
} else if(request.type == link_pkt::PacketListUsers) {
reply = on_list_users_remote(conn->conn_id, *conn->bindy, request.content);
} else if(request.type == link_pkt::PacketSetMaster) {
reply = on_set_master_remote(conn->conn_id, *conn->bindy, request.content);
}
unsigned long orig_reply_size = (unsigned long)reply.content.size();
reply.content.resize(orig_reply_size + sizeof(ack_id_t));
std::memcpy(reply.content.data() + orig_reply_size, &msg_id, sizeof(ack_id_t));
conn->send_packet(reply.type, reply.content);
}
}
}
} catch(...) {
DEBUG("Caught exception, deleting connection...");
}
if (conn != nullptr) {
conn->disconnect_self();
delete conn;