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
|
#include "../include/Channel.hpp"
#include "../include/ChannelSidePanel.hpp"
#include "../include/UsersSidePanel.hpp"
#include "../include/ChannelTopPanel.hpp"
#include "../include/Cache.hpp"
#include "../include/ResourceCache.hpp"
#include "../include/Video.hpp"
#include "../include/Command.hpp"
#include "../include/Settings.hpp"
#include "../include/ColorScheme.hpp"
#include "../include/GlobalContextMenu.hpp"
#include "../include/StringUtils.hpp"
#include "../include/ImagePreview.hpp"
#include <string>
#include <SFML/Graphics.hpp>
#include <cstring>
#include <boost/filesystem/path.hpp>
#include <odhtdb/Database.hpp>
#include <odhtdb/Signature.hpp>
#include <odhtdb/bin2hex.hpp>
#include <odhtdb/hex2bin.hpp>
#include <ntp/NtpClient.hpp>
#include <sibs/SafeSerializer.hpp>
#include <X11/Xlib.h>
using namespace std;
using namespace dchat;
static bool focused = true;
static void channelChangeUserNickname(Channel *channel, const StringView data, const odhtdb::Signature::PublicKey &userPublicKey)
{
auto user = channel->getUserByPublicKey(userPublicKey);
if(!user)
{
fprintf(stderr, "Nickname change: user with public key %s not found in channel %s\n", userPublicKey.toString().c_str(), channel->getName().c_str());
return;
}
sibs::SafeDeserializer deserializer((const u8*)data.data, data.size);
u8 nameLength = deserializer.extract<u8>();
if(nameLength > 0)
{
user->name.resize(nameLength);
deserializer.extract((u8*)&user->name[0], nameLength);
}
// We dont care if there is more data to read (malicious packet), we already got all the data we need
}
static void channelAddStoredMessage(Channel *channel, const odhtdb::Hash &requestHash, const odhtdb::Signature::PublicKey &creatorPublicKey, const StringView decryptedObject, u64 timestamp)
{
User *user = channel->getUserByPublicKey(creatorPublicKey);
if(!user)
{
fprintf(stderr, "Missing user? %s\n", creatorPublicKey.toString().c_str());
return;
}
if(decryptedObject.size > 1)
{
auto channelDataType = (ChannelDataType)static_cast<const char*>(decryptedObject.data)[0];
StringView decryptedData((const char*)decryptedObject.data + 1, decryptedObject.size - 1);
switch(channelDataType)
{
case ChannelDataType::ADD_MESSAGE:
{
string msg(decryptedData.data, decryptedData.size);
channel->addLocalMessage(msg, user, ntp::NtpTimestamp::fromCombined(timestamp).seconds, requestHash);
if(!focused)
{
stringReplaceChar(msg, "'", "");
stringReplaceChar(msg, "\\", "");
string cmd = "notify-send dchat '";
cmd += msg;
cmd += "'";
system(cmd.c_str());
}
break;
}
case ChannelDataType::DELETE_MESSAGE:
{
sibs::SafeDeserializer deserializer((const u8*)decryptedData.data, decryptedData.size);
odhtdb::Hash messageId;
deserializer.extract((u8*)messageId.getData(), odhtdb::HASH_BYTE_SIZE);
channel->deleteLocalMessage(messageId, creatorPublicKey);
break;
}
case ChannelDataType::NICKNAME_CHANGE:
{
try
{
channelChangeUserNickname(channel, decryptedData, creatorPublicKey);
}
catch(sibs::DeserializeException &e)
{
fprintf(stderr, "Failed to deserialize nick change\n");
}
break;
}
default:
fprintf(stderr, "Got unexpected channel data type: %u\n", channelDataType);
break;
}
}
else
{
fprintf(stderr, "ADD_DATA packet too small, ignoring...\n");
}
}
int main(int argc, char **argv)
{
/*
boost::filesystem::path programPath(argv[0]);
auto parentPath = programPath.parent_path();
printf("parent path: %s\n", parentPath.string().c_str());
boost::filesystem::current_path(parentPath); // Ensures loading of resources works no matter which path we run this executable from
*/
const sf::Int64 FRAMERATE_FOCUSED = 144;
const sf::Int64 FRAMERATE_NOT_FOCUSED = 10;
XInitThreads();
sf::RenderWindow window(sf::VideoMode(1280, 768), "dchat");
window.setVerticalSyncEnabled(false);
window.setFramerateLimit(FRAMERATE_FOCUSED);
//Video video(500, 500, "https://www.youtube.com/watch?v=bs0-EX9mJmg");
Cache cache;
Cache::loadBindsFromFile();
Channel offlineChannel("Offline");
ChannelSidePanel::addChannel(&offlineChannel);
Channel::setCurrent(&offlineChannel);
vector<Channel*> channels;
vector<odhtdb::DatabaseNode> waitingToJoinChannels;
odhtdb::MapHash<odhtdb::StoredNodeInfo> localNodeUsers;
string currentUsername;
string currentPassword;
recursive_mutex channelMessageMutex;
bool waitingToJoin = false;
bool loggedIn = false;
sf::Clock lastFocusedTimer;
odhtdb::Database *database = nullptr;
odhtdb::DatabaseCallbackFuncs callbackFuncs;
callbackFuncs.createNodeCallbackFunc = [&waitingToJoinChannels, &database, &channels, &channelMessageMutex, &waitingToJoin, &localNodeUsers, &lastFocusedTimer](const odhtdb::DatabaseCreateNodeRequest &request)
{
lock_guard<recursive_mutex> lock(channelMessageMutex);
//printf("Create node callback func %s\n", request.nodeHash->toString().c_str());
auto nodeUserData = localNodeUsers.find(*request.nodeHash);
if(nodeUserData == localNodeUsers.end()) return;
User *localUser;
if(nodeUserData->second.userKeyPair->getPublicKey() == *request.creatorPublicKey)
localUser = new OnlineLocalUser("NoName", *nodeUserData->second.userKeyPair);
else
localUser = new OfflineUser("You");
shared_ptr<odhtdb::Hash> databaseNodeHash = make_shared<odhtdb::Hash>();
memcpy(databaseNodeHash->getData(), request.nodeHash->getData(), odhtdb::HASH_BYTE_SIZE);
odhtdb::DatabaseNode databaseNode(nodeUserData->second.nodeEncryptionKey, databaseNodeHash);
Channel *channel = new Channel("NoChannelName", databaseNode, localUser, database);
ChannelSidePanel::addChannel(channel);
channels.push_back(channel);
Channel::setCurrent(channel);
if(localUser->type == User::Type::OFFLINE)
{
User *nodeCreatorUser = new OnlineRemoteUser("NoName", *request.creatorPublicKey);
channel->addUserLocally(nodeCreatorUser);
}
for(vector<odhtdb::DatabaseNode>::iterator it = waitingToJoinChannels.begin(); it != waitingToJoinChannels.end(); ++it)
{
if(*request.nodeHash == *it->getRequestHash())
{
waitingToJoin = true;
waitingToJoinChannels.erase(it);
return;
}
}
};
callbackFuncs.addNodeCallbackFunc = [&channels, &channelMessageMutex, &lastFocusedTimer](const odhtdb::DatabaseAddNodeRequest &request)
{
lock_guard<recursive_mutex> lock(channelMessageMutex);
//printf("Add node callback func %s\n", request.requestHash->toString().c_str());
for(Channel *channel : channels)
{
if(*request.nodeHash == *channel->getNodeInfo().getRequestHash())
{
channelAddStoredMessage(channel, *request.requestHash, *request.creatorPublicKey, StringView((const char*)request.decryptedData.data, request.decryptedData.size), request.timestamp);
lastFocusedTimer.restart();
return;
}
}
};
callbackFuncs.addUserCallbackFunc = [&channels, &channelMessageMutex, &waitingToJoin, &localNodeUsers, &lastFocusedTimer](const odhtdb::DatabaseAddUserRequest &request)
{
lock_guard<recursive_mutex> lock(channelMessageMutex);
printf("Add user callback. Channel to add user to: %s\n", request.nodeHash->toString().c_str());
for(Channel *channel : channels)
{
printf("My channel: %s (%s)\n", channel->getNodeInfo().getRequestHash()->toString().c_str(), channel->getName().c_str());
if(*request.nodeHash == *channel->getNodeInfo().getRequestHash())
{
printf("Add user to one of my channels\n");
auto nodeUserData = localNodeUsers.find(*request.nodeHash);
User *userToAdd = channel->getUserByPublicKey(*request.userToAddPublicKey);
if(userToAdd)
{
fprintf(stderr, "User %s already exists in channel\n", request.userToAddPublicKey->toString().c_str());
return;
}
lastFocusedTimer.restart();
if(*request.userToAddPublicKey == nodeUserData->second.userKeyPair->getPublicKey())
{
printf("You were added to channel %s by %s\n", request.nodeHash->toString().c_str(), request.creatorPublicKey->toString().c_str());
channel->replaceLocalUser(new OnlineLocalUser("NoName", *nodeUserData->second.userKeyPair));
waitingToJoin = false;
return;
}
User *newRemoteUser = new OnlineRemoteUser("NoName", *request.userToAddPublicKey);
channel->addUserLocally(newRemoteUser);
return;
}
}
};
database = new odhtdb::Database("bootstrap.ring.cx", 4222, Cache::getDchatDir(), callbackFuncs);
auto addSystemMessage = [&lastFocusedTimer](const std::string &msg)
{
Channel::getCurrent()->addLocalMessage(msg, Channel::getCurrent()->getSystemUser());
lastFocusedTimer.restart();
};
// Login to account
Command::add("login", [&localNodeUsers, &database, &channels, &loggedIn, &channelMessageMutex, ¤tUsername, ¤tPassword](const vector<string> &args)
{
lock_guard<recursive_mutex> lock(channelMessageMutex);
if(args.size() != 2)
{
fprintf(stderr, "Expected 2 arguments for command login (username and password), got %u argument(s)\n", args.size());
return;
}
try
{
localNodeUsers = database->getStoredNodeUserInfoDecrypted(args[0], args[1]);
ChannelSidePanel::removeAllChannels();
for(Channel *channel : channels)
{
delete channel;
}
channels.clear();
printf("Loading %u channel(s) for user\n", localNodeUsers.size());
for(auto &localNodeUser : localNodeUsers)
{
database->loadNode(localNodeUser.first);
}
printf("Successfully logged into user %s\n", args[0].c_str());
currentUsername = args[0];
currentPassword = args[1];
loggedIn = true;
}
catch(std::exception &e)
{
fprintf(stderr, "Failed to login, reason: %s\n", e.what());
}
});
// Register account
Command::add("register", [&localNodeUsers, &database, &channels, &loggedIn, &channelMessageMutex, ¤tUsername, ¤tPassword](const vector<string> &args)
{
lock_guard<recursive_mutex> lock(channelMessageMutex);
if(args.size() != 2)
{
fprintf(stderr, "Expected 2 arguments for command register (username and password), got %u argument(s)\n", args.size());
return;
}
try
{
database->storeUserWithoutNodes(args[0], args[1]);
}
catch(odhtdb::SqlExecException &e)
{
fprintf(stderr, "User with name %s already exists in storage\n", args[0].c_str());
return;
}
printf("Registered user %s\n", args[0].c_str());
ChannelSidePanel::removeAllChannels();
for(Channel *channel : channels)
{
delete channel;
}
channels.clear();
localNodeUsers.clear();
printf("Successfully logged into user %s\n", args[0].c_str());
currentUsername = args[0];
currentPassword = args[1];
loggedIn = true;
});
// TODO: Use database->addData to change channel name
// Create channel
Command::add("cc", [&database, &channels, &channelMessageMutex, &loggedIn, &localNodeUsers, ¤tUsername, ¤tPassword, &lastFocusedTimer, addSystemMessage](const vector<string> &args)
{
lock_guard<recursive_mutex> lock(channelMessageMutex);
if(args.size() != 1)
{
fprintf(stderr, "Expected 1 argument for command cc (channel name), got %u argument(s)\n", args.size());
return;
}
if(!loggedIn)
{
fprintf(stderr, "You are not logged in. Please login before creating a channel\n");
return;
}
auto createResponse = database->create();
printf("Created channel %s\n", createResponse->getRequestHash()->toString().c_str());
User *newLocalUser = new OnlineLocalUser("NoName", *createResponse->getNodeAdminKeyPair());
odhtdb::DatabaseNode databaseNode(createResponse->getNodeEncryptionKey(), createResponse->getRequestHash());
Channel *channel = new Channel(args[0], databaseNode, newLocalUser, database);
ChannelSidePanel::addChannel(channel);
channels.push_back(channel);
Channel::setCurrent(channel);
lastFocusedTimer.restart();
localNodeUsers[*createResponse->getRequestHash()] = { createResponse->getNodeEncryptionKey(), createResponse->getNodeAdminKeyPair() };
database->storeNodeInfoForUserEncrypted(databaseNode, currentUsername, currentPassword, *createResponse->getNodeAdminKeyPair());
addSystemMessage("Channel created and stored in database");
});
// Create invite key
Command::add("invite", [&channelMessageMutex, &offlineChannel, &database, addSystemMessage](const vector<string> &args)
{
lock_guard<recursive_mutex> lock(channelMessageMutex);
if(args.size() != 0)
{
fprintf(stderr, "Expected 0 arguments for command invite, got %u argument(s)\n", args.size());
return;
}
Channel *currentChannel = Channel::getCurrent();
if(currentChannel == &offlineChannel)
{
addSystemMessage("You need to be in a channel to create an invite key");
return;
}
// TODO: Verify user has permission to add users before generating invite key, otherwise invite will fail and the users attempting to join will wait in futile
auto channelNodeHash = currentChannel->getNodeInfo().getRequestHash();
auto channelEncryptionKey = currentChannel->getNodeInfo().getNodeEncryptionKey();
shared_ptr<odhtdb::OwnedByteArray> encryptionKey = make_shared<odhtdb::OwnedByteArray>(new u8[odhtdb::ENCRYPTION_KEY_BYTE_SIZE], odhtdb::ENCRYPTION_KEY_BYTE_SIZE);
odhtdb::Encryption::generateKey((unsigned char*)encryptionKey->data);
string inviteKey = odhtdb::bin2hex((const char*)channelNodeHash->getData(), channelNodeHash->getSize());
inviteKey += '&';
inviteKey += odhtdb::bin2hex((const char*)encryptionKey->data, odhtdb::ENCRYPTION_KEY_BYTE_SIZE);
string msg = "You are now listening for users to join the channel using the key: ";
msg += inviteKey;
addSystemMessage(msg);
printf("%s\n", msg.c_str());
sibs::SafeSerializer keySerializer;
keySerializer.add((const u8*)channelNodeHash->getData(), channelNodeHash->getSize());
keySerializer.add((const u8*)encryptionKey->data, odhtdb::ENCRYPTION_KEY_BYTE_SIZE);
dht::InfoHash key = odhtdb::Database::getInfoHash(keySerializer.getBuffer().data(), keySerializer.getBuffer().size());
database->receiveCustomMessage(key, [&channelMessageMutex, encryptionKey, channelEncryptionKey, currentChannel, &database](const void *data, usize size)
{
// TODO: User can remove channel @currentChannel before we get here, meaning @currentChannel is deleted and would be invalid; causing the program to crash
try
{
sibs::SafeDeserializer deserializer((const u8*)data, size);
u8 userToAddPublicKeyRaw[odhtdb::PUBLIC_KEY_NUM_BYTES];
deserializer.extract(userToAddPublicKeyRaw, odhtdb::PUBLIC_KEY_NUM_BYTES);
odhtdb::Signature::PublicKey userToAddPublicKey((const char*)userToAddPublicKeyRaw, odhtdb::PUBLIC_KEY_NUM_BYTES);
string unsignedEncryptedMsg = userToAddPublicKey.unsign(odhtdb::DataView((void*)deserializer.getBuffer(), deserializer.getSize()));
sibs::SafeDeserializer encryptedDataDeserializer((const u8*)unsignedEncryptedMsg.data(), unsignedEncryptedMsg.size());
u8 nonce[odhtdb::ENCRYPTION_NONCE_BYTE_SIZE];
encryptedDataDeserializer.extract(nonce, odhtdb::ENCRYPTION_NONCE_BYTE_SIZE);
odhtdb::Decryption decryptedMsg(odhtdb::DataView((void*)encryptedDataDeserializer.getBuffer(), encryptedDataDeserializer.getSize()),
odhtdb::DataView(nonce, odhtdb::ENCRYPTION_NONCE_BYTE_SIZE),
encryptionKey->getView());
// TODO: Create GUI for accepting users into channel instead of accepting ALL users
sibs::SafeSerializer encryptedDataSerializer;
encryptedDataSerializer.add((const u8*)channelEncryptionKey->data, channelEncryptionKey->size);
encryptedDataSerializer.add((const u8*)userToAddPublicKey.getData(), userToAddPublicKey.getSize());
odhtdb::Encryption encryptedChannelKey(odhtdb::DataView((void*)encryptedDataSerializer.getBuffer().data(), encryptedDataSerializer.getBuffer().size()), encryptionKey->getView());
sibs::SafeSerializer serializer;
serializer.add((const u8*)encryptedChannelKey.getNonce().data, encryptedChannelKey.getNonce().size);
serializer.add((const u8*)encryptedChannelKey.getCipherText().data, encryptedChannelKey.getCipherText().size);
const auto &localUserPublicKey = static_cast<OnlineLocalUser*>(currentChannel->getLocalUser())->getPublicKey();
auto localUserGroups = database->getUserGroups(*currentChannel->getNodeInfo().getRequestHash(), localUserPublicKey);
if(localUserGroups.empty())
{
fprintf(stderr, "No group to add user to...\n");
return sibs::SafeSerializer();
}
lock_guard<recursive_mutex> lock(channelMessageMutex);
currentChannel->addUser(userToAddPublicKey, localUserGroups[0].getView());
return serializer;
}
catch(std::exception &e)
{
fprintf(stderr, "Failed while parsing user data to add to channel, reason: %s\n", e.what());
}
return sibs::SafeSerializer();
});
});
// Join channel using invite key
Command::add("jc", [&loggedIn, &database, &localNodeUsers, &channelMessageMutex, &waitingToJoin, &waitingToJoinChannels, ¤tUsername, ¤tPassword](const vector<string> &args)
{
lock_guard<recursive_mutex> lock(channelMessageMutex);
if(args.size() != 1)
{
fprintf(stderr, "Expected 1 argument for command jc (channel join key), got %u argument(s)\n", args.size());
return;
}
if(args[0].size() != 129)
{
fprintf(stderr, "Expected join key to be 129 characters, was %u character(s)\n", args[0].size());
return;
}
if(!loggedIn)
{
fprintf(stderr, "You are not logged in. Please login before joining a channel\n");
return;
}
string nodeHashBinRaw = odhtdb::hex2bin(args[0].c_str(), 64);
shared_ptr<odhtdb::Hash> nodeHash = make_shared<odhtdb::Hash>();
memcpy(nodeHash->getData(), nodeHashBinRaw.data(), nodeHashBinRaw.size());
auto nodeUserIt = localNodeUsers.find(*nodeHash);
if(nodeUserIt != localNodeUsers.end())
{
fprintf(stderr, "You have already joined the channel %s\n", args[0].c_str());
return;
}
string encryptionKeyBinRaw = odhtdb::hex2bin(args[0].c_str() + 65, 64);
shared_ptr<odhtdb::OwnedByteArray> encryptionKey = make_shared<odhtdb::OwnedByteArray>(new u8[odhtdb::ENCRYPTION_KEY_BYTE_SIZE], odhtdb::ENCRYPTION_KEY_BYTE_SIZE);
memcpy(encryptionKey->data, encryptionKeyBinRaw.data(), encryptionKeyBinRaw.size());
shared_ptr<odhtdb::Signature::KeyPair> keyPair = make_shared<odhtdb::Signature::KeyPair>();
sibs::SafeSerializer serializer;
serializer.add((const u8*)keyPair->getPublicKey().getData(), keyPair->getPublicKey().getSize());
const char *msg = "please let me join";
odhtdb::Encryption encryptedJoinMsg(odhtdb::DataView((void*)msg, strlen(msg)), encryptionKey->getView());
sibs::SafeSerializer encryptedDataSerializer;
encryptedDataSerializer.add((const u8*)encryptedJoinMsg.getNonce().data, encryptedJoinMsg.getNonce().size);
encryptedDataSerializer.add((const u8*)encryptedJoinMsg.getCipherText().data, encryptedJoinMsg.getCipherText().size);
string signedEncryptedMsg = keyPair->getPrivateKey().sign(odhtdb::DataView(encryptedDataSerializer.getBuffer().data(), encryptedDataSerializer.getBuffer().size()));
serializer.add((const u8*)signedEncryptedMsg.data(), signedEncryptedMsg.size());
sibs::SafeSerializer keySerializer;
keySerializer.add((const u8*)nodeHash->getData(), nodeHash->getSize());
keySerializer.add((const u8*)encryptionKeyBinRaw.data(), odhtdb::ENCRYPTION_KEY_BYTE_SIZE);
dht::InfoHash key = odhtdb::Database::getInfoHash(keySerializer.getBuffer().data(), keySerializer.getBuffer().size());
database->sendCustomMessage(key, move(serializer.getBuffer()), [&database, nodeHash, encryptionKey, &waitingToJoinChannels, &channelMessageMutex, keyPair, ¤tUsername, ¤tPassword, &localNodeUsers](bool gotResponse, const void *data, usize size)
{
if(!gotResponse)
{
printf("We didn't get a response from anybody in the channel. Is there nobody that can add us (nobody with the permission required to do so or no online users) or is the node hash invalid?\n");
return false;
}
try
{
sibs::SafeDeserializer deserializer((const u8*)data, size);
u8 nonce[odhtdb::ENCRYPTION_NONCE_BYTE_SIZE];
deserializer.extract(nonce, odhtdb::ENCRYPTION_NONCE_BYTE_SIZE);
odhtdb::Decryption decryptedMsg(odhtdb::DataView((void*)deserializer.getBuffer(), deserializer.getSize()),
odhtdb::DataView(nonce, odhtdb::ENCRYPTION_NONCE_BYTE_SIZE),
encryptionKey->getView());
if(decryptedMsg.getDecryptedText().size != odhtdb::ENCRYPTION_KEY_BYTE_SIZE + odhtdb::PUBLIC_KEY_NUM_BYTES)
{
fprintf(stderr, "Invite response was of unexpected size, maybe it wasn't meant for us?\n");
return true;
}
odhtdb::DataView channelEncryptionKeyRaw(decryptedMsg.getDecryptedText().data, odhtdb::ENCRYPTION_KEY_BYTE_SIZE);
odhtdb::DataView invitedUserPublicKey((u8*)decryptedMsg.getDecryptedText().data + odhtdb::ENCRYPTION_KEY_BYTE_SIZE, odhtdb::PUBLIC_KEY_NUM_BYTES);
if(memcmp(keyPair->getPublicKey().getData(), invitedUserPublicKey.data, odhtdb::PUBLIC_KEY_NUM_BYTES) != 0)
{
fprintf(stderr, "Invite response was not meant for us\n");
return true;
}
shared_ptr<odhtdb::OwnedByteArray> channelEncryptionKey = make_shared<odhtdb::OwnedByteArray>(new u8[channelEncryptionKeyRaw.size], channelEncryptionKeyRaw.size);
memcpy(channelEncryptionKey->data, channelEncryptionKeyRaw.data, channelEncryptionKeyRaw.size);
odhtdb::DatabaseNode databaseNode(channelEncryptionKey, nodeHash);
localNodeUsers[*nodeHash] = { channelEncryptionKey, keyPair };
database->storeNodeInfoForUserEncrypted(databaseNode, currentUsername, currentPassword, *keyPair);
printf("Got a response from a person in the channel, we might get added...\n");
waitingToJoinChannels.push_back(databaseNode);
lock_guard<recursive_mutex> lock(channelMessageMutex);
database->seed(databaseNode);
return false;
}
catch(std::exception &e)
{
fprintf(stderr, "Failed while parsing join response for invite link, reason: %s\n", e.what());
}
return true;
});
waitingToJoin = true;
});
// Scale UI
Command::add("scale", [](const vector<string> &args)
{
if(args.size() != 1)
{
fprintf(stderr, "Expected 1 argument for command scale, got %u argument(s)\n", args.size());
return;
}
float scaling = stof(args[0]);
Settings::setScaling(scaling);
printf("UI scaling set to %f\n", scaling);
});
Command::add("addbind", [addSystemMessage](const vector<string> &args)
{
if(args.size() != 2)
{
string errMsg = "Expected 2 arguments for command addbind, got ";
errMsg += to_string(args.size());
errMsg += " argument(s)";
addSystemMessage(errMsg);
return;
}
string key = ":";
key += args[0];
key += ":";
if(key.size() > 255)
{
// 253 = bind + two colons
addSystemMessage("Bind is too long. Max size is 253 bytes");
return;
}
bool bindAdded = Chatbar::addBind(key, args[1]);
if(bindAdded)
addSystemMessage("Bind added");
else
addSystemMessage("Bind already exists. Remove it first if you want to replace it");
});
Command::add("removebind", [addSystemMessage](const vector<string> &args)
{
if(args.size() != 1)
{
string errMsg = "Expected 1 argument for command removebind, got ";
errMsg += to_string(args.size());
errMsg += " argument(s)";
addSystemMessage(errMsg);
return;
}
string key = ":";
key += args[0];
key += ":";
if(key.size() > 255)
{
// 253 = bind + two colons
addSystemMessage("Bind is too long. Max size is 253 bytes");
return;
}
bool bindRemoved = Chatbar::removeBind(key);
if(bindRemoved)
addSystemMessage("Bind removed");
else
addSystemMessage("Bind doesn't exist, nothing was removed");
});
Command::add("binds", [addSystemMessage](const vector<string> &args)
{
if(args.size() != 0)
{
string errMsg = "Expected 0 arguments for command removebind, got ";
errMsg += to_string(args.size());
errMsg += " argument(s)";
addSystemMessage(errMsg);
return;
}
string msg = "Binds:";
auto binds = Chatbar::getBinds();
for(auto &bind : binds)
{
msg += "\n";
msg += bind.first;
msg += " ";
msg += bind.second;
}
addSystemMessage(msg);
});
// Change nick of current user in current channel
Command::add("nick", [&loggedIn, &offlineChannel, addSystemMessage](const vector<string> &args)
{
if(args.size() != 1)
{
string errMsg = "Expected 1 argument for command nick, got ";
errMsg += to_string(args.size());
errMsg += " argument(s)";
addSystemMessage(errMsg);
return;
}
if(!loggedIn)
{
addSystemMessage("You need to be logged in to change your nickname");
return;
}
if(Channel::getCurrent() == &offlineChannel)
{
addSystemMessage("You need to be in a channel to change your nickname");
return;
}
if(args[0].size() == 0 || args[0].size() > 255)
{
addSystemMessage("Invalid nickname. Nickname has to be between 1 and 255 characters");
return;
}
Channel::getCurrent()->changeNick(args[0]);
string msg = "Your nickname was changed to ";
msg += args[0];
addSystemMessage(msg);
});
Command::add("clearcache", [&database](const vector<string> &args)
{
printf("Cleared cache (%d bytes)\n", database->clearCache());
});
sf::Clock frameTimer;
while (window.isOpen())
{
frameTimer.restart();
Channel *currentChannel = Channel::getCurrent();
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
else if(event.type == sf::Event::Resized)
{
sf::FloatRect viewRect(0.0f, 0.0f, event.size.width, event.size.height);
/* // TODO: Use xlib to set window minimum size instead
const int minWidth = 800;
if(event.size.width < minWidth)
{
viewRect.width = minWidth;
window.setSize(sf::Vector2u(minWidth, event.size.height));
}
*/
sf::View view(viewRect);
window.setView(view);
}
else if(event.type == sf::Event::MouseEntered)
window.setFramerateLimit(FRAMERATE_FOCUSED);
//else if(event.type == sf::Event::MouseLeft)
// window.setFramerateLimit(FRAMERATE_NOT_FOCUSED);
if(event.type == sf::Event::MouseEntered)
focused = true;
else if(event.type == sf::Event::MouseLeft)
focused = false;
if(focused)
{
ImagePreview::processEvent(event);
}
if(!ImagePreview::getPreviewContentPtr() && ImagePreview::getTimeSinceLastSeenMs() > 250)
{
GlobalContextMenu::processEvent(event);
currentChannel->processEvent(event, cache);
}
lastFocusedTimer.restart();
}
if(lastFocusedTimer.getElapsedTime().asMilliseconds() > 3000)
{
this_thread::sleep_for(chrono::milliseconds(250));
continue;
}
window.clear(ColorScheme::getBackgroundColor());
ChannelSidePanel::draw(window);
currentChannel->draw(window, cache);
UsersSidePanel::draw(window, cache);
ChannelTopPanel::draw(window);
GlobalContextMenu::draw(window);
ImagePreview::draw(window);
if(waitingToJoin)
{
auto windowSize = window.getSize();
sf::RectangleShape shadeRect(sf::Vector2f(windowSize.x, windowSize.y));
shadeRect.setFillColor(sf::Color(0, 0, 0, 200));
window.draw(shadeRect);
const sf::Font *FONT = ResourceCache::getFont("fonts/Roboto-Regular.ttf");
const float FONT_SIZE = (double)windowSize.x / 40.0;
sf::Text text("Wait until you are added to the channel", *FONT, FONT_SIZE);
text.setPosition(floor((float)windowSize.x * 0.5f - text.getLocalBounds().width * 0.5f), floor((float)windowSize.y * 0.5f - FONT->getLineSpacing(FONT_SIZE) * 0.5f));
window.draw(text);
}
//video.draw(window);
window.display();
}
return 0;
}
|