forked from grishka/libtgvoip
-
Notifications
You must be signed in to change notification settings - Fork 2
/
VoIPController.cpp
3200 lines (2980 loc) · 96.4 KB
/
VoIPController.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
//
// libtgvoip is free and unencumbered public domain software.
// For more information, see http://unlicense.org or the UNLICENSE file
// you should have received with this source code distribution.
//
#ifndef _WIN32
#include <unistd.h>
#include <sys/time.h>
#endif
#include <errno.h>
#include <string.h>
#include <wchar.h>
#include "VoIPController.h"
#include "logging.h"
#include "threading.h"
#include "Buffers.h"
#include "OpusEncoder.h"
#include "OpusDecoder.h"
#include "VoIPServerConfig.h"
#include "PrivateDefines.h"
#include <assert.h>
#include <time.h>
#include <math.h>
#include <exception>
#include <stdexcept>
#include <algorithm>
inline int pad4(int x){
int r=PAD4(x);
if(r==4)
return 0;
return r;
}
using namespace tgvoip;
using namespace std;
#ifdef __APPLE__
#include "os/darwin/AudioUnitIO.h"
#include <mach/mach_time.h>
double VoIPController::machTimebase=0;
uint64_t VoIPController::machTimestart=0;
#endif
#ifdef _WIN32
int64_t VoIPController::win32TimeScale = 0;
bool VoIPController::didInitWin32TimeScale = false;
#endif
#ifndef TGVOIP_USE_CUSTOM_CRYPTO
extern "C" {
#include <openssl/sha.h>
#include <openssl/aes.h>
#include <openssl/modes.h>
#include <openssl/rand.h>
}
void tgvoip_openssl_aes_ige_encrypt(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv){
AES_KEY akey;
AES_set_encrypt_key(key, 32*8, &akey);
AES_ige_encrypt(in, out, length, &akey, iv, AES_ENCRYPT);
}
void tgvoip_openssl_aes_ige_decrypt(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv){
AES_KEY akey;
AES_set_decrypt_key(key, 32*8, &akey);
AES_ige_encrypt(in, out, length, &akey, iv, AES_DECRYPT);
}
void tgvoip_openssl_rand_bytes(uint8_t* buffer, size_t len){
RAND_bytes(buffer, len);
}
void tgvoip_openssl_sha1(uint8_t* msg, size_t len, uint8_t* output){
SHA1(msg, len, output);
}
void tgvoip_openssl_sha256(uint8_t* msg, size_t len, uint8_t* output){
SHA256(msg, len, output);
}
void tgvoip_openssl_aes_ctr_encrypt(uint8_t* inout, size_t length, uint8_t* key, uint8_t* iv, uint8_t* ecount, uint32_t* num){
AES_KEY akey;
AES_set_encrypt_key(key, 32*8, &akey);
CRYPTO_ctr128_encrypt(inout, inout, length, &akey, iv, ecount, num, (block128_f) AES_encrypt);
}
void tgvoip_openssl_aes_cbc_encrypt(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv){
AES_KEY akey;
AES_set_encrypt_key(key, 256, &akey);
AES_cbc_encrypt(in, out, length, &akey, iv, AES_ENCRYPT);
}
void tgvoip_openssl_aes_cbc_decrypt(uint8_t* in, uint8_t* out, size_t length, uint8_t* key, uint8_t* iv){
AES_KEY akey;
AES_set_decrypt_key(key, 256, &akey);
AES_cbc_encrypt(in, out, length, &akey, iv, AES_DECRYPT);
}
CryptoFunctions VoIPController::crypto={
tgvoip_openssl_rand_bytes,
tgvoip_openssl_sha1,
tgvoip_openssl_sha256,
tgvoip_openssl_aes_ige_encrypt,
tgvoip_openssl_aes_ige_decrypt,
tgvoip_openssl_aes_ctr_encrypt,
tgvoip_openssl_aes_cbc_encrypt,
tgvoip_openssl_aes_cbc_decrypt
};
#else
CryptoFunctions VoIPController::crypto; // set it yourself upon initialization
#endif
extern FILE* tgvoipLogFile;
VoIPController::VoIPController() : activeNetItfName(""),
currentAudioInput("default"),
currentAudioOutput("default"),
outgoingPacketsBufferPool(1024, 20),
proxyAddress(""),
proxyUsername(""),
proxyPassword(""){
seq=1;
lastRemoteSeq=0;
state=STATE_WAIT_INIT;
audioInput=NULL;
audioOutput=NULL;
encoder=NULL;
audioOutStarted=false;
audioTimestampIn=0;
audioTimestampOut=0;
stopping=false;
sendQueue=new BlockingQueue<PendingOutgoingPacket>(21);
memset(recvPacketTimes, 0, sizeof(double)*32);
memset(&stats, 0, sizeof(TrafficStats));
lastRemoteAckSeq=0;
lastSentSeq=0;
recvLossCount=0;
packetsReceived=0;
waitingForAcks=false;
networkType=NET_TYPE_UNKNOWN;
echoCanceller=NULL;
dontSendPackets=0;
micMuted=false;
currentEndpoint=NULL;
waitingForRelayPeerInfo=false;
allowP2p=true;
dataSavingMode=false;
publicEndpointsReqTime=0;
connectionInitTime=0;
lastRecvPacketTime=0;
dataSavingRequestedByPeer=false;
peerVersion=0;
conctl=new CongestionControl();
prevSendLossCount=0;
receivedInit=false;
receivedInitAck=false;
peerPreferredRelay=NULL;
statsDump=NULL;
useTCP=false;
useUDP=true;
didAddTcpRelays=false;
udpPingCount=0;
lastUdpPingTime=0;
openingTcpSocket=NULL;
proxyProtocol=PROXY_NONE;
proxyPort=0;
resolvedProxyAddress=NULL;
selectCanceller=SocketSelectCanceller::Create();
udpSocket=NetworkSocket::Create(PROTO_UDP);
realUdpSocket=udpSocket;
udpConnectivityState=UDP_UNKNOWN;
echoCancellationStrength=1;
outputAGC=NULL;
outputAGCEnabled=false;
peerCapabilities=0;
callbacks={0};
didReceiveGroupCallKey=false;
didReceiveGroupCallKeyAck=false;
didSendGroupCallKey=false;
didSendUpgradeRequest=false;
didInvokeUpgradeCallback=false;
connectionMaxLayer=0;
useMTProto2=false;
setCurrentEndpointToTCP=false;
useIPv6=false;
peerIPv6Available=false;
shittyInternetMode=false;
didAddIPv6Relays=false;
didSendIPv6Endpoint=false;
sendThread=NULL;
recvThread=NULL;
maxAudioBitrate=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_max_bitrate", 20000);
maxAudioBitrateGPRS=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_max_bitrate_gprs", 8000);
maxAudioBitrateEDGE=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_max_bitrate_edge", 16000);
maxAudioBitrateSaving=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_max_bitrate_saving", 8000);
initAudioBitrate=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_init_bitrate", 16000);
initAudioBitrateGPRS=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_init_bitrate_gprs", 8000);
initAudioBitrateEDGE=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_init_bitrate_edge", 8000);
initAudioBitrateSaving=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_init_bitrate_saving", 8000);
audioBitrateStepIncr=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_bitrate_step_incr", 1000);
audioBitrateStepDecr=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_bitrate_step_decr", 1000);
minAudioBitrate=(uint32_t) ServerConfig::GetSharedInstance()->GetInt("audio_min_bitrate", 8000);
relaySwitchThreshold=ServerConfig::GetSharedInstance()->GetDouble("relay_switch_threshold", 0.8);
p2pToRelaySwitchThreshold=ServerConfig::GetSharedInstance()->GetDouble("p2p_to_relay_switch_threshold", 0.6);
relayToP2pSwitchThreshold=ServerConfig::GetSharedInstance()->GetDouble("relay_to_p2p_switch_threshold", 0.8);
reconnectingTimeout=ServerConfig::GetSharedInstance()->GetDouble("reconnecting_state_timeout", 2.0);
#ifdef __APPLE__
machTimestart=0;
#endif
shared_ptr<Stream> stm=make_shared<Stream>();
stm->id=1;
stm->type=STREAM_TYPE_AUDIO;
stm->codec=CODEC_OPUS;
stm->enabled=1;
stm->frameDuration=60;
outgoingStreams.push_back(stm);
/*Stream vstm={0};
vstm.id=2;
vstm.type=STREAM_TYPE_VIDEO;
vstm.codec=CODEC_AVC;
vstm.enabled=1;
outgoingStreams.push_back(vstm);*/
}
VoIPController::~VoIPController(){
LOGD("Entered VoIPController::~VoIPController");
if(!stopping){
LOGE("!!!!!!!!!!!!!!!!!!!! CALL controller->Stop() BEFORE DELETING THE CONTROLLER OBJECT !!!!!!!!!!!!!!!!!!!!!!!1");
abort();
}
LOGD("before close socket");
if(udpSocket)
delete udpSocket;
if(udpSocket!=realUdpSocket)
delete realUdpSocket;
for(vector<shared_ptr<Stream>>::iterator _stm=incomingStreams.begin();_stm!=incomingStreams.end();++_stm){
//LOGD("before delete jitter buffer");
shared_ptr<Stream> stm=*_stm;
/*if(stm->jitterBuffer){
delete stm->jitterBuffer;
}*/
LOGD("before stop decoder");
if(stm->decoder){
stm->decoder->Stop();
}
}
//LOGD("before delete audio input");
//if(audioInput){
// delete audioInput;
//}
LOGD("before delete encoder");
if(encoder){
encoder->Stop();
delete encoder;
}
//LOGD("before delete audio output");
//if(audioOutput){
//delete audioOutput;
//audioOutput.reset();
//}
/*for(vector<shared_ptr<Stream>>::iterator stm=incomingStreams.begin();stm!=incomingStreams.end();++stm){
LOGD("before delete decoder");
if((*stm)->decoder){
delete (*stm)->decoder;
}
}*/
LOGD("before delete echo canceller");
if(echoCanceller){
echoCanceller->Stop();
delete echoCanceller;
}
delete sendQueue;
/*for(i=0;i<queuedPackets.size();i++){
if(queuedPackets[i]->data)
free(queuedPackets[i]->data);
free(queuedPackets[i]);
}*/
delete conctl;
/*for(vector<Endpoint*>::iterator itr=endpoints.begin();itr!=endpoints.end();++itr){
if((*itr)->socket){
(*itr)->socket->Close();
delete (*itr)->socket;
}
delete *itr;
}*/
if(tgvoipLogFile){
FILE* log=tgvoipLogFile;
tgvoipLogFile=NULL;
fclose(log);
}
if(statsDump)
fclose(statsDump);
if(resolvedProxyAddress)
delete resolvedProxyAddress;
delete selectCanceller;
if(outputAGC)
delete outputAGC;
LOGD("Left VoIPController::~VoIPController");
}
void VoIPController::Stop(){
LOGD("Entered VoIPController::Stop");
stopping=true;
runReceiver=false;
LOGD("before shutdown socket");
if(udpSocket)
udpSocket->Close();
if(realUdpSocket!=udpSocket)
realUdpSocket->Close();
selectCanceller->CancelSelect();
sendQueue->Put(PendingOutgoingPacket{0});
if(openingTcpSocket)
openingTcpSocket->Close();
LOGD("before join sendThread");
if(sendThread){
sendThread->Join();
delete sendThread;
sendThread=NULL;
}
LOGD("before join recvThread");
if(recvThread){
recvThread->Join();
delete recvThread;
recvThread = NULL;
}
LOGD("before stop messageThread");
messageThread.Stop();
{
LOGD("Before stop audio I/O");
MutexGuard m(audioIOMutex);
if(audioInput)
audioInput->Stop();
if(audioOutput)
audioOutput->Stop();
}
LOGD("Left VoIPController::Stop");
}
void VoIPController::SetRemoteEndpoints(vector<Endpoint> endpoints, bool allowP2p, int32_t connectionMaxLayer){
LOGW("Set remote endpoints, allowP2P=%d, connectionMaxLayer=%u", allowP2p ? 1 : 0, connectionMaxLayer);
preferredRelay=NULL;
{
MutexGuard m(endpointsMutex);
this->endpoints.clear();
didAddTcpRelays=false;
useTCP=true;
for(vector<Endpoint>::iterator itrtr=endpoints.begin();itrtr!=endpoints.end();++itrtr){
this->endpoints.push_back(make_shared<Endpoint>(*itrtr));
if(itrtr->type==Endpoint::TYPE_TCP_RELAY)
didAddTcpRelays=true;
if(itrtr->type==Endpoint::TYPE_UDP_RELAY)
useTCP=false;
LOGV("Adding endpoint: %s:%d, %s", itrtr->address.ToString().c_str(), itrtr->port, itrtr->type==Endpoint::TYPE_UDP_RELAY ? "UDP" : "TCP");
}
}
currentEndpoint=this->endpoints[0];
preferredRelay=currentEndpoint;
this->allowP2p=allowP2p;
this->connectionMaxLayer=connectionMaxLayer;
if(connectionMaxLayer>=74){
useMTProto2=true;
}
AddIPv6Relays();
}
void VoIPController::Start(){
LOGW("Starting voip controller");
udpSocket->Open();
if(udpSocket->IsFailed()){
SetState(STATE_FAILED);
return;
}
//SendPacket(NULL, 0, currentEndpoint);
runReceiver=true;
recvThread=new Thread(new MethodPointer<VoIPController>(&VoIPController::RunRecvThread, this), NULL);
recvThread->SetName("VoipRecv");
recvThread->Start();
sendThread=new Thread(new MethodPointer<VoIPController>(&VoIPController::RunSendThread, this), NULL);
sendThread->SetName("VoipSend");
sendThread->Start();
messageThread.Start();
}
void VoIPController::AudioInputCallback(unsigned char* data, size_t length, unsigned char* secondaryData, size_t secondaryLength, void* param){
((VoIPController*)param)->HandleAudioInput(data, length, secondaryData, secondaryLength);
}
void VoIPController::HandleAudioInput(unsigned char *data, size_t len, unsigned char* secondaryData, size_t secondaryLen){
if(stopping)
return;
if(waitingForAcks || dontSendPackets>0){
LOGV("waiting for RLC, dropping outgoing audio packet");
return;
}
//LOGV("Audio packet size %u", (unsigned int)len);
unsigned char* buf=outgoingPacketsBufferPool.Get();
if(buf){
BufferOutputStream pkt(buf, outgoingPacketsBufferPool.GetSingleBufferSize());
unsigned char flags=(unsigned char) (len>255 ? STREAM_DATA_FLAG_LEN16 : 0);
pkt.WriteByte((unsigned char) (1 | flags)); // streamID + flags
if(len>255)
pkt.WriteInt16((int16_t) len);
else
pkt.WriteByte((unsigned char) len);
pkt.WriteInt32(audioTimestampOut);
pkt.WriteBytes(data, len);
PendingOutgoingPacket p{
/*.seq=*/GenerateOutSeq(),
/*.type=*/PKT_STREAM_DATA,
/*.len=*/pkt.GetLength(),
/*.data=*/buf,
/*.endpoint=*/0,
};
sendQueue->Put(p);
}else{
LOGW("Out of outgoing packet buffers!");
}
if(secondaryData && secondaryLen && shittyInternetMode){
Buffer ecBuf(secondaryLen);
ecBuf.CopyFrom(secondaryData, 0, secondaryLen);
ecAudioPackets.push_back(move(ecBuf));
while(ecAudioPackets.size()>4)
ecAudioPackets.erase(ecAudioPackets.begin());
buf=outgoingPacketsBufferPool.Get();
if(buf){
BufferOutputStream pkt(buf, outgoingPacketsBufferPool.GetSingleBufferSize());
pkt.WriteByte(outgoingStreams[0]->id);
pkt.WriteInt32(audioTimestampOut);
pkt.WriteByte((unsigned char)ecAudioPackets.size());
for(Buffer& ecData:ecAudioPackets){
pkt.WriteByte((unsigned char)ecData.Length());
pkt.WriteBytes(ecData);
}
PendingOutgoingPacket p{
GenerateOutSeq(),
PKT_STREAM_EC,
pkt.GetLength(),
buf,
0
};
sendQueue->Put(p);
}else{
LOGW("Out of outgoing packet buffers!");
}
}
audioTimestampOut+=outgoingStreams[0]->frameDuration;
}
void VoIPController::HandleVideoInput(EncodedVideoFrame& frame){
if(stopping)
return;
if(waitingForAcks || dontSendPackets>0 || networkType==NET_TYPE_EDGE || networkType==NET_TYPE_GPRS){
LOGV("dropping outgoing video packet");
return;
}
}
void VoIPController::Connect(){
assert(state!=STATE_WAIT_INIT_ACK);
if(proxyProtocol==PROXY_SOCKS5){
resolvedProxyAddress=NetworkSocket::ResolveDomainName(proxyAddress);
if(!resolvedProxyAddress){
LOGW("Error resolving proxy address %s", proxyAddress.c_str());
SetState(STATE_FAILED);
return;
}
InitUDPProxy();
}
connectionInitTime=GetCurrentTime();
if(config.initTimeout==0.0){
LOGE("Init timeout is 0 -- did you forget to set config?");
config.initTimeout=30.0;
}
InitializeTimers();
SendInit();
}
void VoIPController::InitializeTimers(){
initTimeoutID=messageThread.Post([this]{
LOGW("Init timeout, disconnecting");
lastError=ERROR_TIMEOUT;
SetState(STATE_FAILED);
}, config.initTimeout);
if(!config.statsDumpFilePath.empty()){
messageThread.Post([this]{
if(statsDump && incomingStreams.size()==1){
shared_ptr<JitterBuffer>& jitterBuffer=incomingStreams[0]->jitterBuffer;
//fprintf(statsDump, "Time\tRTT\tLISeq\tLASeq\tCWnd\tBitrate\tJitter\tJDelay\tAJDelay\n");
fprintf(statsDump, "%.3f\t%.3f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%.3f\t%.3f\t%.3f\n",
GetCurrentTime()-connectionInitTime,
currentEndpoint->rtts[0],
lastRemoteSeq,
seq,
lastRemoteAckSeq,
recvLossCount,
conctl ? conctl->GetSendLossCount() : 0,
conctl ? (int)conctl->GetInflightDataSize() : 0,
encoder ? encoder->GetBitrate() : 0,
encoder ? encoder->GetPacketLoss() : 0,
jitterBuffer ? jitterBuffer->GetLastMeasuredJitter() : 0,
jitterBuffer ? jitterBuffer->GetLastMeasuredDelay()*0.06 : 0,
jitterBuffer ? jitterBuffer->GetAverageDelay()*0.06 : 0);
}
}, 0.1, 0.1);
}
udpConnectivityState=UDP_PING_PENDING;
udpPingTimeoutID=messageThread.Post(std::bind(&VoIPController::SendUdpPings, this), 0.0, 0.5);
messageThread.Post(std::bind(&VoIPController::SendRelayPings, this), 0.0, 2.0);
}
void VoIPController::SetEncryptionKey(char *key, bool isOutgoing){
memcpy(encryptionKey, key, 256);
uint8_t sha1[SHA1_LENGTH];
crypto.sha1((uint8_t*) encryptionKey, 256, sha1);
memcpy(keyFingerprint, sha1+(SHA1_LENGTH-8), 8);
uint8_t sha256[SHA256_LENGTH];
crypto.sha256((uint8_t*) encryptionKey, 256, sha256);
memcpy(callID, sha256+(SHA256_LENGTH-16), 16);
this->isOutgoing=isOutgoing;
}
uint32_t VoIPController::GenerateOutSeq(){
return seq++;
}
void VoIPController::WritePacketHeader(uint32_t pseq, BufferOutputStream *s, unsigned char type, uint32_t length){
uint32_t acks=0;
int i;
for(i=0;i<32;i++){
if(recvPacketTimes[i]>0)
acks|=1;
if(i<31)
acks<<=1;
}
if(state==STATE_WAIT_INIT || state==STATE_WAIT_INIT_ACK){
s->WriteInt32(TLID_DECRYPTED_AUDIO_BLOCK);
int64_t randomID;
crypto.rand_bytes((uint8_t *) &randomID, 8);
s->WriteInt64(randomID);
unsigned char randBytes[7];
crypto.rand_bytes(randBytes, 7);
s->WriteByte(7);
s->WriteBytes(randBytes, 7);
uint32_t pflags=PFLAG_HAS_RECENT_RECV | PFLAG_HAS_SEQ;
if(length>0)
pflags|=PFLAG_HAS_DATA;
if(state==STATE_WAIT_INIT || state==STATE_WAIT_INIT_ACK){
pflags|=PFLAG_HAS_CALL_ID | PFLAG_HAS_PROTO;
}
pflags|=((uint32_t) type) << 24;
s->WriteInt32(pflags);
if(pflags & PFLAG_HAS_CALL_ID){
s->WriteBytes(callID, 16);
}
s->WriteInt32(lastRemoteSeq);
s->WriteInt32(pseq);
s->WriteInt32(acks);
if(pflags & PFLAG_HAS_PROTO){
s->WriteInt32(PROTOCOL_NAME);
}
if(length>0){
if(length<=253){
s->WriteByte((unsigned char) length);
}else{
s->WriteByte(254);
s->WriteByte((unsigned char) (length & 0xFF));
s->WriteByte((unsigned char) ((length >> 8) & 0xFF));
s->WriteByte((unsigned char) ((length >> 16) & 0xFF));
}
}
}else{
s->WriteInt32(TLID_SIMPLE_AUDIO_BLOCK);
int64_t randomID;
crypto.rand_bytes((uint8_t *) &randomID, 8);
s->WriteInt64(randomID);
unsigned char randBytes[7];
crypto.rand_bytes(randBytes, 7);
s->WriteByte(7);
s->WriteBytes(randBytes, 7);
uint32_t lenWithHeader=length+13;
if(lenWithHeader>0){
if(lenWithHeader<=253){
s->WriteByte((unsigned char) lenWithHeader);
}else{
s->WriteByte(254);
s->WriteByte((unsigned char) (lenWithHeader & 0xFF));
s->WriteByte((unsigned char) ((lenWithHeader >> 8) & 0xFF));
s->WriteByte((unsigned char) ((lenWithHeader >> 16) & 0xFF));
}
}
s->WriteByte(type);
s->WriteInt32(lastRemoteSeq);
s->WriteInt32(pseq);
s->WriteInt32(acks);
if(peerVersion>=6){
MutexGuard m(queuedPacketsMutex);
if(currentExtras.empty()){
s->WriteByte(0);
}else{
s->WriteByte(XPFLAG_HAS_EXTRA);
s->WriteByte(static_cast<unsigned char>(currentExtras.size()));
for(vector<UnacknowledgedExtraData>::iterator x=currentExtras.begin();x!=currentExtras.end();++x){
LOGV("Writing extra into header: type %u, length %lu", x->type, x->data.Length());
assert(x->data.Length()<=254);
s->WriteByte(static_cast<unsigned char>(x->data.Length()+1));
s->WriteByte(x->type);
s->WriteBytes(*x->data, x->data.Length());
if(x->firstContainingSeq==0)
x->firstContainingSeq=pseq;
}
}
}
}
if(type==PKT_STREAM_DATA || type==PKT_STREAM_DATA_X2 || type==PKT_STREAM_DATA_X3)
conctl->PacketSent(pseq, length);
MutexGuard m(queuedPacketsMutex);
recentOutgoingPackets.push_back(RecentOutgoingPacket{
pseq,
0,
GetCurrentTime(),
0
});
while(recentOutgoingPackets.size()>MAX_RECENT_PACKETS)
recentOutgoingPackets.erase(recentOutgoingPackets.begin());
lastSentSeq=pseq;
//LOGI("packet header size %d", s->GetLength());
}
void VoIPController::UpdateAudioBitrateLimit(){
if(encoder){
if(dataSavingMode || dataSavingRequestedByPeer){
maxBitrate=maxAudioBitrateSaving;
encoder->SetBitrate(initAudioBitrateSaving);
}else if(networkType==NET_TYPE_GPRS){
maxBitrate=maxAudioBitrateGPRS;
encoder->SetBitrate(initAudioBitrateGPRS);
}else if(networkType==NET_TYPE_EDGE){
maxBitrate=maxAudioBitrateEDGE;
encoder->SetBitrate(initAudioBitrateEDGE);
}else{
maxBitrate=maxAudioBitrate;
encoder->SetBitrate(initAudioBitrate);
}
}
}
void VoIPController::SendInit(){
{
MutexGuard m(endpointsMutex);
uint32_t initSeq=GenerateOutSeq();
for(shared_ptr<Endpoint>& e:endpoints){
if(e->type==Endpoint::TYPE_TCP_RELAY && !useTCP)
continue;
unsigned char *pkt=outgoingPacketsBufferPool.Get();
if(!pkt){
LOGW("can't send init, queue overflow");
continue;
}
BufferOutputStream out(pkt, outgoingPacketsBufferPool.GetSingleBufferSize());
out.WriteInt32(PROTOCOL_VERSION);
out.WriteInt32(MIN_PROTOCOL_VERSION);
uint32_t flags=0;
if(config.enableCallUpgrade)
flags|=INIT_FLAG_GROUP_CALLS_SUPPORTED;
if(dataSavingMode)
flags|=INIT_FLAG_DATA_SAVING_ENABLED;
out.WriteInt32(flags);
if(connectionMaxLayer<74){
out.WriteByte(2); // audio codecs count
out.WriteByte(CODEC_OPUS_OLD);
out.WriteByte(0);
out.WriteByte(0);
out.WriteByte(0);
out.WriteInt32(CODEC_OPUS);
out.WriteByte(0); // video codecs count (decode)
out.WriteByte(0); // video codecs count (encode)
}else{
out.WriteByte(1);
out.WriteInt32(CODEC_OPUS);
/*out.WriteByte(1);
out.WriteInt32(CODEC_AVC);
out.WriteByte(1);
out.WriteInt32(CODEC_AVC);*/
out.WriteByte(0);
out.WriteByte(0);
}
sendQueue->Put(PendingOutgoingPacket{
/*.seq=*/initSeq,
/*.type=*/PKT_INIT,
/*.len=*/out.GetLength(),
/*.data=*/pkt,
/*.endpoint=*/e->id
});
}
}
if(state==STATE_WAIT_INIT)
SetState(STATE_WAIT_INIT_ACK);
messageThread.Post([this]{
if(state==STATE_WAIT_INIT_ACK){
SendInit();
}
}, 0.5);
}
void VoIPController::InitUDPProxy(){
if(realUdpSocket!=udpSocket){
udpSocket->Close();
delete udpSocket;
udpSocket=realUdpSocket;
}
NetworkSocket* tcp=NetworkSocket::Create(PROTO_TCP);
tcp->Connect(resolvedProxyAddress, proxyPort);
if(tcp->IsFailed()){
lastError=ERROR_PROXY;
SetState(STATE_FAILED);
tcp->Close();
delete tcp;
return;
}
NetworkSocketSOCKS5Proxy* udpProxy=new NetworkSocketSOCKS5Proxy(tcp, udpSocket, proxyUsername, proxyPassword);
udpProxy->InitConnection();
udpProxy->Open();
if(udpProxy->IsFailed()){
udpProxy->Close();
delete udpProxy;
useTCP=true;
useUDP=false;
udpConnectivityState=UDP_NOT_AVAILABLE;
}else{
udpSocket=udpProxy;
}
}
void VoIPController::RunRecvThread(void* arg){
LOGI("Receive thread starting");
unsigned char *buffer = (unsigned char *)malloc(1500);
NetworkPacket packet={0};
while(runReceiver){
packet.data=buffer;
packet.length=1500;
vector<NetworkSocket*> readSockets;
vector<NetworkSocket*> errorSockets;
readSockets.push_back(realUdpSocket);
errorSockets.push_back(realUdpSocket);
{
MutexGuard m(endpointsMutex);
for(shared_ptr<Endpoint>& e:endpoints){
if(e->type==Endpoint::TYPE_TCP_RELAY){
if(e->socket){
readSockets.push_back(e->socket);
errorSockets.push_back(e->socket);
}
}
}
}
{
MutexGuard m(socketSelectMutex);
bool selRes=NetworkSocket::Select(readSockets, errorSockets, selectCanceller);
if(!selRes){
LOGV("Select canceled");
continue;
}
}
if(!runReceiver)
return;
if(!errorSockets.empty()){
if(find(errorSockets.begin(), errorSockets.end(), realUdpSocket)!=errorSockets.end()){
LOGW("UDP socket failed");
SetState(STATE_FAILED);
return;
}
MutexGuard m(endpointsMutex);
for(vector<NetworkSocket*>::iterator itr=errorSockets.begin();itr!=errorSockets.end();++itr){
for(shared_ptr<Endpoint>& e:endpoints){
if(e->socket && e->socket==*itr){
e->socket->Close();
delete e->socket;
e->socket=NULL;
LOGI("Closing failed TCP socket for %s:%u", e->GetAddress().ToString().c_str(), e->port);
}
}
}
continue;
}
//NetworkSocket* socket=NULL;
/*if(find(readSockets.begin(), readSockets.end(), realUdpSocket)!=readSockets.end()){
socket=udpSocket;
}else if(readSockets.size()>0){
socket=readSockets[0];
}else{
LOGI("no sockets to read from");
continue;
}*/
for(NetworkSocket*& socket:readSockets){
socket->Receive(&packet);
if(!packet.address){
LOGE("Packet has null address. This shouldn't happen.");
continue;
}
size_t len=packet.length;
if(!len){
LOGE("Packet has zero length.");
continue;
}
//LOGV("Received %d bytes from %s:%d at %.5lf", len, packet.address->ToString().c_str(), packet.port, GetCurrentTime());
shared_ptr<Endpoint> srcEndpoint;
IPv4Address *src4=dynamic_cast<IPv4Address *>(packet.address);
if(src4){
MutexGuard m(endpointsMutex);
for(shared_ptr<Endpoint> &e:endpoints){
if(e->address==*src4 && e->port==packet.port){
if((e->type!=Endpoint::TYPE_TCP_RELAY && packet.protocol==PROTO_UDP) || (e->type==Endpoint::TYPE_TCP_RELAY && packet.protocol==PROTO_TCP)){
srcEndpoint=e;
break;
}
}
}
}else{
IPv6Address *src6=dynamic_cast<IPv6Address *>(packet.address);
if(src6){
MutexGuard m(endpointsMutex);
for(shared_ptr<Endpoint> &e:endpoints){
if(e->v6address==*src6 && e->port==packet.port && e->address.IsEmpty()){
if((e->type!=Endpoint::TYPE_TCP_RELAY && packet.protocol==PROTO_UDP) || (e->type==Endpoint::TYPE_TCP_RELAY && packet.protocol==PROTO_TCP)){
srcEndpoint=e;
break;
}
}
}
}
}
if(!srcEndpoint){
LOGW("Received a packet from unknown source %s:%u", packet.address->ToString().c_str(), packet.port);
continue;
}
if(len<=0){
//LOGW("error receiving: %d / %s", errno, strerror(errno));
continue;
}
if(IS_MOBILE_NETWORK(networkType))
stats.bytesRecvdMobile+=(uint64_t) len;
else
stats.bytesRecvdWifi+=(uint64_t) len;
try{
ProcessIncomingPacket(packet, srcEndpoint);
}catch(out_of_range x){
LOGW("Error parsing packet: %s", x.what());
}
}
}
free(buffer);
LOGI("=== recv thread exiting ===");
}
void VoIPController::RunSendThread(void* arg){
unsigned char buf[1500];
while(runReceiver){
PendingOutgoingPacket pkt=sendQueue->GetBlocking();
if(pkt.data){
shared_ptr<Endpoint> endpoint;
if(pkt.endpoint){
endpoint=GetEndpointByID(pkt.endpoint);
}
if(!endpoint){ // either packet has no endpoint specified or it no longer exists
endpoint=currentEndpoint;
}
if((endpoint->type==Endpoint::TYPE_TCP_RELAY && useTCP) || (endpoint->type!=Endpoint::TYPE_TCP_RELAY && useUDP)){
BufferOutputStream p(buf, sizeof(buf));
WritePacketHeader(pkt.seq, &p, pkt.type, (uint32_t)pkt.len);
p.WriteBytes(pkt.data, pkt.len);
SendPacket(p.GetBuffer(), p.GetLength(), endpoint, pkt);
}
outgoingPacketsBufferPool.Reuse(pkt.data);
}else{
LOGE("tried to send null packet");
}
}
LOGI("=== send thread exiting ===");
}
void VoIPController::ProcessIncomingPacket(NetworkPacket &packet, shared_ptr<Endpoint> srcEndpoint){
unsigned char* buffer=packet.data;
size_t len=packet.length;
BufferInputStream in(buffer, (size_t)len);
if(memcmp(buffer, srcEndpoint->type==Endpoint::TYPE_UDP_RELAY || srcEndpoint->type==Endpoint::TYPE_TCP_RELAY ? (void*)srcEndpoint->peerTag : (void*)callID, 16)!=0){
LOGW("Received packet has wrong peerTag");
return;
}
in.Seek(16);
if(in.Remaining()>=16 && (srcEndpoint->type==Endpoint::TYPE_UDP_RELAY || srcEndpoint->type==Endpoint::TYPE_TCP_RELAY)
&& *reinterpret_cast<uint64_t*>(buffer+16)==0xFFFFFFFFFFFFFFFFLL && *reinterpret_cast<uint32_t*>(buffer+24)==0xFFFFFFFF){
// relay special request response
in.Seek(16+12);
uint32_t tlid=(uint32_t) in.ReadInt32();
if(tlid==TLID_UDP_REFLECTOR_SELF_INFO){
if(srcEndpoint->type==Endpoint::TYPE_UDP_RELAY /*&& udpConnectivityState==UDP_PING_SENT*/ && in.Remaining()>=32){
int32_t date=in.ReadInt32();
int64_t queryID=in.ReadInt64();
unsigned char myIP[16];
in.ReadBytes(myIP, 16);
int32_t myPort=in.ReadInt32();
//udpConnectivityState=UDP_AVAILABLE;
LOGV("Received UDP ping reply from %s:%d: date=%d, queryID=%ld, my IP=%s, my port=%d", srcEndpoint->address.ToString().c_str(), srcEndpoint->port, date, (long int)queryID, IPv4Address(*reinterpret_cast<uint32_t*>(myIP+12)).ToString().c_str(), myPort);
srcEndpoint->udpPongCount++;
if(srcEndpoint->IsIPv6Only() && !didSendIPv6Endpoint){
IPv6Address realAddr(myIP);
if(realAddr==myIPv6){
LOGI("Public IPv6 matches local address");
useIPv6=true;
if(allowP2p){
didSendIPv6Endpoint=true;
BufferOutputStream o(18);
o.WriteBytes(myIP, 16);
o.WriteInt16(udpSocket->GetLocalPort());
Buffer b(move(o));
SendExtra(b, EXTRA_TYPE_IPV6_ENDPOINT);
}
}
}
}
}else if(tlid==TLID_UDP_REFLECTOR_PEER_INFO){
if(waitingForRelayPeerInfo && in.Remaining()>=16){
MutexGuard _m(endpointsMutex);
uint32_t myAddr=(uint32_t) in.ReadInt32();
uint32_t myPort=(uint32_t) in.ReadInt32();
uint32_t peerAddr=(uint32_t) in.ReadInt32();
uint32_t peerPort=(uint32_t) in.ReadInt32();
for(vector<shared_ptr<Endpoint>>::iterator itrtr=endpoints.begin(); itrtr!=endpoints.end(); ++itrtr){
shared_ptr<Endpoint> ep=*itrtr;
if(ep->type==Endpoint::TYPE_UDP_P2P_INET && !ep->IsIPv6Only()){
if(currentEndpoint==ep)
currentEndpoint=preferredRelay;
endpoints.erase(itrtr);
break;
}
}
for(vector<shared_ptr<Endpoint>>::iterator itrtr=endpoints.begin(); itrtr!=endpoints.end(); ++itrtr){
shared_ptr<Endpoint> ep=*itrtr;
if(ep->type==Endpoint::TYPE_UDP_P2P_LAN){
if(currentEndpoint==ep)
currentEndpoint=preferredRelay;
endpoints.erase(itrtr);
break;
}
}
IPv4Address _peerAddr(peerAddr);
IPv6Address emptyV6(string("::0"));
unsigned char peerTag[16];
endpoints.push_back(make_shared<Endpoint>((int64_t)(FOURCC('P','2','P','4')) << 32, (uint16_t) peerPort, _peerAddr, emptyV6, Endpoint::TYPE_UDP_P2P_INET, peerTag));
LOGW("Received reflector peer info, my=%08X:%u, peer=%08X:%u", myAddr, myPort, peerAddr, peerPort);
if(myAddr==peerAddr){
LOGW("Detected LAN");
IPv4Address lanAddr(0);
udpSocket->GetLocalInterfaceInfo(&lanAddr, NULL);