| 6 |
| * Copyright Nikolai Kudashov, 2015-2018. |
| 7 | */ |
| 8 |
| 9 | #include <openssl/rand.h> |
| 10 | #include <stdlib.h> |
| 11 | #include <cstring> |
| 12 | #include <openssl/sha.h> |
| 13 | #include <algorithm> |
| 14 | #include "Connection.h" |
| 15 | #include "ConnectionsManager.h" |
| 16 | #include "BuffersStorage.h" |
| 17 | #include "FileLog.h" |
| 18 | #include "Timer.h" |
| 19 | #include "Datacenter.h" |
| 20 | #include "NativeByteBuffer.h" |
| 21 | #include "ByteArray.h" |
| 22 |
| 23 | thread_local static uint32_t lastConnectionToken = 1; |
| 24 |
| 25 | Connection::Connection(Datacenter *datacenter, ConnectionType type, int8_t num) : ConnectionSession(datacenter->instanceNum), ConnectionSocket(datacenter->instanceNum) { |
| 26 | currentDatacenter = datacenter; |
| 27 | connectionNum = num; |
| 28 | connectionType = type; |
| 29 | genereateNewSessionId(); |
| 30 | connectionState = TcpConnectionStageIdle; |
| 31 | reconnectTimer = new Timer(datacenter->instanceNum, [&] { |
| 32 | reconnectTimer->stop(); |
| 33 | waitForReconnectTimer = false; |
| 34 | connect(); |
| 35 | }); |
| 36 | } |
| 37 |
| 38 | Connection::~Connection() { |
| 39 | if (reconnectTimer != nullptr) { |
| 40 | reconnectTimer->stop(); |
| 41 | delete reconnectTimer; |
| 42 | reconnectTimer = nullptr; |
| 43 | } |
| 44 | } |
| 45 |
| 46 | void Connection::suspendConnection() { |
| 47 | suspendConnection(false); |
| 48 | } |
| 49 |
| 50 | void Connection::suspendConnection(bool idle) { |
| 51 | reconnectTimer->stop(); |
| 52 | waitForReconnectTimer = false; |
| 53 | if (connectionState == TcpConnectionStageIdle || connectionState == TcpConnectionStageSuspended) { |
| 54 | return; |
| 55 | } |
| 56 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) suspend", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType); |
| 57 | connectionState = idle ? TcpConnectionStageIdle : TcpConnectionStageSuspended; |
| 58 | dropConnection(); |
| 59 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).onConnectionClosed(this, 0); |
| 60 | generation++; |
| 61 | firstPacketSent = false; |
| 62 | if (restOfTheData != nullptr) { |
| 63 | restOfTheData->reuse(); |
| 64 | restOfTheData = nullptr; |
| 65 | } |
| 66 | lastPacketLength = 0; |
| 67 | connectionToken = 0; |
| 68 | wasConnected = false; |
| 69 | } |
| 70 |
| 71 | void Connection::onReceivedData(NativeByteBuffer *buffer) { |
| 72 | AES_ctr128_encrypt(buffer->bytes(), buffer->bytes(), buffer->limit(), &decryptKey, decryptIv, decryptCount, &decryptNum); |
| 73 |
| 74 | failedConnectionCount = 0; |
| 75 |
| 76 | if (connectionType == ConnectionTypeGeneric || connectionType == ConnectionTypeTemp || connectionType == ConnectionTypeGenericMedia) { |
| 77 | receivedDataAmount += buffer->limit(); |
| 78 | if (receivedDataAmount >= 512 * 1024) { |
| 79 | if (currentTimeout > 4) { |
| 80 | currentTimeout -= 2; |
| 81 | setTimeout(currentTimeout); |
| 82 | } |
| 83 | receivedDataAmount = 0; |
| 84 | } |
| 85 | } |
| 86 |
| 87 | NativeByteBuffer *parseLaterBuffer = nullptr; |
| 88 | if (restOfTheData != nullptr) { |
| 89 | if (lastPacketLength == 0) { |
| 90 | if (restOfTheData->capacity() - restOfTheData->position() >= buffer->limit()) { |
| 91 | restOfTheData->limit(restOfTheData->position() + buffer->limit()); |
| 92 | restOfTheData->writeBytes(buffer); |
| 93 | buffer = restOfTheData; |
| 94 | } else { |
| 95 | NativeByteBuffer *newBuffer = BuffersStorage::getInstance().getFreeBuffer(restOfTheData->limit() + buffer->limit()); |
| 96 | restOfTheData->rewind(); |
| 97 | newBuffer->writeBytes(restOfTheData); |
| 98 | newBuffer->writeBytes(buffer); |
| 99 | buffer = newBuffer; |
| 100 | restOfTheData->reuse(); |
| 101 | restOfTheData = newBuffer; |
| 102 | } |
| 103 | } else { |
| 104 | uint32_t len; |
| 105 | if (lastPacketLength - restOfTheData->position() <= buffer->limit()) { |
| 106 | len = lastPacketLength - restOfTheData->position(); |
| 107 | } else { |
| 108 | len = buffer->limit(); |
| 109 | } |
| 110 | uint32_t oldLimit = buffer->limit(); |
| 111 | buffer->limit(len); |
| 112 | restOfTheData->writeBytes(buffer); |
| 113 | buffer->limit(oldLimit); |
| 114 | if (restOfTheData->position() == lastPacketLength) { |
| 115 | parseLaterBuffer = buffer->hasRemaining() ? buffer : nullptr; |
| 116 | buffer = restOfTheData; |
| 117 | } else { |
| 118 | // if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received packet size less(%u) then message size(%u)", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType, restOfTheData->position(), lastPacketLength); |
| 119 | return; |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 |
| 124 | buffer->rewind(); |
| 125 |
| 126 | NativeByteBuffer *reuseLater = nullptr; |
| 127 | while (buffer->hasRemaining()) { |
| 128 | if (!hasSomeDataSinceLastConnect) { |
| 129 | currentDatacenter->storeCurrentAddressAndPortNum(); |
| 130 | isTryingNextPort = false; |
| 131 | if (connectionType == ConnectionTypeProxy) { |
| 132 | setTimeout(5); |
| 133 | } else if (connectionType == ConnectionTypePush) { |
| 134 | setTimeout(60 * 15); |
| 135 | } else if (connectionType == ConnectionTypeUpload) { |
| 136 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).networkSlow) { |
| 137 | setTimeout(40); |
| 138 | } else { |
| 139 | setTimeout(25); |
| 140 | } |
| 141 | } else if (connectionType == ConnectionTypeDownload) { |
| 142 | setTimeout(25); |
| 143 | } else { |
| 144 | setTimeout(currentTimeout); |
| 145 | } |
| 146 | } |
| 147 | hasSomeDataSinceLastConnect = true; |
| 148 |
| 149 | uint32_t currentPacketLength = 0; |
| 150 | uint32_t mark = buffer->position(); |
| 151 | uint32_t len; |
| 152 |
| 153 | if (currentProtocolType == ProtocolTypeEF) { |
| 154 | uint8_t fByte = buffer->readByte(nullptr); |
| 155 |
| 156 | if ((fByte & (1 << 7)) != 0) { |
| 157 | buffer->position(mark); |
| 158 | if (buffer->remaining() < 4) { |
| 159 | reuseLater = restOfTheData; |
| 160 | restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384); |
| 161 | restOfTheData->writeBytes(buffer); |
| 162 | restOfTheData->limit(restOfTheData->position()); |
| 163 | lastPacketLength = 0; |
| 164 | break; |
| 165 | } |
| 166 | int32_t ackId = buffer->readBigInt32(nullptr) & (~(1 << 31)); |
| 167 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).onConnectionQuickAckReceived(this, ackId); |
| 168 | continue; |
| 169 | } |
| 170 |
| 171 | if (fByte != 0x7f) { |
| 172 | currentPacketLength = ((uint32_t) fByte) * 4; |
| 173 | } else { |
| 174 | buffer->position(mark); |
| 175 | if (buffer->remaining() < 4) { |
| 176 | if (restOfTheData == nullptr || (restOfTheData != nullptr && restOfTheData->position() != 0)) { |
| 177 | reuseLater = restOfTheData; |
| 178 | restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384); |
| 179 | restOfTheData->writeBytes(buffer); |
| 180 | restOfTheData->limit(restOfTheData->position()); |
| 181 | lastPacketLength = 0; |
| 182 | } else { |
| 183 | restOfTheData->position(restOfTheData->limit()); |
| 184 | } |
| 185 | break; |
| 186 | } |
| 187 | currentPacketLength = ((uint32_t) buffer->readInt32(nullptr) >> 8) * 4; |
| 188 | } |
| 189 |
| 190 | len = currentPacketLength + (fByte != 0x7f ? 1 : 4); |
| 191 | } else { |
| 192 | if (buffer->remaining() < 4) { |
| 193 | if (restOfTheData == nullptr || (restOfTheData != nullptr && restOfTheData->position() != 0)) { |
| 194 | reuseLater = restOfTheData; |
| 195 | restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384); |
| 196 | restOfTheData->writeBytes(buffer); |
| 197 | restOfTheData->limit(restOfTheData->position()); |
| 198 | lastPacketLength = 0; |
| 199 | } else { |
| 200 | restOfTheData->position(restOfTheData->limit()); |
| 201 | } |
| 202 | break; |
| 203 | } |
| 204 |
| 205 | uint32_t fInt = buffer->readUint32(nullptr); |
| 206 |
| 207 | if ((fInt & (0x80000000)) != 0) { |
| 208 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).onConnectionQuickAckReceived(this, fInt & (~(1 << 31))); |
| 209 | continue; |
| 210 | } |
| 211 |
| 212 | currentPacketLength = fInt; |
| 213 | len = currentPacketLength + 4; |
| 214 | } |
| 215 |
| 216 | if (currentProtocolType != ProtocolTypeDD && currentProtocolType != ProtocolTypeTLS && currentPacketLength % 4 != 0 || currentPacketLength > 2 * 1024 * 1024) { |
| 217 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received invalid packet length", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType); |
| 218 | reconnect(); |
| 219 | break; |
| 220 | } |
| 221 |
| 222 | if (currentPacketLength < buffer->remaining()) { |
| 223 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received message len %u but packet larger %u", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType, currentPacketLength, buffer->remaining()); |
| 224 | } else if (currentPacketLength == buffer->remaining()) { |
| 225 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received message len %u equal to packet size", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType, currentPacketLength); |
| 226 | } else { |
| 227 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received packet size less(%u) then message size(%u)", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType, buffer->remaining(), currentPacketLength); |
| 228 |
| 229 | if (restOfTheData != nullptr && restOfTheData->capacity() < len) { |
| 230 | reuseLater = restOfTheData; |
| 231 | restOfTheData = nullptr; |
| 232 | } |
| 233 | if (restOfTheData == nullptr) { |
| 234 | buffer->position(mark); |
| 235 | restOfTheData = BuffersStorage::getInstance().getFreeBuffer(len); |
| 236 | restOfTheData->writeBytes(buffer); |
| 237 | } else { |
| 238 | restOfTheData->position(restOfTheData->limit()); |
| 239 | restOfTheData->limit(len); |
| 240 | } |
| 241 | lastPacketLength = len; |
| 242 | break; |
| 243 | } |
| 244 |
| 245 | uint32_t old = buffer->limit(); |
| 246 | buffer->limit(buffer->position() + currentPacketLength); |
| 247 | uint32_t current_generation = generation; |
| 248 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).onConnectionDataReceived(this, buffer, currentPacketLength); |
| 249 | if (current_generation != generation) { |
| 250 | break; |
| 251 | } |
| 252 | buffer->position(buffer->limit()); |
| 253 | buffer->limit(old); |
| 254 |
| 255 | if (restOfTheData != nullptr) { |
| 256 | if ((lastPacketLength != 0 && restOfTheData->position() == lastPacketLength) || (lastPacketLength == 0 && !restOfTheData->hasRemaining())) { |
| 257 | reuseLater = restOfTheData; |
| 258 | restOfTheData = nullptr; |
| 259 | } else { |
| 260 | restOfTheData->compact(); |
| 261 | restOfTheData->limit(restOfTheData->position()); |
| 262 | restOfTheData->position(0); |
| 263 | } |
| 264 | } |
| 265 |
| 266 | if (parseLaterBuffer != nullptr) { |
| 267 | buffer = parseLaterBuffer; |
| 268 | parseLaterBuffer = nullptr; |
| 269 | } |
| 270 | } |
| 271 | if (reuseLater != nullptr) { |
| 272 | reuseLater->reuse(); |
| 273 | } |
| 274 | } |
| 275 |
| 276 | void Connection::connect() { |
| 277 | if (waitForReconnectTimer) { |
| 278 | return; |
| 279 | } |
| 280 | if (!ConnectionsManager::getInstance(currentDatacenter->instanceNum).isNetworkAvailable()) { |
| 281 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).onConnectionClosed(this, 0); |
| 282 | return; |
| 283 | } |
| 284 | if (connectionState == TcpConnectionStageConnected || connectionState == TcpConnectionStageConnecting) { |
| 285 | return; |
| 286 | } |
| 287 | connectionInProcess = true; |
| 288 | connectionState = TcpConnectionStageConnecting; |
| 289 | isMediaConnection = false; |
| 290 | uint8_t strategy = ConnectionsManager::getInstance(currentDatacenter->instanceNum).getIpStratagy(); |
| 291 | uint32_t ipv6; |
| 292 | if (strategy == USE_IPV6_ONLY) { |
| 293 | ipv6 = TcpAddressFlagIpv6; |
| 294 | } else if (strategy == USE_IPV4_IPV6_RANDOM) { |
| 295 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).lastProtocolUsefullData) { |
| 296 | ipv6 = ConnectionsManager::getInstance(currentDatacenter->instanceNum).lastProtocolIsIpv6 ? TcpAddressFlagIpv6 : 0; |
| 297 | } else { |
| 298 | uint8_t value; |
| 299 | RAND_bytes(&value, 1); |
| 300 | ipv6 = value % 3 == 0 ? TcpAddressFlagIpv6 : 0; |
| 301 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).lastProtocolIsIpv6 = ipv6 != 0; |
| 302 | } |
| 303 | if (connectionType == ConnectionTypeGeneric) { |
| 304 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).lastProtocolUsefullData = false; |
| 305 | } |
| 306 | } else { |
| 307 | ipv6 = 0; |
| 308 | } |
| 309 | uint32_t isStatic = connectionType == ConnectionTypeProxy || !ConnectionsManager::getInstance(currentDatacenter->instanceNum).proxyAddress.empty() ? TcpAddressFlagStatic : 0; |
| 310 | TcpAddress *tcpAddress = nullptr; |
| 311 | if (isMediaConnectionType(connectionType)) { |
| 312 | currentAddressFlags = TcpAddressFlagDownload | isStatic; |
| 313 | tcpAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | ipv6); |
| 314 | if (tcpAddress == nullptr) { |
| 315 | currentAddressFlags = isStatic; |
| 316 | tcpAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | ipv6); |
| 317 | } else { |
| 318 | isMediaConnection = true; |
| 319 | } |
| 320 | if (tcpAddress == nullptr && ipv6) { |
| 321 | ipv6 = 0; |
| 322 | currentAddressFlags = TcpAddressFlagDownload | isStatic; |
| 323 | tcpAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); |
| 324 | if (tcpAddress == nullptr) { |
| 325 | currentAddressFlags = isStatic; |
| 326 | tcpAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); |
| 327 | } else { |
| 328 | isMediaConnection = true; |
| 329 | } |
| 330 | } |
| 331 | } else if (connectionType == ConnectionTypeTemp) { |
| 332 | currentAddressFlags = TcpAddressFlagTemp; |
| 333 | tcpAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); |
| 334 | ipv6 = 0; |
| 335 | } else { |
| 336 | currentAddressFlags = isStatic; |
| 337 | tcpAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | ipv6); |
| 338 | if (tcpAddress == nullptr && ipv6) { |
| 339 | ipv6 = 0; |
| 340 | tcpAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); |
| 341 | } |
| 342 | } |
| 343 | if (tcpAddress == nullptr) { |
| 344 | hostAddress = ""; |
| 345 | } else { |
| 346 | hostAddress = tcpAddress->address; |
| 347 | secret = tcpAddress->secret; |
| 348 | } |
| 349 | if (tcpAddress != nullptr && isStatic) { |
| 350 | hostPort = (uint16_t) tcpAddress->port; |
| 351 | } else { |
| 352 | hostPort = (uint16_t) currentDatacenter->getCurrentPort(currentAddressFlags); |
| 353 | } |
| 354 |
| 355 | reconnectTimer->stop(); |
| 356 |
| 357 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) connecting (%s:%hu)", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); |
| 358 | generation++; |
| 359 | firstPacketSent = false; |
| 360 | if (restOfTheData != nullptr) { |
| 361 | restOfTheData->reuse(); |
| 362 | restOfTheData = nullptr; |
| 363 | } |
| 364 | lastPacketLength = 0; |
| 365 | wasConnected = false; |
| 366 | hasSomeDataSinceLastConnect = false; |
| 367 | openConnection(hostAddress, hostPort, secret, ipv6 != 0, ConnectionsManager::getInstance(currentDatacenter->instanceNum).currentNetworkType); |
| 368 | if (connectionType == ConnectionTypeProxy) { |
| 369 | setTimeout(5); |
| 370 | } else if (connectionType == ConnectionTypePush) { |
| 371 | if (isTryingNextPort) { |
| 372 | setTimeout(20); |
| 373 | } else { |
| 374 | setTimeout(30); |
| 375 | } |
| 376 | } else if (connectionType == ConnectionTypeUpload) { |
| 377 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).networkSlow) { |
| 378 | setTimeout(40); |
| 379 | } else { |
| 380 | setTimeout(25); |
| 381 | } |
| 382 | } else { |
| 383 | if (isTryingNextPort) { |
| 384 | setTimeout(8); |
| 385 | } else { |
| 386 | setTimeout(12); |
| 387 | } |
| 388 | } |
| 389 | connectionInProcess = false; |
| 390 | } |
| 391 |
| 392 | void Connection::reconnect() { |
| 393 | if (connectionType == ConnectionTypeProxy) { |
| 394 | suspendConnection(false); |
| 395 | } else { |
| 396 | forceNextPort = true; |
| 397 | suspendConnection(true); |
| 398 | connect(); |
| 399 | } |
| 400 | } |
| 401 |
| 402 | bool Connection::hasUsefullData() { |
| 403 | int64_t time = ConnectionsManager::getInstance(currentDatacenter->instanceNum).getCurrentTimeMonotonicMillis(); |
| 404 | if (usefullData && llabs(time - usefullDataReceiveTime) < 4 * 1000L) { |
| 405 | return false; |
| 406 | } |
| 407 | return usefullData; |
| 408 | } |
| 409 |
| 410 | bool Connection::isSuspended() { |
| 411 | return connectionState == TcpConnectionStageSuspended; |
| 412 | } |
| 413 |
| 414 | bool Connection::isMediaConnectionType(ConnectionType type) { |
| 415 | return (type & ConnectionTypeGenericMedia) != 0 || (type & ConnectionTypeDownload) != 0; |
| 416 | } |
| 417 |
| 418 | void Connection::setHasUsefullData() { |
| 419 | if (!usefullData) { |
| 420 | usefullDataReceiveTime = ConnectionsManager::getInstance(currentDatacenter->instanceNum).getCurrentTimeMonotonicMillis(); |
| 421 | usefullData = true; |
| 422 | lastReconnectTimeout = 50; |
| 423 | } |
| 424 | } |
| 425 |
| 426 | bool Connection::allowsCustomPadding() { |
| 427 | return currentProtocolType == ProtocolTypeTLS || currentProtocolType == ProtocolTypeDD || currentProtocolType == ProtocolTypeEF; |
| 428 | } |
| 429 |
| 430 | void Connection::sendData(NativeByteBuffer *buff, bool reportAck, bool encrypted) { |
| 431 | if (buff == nullptr) { |
| 432 | return; |
| 433 | } |
| 434 | buff->rewind(); |
| 435 | if (connectionState == TcpConnectionStageIdle || connectionState == TcpConnectionStageReconnecting || connectionState == TcpConnectionStageSuspended) { |
| 436 | connect(); |
| 437 | } |
| 438 |
| 439 | if (isDisconnected()) { |
| 440 | buff->reuse(); |
| 441 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) disconnected, don't send data", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType); |
| 442 | return; |
| 443 | } |
| 444 |
| 445 | uint32_t bufferLen = 0; |
| 446 | uint32_t packetLength; |
| 447 |
| 448 | uint8_t useSecret = 0; |
| 449 | if (!firstPacketSent) { |
| 450 | if (!overrideProxyAddress.empty()) { |
| 451 | if (!overrideProxySecret.empty()) { |
| 452 | useSecret = 1; |
| 453 | } else if (!secret.empty()) { |
| 454 | useSecret = 2; |
| 455 | } |
| 456 | } else if (!ConnectionsManager::getInstance(currentDatacenter->instanceNum).proxyAddress.empty() && !ConnectionsManager::getInstance(currentDatacenter->instanceNum).proxySecret.empty()) { |
| 457 | useSecret = 1; |
| 458 | } else if (!secret.empty()) { |
| 459 | useSecret = 2; |
| 460 | } |
| 461 | if (useSecret != 0) { |
| 462 | std::string *currentSecret = getCurrentSecret(useSecret); |
| 463 | if (currentSecret->length() >= 17 && (*currentSecret)[0] == '\xdd') { |
| 464 | currentProtocolType = ProtocolTypeDD; |
| 465 | } else if (currentSecret->length() > 17 && (*currentSecret)[0] == '\xee') { |
| 466 | currentProtocolType = ProtocolTypeTLS; |
| 467 | } else { |
| 468 | currentProtocolType = ProtocolTypeEF; |
| 469 | } |
| 470 | } else { |
| 471 | currentProtocolType = ProtocolTypeEF; |
| 472 | } |
| 473 | } |
| 474 |
| 475 | uint32_t additinalPacketSize = 0; |
| 476 | if (currentProtocolType == ProtocolTypeEF) { |
| 477 | packetLength = buff->limit() / 4; |
| 478 | if (packetLength < 0x7f) { |
| 479 | bufferLen++; |
| 480 | } else { |
| 481 | bufferLen += 4; |
| 482 | } |
| 483 | } else { |
| 484 | packetLength = buff->limit(); |
| 485 | if (currentProtocolType == ProtocolTypeDD || currentProtocolType == ProtocolTypeTLS) { |
| 486 | RAND_bytes((uint8_t *) &additinalPacketSize, 4); |
| 487 | if (!encrypted) { |
| 488 | additinalPacketSize = additinalPacketSize % 257; |
| 489 | } else { |
| 490 | additinalPacketSize = additinalPacketSize % 16; |
| 491 | } |
| 492 | packetLength += additinalPacketSize; |
| 493 | } else { |
| 494 | RAND_bytes((uint8_t *) &additinalPacketSize, 4); |
| 495 | if (!encrypted) { |
| 496 | additinalPacketSize = additinalPacketSize % 257; |
| 497 | uint32_t additionalSize = additinalPacketSize % 4; |
| 498 | if (additionalSize != 0) { |
| 499 | additinalPacketSize += (4 - additionalSize); |
| 500 | } |
| 501 | } |
| 502 | packetLength += additinalPacketSize; |
| 503 | } |
| 504 | bufferLen += 4; |
| 505 | } |
| 506 |
| 507 | if (!firstPacketSent) { |
| 508 | bufferLen += 64; |
| 509 | } |
| 510 |
| 511 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(bufferLen); |
| 512 | NativeByteBuffer *buffer2; |
| 513 | if (additinalPacketSize > 0) { |
| 514 | buffer2 = BuffersStorage::getInstance().getFreeBuffer(additinalPacketSize); |
| 515 | RAND_bytes(buffer2->bytes(), additinalPacketSize); |
| 516 | } else { |
| 517 | buffer2 = nullptr; |
| 518 | } |
| 519 | uint8_t *bytes = buffer->bytes(); |
| 520 |
| 521 | if (!firstPacketSent) { |
| 522 | buffer->position(64); |
| 523 | while (true) { |
| 524 | RAND_bytes(bytes, 64); |
| 525 | uint32_t val = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0]); |
| 526 | uint32_t val2 = (bytes[7] << 24) | (bytes[6] << 16) | (bytes[5] << 8) | (bytes[4]); |
| 527 | if (currentProtocolType == ProtocolTypeTLS || bytes[0] != 0xef && val != 0x44414548 && val != 0x54534f50 && val != 0x20544547 && val != 0x4954504f && val != 0xeeeeeeee && val != 0xdddddddd && val != 0x02010316 && val2 != 0x00000000) { |
| 528 | if (currentProtocolType == ProtocolTypeEF) { |
| 529 | bytes[56] = bytes[57] = bytes[58] = bytes[59] = 0xef; |
| 530 | } else if (currentProtocolType == ProtocolTypeDD || currentProtocolType == ProtocolTypeTLS) { |
| 531 | bytes[56] = bytes[57] = bytes[58] = bytes[59] = 0xdd; |
| 532 | } else if (currentProtocolType == ProtocolTypeEE) { |
| 533 | bytes[56] = bytes[57] = bytes[58] = bytes[59] = 0xee; |
| 534 | } |
| 535 |
| 536 | if (useSecret != 0) { |
| 537 | int16_t datacenterId; |
| 538 | if (isMediaConnection) { |
| 539 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) { |
| 540 | datacenterId = -(int16_t) (10000 + currentDatacenter->getDatacenterId()); |
| 541 | } else { |
| 542 | datacenterId = -(int16_t) currentDatacenter->getDatacenterId(); |
| 543 | } |
| 544 | } else { |
| 545 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).testBackend) { |
| 546 | datacenterId = (int16_t) (10000 + currentDatacenter->getDatacenterId()); |
| 547 | } else { |
| 548 | datacenterId = (int16_t) currentDatacenter->getDatacenterId(); |
| 549 | } |
| 550 | } |
| 551 | bytes[60] = (uint8_t) (datacenterId & 0xff); |
| 552 | bytes[61] = (uint8_t) ((datacenterId >> 8) & 0xff); |
| 553 | } |
| 554 | break; |
| 555 | } |
| 556 | } |
| 557 |
| 558 | encryptNum = decryptNum = 0; |
| 559 | memset(encryptCount, 0, 16); |
| 560 | memset(decryptCount, 0, 16); |
| 561 |
| 562 | for (int32_t a = 0; a < 48; a++) { |
| 563 | temp[a] = bytes[a + 8]; |
| 564 | } |
| 565 | encryptKeyWithSecret(temp, useSecret); |
| 566 | if (AES_set_encrypt_key(temp, 256, &encryptKey) < 0) { |
| 567 | if (LOGS_ENABLED) DEBUG_E("unable to set encryptKey"); |
| 568 | exit(1); |
| 569 | } |
| 570 | memcpy(encryptIv, temp + 32, 16); |
| 571 |
| 572 | for (int32_t a = 0; a < 48; a++) { |
| 573 | temp[a] = bytes[55 - a]; |
| 574 | } |
| 575 | encryptKeyWithSecret(temp, useSecret); |
| 576 | if (AES_set_encrypt_key(temp, 256, &decryptKey) < 0) { |
| 577 | if (LOGS_ENABLED) DEBUG_E("unable to set decryptKey"); |
| 578 | exit(1); |
| 579 | } |
| 580 | memcpy(decryptIv, temp + 32, 16); |
| 581 |
| 582 | AES_ctr128_encrypt(bytes, temp, 64, &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 583 | memcpy(bytes + 56, temp + 56, 8); |
| 584 |
| 585 | firstPacketSent = true; |
| 586 | } |
| 587 | if (currentProtocolType == ProtocolTypeEF) { |
| 588 | if (packetLength < 0x7f) { |
| 589 | if (reportAck) { |
| 590 | packetLength |= (1 << 7); |
| 591 | } |
| 592 | buffer->writeByte((uint8_t) packetLength); |
| 593 | bytes += (buffer->limit() - 1); |
| 594 | AES_ctr128_encrypt(bytes, bytes, 1, &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 595 | } else { |
| 596 | packetLength = (packetLength << 8) + 0x7f; |
| 597 | if (reportAck) { |
| 598 | packetLength |= (1 << 7); |
| 599 | } |
| 600 | buffer->writeInt32(packetLength); |
| 601 | bytes += (buffer->limit() - 4); |
| 602 | AES_ctr128_encrypt(bytes, bytes, 4, &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 603 | } |
| 604 | } else { |
| 605 | if (reportAck) { |
| 606 | packetLength |= 0x80000000; |
| 607 | } |
| 608 | buffer->writeInt32(packetLength); |
| 609 | bytes += (buffer->limit() - 4); |
| 610 | AES_ctr128_encrypt(bytes, bytes, 4, &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 611 | } |
| 612 |
| 613 | buffer->rewind(); |
| 614 | writeBuffer(buffer); |
| 615 | buff->rewind(); |
| 616 | AES_ctr128_encrypt(buff->bytes(), buff->bytes(), buff->limit(), &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 617 | writeBuffer(buff); |
| 618 | if (buffer2 != nullptr) { |
| 619 | AES_ctr128_encrypt(buffer2->bytes(), buffer2->bytes(), buffer2->limit(), &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 620 | writeBuffer(buffer2); |
| 621 | } |
| 622 | } |
| 623 |
| 624 | inline std::string *Connection::getCurrentSecret(uint8_t secretType) { |
| 625 | if (secretType == 2) { |
| 626 | return &secret; |
| 627 | } else if (!overrideProxySecret.empty()) { |
| 628 | return &overrideProxySecret; |
| 629 | } else { |
| 630 | return &ConnectionsManager::getInstance(currentDatacenter->instanceNum).proxySecret; |
| 631 | } |
| 632 | } |
| 633 |
| 634 | inline void Connection::encryptKeyWithSecret(uint8_t *bytes, uint8_t secretType) { |
| 635 | if (secretType == 0) { |
| 636 | return; |
| 637 | } |
| 638 | std::string *currentSecret = getCurrentSecret(secretType); |
| 639 | size_t a = 0; |
| 640 | size_t size = std::min((size_t) 16, currentSecret->length()); |
| 641 | if (currentSecret->length() >= 17 && ((*currentSecret)[0] == '\xdd' || (*currentSecret)[0] == '\xee')) { |
| 642 | a = 1; |
| 643 | size = 17; |
| 644 | } |
| 645 |
| 646 | SHA256_CTX sha256Ctx; |
| 647 | SHA256_Init(&sha256Ctx); |
| 648 | SHA256_Update(&sha256Ctx, bytes, 32); |
| 649 | char b[1]; |
| 650 | for (; a < size; a++) { |
| 651 | b[0] = (char) (*currentSecret)[a]; |
| 652 | SHA256_Update(&sha256Ctx, b, 1); |
| 653 | } |
| 654 | SHA256_Final(bytes, &sha256Ctx); |
| 655 | } |
| 656 |
| 657 | void Connection::onDisconnectedInternal(int32_t reason, int32_t error) { |
| 658 | reconnectTimer->stop(); |
| 659 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) disconnected with reason %d", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType, reason); |
| 660 | bool switchToNextPort = reason == 2 && wasConnected && (!hasSomeDataSinceLastConnect || currentDatacenter->isCustomPort(currentAddressFlags)) || forceNextPort; |
| 661 | if (connectionType == ConnectionTypeGeneric || connectionType == ConnectionTypeTemp || connectionType == ConnectionTypeGenericMedia) { |
| 662 | if (wasConnected && reason == 2 && currentTimeout < 16) { |
| 663 | currentTimeout += 2; |
| 664 | } |
| 665 | } |
| 666 | generation++; |
| 667 | firstPacketSent = false; |
| 668 | if (restOfTheData != nullptr) { |
| 669 | restOfTheData->reuse(); |
| 670 | restOfTheData = nullptr; |
| 671 | } |
| 672 | lastPacketLength = 0; |
| 673 | receivedDataAmount = 0; |
| 674 | wasConnected = false; |
| 675 | if (connectionState != TcpConnectionStageSuspended && connectionState != TcpConnectionStageIdle) { |
| 676 | connectionState = TcpConnectionStageIdle; |
| 677 | } |
| 678 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).onConnectionClosed(this, reason); |
| 679 | connectionToken = 0; |
| 680 |
| 681 | uint32_t datacenterId = currentDatacenter->getDatacenterId(); |
| 682 | if (connectionState == TcpConnectionStageIdle) { |
| 683 | connectionState = TcpConnectionStageReconnecting; |
| 684 | failedConnectionCount++; |
| 685 | if (failedConnectionCount == 1) { |
| 686 | if (hasUsefullData()) { |
| 687 | willRetryConnectCount = 3; |
| 688 | } else { |
| 689 | willRetryConnectCount = 1; |
| 690 | } |
| 691 | } |
| 692 | if (ConnectionsManager::getInstance(currentDatacenter->instanceNum).isNetworkAvailable() && connectionType != ConnectionTypeProxy) { |
| 693 | isTryingNextPort = true; |
| 694 | if (failedConnectionCount > willRetryConnectCount || switchToNextPort) { |
| 695 | currentDatacenter->nextAddressOrPort(currentAddressFlags); |
| 696 | if (currentDatacenter->isRepeatCheckingAddresses() && (ConnectionsManager::getInstance(currentDatacenter->instanceNum).getIpStratagy() == USE_IPV4_ONLY || ConnectionsManager::getInstance(currentDatacenter->instanceNum).getIpStratagy() == USE_IPV6_ONLY)) { |
| 697 | if (LOGS_ENABLED) DEBUG_D("started retrying connection, set ipv4 ipv6 random strategy"); |
| 698 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).setIpStrategy(USE_IPV4_IPV6_RANDOM); |
| 699 | } |
| 700 | failedConnectionCount = 0; |
| 701 | } |
| 702 | } |
| 703 | if (error == 0x68 || error == 0x71) { |
| 704 | if (connectionType != ConnectionTypeProxy) { |
| 705 | waitForReconnectTimer = true; |
| 706 | reconnectTimer->setTimeout(lastReconnectTimeout, false); |
| 707 | lastReconnectTimeout *= 2; |
| 708 | if (lastReconnectTimeout > 400) { |
| 709 | lastReconnectTimeout = 400; |
| 710 | } |
| 711 | reconnectTimer->start(); |
| 712 | } |
| 713 | } else { |
| 714 | waitForReconnectTimer = false; |
| 715 | if (connectionType == ConnectionTypeGenericMedia && currentDatacenter->isHandshaking(true) || connectionType == ConnectionTypeGeneric && (currentDatacenter->isHandshaking(false) || datacenterId == ConnectionsManager::getInstance(currentDatacenter->instanceNum).currentDatacenterId || datacenterId == ConnectionsManager::getInstance(currentDatacenter->instanceNum).movingToDatacenterId)) { |
| 716 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) reconnect %s:%hu", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); |
| 717 | reconnectTimer->setTimeout(1000, false); |
| 718 | reconnectTimer->start(); |
| 719 | } |
| 720 | } |
| 721 | } |
| 722 | usefullData = false; |
| 723 | } |
| 724 |
| 725 | void Connection::onDisconnected(int32_t reason, int32_t error) { |
| 726 | if (connectionInProcess) { |
| 727 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).scheduleTask([&, reason, error] { |
| 728 | onDisconnectedInternal(reason, error); |
| 729 | }); |
| 730 | } else { |
| 731 | onDisconnectedInternal(reason, error); |
| 732 | } |
| 733 | } |
| 734 |
| 735 | void Connection::onConnected() { |
| 736 | connectionState = TcpConnectionStageConnected; |
| 737 | connectionToken = lastConnectionToken++; |
| 738 | wasConnected = true; |
| 739 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) connected to %s:%hu", this, currentDatacenter->instanceNum, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); |
| 740 | ConnectionsManager::getInstance(currentDatacenter->instanceNum).onConnectionConnected(this); |
| 741 | } |
| 742 |
| 743 | bool Connection::hasPendingRequests() { |
| 744 | return ConnectionsManager::getInstance(currentDatacenter->instanceNum).hasPendingRequestsForConnection(this); |
| 745 | } |
| 746 |
| 747 | Datacenter *Connection::getDatacenter() { |
| 748 | return currentDatacenter; |
| 749 | } |
| 750 |
| 751 | ConnectionType Connection::getConnectionType() { |
| 752 | return connectionType; |
| 753 | } |
| 754 |
| 755 | int8_t Connection::getConnectionNum() { |
| 756 | return connectionNum; |
| 757 | } |
| 758 |
| 759 | uint32_t Connection::getConnectionToken() { |
| 760 | return connectionToken; |
| 761 | } |
| 762 |