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