| 6 |
| * Copyright Nikolai Kudashov, 2015. |
| 7 | */ |
| 8 |
| 9 | #include <openssl/rand.h> |
| 10 | #include <stdlib.h> |
| 11 | #include "Connection.h" |
| 12 | #include "ConnectionsManager.h" |
| 13 | #include "BuffersStorage.h" |
| 14 | #include "FileLog.h" |
| 15 | #include "Timer.h" |
| 16 | #include "Datacenter.h" |
| 17 | #include "NativeByteBuffer.h" |
| 18 |
| 19 | static uint32_t lastConnectionToken = 1; |
| 20 |
| 21 | Connection::Connection(Datacenter *datacenter, ConnectionType type) { |
| 22 | currentDatacenter = datacenter; |
| 23 | connectionType = type; |
| 24 | genereateNewSessionId(); |
| 25 | connectionState = TcpConnectionStageIdle; |
| 26 | reconnectTimer = new Timer([&] { |
| 27 | reconnectTimer->stop(); |
| 28 | connect(); |
| 29 | }); |
| 30 | } |
| 31 |
| 32 | Connection::~Connection() { |
| 33 | if (reconnectTimer != nullptr) { |
| 34 | reconnectTimer->stop(); |
| 35 | delete reconnectTimer; |
| 36 | reconnectTimer = nullptr; |
| 37 | } |
| 38 | } |
| 39 |
| 40 | void Connection::suspendConnection() { |
| 41 | suspendConnection(false); |
| 42 | } |
| 43 |
| 44 | void Connection::suspendConnection(bool idle) { |
| 45 | reconnectTimer->stop(); |
| 46 | if (connectionState == TcpConnectionStageIdle || connectionState == TcpConnectionStageSuspended) { |
| 47 | return; |
| 48 | } |
| 49 | DEBUG_D("connection(%p, dc%u, type %d) suspend", this, currentDatacenter->getDatacenterId(), connectionType); |
| 50 | connectionState = idle ? TcpConnectionStageIdle : TcpConnectionStageSuspended; |
| 51 | dropConnection(); |
| 52 | ConnectionsManager::getInstance().onConnectionClosed(this, 0); |
| 53 | firstPacketSent = false; |
| 54 | if (restOfTheData != nullptr) { |
| 55 | restOfTheData->reuse(); |
| 56 | restOfTheData = nullptr; |
| 57 | } |
| 58 | lastPacketLength = 0; |
| 59 | connectionToken = 0; |
| 60 | wasConnected = false; |
| 61 | } |
| 62 |
| 63 | void Connection::onReceivedData(NativeByteBuffer *buffer) { |
| 64 | AES_ctr128_encrypt(buffer->bytes(), buffer->bytes(), buffer->limit(), &decryptKey, decryptIv, decryptCount, &decryptNum); |
| 65 |
| 66 | failedConnectionCount = 0; |
| 67 |
| 68 | NativeByteBuffer *parseLaterBuffer = nullptr; |
| 69 | if (restOfTheData != nullptr) { |
| 70 | if (lastPacketLength == 0) { |
| 71 | if (restOfTheData->capacity() - restOfTheData->position() >= buffer->limit()) { |
| 72 | restOfTheData->limit(restOfTheData->position() + buffer->limit()); |
| 73 | restOfTheData->writeBytes(buffer); |
| 74 | buffer = restOfTheData; |
| 75 | } else { |
| 76 | NativeByteBuffer *newBuffer = BuffersStorage::getInstance().getFreeBuffer(restOfTheData->limit() + buffer->limit()); |
| 77 | restOfTheData->rewind(); |
| 78 | newBuffer->writeBytes(restOfTheData); |
| 79 | newBuffer->writeBytes(buffer); |
| 80 | buffer = newBuffer; |
| 81 | restOfTheData->reuse(); |
| 82 | restOfTheData = newBuffer; |
| 83 | } |
| 84 | } else { |
| 85 | uint32_t len; |
| 86 | if (lastPacketLength - restOfTheData->position() <= buffer->limit()) { |
| 87 | len = lastPacketLength - restOfTheData->position(); |
| 88 | } else { |
| 89 | len = buffer->limit(); |
| 90 | } |
| 91 | uint32_t oldLimit = buffer->limit(); |
| 92 | buffer->limit(len); |
| 93 | restOfTheData->writeBytes(buffer); |
| 94 | buffer->limit(oldLimit); |
| 95 | if (restOfTheData->position() == lastPacketLength) { |
| 96 | parseLaterBuffer = buffer->hasRemaining() ? buffer : nullptr; |
| 97 | buffer = restOfTheData; |
| 98 | } else { |
| 99 | return; |
| 100 | } |
| 101 | } |
| 102 | } |
| 103 |
| 104 | buffer->rewind(); |
| 105 |
| 106 | while (buffer->hasRemaining()) { |
| 107 | if (!hasSomeDataSinceLastConnect) { |
| 108 | currentDatacenter->storeCurrentAddressAndPortNum(); |
| 109 | isTryingNextPort = false; |
| 110 | if (connectionType == ConnectionTypePush) { |
| 111 | setTimeout(60 * 15); |
| 112 | } else { |
| 113 | setTimeout(25); |
| 114 | } |
| 115 | } |
| 116 | hasSomeDataSinceLastConnect = true; |
| 117 |
| 118 | uint32_t currentPacketLength = 0; |
| 119 | uint32_t mark = buffer->position(); |
| 120 | uint8_t fByte = buffer->readByte(nullptr); |
| 121 |
| 122 | if ((fByte & (1 << 7)) != 0) { |
| 123 | buffer->position(mark); |
| 124 | if (buffer->remaining() < 4) { |
| 125 | NativeByteBuffer *reuseLater = restOfTheData; |
| 126 | restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384); |
| 127 | restOfTheData->writeBytes(buffer); |
| 128 | restOfTheData->limit(restOfTheData->position()); |
| 129 | lastPacketLength = 0; |
| 130 | if (reuseLater != nullptr) { |
| 131 | reuseLater->reuse(); |
| 132 | } |
| 133 | break; |
| 134 | } |
| 135 | int32_t ackId = buffer->readBigInt32(nullptr) & (~(1 << 31)); |
| 136 | ConnectionsManager::getInstance().onConnectionQuickAckReceived(this, ackId); |
| 137 | continue; |
| 138 | } |
| 139 |
| 140 | if (fByte != 0x7f) { |
| 141 | currentPacketLength = ((uint32_t) fByte) * 4; |
| 142 | } else { |
| 143 | buffer->position(mark); |
| 144 | if (buffer->remaining() < 4) { |
| 145 | if (restOfTheData == nullptr || (restOfTheData != nullptr && restOfTheData->position() != 0)) { |
| 146 | NativeByteBuffer *reuseLater = restOfTheData; |
| 147 | restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384); |
| 148 | restOfTheData->writeBytes(buffer); |
| 149 | restOfTheData->limit(restOfTheData->position()); |
| 150 | lastPacketLength = 0; |
| 151 | if (reuseLater != nullptr) { |
| 152 | reuseLater->reuse(); |
| 153 | } |
| 154 | } else { |
| 155 | restOfTheData->position(restOfTheData->limit()); |
| 156 | } |
| 157 | break; |
| 158 | } |
| 159 | currentPacketLength = ((uint32_t) buffer->readInt32(nullptr) >> 8) * 4; |
| 160 | } |
| 161 |
| 162 | if (currentPacketLength % 4 != 0 || currentPacketLength > 2 * 1024 * 1024) { |
| 163 | DEBUG_E("connection(%p, dc%u, type %d) received invalid packet length", this, currentDatacenter->getDatacenterId(), connectionType); |
| 164 | reconnect(); |
| 165 | return; |
| 166 | } |
| 167 |
| 168 | if (currentPacketLength < buffer->remaining()) { |
| 169 | DEBUG_E("connection(%p, dc%u, type %d) received message len %u but packet larger %u", this, currentDatacenter->getDatacenterId(), connectionType, currentPacketLength, buffer->remaining()); |
| 170 | } else if (currentPacketLength == buffer->remaining()) { |
| 171 | DEBUG_E("connection(%p, dc%u, type %d) received message len %u equal to packet size", this, currentDatacenter->getDatacenterId(), connectionType, currentPacketLength); |
| 172 | } else { |
| 173 | DEBUG_E("connection(%p, dc%u, type %d) received packet size less(%u) then message size(%u)", this, currentDatacenter->getDatacenterId(), connectionType, buffer->remaining(), currentPacketLength); |
| 174 |
| 175 | NativeByteBuffer *reuseLater = nullptr; |
| 176 | uint32_t len = currentPacketLength + (fByte != 0x7f ? 1 : 4); |
| 177 | if (restOfTheData != nullptr && restOfTheData->capacity() < len) { |
| 178 | reuseLater = restOfTheData; |
| 179 | restOfTheData = nullptr; |
| 180 | } |
| 181 | if (restOfTheData == nullptr) { |
| 182 | buffer->position(mark); |
| 183 | restOfTheData = BuffersStorage::getInstance().getFreeBuffer(len); |
| 184 | restOfTheData->writeBytes(buffer); |
| 185 | } else { |
| 186 | restOfTheData->position(restOfTheData->limit()); |
| 187 | restOfTheData->limit(len); |
| 188 | } |
| 189 | lastPacketLength = len; |
| 190 | if (reuseLater != nullptr) { |
| 191 | reuseLater->reuse(); |
| 192 | } |
| 193 | return; |
| 194 | } |
| 195 |
| 196 | uint32_t old = buffer->limit(); |
| 197 | buffer->limit(buffer->position() + currentPacketLength); |
| 198 | ConnectionsManager::getInstance().onConnectionDataReceived(this, buffer, currentPacketLength); |
| 199 | buffer->position(buffer->limit()); |
| 200 | buffer->limit(old); |
| 201 |
| 202 | if (restOfTheData != nullptr) { |
| 203 | if ((lastPacketLength != 0 && restOfTheData->position() == lastPacketLength) || (lastPacketLength == 0 && !restOfTheData->hasRemaining())) { |
| 204 | restOfTheData->reuse(); |
| 205 | restOfTheData = nullptr; |
| 206 | } else { |
| 207 | DEBUG_E("compact occured"); |
| 208 | restOfTheData->compact(); |
| 209 | restOfTheData->limit(restOfTheData->position()); |
| 210 | restOfTheData->position(0); |
| 211 | } |
| 212 | } |
| 213 |
| 214 | if (parseLaterBuffer != nullptr) { |
| 215 | buffer = parseLaterBuffer; |
| 216 | parseLaterBuffer = nullptr; |
| 217 | } |
| 218 | } |
| 219 | } |
| 220 |
| 221 | void Connection::connect() { |
| 222 | if (!ConnectionsManager::getInstance().isNetworkAvailable()) { |
| 223 | ConnectionsManager::getInstance().onConnectionClosed(this, 0); |
| 224 | return; |
| 225 | } |
| 226 | if ((connectionState == TcpConnectionStageConnected || connectionState == TcpConnectionStageConnecting)) { |
| 227 | return; |
| 228 | } |
| 229 | connectionState = TcpConnectionStageConnecting; |
| 230 | uint32_t ipv6 = ConnectionsManager::getInstance().isIpv6Enabled() ? TcpAddressFlagIpv6 : 0; |
| 231 | uint32_t isStatic = !ConnectionsManager::getInstance().proxyAddress.empty() ? TcpAddressFlagStatic : 0; |
| 232 | if (connectionType == ConnectionTypeDownload) { |
| 233 | currentAddressFlags = TcpAddressFlagDownload | isStatic; |
| 234 | hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | ipv6); |
| 235 | if (hostAddress.empty()) { |
| 236 | currentAddressFlags = isStatic; |
| 237 | hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | ipv6); |
| 238 | } |
| 239 | if (hostAddress.empty() && ipv6) { |
| 240 | ipv6 = 0; |
| 241 | currentAddressFlags = TcpAddressFlagDownload | isStatic; |
| 242 | hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); |
| 243 | if (hostAddress.empty()) { |
| 244 | currentAddressFlags = isStatic; |
| 245 | hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); |
| 246 | } |
| 247 | } |
| 248 | } else { |
| 249 | currentAddressFlags = isStatic; |
| 250 | hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | ipv6); |
| 251 | if (hostAddress.empty() && ipv6) { |
| 252 | ipv6 = 0; |
| 253 | hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); |
| 254 | } |
| 255 | } |
| 256 | hostPort = (uint16_t) currentDatacenter->getCurrentPort(currentAddressFlags); |
| 257 |
| 258 | reconnectTimer->stop(); |
| 259 |
| 260 | DEBUG_D("connection(%p, dc%u, type %d) connecting (%s:%hu)", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); |
| 261 | firstPacketSent = false; |
| 262 | if (restOfTheData != nullptr) { |
| 263 | restOfTheData->reuse(); |
| 264 | restOfTheData = nullptr; |
| 265 | } |
| 266 | lastPacketLength = 0; |
| 267 | wasConnected = false; |
| 268 | hasSomeDataSinceLastConnect = false; |
| 269 | openConnection(hostAddress, hostPort, ipv6 != 0, ConnectionsManager::getInstance().currentNetworkType); |
| 270 | if (connectionType == ConnectionTypePush) { |
| 271 | if (isTryingNextPort) { |
| 272 | setTimeout(20); |
| 273 | } else { |
| 274 | setTimeout(30); |
| 275 | } |
| 276 | } else { |
| 277 | if (isTryingNextPort) { |
| 278 | setTimeout(8); |
| 279 | } else { |
| 280 | if (connectionType == ConnectionTypeUpload) { |
| 281 | setTimeout(25); |
| 282 | } else { |
| 283 | setTimeout(12); |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 |
| 289 | void Connection::reconnect() { |
| 290 | forceNextPort = true; |
| 291 | suspendConnection(true); |
| 292 | connect(); |
| 293 | } |
| 294 |
| 295 | bool Connection::hasUsefullData() { |
| 296 | return usefullData; |
| 297 | } |
| 298 |
| 299 | void Connection::setHasUsefullData() { |
| 300 | usefullData = true; |
| 301 | } |
| 302 |
| 303 | void Connection::sendData(NativeByteBuffer *buff, bool reportAck) { |
| 304 | if (buff == nullptr) { |
| 305 | return; |
| 306 | } |
| 307 | buff->rewind(); |
| 308 | if (connectionState == TcpConnectionStageIdle || connectionState == TcpConnectionStageReconnecting || connectionState == TcpConnectionStageSuspended) { |
| 309 | connect(); |
| 310 | } |
| 311 |
| 312 | if (isDisconnected()) { |
| 313 | buff->reuse(); |
| 314 | DEBUG_D("connection(%p, dc%u, type %d) disconnected, don't send data", this, currentDatacenter->getDatacenterId(), connectionType); |
| 315 | return; |
| 316 | } |
| 317 |
| 318 | uint32_t bufferLen = 0; |
| 319 | uint32_t packetLength = buff->limit() / 4; |
| 320 |
| 321 | if (packetLength < 0x7f) { |
| 322 | bufferLen++; |
| 323 | } else { |
| 324 | bufferLen += 4; |
| 325 | } |
| 326 | if (!firstPacketSent) { |
| 327 | bufferLen += 64; |
| 328 | } |
| 329 |
| 330 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(bufferLen); |
| 331 | uint8_t *bytes = buffer->bytes(); |
| 332 |
| 333 | if (!firstPacketSent) { |
| 334 | buffer->position(64); |
| 335 | static uint8_t temp[64]; |
| 336 | while (true) { |
| 337 | RAND_bytes(bytes, 64); |
| 338 | uint32_t val = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0]); |
| 339 | uint32_t val2 = (bytes[7] << 24) | (bytes[6] << 16) | (bytes[5] << 8) | (bytes[4]); |
| 340 | if (bytes[0] != 0xef && val != 0x44414548 && val != 0x54534f50 && val != 0x20544547 && val != 0x4954504f && val != 0xeeeeeeee && val2 != 0x00000000) { |
| 341 | bytes[56] = bytes[57] = bytes[58] = bytes[59] = 0xef; |
| 342 | break; |
| 343 | } |
| 344 | } |
| 345 | for (int a = 0; a < 48; a++) { |
| 346 | temp[a] = bytes[55 - a]; |
| 347 | } |
| 348 |
| 349 | encryptNum = decryptNum = 0; |
| 350 | memset(encryptCount, 0, 16); |
| 351 | memset(decryptCount, 0, 16); |
| 352 |
| 353 | if (AES_set_encrypt_key(bytes + 8, 256, &encryptKey) < 0) { |
| 354 | DEBUG_E("unable to set encryptKey"); |
| 355 | exit(1); |
| 356 | } |
| 357 | memcpy(encryptIv, bytes + 40, 16); |
| 358 |
| 359 | if (AES_set_encrypt_key(temp, 256, &decryptKey) < 0) { |
| 360 | DEBUG_E("unable to set decryptKey"); |
| 361 | exit(1); |
| 362 | } |
| 363 | memcpy(decryptIv, temp + 32, 16); |
| 364 |
| 365 | AES_ctr128_encrypt(bytes, temp, 64, &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 366 | memcpy(bytes + 56, temp + 56, 8); |
| 367 |
| 368 | firstPacketSent = true; |
| 369 | } |
| 370 | if (packetLength < 0x7f) { |
| 371 | if (reportAck) { |
| 372 | packetLength |= (1 << 7); |
| 373 | } |
| 374 | buffer->writeByte((uint8_t) packetLength); |
| 375 | bytes += (buffer->limit() - 1); |
| 376 | AES_ctr128_encrypt(bytes, bytes, 1, &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 377 | } else { |
| 378 | packetLength = (packetLength << 8) + 0x7f; |
| 379 | if (reportAck) { |
| 380 | packetLength |= (1 << 7); |
| 381 | } |
| 382 | buffer->writeInt32(packetLength); |
| 383 | bytes += (buffer->limit() - 4); |
| 384 | AES_ctr128_encrypt(bytes, bytes, 4, &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 385 | } |
| 386 |
| 387 | buffer->rewind(); |
| 388 | writeBuffer(buffer); |
| 389 | buff->rewind(); |
| 390 | AES_ctr128_encrypt(buff->bytes(), buff->bytes(), buff->limit(), &encryptKey, encryptIv, encryptCount, &encryptNum); |
| 391 | writeBuffer(buff); |
| 392 | } |
| 393 |
| 394 | void Connection::onDisconnected(int reason) { |
| 395 | reconnectTimer->stop(); |
| 396 | DEBUG_D("connection(%p, dc%u, type %d) disconnected with reason %d", this, currentDatacenter->getDatacenterId(), connectionType, reason); |
| 397 | bool switchToNextPort = wasConnected && !hasSomeDataSinceLastConnect && reason == 2 || forceNextPort; |
| 398 | firstPacketSent = false; |
| 399 | if (restOfTheData != nullptr) { |
| 400 | restOfTheData->reuse(); |
| 401 | restOfTheData = nullptr; |
| 402 | } |
| 403 | connectionToken = 0; |
| 404 | lastPacketLength = 0; |
| 405 | wasConnected = false; |
| 406 | if (connectionState != TcpConnectionStageSuspended && connectionState != TcpConnectionStageIdle) { |
| 407 | connectionState = TcpConnectionStageIdle; |
| 408 | } |
| 409 | ConnectionsManager::getInstance().onConnectionClosed(this, reason); |
| 410 |
| 411 | uint32_t datacenterId = currentDatacenter->getDatacenterId(); |
| 412 | if (connectionState == TcpConnectionStageIdle) { |
| 413 | connectionState = TcpConnectionStageReconnecting; |
| 414 | failedConnectionCount++; |
| 415 | if (failedConnectionCount == 1) { |
| 416 | if (usefullData) { |
| 417 | willRetryConnectCount = 3; |
| 418 | } else { |
| 419 | willRetryConnectCount = 1; |
| 420 | } |
| 421 | } |
| 422 | if (ConnectionsManager::getInstance().isNetworkAvailable()) { |
| 423 | isTryingNextPort = true; |
| 424 | if (failedConnectionCount > willRetryConnectCount || switchToNextPort) { |
| 425 | currentDatacenter->nextAddressOrPort(currentAddressFlags); |
| 426 | failedConnectionCount = 0; |
| 427 | } |
| 428 | } |
| 429 | if (connectionType == ConnectionTypeGeneric && (currentDatacenter->isHandshaking() || datacenterId == ConnectionsManager::getInstance().currentDatacenterId || datacenterId == ConnectionsManager::getInstance().movingToDatacenterId)) { |
| 430 | DEBUG_D("connection(%p, dc%u, type %d) reconnect %s:%hu", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); |
| 431 | reconnectTimer->setTimeout(1000, false); |
| 432 | reconnectTimer->start(); |
| 433 | } |
| 434 |
| 435 | } |
| 436 | usefullData = false; |
| 437 | } |
| 438 |
| 439 | void Connection::onConnected() { |
| 440 | connectionState = TcpConnectionStageConnected; |
| 441 | connectionToken = lastConnectionToken++; |
| 442 | wasConnected = true; |
| 443 | DEBUG_D("connection(%p, dc%u, type %d) connected to %s:%hu", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); |
| 444 | ConnectionsManager::getInstance().onConnectionConnected(this); |
| 445 | } |
| 446 |
| 447 | Datacenter *Connection::getDatacenter() { |
| 448 | return currentDatacenter; |
| 449 | } |
| 450 |
| 451 | ConnectionType Connection::getConnectionType() { |
| 452 | return connectionType; |
| 453 | } |
| 454 |
| 455 | uint32_t Connection::getConnectionToken() { |
| 456 | return connectionToken; |
| 457 | } |
| 458 |