| #include "rtc_base/byte_buffer.h" |
| 6 | #include "rtc_base/time_utils.h" |
| 7 |
| 8 | namespace tgcalls { |
| 9 | namespace { |
| 10 |
| 11 | constexpr auto kSingleMessagePacketSeqBit = (uint32_t(1) << 31); |
| 12 | constexpr auto kMessageRequiresAckSeqBit = (uint32_t(1) << 30); |
| 13 | constexpr auto kMaxAllowedCounter = std::numeric_limits<uint32_t>::max() |
| 14 | & ~kSingleMessagePacketSeqBit |
| 15 | & ~kMessageRequiresAckSeqBit; |
| 16 |
| 17 | static_assert(kMaxAllowedCounter < kSingleMessagePacketSeqBit, "bad"); |
| 18 | static_assert(kMaxAllowedCounter < kMessageRequiresAckSeqBit, "bad"); |
| 19 |
| 20 | constexpr auto kAckSerializedSize = sizeof(uint32_t) + sizeof(uint8_t); |
| 21 | constexpr auto kNotAckedMessagesLimit = 64 * 1024; |
| 22 | constexpr auto kMaxIncomingPacketSize = 128 * 1024; // don't try decrypting more |
| 23 | constexpr auto kKeepIncomingCountersCount = 64; |
| 24 | constexpr auto kMaxFullPacketSize = 1500; // IP_PACKET_SIZE from webrtc. |
| 25 |
| 26 | // Max seen turn_overhead is around 36. |
| 27 | constexpr auto kMaxOuterPacketSize = kMaxFullPacketSize - 48; |
| 28 |
| 29 | constexpr auto kMaxSignalingPacketSize = 16 * 1024; |
| 30 |
| 31 | constexpr auto kServiceCauseAcks = 1; |
| 32 | constexpr auto kServiceCauseResend = 2; |
| 33 |
| 34 | static constexpr uint8_t kAckId = uint8_t(-1); |
| 35 | static constexpr uint8_t kEmptyId = uint8_t(-2); |
| 36 | static constexpr uint8_t kCustomId = uint8_t(127); |
| 37 |
| 38 | void AppendSeq(rtc::CopyOnWriteBuffer &buffer, uint32_t seq) { |
| 39 | const auto bytes = rtc::HostToNetwork32(seq); |
| 40 | buffer.AppendData(reinterpret_cast<const char*>(&bytes), sizeof(bytes)); |
| 41 | } |
| 42 |
| 43 | void WriteSeq(void *bytes, uint32_t seq) { |
| 44 | *reinterpret_cast<uint32_t*>(bytes) = rtc::HostToNetwork32(seq); |
| 45 | } |
| 46 |
| 47 | uint32_t ReadSeq(const void *bytes) { |
| 48 | return rtc::NetworkToHost32(*reinterpret_cast<const uint32_t*>(bytes)); |
| 49 | } |
| 50 |
| 51 | uint32_t CounterFromSeq(uint32_t seq) { |
| 52 | return seq & ~kSingleMessagePacketSeqBit & ~kMessageRequiresAckSeqBit; |
| 53 | } |
| 54 |
| 55 | absl::nullopt_t LogError( |
| 56 | const char *message, |
| 57 | const std::string &additional = std::string()) { |
| 58 | RTC_LOG(LS_ERROR) << "ERROR! " << message << additional; |
| 59 | return absl::nullopt; |
| 60 | } |
| 61 |
| 62 | bool ConstTimeIsDifferent(const void *a, const void *b, size_t size) { |
| 63 | auto ca = reinterpret_cast<const char*>(a); |
| 64 | auto cb = reinterpret_cast<const char*>(b); |
| 65 | volatile auto different = false; |
| 66 | for (const auto ce = ca + size; ca != ce; ++ca, ++cb) { |
| 67 | different = different | (*ca != *cb); |
| 68 | } |
| 69 | return different; |
| 70 | } |
| 71 |
| 72 | rtc::CopyOnWriteBuffer SerializeRawMessageWithSeq( |
| 73 | const rtc::CopyOnWriteBuffer &message, |
| 74 | uint32_t seq, |
| 75 | bool singleMessagePacket) { |
| 76 | rtc::ByteBufferWriter writer; |
| 77 | writer.WriteUInt32(seq); |
| 78 | writer.WriteUInt8(kCustomId); |
| 79 | writer.WriteUInt32((uint32_t)message.size()); |
| 80 | writer.WriteBytes((const uint8_t *)message.data(), message.size()); |
| 81 |
| 82 | auto result = rtc::CopyOnWriteBuffer(); |
| 83 | result.AppendData(writer.Data(), writer.Length()); |
| 84 |
| 85 | return result; |
| 86 | } |
| 87 |
| 88 | } // namespace |
| 89 |
| 90 | EncryptedConnection::EncryptedConnection( |
| 91 | Type type, |
| 92 | const EncryptionKey &key, |
| 93 | std::function<void(int delayMs, int cause)> requestSendService) : |
| 94 | _type(type), |
| 95 | _key(key), |
| 96 | _delayIntervals(DelayIntervalsByType(type)), |
| 97 | _requestSendService(std::move(requestSendService)) { |
| 98 | assert(_key.value != nullptr); |
| 99 | } |
| 100 |
| 101 | absl::optional<rtc::CopyOnWriteBuffer> EncryptedConnection::encryptRawPacket(rtc::CopyOnWriteBuffer const &buffer) { |
| 102 | auto seq = ++_counter; |
| 103 |
| 104 | rtc::ByteBufferWriter writer; |
| 105 | writer.WriteUInt32(seq); |
| 106 |
| 107 | auto result = rtc::CopyOnWriteBuffer(); |
| 108 | result.AppendData(writer.Data(), writer.Length()); |
| 109 |
| 110 | result.AppendData(buffer); |
| 111 |
| 112 | auto encryptedPacket = encryptPrepared(result); |
| 113 |
| 114 | rtc::CopyOnWriteBuffer encryptedBuffer; |
| 115 | encryptedBuffer.AppendData(encryptedPacket.bytes.data(), encryptedPacket.bytes.size()); |
| 116 | return encryptedBuffer; |
| 117 | } |
| 118 |
| 119 | absl::optional<rtc::CopyOnWriteBuffer> EncryptedConnection::decryptRawPacket(rtc::CopyOnWriteBuffer const &buffer) { |
| 120 | if (buffer.size() < 21 || buffer.size() > kMaxIncomingPacketSize) { |
| 121 | return absl::nullopt; |
| 122 | } |
| 123 |
| 124 | const auto x = (_key.isOutgoing ? 8 : 0) + (_type == Type::Signaling ? 128 : 0); |
| 125 | const auto key = _key.value->data(); |
| 126 | const auto msgKey = reinterpret_cast<const uint8_t*>(buffer.data()); |
| 127 | const auto encryptedData = msgKey + 16; |
| 128 | const auto dataSize = buffer.size() - 16; |
| 129 |
| 130 | auto aesKeyIv = PrepareAesKeyIv(key, msgKey, x); |
| 131 |
| 132 | auto decryptionBuffer = rtc::Buffer(dataSize); |
| 133 | AesProcessCtr( |
| 134 | MemorySpan{ encryptedData, dataSize }, |
| 135 | decryptionBuffer.data(), |
| 136 | std::move(aesKeyIv)); |
| 137 |
| 138 | const auto msgKeyLarge = ConcatSHA256( |
| 139 | MemorySpan{ key + 88 + x, 32 }, |
| 140 | MemorySpan{ decryptionBuffer.data(), decryptionBuffer.size() }); |
| 141 | if (ConstTimeIsDifferent(msgKeyLarge.data() + 8, msgKey, 16)) { |
| 142 | return absl::nullopt; |
| 143 | } |
| 144 |
| 145 | const auto incomingSeq = ReadSeq(decryptionBuffer.data()); |
| 146 | const auto incomingCounter = CounterFromSeq(incomingSeq); |
| 147 | if (!registerIncomingCounter(incomingCounter)) { |
| 148 | // We've received that packet already. |
| 149 | return absl::nullopt; |
| 150 | } |
| 151 |
| 152 | rtc::CopyOnWriteBuffer resultBuffer; |
| 153 | resultBuffer.AppendData(decryptionBuffer.data() + 4, decryptionBuffer.size() - 4); |
| 154 | return resultBuffer; |
| 155 | } |
| 156 |
| 157 | auto EncryptedConnection::prepareForSending(const Message &message) |
| 158 | -> absl::optional<EncryptedPacket> { |
| 159 | const auto messageRequiresAck = absl::visit([](const auto &data) { |
| 160 | return std::decay_t<decltype(data)>::kRequiresAck; |
| 161 | }, message.data); |
| 162 |
| 163 | // If message requires ack, then we can't serialize it as a single |
| 164 | // message packet, because later it may be sent as a part of big packet. |
| 165 | const auto singleMessagePacket = !haveAdditionalMessages() && !messageRequiresAck; |
| 166 | const auto maybeSeq = computeNextSeq(messageRequiresAck, singleMessagePacket); |
| 167 | if (!maybeSeq) { |
| 168 | return absl::nullopt; |
| 169 | } |
| 170 | const auto seq = *maybeSeq; |
| 171 | auto serialized = SerializeMessageWithSeq(message, seq, singleMessagePacket); |
| 172 |
| 173 | return prepareForSendingMessageInternal(serialized, seq, messageRequiresAck); |
| 174 | } |
| 175 |
| 176 | absl::optional<EncryptedConnection::EncryptedPacket> EncryptedConnection::prepareForSendingRawMessage(rtc::CopyOnWriteBuffer &message, bool messageRequiresAck) { |
| 177 | // If message requires ack, then we can't serialize it as a single |
| 178 | // message packet, because later it may be sent as a part of big packet. |
| 179 | const auto singleMessagePacket = !haveAdditionalMessages() && !messageRequiresAck; |
| 180 | const auto maybeSeq = computeNextSeq(messageRequiresAck, singleMessagePacket); |
| 181 | if (!maybeSeq) { |
| 182 | return absl::nullopt; |
| 183 | } |
| 184 | const auto seq = *maybeSeq; |
| 185 | auto serialized = SerializeRawMessageWithSeq(message, seq, singleMessagePacket); |
| 186 |
| 187 | return prepareForSendingMessageInternal(serialized, seq, messageRequiresAck); |
| 188 | } |
| 189 |
| 190 | absl::optional<EncryptedConnection::EncryptedPacket> EncryptedConnection::prepareForSendingMessageInternal(rtc::CopyOnWriteBuffer &serialized, uint32_t seq, bool messageRequiresAck) { |
| 191 | if (!enoughSpaceInPacket(serialized, 0)) { |
| 192 | return LogError("Too large packet: ", std::to_string(serialized.size())); |
| 193 | } |
| 194 | const auto notYetAckedCopy = messageRequiresAck |
| 195 | ? serialized |
| 196 | : rtc::CopyOnWriteBuffer(); |
| 197 | if (!messageRequiresAck) { |
| 198 | appendAdditionalMessages(serialized); |
| 199 | return encryptPrepared(serialized); |
| 200 | } |
| 201 | const auto type = uint8_t(serialized.cdata()[4]); |
| 202 | const auto sendEnqueued = !_myNotYetAckedMessages.empty(); |
| 203 | if (sendEnqueued) { |
| 204 | // All requiring ack messages should always be sent in order within |
| 205 | // one packet, starting with the least not-yet-acked one. |
| 206 | // So if we still have those, we send an empty message with all |
| 207 | // requiring ack messages that will fit in correct order. |
| 208 | RTC_LOG(LS_INFO) << logHeader() |
| 209 | << "Enqueue SEND:type" << type << "#" << CounterFromSeq(seq); |
| 210 | } else { |
| 211 | RTC_LOG(LS_INFO) << logHeader() |
| 212 | << "Add SEND:type" << type << "#" << CounterFromSeq(seq); |
| 213 | appendAdditionalMessages(serialized); |
| 214 | } |
| 215 | _myNotYetAckedMessages.push_back({ notYetAckedCopy, rtc::TimeMillis() }); |
| 216 | if (!sendEnqueued) { |
| 217 | return encryptPrepared(serialized); |
| 218 | } |
| 219 | for (auto &queued : _myNotYetAckedMessages) { |
| 220 | queued.lastSent = 0; |
| 221 | } |
| 222 | return prepareForSendingService(0); |
| 223 | } |
| 224 |
| 225 | auto EncryptedConnection::prepareForSendingService(int cause) |
| 226 | -> absl::optional<EncryptedPacket> { |
| 227 | if (cause == kServiceCauseAcks) { |
| 228 | _sendAcksTimerActive = false; |
| 229 | } else if (cause == kServiceCauseResend) { |
| 230 | _resendTimerActive = false; |
| 231 | } |
| 232 | if (!haveAdditionalMessages()) { |
| 233 | return absl::nullopt; |
| 234 | } |
| 235 | const auto messageRequiresAck = false; |
| 236 | const auto singleMessagePacket = false; |
| 237 | const auto seq = computeNextSeq(messageRequiresAck, singleMessagePacket); |
| 238 | if (!seq) { |
| 239 | return absl::nullopt; |
| 240 | } |
| 241 | auto serialized = SerializeEmptyMessageWithSeq(*seq); |
| 242 | assert(enoughSpaceInPacket(serialized, 0)); |
| 243 |
| 244 | RTC_LOG(LS_INFO) << logHeader() |
| 245 | << "SEND:empty#" << CounterFromSeq(*seq); |
| 246 |
| 247 | appendAdditionalMessages(serialized); |
| 248 | return encryptPrepared(serialized); |
| 249 | } |
| 250 |
| 251 | bool EncryptedConnection::haveAdditionalMessages() const { |
| 252 | return !_myNotYetAckedMessages.empty() || !_acksToSendSeqs.empty(); |
| 253 | } |
| 254 |
| 255 | absl::optional<uint32_t> EncryptedConnection::computeNextSeq( |
| 256 | bool messageRequiresAck, |
| 257 | bool singleMessagePacket) { |
| 258 | if (messageRequiresAck && _myNotYetAckedMessages.size() >= kNotAckedMessagesLimit) { |
| 259 | return LogError("Too many not ACKed messages."); |
| 260 | } else if (_counter == kMaxAllowedCounter) { |
| 261 | return LogError("Outgoing packet limit reached."); |
| 262 | } |
| 263 |
| 264 | return (++_counter) |
| 265 | | (singleMessagePacket ? kSingleMessagePacketSeqBit : 0) |
| 266 | | (messageRequiresAck ? kMessageRequiresAckSeqBit : 0); |
| 267 | } |
| 268 |
| 269 | size_t EncryptedConnection::packetLimit() const { |
| 270 | switch (_type) { |
| 271 | case Type::Signaling: |
| 272 | return kMaxSignalingPacketSize; |
| 273 | default: |
| 274 | return kMaxOuterPacketSize; |
| 275 | } |
| 276 | } |
| 277 |
| 278 | bool EncryptedConnection::enoughSpaceInPacket(const rtc::CopyOnWriteBuffer &buffer, size_t amount) const { |
| 279 | const auto limit = packetLimit(); |
| 280 | return (amount < limit) |
| 281 | && (16 + buffer.size() + amount <= limit); |
| 282 | } |
| 283 |
| 284 | void EncryptedConnection::appendAcksToSend(rtc::CopyOnWriteBuffer &buffer) { |
| 285 | auto i = _acksToSendSeqs.begin(); |
| 286 | while ((i != _acksToSendSeqs.end()) |
| 287 | && enoughSpaceInPacket( |
| 288 | buffer, |
| 289 | kAckSerializedSize)) { |
| 290 |
| 291 | RTC_LOG(LS_INFO) << logHeader() |
| 292 | << "Add ACK#" << CounterFromSeq(*i); |
| 293 |
| 294 | AppendSeq(buffer, *i); |
| 295 | buffer.AppendData(&kAckId, 1); |
| 296 | ++i; |
| 297 | } |
| 298 | _acksToSendSeqs.erase(_acksToSendSeqs.begin(), i); |
| 299 | for (const auto seq : _acksToSendSeqs) { |
| 300 | RTC_LOG(LS_INFO) << logHeader() |
| 301 | << "Skip ACK#" << CounterFromSeq(seq) |
| 302 | << " (no space, length: " << kAckSerializedSize << ", already: " << buffer.size() << ")"; |
| 303 | } |
| 304 | } |
| 305 |
| 306 | size_t EncryptedConnection::fullNotAckedLength() const { |
| 307 | assert(_myNotYetAckedMessages.size() < kNotAckedMessagesLimit); |
| 308 |
| 309 | auto result = size_t(); |
| 310 | for (const auto &message : _myNotYetAckedMessages) { |
| 311 | result += message.data.size(); |
| 312 | } |
| 313 | return result; |
| 314 | } |
| 315 |
| 316 | void EncryptedConnection::appendAdditionalMessages(rtc::CopyOnWriteBuffer &buffer) { |
| 317 | appendAcksToSend(buffer); |
| 318 |
| 319 | if (_myNotYetAckedMessages.empty()) { |
| 320 | return; |
| 321 | } |
| 322 |
| 323 | const auto now = rtc::TimeMillis(); |
| 324 | for (auto &resending : _myNotYetAckedMessages) { |
| 325 | const auto sent = resending.lastSent; |
| 326 | const auto when = sent |
| 327 | ? (sent + _delayIntervals.minDelayBeforeMessageResend) |
| 328 | : 0; |
| 329 |
| 330 | assert(resending.data.size() >= 5); |
| 331 | const auto counter = CounterFromSeq(ReadSeq(resending.data.data())); |
| 332 | const auto type = uint8_t(resending.data.data()[4]); |
| 333 | if (when > now) { |
| 334 | RTC_LOG(LS_INFO) << logHeader() |
| 335 | << "Skip RESEND:type" << type << "#" << counter |
| 336 | << " (wait " << (when - now) << "ms)."; |
| 337 | break; |
| 338 | } else if (enoughSpaceInPacket(buffer, resending.data.size())) { |
| 339 | RTC_LOG(LS_INFO) << logHeader() |
| 340 | << "Add RESEND:type" << type << "#" << counter; |
| 341 | buffer.AppendData(resending.data); |
| 342 | resending.lastSent = now; |
| 343 | } else { |
| 344 | RTC_LOG(LS_INFO) << logHeader() |
| 345 | << "Skip RESEND:type" << type << "#" << counter |
| 346 | << " (no space, length: " << resending.data.size() << ", already: " << buffer.size() << ")"; |
| 347 | break; |
| 348 | } |
| 349 | } |
| 350 | if (!_resendTimerActive) { |
| 351 | _resendTimerActive = true; |
| 352 | _requestSendService( |
| 353 | _delayIntervals.maxDelayBeforeMessageResend, |
| 354 | kServiceCauseResend); |
| 355 | } |
| 356 | } |
| 357 |
| 358 | auto EncryptedConnection::encryptPrepared(const rtc::CopyOnWriteBuffer &buffer) |
| 359 | -> EncryptedPacket { |
| 360 | auto result = EncryptedPacket(); |
| 361 | result.counter = CounterFromSeq(ReadSeq(buffer.data())); |
| 362 | result.bytes.resize(16 + buffer.size()); |
| 363 |
| 364 | const auto x = (_key.isOutgoing ? 0 : 8) + (_type == Type::Signaling ? 128 : 0); |
| 365 | const auto key = _key.value->data(); |
| 366 |
| 367 | const auto msgKeyLarge = ConcatSHA256( |
| 368 | MemorySpan{ key + 88 + x, 32 }, |
| 369 | MemorySpan{ buffer.data(), buffer.size() }); |
| 370 | const auto msgKey = result.bytes.data(); |
| 371 | memcpy(msgKey, msgKeyLarge.data() + 8, 16); |
| 372 |
| 373 | auto aesKeyIv = PrepareAesKeyIv(key, msgKey, x); |
| 374 |
| 375 | AesProcessCtr( |
| 376 | MemorySpan{ buffer.data(), buffer.size() }, |
| 377 | result.bytes.data() + 16, |
| 378 | std::move(aesKeyIv)); |
| 379 |
| 380 | return result; |
| 381 | } |
| 382 |
| 383 | bool EncryptedConnection::registerIncomingCounter(uint32_t incomingCounter) { |
| 384 | auto &list = _largestIncomingCounters; |
| 385 |
| 386 | const auto position = std::lower_bound(list.begin(), list.end(), incomingCounter); |
| 387 | const auto largest = list.empty() ? 0 : list.back(); |
| 388 | if (position != list.end() && *position == incomingCounter) { |
| 389 | // The packet is in the list already. |
| 390 | return false; |
| 391 | } else if (incomingCounter + kKeepIncomingCountersCount <= largest) { |
| 392 | // The packet is too old. |
| 393 | return false; |
| 394 | } |
| 395 | const auto eraseTill = std::find_if(list.begin(), list.end(), [&](uint32_t counter) { |
| 396 | return (counter + kKeepIncomingCountersCount > incomingCounter); |
| 397 | }); |
| 398 | const auto eraseCount = eraseTill - list.begin(); |
| 399 | const auto positionIndex = (position - list.begin()) - eraseCount; |
| 400 | list.erase(list.begin(), eraseTill); |
| 401 |
| 402 | assert(positionIndex >= 0 && positionIndex <= list.size()); |
| 403 | list.insert(list.begin() + positionIndex, incomingCounter); |
| 404 | return true; |
| 405 | } |
| 406 |
| 407 | auto EncryptedConnection::handleIncomingPacket(const char *bytes, size_t size) |
| 408 | -> absl::optional<DecryptedPacket> { |
| 409 | if (size < 21 || size > kMaxIncomingPacketSize) { |
| 410 | return LogError("Bad incoming packet size: ", std::to_string(size)); |
| 411 | } |
| 412 |
| 413 | const auto x = (_key.isOutgoing ? 8 : 0) + (_type == Type::Signaling ? 128 : 0); |
| 414 | const auto key = _key.value->data(); |
| 415 | const auto msgKey = reinterpret_cast<const uint8_t*>(bytes); |
| 416 | const auto encryptedData = msgKey + 16; |
| 417 | const auto dataSize = size - 16; |
| 418 |
| 419 | auto aesKeyIv = PrepareAesKeyIv(key, msgKey, x); |
| 420 |
| 421 | auto decryptionBuffer = rtc::Buffer(dataSize); |
| 422 | AesProcessCtr( |
| 423 | MemorySpan{ encryptedData, dataSize }, |
| 424 | decryptionBuffer.data(), |
| 425 | std::move(aesKeyIv)); |
| 426 |
| 427 | const auto msgKeyLarge = ConcatSHA256( |
| 428 | MemorySpan{ key + 88 + x, 32 }, |
| 429 | MemorySpan{ decryptionBuffer.data(), decryptionBuffer.size() }); |
| 430 | if (ConstTimeIsDifferent(msgKeyLarge.data() + 8, msgKey, 16)) { |
| 431 | return LogError("Bad incoming data hash."); |
| 432 | } |
| 433 |
| 434 | const auto incomingSeq = ReadSeq(decryptionBuffer.data()); |
| 435 | const auto incomingCounter = CounterFromSeq(incomingSeq); |
| 436 | if (!registerIncomingCounter(incomingCounter)) { |
| 437 | // We've received that packet already. |
| 438 | return LogError("Already handled packet received.", std::to_string(incomingCounter)); |
| 439 | } |
| 440 | return processPacket(decryptionBuffer, incomingSeq); |
| 441 | } |
| 442 |
| 443 | absl::optional<EncryptedConnection::DecryptedRawPacket> EncryptedConnection::handleIncomingRawPacket(const char *bytes, size_t size) { |
| 444 | if (size < 21 || size > kMaxIncomingPacketSize) { |
| 445 | return LogError("Bad incoming packet size: ", std::to_string(size)); |
| 446 | } |
| 447 |
| 448 | const auto x = (_key.isOutgoing ? 8 : 0) + (_type == Type::Signaling ? 128 : 0); |
| 449 | const auto key = _key.value->data(); |
| 450 | const auto msgKey = reinterpret_cast<const uint8_t*>(bytes); |
| 451 | const auto encryptedData = msgKey + 16; |
| 452 | const auto dataSize = size - 16; |
| 453 |
| 454 | auto aesKeyIv = PrepareAesKeyIv(key, msgKey, x); |
| 455 |
| 456 | auto decryptionBuffer = rtc::Buffer(dataSize); |
| 457 | AesProcessCtr( |
| 458 | MemorySpan{ encryptedData, dataSize }, |
| 459 | decryptionBuffer.data(), |
| 460 | std::move(aesKeyIv)); |
| 461 |
| 462 | const auto msgKeyLarge = ConcatSHA256( |
| 463 | MemorySpan{ key + 88 + x, 32 }, |
| 464 | MemorySpan{ decryptionBuffer.data(), decryptionBuffer.size() }); |
| 465 | if (ConstTimeIsDifferent(msgKeyLarge.data() + 8, msgKey, 16)) { |
| 466 | return LogError("Bad incoming data hash."); |
| 467 | } |
| 468 |
| 469 | const auto incomingSeq = ReadSeq(decryptionBuffer.data()); |
| 470 | const auto incomingCounter = CounterFromSeq(incomingSeq); |
| 471 | if (!registerIncomingCounter(incomingCounter)) { |
| 472 | // We've received that packet already. |
| 473 | return LogError("Already handled packet received.", std::to_string(incomingCounter)); |
| 474 | } |
| 475 | return processRawPacket(decryptionBuffer, incomingSeq); |
| 476 | } |
| 477 |
| 478 | auto EncryptedConnection::processPacket( |
| 479 | const rtc::Buffer &fullBuffer, |
| 480 | uint32_t packetSeq) |
| 481 | -> absl::optional<DecryptedPacket> { |
| 482 | assert(fullBuffer.size() >= 5); |
| 483 |
| 484 | auto additionalMessage = false; |
| 485 | auto firstMessageRequiringAck = true; |
| 486 | auto newRequiringAckReceived = false; |
| 487 |
| 488 | auto currentSeq = packetSeq; |
| 489 | auto currentCounter = CounterFromSeq(currentSeq); |
| 490 | rtc::ByteBufferReader reader(rtc::ArrayView<const uint8_t>( |
| 491 | reinterpret_cast<const uint8_t *>(fullBuffer.data() + 4), // Skip seq. |
| 492 | fullBuffer.size() - 4)); |
| 493 |
| 494 | auto result = absl::optional<DecryptedPacket>(); |
| 495 | while (true) { |
| 496 | const auto type = uint8_t(*reader.Data()); |
| 497 | const auto singleMessagePacket = ((currentSeq & kSingleMessagePacketSeqBit) != 0); |
| 498 | if (singleMessagePacket && additionalMessage) { |
| 499 | return LogError("Single message packet bit in not first message."); |
| 500 | } |
| 501 |
| 502 | if (type == kEmptyId) { |
| 503 | if (additionalMessage) { |
| 504 | return LogError("Empty message should be only the first one in the packet."); |
| 505 | } |
| 506 | RTC_LOG(LS_INFO) << logHeader() |
| 507 | << "Got RECV:empty" << "#" << currentCounter; |
| 508 | reader.Consume(1); |
| 509 | } else if (type == kAckId) { |
| 510 | if (!additionalMessage) { |
| 511 | return LogError("Ack message must not be the first one in the packet."); |
| 512 | } |
| 513 | ackMyMessage(currentSeq); |
| 514 | reader.Consume(1); |
| 515 | } else if (auto message = DeserializeMessage(reader, singleMessagePacket)) { |
| 516 | const auto messageRequiresAck = ((currentSeq & kMessageRequiresAckSeqBit) != 0); |
| 517 | const auto skipMessage = messageRequiresAck |
| 518 | ? !registerSentAck(currentCounter, firstMessageRequiringAck) |
| 519 | : (additionalMessage && !registerIncomingCounter(currentCounter)); |
| 520 | if (messageRequiresAck) { |
| 521 | firstMessageRequiringAck = false; |
| 522 | if (!skipMessage) { |
| 523 | newRequiringAckReceived = true; |
| 524 | } |
| 525 | sendAckPostponed(currentSeq); |
| 526 | RTC_LOG(LS_INFO) << logHeader() |
| 527 | << (skipMessage ? "Repeated RECV:type" : "Got RECV:type") << type << "#" << currentCounter; |
| 528 | } |
| 529 | if (!skipMessage) { |
| 530 | appendReceivedMessage(result, std::move(*message), currentSeq); |
| 531 | } |
| 532 | } else { |
| 533 | return LogError("Could not parse message from packet, type: ", std::to_string(type)); |
| 534 | } |
| 535 | if (!reader.Length()) { |
| 536 | break; |
| 537 | } else if (singleMessagePacket) { |
| 538 | return LogError("Single message didn't fill the entire packet."); |
| 539 | } else if (reader.Length() < 5) { |
| 540 | return LogError("Bad remaining data size: ", std::to_string(reader.Length())); |
| 541 | } |
| 542 | const auto success = reader.ReadUInt32(¤tSeq); |
| 543 | assert(success); |
| 544 | (void)success; |
| 545 | currentCounter = CounterFromSeq(currentSeq); |
| 546 |
| 547 | additionalMessage = true; |
| 548 | } |
| 549 |
| 550 | if (!_acksToSendSeqs.empty()) { |
| 551 | if (newRequiringAckReceived) { |
| 552 | _requestSendService(0, 0); |
| 553 | } else if (!_sendAcksTimerActive) { |
| 554 | _sendAcksTimerActive = true; |
| 555 | _requestSendService( |
| 556 | _delayIntervals.maxDelayBeforeAckResend, |
| 557 | kServiceCauseAcks); |
| 558 | } |
| 559 | } |
| 560 |
| 561 | return result; |
| 562 | } |
| 563 |
| 564 | auto EncryptedConnection::processRawPacket( |
| 565 | const rtc::Buffer &fullBuffer, |
| 566 | uint32_t packetSeq) |
| 567 | -> absl::optional<DecryptedRawPacket> { |
| 568 | assert(fullBuffer.size() >= 5); |
| 569 |
| 570 | auto additionalMessage = false; |
| 571 | auto firstMessageRequiringAck = true; |
| 572 | auto newRequiringAckReceived = false; |
| 573 |
| 574 | auto currentSeq = packetSeq; |
| 575 | auto currentCounter = CounterFromSeq(currentSeq); |
| 576 | rtc::ByteBufferReader reader(rtc::ArrayView<const uint8_t>( |
| 577 | reinterpret_cast<const uint8_t *>(fullBuffer.data() + 4), // Skip seq. |
| 578 | fullBuffer.size() - 4)); |
| 579 |
| 580 | auto result = absl::optional<DecryptedRawPacket>(); |
| 581 | while (true) { |
| 582 | const auto type = uint8_t(*reader.Data()); |
| 583 | const auto singleMessagePacket = ((currentSeq & kSingleMessagePacketSeqBit) != 0); |
| 584 | if (singleMessagePacket && additionalMessage) { |
| 585 | return LogError("Single message packet bit in not first message."); |
| 586 | } |
| 587 |
| 588 | if (type == kEmptyId) { |
| 589 | if (additionalMessage) { |
| 590 | return LogError("Empty message should be only the first one in the packet."); |
| 591 | } |
| 592 | RTC_LOG(LS_INFO) << logHeader() |
| 593 | << "Got RECV:empty" << "#" << currentCounter; |
| 594 | reader.Consume(1); |
| 595 | } else if (type == kAckId) { |
| 596 | if (!additionalMessage) { |
| 597 | return LogError("Ack message must not be the first one in the packet."); |
| 598 | } |
| 599 | ackMyMessage(currentSeq); |
| 600 | reader.Consume(1); |
| 601 | } else if (type == kCustomId) { |
| 602 | reader.Consume(1); |
| 603 |
| 604 | if (auto message = DeserializeRawMessage(reader, singleMessagePacket)) { |
| 605 | const auto messageRequiresAck = ((currentSeq & kMessageRequiresAckSeqBit) != 0); |
| 606 | const auto skipMessage = messageRequiresAck |
| 607 | ? !registerSentAck(currentCounter, firstMessageRequiringAck) |
| 608 | : (additionalMessage && !registerIncomingCounter(currentCounter)); |
| 609 | if (messageRequiresAck) { |
| 610 | firstMessageRequiringAck = false; |
| 611 | if (!skipMessage) { |
| 612 | newRequiringAckReceived = true; |
| 613 | } |
| 614 | sendAckPostponed(currentSeq); |
| 615 | RTC_LOG(LS_INFO) << logHeader() |
| 616 | << (skipMessage ? "Repeated RECV:type" : "Got RECV:type") << type << "#" << currentCounter; |
| 617 | } |
| 618 | if (!skipMessage) { |
| 619 | appendReceivedRawMessage(result, std::move(*message), currentSeq); |
| 620 | } |
| 621 | } else { |
| 622 | return LogError("Could not parse message from packet, type: ", std::to_string(type)); |
| 623 | } |
| 624 | } else { |
| 625 | return LogError("Could not parse message from packet, type: ", std::to_string(type)); |
| 626 | } |
| 627 | if (!reader.Length()) { |
| 628 | break; |
| 629 | } else if (singleMessagePacket) { |
| 630 | return LogError("Single message didn't fill the entire packet."); |
| 631 | } else if (reader.Length() < 5) { |
| 632 | return LogError("Bad remaining data size: ", std::to_string(reader.Length())); |
| 633 | } |
| 634 | const auto success = reader.ReadUInt32(¤tSeq); |
| 635 | assert(success); |
| 636 | (void)success; |
| 637 | currentCounter = CounterFromSeq(currentSeq); |
| 638 |
| 639 | additionalMessage = true; |
| 640 | } |
| 641 |
| 642 | if (!_acksToSendSeqs.empty()) { |
| 643 | if (newRequiringAckReceived) { |
| 644 | _requestSendService(0, 0); |
| 645 | } else if (!_sendAcksTimerActive) { |
| 646 | _sendAcksTimerActive = true; |
| 647 | _requestSendService( |
| 648 | _delayIntervals.maxDelayBeforeAckResend, |
| 649 | kServiceCauseAcks); |
| 650 | } |
| 651 | } |
| 652 |
| 653 | return result; |
| 654 | } |
| 655 |
| 656 | void EncryptedConnection::appendReceivedMessage( |
| 657 | absl::optional<DecryptedPacket> &to, |
| 658 | Message &&message, |
| 659 | uint32_t incomingSeq) { |
| 660 | auto decrypted = DecryptedMessage{ |
| 661 | std::move(message), |
| 662 | CounterFromSeq(incomingSeq) |
| 663 | }; |
| 664 | if (to) { |
| 665 | to->additional.push_back(std::move(decrypted)); |
| 666 | } else { |
| 667 | to = DecryptedPacket{ std::move(decrypted) }; |
| 668 | } |
| 669 | } |
| 670 |
| 671 | void EncryptedConnection::appendReceivedRawMessage( |
| 672 | absl::optional<DecryptedRawPacket> &to, |
| 673 | rtc::CopyOnWriteBuffer &&message, |
| 674 | uint32_t incomingSeq) { |
| 675 | auto decrypted = DecryptedRawMessage{ |
| 676 | std::move(message), |
| 677 | CounterFromSeq(incomingSeq) |
| 678 | }; |
| 679 | if (to) { |
| 680 | to->additional.push_back(std::move(decrypted)); |
| 681 | } else { |
| 682 | to = DecryptedRawPacket{ std::move(decrypted) }; |
| 683 | } |
| 684 | } |
| 685 |
| 686 | const char *EncryptedConnection::logHeader() const { |
| 687 | return (_type == Type::Signaling) ? "(signaling) " : "(transport) "; |
| 688 | } |
| 689 |
| 690 | bool EncryptedConnection::registerSentAck(uint32_t counter, bool firstInPacket) { |
| 691 | auto &list = _acksSentCounters; |
| 692 |
| 693 | const auto position = std::lower_bound(list.begin(), list.end(), counter); |
| 694 | const auto already = (position != list.end()) && (*position == counter); |
| 695 |
| 696 | const auto was = list; |
| 697 | if (firstInPacket) { |
| 698 | list.erase(list.begin(), position); |
| 699 | if (!already) { |
| 700 | list.insert(list.begin(), counter); |
| 701 | } |
| 702 | } else if (!already) { |
| 703 | list.insert(position, counter); |
| 704 | } |
| 705 | return !already; |
| 706 | } |
| 707 |
| 708 | void EncryptedConnection::sendAckPostponed(uint32_t incomingSeq) { |
| 709 | auto &list = _acksToSendSeqs; |
| 710 | const auto already = std::find(list.begin(), list.end(), incomingSeq); |
| 711 | if (already == list.end()) { |
| 712 | list.push_back(incomingSeq); |
| 713 | } |
| 714 | } |
| 715 |
| 716 | void EncryptedConnection::ackMyMessage(uint32_t seq) { |
| 717 | auto type = uint8_t(0); |
| 718 | auto &list = _myNotYetAckedMessages; |
| 719 | for (auto i = list.begin(), e = list.end(); i != e; ++i) { |
| 720 | assert(i->data.size() >= 5); |
| 721 | if (ReadSeq(i->data.cdata()) == seq) { |
| 722 | type = uint8_t(i->data.cdata()[4]); |
| 723 | list.erase(i); |
| 724 | break; |
| 725 | } |
| 726 | } |
| 727 | RTC_LOG(LS_INFO) << logHeader() |
| 728 | << (type ? "Got ACK:type" + std::to_string(type) + "#" : "Repeated ACK#") |
| 729 | << CounterFromSeq(seq); |
| 730 | } |
| 731 |
| 732 | auto EncryptedConnection::DelayIntervalsByType(Type type) -> DelayIntervals { |
| 733 | auto result = DelayIntervals(); |
| 734 | const auto signaling = (type == Type::Signaling); |
| 735 |
| 736 | // Don't resend faster than min delay even if we have a packet we can attach to. |
| 737 | result.minDelayBeforeMessageResend = signaling ? 3000 : 300; |
| 738 |
| 739 | // When max delay elapsed we resend anyway, in a dedicated packet. |
| 740 | result.maxDelayBeforeMessageResend = signaling ? 5000 : 1000; |
| 741 | result.maxDelayBeforeAckResend = signaling ? 5000 : 1000; |
| 742 |
| 743 | return result; |
| 744 | } |
| 745 |
| 746 | rtc::CopyOnWriteBuffer EncryptedConnection::SerializeEmptyMessageWithSeq(uint32_t seq) { |
| 747 | auto result = rtc::CopyOnWriteBuffer(5); |
| 748 | auto bytes = result.MutableData(); |
| 749 | WriteSeq(bytes, seq); |
| 750 | bytes[4] = kEmptyId; |
| 751 | return result; |
| 752 | } |
| 753 |
| 754 | } // namespace tgcalls |
| 755 |