| 6 |
| 7 | #include "VoIPController.h" |
| 8 | #include "logging.h" |
| 9 | #include "VoIPServerConfig.h" |
| 10 | #include "PrivateDefines.h" |
| 11 | #include <assert.h> |
| 12 | #include <math.h> |
| 13 | #include <time.h> |
| 14 |
| 15 | using namespace tgvoip; |
| 16 | using namespace std; |
| 17 |
| 18 | VoIPGroupController::VoIPGroupController(int32_t timeDifference){ |
| 19 | audioMixer=new AudioMixer(); |
| 20 | memset(&callbacks, 0, sizeof(callbacks)); |
| 21 | userSelfID=0; |
| 22 | this->timeDifference=timeDifference; |
| 23 | LOGV("Created VoIPGroupController; timeDifference=%d", timeDifference); |
| 24 | } |
| 25 |
| 26 | VoIPGroupController::~VoIPGroupController(){ |
| 27 | if(audioOutput){ |
| 28 | audioOutput->Stop(); |
| 29 | } |
| 30 | LOGD("before stop audio mixer"); |
| 31 | audioMixer->Stop(); |
| 32 | delete audioMixer; |
| 33 |
| 34 | for(vector<GroupCallParticipant>::iterator p=participants.begin();p!=participants.end();p++){ |
| 35 | if(p->levelMeter) |
| 36 | delete p->levelMeter; |
| 37 | } |
| 38 | } |
| 39 |
| 40 | void VoIPGroupController::SetGroupCallInfo(unsigned char *encryptionKey, unsigned char *reflectorGroupTag, unsigned char *reflectorSelfTag, unsigned char *reflectorSelfSecret, unsigned char* reflectorSelfTagHash, int32_t selfUserID, NetworkAddress reflectorAddress, NetworkAddress reflectorAddressV6, uint16_t reflectorPort){ |
| 41 | Endpoint e; |
| 42 | e.address=reflectorAddress; |
| 43 | e.v6address=reflectorAddressV6; |
| 44 | e.port=reflectorPort; |
| 45 | memcpy(e.peerTag, reflectorGroupTag, 16); |
| 46 | e.type=Endpoint::Type::UDP_RELAY; |
| 47 | e.id=FOURCC('G','R','P','R'); |
| 48 | endpoints[e.id]=e; |
| 49 | groupReflector=e; |
| 50 | currentEndpoint=e.id; |
| 51 |
| 52 | memcpy(this->encryptionKey, encryptionKey, 256); |
| 53 | memcpy(this->reflectorSelfTag, reflectorSelfTag, 16); |
| 54 | memcpy(this->reflectorSelfSecret, reflectorSelfSecret, 16); |
| 55 | memcpy(this->reflectorSelfTagHash, reflectorSelfTagHash, 16); |
| 56 | uint8_t sha256[SHA256_LENGTH]; |
| 57 | crypto.sha256((uint8_t*) encryptionKey, 256, sha256); |
| 58 | memcpy(callID, sha256+(SHA256_LENGTH-16), 16); |
| 59 | memcpy(keyFingerprint, sha256+(SHA256_LENGTH-16), 8); |
| 60 | this->userSelfID=selfUserID; |
| 61 |
| 62 | //LOGD("reflectorSelfTag = %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X", reflectorSelfTag[0], reflectorSelfTag[1], reflectorSelfTag[2], reflectorSelfTag[3], reflectorSelfTag[4], reflectorSelfTag[5], reflectorSelfTag[6], reflectorSelfTag[7], reflectorSelfTag[8], reflectorSelfTag[9], reflectorSelfTag[10], reflectorSelfTag[11], reflectorSelfTag[12], reflectorSelfTag[13], reflectorSelfTag[14], reflectorSelfTag[15]); |
| 63 | //LOGD("reflectorSelfSecret = %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X", reflectorSelfSecret[0], reflectorSelfSecret[1], reflectorSelfSecret[2], reflectorSelfSecret[3], reflectorSelfSecret[4], reflectorSelfSecret[5], reflectorSelfSecret[6], reflectorSelfSecret[7], reflectorSelfSecret[8], reflectorSelfSecret[9], reflectorSelfSecret[10], reflectorSelfSecret[11], reflectorSelfSecret[12], reflectorSelfSecret[13], reflectorSelfSecret[14], reflectorSelfSecret[15]); |
| 64 | //LOGD("reflectorSelfTagHash = %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X", reflectorSelfTagHash[0], reflectorSelfTagHash[1], reflectorSelfTagHash[2], reflectorSelfTagHash[3], reflectorSelfTagHash[4], reflectorSelfTagHash[5], reflectorSelfTagHash[6], reflectorSelfTagHash[7], reflectorSelfTagHash[8], reflectorSelfTagHash[9], reflectorSelfTagHash[10], reflectorSelfTagHash[11], reflectorSelfTagHash[12], reflectorSelfTagHash[13], reflectorSelfTagHash[14], reflectorSelfTagHash[15]); |
| 65 | } |
| 66 |
| 67 | void VoIPGroupController::AddGroupCallParticipant(int32_t userID, unsigned char *memberTagHash, unsigned char* serializedStreams, size_t streamsLength){ |
| 68 | if(userID==userSelfID) |
| 69 | return; |
| 70 | if(userSelfID==0) |
| 71 | return; |
| 72 | //if(streamsLength==0) |
| 73 | // return; |
| 74 | MutexGuard m(participantsMutex); |
| 75 | LOGV("Adding group call user %d, streams length %u", userID, (unsigned int)streamsLength); |
| 76 |
| 77 | for(vector<GroupCallParticipant>::iterator p=participants.begin();p!=participants.end();++p){ |
| 78 | if(p->userID==userID){ |
| 79 | LOGE("user %d already added", userID); |
| 80 | abort(); |
| 81 | break; |
| 82 | } |
| 83 | } |
| 84 |
| 85 | GroupCallParticipant p; |
| 86 | p.userID=userID; |
| 87 | memcpy(p.memberTagHash, memberTagHash, sizeof(p.memberTagHash)); |
| 88 | p.levelMeter=new AudioLevelMeter(); |
| 89 |
| 90 | BufferInputStream ss(serializedStreams, streamsLength); |
| 91 | vector<shared_ptr<Stream>> streams=DeserializeStreams(ss); |
| 92 |
| 93 | unsigned char audioStreamID=0; |
| 94 |
| 95 | for(vector<shared_ptr<Stream>>::iterator _s=streams.begin();_s!=streams.end();++_s){ |
| 96 | shared_ptr<Stream>& s=*_s; |
| 97 | s->userID=userID; |
| 98 | if(s->type==STREAM_TYPE_AUDIO && s->codec==CODEC_OPUS && !audioStreamID){ |
| 99 | audioStreamID=s->id; |
| 100 | s->jitterBuffer=make_shared<JitterBuffer>(nullptr, s->frameDuration); |
| 101 | if(s->frameDuration>50) |
| 102 | s->jitterBuffer->SetMinPacketCount((uint32_t) ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_60", 2)); |
| 103 | else if(s->frameDuration>30) |
| 104 | s->jitterBuffer->SetMinPacketCount((uint32_t) ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_40", 4)); |
| 105 | else |
| 106 | s->jitterBuffer->SetMinPacketCount((uint32_t) ServerConfig::GetSharedInstance()->GetInt("jitter_initial_delay_20", 6)); |
| 107 | s->callbackWrapper=make_shared<CallbackWrapper>(); |
| 108 | s->decoder=make_shared<OpusDecoder>(s->callbackWrapper, false, false); |
| 109 | s->decoder->SetJitterBuffer(s->jitterBuffer); |
| 110 | s->decoder->SetFrameDuration(s->frameDuration); |
| 111 | s->decoder->SetDTX(true); |
| 112 | s->decoder->SetLevelMeter(p.levelMeter); |
| 113 | audioMixer->AddInput(s->callbackWrapper); |
| 114 | } |
| 115 | incomingStreams.push_back(s); |
| 116 | } |
| 117 |
| 118 | if(!audioStreamID){ |
| 119 | LOGW("User %d has no usable audio stream", userID); |
| 120 | } |
| 121 |
| 122 | p.streams.insert(p.streams.end(), streams.begin(), streams.end()); |
| 123 | participants.push_back(p); |
| 124 | LOGI("Added group call participant %d", userID); |
| 125 | } |
| 126 |
| 127 | void VoIPGroupController::RemoveGroupCallParticipant(int32_t userID){ |
| 128 | MutexGuard m(participantsMutex); |
| 129 | vector<shared_ptr<Stream>>::iterator stm=incomingStreams.begin(); |
| 130 | while(stm!=incomingStreams.end()){ |
| 131 | if((*stm)->userID==userID){ |
| 132 | LOGI("Removed stream %d belonging to user %d", (*stm)->id, userID); |
| 133 | audioMixer->RemoveInput((*stm)->callbackWrapper); |
| 134 | (*stm)->decoder->Stop(); |
| 135 | //delete (*stm)->decoder; |
| 136 | //delete (*stm)->jitterBuffer; |
| 137 | //delete (*stm)->callbackWrapper; |
| 138 | stm=incomingStreams.erase(stm); |
| 139 | continue; |
| 140 | } |
| 141 | ++stm; |
| 142 | } |
| 143 | for(vector<GroupCallParticipant>::iterator p=participants.begin();p!=participants.end();++p){ |
| 144 | if(p->userID==userID){ |
| 145 | if(p->levelMeter) |
| 146 | delete p->levelMeter; |
| 147 | participants.erase(p); |
| 148 | LOGI("Removed group call participant %d", userID); |
| 149 | break; |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 |
| 154 | vector<shared_ptr<VoIPController::Stream>> VoIPGroupController::DeserializeStreams(BufferInputStream& in){ |
| 155 | vector<shared_ptr<Stream>> res; |
| 156 | try{ |
| 157 | unsigned char count=in.ReadByte(); |
| 158 | for(unsigned char i=0;i<count;i++){ |
| 159 | uint16_t len=(uint16_t) in.ReadInt16(); |
| 160 | BufferInputStream inner=in.GetPartBuffer(len, true); |
| 161 | shared_ptr<Stream> s=make_shared<Stream>(); |
| 162 | s->id=inner.ReadByte(); |
| 163 | s->type=inner.ReadByte(); |
| 164 | s->codec=(uint32_t) inner.ReadInt32(); |
| 165 | uint32_t flags=(uint32_t) inner.ReadInt32(); |
| 166 | s->enabled=(flags & STREAM_FLAG_ENABLED)==STREAM_FLAG_ENABLED; |
| 167 | s->frameDuration=(uint16_t) inner.ReadInt16(); |
| 168 | res.push_back(s); |
| 169 | } |
| 170 | }catch(out_of_range& x){ |
| 171 | LOGW("Error deserializing streams: %s", x.what()); |
| 172 | } |
| 173 | return res; |
| 174 | } |
| 175 |
| 176 | void VoIPGroupController::SetParticipantStreams(int32_t userID, unsigned char *serializedStreams, size_t length){ |
| 177 | LOGD("Set participant streams for %d", userID); |
| 178 | MutexGuard m(participantsMutex); |
| 179 | for(vector<GroupCallParticipant>::iterator p=participants.begin();p!=participants.end();++p){ |
| 180 | if(p->userID==userID){ |
| 181 | BufferInputStream in(serializedStreams, length); |
| 182 | vector<shared_ptr<Stream>> streams=DeserializeStreams(in); |
| 183 | for(vector<shared_ptr<Stream>>::iterator ns=streams.begin();ns!=streams.end();++ns){ |
| 184 | bool found=false; |
| 185 | for(vector<shared_ptr<Stream>>::iterator s=p->streams.begin();s!=p->streams.end();++s){ |
| 186 | if((*s)->id==(*ns)->id){ |
| 187 | (*s)->enabled=(*ns)->enabled; |
| 188 | if(groupCallbacks.participantAudioStateChanged) |
| 189 | groupCallbacks.participantAudioStateChanged(this, userID, (*s)->enabled); |
| 190 | found=true; |
| 191 | break; |
| 192 | } |
| 193 | } |
| 194 | if(!found){ |
| 195 | LOGW("Tried to add stream %d for user %d but adding/removing streams is not supported", (*ns)->id, userID); |
| 196 | } |
| 197 | } |
| 198 | break; |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 |
| 203 | size_t VoIPGroupController::GetInitialStreams(unsigned char *buf, size_t size){ |
| 204 | BufferOutputStream s(buf, size); |
| 205 | s.WriteByte(1); // streams count |
| 206 |
| 207 | s.WriteInt16(12); // this object length |
| 208 | s.WriteByte(1); // stream id |
| 209 | s.WriteByte(STREAM_TYPE_AUDIO); |
| 210 | s.WriteInt32(CODEC_OPUS); |
| 211 | s.WriteInt32(STREAM_FLAG_ENABLED | STREAM_FLAG_DTX); // flags |
| 212 | s.WriteInt16(60); // frame duration |
| 213 |
| 214 | return s.GetLength(); |
| 215 | } |
| 216 |
| 217 | void VoIPGroupController::SendInit(){ |
| 218 | SendRecentPacketsRequest(); |
| 219 | } |
| 220 |
| 221 | void VoIPGroupController::ProcessIncomingPacket(NetworkPacket &packet, Endpoint& srcEndpoint){ |
| 222 | //LOGD("Received incoming packet from %s:%u, %u bytes", packet.address->ToString().c_str(), packet.port, packet.length); |
| 223 | /*if(packet.length<17 || packet.length>2000){ |
| 224 | LOGW("Received packet has wrong length %d", (int)packet.length); |
| 225 | return; |
| 226 | } |
| 227 | BufferOutputStream sigData(packet.length); |
| 228 | sigData.WriteBytes(packet.data, packet.length-16); |
| 229 | sigData.WriteBytes(reflectorSelfSecret, 16); |
| 230 | unsigned char sig[32]; |
| 231 | crypto.sha256(sigData.GetBuffer(), sigData.GetLength(), sig); |
| 232 | if(memcmp(sig, packet.data+(packet.length-16), 16)!=0){ |
| 233 | LOGW("Received packet has incorrect signature"); |
| 234 | return; |
| 235 | } |
| 236 |
| 237 | // reflector special response |
| 238 | if(memcmp(packet.data, reflectorSelfTagHash, 16)==0 && packet.length>60){ |
| 239 | //LOGI("possible reflector special response"); |
| 240 | unsigned char firstBlock[16]; |
| 241 | unsigned char iv[16]; |
| 242 | memcpy(iv, packet.data+16, 16); |
| 243 | unsigned char key[32]; |
| 244 | crypto.sha256(reflectorSelfSecret, 16, key); |
| 245 | crypto.aes_cbc_decrypt(packet.data+32, firstBlock, 16, key, iv); |
| 246 | BufferInputStream in(firstBlock, 16); |
| 247 | in.Seek(8); |
| 248 | size_t len=(size_t) in.ReadInt32(); |
| 249 | int32_t tlid=in.ReadInt32(); |
| 250 | //LOGD("special response: len=%d, tlid=0x%08X", len, tlid); |
| 251 | if(len%4==0 && len+60<=packet.length && packet.length<=1500){ |
| 252 | lastRecvPacketTime=GetCurrentTime(); |
| 253 | memcpy(iv, packet.data+16, 16); |
| 254 | unsigned char buf[1500]; |
| 255 | crypto.aes_cbc_decrypt(packet.data+32, buf, len+16, key, iv); |
| 256 | try{ |
| 257 | if(tlid==TLID_UDP_REFLECTOR_LAST_PACKETS_INFO){ |
| 258 | MutexGuard m(sentPacketsMutex); |
| 259 | //LOGV("received udpReflector.lastPacketsInfo"); |
| 260 | in=BufferInputStream(buf, len+16); |
| 261 | in.Seek(16); |
| 262 | /*int32_t date=* /in.ReadInt32(); |
| 263 | /*int64_t queryID=* /in.ReadInt64(); |
| 264 | int32_t vectorMagic=in.ReadInt32(); |
| 265 | if(vectorMagic!=TLID_VECTOR){ |
| 266 | LOGW("last packets info: expected vector, got %08X", vectorMagic); |
| 267 | return; |
| 268 | } |
| 269 | int32_t recvCount=in.ReadInt32(); |
| 270 | //LOGV("%d received packets", recvCount); |
| 271 | for(int i=0;i<recvCount;i++){ |
| 272 | uint32_t p=(uint32_t) in.ReadInt32(); |
| 273 | //LOGV("Relay received packet: %08X", p); |
| 274 | uint16_t id=(uint16_t) (p & 0xFFFF); |
| 275 | //LOGV("ack id %04X", id); |
| 276 | for(vector<PacketIdMapping>::iterator pkt=recentSentPackets.begin();pkt!=recentSentPackets.end();++pkt){ |
| 277 | //LOGV("== sent id %04X", pkt->id); |
| 278 | if(pkt->id==id){ |
| 279 | if(!pkt->ackTime){ |
| 280 | pkt->ackTime=GetCurrentTime(); |
| 281 | conctl->PacketAcknowledged(pkt->seq); |
| 282 | //LOGV("relay acknowledged packet %u", pkt->seq); |
| 283 | if(seqgt(pkt->seq, lastRemoteAckSeq)) |
| 284 | lastRemoteAckSeq=pkt->seq; |
| 285 | } |
| 286 | break; |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | vectorMagic=in.ReadInt32(); |
| 291 | if(vectorMagic!=TLID_VECTOR){ |
| 292 | LOGW("last packets info: expected vector, got %08X", vectorMagic); |
| 293 | return; |
| 294 | } |
| 295 | int32_t sentCount=in.ReadInt32(); |
| 296 | //LOGV("%d sent packets", sentCount); |
| 297 | for(int i=0;i<sentCount;i++){ |
| 298 | /*int32_t p=* /in.ReadInt32(); |
| 299 | //LOGV("Sent packet: %08X", p); |
| 300 | } |
| 301 | if(udpConnectivityState!=UDP_AVAILABLE) |
| 302 | udpConnectivityState=UDP_AVAILABLE; |
| 303 | if(state!=STATE_ESTABLISHED) |
| 304 | SetState(STATE_ESTABLISHED); |
| 305 | if(!audioInput){ |
| 306 | InitializeAudio(); |
| 307 | if(state!=STATE_FAILED){ |
| 308 | // audioOutput->Start(); |
| 309 | } |
| 310 | } |
| 311 | } |
| 312 | }catch(out_of_range& x){ |
| 313 | LOGE("Error parsing special response: %s", x.what()); |
| 314 | } |
| 315 | return; |
| 316 | } |
| 317 | } |
| 318 |
| 319 | if(packet.length<32) |
| 320 | return; |
| 321 |
| 322 | // it's a packet relayed from another participant - find the sender |
| 323 | MutexGuard m(participantsMutex); |
| 324 | GroupCallParticipant* sender=NULL; |
| 325 | for(vector<GroupCallParticipant>::iterator p=participants.begin();p!=participants.end();++p){ |
| 326 | if(memcmp(packet.data, p->memberTagHash, 16)==0){ |
| 327 | //LOGV("received data packet from user %d", p->userID); |
| 328 | sender=&*p; |
| 329 | break; |
| 330 | } |
| 331 | } |
| 332 | if(!sender){ |
| 333 | LOGV("Received data packet is from unknown user"); |
| 334 | return; |
| 335 | } |
| 336 |
| 337 | if(memcmp(packet.data+16, keyFingerprint, 8)!=0){ |
| 338 | LOGW("received packet has wrong key fingerprint"); |
| 339 | return; |
| 340 | } |
| 341 |
| 342 | BufferInputStream in(packet.data, packet.length-16); |
| 343 | in.Seek(16+8); // peer tag + key fingerprint |
| 344 |
| 345 | unsigned char msgKey[16]; |
| 346 | in.ReadBytes(msgKey, 16); |
| 347 |
| 348 | unsigned char decrypted[1500]; |
| 349 | unsigned char aesKey[32], aesIv[32]; |
| 350 | KDF2(msgKey, 0, aesKey, aesIv); |
| 351 | size_t decryptedLen=in.Remaining()-16; |
| 352 | if(decryptedLen>sizeof(decrypted)) |
| 353 | return; |
| 354 | //LOGV("-> MSG KEY: %08x %08x %08x %08x, hashed %u", *reinterpret_cast<int32_t*>(msgKey), *reinterpret_cast<int32_t*>(msgKey+4), *reinterpret_cast<int32_t*>(msgKey+8), *reinterpret_cast<int32_t*>(msgKey+12), decryptedLen-4); |
| 355 | uint8_t *decryptOffset = packet.data + in.GetOffset(); |
| 356 | if ((((intptr_t)decryptOffset) % sizeof(long)) != 0) { |
| 357 | LOGE("alignment2 packet.data+in.GetOffset()"); |
| 358 | } |
| 359 | if (decryptedLen % sizeof(long) != 0) { |
| 360 | LOGE("alignment2 decryptedLen"); |
| 361 | } |
| 362 | crypto.aes_ige_decrypt(packet.data+in.GetOffset(), decrypted, decryptedLen, aesKey, aesIv); |
| 363 |
| 364 | in=BufferInputStream(decrypted, decryptedLen); |
| 365 | //LOGD("received packet length: %d", in.ReadInt32()); |
| 366 |
| 367 | BufferOutputStream buf(decryptedLen+32); |
| 368 | size_t x=0; |
| 369 | buf.WriteBytes(encryptionKey+88+x, 32); |
| 370 | buf.WriteBytes(decrypted+4, decryptedLen-4); |
| 371 | unsigned char msgKeyLarge[32]; |
| 372 | crypto.sha256(buf.GetBuffer(), buf.GetLength(), msgKeyLarge); |
| 373 |
| 374 | if(memcmp(msgKey, msgKeyLarge+8, 16)!=0){ |
| 375 | LOGW("Received packet from user %d has wrong hash", sender->userID); |
| 376 | return; |
| 377 | } |
| 378 |
| 379 | uint32_t innerLen=(uint32_t) in.ReadInt32(); |
| 380 | if(innerLen>decryptedLen-4){ |
| 381 | LOGW("Received packet has wrong inner length (%d with total of %u)", (int)innerLen, (unsigned int)decryptedLen); |
| 382 | return; |
| 383 | } |
| 384 | if(decryptedLen-innerLen<12){ |
| 385 | LOGW("Received packet has too little padding (%u)", (unsigned int)(decryptedLen-innerLen)); |
| 386 | return; |
| 387 | } |
| 388 | in=BufferInputStream(decrypted+4, (size_t) innerLen); |
| 389 |
| 390 | uint32_t tlid=(uint32_t) in.ReadInt32(); |
| 391 | if(tlid!=TLID_DECRYPTED_AUDIO_BLOCK){ |
| 392 | LOGW("Received packet has unknown TL ID 0x%08x", tlid); |
| 393 | return; |
| 394 | } |
| 395 | in.Seek(in.GetOffset()+16); // random bytes |
| 396 | int32_t flags=in.ReadInt32(); |
| 397 | if(!(flags & PFLAG_HAS_SEQ) || !(flags & PFLAG_HAS_SENDER_TAG_HASH)){ |
| 398 | LOGW("Received packet has wrong flags"); |
| 399 | return; |
| 400 | } |
| 401 | /*uint32_t seq=(uint32_t) * /in.ReadInt32(); |
| 402 | unsigned char senderTagHash[16]; |
| 403 | in.ReadBytes(senderTagHash, 16); |
| 404 | if(memcmp(senderTagHash, sender->memberTagHash, 16)!=0){ |
| 405 | LOGW("Received packet has wrong inner sender tag hash"); |
| 406 | return; |
| 407 | } |
| 408 |
| 409 | //int32_t oneMoreInnerLengthWhyDoWeEvenNeedThis; |
| 410 | if(flags & PFLAG_HAS_DATA){ |
| 411 | /*oneMoreInnerLengthWhyDoWeEvenNeedThis=* /in.ReadTlLength(); |
| 412 | } |
| 413 | unsigned char type=(unsigned char) ((flags >> 24) & 0xFF); |
| 414 | lastRecvPacketTime=GetCurrentTime(); |
| 415 |
| 416 | if(type==PKT_STREAM_DATA || type==PKT_STREAM_DATA_X2 || type==PKT_STREAM_DATA_X3){ |
| 417 | if(state!=STATE_ESTABLISHED && receivedInitAck) |
| 418 | SetState(STATE_ESTABLISHED); |
| 419 | int count; |
| 420 | switch(type){ |
| 421 | case PKT_STREAM_DATA_X2: |
| 422 | count=2; |
| 423 | break; |
| 424 | case PKT_STREAM_DATA_X3: |
| 425 | count=3; |
| 426 | break; |
| 427 | case PKT_STREAM_DATA: |
| 428 | default: |
| 429 | count=1; |
| 430 | break; |
| 431 | } |
| 432 | int i; |
| 433 | //if(srcEndpoint->type==Endpoint::Type::UDP_RELAY && srcEndpoint!=peerPreferredRelay){ |
| 434 | // peerPreferredRelay=srcEndpoint; |
| 435 | //} |
| 436 | for(i=0;i<count;i++){ |
| 437 | unsigned char streamID=in.ReadByte(); |
| 438 | unsigned char sflags=(unsigned char) (streamID & 0xC0); |
| 439 | uint16_t sdlen=(uint16_t) (sflags & STREAM_DATA_FLAG_LEN16 ? in.ReadInt16() : in.ReadByte()); |
| 440 | uint32_t pts=(uint32_t) in.ReadInt32(); |
| 441 | //LOGD("stream data, pts=%d, len=%d, rem=%d", pts, sdlen, in.Remaining()); |
| 442 | audioTimestampIn=pts; |
| 443 | /*if(!audioOutStarted && audioOutput){ |
| 444 | audioOutput->Start(); |
| 445 | audioOutStarted=true; |
| 446 | }* / |
| 447 | if(in.GetOffset()+sdlen>in.GetLength()){ |
| 448 | return; |
| 449 | } |
| 450 | for(vector<shared_ptr<Stream>>::iterator stm=sender->streams.begin();stm!=sender->streams.end();++stm){ |
| 451 | if((*stm)->id==streamID){ |
| 452 | if((*stm)->jitterBuffer){ |
| 453 | (*stm)->jitterBuffer->HandleInput(decrypted+4+in.GetOffset(), sdlen, pts, false); |
| 454 | } |
| 455 | break; |
| 456 | } |
| 457 | } |
| 458 | if(i<count-1) |
| 459 | in.Seek(in.GetOffset()+sdlen); |
| 460 | } |
| 461 | }*/ |
| 462 | } |
| 463 |
| 464 | void VoIPGroupController::SendUdpPing(Endpoint& endpoint){ |
| 465 |
| 466 | } |
| 467 |
| 468 | void VoIPGroupController::SetNetworkType(int type){ |
| 469 | networkType=type; |
| 470 | UpdateDataSavingState(); |
| 471 | UpdateAudioBitrateLimit(); |
| 472 | string itfName=udpSocket->GetLocalInterfaceInfo(NULL, NULL); |
| 473 | if(itfName!=activeNetItfName){ |
| 474 | udpSocket->OnActiveInterfaceChanged(); |
| 475 | LOGI("Active network interface changed: %s -> %s", activeNetItfName.c_str(), itfName.c_str()); |
| 476 | bool isFirstChange=activeNetItfName.length()==0; |
| 477 | activeNetItfName=itfName; |
| 478 | if(isFirstChange) |
| 479 | return; |
| 480 | udpConnectivityState=UDP_UNKNOWN; |
| 481 | udpPingCount=0; |
| 482 | lastUdpPingTime=0; |
| 483 | if(proxyProtocol==PROXY_SOCKS5) |
| 484 | InitUDPProxy(); |
| 485 | selectCanceller->CancelSelect(); |
| 486 | } |
| 487 | } |
| 488 |
| 489 | void VoIPGroupController::SendRecentPacketsRequest(){ |
| 490 | BufferOutputStream out(1024); |
| 491 | out.WriteInt32(TLID_UDP_REFLECTOR_REQUEST_PACKETS_INFO); // TL function |
| 492 | out.WriteInt32(GetCurrentUnixtime()); // date:int |
| 493 | out.WriteInt64(0); // query_id:long |
| 494 | out.WriteInt32(64); // recv_num:int |
| 495 | out.WriteInt32(0); // sent_num:int |
| 496 | SendSpecialReflectorRequest(out.GetBuffer(), out.GetLength()); |
| 497 | } |
| 498 |
| 499 | void VoIPGroupController::SendSpecialReflectorRequest(unsigned char *data, size_t len){ |
| 500 | /*BufferOutputStream out(1024); |
| 501 | unsigned char buf[1500]; |
| 502 | crypto.rand_bytes(buf, 8); |
| 503 | out.WriteBytes(buf, 8); |
| 504 | out.WriteInt32((int32_t)len); |
| 505 | out.WriteBytes(data, len); |
| 506 | if(out.GetLength()%16!=0){ |
| 507 | size_t paddingLen=16-(out.GetLength()%16); |
| 508 | crypto.rand_bytes(buf, paddingLen); |
| 509 | out.WriteBytes(buf, paddingLen); |
| 510 | } |
| 511 | unsigned char iv[16]; |
| 512 | crypto.rand_bytes(iv, 16); |
| 513 | unsigned char key[32]; |
| 514 | crypto.sha256(reflectorSelfSecret, 16, key); |
| 515 | unsigned char _iv[16]; |
| 516 | memcpy(_iv, iv, 16); |
| 517 | size_t encryptedLen=out.GetLength(); |
| 518 | crypto.aes_cbc_encrypt(out.GetBuffer(), buf, encryptedLen, key, _iv); |
| 519 | out.Reset(); |
| 520 | out.WriteBytes(reflectorSelfTag, 16); |
| 521 | out.WriteBytes(iv, 16); |
| 522 | out.WriteBytes(buf, encryptedLen); |
| 523 | out.WriteBytes(reflectorSelfSecret, 16); |
| 524 | crypto.sha256(out.GetBuffer(), out.GetLength(), buf); |
| 525 | out.Rewind(16); |
| 526 | out.WriteBytes(buf, 16); |
| 527 |
| 528 | NetworkPacket pkt={0}; |
| 529 | pkt.address=&groupReflector.address; |
| 530 | pkt.port=groupReflector.port; |
| 531 | pkt.protocol=PROTO_UDP; |
| 532 | pkt.data=out.GetBuffer(); |
| 533 | pkt.length=out.GetLength(); |
| 534 | ActuallySendPacket(pkt, groupReflector);*/ |
| 535 | } |
| 536 |
| 537 | void VoIPGroupController::SendRelayPings(){ |
| 538 | //LOGV("Send relay pings 2"); |
| 539 | double currentTime=GetCurrentTime(); |
| 540 | if(currentTime-groupReflector.lastPingTime>=0.25){ |
| 541 | SendRecentPacketsRequest(); |
| 542 | groupReflector.lastPingTime=currentTime; |
| 543 | } |
| 544 | } |
| 545 |
| 546 | void VoIPGroupController::OnAudioOutputReady(){ |
| 547 | encoder->SetDTX(true); |
| 548 | audioMixer->SetOutput(audioOutput); |
| 549 | audioMixer->SetEchoCanceller(echoCanceller); |
| 550 | audioMixer->Start(); |
| 551 | audioOutput->Start(); |
| 552 | audioOutStarted=true; |
| 553 | encoder->SetLevelMeter(&selfLevelMeter); |
| 554 | } |
| 555 |
| 556 | void VoIPGroupController::WritePacketHeader(uint32_t seq, BufferOutputStream *s, unsigned char type, uint32_t length, PacketSender* source){ |
| 557 | s->WriteInt32(TLID_DECRYPTED_AUDIO_BLOCK); |
| 558 | int64_t randomID; |
| 559 | crypto.rand_bytes((uint8_t *) &randomID, 8); |
| 560 | s->WriteInt64(randomID); |
| 561 | unsigned char randBytes[7]; |
| 562 | crypto.rand_bytes(randBytes, 7); |
| 563 | s->WriteByte(7); |
| 564 | s->WriteBytes(randBytes, 7); |
| 565 | uint32_t pflags=PFLAG_HAS_SEQ | PFLAG_HAS_SENDER_TAG_HASH; |
| 566 | if(length>0) |
| 567 | pflags|=PFLAG_HAS_DATA; |
| 568 | pflags|=((uint32_t) type) << 24; |
| 569 | s->WriteInt32(pflags); |
| 570 |
| 571 | if(type==PKT_STREAM_DATA || type==PKT_STREAM_DATA_X2 || type==PKT_STREAM_DATA_X3){ |
| 572 | conctl->PacketSent(seq, length); |
| 573 | } |
| 574 |
| 575 | /*if(pflags & PFLAG_HAS_CALL_ID){ |
| 576 | s->WriteBytes(callID, 16); |
| 577 | }*/ |
| 578 | //s->WriteInt32(lastRemoteSeq); |
| 579 | s->WriteInt32(seq); |
| 580 | s->WriteBytes(reflectorSelfTagHash, 16); |
| 581 | if(length>0){ |
| 582 | if(length<=253){ |
| 583 | s->WriteByte((unsigned char) length); |
| 584 | }else{ |
| 585 | s->WriteByte(254); |
| 586 | s->WriteByte((unsigned char) (length & 0xFF)); |
| 587 | s->WriteByte((unsigned char) ((length >> 8) & 0xFF)); |
| 588 | s->WriteByte((unsigned char) ((length >> 16) & 0xFF)); |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 |
| 593 | void VoIPGroupController::SendPacket(unsigned char *data, size_t len, Endpoint& ep, PendingOutgoingPacket& srcPacket){ |
| 594 | if(stopping) |
| 595 | return; |
| 596 | if(ep.type==Endpoint::Type::TCP_RELAY && !useTCP) |
| 597 | return; |
| 598 | BufferOutputStream out(len+128); |
| 599 | //LOGV("send group packet %u", len); |
| 600 |
| 601 | out.WriteBytes(reflectorSelfTag, 16); |
| 602 |
| 603 | if(len>0){ |
| 604 | BufferOutputStream inner(len+128); |
| 605 | inner.WriteInt32((uint32_t)len); |
| 606 | inner.WriteBytes(data, len); |
| 607 | size_t padLen=16-inner.GetLength()%16; |
| 608 | if(padLen<12) |
| 609 | padLen+=16; |
| 610 | unsigned char padding[28]; |
| 611 | crypto.rand_bytes((uint8_t *) padding, padLen); |
| 612 | inner.WriteBytes(padding, padLen); |
| 613 | assert(inner.GetLength()%16==0); |
| 614 |
| 615 | unsigned char key[32], iv[32], msgKey[16]; |
| 616 | out.WriteBytes(keyFingerprint, 8); |
| 617 | BufferOutputStream buf(len+32); |
| 618 | size_t x=0; |
| 619 | buf.WriteBytes(encryptionKey+88+x, 32); |
| 620 | buf.WriteBytes(inner.GetBuffer()+4, inner.GetLength()-4); |
| 621 | unsigned char msgKeyLarge[32]; |
| 622 | crypto.sha256(buf.GetBuffer(), buf.GetLength(), msgKeyLarge); |
| 623 | memcpy(msgKey, msgKeyLarge+8, 16); |
| 624 | KDF2(msgKey, 0, key, iv); |
| 625 | out.WriteBytes(msgKey, 16); |
| 626 | //LOGV("<- MSG KEY: %08x %08x %08x %08x, hashed %u", *reinterpret_cast<int32_t*>(msgKey), *reinterpret_cast<int32_t*>(msgKey+4), *reinterpret_cast<int32_t*>(msgKey+8), *reinterpret_cast<int32_t*>(msgKey+12), inner.GetLength()-4); |
| 627 |
| 628 | unsigned char aesOut[MSC_STACK_FALLBACK(inner.GetLength(), 1500)]; |
| 629 | crypto.aes_ige_encrypt(inner.GetBuffer(), aesOut, inner.GetLength(), key, iv); |
| 630 | out.WriteBytes(aesOut, inner.GetLength()); |
| 631 | } |
| 632 |
| 633 | // relay signature |
| 634 | out.WriteBytes(reflectorSelfSecret, 16); |
| 635 | unsigned char sig[32]; |
| 636 | crypto.sha256(out.GetBuffer(), out.GetLength(), sig); |
| 637 | out.Rewind(16); |
| 638 | out.WriteBytes(sig, 16); |
| 639 |
| 640 | if(srcPacket.type==PKT_STREAM_DATA || srcPacket.type==PKT_STREAM_DATA_X2 || srcPacket.type==PKT_STREAM_DATA_X3){ |
| 641 | PacketIdMapping mapping={srcPacket.seq, *reinterpret_cast<uint16_t*>(sig+14), 0}; |
| 642 | MutexGuard m(sentPacketsMutex); |
| 643 | recentSentPackets.push_back(mapping); |
| 644 | //LOGD("sent packet with id: %04X", mapping.id); |
| 645 | while(recentSentPackets.size()>64) |
| 646 | recentSentPackets.erase(recentSentPackets.begin()); |
| 647 | } |
| 648 | lastSentSeq=srcPacket.seq; |
| 649 |
| 650 | if(IS_MOBILE_NETWORK(networkType)) |
| 651 | stats.bytesSentMobile+=(uint64_t)out.GetLength(); |
| 652 | else |
| 653 | stats.bytesSentWifi+=(uint64_t)out.GetLength(); |
| 654 |
| 655 | /*NetworkPacket pkt={0}; |
| 656 | pkt.address=(NetworkAddress*)&ep.address; |
| 657 | pkt.port=ep.port; |
| 658 | pkt.length=out.GetLength(); |
| 659 | pkt.data=out.GetBuffer(); |
| 660 | pkt.protocol=ep.type==Endpoint::Type::TCP_RELAY ? PROTO_TCP : PROTO_UDP; |
| 661 | ActuallySendPacket(pkt, ep);*/ |
| 662 | } |
| 663 |
| 664 | void VoIPGroupController::SetCallbacks(VoIPGroupController::Callbacks callbacks){ |
| 665 | VoIPController::SetCallbacks(callbacks); |
| 666 | this->groupCallbacks=callbacks; |
| 667 | } |
| 668 |
| 669 | int32_t VoIPGroupController::GetCurrentUnixtime(){ |
| 670 | return time(NULL)+timeDifference; |
| 671 | } |
| 672 |
| 673 | float VoIPGroupController::GetParticipantAudioLevel(int32_t userID){ |
| 674 | if(userID==userSelfID) |
| 675 | return selfLevelMeter.GetLevel(); |
| 676 | MutexGuard m(participantsMutex); |
| 677 | for(vector<GroupCallParticipant>::iterator p=participants.begin(); p!=participants.end(); ++p){ |
| 678 | if(p->userID==userID){ |
| 679 | return p->levelMeter->GetLevel(); |
| 680 | } |
| 681 | } |
| 682 | return 0; |
| 683 | } |
| 684 |
| 685 | void VoIPGroupController::SetMicMute(bool mute){ |
| 686 | micMuted=mute; |
| 687 | if(audioInput){ |
| 688 | if(mute) |
| 689 | audioInput->Stop(); |
| 690 | else |
| 691 | audioInput->Start(); |
| 692 | if(!audioInput->IsInitialized()){ |
| 693 | lastError=ERROR_AUDIO_IO; |
| 694 | SetState(STATE_FAILED); |
| 695 | return; |
| 696 | } |
| 697 | } |
| 698 | outgoingStreams[0]->enabled=!mute; |
| 699 | SerializeAndUpdateOutgoingStreams(); |
| 700 | } |
| 701 |
| 702 | void VoIPGroupController::SetParticipantVolume(int32_t userID, float volume){ |
| 703 | MutexGuard m(participantsMutex); |
| 704 | for(vector<GroupCallParticipant>::iterator p=participants.begin();p!=participants.end();++p){ |
| 705 | if(p->userID==userID){ |
| 706 | for(vector<shared_ptr<Stream>>::iterator s=p->streams.begin();s!=p->streams.end();++s){ |
| 707 | if((*s)->type==STREAM_TYPE_AUDIO){ |
| 708 | if((*s)->decoder){ |
| 709 | float db; |
| 710 | if(volume==0.0f) |
| 711 | db=-INFINITY; |
| 712 | else if(volume<1.0f) |
| 713 | db=-50.0f*(1.0f-volume); |
| 714 | else if(volume>1.0f && volume<=2.0f) |
| 715 | db=10.0f*(volume-1.0f); |
| 716 | else |
| 717 | db=0.0f; |
| 718 | //LOGV("Setting user %u audio volume to %.2f dB", userID, db); |
| 719 | audioMixer->SetInputVolume((*s)->callbackWrapper, db); |
| 720 | } |
| 721 | break; |
| 722 | } |
| 723 | } |
| 724 | break; |
| 725 | } |
| 726 | } |
| 727 | } |
| 728 |
| 729 | void VoIPGroupController::SerializeAndUpdateOutgoingStreams(){ |
| 730 | BufferOutputStream out(1024); |
| 731 | out.WriteByte((unsigned char) outgoingStreams.size()); |
| 732 |
| 733 | for(vector<shared_ptr<Stream>>::iterator s=outgoingStreams.begin(); s!=outgoingStreams.end(); ++s){ |
| 734 | BufferOutputStream o(128); |
| 735 | o.WriteByte((*s)->id); |
| 736 | o.WriteByte((*s)->type); |
| 737 | o.WriteInt32((*s)->codec); |
| 738 | o.WriteInt32((unsigned char) (((*s)->enabled ? STREAM_FLAG_ENABLED : 0) | STREAM_FLAG_DTX)); |
| 739 | o.WriteInt16((*s)->frameDuration); |
| 740 | out.WriteInt16((int16_t) o.GetLength()); |
| 741 | out.WriteBytes(o.GetBuffer(), o.GetLength()); |
| 742 | } |
| 743 | if(groupCallbacks.updateStreams) |
| 744 | groupCallbacks.updateStreams(this, out.GetBuffer(), out.GetLength()); |
| 745 | } |
| 746 |
| 747 | std::string VoIPGroupController::GetDebugString(){ |
| 748 | std::string r="Remote endpoints: \n"; |
| 749 | char buffer[2048]; |
| 750 | for(pair<const int64_t, Endpoint>& _endpoint:endpoints){ |
| 751 | Endpoint& endpoint=_endpoint.second; |
| 752 | const char* type; |
| 753 | switch(endpoint.type){ |
| 754 | case Endpoint::Type::UDP_P2P_INET: |
| 755 | type="UDP_P2P_INET"; |
| 756 | break; |
| 757 | case Endpoint::Type::UDP_P2P_LAN: |
| 758 | type="UDP_P2P_LAN"; |
| 759 | break; |
| 760 | case Endpoint::Type::UDP_RELAY: |
| 761 | type="UDP_RELAY"; |
| 762 | break; |
| 763 | case Endpoint::Type::TCP_RELAY: |
| 764 | type="TCP_RELAY"; |
| 765 | break; |
| 766 | default: |
| 767 | type="UNKNOWN"; |
| 768 | break; |
| 769 | } |
| 770 | snprintf(buffer, sizeof(buffer), "%s:%u %dms [%s%s]\n", endpoint.address.ToString().c_str(), endpoint.port, (int)(endpoint.averageRTT*1000), type, currentEndpoint==endpoint.id ? ", IN_USE" : ""); |
| 771 | r+=buffer; |
| 772 | } |
| 773 | double avgLate[3]; |
| 774 | shared_ptr<JitterBuffer> jitterBuffer=incomingStreams.size()==1 ? incomingStreams[0]->jitterBuffer : NULL; |
| 775 | if(jitterBuffer) |
| 776 | jitterBuffer->GetAverageLateCount(avgLate); |
| 777 | else |
| 778 | memset(avgLate, 0, 3*sizeof(double)); |
| 779 | snprintf(buffer, sizeof(buffer), |
| 780 | "RTT avg/min: %d/%d\n" |
| 781 | "Congestion window: %d/%d bytes\n" |
| 782 | "Key fingerprint: %02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX%02hhX\n" |
| 783 | "Last sent/ack'd seq: %u/%u\n" |
| 784 | "Send/recv losses: %u/%u (%d%%)\n" |
| 785 | "Audio bitrate: %d kbit\n" |
| 786 | "Bytes sent/recvd: %llu/%llu\n\n", |
| 787 | (int)(conctl->GetAverageRTT()*1000), (int)(conctl->GetMinimumRTT()*1000), |
| 788 | int(conctl->GetInflightDataSize()), int(conctl->GetCongestionWindow()), |
| 789 | keyFingerprint[0],keyFingerprint[1],keyFingerprint[2],keyFingerprint[3],keyFingerprint[4],keyFingerprint[5],keyFingerprint[6],keyFingerprint[7], |
| 790 | lastSentSeq, lastRemoteAckSeq, |
| 791 | conctl->GetSendLossCount(), recvLossCount, encoder ? encoder->GetPacketLoss() : 0, |
| 792 | encoder ? (encoder->GetBitrate()/1000) : 0, |
| 793 | (long long unsigned int)(stats.bytesSentMobile+stats.bytesSentWifi), |
| 794 | (long long unsigned int)(stats.bytesRecvdMobile+stats.bytesRecvdWifi)); |
| 795 |
| 796 | MutexGuard m(participantsMutex); |
| 797 | for(vector<GroupCallParticipant>::iterator p=participants.begin();p!=participants.end();++p){ |
| 798 | snprintf(buffer, sizeof(buffer), "Participant id: %d\n", p->userID); |
| 799 | r+=buffer; |
| 800 | for(vector<shared_ptr<Stream>>::iterator stm=p->streams.begin();stm!=p->streams.end();++stm){ |
| 801 | char* codec=reinterpret_cast<char*>(&(*stm)->codec); |
| 802 | snprintf(buffer, sizeof(buffer), "Stream %d (type %d, codec '%c%c%c%c', %sabled)\n", |
| 803 | (*stm)->id, (*stm)->type, codec[3], codec[2], codec[1], codec[0], (*stm)->enabled ? "en" : "dis"); |
| 804 | r+=buffer; |
| 805 | if((*stm)->enabled){ |
| 806 | if((*stm)->jitterBuffer){ |
| 807 | snprintf(buffer, sizeof(buffer), "Jitter buffer: %d/%.2f\n", |
| 808 | (*stm)->jitterBuffer->GetMinPacketCount(), (*stm)->jitterBuffer->GetAverageDelay()); |
| 809 | r+=buffer; |
| 810 | } |
| 811 | } |
| 812 | } |
| 813 | r+="\n"; |
| 814 | } |
| 815 | return r; |
| 816 | } |
| 817 |