-
Notifications
You must be signed in to change notification settings - Fork 207
/
Copy pathwhatsapp-protocol.cc
1944 lines (1644 loc) · 54 KB
/
whatsapp-protocol.cc
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
/*
* WhatsApp API implementation in C++ for libpurple.
* Written by David Guillen Fandos ([email protected]) based
* on the sources of WhatsAPI PHP implementation.
* v1.4 changes based on WP7 sources
*
* Share and enjoy!
*
*/
#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <map>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include "wadict.h"
#include "rc4.h"
#include "keygen.h"
#include "databuffer.h"
#include "tree.h"
#include "contacts.h"
#include "message.h"
#include "wa_connection.h"
#include "wa_util.h"
#include "wa_constants.h"
#include "AxolotlMessages.pb.h"
#include "keyhelper.h"
#include "prekeywhispermessage.h"
#include "sessioncipher.h"
#include "whisperexception.h"
#include "sessioncipher.h"
#include "axolotl_groups.h"
#include "group_session_builder.h"
static int isbroadcast(const std::string user)
{
return (user.find("@broadcast") != std::string::npos);
}
// Group numbers are a bit tricky! I wish I stored them as strings...
static uint64_t JidAsInt(const std::string & s) {
std::string id = s.substr(0, s.find("@"));
std::string onlynums;
for (auto c: id)
if (c >= '0' && c <= '9')
onlynums += c;
// This is fucking disgusting :D
onlynums = onlynums.substr(0, 19);
return std::stoull(onlynums);
}
DataBuffer WhatsappConnection::generateResponse(std::string from, std::string type, std::string id)
{
if (type == "") { // Auto
if (sendRead) type = "read";
else type = "delivery";
}
Tree mes("receipt", makeat({"to", from, "id", id, "type", type, "t", std::to_string(1)}));
return serialize_tree(&mes);
}
std::string WhatsappConnection::tohex(uint64_t n) {
std::string ret;
const char *hext = "0123456789abcdef";
uint64_t cnum = n;
while (cnum > 0) {
ret += hext[cnum&15];
cnum >>= 4;
}
return ret;
}
#define adjustId(id) numToBytesZPadded(id, 3)
static std::string numToBytesZPadded(uint64_t n, unsigned int padding) {
std::string ret;
while (n > 0) {
ret = std::string(1, (char)(n&255)) + ret;
n = n >> 8;
}
while (ret.size() < padding)
ret = '\0' + ret;
return ret;
}
static uint64_t num2int64(std::string s) {
uint64_t ret = 0;
for (auto c: s) {
ret = ret << 8;
ret |= (unsigned char)c;
}
return ret;
}
std::string WhatsappConnection::getNextIqId() {
return tohex(++iqid);
}
/* Send image transaction */
int WhatsappConnection::sendImage(std::string mid, std::string to, int w, int h, unsigned int size, const char *fp)
{
/* Type can be: audio/image/video */
std::string siqid = getNextIqId();
std::string sha256b64hash = SHA256_file_b64(fp);
Tree iq("media", makeat({"type", "image", "hash", sha256b64hash, "size", std::to_string(size)}));
Tree req("iq", makeat({"id", siqid, "type", "set", "to", whatsappserver, "xmlns", "w:m"}));
req.addChild(iq);
t_fileupload fu;
fu.to = to;
fu.file = std::string(fp);
fu.rid = iqid;
fu.hash = sha256b64hash;
fu.type = "image";
fu.uploading = false;
fu.totalsize = 0;
fu.thumbnail = getpreview(fp);
fu.msgid = mid;
uploadfile_queue.push_back(fu);
outbuffer = outbuffer + serialize_tree(&req);
return iqid;
}
WhatsappConnection::WhatsappConnection(std::string phonenum, std::string password, std::string nickname, std::string axolotldb)
{
this->phone = phonenum;
this->password = password;
this->in = NULL;
this->out = NULL;
this->conn_status = SessionNone;
this->msgcounter = 1;
this->iqid = 0;
this->nickname = nickname;
this->whatsappserver = WHATSAPP_SERVER;
this->whatsappservergroup = "g.us";
this->mypresence = "available";
this->groups_updated = false;
this->blists_updated = false;
this->sslstatus = 0;
this->frame_seq = 0;
this->sendRead = true;
this->last_keepalive = 0;
// Create in memory temp database!
//this->axolotlStore.reset(new LiteAxolotlStore(axolotldb));
this->axolotlStore.reset(new InMemoryAxolotlStore());
/* Trim password spaces */
while (password.size() > 0 and password[0] == ' ')
password = password.substr(1);
while (password.size() > 0 and password[password.size() - 1] == ' ')
password = password.substr(0, password.size() - 1);
/* Remove non-numbers from phone */
phone.erase(std::remove_if(phone.begin(), phone.end(), [](char ch){return !isdigit(ch);}), phone.end());
}
WhatsappConnection::~WhatsappConnection()
{
if (this->in)
delete this->in;
if (this->out)
delete this->out;
for (unsigned int i = 0; i < recv_messages.size(); i++) {
delete recv_messages[i];
}
}
std::string WhatsappConnection::saveAxolotlDatabase()
{
// Serialize the database
//return axolotlStore->serialize();
return "";
}
std::map < std::string, Group > WhatsappConnection::getGroups()
{
return groups;
}
bool WhatsappConnection::groupsUpdated()
{
bool r = groups_updated;
groups_updated = false;
return r;
}
void WhatsappConnection::updateGroups()
{
/* Get the group list */
groups.clear();
{
Tree req("iq", makeat({"id", getNextIqId(), "type", "get", "to", "g.us", "xmlns", "w:g2"}));
req.addChild(Tree("participating"));
outbuffer = outbuffer + serialize_tree(&req);
}
}
void WhatsappConnection::manageParticipant(std::string group, std::string participant, std::string command)
{
Tree iq(command);
iq.addChild(Tree("participant", makeat({"jid", participant})));
Tree req("iq", makeat({"id", getNextIqId(), "type", "set", "to", group + "@g.us", "xmlns", "w:g2"}));
req.addChild(iq);
outbuffer = outbuffer + serialize_tree(&req);
}
void WhatsappConnection::leaveGroup(std::string group)
{
Tree iq("leave");
iq.addChild(Tree("group", makeat({"id", group + "@g.us"})));
Tree req("iq", makeat({"id", getNextIqId(), "type", "set", "to", "g.us", "xmlns", "w:g2"}));
req.addChild(iq);
outbuffer = outbuffer + serialize_tree(&req);
}
void WhatsappConnection::addGroup(std::string subject)
{
Tree req("iq", makeat({"id", getNextIqId(), "type", "set", "to", "g.us", "xmlns", "w:g2"}));
Tree create("create", makeat({"subject", subject}));
req.addChild(create);
outbuffer = outbuffer + serialize_tree(&req);
}
void WhatsappConnection::updateBlists()
{
blists.clear();
Tree req("iq", makeat({
"id", getNextIqId(),
"from", phone + "@" + whatsappserver,
"type", "get",
"to", WHATSAPP_SERVER,
"xmlns", "w:b"}
));
req.addChild(Tree("lists"));
outbuffer = outbuffer + serialize_tree(&req);
}
bool WhatsappConnection::blistsUpdated()
{
bool r = blists_updated;
blists_updated = false;
return r;
}
void WhatsappConnection::deleteBlist(std::string id)
{
Tree req("iq", makeat({
"id", getNextIqId(),
"type", "set",
"to", WHATSAPP_SERVER,
"xmlns", "w:b"}
));
Tree del;
del.addChild(Tree("list", makeat({"id", id + "@broadcast"})));
req.addChild(del);
outbuffer = outbuffer + serialize_tree(&req);
}
void WhatsappConnection::doLogin(std::string resource, bool send_ciphered)
{
this->send_ciphered = send_ciphered;
this->resource = resource;
/* Send stream init */
DataBuffer first;
error_queue.clear();
{
first.addData("WA\1\6", 4);
Tree t("start", makeat({"resource",resource, "to",whatsappserver}));
first = first + serialize_tree(&t, false);
}
/* Send features */
{
Tree p("stream:features");
first = first + serialize_tree(&p, false);
}
/* Send auth request */
{
Tree t("auth", makeat({"mechanism","WAUTH-2", "user",phone}));
first = first + serialize_tree(&t, false);
}
conn_status = SessionWaitingChallenge;
outbuffer = first;
}
void WhatsappConnection::receiveCallback(const char *data, int len)
{
if (data != NULL and len > 0)
inbuffer.addData(data, len);
this->processIncomingData();
}
int WhatsappConnection::sendCallback(char *data, int len)
{
int minlen = outbuffer.size();
if (minlen > len)
minlen = len;
memcpy(data, outbuffer.getPtr(), minlen);
return minlen;
}
bool WhatsappConnection::hasDataToSend()
{
// Check whether we need to send a keepalive
if (time(0) - last_keepalive > 30) {
last_keepalive = time(0);
if (conn_status == SessionConnected)
notifyMyPresence();
}
// Retry messages in the queue
processMsgQueue();
return outbuffer.size() != 0;
}
void WhatsappConnection::sentCallback(int len)
{
outbuffer.popData(len);
}
int WhatsappConnection::sendSSLCallback(char *buffer, int maxbytes)
{
int minlen = sslbuffer.size();
if (minlen > maxbytes)
minlen = maxbytes;
memcpy(buffer, sslbuffer.getPtr(), minlen);
return minlen;
}
int WhatsappConnection::sentSSLCallback(int bytessent)
{
sslbuffer.popData(bytessent);
return bytessent;
}
void WhatsappConnection::receiveSSLCallback(char *buffer, int bytesrecv)
{
if (buffer != NULL and bytesrecv > 0)
sslbuffer_in.addData(buffer, bytesrecv);
this->processSSLIncomingData();
}
bool WhatsappConnection::hasSSLDataToSend()
{
return sslbuffer.size() != 0;
}
bool WhatsappConnection::closeSSLConnection()
{
return sslstatus == 0;
}
void WhatsappConnection::SSLCloseCallback()
{
sslstatus = 0;
}
bool WhatsappConnection::hasSSLConnection(std::string & host, int & port)
{
host = "";
port = 443;
if (sslstatus == 1)
for (unsigned int j = 0; j < uploadfile_queue.size(); j++)
if (uploadfile_queue[j].uploading) {
host = uploadfile_queue[j].host;
return true;
}
return false;
}
int WhatsappConnection::uploadProgress(int &rid, int &bs)
{
if (!(sslstatus == 1 or sslstatus == 2))
return 0;
int totalsize = 0;
for (unsigned int j = 0; j < uploadfile_queue.size(); j++)
if (uploadfile_queue[j].uploading) {
rid = uploadfile_queue[j].rid;
totalsize = uploadfile_queue[j].totalsize;
break;
}
bs = totalsize - sslbuffer.size();
if (bs < 0)
bs = 0;
return 1;
}
int WhatsappConnection::uploadComplete(int rid) {
for (unsigned int j = 0; j < uploadfile_queue.size(); j++)
if (rid == uploadfile_queue[j].rid)
return 0;
return 1;
}
void WhatsappConnection::subscribePresence(std::string user)
{
Tree request("presence", makeat({"type", "subscribe", "to", user}));
outbuffer = outbuffer + serialize_tree(&request);
}
void WhatsappConnection::queryStatuses()
{
Tree req("iq", makeat({"to", WHATSAPP_SERVER, "type", "get", "id", getNextIqId(), "xmlns", "status"}));
Tree stat("status");
for (std::map < std::string, Contact >::iterator iter = contacts.begin(); iter != contacts.end(); iter++)
{
stat.addChild(Tree("user", makeat({"jid", iter->first + "@" + whatsappserver})));
}
req.addChild(stat);
outbuffer = outbuffer + serialize_tree(&req);
}
std::string WhatsappConnection::syncContacts(std::vector < std::string > clist)
{
std::string uid = getNextIqId();
Tree req("iq", makeat({"id", uid, "type", "get", "xmlns", "urn:xmpp:whatsapp:sync"}));
Tree sync("sync", makeat({"sid", std::to_string(time(0)), "index", "0", "mode", "full", "context", "registration", "last", "true"}));
for (auto & u: clist) {
Tree t("user");
t.setData(u);
sync.addChild(t);
}
req.addChild(sync);
outbuffer = outbuffer + serialize_tree(&req);
return uid;
}
bool WhatsappConnection::getSyncResult(std::string uid, std::vector<std::string> & out)
{
if (sync_result.find(uid) == sync_result.end())
return false;
out = sync_result[uid];
sync_result.erase(uid);
return true;
}
void WhatsappConnection::gotTyping(std::string who, std::string tstat)
{
who = getusername(who);
if (contacts.find(who) != contacts.end()) {
contacts[who].typing = tstat;
user_typing.push_back(who);
}
}
void WhatsappConnection::notifyTyping(std::string who, int status)
{
std::string s = "paused";
if (status == 1)
s = "composing";
Tree mes("chatstate", makeat({"to", who + "@" + whatsappserver}));
mes.addChild(Tree(s));
outbuffer = outbuffer + serialize_tree(&mes);
}
void WhatsappConnection::account_info(unsigned long long &creation, unsigned long long &freeexp, std::string & status)
{
creation = std::stoull(account_creation);
freeexp = std::stoull(account_expiration);
status = account_status;
}
void WhatsappConnection::queryPreview(std::string user)
{
Tree req("iq", makeat({"id", getNextIqId(), "type", "get", "to", user, "xmlns", "w:profile:picture"}));
req.addChild(Tree("picture", makeat({"type", "preview"})));
outbuffer = outbuffer + serialize_tree(&req);
}
void WhatsappConnection::queryFullSize(std::string user)
{
Tree req("iq", makeat({"id", getNextIqId(), "type", "get", "to", user, "xmlns", "w:profile:picture"}));
req.addChild(Tree("picture"));
outbuffer = outbuffer + serialize_tree(&req);
}
void WhatsappConnection::send_avatar(const std::string & avatar, const std::string & avatarp)
{
Tree pic("picture"); pic.setData(avatar);
Tree prev("picture", makeat({"type", "preview"})); prev.setData(avatarp);
Tree req("iq", makeat({"id", "set_photo_"+getNextIqId(), "type", "set", "to", phone + "@" + whatsappserver, "xmlns", "w:profile:picture"}));
req.addChild(pic);
req.addChild(prev);
outbuffer = outbuffer + serialize_tree(&req);
}
bool WhatsappConnection::queryReceivedMessage(std::string & msgid, int & type, unsigned long long & t, std::string & sender)
{
if (received_messages.size() == 0) return false;
// Remove messages in the queue on read or delivered successfully
if (type == rRead || type == rDelivered) {
for (auto msg: queue_messages) {
if (msg->id == msgid) {
msg->retries = -1;
break;
}
}
}
msgid = received_messages[0].id;
type = received_messages[0].type;
t = received_messages[0].t;
sender = received_messages[0].from;
received_messages.erase(received_messages.begin());
return true;
}
std::string WhatsappConnection::getMessageId()
{
unsigned int t = time(NULL);
unsigned int mid = msgcounter++;
return std::to_string(t) + "-" + std::to_string(mid);
}
void WhatsappConnection::retryMessage(std::string id) {
// Look for the message in the queue and resend it on the plain :D
for (auto msg: queue_messages) {
if (msg->id == id) {
msg->axolotl = false;
msg->retries = 0;
// Re-query user keys just in case they've changed
sendGetCipherKeysFromUser(msg->from);
break;
}
}
// Process the message queue
processMsgQueue();
}
void WhatsappConnection::processMsgQueue() {
for (auto msg: queue_messages) {
if (msg->retries != 0) continue;
// Only processing messages that haven't been processed!
DataBuffer buf;
if (msg->axolotl && this->send_ciphered) {
uint64_t recepientId = JidAsInt(msg->from);
if (!axolotlStore->containsSession(recepientId, 1)) {
DEBUG_PRINT("Cannot find session " << recepientId);
// Schedule key retrieval, this message will go plaintext I'm afraid!
sendGetCipherKeysFromUser(msg->from);
msg->axolotl = false;
}
else {
DEBUG_PRINT("Session found!");
ChatMessage * txtmsg = dynamic_cast<ChatMessage*>(msg);
if (txtmsg) {
SessionCipher *cipher = getSessionCipher(recepientId);
std::shared_ptr<CiphertextMessage> ciphertext(cipher->encrypt(txtmsg->getProtoBuf().c_str()));
CipheredChatMessage cmsg(
this, msg->from, msg->t, msg->id, ciphertext->serialize(), txtmsg->author,
ciphertext->getType() == CiphertextMessage::WHISPER_TYPE ? "msg" : "pkmsg"
);
buf = cmsg.serialize();
// Put it in hold, just in case we have to retransmit it
msg->retries = 1;
}
}
}
// Plaintext!
if (!msg->axolotl || !this->send_ciphered) {
buf = msg->serialize();
msg->retries = -1;
}
outbuffer = outbuffer + buf;
}
// Clean up messages that are no longer needed
auto it = queue_messages.begin();
while (it != queue_messages.end()) {
if ((*it)->retries < 0)
it = queue_messages.erase(it);
else
it++;
}
}
void WhatsappConnection::sendVCard(const std::string msgid, const std::string to, const std::string name, const std::string vcard)
{
VCardMessage msg(this, to, time(NULL), msgid, nickname, name, vcard);
DataBuffer buf = msg.serialize();
outbuffer = outbuffer + buf;
}
void WhatsappConnection::sendChat(std::string msgid, std::string to, std::string message)
{
queue_messages.push_back(new ChatMessage(this, to, time(NULL), msgid, message, nickname));
processMsgQueue();
}
void WhatsappConnection::sendGroupChat(std::string msgid, std::string to, std::string message)
{
ChatMessage msg(this, to, time(NULL), msgid, message, nickname);
msg.server = "g.us";
DataBuffer buf = msg.serialize();
outbuffer = outbuffer + buf;
}
void WhatsappConnection::addContacts(std::vector < std::string > clist)
{
/* Insert the contacts to the contact list */
for (unsigned int i = 0; i < clist.size(); i++) {
if (contacts.find(clist[i]) == contacts.end())
contacts[clist[i]] = Contact(clist[i], true);
else
contacts[clist[i]].mycontact = true;
user_changes.push_back(clist[i]);
}
}
void WhatsappConnection::contactsUpdate() {
/* Query the profile pictures */
bool qstatus = false;
for (std::map < std::string, Contact >::iterator iter = contacts.begin(); iter != contacts.end(); iter++) {
if (not iter->second.subscribed) {
iter->second.subscribed = true;
this->subscribePresence(iter->first + "@" + whatsappserver);
this->queryPreview(iter->first + "@" + whatsappserver);
qstatus = true;
}
}
/* Query statuses */
if (qstatus)
this->queryStatuses();
}
unsigned char hexchars(char c1, char c2)
{
if (c1 >= '0' and c1 <= '9')
c1 -= '0';
else if (c1 >= 'A' and c1 <= 'F')
c1 = c1 - 'A' + 10;
else if (c1 >= 'a' and c1 <= 'f')
c1 = c1 - 'a' + 10;
if (c2 >= '0' and c2 <= '9')
c2 -= '0';
else if (c2 >= 'A' and c2 <= 'F')
c2 = c2 - 'A' + 10;
else if (c2 >= 'a' and c2 <= 'f')
c2 = c2 - 'a' + 10;
unsigned char r = c2 | (c1 << 4);
return r;
}
std::string UnicodeToUTF8(unsigned int c)
{
std::string ret;
if (c <= 0x7F)
ret += ((char)c);
else if (c <= 0x7FF) {
ret += ((char)(0xC0 | (c >> 6)));
ret += ((char)(0x80 | (c & 0x3F)));
} else if (c <= 0xFFFF) {
if (c >= 0xD800 and c <= 0xDFFF)
return ret; /* Invalid char */
ret += ((char)(0xE0 | (c >> 12)));
ret += ((char)(0x80 | ((c >> 6) & 0x3F)));
ret += ((char)(0x80 | (c & 0x3F)));
}
return ret;
}
std::string utf8_decode(std::string in)
{
std::string dec;
for (unsigned int i = 0; i < in.size(); i++) {
if (in[i] == '\\' and in[i + 1] == 'u') {
i += 2; /* Skip \u */
unsigned char hex1 = hexchars(in[i + 0], in[i + 1]);
unsigned char hex2 = hexchars(in[i + 2], in[i + 3]);
unsigned int uchar = (hex1 << 8) | hex2;
dec += UnicodeToUTF8(uchar);
i += 3;
} else if (in[i] == '\\' and in[i + 1] == '"') {
dec += '"';
i++;
} else
dec += in[i];
}
return dec;
}
std::string query_field(std::string work, std::string lo, bool integer = false)
{
size_t p = work.find("\"" + lo + "\"");
if (p == std::string::npos)
return "";
work = work.substr(p + ("\"" + lo + "\"").size());
p = work.find("\"");
if (integer)
p = work.find(":");
if (p == std::string::npos)
return "";
work = work.substr(p + 1);
p = 0;
while (p < work.size()) {
if (work[p] == '"' and(p == 0 or work[p - 1] != '\\'))
break;
p++;
}
if (integer) {
p = 0;
while (p < work.size()and work[p] >= '0' and work[p] <= '9')
p++;
}
if (p == std::string::npos)
return "";
work = work.substr(0, p);
return work;
}
std::string base64_encode_esp(unsigned char const *bytes_to_encode, unsigned int in_len);
void WhatsappConnection::updateFileUpload(std::string json)
{
DEBUG_PRINT("FILE UPLOAD:");
DEBUG_PRINT(json);
size_t offset = json.find("{");
if (offset == std::string::npos)
return;
json = json.substr(offset + 1);
/* Look for closure */
size_t cl = json.find("{");
if (cl == std::string::npos)
cl = json.size();
std::string work = json.substr(0, cl);
std::string url = query_field(work, "url");
std::string type = query_field(work, "type");
std::string size = query_field(work, "size");
std::string width = query_field(work, "width");
std::string height = query_field(work, "height");
std::string filehash = query_field(work, "filehash");
std::string mimetype = query_field(work, "mimetype");
std::string to, thumb, ip, mid;
for (unsigned int j = 0; j < uploadfile_queue.size(); j++)
if (uploadfile_queue[j].uploading and uploadfile_queue[j].hash == filehash) {
to = uploadfile_queue[j].to;
thumb = uploadfile_queue[j].thumbnail;
ip = uploadfile_queue[j].ip;
mid = uploadfile_queue[j].msgid;
uploadfile_queue.erase(uploadfile_queue.begin() + j);
break;
}
/* Send the message with the URL :) */
ImageMessage msg(this, to, time(NULL), mid, "author", url, "", ip,
std::stoi(width), std::stoi(height), std::stoi(size), "encoding",
filehash, mimetype, thumb);
DataBuffer buf = msg.serialize();
outbuffer = outbuffer + buf;
}
/* Quick and dirty way to parse the HTTP responses */
void WhatsappConnection::processSSLIncomingData()
{
/* Parse HTTPS headers and JSON body */
if (sslstatus == 1)
sslstatus++;
if (sslstatus == 2) {
/* Look for the first line, to be 200 OK */
std::string toparse((char *)sslbuffer_in.getPtr(), sslbuffer_in.size());
if (toparse.find("\r\n") != std::string::npos) {
std::string fl = toparse.substr(0, toparse.find("\r\n"));
if (fl.find("200") == std::string::npos)
goto abortStatus;
if (toparse.find("\r\n\r\n") != std::string::npos) {
std::string headers = toparse.substr(0, toparse.find("\r\n\r\n") + 4);
std::string content = toparse.substr(toparse.find("\r\n\r\n") + 4);
/* Look for content length */
if (headers.find("Content-Length:") != std::string::npos) {
std::string clen = headers.substr(headers.find("Content-Length:") + strlen("Content-Length:"));
clen = clen.substr(0, clen.find("\r\n"));
while (clen.size() > 0 and clen[0] == ' ')
clen = clen.substr(1);
unsigned int contentlength = std::stoi(clen);
if (contentlength == content.size()) {
/* Now we can proceed to parse the JSON */
updateFileUpload(content);
sslstatus = 0;
}
}
}
}
}
processUploadQueue();
return;
abortStatus:
sslstatus = 0;
processUploadQueue();
return;
}
std::string WhatsappConnection::generateUploadPOST(t_fileupload * fu)
{
std::string file_buffer;
FILE *fd = fopen(fu->file.c_str(), "rb");
int read = 0;
do {
char buf[1024];
read = fread(buf, 1, 1024, fd);
file_buffer += std::string(buf, read);
} while (read > 0);
fclose(fd);
std::string mime_type = std::string(file_mime_type(fu->file.c_str(), file_buffer.c_str(), file_buffer.size()));
std::string encoded_name = "TODO..:";
std::string ret;
/* BODY HEAD */
ret += "--zzXXzzYYzzXXzzQQ\r\n";
ret += "Content-Disposition: form-data; name=\"to\"\r\n\r\n";
ret += fu->to + "\r\n";
ret += "--zzXXzzYYzzXXzzQQ\r\n";
ret += "Content-Disposition: form-data; name=\"from\"\r\n\r\n";
ret += fu->from + "\r\n";
ret += "--zzXXzzYYzzXXzzQQ\r\n";
ret += "Content-Disposition: form-data; name=\"file\"; filename=\"" + encoded_name + "\"\r\n";
ret += "Content-Type: " + mime_type + "\r\n\r\n";
/* File itself */
ret += file_buffer;
/* TAIL */
ret += "\r\n--zzXXzzYYzzXXzzQQ--\r\n";
std::string post;
post += "POST " + fu->uploadurl + "\r\n";
post += "Content-Type: multipart/form-data; boundary=zzXXzzYYzzXXzzQQ\r\n";
post += "Host: " + fu->host + "\r\n";
post += WHATSAPP_USER_AGENT;
post += "Content-Length: " + std::to_string(ret.size()) + "\r\n\r\n";
std::string all = post + ret;
DEBUG_PRINT(post);
fu->totalsize = file_buffer.size();
return all;
}
void WhatsappConnection::processUploadQueue()
{
/* At idle check for new uploads */
if (sslstatus == 0) {
for (unsigned int j = 0; j < uploadfile_queue.size(); j++) {
if (uploadfile_queue[j].uploadurl != "" and not uploadfile_queue[j].uploading) {
uploadfile_queue[j].uploading = true;
std::string postq = generateUploadPOST(&uploadfile_queue[j]);
sslbuffer_in.clear();
sslbuffer.clear();
sslbuffer.addData(postq.c_str(), postq.size());
sslstatus = 1;
break;
}
}
}
}
void WhatsappConnection::processIncomingData()
{
/* Parse the data and create as many Trees as possible */
std::vector < Tree > treelist;
if (inbuffer.size() >= 3) {
/* Consume as many trees as possible */
bool ok;
do {
Tree t;
ok = parse_tree(&inbuffer, t);
if (ok)
treelist.push_back(t);
} while (ok and inbuffer.size() >= 3);
}
/* Now process the tree list! */
//for (unsigned int i = 0; i < treelist.size(); i++) {
for (auto & tl : treelist) {
DEBUG_PRINT( "Tree read:\n" );
DEBUG_PRINT( tl.toString() );
if (tl.getTag() == "challenge") {
/* Generate a session key using the challege & the password */
assert(conn_status == SessionWaitingChallenge);
KeyGenerator::generateKeysV14(password, tl.getData().c_str(), tl.getData().size(), (char *)this->session_key);
in = new RC4Decoder(&session_key[20*2], 20, 768);
out = new RC4Decoder(&session_key[20*0], 20, 768);
conn_status = SessionWaitingAuthOK;
challenge_data = tl.getData();
this->sendResponse();
} else if (tl.getTag() == "success") {
/* Notifies the success of the auth */
conn_status = SessionConnected;
if (tl.hasAttribute("status"))
this->account_status = tl["status"];
if (tl.hasAttribute("kind"))
this->account_type = tl["kind"];
if (tl.hasAttribute("expiration"))
this->account_expiration = tl["expiration"];
if (tl.hasAttribute("creation"))
this->account_creation = tl["creation"];
this->notifyMyPresence();
this->updatePrivacy();
this->sendInitial(); // Seems to trigger an error IQ response
this->updateGroups();
this->updateBlists();
if (axolotlStore->countPreKeys() == 0)
this->sendEncrypt(true);
DEBUG_PRINT("Logged in!!!");
} else if (tl.getTag() == "failure") {
std::string reason = "unknown";
if (tl.hasChild("not-authorized"))
reason = "not-authorized";
if (conn_status == SessionWaitingAuthOK)
this->notifyError(errorAuth, reason);
else
this->notifyError(errorUnknown, reason);
} else if (tl.getTag() == "notification") {
DataBuffer reply = generateResponse( tl["from"], tl["type"], tl["id"] );
outbuffer = outbuffer + reply;
if (tl.hasAttributeValue("type", "participant") ||
tl.hasAttributeValue("type", "owner") ||
tl.hasAttributeValue("type", "w:gp2") ) {
/* If the nofitication comes from a group, assume we have to reload groups ;) */