forked from grishka/libtgvoip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VoIPController.cpp
2026 lines (1880 loc) · 59.9 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 "BufferOutputStream.h"
#include "BufferInputStream.h"
#include "OpusEncoder.h"
#include "OpusDecoder.h"
#include "VoIPServerConfig.h"
#include <assert.h>
#include <time.h>
#include <math.h>
#include <exception>
#include <stdexcept>
using namespace tgvoip;
#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
#define SHA1_LENGTH 20
#define SHA256_LENGTH 32
#ifndef TGVOIP_USE_CUSTOM_CRYPTO
#include <openssl/sha.h>
#include <openssl/aes.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);
}
voip_crypto_functions_t VoIPController::crypto={
tgvoip_openssl_rand_bytes,
tgvoip_openssl_sha1,
tgvoip_openssl_sha256,
tgvoip_openssl_aes_ige_encrypt,
tgvoip_openssl_aes_ige_decrypt
};
#else
voip_crypto_functions_t VoIPController::crypto; // set it yourself upon initialization
#endif
#ifdef _MSC_VER
#define MSC_STACK_FALLBACK(a, b) (b)
#else
#define MSC_STACK_FALLBACK(a, b) (a)
#endif
extern FILE* tgvoipLogFile;
VoIPController::VoIPController() : activeNetItfName(""){
seq=1;
lastRemoteSeq=0;
state=STATE_WAIT_INIT;
audioInput=NULL;
audioOutput=NULL;
decoder=NULL;
encoder=NULL;
jitterBuffer=NULL;
audioOutStarted=false;
audioTimestampIn=0;
audioTimestampOut=0;
stopping=false;
int i;
for(i=0;i<20;i++){
emptySendBuffers.push_back(new CBufferOutputStream(1024));
}
sendQueue=new CBlockingQueue(21);
init_mutex(sendBufferMutex);
memset(remoteAcks, 0, sizeof(double)*32);
memset(sentPacketTimes, 0, sizeof(double)*32);
memset(recvPacketTimes, 0, sizeof(double)*32);
memset(rttHistory, 0, sizeof(double)*32);
memset(sendLossCountHistory, 0, sizeof(uint32_t)*32);
memset(&stats, 0, sizeof(voip_stats_t));
lastRemoteAckSeq=0;
lastSentSeq=0;
recvLossCount=0;
packetsRecieved=0;
waitingForAcks=false;
networkType=NET_TYPE_UNKNOWN;
audioPacketGrouping=3;
audioPacketsWritten=0;
currentAudioPacket=NULL;
stateCallback=NULL;
echoCanceller=NULL;
dontSendPackets=0;
micMuted=false;
currentEndpoint=NULL;
waitingForRelayPeerInfo=false;
allowP2p=true;
dataSavingMode=false;
publicEndpointsReqTime=0;
init_mutex(queuedPacketsMutex);
init_mutex(endpointsMutex);
connectionInitTime=0;
lastRecvPacketTime=0;
dataSavingRequestedByPeer=false;
peerVersion=0;
conctl=new CCongestionControl();
prevSendLossCount=0;
receivedInit=false;
receivedInitAck=false;
peerPreferredRelay=NULL;
socket=NetworkSocket::Create();
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);
#ifdef __APPLE__
machTimestart=0;
#ifdef TGVOIP_USE_AUDIO_SESSION
needNotifyAcquiredAudioSession=false;
#endif
#endif
voip_stream_t* stm=(voip_stream_t *) malloc(sizeof(voip_stream_t));
stm->id=1;
stm->type=STREAM_TYPE_AUDIO;
stm->codec=CODEC_OPUS;
stm->enabled=1;
stm->frameDuration=60;
outgoingStreams.push_back(stm);
}
VoIPController::~VoIPController(){
LOGD("Entered VoIPController::~VoIPController");
if(audioInput)
audioInput->Stop();
if(audioOutput)
audioOutput->Stop();
stopping=true;
runReceiver=false;
LOGD("before shutdown socket");
if(socket)
socket->Close();
sendQueue->Put(NULL);
LOGD("before join sendThread");
join_thread(sendThread);
LOGD("before join recvThread");
join_thread(recvThread);
LOGD("before join tickThread");
join_thread(tickThread);
free_mutex(sendBufferMutex);
LOGD("before close socket");
if(socket)
delete socket;
LOGD("before free send buffers");
while(emptySendBuffers.size()>0){
delete emptySendBuffers[emptySendBuffers.size()-1];
emptySendBuffers.pop_back();
}
while(sendQueue->Size()>0){
void* p=sendQueue->Get();
if(p)
delete (CBufferOutputStream*)p;
}
LOGD("before delete jitter buffer");
if(jitterBuffer){
delete jitterBuffer;
}
LOGD("before stop decoder");
if(decoder){
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;
}
LOGD("before delete decoder");
if(decoder){
delete decoder;
}
LOGD("before delete echo canceller");
if(echoCanceller){
echoCanceller->Stop();
delete echoCanceller;
}
delete sendQueue;
unsigned int i;
for(i=0;i<incomingStreams.size();i++){
free(incomingStreams[i]);
}
incomingStreams.clear();
for(i=0;i<outgoingStreams.size();i++){
free(outgoingStreams[i]);
}
outgoingStreams.clear();
free_mutex(queuedPacketsMutex);
free_mutex(endpointsMutex);
for(i=0;i<queuedPackets.size();i++){
if(queuedPackets[i]->data)
free(queuedPackets[i]->data);
free(queuedPackets[i]);
}
delete conctl;
for(std::vector<Endpoint*>::iterator itr=endpoints.begin();itr!=endpoints.end();++itr)
delete *itr;
LOGD("Left VoIPController::~VoIPController");
if(tgvoipLogFile){
FILE* log=tgvoipLogFile;
tgvoipLogFile=NULL;
fclose(log);
}
}
void VoIPController::SetRemoteEndpoints(std::vector<Endpoint> endpoints, bool allowP2p){
LOGW("Set remote endpoints");
preferredRelay=NULL;
size_t i;
lock_mutex(endpointsMutex);
this->endpoints.clear();
for(std::vector<Endpoint>::iterator itrtr=endpoints.begin();itrtr!=endpoints.end();++itrtr){
this->endpoints.push_back(new Endpoint(*itrtr));
}
unlock_mutex(endpointsMutex);
currentEndpoint=this->endpoints[0];
preferredRelay=currentEndpoint;
this->allowP2p=allowP2p;
}
void* VoIPController::StartRecvThread(void* controller){
((VoIPController*)controller)->RunRecvThread();
return NULL;
}
void* VoIPController::StartSendThread(void* controller){
((VoIPController*)controller)->RunSendThread();
return NULL;
}
void* VoIPController::StartTickThread(void* controller){
((VoIPController*) controller)->RunTickThread();
return NULL;
}
void VoIPController::Start(){
int res;
LOGW("Starting voip controller");
int32_t cfgFrameSize=ServerConfig::GetSharedInstance()->GetInt("audio_frame_size", 60);
if(cfgFrameSize==20 || cfgFrameSize==40 || cfgFrameSize==60)
outgoingStreams[0]->frameDuration=(uint16_t) cfgFrameSize;
socket->Open();
SendPacket(NULL, 0, currentEndpoint);
runReceiver=true;
start_thread(recvThread, StartRecvThread, this);
set_thread_priority(recvThread, get_thread_max_priority());
set_thread_name(recvThread, "voip-recv");
start_thread(sendThread, StartSendThread, this);
set_thread_priority(sendThread, get_thread_max_priority());
set_thread_name(sendThread, "voip-send");
start_thread(tickThread, StartTickThread, this);
set_thread_priority(tickThread, get_thread_max_priority());
set_thread_name(tickThread, "voip-tick");
}
size_t VoIPController::AudioInputCallback(unsigned char* data, size_t length, void* param){
((VoIPController*)param)->HandleAudioInput(data, length);
return 0;
}
void VoIPController::HandleAudioInput(unsigned char *data, size_t len){
if(stopping)
return;
if(waitingForAcks || dontSendPackets>0){
LOGV("waiting for RLC, dropping outgoing audio packet");
return;
}
int audioPacketGrouping=1;
CBufferOutputStream* pkt=NULL;
if(audioPacketsWritten==0){
pkt=GetOutgoingPacketBuffer();
if(!pkt){
LOGW("Dropping data packet, queue overflow");
return;
}
currentAudioPacket=pkt;
}else{
pkt=currentAudioPacket;
}
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);
audioPacketsWritten++;
if(audioPacketsWritten>=audioPacketGrouping){
uint32_t pl=pkt->GetLength();
unsigned char tmp[MSC_STACK_FALLBACK(pl, 1024)];
memcpy(tmp, pkt->GetBuffer(), pl);
pkt->Reset();
unsigned char type;
switch(audioPacketGrouping){
case 2:
type=PKT_STREAM_DATA_X2;
break;
case 3:
type=PKT_STREAM_DATA_X3;
break;
default:
type=PKT_STREAM_DATA;
break;
}
WritePacketHeader(pkt, type, pl);
pkt->WriteBytes(tmp, pl);
//LOGI("payload size %u", pl);
if(pl<253)
pl+=1;
for(;pl%4>0;pl++)
pkt->WriteByte(0);
sendQueue->Put(pkt);
audioPacketsWritten=0;
}
audioTimestampOut+=outgoingStreams[0]->frameDuration;
}
void VoIPController::Connect(){
assert(state!=STATE_WAIT_INIT_ACK);
connectionInitTime=GetCurrentTime();
SendInit();
}
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::WritePacketHeader(CBufferOutputStream *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;
}
uint32_t pseq=seq++;
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(type==PKT_STREAM_DATA || type==PKT_STREAM_DATA_X2 || type==PKT_STREAM_DATA_X3)
conctl->PacketSent(pseq, length);
memmove(&sentPacketTimes[1], sentPacketTimes, 31*sizeof(double));
sentPacketTimes[0]=GetCurrentTime();
lastSentSeq=pseq;
//LOGI("packet header size %d", s->GetLength());
return pseq;
}
void VoIPController::UpdateAudioBitrate(){
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(){
CBufferOutputStream* out=new CBufferOutputStream(1024);
WritePacketHeader(out, PKT_INIT, 15);
out->WriteInt32(PROTOCOL_VERSION);
out->WriteInt32(MIN_PROTOCOL_VERSION);
uint32_t flags=0;
if(dataSavingMode)
flags|=INIT_FLAG_DATA_SAVING_ENABLED;
out->WriteInt32(flags);
out->WriteByte(1); // audio codecs count
out->WriteByte(CODEC_OPUS);
out->WriteByte(0); // video codecs count
lock_mutex(endpointsMutex);
for(std::vector<Endpoint*>::iterator itr=endpoints.begin();itr!=endpoints.end();++itr){
SendPacket(out->GetBuffer(), out->GetLength(), *itr);
}
unlock_mutex(endpointsMutex);
SetState(STATE_WAIT_INIT_ACK);
delete out;
}
void VoIPController::SendInitAck(){
}
void VoIPController::RunRecvThread(){
LOGI("Receive thread starting");
unsigned char buffer[1024];
NetworkPacket packet;
while(runReceiver){
//LOGI("Before recv");
packet.data=buffer;
packet.length=1024;
socket->Receive(&packet);
if(!packet.address){
LOGE("Packet has null address. This shouldn't happen.");
continue;
}
size_t len=packet.length;
//LOGV("Received %d bytes from %s:%d at %.5lf", len, inet_ntoa(srcAddr.sin_addr), ntohs(srcAddr.sin_port), GetCurrentTime());
Endpoint* srcEndpoint=NULL;
IPv4Address* src4=dynamic_cast<IPv4Address*>(packet.address);
if(src4){
lock_mutex(endpointsMutex);
for(std::vector<Endpoint*>::iterator itrtr=endpoints.begin();itrtr!=endpoints.end();++itrtr){
if((*itrtr)->address==*src4){
srcEndpoint=*itrtr;
break;
}
}
unlock_mutex(endpointsMutex);
}
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;
CBufferInputStream* in=new CBufferInputStream(buffer, (size_t)len);
try{
if(memcmp(buffer, srcEndpoint->type==EP_TYPE_UDP_RELAY ? srcEndpoint->peerTag : callID, 16)!=0){
LOGW("Received packet has wrong peerTag");
delete in;
continue;
}
in->Seek(16);
if(waitingForRelayPeerInfo && in->Remaining()>=32){
bool isPublicIpResponse=true;
int i;
for(i=0;i<12;i++){
if((unsigned char)buffer[in->GetOffset()+i]!=0xFF){
isPublicIpResponse=false;
break;
}
}
if(isPublicIpResponse){
waitingForRelayPeerInfo=false;
in->Seek(in->GetOffset()+12);
uint32_t tlid=(uint32_t) in->ReadInt32();
if(tlid==TLID_UDP_REFLECTOR_PEER_INFO){
lock_mutex(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(std::vector<Endpoint*>::iterator itrtr=endpoints.begin();itrtr!=endpoints.end();++itrtr){
if((*itrtr)->type==EP_TYPE_UDP_P2P_INET){
delete *itrtr;
endpoints.erase(itrtr);
break;
}
}
for(std::vector<Endpoint*>::iterator itrtr=endpoints.begin();itrtr!=endpoints.end();++itrtr){
if((*itrtr)->type==EP_TYPE_UDP_P2P_LAN){
delete *itrtr;
endpoints.erase(itrtr);
break;
}
}
IPv4Address _peerAddr(peerAddr);
IPv6Address emptyV6("::0");
unsigned char peerTag[16];
endpoints.push_back(new Endpoint(0, (uint16_t) peerPort, _peerAddr, emptyV6, EP_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);
socket->GetLocalInterfaceInfo(&lanAddr, NULL);
CBufferOutputStream pkt(8);
pkt.WriteInt32(lanAddr.GetAddress());
pkt.WriteInt32(socket->GetLocalPort());
SendPacketReliably(PKT_LAN_ENDPOINT, pkt.GetBuffer(), pkt.GetLength(), 0.5, 10);
}
unlock_mutex(endpointsMutex);
}else{
LOGE("It looks like a reflector response but tlid is %08X, expected %08X", tlid, TLID_UDP_REFLECTOR_PEER_INFO);
}
delete in;
continue;
}
}
if(in->Remaining()<40){
delete in;
continue;
}
unsigned char fingerprint[8], msgHash[16];
in->ReadBytes(fingerprint, 8);
in->ReadBytes(msgHash, 16);
if(memcmp(fingerprint, keyFingerprint, 8)!=0){
LOGW("Received packet has wrong key fingerprint");
delete in;
continue;
}
unsigned char key[32], iv[32];
KDF(msgHash, isOutgoing ? 8 : 0, key, iv);
unsigned char aesOut[MSC_STACK_FALLBACK(in->Remaining(), 1024)];
crypto.aes_ige_decrypt((unsigned char *) buffer+in->GetOffset(), aesOut, in->Remaining(), key, iv);
memcpy(buffer+in->GetOffset(), aesOut, in->Remaining());
unsigned char sha[SHA1_LENGTH];
uint32_t _len=(uint32_t) in->ReadInt32();
if(_len>in->Remaining())
_len=in->Remaining();
crypto.sha1((uint8_t *) (buffer+in->GetOffset()-4), (size_t) (_len+4), sha);
if(memcmp(msgHash, sha+(SHA1_LENGTH-16), 16)!=0){
LOGW("Received packet has wrong hash after decryption");
delete in;
continue;
}
lastRecvPacketTime=GetCurrentTime();
/*decryptedAudioBlock random_id:long random_bytes:string flags:# voice_call_id:flags.2?int128 in_seq_no:flags.4?int out_seq_no:flags.4?int
* recent_received_mask:flags.5?int proto:flags.3?int extra:flags.1?string raw_data:flags.0?string = DecryptedAudioBlock
simpleAudioBlock random_id:long random_bytes:string raw_data:string = DecryptedAudioBlock;
*/
uint32_t ackId, pseq, acks;
unsigned char type;
uint32_t tlid=(uint32_t) in->ReadInt32();
uint32_t packetInnerLen;
if(tlid==TLID_DECRYPTED_AUDIO_BLOCK){
in->ReadInt64(); // random id
uint32_t randLen=(uint32_t) in->ReadTlLength();
in->Seek(in->GetOffset()+randLen+pad4(randLen));
uint32_t flags=(uint32_t) in->ReadInt32();
type=(unsigned char) ((flags >> 24) & 0xFF);
if(!(flags & PFLAG_HAS_SEQ && flags & PFLAG_HAS_RECENT_RECV)){
LOGW("Received packet doesn't have PFLAG_HAS_SEQ, PFLAG_HAS_RECENT_RECV, or both");
delete in;
continue;
}
if(flags & PFLAG_HAS_CALL_ID){
unsigned char pktCallID[16];
in->ReadBytes(pktCallID, 16);
if(memcmp(pktCallID, callID, 16)!=0){
LOGW("Received packet has wrong call id");
delete in;
lastError=TGVOIP_ERROR_UNKNOWN;
SetState(STATE_FAILED);
return;
}
}
ackId=(uint32_t) in->ReadInt32();
pseq=(uint32_t) in->ReadInt32();
acks=(uint32_t) in->ReadInt32();
if(flags & PFLAG_HAS_PROTO){
uint32_t proto=(uint32_t) in->ReadInt32();
if(proto!=PROTOCOL_NAME){
LOGW("Received packet uses wrong protocol");
delete in;
lastError=TGVOIP_ERROR_INCOMPATIBLE;
SetState(STATE_FAILED);
return;
}
}
if(flags & PFLAG_HAS_EXTRA){
uint32_t extraLen=(uint32_t) in->ReadTlLength();
in->Seek(in->GetOffset()+extraLen+pad4(extraLen));
}
if(flags & PFLAG_HAS_DATA){
packetInnerLen=in->ReadTlLength();
}
}else if(tlid==TLID_SIMPLE_AUDIO_BLOCK){
in->ReadInt64(); // random id
uint32_t randLen=(uint32_t) in->ReadTlLength();
in->Seek(in->GetOffset()+randLen+pad4(randLen));
packetInnerLen=in->ReadTlLength();
type=in->ReadByte();
ackId=(uint32_t) in->ReadInt32();
pseq=(uint32_t) in->ReadInt32();
acks=(uint32_t) in->ReadInt32();
}else{
LOGW("Received a packet of unknown type %08X", tlid);
delete in;
continue;
}
packetsRecieved++;
if(seqgt(pseq, lastRemoteSeq)){
uint32_t diff=pseq-lastRemoteSeq;
if(diff>31){
memset(recvPacketTimes, 0, 32*sizeof(double));
}else{
memmove(&recvPacketTimes[diff], recvPacketTimes, (32-diff)*sizeof(double));
if(diff>1){
memset(recvPacketTimes, 0, diff*sizeof(double));
}
recvPacketTimes[0]=GetCurrentTime();
}
lastRemoteSeq=pseq;
}else if(!seqgt(pseq, lastRemoteSeq) && lastRemoteSeq-pseq<32){
if(recvPacketTimes[lastRemoteSeq-pseq]!=0){
LOGW("Received duplicated packet for seq %u", pseq);
delete in;
continue;
}
recvPacketTimes[lastRemoteSeq-pseq]=GetCurrentTime();
}else if(lastRemoteSeq-pseq>=32){
LOGW("Packet %u is out of order and too late", pseq);
delete in;
continue;
}
if(seqgt(ackId, lastRemoteAckSeq)){
uint32_t diff=ackId-lastRemoteAckSeq;
if(diff>31){
memset(remoteAcks, 0, 32*sizeof(double));
}else{
memmove(&remoteAcks[diff], remoteAcks, (32-diff)*sizeof(double));
if(diff>1){
memset(remoteAcks, 0, diff*sizeof(double));
}
remoteAcks[0]=GetCurrentTime();
}
if(waitingForAcks && lastRemoteAckSeq>=firstSentPing){
memset(rttHistory, 0, 32*sizeof(double));
waitingForAcks=false;
dontSendPackets=10;
LOGI("resuming sending");
}
lastRemoteAckSeq=ackId;
conctl->PacketAcknowledged(ackId);
int i;
for(i=0;i<31;i++){
if(remoteAcks[i+1]==0){
if((acks >> (31-i)) & 1){
remoteAcks[i+1]=GetCurrentTime();
conctl->PacketAcknowledged(ackId-(i+1));
}
}
}
lock_mutex(queuedPacketsMutex);
for(i=0;i<queuedPackets.size();i++){
voip_queued_packet_t* qp=queuedPackets[i];
int j;
bool didAck=false;
for(j=0;j<16;j++){
LOGD("queued packet %u, seq %u=%u", i, j, qp->seqs[j]);
if(qp->seqs[j]==0)
break;
int remoteAcksIndex=lastRemoteAckSeq-qp->seqs[j];
LOGV("remote acks index %u, value %f", remoteAcksIndex, remoteAcksIndex>=0 && remoteAcksIndex<32 ? remoteAcks[remoteAcksIndex] : -1);
if(seqgt(lastRemoteAckSeq, qp->seqs[j]) && remoteAcksIndex>=0 && remoteAcksIndex<32 && remoteAcks[remoteAcksIndex]>0){
LOGD("did ack seq %u, removing", qp->seqs[j]);
didAck=true;
break;
}
}
if(didAck){
if(qp->data)
free(qp->data);
free(qp);
queuedPackets.erase(queuedPackets.begin()+i);
i--;
continue;
}
}
unlock_mutex(queuedPacketsMutex);
}
if(srcEndpoint!=currentEndpoint && srcEndpoint->type==EP_TYPE_UDP_RELAY && currentEndpoint->type!=EP_TYPE_UDP_RELAY){
if(seqgt(lastSentSeq-32, lastRemoteAckSeq)){
currentEndpoint=srcEndpoint;
LOGI("Peer network address probably changed, switching to relay");
if(allowP2p)
SendPublicEndpointsRequest();
}
}
//LOGV("acks: %u -> %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf", lastRemoteAckSeq, remoteAcks[0], remoteAcks[1], remoteAcks[2], remoteAcks[3], remoteAcks[4], remoteAcks[5], remoteAcks[6], remoteAcks[7]);
//LOGD("recv: %u -> %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf, %.2lf", lastRemoteSeq, recvPacketTimes[0], recvPacketTimes[1], recvPacketTimes[2], recvPacketTimes[3], recvPacketTimes[4], recvPacketTimes[5], recvPacketTimes[6], recvPacketTimes[7]);
//LOGI("RTT = %.3lf", GetAverageRTT());
//LOGV("Packet %u type is %d", pseq, type);
if(type==PKT_INIT){
LOGD("Received init");
if(!receivedInit){
receivedInit=true;
currentEndpoint=srcEndpoint;
if(srcEndpoint->type==EP_TYPE_UDP_RELAY)
preferredRelay=srcEndpoint;
LogDebugInfo();
}
peerVersion=(uint32_t) in->ReadInt32();
LOGI("Peer version is %d", peerVersion);
uint32_t minVer=(uint32_t) in->ReadInt32();
if(minVer>PROTOCOL_VERSION || peerVersion<MIN_PROTOCOL_VERSION){
lastError=TGVOIP_ERROR_INCOMPATIBLE;
delete in;
SetState(STATE_FAILED);
return;
}
uint32_t flags=(uint32_t) in->ReadInt32();
if(flags & INIT_FLAG_DATA_SAVING_ENABLED){
dataSavingRequestedByPeer=true;
UpdateDataSavingState();
UpdateAudioBitrate();
}
int i;
int numSupportedAudioCodecs=in->ReadByte();
for(i=0; i<numSupportedAudioCodecs; i++){
in->ReadByte(); // ignore for now
}
int numSupportedVideoCodecs=in->ReadByte();
for(i=0; i<numSupportedVideoCodecs; i++){
in->ReadByte(); // ignore for now
}
CBufferOutputStream *out=new CBufferOutputStream(1024);
WritePacketHeader(out, PKT_INIT_ACK, (peerVersion>=2 ? 10 : 2)+(peerVersion>=2 ? 6 : 4)*outgoingStreams.size());
if(peerVersion>=2){
out->WriteInt32(PROTOCOL_VERSION);
out->WriteInt32(MIN_PROTOCOL_VERSION);
}
out->WriteByte((unsigned char) outgoingStreams.size());
for(i=0; i<outgoingStreams.size(); i++){
out->WriteByte(outgoingStreams[i]->id);
out->WriteByte(outgoingStreams[i]->type);
out->WriteByte(outgoingStreams[i]->codec);
if(peerVersion>=2)
out->WriteInt16(outgoingStreams[i]->frameDuration);
else
outgoingStreams[i]->frameDuration=20;
out->WriteByte((unsigned char) (outgoingStreams[i]->enabled ? 1 : 0));
}
SendPacket(out->GetBuffer(), out->GetLength(), currentEndpoint);
delete out;
}
if(type==PKT_INIT_ACK){
LOGD("Received init ack");
if(!receivedInitAck){
receivedInitAck=true;
if(packetInnerLen>10){
peerVersion=in->ReadInt32();
uint32_t minVer=(uint32_t) in->ReadInt32();
if(minVer>PROTOCOL_VERSION || peerVersion<MIN_PROTOCOL_VERSION){
lastError=TGVOIP_ERROR_INCOMPATIBLE;
delete in;
SetState(STATE_FAILED);
return;
}
}else{
peerVersion=1;
}
LOGI("peer version from init ack %d", peerVersion);
unsigned char streamCount=in->ReadByte();
if(streamCount==0)
goto malformed_packet;
int i;
voip_stream_t *incomingAudioStream=NULL;
for(i=0; i<streamCount; i++){
voip_stream_t *stm=(voip_stream_t *) malloc(sizeof(voip_stream_t));
stm->id=in->ReadByte();
stm->type=in->ReadByte();
stm->codec=in->ReadByte();
if(peerVersion>=2)
stm->frameDuration=(uint16_t) in->ReadInt16();
else
stm->frameDuration=20;
stm->enabled=in->ReadByte()==1;
incomingStreams.push_back(stm);
if(stm->type==STREAM_TYPE_AUDIO && !incomingAudioStream)
incomingAudioStream=stm;
}
if(!incomingAudioStream)
goto malformed_packet;
voip_stream_t *outgoingAudioStream=outgoingStreams[0];
if(!audioInput){
LOGI("before create audio io");
audioInput=CAudioInput::Create();
audioInput->Configure(48000, 16, 1);
audioOutput=CAudioOutput::Create();
audioOutput->Configure(48000, 16, 1);
echoCanceller=new CEchoCanceller(config.enableAEC, config.enableNS, config.enableAGC);
encoder=new COpusEncoder(audioInput);
encoder->SetCallback(AudioInputCallback, this);
encoder->SetOutputFrameDuration(outgoingAudioStream->frameDuration);
encoder->SetEchoCanceller(echoCanceller);
encoder->Start();
if(!micMuted){
audioInput->Start();
if(!audioInput->IsInitialized()){
lastError=TGVOIP_ERROR_AUDIO_IO;
delete in;
SetState(STATE_FAILED);
return;
}
}
UpdateAudioBitrate();
jitterBuffer=new CJitterBuffer(NULL, incomingAudioStream->frameDuration);
decoder=new COpusDecoder(audioOutput);
decoder->SetEchoCanceller(echoCanceller);
decoder->SetJitterBuffer(jitterBuffer);
decoder->SetFrameDuration(incomingAudioStream->frameDuration);
decoder->Start();
if(incomingAudioStream->frameDuration>50)
jitterBuffer->SetMinPacketCount(ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_60", 3));
else if(incomingAudioStream->frameDuration>30)
jitterBuffer->SetMinPacketCount(ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_40", 4));
else
jitterBuffer->SetMinPacketCount(ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_20", 6));
//audioOutput->Start();
#ifdef TGVOIP_USE_AUDIO_SESSION
#ifdef __APPLE__
if(acquireAudioSession){
acquireAudioSession(^(){
LOGD("Audio session acquired");
needNotifyAcquiredAudioSession=true;
});
}else{
CAudioUnitIO::AudioSessionAcquired();
}
#endif
#endif
}
SetState(STATE_ESTABLISHED);
if(allowP2p)
SendPublicEndpointsRequest();
}
}
if(type==PKT_STREAM_DATA || type==PKT_STREAM_DATA_X2 || type==PKT_STREAM_DATA_X3){
int count;
switch(type){
case PKT_STREAM_DATA_X2:
count=2;
break;
case PKT_STREAM_DATA_X3:
count=3;
break;
case PKT_STREAM_DATA: