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