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
|
/*
WhatsAppWeb plugin for Miranda NG
Copyright © 2019 George Hazan
*/
#include "stdafx.h"
WAUser* WhatsAppProto::FindUser(const char *szId)
{
mir_cslock lck(m_csUsers);
auto *tmp = (WAUser *)_alloca(sizeof(WAUser));
tmp->szId = (char*)szId;
return m_arUsers.find(tmp);
}
WAUser* WhatsAppProto::AddUser(const char *szId, bool bTemporary)
{
auto *pUser = FindUser(szId);
if (pUser != nullptr)
return pUser;
MCONTACT hContact = db_add_contact();
Proto_AddToContact(hContact, m_szModuleName);
setString(hContact, DBKEY_ID, szId);
pUser = new WAUser(hContact, mir_strdup(szId));
if (bTemporary)
Contact::RemoveFromList(hContact);
if (m_wszDefaultGroup)
Clist_SetGroup(hContact, m_wszDefaultGroup);
mir_cslock lck(m_csUsers);
m_arUsers.insert(pUser);
return pUser;
}
/////////////////////////////////////////////////////////////////////////////////////////
bool WhatsAppProto::getBlob(const char *szSetting, MBinBuffer &buf)
{
DBVARIANT dbv = { DBVT_BLOB };
if (db_get(0, m_szModuleName, szSetting, &dbv))
return false;
buf.assign(dbv.pbVal, dbv.cpbVal);
db_free(&dbv);
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////
// sends a piece of JSON to a server via a websocket, masked
int WhatsAppProto::WSSend(const MessageLite &msg, WA_PKT_HANDLER /*pHandler*/, void * /*pUserInfo*/)
{
if (m_hServerConn == nullptr)
return -1;
// debugLogA("Sending packet: %s", msg..DebugString().c_str());
int cbLen = msg.ByteSize();
ptrA protoBuf((char *)mir_alloc(cbLen));
msg.SerializeToArray(protoBuf, cbLen);
MBinBuffer payload;
m_noise->encodeFrame(protoBuf, cbLen, payload);
WebSocket_SendBinary(m_hServerConn, payload.data(), payload.length());
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////
static char zeroData[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int WhatsAppProto::WSSendNode(const char *pszPrefix, int flags, WANode &node, WA_PKT_HANDLER pHandler)
{
if (m_hServerConn == nullptr)
return 0;
{
char str[100];
_i64toa(_time64(0), str, 10);
node.addAttr("epoch", str);
CMStringA szText;
node.print(szText);
debugLogA("Sending binary node: %s", szText.c_str());
}
WAWriter writer;
writer.writeNode(&node);
// AES block size = 16 bytes, let's expand data to block size boundary
size_t rest = writer.body.length() % 16;
if (rest != 0)
writer.body.append(zeroData, 16 - rest);
BYTE iv[16];
Utils_GetRandom(iv, sizeof(iv));
// allocate the buffer of the same size + 32 bytes for temporary operations
MBinBuffer enc;
enc.assign(writer.body.data(), writer.body.length());
enc.append(mac_key.data(), mac_key.length());
int enc_len = 0, final_len = 0;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (BYTE *)enc_key.data(), iv);
EVP_EncryptUpdate(ctx, (BYTE *)enc.data(), &enc_len, (BYTE *)writer.body.data(), (int)writer.body.length());
EVP_EncryptFinal_ex(ctx, (BYTE *)enc.data() + enc_len, &final_len);
EVP_CIPHER_CTX_free(ctx);
// build the resulting buffer of the following structure:
// - packet prefix
// - 32 bytes of HMAC
// - 16 bytes of iv
// - rest of encoded data
BYTE hmac[32];
unsigned int hmac_len = 32;
HMAC(EVP_sha256(), mac_key.data(), (int)mac_key.length(), (BYTE *)enc.data(), enc_len, hmac, &hmac_len);
int pktId = ++m_iPktNumber;
if (pHandler != nullptr) {
auto *pReq = new WARequest;
pReq->pHandler = pHandler;
pReq->szPrefix = pszPrefix;
mir_cslock lck(m_csPacketQueue);
m_arPacketQueue.insert(pReq);
}
char postPrefix[3] = {',', 0, (char)flags};
MBinBuffer ret;
ret.append(pszPrefix, strlen(pszPrefix));
ret.append(postPrefix, sizeof(postPrefix));
ret.append(hmac, sizeof(hmac));
ret.append(iv, sizeof(iv));
ret.append(enc.data(), enc_len);
WebSocket_SendBinary(m_hServerConn, ret.data(), ret.length());
return pktId;
}
/////////////////////////////////////////////////////////////////////////////////////////
bool WhatsAppProto::decryptBinaryMessage(size_t cbSize, const void *buf, MBinBuffer &res)
{
if (cbSize <= 32)
return false;
// validate message first
{
unsigned int md_len = 32;
BYTE md[32];
HMAC(EVP_sha256(), mac_key.data(), (int)mac_key.length(), (unsigned char *)buf+32, (int)cbSize-32, md, &md_len);
if (memcmp(buf, md, sizeof(md))) {
debugLogA("Message cannot be decrypted, check your keys");
return false;
}
}
// okay, let's decrypt this thing
auto *pBuf = (const unsigned char *)buf;
{
BYTE iv[16];
memcpy(iv, pBuf + 32, sizeof(iv));
res.assign(pBuf + 48, cbSize - 48);
res.append(mac_key.data(), 32); // reserve 32 more bytes for temp data
int dec_len = 0, final_len = 0;
EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (BYTE*)enc_key.data(), iv);
EVP_DecryptUpdate(ctx, (BYTE*)res.data(), &dec_len, pBuf + 48, (int)cbSize - 48);
EVP_DecryptFinal_ex(ctx, (BYTE*)res.data() + dec_len, &final_len);
EVP_CIPHER_CTX_free(ctx);
}
return true;
}
/////////////////////////////////////////////////////////////////////////////////////////
// WANoise members
static uint8_t intro_header[] = { 87, 65, 6, DICT_VERSION };
static uint8_t noise_init[] = "Noise_XX_25519_AESGCM_SHA256\0\0\0\0";
WANoise::WANoise()
{
salt.assign(noise_init, 32);
encKey.assign(noise_init, 32);
decKey.assign(noise_init, 32);
// generate ephemeral keys: public & private
ec_key_pair *pKeys;
curve_generate_key_pair(g_plugin.pCtx, &pKeys);
auto *pPubKey = ec_key_pair_get_public(pKeys);
pubKey.assign(pPubKey->data, sizeof(pPubKey->data));
auto *pPrivKey = ec_key_pair_get_private(pKeys);
privKey.assign(pPrivKey->data, sizeof(pPrivKey->data));
ec_key_pair_destroy(pKeys);
// prepare hash
memcpy(hash, noise_init, 32);
updateHash(intro_header, 4);
updateHash(pubKey.data(), pubKey.length());
}
void WANoise::deriveKey(const void *pData, size_t cbLen, MBinBuffer &write, MBinBuffer &read)
{
auto *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
EVP_PKEY_derive_init(pctx);
EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256());
EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt.data(), (int)salt.length());
EVP_PKEY_CTX_set1_hkdf_key(pctx, pData, (int)cbLen);
size_t outlen = 64;
uint8_t out[64];
EVP_PKEY_derive(pctx, out, &outlen);
EVP_PKEY_CTX_free(pctx);
write.assign(out, 32);
read.assign(out + 32, 32);
}
void WANoise::mixIntoKey(const void *pData, size_t cbLen)
{
deriveKey(pData, cbLen, salt, encKey);
decKey.assign(encKey.data(), encKey.length());
readCounter = writeCounter = 0;
}
bool WANoise::decodeFrame(const void *pData, size_t cbLen)
{
if (!bInitFinished) {
proto::HandshakeMessage msg;
if (msg.ParseFromArray(pData, (int)cbLen)) {
auto &ephemeral = msg.serverhello().ephemeral();
auto &static_ = msg.serverhello().static_();
auto &payload = msg.serverhello().payload();
updateHash(ephemeral.c_str(), ephemeral.size());
mixIntoKey(ephemeral.c_str(), ephemeral.size());
}
return true;
}
return false;
}
void WANoise::encodeFrame(const void *pData, size_t cbLen, MBinBuffer &res)
{
if (!bSendIntro) {
bSendIntro = true;
res.append(intro_header, 4);
}
uint8_t buf[3];
size_t foo = cbLen;
for (int i = 0; i < 3; i++) {
buf[2 - i] = foo & 0xFF;
foo >>= 8;
}
res.append(buf, 3);
res.append(pData, cbLen);
}
void WANoise::updateHash(const void *pData, size_t cbLen)
{
if (bInitFinished)
return;
SHA256_CTX ctx;
SHA256_Init(&ctx);
SHA256_Update(&ctx, hash, sizeof(hash));
SHA256_Update(&ctx, pData, cbLen);
SHA256_Final(hash, &ctx);
}
/////////////////////////////////////////////////////////////////////////////////////////
// WANode members
WANode::WANode()
{}
WANode::~WANode()
{
for (auto &p: attrs)
delete p;
for (auto &p: children)
delete p;
}
CMStringA WANode::getAttr(const char *pszFieldName) const
{
for (auto &p: attrs)
if (p->name == pszFieldName)
return p->value;
return "";
}
void WANode::addAttr(const char *pszName, const char *pszValue)
{
attrs.push_back(new Attr(pszName, pszValue));
}
void WANode::print(CMStringA &dest, int level) const
{
for (int i = 0; i < level; i++)
dest.Append(" ");
dest.AppendFormat("<%s ", title.c_str());
for (auto &p: attrs)
dest.AppendFormat("%s=\"%s\" ", p->name.c_str(), p->value.c_str());
dest.Truncate(dest.GetLength() - 1);
if (content.isEmpty() && children.empty()) {
dest.Append("/>\n");
return;
}
dest.Append(">");
if (!content.isEmpty()) {
ptrA tmp((char *)mir_alloc(content.length() * 2 + 1));
bin2hex(content.data(), content.length(), tmp);
dest.AppendFormat("%s", tmp.get());
}
if (!children.empty()) {
dest.Append("\n");
for (auto &p : children)
p->print(dest, level + 1);
for (int i = 0; i < level; i++)
dest.Append(" ");
}
dest.AppendFormat("</%s>\n", title.c_str());
}
/////////////////////////////////////////////////////////////////////////////////////////
// WAReader class members
bool WAReader::readAttributes(WANode *pNode, int count)
{
if (count == 0)
return true;
for (int i = 0; i < count; i++) {
CMStringA name = readString(readInt8());
if (name.IsEmpty())
return false;
CMStringA value = readString(readInt8());
if (value.IsEmpty())
return false;
pNode->addAttr(name, value);
}
return true;
}
uint32_t WAReader::readInt20()
{
if (m_limit - m_buf < 3)
return 0;
int ret = (int(m_buf[0] & 0x0F) << 16) + (int(m_buf[1]) << 8) + int(m_buf[2]);
m_buf += 3;
return ret;
}
uint32_t WAReader::readIntN(int n)
{
if (m_limit - m_buf < n)
return 0;
uint32_t res = 0;
for (int i = 0; i < n; i++, m_buf++)
res = (res <<= 8) + *m_buf;
return res;
}
bool WAReader::readList(WANode *pParent, int tag)
{
int size = readListSize(tag);
if (size == -1)
return false;
for (int i = 0; i < size; i++) {
WANode *pNew = readNode();
if (pNew == nullptr)
return false;
pParent->children.push_back(pNew);
}
return true;
}
int WAReader::readListSize(int tag)
{
switch (tag) {
case LIST_EMPTY:
return 0;
case LIST_8:
return readInt8();
case LIST_16:
return readInt16();
}
return -1;
}
WANode* WAReader::readNode()
{
int listSize = readListSize(readInt8());
if (listSize == -1)
return nullptr;
int descrTag = readInt8();
if (descrTag == STREAM_END)
return nullptr;
CMStringA name = readString(descrTag);
if (name.IsEmpty())
return nullptr;
std::unique_ptr<WANode> ret(new WANode());
ret->title = name.c_str();
if (!readAttributes(ret.get(), (listSize-1)>>1))
return nullptr;
if ((listSize % 2) == 1)
return ret.release();
int size, tag = readInt8();
switch (tag) {
case LIST_EMPTY: case LIST_8: case LIST_16:
readList(ret.get(), tag);
break;
case BINARY_8:
size = readInt8();
LBL_Binary:
if (m_limit - m_buf < size)
return false;
ret->content.assign((void*)m_buf, size);
m_buf += size;
break;
case BINARY_20:
size = readInt20();
goto LBL_Binary;
case BINARY_32:
size = readInt32();
goto LBL_Binary;
default:
CMStringA str = readString(tag);
ret->content.assign(str.GetBuffer(), str.GetLength() + 1);
}
return ret.release();
}
/////////////////////////////////////////////////////////////////////////////////////////
static int unpackHex(int val)
{
if (val < 0 || val > 15)
return -1;
return (val < 10) ? val + '0' : val - 10 + 'A';
}
static int unpackNibble(int val)
{
if (val < 0 || val > 15)
return -1;
switch (val) {
case 10: return '-';
case 11: return '.';
case 15: return 0;
default: return '0' + val;
}
}
CMStringA WAReader::readPacked(int tag)
{
int startByte = readInt8();
bool bTrim = false;
if (startByte & 0x80) {
startByte &= ~0x80;
bTrim = true;
}
CMStringA ret;
for (int i = 0; i < startByte; i++) {
BYTE b = readInt8();
int lower = (tag == NIBBLE_8) ? unpackNibble(b >> 4) : unpackHex(b >> 4);
if (lower == -1)
return "";
int higher = (tag == NIBBLE_8) ? unpackNibble(b & 0x0F) : unpackHex(b & 0x0F);
if (higher == -1)
return "";
ret.AppendChar(lower);
ret.AppendChar(higher);
}
if (bTrim && !ret.IsEmpty())
ret.Truncate(ret.GetLength() - 1);
return ret;
}
/////////////////////////////////////////////////////////////////////////////////////////
static char *SingleByteTokens[] = {
"", "", "", "200", "400", "404", "500", "501", "502", "action", "add",
"after", "archive", "author", "available", "battery", "before", "body",
"broadcast", "chat", "clear", "code", "composing", "contacts", "count",
"create", "debug", "delete", "demote", "duplicate", "encoding", "error",
"false", "filehash", "from", "g.us", "group", "groups_v2", "height", "id",
"image", "in", "index", "invis", "item", "jid", "kind", "last", "leave",
"live", "log", "media", "message", "mimetype", "missing", "modify", "name",
"notification", "notify", "out", "owner", "participant", "paused",
"picture", "played", "presence", "preview", "promote", "query", "raw",
"read", "receipt", "received", "recipient", "recording", "relay",
"remove", "response", "resume", "retry", "s.whatsapp.net", "seconds",
"set", "size", "status", "subject", "subscribe", "t", "text", "to", "true",
"type", "unarchive", "unavailable", "url", "user", "value", "web", "width",
"mute", "read_only", "admin", "creator", "short", "update", "powersave",
"checksum", "epoch", "block", "previous", "409", "replaced", "reason",
"spam", "modify_tag", "message_info", "delivery", "emoji", "title",
"description", "canonical-url", "matched-text", "star", "unstar",
"media_key", "filename", "identity", "unread", "page", "page_count",
"search", "media_message", "security", "call_log", "profile", "ciphertext",
"invite", "gif", "vcard", "frequent", "privacy", "blacklist", "whitelist",
"verify", "location", "document", "elapsed", "revoke_invite", "expiration",
"unsubscribe", "disable", "vname", "old_jid", "new_jid", "announcement",
"locked", "prop", "label", "color", "call", "offer", "call-id",
"quick_reply", "sticker", "pay_t", "accept", "reject", "sticker_pack",
"invalid", "canceled", "missed", "connected", "result", "audio",
"video", "recent" };
CMStringA WAReader::readString(int tag)
{
if (tag >= 3 && tag < _countof(SingleByteTokens)) {
CMStringA ret = SingleByteTokens[tag];
if (ret == "s.whatsapp.net")
return "c.us";
return ret;
}
switch (tag) {
// case DICTIONARY_0: return dict0[readInt8()];
// case DICTIONARY_1: return dict1[readInt8()];
// case DICTIONARY_2: return dict2[readInt8()];
// case DICTIONARY_3: return dict3[readInt8()];
case LIST_EMPTY:
return "";
case BINARY_8:
return readStringFromChars(readInt8());
case BINARY_20:
return readStringFromChars(readInt20());
case BINARY_32:
return readStringFromChars(readInt32());
case NIBBLE_8:
case HEX_8:
return readPacked(tag);
case JID_PAIR:
CMStringA s1 = readString(readInt8());
if (s1.IsEmpty())
break;
CMStringA s2 = readString(readInt8());
if (s2.IsEmpty())
break;
return CMStringA(FORMAT, "%s@%s", s1.c_str(), s2.c_str());
}
// error
return "";
}
CMStringA WAReader::readStringFromChars(int size)
{
if (m_limit - m_buf < size)
return "";
CMStringA ret((char*)m_buf, size);
m_buf += size;
return ret;
}
/////////////////////////////////////////////////////////////////////////////////////////
// WAWriter class members
void WAWriter::writeByte(uint8_t b)
{
body.append(&b, 1);
}
void WAWriter::writeIntN(int value, int n)
{
for (int i = n - 1; i >= 0; i--)
writeByte((value >> i * 8) & 0xFF);
}
void WAWriter::writeInt20(int value)
{
writeByte((value >> 16) & 0xFF);
writeByte((value >> 8) & 0xFF);
writeByte(value & 0xFF);
}
void WAWriter::writeLength(int value)
{
if (value >= (1 << 20)) {
writeByte(BINARY_32);
writeInt32(value);
}
else if (value >= 256) {
writeByte(BINARY_20);
writeInt20(value);
}
else {
writeByte(BINARY_8);
writeInt8(value);
}
}
void WAWriter::writeListSize(int length)
{
if (length == 0)
writeByte(LIST_EMPTY);
else if (length < 256) {
writeByte(LIST_8);
writeInt8(length);
}
else {
writeByte(LIST_16);
writeInt16(length);
}
}
void WAWriter::writeNode(const WANode *pNode)
{
int numAttrs = (int)pNode->attrs.size();
int hasContent = pNode->content.length() != 0;
writeListSize(2*numAttrs + 1 + hasContent);
writeString(pNode->title.c_str());
// write attributes
for (auto &it : pNode->attrs) {
if (it->value.IsEmpty())
continue;
writeString(it->name.c_str());
writeString(it->value.c_str());
}
// write contents
if (pNode->content.length()) {
writeLength((int)pNode->content.length());
body.append(pNode->content.data(), pNode->content.length());
}
// write children
if (pNode->children.size()) {
writeListSize((int)pNode->children.size());
for (auto &it : pNode->children)
writeNode(it);
}
}
void WAWriter::writeString(const char *str, bool bRaw)
{
if (!bRaw && !mir_strcmp(str, "c.us")) {
writeToken("s.whatsapp.net");
return;
}
if (writeToken(str))
return;
auto *pszDelimiter = strchr(str, '@');
if (pszDelimiter) {
writeByte(JID_PAIR);
if (pszDelimiter == str) // empty jid
writeByte(LIST_EMPTY);
else
writePacked(CMStringA(str, int(pszDelimiter - str)));
}
else {
int len = (int)strlen(str);
writeLength(len);
body.append(str, len);
}
}
bool WAWriter::writeToken(const char *str)
{
for (auto &it : SingleByteTokens)
if (!strcmp(str, it)) {
writeByte(int(&it - SingleByteTokens));
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////////////////
static BYTE packNibble(char c)
{
if (c >= '0' && c <= '9')
return c - '0';
switch (c) {
case '-': return 10;
case '.': return 11;
case 0: return 15;
}
return -1;
}
static BYTE packHex(char c)
{
if (c == 0)
return 15;
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'A' && c <= 'F')
return c - 'A';
if (c >= 'a' && c <= 'f')
return c - 'a';
return -1;
}
static BYTE packPair(int type, char c1, char c2)
{
BYTE b1 = (type == NIBBLE_8) ? packNibble(c1) : packHex(c1);
BYTE b2 = (type == NIBBLE_8) ? packNibble(c2) : packHex(c2);
return (b1 << 4) + b2;
}
void WAWriter::writePacked(const CMStringA &str)
{
if (str.GetLength() > 254)
return;
// all symbols of str can be a nibble?
int type = (strspn(str, "0123456789-.") == str.GetLength()) ? NIBBLE_8 : HEX_8;
int len = str.GetLength() / 2;
BYTE firstByte = (len % 2) == 0 ? 0 : 0x80;
writeByte(firstByte | len);
const char *p = str;
for (int i = 0; i < len; i++, p += 2)
writeByte(packPair(type, p[0], p[1]));
if (firstByte != 0)
writeByte(packPair(type, p[0], 0));
}
|