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