| 7 | */ |
| 8 |
| 9 | #include <cassert> |
| 10 | #include <cstdlib> |
| 11 | #include <sys/eventfd.h> |
| 12 | #include <unistd.h> |
| 13 | #include <chrono> |
| 14 | #include <algorithm> |
| 15 | #include <fcntl.h> |
| 16 | #include <memory.h> |
| 17 | #include <openssl/rand.h> |
| 18 | #include <zlib.h> |
| 19 | #include <memory> |
| 20 | #include <string> |
| 21 | #include <cinttypes> |
| 22 | #include "ConnectionsManager.h" |
| 23 | #include "FileLog.h" |
| 24 | #include "EventObject.h" |
| 25 | #include "MTProtoScheme.h" |
| 26 | #include "ApiScheme.h" |
| 27 | #include "NativeByteBuffer.h" |
| 28 | #include "Connection.h" |
| 29 | #include "Datacenter.h" |
| 30 | #include "Request.h" |
| 31 | #include "BuffersStorage.h" |
| 32 | #include "ByteArray.h" |
| 33 | #include "Config.h" |
| 34 | #include "ProxyCheckInfo.h" |
| 35 | #include "Handshake.h" |
| 36 |
| 37 | #ifdef ANDROID |
| 38 | #include <jni.h> |
| 39 | JavaVM *javaVm = nullptr; |
| 40 | JNIEnv *jniEnv[MAX_ACCOUNT_COUNT]; |
| 41 | jclass jclass_ByteBuffer = nullptr; |
| 42 | jmethodID jclass_ByteBuffer_allocateDirect = nullptr; |
| 43 | #endif |
| 44 |
| 45 | static bool done = false; |
| 46 |
| 47 | ConnectionsManager::ConnectionsManager(int32_t instance) { |
| 48 | instanceNum = instance; |
| 49 | if ((epolFd = epoll_create(128)) == -1) { |
| 50 | if (LOGS_ENABLED) DEBUG_E("unable to create epoll instance"); |
| 51 | exit(1); |
| 52 | } |
| 53 | int flags; |
| 54 | if ((flags = fcntl(epolFd, F_GETFD, NULL)) < 0) { |
| 55 | if (LOGS_ENABLED) DEBUG_W("fcntl(%d, F_GETFD)", epolFd); |
| 56 | } |
| 57 | if (!(flags & FD_CLOEXEC)) { |
| 58 | if (fcntl(epolFd, F_SETFD, flags | FD_CLOEXEC) == -1) { |
| 59 | if (LOGS_ENABLED) DEBUG_W("fcntl(%d, F_SETFD)", epolFd); |
| 60 | } |
| 61 | } |
| 62 |
| 63 | if ((epollEvents = new epoll_event[128]) == nullptr) { |
| 64 | if (LOGS_ENABLED) DEBUG_E("unable to allocate epoll events"); |
| 65 | exit(1); |
| 66 | } |
| 67 |
| 68 | eventFd = eventfd(0, EFD_NONBLOCK); |
| 69 | if (eventFd != -1) { |
| 70 | struct epoll_event event = {0}; |
| 71 | event.data.ptr = new EventObject(&eventFd, EventObjectTypeEvent); |
| 72 | event.events = EPOLLIN | EPOLLET; |
| 73 | if (epoll_ctl(epolFd, EPOLL_CTL_ADD, eventFd, &event) == -1) { |
| 74 | eventFd = -1; |
| 75 | FileLog::e("unable to add eventfd"); |
| 76 | } |
| 77 | } |
| 78 |
| 79 | if (eventFd == -1) { |
| 80 | pipeFd = new int[2]; |
| 81 | if (pipe(pipeFd) != 0) { |
| 82 | if (LOGS_ENABLED) DEBUG_E("unable to create pipe"); |
| 83 | exit(1); |
| 84 | } |
| 85 | flags = fcntl(pipeFd[0], F_GETFL); |
| 86 | if (flags == -1) { |
| 87 | if (LOGS_ENABLED) DEBUG_E("fcntl get pipefds[0] failed"); |
| 88 | exit(1); |
| 89 | } |
| 90 | if (fcntl(pipeFd[0], F_SETFL, flags | O_NONBLOCK) == -1) { |
| 91 | if (LOGS_ENABLED) DEBUG_E("fcntl set pipefds[0] failed"); |
| 92 | exit(1); |
| 93 | } |
| 94 |
| 95 | flags = fcntl(pipeFd[1], F_GETFL); |
| 96 | if (flags == -1) { |
| 97 | if (LOGS_ENABLED) DEBUG_E("fcntl get pipefds[1] failed"); |
| 98 | exit(1); |
| 99 | } |
| 100 | if (fcntl(pipeFd[1], F_SETFL, flags | O_NONBLOCK) == -1) { |
| 101 | if (LOGS_ENABLED) DEBUG_E("fcntl set pipefds[1] failed"); |
| 102 | exit(1); |
| 103 | } |
| 104 |
| 105 | auto eventObject = new EventObject(pipeFd, EventObjectTypePipe); |
| 106 |
| 107 | epoll_event eventMask = {}; |
| 108 | eventMask.events = EPOLLIN; |
| 109 | eventMask.data.ptr = eventObject; |
| 110 | if (epoll_ctl(epolFd, EPOLL_CTL_ADD, pipeFd[0], &eventMask) != 0) { |
| 111 | if (LOGS_ENABLED) DEBUG_E("can't add pipe to epoll"); |
| 112 | exit(1); |
| 113 | } |
| 114 | } |
| 115 |
| 116 | sizeCalculator = new NativeByteBuffer(true); |
| 117 | networkBuffer = new NativeByteBuffer((uint32_t) READ_BUFFER_SIZE); |
| 118 | if (networkBuffer == nullptr) { |
| 119 | if (LOGS_ENABLED) DEBUG_E("unable to allocate read buffer"); |
| 120 | exit(1); |
| 121 | } |
| 122 |
| 123 | pthread_mutex_init(&mutex, nullptr); |
| 124 | } |
| 125 |
| 126 | ConnectionsManager::~ConnectionsManager() { |
| 127 | if (epolFd != 0) { |
| 128 | close(epolFd); |
| 129 | epolFd = 0; |
| 130 | } |
| 131 | if (pipeFd != nullptr) { |
| 132 | delete[] pipeFd; |
| 133 | pipeFd = nullptr; |
| 134 | } |
| 135 | pthread_mutex_destroy(&mutex); |
| 136 | } |
| 137 |
| 138 | ConnectionsManager& ConnectionsManager::getInstance(int32_t instanceNum) { |
| 139 | switch (instanceNum) { |
| 140 | case 0: |
| 141 | static ConnectionsManager instance0(0); |
| 142 | return instance0; |
| 143 | case 1: |
| 144 | static ConnectionsManager instance1(1); |
| 145 | return instance1; |
| 146 | case 2: |
| 147 | static ConnectionsManager instance2(2); |
| 148 | return instance2; |
| 149 | case 3: |
| 150 | static ConnectionsManager instance3(3); |
| 151 | return instance3; |
| 152 | case 4: |
| 153 | default: |
| 154 | static ConnectionsManager instance4(4); |
| 155 | return instance4; |
| 156 | } |
| 157 | } |
| 158 |
| 159 | int ConnectionsManager::callEvents(int64_t now) { |
| 160 | if (!events.empty()) { |
| 161 | for (auto iter = events.begin(); iter != events.end();) { |
| 162 | EventObject *eventObject = (*iter); |
| 163 | if (eventObject->time <= now) { |
| 164 | iter = events.erase(iter); |
| 165 | eventObject->onEvent(0); |
| 166 | } else { |
| 167 | int diff = (int) (eventObject->time - now); |
| 168 | return diff > 1000 || diff < 0 ? 1000 : diff; |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | if (!networkPaused) { |
| 173 | return 1000; |
| 174 | } |
| 175 | auto timeToPushPing = (int32_t) ((sendingPushPing ? 30000 : nextPingTimeOffset) - llabs(now - lastPushPingTime)); |
| 176 | if (timeToPushPing <= 0) { |
| 177 | return 1000; |
| 178 | } |
| 179 | return timeToPushPing; |
| 180 | } |
| 181 |
| 182 | void ConnectionsManager::checkPendingTasks() { |
| 183 | int32_t count = INT_MAX; |
| 184 | while (true) { |
| 185 | std::function<void()> task; |
| 186 | pthread_mutex_lock(&mutex); |
| 187 | if (pendingTasks.empty() || count <= 0) { |
| 188 | pthread_mutex_unlock(&mutex); |
| 189 | return; |
| 190 | } |
| 191 | if (count == INT_MAX) { |
| 192 | count = (int32_t) pendingTasks.size(); |
| 193 | } else { |
| 194 | count--; |
| 195 | } |
| 196 | task = pendingTasks.front(); |
| 197 | pendingTasks.pop(); |
| 198 | pthread_mutex_unlock(&mutex); |
| 199 | task(); |
| 200 | } |
| 201 | } |
| 202 |
| 203 | void ConnectionsManager::select() { |
| 204 | checkPendingTasks(); |
| 205 | int eventsCount = epoll_wait(epolFd, epollEvents, 128, callEvents(getCurrentTimeMonotonicMillis())); |
| 206 | checkPendingTasks(); |
| 207 | int64_t now = getCurrentTimeMonotonicMillis(); |
| 208 | callEvents(now); |
| 209 | for (int32_t a = 0; a < eventsCount; a++) { |
| 210 | auto eventObject = (EventObject *) epollEvents[a].data.ptr; |
| 211 | eventObject->onEvent(epollEvents[a].events); |
| 212 | } |
| 213 | activeConnectionsCopy.resize(activeConnections.size()); |
| 214 | std::copy(std::begin(activeConnections), std::end(activeConnections), std::begin(activeConnectionsCopy)); |
| 215 | for (auto connection : activeConnectionsCopy) { |
| 216 | connection->checkTimeout(now); |
| 217 | } |
| 218 |
| 219 | Datacenter *datacenter = getDatacenterWithId(currentDatacenterId); |
| 220 | if (pushConnectionEnabled) { |
| 221 | if ((sendingPushPing && llabs(now - lastPushPingTime) >= 30000) || llabs(now - lastPushPingTime) >= nextPingTimeOffset + 10000) { |
| 222 | lastPushPingTime = 0; |
| 223 | sendingPushPing = false; |
| 224 | if (datacenter != nullptr) { |
| 225 | Connection *connection = datacenter->getPushConnection(false); |
| 226 | if (connection != nullptr) { |
| 227 | connection->suspendConnection(); |
| 228 | } |
| 229 | } |
| 230 | if (LOGS_ENABLED) DEBUG_D("push ping timeout"); |
| 231 | } |
| 232 | if (llabs(now - lastPushPingTime) >= nextPingTimeOffset) { |
| 233 | if (LOGS_ENABLED) DEBUG_D("time for push ping"); |
| 234 | lastPushPingTime = now; |
| 235 | uint8_t offset; |
| 236 | RAND_bytes(&offset, 1); |
| 237 | nextPingTimeOffset = 60000 * 3 + (offset % 40) - 20; |
| 238 | if (datacenter != nullptr) { |
| 239 | sendPing(datacenter, true); |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 |
| 244 | if (lastPauseTime != 0 && llabs(now - lastPauseTime) >= nextSleepTimeout) { |
| 245 | bool dontSleep = !requestingSaltsForDc.empty(); |
| 246 | if (!dontSleep) { |
| 247 | for (auto & runningRequest : runningRequests) { |
| 248 | Request *request = runningRequest.get(); |
| 249 | if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) { |
| 250 | dontSleep = true; |
| 251 | break; |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | if (!dontSleep) { |
| 256 | for (auto & iter : requestsQueue) { |
| 257 | Request *request = iter.get(); |
| 258 | if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) { |
| 259 | dontSleep = true; |
| 260 | break; |
| 261 | } |
| 262 | } |
| 263 | } |
| 264 | if (!dontSleep) { |
| 265 | if (!networkPaused) { |
| 266 | if (LOGS_ENABLED) DEBUG_D("pausing network and timers by sleep time = %d", nextSleepTimeout); |
| 267 | for (auto & dc : datacenters) { |
| 268 | dc.second->suspendConnections(false); |
| 269 | } |
| 270 | } |
| 271 | networkPaused = true; |
| 272 | return; |
| 273 | } else { |
| 274 | lastPauseTime = now; |
| 275 | if (LOGS_ENABLED) DEBUG_D("don't sleep because of salt, upload or download request"); |
| 276 | } |
| 277 | } |
| 278 | if (networkPaused) { |
| 279 | networkPaused = false; |
| 280 | for (auto & dc : datacenters) { |
| 281 | if (dc.second->isHandshaking(false)) { |
| 282 | dc.second->createGenericConnection()->connect(); |
| 283 | } else if (dc.second->isHandshaking(true)) { |
| 284 | dc.second->createGenericMediaConnection()->connect(); |
| 285 | } |
| 286 | } |
| 287 | if (LOGS_ENABLED) DEBUG_D("resume network and timers"); |
| 288 | } |
| 289 |
| 290 | if (delegate != nullptr) { |
| 291 | delegate->onUpdate(instanceNum); |
| 292 | } |
| 293 | if (datacenter != nullptr) { |
| 294 | if (datacenter->hasAuthKey(ConnectionTypeGeneric, 1)) { |
| 295 | if (llabs(now - lastPingTime) >= (testBackend ? 2000 : 19000)) { |
| 296 | lastPingTime = now; |
| 297 | sendPing(datacenter, false); |
| 298 | } |
| 299 | if (abs((int32_t) (now / 1000) - lastDcUpdateTime) >= DC_UPDATE_TIME) { |
| 300 | updateDcSettings(0, false, false); |
| 301 | } |
| 302 | processRequestQueue(0, 0); |
| 303 | } else if (!datacenter->isHandshakingAny()) { |
| 304 | datacenter->beginHandshake(HandshakeTypeAll, true); |
| 305 | } |
| 306 | } |
| 307 | } |
| 308 |
| 309 | void ConnectionsManager::scheduleTask(std::function<void()> task) { |
| 310 | pthread_mutex_lock(&mutex); |
| 311 | pendingTasks.push(task); |
| 312 | pthread_mutex_unlock(&mutex); |
| 313 | wakeup(); |
| 314 | } |
| 315 |
| 316 | void ConnectionsManager::scheduleEvent(EventObject *eventObject, uint32_t time) { |
| 317 | eventObject->time = getCurrentTimeMonotonicMillis() + time; |
| 318 | std::list<EventObject *>::iterator iter; |
| 319 | for (iter = events.begin(); iter != events.end(); iter++) { |
| 320 | if ((*iter)->time > eventObject->time) { |
| 321 | break; |
| 322 | } |
| 323 | } |
| 324 | events.insert(iter, eventObject); |
| 325 | } |
| 326 |
| 327 | void ConnectionsManager::removeEvent(EventObject *eventObject) { |
| 328 | for (auto iter = events.begin(); iter != events.end(); iter++) { |
| 329 | if (*iter == eventObject) { |
| 330 | events.erase(iter); |
| 331 | break; |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 |
| 336 | void ConnectionsManager::wakeup() { |
| 337 | if (pipeFd == nullptr) { |
| 338 | eventfd_write(eventFd, 1); |
| 339 | } else { |
| 340 | char ch = 'x'; |
| 341 | write(pipeFd[1], &ch, 1); |
| 342 | } |
| 343 | } |
| 344 |
| 345 | void *ConnectionsManager::ThreadProc(void *data) { |
| 346 | if (LOGS_ENABLED) DEBUG_D("network thread started"); |
| 347 | auto networkManager = (ConnectionsManager *) (data); |
| 348 | #ifdef ANDROID |
| 349 | javaVm->AttachCurrentThread(&jniEnv[networkManager->instanceNum], nullptr); |
| 350 | #endif |
| 351 | if (networkManager->currentUserId != 0 && networkManager->pushConnectionEnabled) { |
| 352 | Datacenter *datacenter = networkManager->getDatacenterWithId(networkManager->currentDatacenterId); |
| 353 | if (datacenter != nullptr) { |
| 354 | datacenter->createPushConnection()->setSessionId(networkManager->pushSessionId); |
| 355 | networkManager->sendPing(datacenter, true); |
| 356 | } |
| 357 | } |
| 358 | do { |
| 359 | networkManager->select(); |
| 360 | } while (!done); |
| 361 | return nullptr; |
| 362 | } |
| 363 |
| 364 | void ConnectionsManager::loadConfig() { |
| 365 | if (config == nullptr) { |
| 366 | config = new Config(instanceNum, "tgnet.dat"); |
| 367 | } |
| 368 | NativeByteBuffer *buffer = config->readConfig(); |
| 369 | if (buffer != nullptr) { |
| 370 | uint32_t version = buffer->readUint32(nullptr); |
| 371 | if (LOGS_ENABLED) DEBUG_D("config version = %u", version); |
| 372 | if (version <= configVersion) { |
| 373 | testBackend = buffer->readBool(nullptr); |
| 374 | if (version >= 3) { |
| 375 | clientBlocked = buffer->readBool(nullptr); |
| 376 | } |
| 377 | if (version >= 4) { |
| 378 | lastInitSystemLangcode = buffer->readString(nullptr); |
| 379 | } |
| 380 | if (buffer->readBool(nullptr)) { |
| 381 | currentDatacenterId = buffer->readUint32(nullptr); |
| 382 | timeDifference = buffer->readInt32(nullptr); |
| 383 | lastDcUpdateTime = buffer->readInt32(nullptr); |
| 384 | pushSessionId = buffer->readInt64(nullptr); |
| 385 | if (version >= 2) { |
| 386 | registeredForInternalPush = buffer->readBool(nullptr); |
| 387 | } |
| 388 | if (version >= 5) { |
| 389 | int32_t lastServerTime = buffer->readInt32(nullptr); |
| 390 | int32_t currentTime = getCurrentTime(); |
| 391 | if (currentTime > timeDifference && currentTime < lastServerTime) { |
| 392 | timeDifference += (lastServerTime - currentTime); |
| 393 | } |
| 394 | } |
| 395 |
| 396 | if (LOGS_ENABLED) DEBUG_D("current dc id = %u, time difference = %d, registered for push = %d", currentDatacenterId, timeDifference, (int32_t) registeredForInternalPush); |
| 397 |
| 398 | uint32_t count = buffer->readUint32(nullptr); |
| 399 | for (uint32_t a = 0; a < count; a++) { |
| 400 | sessionsToDestroy.push_back(buffer->readInt64(nullptr)); |
| 401 | } |
| 402 |
| 403 | count = buffer->readUint32(nullptr); |
| 404 | for (uint32_t a = 0; a < count; a++) { |
| 405 | auto datacenter = new Datacenter(instanceNum, buffer); |
| 406 | datacenters[datacenter->getDatacenterId()] = datacenter; |
| 407 | if (LOGS_ENABLED) DEBUG_D("datacenter(%p) %u loaded (hasAuthKey = %d, 0x%" PRIx64 ")", datacenter, datacenter->getDatacenterId(), (int) datacenter->hasPermanentAuthKey(), datacenter->getPermanentAuthKeyId()); |
| 408 | if (datacenter->isCdnDatacenter && !datacenter->hasPermanentAuthKey()) { |
| 409 | datacenter->clearAuthKey(HandshakeTypePerm); |
| 410 | } |
| 411 | } |
| 412 | } |
| 413 | } |
| 414 | buffer->reuse(); |
| 415 | } |
| 416 |
| 417 | if (currentDatacenterId != 0 && currentUserId) { |
| 418 | Datacenter *datacenter = getDatacenterWithId(currentDatacenterId); |
| 419 | if (datacenter == nullptr || !datacenter->hasPermanentAuthKey()) { |
| 420 | if (datacenter != nullptr) { |
| 421 | if (LOGS_ENABLED) DEBUG_D("reset authorization because of dc %d", currentDatacenterId); |
| 422 | } |
| 423 | currentDatacenterId = 0; |
| 424 | datacenters.clear(); |
| 425 | scheduleTask([&] { |
| 426 | if (delegate != nullptr) { |
| 427 | delegate->onLogout(instanceNum); |
| 428 | } |
| 429 | }); |
| 430 | } |
| 431 | } |
| 432 |
| 433 | initDatacenters(); |
| 434 |
| 435 | if ((!datacenters.empty() && currentDatacenterId == 0) || pushSessionId == 0) { |
| 436 | if (pushSessionId == 0) { |
| 437 | RAND_bytes((uint8_t *) &pushSessionId, 8); |
| 438 | } |
| 439 | if (currentDatacenterId == 0) { |
| 440 | currentDatacenterId = 2; |
| 441 | } |
| 442 | saveConfig(); |
| 443 | } |
| 444 | movingToDatacenterId = DEFAULT_DATACENTER_ID; |
| 445 | } |
| 446 |
| 447 | void ConnectionsManager::saveConfigInternal(NativeByteBuffer *buffer) { |
| 448 | buffer->writeInt32(configVersion); |
| 449 | buffer->writeBool(testBackend); |
| 450 | buffer->writeBool(clientBlocked); |
| 451 | buffer->writeString(lastInitSystemLangcode); |
| 452 | Datacenter *currentDatacenter = getDatacenterWithId(currentDatacenterId); |
| 453 | buffer->writeBool(currentDatacenter != nullptr); |
| 454 | if (currentDatacenter != nullptr) { |
| 455 | buffer->writeInt32(currentDatacenterId); |
| 456 | buffer->writeInt32(timeDifference); |
| 457 | buffer->writeInt32(lastDcUpdateTime); |
| 458 | buffer->writeInt64(pushSessionId); |
| 459 | buffer->writeBool(registeredForInternalPush); |
| 460 | buffer->writeInt32(getCurrentTime()); |
| 461 |
| 462 | std::vector<int64_t> sessions; |
| 463 | currentDatacenter->getSessions(sessions); |
| 464 |
| 465 | auto count = (uint32_t) sessions.size(); |
| 466 | buffer->writeInt32(count); |
| 467 | for (uint32_t a = 0; a < count; a++) { |
| 468 | buffer->writeInt64(sessions[a]); |
| 469 | } |
| 470 | count = (uint32_t) datacenters.size(); |
| 471 | buffer->writeInt32(count); |
| 472 | for (auto & datacenter : datacenters) { |
| 473 | datacenter.second->serializeToStream(buffer); |
| 474 | } |
| 475 | } |
| 476 | } |
| 477 |
| 478 | void ConnectionsManager::saveConfig() { |
| 479 | if (config == nullptr) { |
| 480 | config = new Config(instanceNum, "tgnet.dat"); |
| 481 | } |
| 482 | sizeCalculator->clearCapacity(); |
| 483 | saveConfigInternal(sizeCalculator); |
| 484 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(sizeCalculator->capacity()); |
| 485 | saveConfigInternal(buffer); |
| 486 | config->writeConfig(buffer); |
| 487 | buffer->reuse(); |
| 488 | } |
| 489 |
| 490 | inline NativeByteBuffer *decompressGZip(NativeByteBuffer *data) { |
| 491 | int retCode; |
| 492 | z_stream stream; |
| 493 |
| 494 | memset(&stream, 0, sizeof(z_stream)); |
| 495 | stream.avail_in = data->limit(); |
| 496 | stream.next_in = data->bytes(); |
| 497 |
| 498 | retCode = inflateInit2(&stream, 15 + 32); |
| 499 | if (retCode != Z_OK) { |
| 500 | if (LOGS_ENABLED) DEBUG_E("can't decompress data"); |
| 501 | exit(1); |
| 502 | } |
| 503 | NativeByteBuffer *result = BuffersStorage::getInstance().getFreeBuffer(data->limit() * 4); |
| 504 | stream.avail_out = result->capacity(); |
| 505 | stream.next_out = result->bytes(); |
| 506 | while (1) { |
| 507 | retCode = inflate(&stream, Z_NO_FLUSH); |
| 508 | if (retCode == Z_STREAM_END) { |
| 509 | break; |
| 510 | } |
| 511 | if (retCode == Z_OK) { |
| 512 | NativeByteBuffer *newResult = BuffersStorage::getInstance().getFreeBuffer(result->capacity() * 2); |
| 513 | memcpy(newResult->bytes(), result->bytes(), result->capacity()); |
| 514 | stream.avail_out = newResult->capacity() - result->capacity(); |
| 515 | stream.next_out = newResult->bytes() + result->capacity(); |
| 516 | result->reuse(); |
| 517 | result = newResult; |
| 518 | } else { |
| 519 | if (LOGS_ENABLED) DEBUG_E("can't decompress data"); |
| 520 | exit(1); |
| 521 | } |
| 522 | } |
| 523 | result->limit((uint32_t) stream.total_out); |
| 524 | inflateEnd(&stream); |
| 525 | return result; |
| 526 | } |
| 527 |
| 528 | inline NativeByteBuffer *compressGZip(NativeByteBuffer *buffer) { |
| 529 | if (buffer == nullptr || buffer->limit() == 0) { |
| 530 | return nullptr; |
| 531 | } |
| 532 | z_stream stream; |
| 533 | int retCode; |
| 534 |
| 535 | memset(&stream, 0, sizeof(z_stream)); |
| 536 | stream.avail_in = buffer->limit(); |
| 537 | stream.next_in = buffer->bytes(); |
| 538 |
| 539 | retCode = deflateInit2(&stream, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY); |
| 540 | if (retCode != Z_OK) { |
| 541 | if (LOGS_ENABLED) DEBUG_E("%s: deflateInit2() failed with error %i", __PRETTY_FUNCTION__, retCode); |
| 542 | return nullptr; |
| 543 | } |
| 544 |
| 545 | NativeByteBuffer *result = BuffersStorage::getInstance().getFreeBuffer(buffer->limit()); |
| 546 | stream.avail_out = result->limit(); |
| 547 | stream.next_out = result->bytes(); |
| 548 | retCode = deflate(&stream, Z_FINISH); |
| 549 | if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) { |
| 550 | if (LOGS_ENABLED) DEBUG_E("%s: deflate() failed with error %i", __PRETTY_FUNCTION__, retCode); |
| 551 | deflateEnd(&stream); |
| 552 | result->reuse(); |
| 553 | return nullptr; |
| 554 | } |
| 555 | if (retCode != Z_STREAM_END || stream.total_out >= buffer->limit() - 4) { |
| 556 | deflateEnd(&stream); |
| 557 | result->reuse(); |
| 558 | return nullptr; |
| 559 | } |
| 560 | result->limit((uint32_t) stream.total_out); |
| 561 | deflateEnd(&stream); |
| 562 | return result; |
| 563 | } |
| 564 |
| 565 | int64_t ConnectionsManager::getCurrentTimeMillis() { |
| 566 | clock_gettime(CLOCK_REALTIME, &timeSpec); |
| 567 | return (int64_t) timeSpec.tv_sec * 1000 + (int64_t) timeSpec.tv_nsec / 1000000; |
| 568 | } |
| 569 |
| 570 | int64_t ConnectionsManager::getCurrentTimeMonotonicMillis() { |
| 571 | clock_gettime(CLOCK_BOOTTIME, &timeSpecMonotonic); |
| 572 | return (int64_t) timeSpecMonotonic.tv_sec * 1000 + (int64_t) timeSpecMonotonic.tv_nsec / 1000000; |
| 573 | } |
| 574 |
| 575 | int32_t ConnectionsManager::getCurrentTime() { |
| 576 | return (int32_t) (getCurrentTimeMillis() / 1000) + timeDifference; |
| 577 | } |
| 578 |
| 579 | int32_t ConnectionsManager::getCurrentPingTime() { |
| 580 | return (int32_t) currentPingTimeLive; |
| 581 | } |
| 582 |
| 583 | uint32_t ConnectionsManager::getCurrentDatacenterId() { |
| 584 | Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID); |
| 585 | return datacenter != nullptr ? datacenter->getDatacenterId() : INT_MAX; |
| 586 | } |
| 587 |
| 588 | int64_t ConnectionsManager::getCurrentAuthKeyId() { |
| 589 | Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID); |
| 590 | return datacenter != nullptr ? datacenter->getPermanentAuthKeyId() : 0; |
| 591 | } |
| 592 |
| 593 | bool ConnectionsManager::isTestBackend() { |
| 594 | return testBackend; |
| 595 | } |
| 596 |
| 597 | int32_t ConnectionsManager::getTimeDifference() { |
| 598 | return timeDifference; |
| 599 | } |
| 600 |
| 601 | int64_t ConnectionsManager::generateMessageId() { |
| 602 | auto messageId = (int64_t) ((((double) getCurrentTimeMillis() + ((double) timeDifference) * 1000) * 4294967296.0) / 1000.0); |
| 603 | if (messageId <= lastOutgoingMessageId) { |
| 604 | messageId = lastOutgoingMessageId + 1; |
| 605 | } |
| 606 | while (messageId % 4 != 0) { |
| 607 | messageId++; |
| 608 | } |
| 609 | lastOutgoingMessageId = messageId; |
| 610 | return messageId; |
| 611 | } |
| 612 |
| 613 | bool ConnectionsManager::isNetworkAvailable() { |
| 614 | return networkAvailable; |
| 615 | } |
| 616 |
| 617 | void ConnectionsManager::cleanUp(bool resetKeys, int32_t datacenterId) { |
| 618 | scheduleTask([&, resetKeys, datacenterId] { |
| 619 | for (auto iter = requestsQueue.begin(); iter != requestsQueue.end();) { |
| 620 | Request *request = iter->get(); |
| 621 | if (datacenterId != -1) { |
| 622 | Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId); |
| 623 | if (requestDatacenter != nullptr && requestDatacenter->getDatacenterId() != datacenterId) { |
| 624 | iter++; |
| 625 | continue; |
| 626 | } |
| 627 | } |
| 628 | if (request->requestFlags & RequestFlagWithoutLogin) { |
| 629 | iter++; |
| 630 | continue; |
| 631 | } |
| 632 | if (request->onCompleteRequestCallback != nullptr) { |
| 633 | auto error = new TL_error(); |
| 634 | error->code = -1000; |
| 635 | error->text = ""; |
| 636 | int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId; |
| 637 | request->onComplete(nullptr, error, 0, 0, request->messageId, dcId); |
| 638 | delete error; |
| 639 | } |
| 640 | iter = requestsQueue.erase(iter); |
| 641 | } |
| 642 | for (auto iter = runningRequests.begin(); iter != runningRequests.end();) { |
| 643 | Request *request = iter->get(); |
| 644 | if (datacenterId != -1) { |
| 645 | Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId); |
| 646 | if (requestDatacenter != nullptr && requestDatacenter->getDatacenterId() != datacenterId) { |
| 647 | iter++; |
| 648 | continue; |
| 649 | } |
| 650 | } |
| 651 | if (request->requestFlags & RequestFlagWithoutLogin) { |
| 652 | iter++; |
| 653 | continue; |
| 654 | } |
| 655 | if (request->onCompleteRequestCallback != nullptr) { |
| 656 | auto error = new TL_error(); |
| 657 | error->code = -1000; |
| 658 | error->text = ""; |
| 659 | int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId; |
| 660 | request->onComplete(nullptr, error, 0, 0, request->messageId, dcId); |
| 661 | delete error; |
| 662 | } |
| 663 | DEBUG_D("1) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 664 | iter = runningRequests.erase(iter); |
| 665 | } |
| 666 | quickAckIdToRequestIds.clear(); |
| 667 |
| 668 | for (auto & datacenter : datacenters) { |
| 669 | if (datacenterId != -1 && datacenter.second->getDatacenterId() != datacenterId) { |
| 670 | continue; |
| 671 | } |
| 672 | if (resetKeys) { |
| 673 | datacenter.second->clearAuthKey(HandshakeTypeAll); |
| 674 | } |
| 675 | datacenter.second->recreateSessions(HandshakeTypeAll); |
| 676 | datacenter.second->authorized = false; |
| 677 | } |
| 678 | if (datacenterId == -1) { |
| 679 | sessionsToDestroy.clear(); |
| 680 | currentUserId = 0; |
| 681 | currentUserPremium = false; |
| 682 | registeredForInternalPush = false; |
| 683 | } |
| 684 | saveConfig(); |
| 685 | }); |
| 686 | } |
| 687 |
| 688 | void ConnectionsManager::onConnectionClosed(Connection *connection, int reason) { |
| 689 | if (reason == 1) { |
| 690 | lastProtocolUsefullData = false; |
| 691 | } |
| 692 | Datacenter *datacenter = connection->getDatacenter(); |
| 693 | if ((connection->getConnectionType() == ConnectionTypeGeneric || connection->getConnectionType() == ConnectionTypeGenericMedia) && datacenter->isHandshakingAny()) { |
| 694 | datacenter->onHandshakeConnectionClosed(connection); |
| 695 | } |
| 696 | if (connection->getConnectionType() == ConnectionTypeGeneric) { |
| 697 | if (datacenter->getDatacenterId() == currentDatacenterId) { |
| 698 | sendingPing = false; |
| 699 | if (!connection->isSuspended() && (proxyAddress.empty() || connection->hasTlsHashMismatch())) { |
| 700 | if (reason == 2) { |
| 701 | disconnectTimeoutAmount += connection->getTimeout(); |
| 702 | } else { |
| 703 | disconnectTimeoutAmount += 4; |
| 704 | } |
| 705 | if (LOGS_ENABLED) DEBUG_D("increase disconnect timeout %d", disconnectTimeoutAmount); |
| 706 | int32_t maxTimeout; |
| 707 | if (clientBlocked) { |
| 708 | maxTimeout = 5; |
| 709 | } else { |
| 710 | maxTimeout = 20; |
| 711 | } |
| 712 | if (disconnectTimeoutAmount >= maxTimeout) { |
| 713 | if (!connection->hasUsefullData()) { |
| 714 | if (LOGS_ENABLED) DEBUG_D("start requesting new address and port due to timeout reach"); |
| 715 | requestingSecondAddressByTlsHashMismatch = connection->hasTlsHashMismatch(); |
| 716 | if (requestingSecondAddressByTlsHashMismatch) { |
| 717 | requestingSecondAddress = 1; |
| 718 | } else { |
| 719 | requestingSecondAddress = 0; |
| 720 | } |
| 721 | delegate->onRequestNewServerIpAndPort(requestingSecondAddress, instanceNum); |
| 722 | } else { |
| 723 | if (LOGS_ENABLED) DEBUG_D("connection has usefull data, don't request anything"); |
| 724 | } |
| 725 | disconnectTimeoutAmount = 0; |
| 726 | } |
| 727 | } |
| 728 |
| 729 | if (networkAvailable) { |
| 730 | if (proxyAddress.empty()) { |
| 731 | if (connectionState != ConnectionStateConnecting) { |
| 732 | connectionState = ConnectionStateConnecting; |
| 733 | if (delegate != nullptr) { |
| 734 | delegate->onConnectionStateChanged(connectionState, instanceNum); |
| 735 | } |
| 736 | } |
| 737 | } else { |
| 738 | if (connectionState != ConnectionStateConnectingViaProxy) { |
| 739 | connectionState = ConnectionStateConnectingViaProxy; |
| 740 | if (delegate != nullptr) { |
| 741 | delegate->onConnectionStateChanged(connectionState, instanceNum); |
| 742 | } |
| 743 | } |
| 744 | } |
| 745 | } else { |
| 746 | if (connectionState != ConnectionStateWaitingForNetwork) { |
| 747 | connectionState = ConnectionStateWaitingForNetwork; |
| 748 | if (delegate != nullptr) { |
| 749 | delegate->onConnectionStateChanged(connectionState, instanceNum); |
| 750 | } |
| 751 | } |
| 752 | } |
| 753 | } |
| 754 | } else if (connection->getConnectionType() == ConnectionTypePush) { |
| 755 | if (LOGS_ENABLED) DEBUG_D("connection(%p) push connection closed", connection); |
| 756 | sendingPushPing = false; |
| 757 | lastPushPingTime = getCurrentTimeMonotonicMillis() - nextPingTimeOffset + 4000; |
| 758 | } else if (connection->getConnectionType() == ConnectionTypeProxy) { |
| 759 | scheduleTask([&, connection] { |
| 760 | for (auto iter = proxyActiveChecks.begin(); iter != proxyActiveChecks.end(); iter++) { |
| 761 | ProxyCheckInfo *proxyCheckInfo = iter->get(); |
| 762 | if (proxyCheckInfo->connectionNum == connection->getConnectionNum()) { |
| 763 | bool found = false; |
| 764 | for (auto iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) { |
| 765 | Request *request = iter2->get(); |
| 766 | if (connection->getConnectionToken() == request->connectionToken && request->requestToken == proxyCheckInfo->requestToken && (request->connectionType & 0x0000ffff) == ConnectionTypeProxy) { |
| 767 | request->completed = true; |
| 768 | DEBUG_D("2) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 769 | runningRequests.erase(iter2); |
| 770 | proxyCheckInfo->onRequestTime(-1); |
| 771 | found = true; |
| 772 | break; |
| 773 | } |
| 774 | } |
| 775 | if (found) { |
| 776 | proxyActiveChecks.erase(iter); |
| 777 | if (!proxyCheckQueue.empty()) { |
| 778 | proxyCheckInfo = proxyCheckQueue[0].release(); |
| 779 | proxyCheckQueue.erase(proxyCheckQueue.begin()); |
| 780 | checkProxyInternal(proxyCheckInfo); |
| 781 | } |
| 782 | } |
| 783 | break; |
| 784 | } |
| 785 | } |
| 786 | }); |
| 787 | } |
| 788 | } |
| 789 |
| 790 | void ConnectionsManager::onConnectionConnected(Connection *connection) { |
| 791 | Datacenter *datacenter = connection->getDatacenter(); |
| 792 | ConnectionType connectionType = connection->getConnectionType(); |
| 793 | if ((connectionType == ConnectionTypeGeneric || connectionType == ConnectionTypeGenericMedia) && datacenter->isHandshakingAny()) { |
| 794 | datacenter->onHandshakeConnectionConnected(connection); |
| 795 | return; |
| 796 | } |
| 797 |
| 798 | if (datacenter->hasAuthKey(connectionType, 1)) { |
| 799 | if (connectionType == ConnectionTypePush) { |
| 800 | sendingPushPing = false; |
| 801 | lastPushPingTime = getCurrentTimeMonotonicMillis(); |
| 802 | sendPing(datacenter, true); |
| 803 | } else { |
| 804 | if (connectionType == ConnectionTypeGeneric && datacenter->getDatacenterId() == currentDatacenterId) { |
| 805 | sendingPing = false; |
| 806 | } |
| 807 | if (networkPaused && lastPauseTime != 0) { |
| 808 | lastPauseTime = getCurrentTimeMonotonicMillis(); |
| 809 | } |
| 810 | processRequestQueue(connection->getConnectionType(), datacenter->getDatacenterId()); |
| 811 | } |
| 812 | } |
| 813 | } |
| 814 |
| 815 | void ConnectionsManager::onConnectionQuickAckReceived(Connection *connection, int32_t ack) { |
| 816 | auto iter = quickAckIdToRequestIds.find(ack); |
| 817 | if (iter == quickAckIdToRequestIds.end()) { |
| 818 | return; |
| 819 | } |
| 820 | for (auto & runningRequest : runningRequests) { |
| 821 | Request *request = runningRequest.get(); |
| 822 | if (std::find(iter->second.begin(), iter->second.end(), request->requestToken) != iter->second.end()) { |
| 823 | request->onQuickAck(); |
| 824 | } |
| 825 | } |
| 826 | quickAckIdToRequestIds.erase(iter); |
| 827 | } |
| 828 |
| 829 | void ConnectionsManager::onConnectionDataReceived(Connection *connection, NativeByteBuffer *data, uint32_t length) { |
| 830 | bool error = false; |
| 831 | if (length <= 24 + 32) { |
| 832 | int32_t code = data->readInt32(&error); |
| 833 | if (code == 0) { |
| 834 | if (LOGS_ENABLED) DEBUG_D("mtproto noop"); |
| 835 | } else if (code == -1) { |
| 836 | int32_t ackId = data->readInt32(&error); |
| 837 | if (!error) { |
| 838 | onConnectionQuickAckReceived(connection, ackId & (~(1 << 31))); |
| 839 | } |
| 840 | } else { |
| 841 | Datacenter *datacenter = connection->getDatacenter(); |
| 842 | if (LOGS_ENABLED) DEBUG_W("mtproto error = %d", code); |
| 843 | if (code == -444 && connection->getConnectionType() == ConnectionTypeGeneric && !proxyAddress.empty() && !proxySecret.empty()) { |
| 844 | if (delegate != nullptr) { |
| 845 | delegate->onProxyError(instanceNum); |
| 846 | } |
| 847 | } else if (code == -404 && (datacenter->isCdnDatacenter || PFS_ENABLED)) { |
| 848 | if (!datacenter->isHandshaking(connection->isMediaConnection) || datacenter->isCdnDatacenter) { |
| 849 | datacenter->clearAuthKey(connection->isMediaConnection ? HandshakeTypeMediaTemp : HandshakeTypeTemp); |
| 850 | datacenter->beginHandshake(connection->isMediaConnection ? HandshakeTypeMediaTemp : HandshakeTypeTemp, true); |
| 851 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) reset auth key due to -404 error", connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType()); |
| 852 | } |
| 853 | } else { |
| 854 | connection->reconnect(); |
| 855 | } |
| 856 | } |
| 857 | return; |
| 858 | } |
| 859 | uint32_t mark = data->position(); |
| 860 |
| 861 | int64_t keyId = data->readInt64(&error); |
| 862 |
| 863 | if (error) { |
| 864 | connection->reconnect(); |
| 865 | return; |
| 866 | } |
| 867 |
| 868 | Datacenter *datacenter = connection->getDatacenter(); |
| 869 |
| 870 | if (connectionState != ConnectionStateConnected && connection->getConnectionType() == ConnectionTypeGeneric && datacenter->getDatacenterId() == currentDatacenterId) { |
| 871 | connectionState = ConnectionStateConnected; |
| 872 | if (delegate != nullptr) { |
| 873 | delegate->onConnectionStateChanged(connectionState, instanceNum); |
| 874 | } |
| 875 | } |
| 876 |
| 877 | if (keyId == 0) { |
| 878 | int64_t messageId = data->readInt64(&error); |
| 879 | if (error) { |
| 880 | connection->reconnect(); |
| 881 | return; |
| 882 | } |
| 883 |
| 884 | if (connection->isMessageIdProcessed(messageId)) { |
| 885 | return; |
| 886 | } |
| 887 |
| 888 | uint32_t messageLength = data->readUint32(&error); |
| 889 | if (error) { |
| 890 | connection->reconnect(); |
| 891 | return; |
| 892 | } |
| 893 |
| 894 | if (!connection->allowsCustomPadding()) { |
| 895 | if (messageLength != data->remaining()) { |
| 896 | if (LOGS_ENABLED) DEBUG_E("connection(%p) received incorrect message length", connection); |
| 897 | connection->reconnect(); |
| 898 | return; |
| 899 | } |
| 900 | } |
| 901 |
| 902 | TLObject *request; |
| 903 | if (datacenter->isHandshaking(connection->isMediaConnection)) { |
| 904 | request = datacenter->getCurrentHandshakeRequest(connection->isMediaConnection); |
| 905 | if (request == nullptr) { |
| 906 | return; |
| 907 | } |
| 908 | } else { |
| 909 | return; |
| 910 | } |
| 911 |
| 912 | deserializingDatacenter = datacenter; |
| 913 | TLObject *object = TLdeserialize(request, messageLength, data); |
| 914 |
| 915 | if (object != nullptr) { |
| 916 | if (datacenter->isHandshaking(connection->isMediaConnection)) { |
| 917 | if (LOGS_ENABLED) DEBUG_E("process handshake"); |
| 918 | datacenter->processHandshakeResponse(connection->isMediaConnection, object, messageId); |
| 919 | } else { |
| 920 | if (LOGS_ENABLED) DEBUG_E("connection(%p) received incorrect unencrypted message type", connection); |
| 921 | connection->reconnect(); |
| 922 | return; |
| 923 | } |
| 924 | lastProtocolUsefullData = true; |
| 925 | connection->setHasUsefullData(); |
| 926 | delete object; |
| 927 | } |
| 928 | } else { |
| 929 | if (connection->allowsCustomPadding()) { |
| 930 | uint32_t padding = (length - 24) % 16; |
| 931 | if (padding != 0) { |
| 932 | length -= padding; |
| 933 | } |
| 934 | } |
| 935 | if (length < 24 + 32 || (!connection->allowsCustomPadding() && (length - 24) % 16 != 0) || !datacenter->decryptServerResponse(keyId, data->bytes() + mark + 8, data->bytes() + mark + 24, length - 24, connection)) { |
| 936 | if (LOGS_ENABLED) DEBUG_E("connection(%p) unable to decrypt server response", connection); |
| 937 | connection->reconnect(); |
| 938 | return; |
| 939 | } |
| 940 | data->position(mark + 24); |
| 941 |
| 942 | int64_t messageServerSalt = data->readInt64(&error); |
| 943 | int64_t messageSessionId = data->readInt64(&error); |
| 944 |
| 945 | if (messageSessionId != connection->getSessionId()) { |
| 946 | if (LOGS_ENABLED) DEBUG_E("connection(%p) received invalid message session id (0x%" PRIx64 " instead of 0x%" PRIx64 ")", connection, (uint64_t) messageSessionId, (uint64_t) connection->getSessionId()); |
| 947 | return; |
| 948 | } |
| 949 |
| 950 | int64_t messageId = data->readInt64(&error); |
| 951 | int32_t messageSeqNo = data->readInt32(&error); |
| 952 | uint32_t messageLength = data->readUint32(&error); |
| 953 |
| 954 | int32_t processedStatus = connection->isMessageIdProcessed(messageId); |
| 955 |
| 956 | if (messageSeqNo % 2 != 0) { |
| 957 | connection->addMessageToConfirm(messageId); |
| 958 | } |
| 959 |
| 960 | TLObject *object = nullptr; |
| 961 |
| 962 | long req_msg_id = 0; |
| 963 | if (processedStatus != 1) { |
| 964 | deserializingDatacenter = datacenter; |
| 965 | object = TLdeserialize(nullptr, messageLength, data); |
| 966 | TL_rpc_result* res = dynamic_cast<TL_rpc_result*>(object); |
| 967 | if (res != nullptr) { |
| 968 | req_msg_id = res->req_msg_id; |
| 969 | } |
| 970 | if (processedStatus == 2) { |
| 971 | if (object == nullptr) { |
| 972 | connection->recreateSession(); |
| 973 | connection->reconnect(); |
| 974 | return; |
| 975 | } else { |
| 976 | delete object; |
| 977 | object = nullptr; |
| 978 | } |
| 979 | } |
| 980 | } |
| 981 | if (!processedStatus) { |
| 982 | if (object != nullptr) { |
| 983 | lastProtocolUsefullData = true; |
| 984 | connection->setHasUsefullData(); |
| 985 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received object %s", connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name()); |
| 986 | processServerResponse(object, messageId, messageSeqNo, messageServerSalt, connection, 0, 0); |
| 987 | connection->addProcessedMessageId(messageId); |
| 988 | delete object; |
| 989 | if (connection->getConnectionType() == ConnectionTypePush) { |
| 990 | std::vector<std::unique_ptr<NetworkMessage>> messages; |
| 991 | sendMessagesToConnectionWithConfirmation(messages, connection, false); |
| 992 | } |
| 993 | } else { |
| 994 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received unparsed packet on 0x%" PRIx64, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), req_msg_id); |
| 995 | if (delegate != nullptr) { |
| 996 | delegate->onUnparsedMessageReceived(messageId, data, connection->getConnectionType(), instanceNum); |
| 997 | } |
| 998 | } |
| 999 | } else { |
| 1000 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received unprocessed packet on 0x%" PRIx64, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), req_msg_id); |
| 1001 | std::vector<std::unique_ptr<NetworkMessage>> messages; |
| 1002 | sendMessagesToConnectionWithConfirmation(messages, connection, false); |
| 1003 | } |
| 1004 | } |
| 1005 | } |
| 1006 |
| 1007 | bool ConnectionsManager::hasPendingRequestsForConnection(Connection *connection) { |
| 1008 | ConnectionType type = connection->getConnectionType(); |
| 1009 | if (type == ConnectionTypeGeneric || type == ConnectionTypeTemp || type == ConnectionTypeGenericMedia) { |
| 1010 | Datacenter *datacenter = connection->getDatacenter(); |
| 1011 | int8_t num = connection->getConnectionNum(); |
| 1012 | uint32_t token = connection->getConnectionToken(); |
| 1013 | if (type == ConnectionTypeGeneric) { |
| 1014 | if (sendingPing && type == ConnectionTypeGeneric && datacenter->getDatacenterId() == currentDatacenterId) { |
| 1015 | return true; |
| 1016 | } else if (datacenter->isHandshaking(false)) { |
| 1017 | return true; |
| 1018 | } |
| 1019 | } else if (type == ConnectionTypeGenericMedia) { |
| 1020 | if (datacenter->isHandshaking(true)) { |
| 1021 | return true; |
| 1022 | } |
| 1023 | } |
| 1024 | for (auto & runningRequest : runningRequests) { |
| 1025 | Request *request = runningRequest.get(); |
| 1026 | auto connectionNum = (uint8_t) (request->connectionType >> 16); |
| 1027 | auto connectionType = (ConnectionType) (request->connectionType & 0x0000ffff); |
| 1028 | if ((connectionType == type && connectionNum == num) || request->connectionToken == token) { |
| 1029 | return true; |
| 1030 | } |
| 1031 | } |
| 1032 | return false; |
| 1033 | } |
| 1034 | return true; |
| 1035 | } |
| 1036 |
| 1037 | TLObject *ConnectionsManager::getRequestWithMessageId(int64_t messageId) { |
| 1038 | for (auto & iter : runningRequests) { |
| 1039 | Request *request = iter.get(); |
| 1040 | if (request->messageId == messageId) { |
| 1041 | return request->rawRequest; |
| 1042 | } |
| 1043 | } |
| 1044 | return nullptr; |
| 1045 | } |
| 1046 |
| 1047 | TLObject *ConnectionsManager::TLdeserialize(TLObject *request, uint32_t bytes, NativeByteBuffer *data) { |
| 1048 | bool error = false; |
| 1049 | uint32_t position = data->position(); |
| 1050 | uint32_t constructor = data->readUint32(&error); |
| 1051 | if (error) { |
| 1052 | data->position(position); |
| 1053 | return nullptr; |
| 1054 | } |
| 1055 |
| 1056 | TLObject *object = TLClassStore::TLdeserialize(data, bytes, constructor, instanceNum, error); |
| 1057 |
| 1058 | if (error) { |
| 1059 | delete object; |
| 1060 | data->position(position); |
| 1061 | return nullptr; |
| 1062 | } |
| 1063 |
| 1064 | if (object == nullptr) { |
| 1065 | if (request != nullptr) { |
| 1066 | auto apiRequest = dynamic_cast<TL_api_request *>(request); |
| 1067 | if (apiRequest != nullptr) { |
| 1068 | object = apiRequest->deserializeResponse(data, bytes, instanceNum, error); |
| 1069 | if (LOGS_ENABLED) DEBUG_D("api request constructor 0x%x, don't parse", constructor); |
| 1070 | } else { |
| 1071 | object = request->deserializeResponse(data, constructor, instanceNum, error); |
| 1072 | if (object != nullptr && error) { |
| 1073 | delete object; |
| 1074 | object = nullptr; |
| 1075 | } |
| 1076 | } |
| 1077 | } else { |
| 1078 | if (constructor == 0x96a18d5) { |
| 1079 | if (LOGS_ENABLED) DEBUG_D("not found file 0x%x", constructor); |
| 1080 | } |
| 1081 | if (LOGS_ENABLED) DEBUG_D("not found request to parse constructor 0x%x", constructor); |
| 1082 | } |
| 1083 | } |
| 1084 | if (object == nullptr) { |
| 1085 | data->position(position); |
| 1086 | } |
| 1087 | return object; |
| 1088 | } |
| 1089 |
| 1090 | void ConnectionsManager::processServerResponse(TLObject *message, int64_t messageId, int32_t messageSeqNo, int64_t messageSalt, Connection *connection, int64_t innerMsgId, int64_t containerMessageId) { |
| 1091 | const std::type_info &typeInfo = typeid(*message); |
| 1092 |
| 1093 | if (LOGS_ENABLED) DEBUG_D("process server response %p - %s", message, typeInfo.name()); |
| 1094 | auto timeMessage = (int64_t) ((messageId != 0 ? messageId : innerMsgId) / 4294967296.0 * 1000); |
| 1095 |
| 1096 | Datacenter *datacenter = connection->getDatacenter(); |
| 1097 |
| 1098 | if (typeInfo == typeid(TL_new_session_created)) { |
| 1099 | auto response = (TL_new_session_created *) message; |
| 1100 |
| 1101 | if (!connection->isSessionProcessed(response->unique_id)) { |
| 1102 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) new session created (first message id: 0x%" PRIx64 ", server salt: 0x%" PRIx64 ", unique id: 0x%" PRIx64 ")", connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), (uint64_t) response->first_msg_id, (uint64_t) response->server_salt, (uint64_t) response->unique_id); |
| 1103 |
| 1104 | std::unique_ptr<TL_future_salt> salt = std::make_unique<TL_future_salt>(); |
| 1105 | salt->valid_until = salt->valid_since = getCurrentTime(); |
| 1106 | salt->valid_until += 30 * 60; |
| 1107 | salt->salt = response->server_salt; |
| 1108 | datacenter->addServerSalt(salt, Connection::isMediaConnectionType(connection->getConnectionType())); |
| 1109 |
| 1110 | for (auto & runningRequest : runningRequests) { |
| 1111 | Request *request = runningRequest.get(); |
| 1112 | Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId); |
| 1113 | if (request->messageId < response->first_msg_id && request->connectionType & connection->getConnectionType() && requestDatacenter != nullptr && requestDatacenter->getDatacenterId() == datacenter->getDatacenterId()) { |
| 1114 | if (LOGS_ENABLED) DEBUG_D("clear request %p - %s", request->rawRequest, typeid(*request->rawRequest).name()); |
| 1115 | request->clear(true); |
| 1116 | } |
| 1117 | } |
| 1118 |
| 1119 | saveConfig(); |
| 1120 |
| 1121 | if (datacenter->getDatacenterId() == currentDatacenterId && currentUserId) { |
| 1122 | if (connection->getConnectionType() == ConnectionTypePush) { |
| 1123 | registerForInternalPushUpdates(); |
| 1124 | } else if (connection->getConnectionType() == ConnectionTypeGeneric) { |
| 1125 | if (delegate != nullptr) { |
| 1126 | delegate->onSessionCreated(instanceNum); |
| 1127 | } |
| 1128 | } |
| 1129 | } |
| 1130 | connection->addProcessedSession(response->unique_id); |
| 1131 | } |
| 1132 | } else if (typeInfo == typeid(TL_msg_container)) { |
| 1133 | auto response = (TL_msg_container *) message; |
| 1134 | size_t count = response->messages.size(); |
| 1135 | if (LOGS_ENABLED) DEBUG_D("received container with %d items", (int32_t) count); |
| 1136 | for (uint32_t a = 0; a < count; a++) { |
| 1137 | TL_message *innerMessage = response->messages[a].get(); |
| 1138 | int64_t innerMessageId = innerMessage->msg_id; |
| 1139 | if (innerMessage->seqno % 2 != 0) { |
| 1140 | connection->addMessageToConfirm(innerMessageId); |
| 1141 | } |
| 1142 | int32_t processedStatus = connection->isMessageIdProcessed(innerMessageId); |
| 1143 | if (processedStatus == 2) { |
| 1144 | if (innerMessage->unparsedBody != nullptr) { |
| 1145 | connection->recreateSession(); |
| 1146 | connection->reconnect(); |
| 1147 | return; |
| 1148 | } |
| 1149 | processedStatus = 0; |
| 1150 | } |
| 1151 | if (processedStatus) { |
| 1152 | if (LOGS_ENABLED) DEBUG_D("inner message %d id 0x%" PRIx64 " already processed", a, innerMessageId); |
| 1153 | continue; |
| 1154 | } |
| 1155 | if (innerMessage->unparsedBody != nullptr) { |
| 1156 | if (LOGS_ENABLED) DEBUG_D("inner message %d id 0x%" PRIx64 " is unparsed", a, innerMessageId); |
| 1157 | if (delegate != nullptr) { |
| 1158 | delegate->onUnparsedMessageReceived(innerMessageId, innerMessage->unparsedBody.get(), connection->getConnectionType(), instanceNum); |
| 1159 | } |
| 1160 | } else { |
| 1161 | if (LOGS_ENABLED) DEBUG_D("inner message %d id 0x%" PRIx64 " process", a, innerMessageId); |
| 1162 | processServerResponse(innerMessage->body.get(), 0, innerMessage->seqno, messageSalt, connection, innerMessageId, messageId); |
| 1163 | } |
| 1164 | connection->addProcessedMessageId(innerMessageId); |
| 1165 | } |
| 1166 | } else if (typeInfo == typeid(TL_pong)) { |
| 1167 | if (connection->getConnectionType() == ConnectionTypePush) { |
| 1168 | if (!registeredForInternalPush) { |
| 1169 | registerForInternalPushUpdates(); |
| 1170 | } |
| 1171 | int32_t diff = getCurrentTimeMonotonicMillis() - sendingPushPingTime; |
| 1172 | currentPingTimeLive = (diff + currentPingTimeLive) / 2; |
| 1173 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received push ping", connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType()); |
| 1174 | sendingPushPing = false; |
| 1175 | } else { |
| 1176 | auto response = (TL_pong *) message; |
| 1177 | if (response->ping_id >= 2000000) { |
| 1178 | for (auto iter = proxyActiveChecks.begin(); iter != proxyActiveChecks.end(); iter++) { |
| 1179 | ProxyCheckInfo *proxyCheckInfo = iter->get(); |
| 1180 | if (proxyCheckInfo->pingId == response->ping_id) { |
| 1181 | for (auto iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) { |
| 1182 | Request *request = iter2->get(); |
| 1183 | if (request->requestToken == proxyCheckInfo->requestToken) { |
| 1184 | int64_t ping = llabs(getCurrentTimeMonotonicMillis() - request->startTimeMillis); |
| 1185 | if (LOGS_ENABLED) DEBUG_D("got ping response for request %p, %" PRId64, request->rawRequest, ping); |
| 1186 | request->completed = true; |
| 1187 | proxyCheckInfo->onRequestTime(ping); |
| 1188 | DEBUG_D("3) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 1189 | runningRequests.erase(iter2); |
| 1190 | break; |
| 1191 | } |
| 1192 | } |
| 1193 | proxyActiveChecks.erase(iter); |
| 1194 |
| 1195 | if (!proxyCheckQueue.empty()) { |
| 1196 | proxyCheckInfo = proxyCheckQueue[0].release(); |
| 1197 | proxyCheckQueue.erase(proxyCheckQueue.begin()); |
| 1198 | scheduleCheckProxyInternal(proxyCheckInfo); |
| 1199 | } |
| 1200 | break; |
| 1201 | } |
| 1202 | } |
| 1203 | } else if (response->ping_id == lastPingId) { |
| 1204 | int32_t diff = (int32_t) (getCurrentTimeMonotonicMillis() / 1000) - pingTime; |
| 1205 | currentPingTimeLive = ((getCurrentTimeMonotonicMillis() - pingTimeMs) + currentPingTimeLive) / 2; |
| 1206 | if (abs(diff) < 10) { |
| 1207 | currentPingTime = (diff + currentPingTime) / 2; |
| 1208 | if (messageId != 0) { |
| 1209 | timeDifference = (int32_t) ((timeMessage - getCurrentTimeMillis()) / 1000 - currentPingTime / 2); |
| 1210 | } |
| 1211 | } |
| 1212 | sendingPing = false; |
| 1213 | } |
| 1214 | } |
| 1215 | } else if (typeInfo == typeid(TL_future_salts)) { |
| 1216 | auto response = (TL_future_salts *) message; |
| 1217 | int64_t requestMid = response->req_msg_id; |
| 1218 | for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { |
| 1219 | Request *request = iter->get(); |
| 1220 | if (request->respondsToMessageId(requestMid)) { |
| 1221 | int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId; |
| 1222 | request->onComplete(response, nullptr, connection->currentNetworkType, timeMessage, requestMid, dcId); |
| 1223 | request->completed = true; |
| 1224 | DEBUG_D("4) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 1225 | runningRequests.erase(iter); |
| 1226 | break; |
| 1227 | } |
| 1228 | } |
| 1229 | } else if (dynamic_cast<DestroySessionRes *>(message)) { |
| 1230 | auto response = (DestroySessionRes *) message; |
| 1231 | if (LOGS_ENABLED) DEBUG_D("destroyed session 0x%" PRIx64 " (%s)", (uint64_t) response->session_id, typeInfo == typeid(TL_destroy_session_ok) ? "ok" : "not found"); |
| 1232 | } else if (typeInfo == typeid(TL_rpc_result)) { |
| 1233 | auto response = (TL_rpc_result *) message; |
| 1234 | int64_t resultMid = response->req_msg_id; |
| 1235 | if (resultMid == lastInvokeAfterMessageId) { |
| 1236 | lastInvokeAfterMessageId = 0; |
| 1237 | } |
| 1238 |
| 1239 | bool hasResult = response->result != nullptr; |
| 1240 | bool ignoreResult = false; |
| 1241 | if (hasResult) { |
| 1242 | TLObject *object = response->result.get(); |
| 1243 | if (LOGS_ENABLED) DEBUG_D("message_id %lld connection(%p, account%u, dc%u, type %d) received rpc_result with %s", messageId, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name()); |
| 1244 | } |
| 1245 | RpcError *error = hasResult ? dynamic_cast<RpcError *>(response->result.get()) : nullptr; |
| 1246 | if (error != nullptr) { |
| 1247 | if (LOGS_ENABLED) DEBUG_E("message_id %lld req_msg_id %lld connection(%p, account%u, dc%u, type %d) rpc error %d: %s", messageId, resultMid, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), error->error_code, error->error_message.c_str()); |
| 1248 | if (error->error_code == 303) { |
| 1249 | uint32_t migrateToDatacenterId = DEFAULT_DATACENTER_ID; |
| 1250 |
| 1251 | static std::vector<std::string> migrateErrors = {"NETWORK_MIGRATE_", "PHONE_MIGRATE_", "USER_MIGRATE_"}; |
| 1252 |
| 1253 | size_t count = migrateErrors.size(); |
| 1254 | for (uint32_t a = 0; a < count; a++) { |
| 1255 | std::string &possibleError = migrateErrors[a]; |
| 1256 | if (error->error_message.find(possibleError) != std::string::npos) { |
| 1257 | std::string num = error->error_message.substr(possibleError.size(), error->error_message.size() - possibleError.size()); |
| 1258 | auto val = (uint32_t) atoi(num.c_str()); |
| 1259 | migrateToDatacenterId = val; |
| 1260 | } |
| 1261 | } |
| 1262 |
| 1263 | if (migrateToDatacenterId != DEFAULT_DATACENTER_ID) { |
| 1264 | ignoreResult = true; |
| 1265 | moveToDatacenter(migrateToDatacenterId); |
| 1266 | } |
| 1267 | } |
| 1268 | } |
| 1269 |
| 1270 | uint32_t retryRequestsFromDatacenter = DEFAULT_DATACENTER_ID - 1; |
| 1271 | uint32_t retryRequestsConnections = 0; |
| 1272 |
| 1273 | if (!ignoreResult) { |
| 1274 | for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { |
| 1275 | Request *request = iter->get(); |
| 1276 | if (!request->respondsToMessageId(resultMid)) { |
| 1277 | continue; |
| 1278 | } |
| 1279 | if (LOGS_ENABLED) DEBUG_D("got response for request %p, req_id = %d - %s (messageId = 0x%" PRIx64 ")", request->rawRequest, request->requestToken, typeid(*request->rawRequest).name(), request->messageId); |
| 1280 | bool discardResponse = false; |
| 1281 | bool isError = false; |
| 1282 | bool allowInitConnection = true; |
| 1283 |
| 1284 | if (request->onCompleteRequestCallback != nullptr) { |
| 1285 | TL_error *implicitError = nullptr; |
| 1286 | NativeByteBuffer *unpacked_data = nullptr; |
| 1287 | TLObject *result = response->result.get(); |
| 1288 | if (typeid(*result) == typeid(TL_gzip_packed)) { |
| 1289 | auto innerResponse = (TL_gzip_packed *) result; |
| 1290 | unpacked_data = decompressGZip(innerResponse->packed_data.get()); |
| 1291 | TLObject *object = TLdeserialize(request->rawRequest, unpacked_data->limit(), unpacked_data); |
| 1292 | if (object != nullptr) { |
| 1293 | response->result = std::unique_ptr<TLObject>(object); |
| 1294 | } else { |
| 1295 | response->result = std::unique_ptr<TLObject>(nullptr); |
| 1296 | } |
| 1297 | } |
| 1298 |
| 1299 | hasResult = response->result != nullptr; |
| 1300 | error = hasResult ? dynamic_cast<RpcError *>(response->result.get()) : nullptr; |
| 1301 | TL_error *error2 = hasResult ? dynamic_cast<TL_error *>(response->result.get()) : nullptr; |
| 1302 | if (error != nullptr) { |
| 1303 | allowInitConnection = false; |
| 1304 | static std::string authRestart = "AUTH_RESTART"; |
| 1305 | static std::string authKeyPermEmpty = "AUTH_KEY_PERM_EMPTY"; |
| 1306 | static std::string workerBusy = "WORKER_BUSY_TOO_LONG_RETRY"; |
| 1307 | static std::string integrityCheckClassic = "INTEGRITY_CHECK_CLASSIC_"; |
| 1308 | static std::string captchaCheck = "RECAPTCHA_CHECK_"; |
| 1309 | bool processEvenFailed = error->error_code == 500 && error->error_message.find(authRestart) != std::string::npos; |
| 1310 | bool isWorkerBusy = error->error_code == 500 && error->error_message.find(workerBusy) != std::string::npos; |
| 1311 | if (LOGS_ENABLED) DEBUG_E("request %p rpc error %d: %s", request, error->error_code, error->error_message.c_str()); |
| 1312 |
| 1313 | if (error->error_code == 401 && error->error_message.find(authKeyPermEmpty) != std::string::npos) { |
| 1314 | discardResponse = true; |
| 1315 | request->minStartTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000 + 1); |
| 1316 | request->startTime = 0; |
| 1317 |
| 1318 | if (!datacenter->isHandshaking(connection->isMediaConnection)) { |
| 1319 | datacenter->clearAuthKey(connection->isMediaConnection ? HandshakeTypeMediaTemp : HandshakeTypeTemp); |
| 1320 | saveConfig(); |
| 1321 | datacenter->beginHandshake(connection->isMediaConnection ? HandshakeTypeMediaTemp : HandshakeTypeTemp, false); |
| 1322 | } |
| 1323 | } else if (error->error_code == 403 && error->error_message.find(integrityCheckClassic) != std::string::npos) { |
| 1324 | discardResponse = true; |
| 1325 | std::string err = error->error_message; |
| 1326 | int index = err.find('_', integrityCheckClassic.size()); |
| 1327 | std::string project = err.substr(integrityCheckClassic.size(), index - integrityCheckClassic.size()); |
| 1328 | std::string nonce = err.substr(integrityCheckClassic.size() + project.size() + 1, err.size() - (integrityCheckClassic.size() + project.size() + 1)); |
| 1329 | request->awaitingIntegrityCheck = true; |
| 1330 | request->awaitingCaptchaCheck = false; |
| 1331 | request->startTime = 0; |
| 1332 | request->startTimeMillis = 0; |
| 1333 | if (delegate != nullptr) { |
| 1334 | delegate->onIntegrityCheckClassic(instanceNum, request->requestToken, project, nonce); |
| 1335 | } |
| 1336 | } else if (error->error_code == 403 && error->error_message.find(captchaCheck) != std::string::npos) { |
| 1337 | discardResponse = true; |
| 1338 | std::string err = error->error_message; |
| 1339 | int index = err.find('_', captchaCheck.size()); |
| 1340 | std::string action = err.substr(captchaCheck.size(), index - captchaCheck.size()); |
| 1341 | std::string key_id = err.substr(captchaCheck.size() + action.size() + 2, err.size() - (captchaCheck.size() + action.size() + 1)); |
| 1342 | request->awaitingIntegrityCheck = false; |
| 1343 | request->awaitingCaptchaCheck = true; |
| 1344 | request->startTime = 0; |
| 1345 | request->startTimeMillis = 0; |
| 1346 | if (delegate != nullptr) { |
| 1347 | delegate->onCaptchaCheck(instanceNum, request->requestToken, action, key_id); |
| 1348 | } |
| 1349 | } else { |
| 1350 | bool failServerErrors = (request->requestFlags & RequestFlagFailOnServerErrors) == 0 || processEvenFailed; |
| 1351 | bool exceptFloodWait = (request->requestFlags & RequestFlagFailOnServerErrorsExceptFloodWait) != 0; |
| 1352 | if (failServerErrors && (error->error_code == 500 || error->error_code < 0)) { |
| 1353 | static std::string waitFailed = "MSG_WAIT_FAILED"; |
| 1354 | static std::string waitTimeout = "MSG_WAIT_TIMEOUT"; |
| 1355 | if (error->error_message.find(waitFailed) != std::string::npos) { |
| 1356 | request->startTime = 0; |
| 1357 | request->startTimeMillis = 0; |
| 1358 | request->requestFlags |= RequestFlagResendAfter; |
| 1359 | } else { |
| 1360 | if (isWorkerBusy) { |
| 1361 | request->minStartTime = 0; |
| 1362 | } else { |
| 1363 | request->minStartTime = request->startTime + (request->serverFailureCount > 10 ? 10 : request->serverFailureCount); |
| 1364 | } |
| 1365 | request->serverFailureCount++; |
| 1366 | } |
| 1367 | discardResponse = true; |
| 1368 | } else if (failServerErrors && error->error_code == -504) { |
| 1369 | discardResponse = (request->requestFlags & RequestFlagIgnoreFloodWait) == 0; |
| 1370 | request->failedByFloodWait = 2; |
| 1371 | request->startTime = 0; |
| 1372 | request->startTimeMillis = 0; |
| 1373 | request->minStartTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000 + 2); |
| 1374 | } else if ( |
| 1375 | (failServerErrors || exceptFloodWait) && |
| 1376 | error->error_code == 420 && (request->requestFlags & RequestFlagIgnoreFloodWait) == 0 && |
| 1377 | error->error_message.find("STORY_SEND_FLOOD") == std::string::npos |
| 1378 | ) { |
| 1379 | int32_t waitTime = 2; |
| 1380 | static std::string floodWait = "FLOOD_WAIT_"; |
| 1381 | static std::string premiumFloodWait = "FLOOD_PREMIUM_WAIT_"; |
| 1382 | static std::string slowmodeWait = "SLOWMODE_WAIT_"; |
| 1383 | bool isPremiumFloodWait = false; |
| 1384 | discardResponse = true; |
| 1385 | if (error->error_message.find(premiumFloodWait) != std::string::npos) { |
| 1386 | isPremiumFloodWait = true; |
| 1387 | std::string num = error->error_message.substr(premiumFloodWait.size(), error->error_message.size() - premiumFloodWait.size()); |
| 1388 | waitTime = atoi(num.c_str()); |
| 1389 | if (waitTime <= 0) { |
| 1390 | waitTime = 2; |
| 1391 | } |
| 1392 | } else if (error->error_message.find(floodWait) != std::string::npos) { |
| 1393 | std::string num = error->error_message.substr(floodWait.size(), error->error_message.size() - floodWait.size()); |
| 1394 | waitTime = atoi(num.c_str()); |
| 1395 | if (waitTime <= 0) { |
| 1396 | waitTime = 2; |
| 1397 | } |
| 1398 | } else if (error->error_message.find(slowmodeWait) != std::string::npos) { |
| 1399 | std::string num = error->error_message.substr(slowmodeWait.size(), error->error_message.size() - slowmodeWait.size()); |
| 1400 | waitTime = atoi(num.c_str()); |
| 1401 | if (waitTime <= 0) { |
| 1402 | waitTime = 2; |
| 1403 | } |
| 1404 | discardResponse = false; |
| 1405 | } |
| 1406 | request->premiumFloodWait = isPremiumFloodWait; |
| 1407 | request->failedByFloodWait = waitTime; |
| 1408 | request->startTime = 0; |
| 1409 | request->startTimeMillis = 0; |
| 1410 | request->minStartTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000 + waitTime); |
| 1411 | if (isPremiumFloodWait && delegate != nullptr) { |
| 1412 | delegate->onPremiumFloodWait(instanceNum, request->requestToken, (request->connectionType & ConnectionTypeUpload) != 0); |
| 1413 | } |
| 1414 | } else if (failServerErrors && error->error_code == 400) { |
| 1415 | static std::string waitFailed = "MSG_WAIT_FAILED"; |
| 1416 | static std::string bindFailed = "ENCRYPTED_MESSAGE_INVALID"; |
| 1417 | static std::string waitTimeout = "MSG_WAIT_TIMEOUT"; |
| 1418 | if (error->error_message.find(waitTimeout) != std::string::npos || error->error_message.find(waitFailed) != std::string::npos) { |
| 1419 | discardResponse = true; |
| 1420 | request->startTime = 0; |
| 1421 | request->startTimeMillis = 0; |
| 1422 | request->requestFlags |= RequestFlagResendAfter; |
| 1423 | } else if (error->error_message.find(bindFailed) != std::string::npos && typeid(*request->rawRequest) == typeid(TL_auth_bindTempAuthKey)) { |
| 1424 | int datacenterId; |
| 1425 | if (delegate != nullptr && getDatacenterWithId(DEFAULT_DATACENTER_ID) == datacenter) { |
| 1426 | delegate->onLogout(instanceNum); |
| 1427 | datacenterId = -1; |
| 1428 | } else { |
| 1429 | datacenterId = datacenter->getDatacenterId(); |
| 1430 | } |
| 1431 | cleanUp(true, datacenterId); |
| 1432 | } |
| 1433 | } |
| 1434 | } |
| 1435 | if (!discardResponse) { |
| 1436 | implicitError = new TL_error(); |
| 1437 | implicitError->code = error->error_code; |
| 1438 | implicitError->text = error->error_message; |
| 1439 | } |
| 1440 | } else if (error2 == nullptr) { |
| 1441 | if (request->rawRequest == nullptr || response->result == nullptr) { |
| 1442 | allowInitConnection = false; |
| 1443 | if (LOGS_ENABLED) DEBUG_E("rawRequest is null"); |
| 1444 | implicitError = new TL_error(); |
| 1445 | implicitError->code = -1000; |
| 1446 | implicitError->text = ""; |
| 1447 | } |
| 1448 |
| 1449 | if (hasResult) { |
| 1450 | // when receiving TL_rpc_answer_dropped_running, we want to still listen for a little for the response, as it may come |
| 1451 | TL_rpc_answer_dropped_running* droppedRunning = dynamic_cast<TL_rpc_answer_dropped_running*>(response->result.get()); |
| 1452 | if (droppedRunning != nullptr) { |
| 1453 | TL_rpc_drop_answer* dropAnswer = dynamic_cast<TL_rpc_drop_answer*>(request->rawRequest); |
| 1454 | if (dropAnswer != nullptr) { |
| 1455 | int64_t originalMessageId = dropAnswer->req_msg_id; |
| 1456 | Request* originalRequest = nullptr; |
| 1457 | for (auto iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) { |
| 1458 | Request *request2 = iter2->get(); |
| 1459 | if (request2->messageId == originalMessageId) { |
| 1460 | originalRequest = request2; |
| 1461 | break; |
| 1462 | } |
| 1463 | } |
| 1464 | if (originalRequest != nullptr && (originalRequest->requestFlags & RequestFlagListenAfterCancel) != 0) { |
| 1465 | if (LOGS_ENABLED) DEBUG_D("doNotClearOnDrop = true; msgid=0x%" PRIx64, originalMessageId); |
| 1466 | originalRequest->disableClearCallback = false; |
| 1467 | originalRequest->doNotClearOnDrop = true; |
| 1468 | originalRequest->clearAfter = (int32_t) (getCurrentTimeMonotonicMillis() / 1000) + 25; |
| 1469 | originalRequest->onRequestClearCallback = request->onRequestClearCallback; |
| 1470 | request->onRequestClearCallback = nullptr; |
| 1471 | } else { |
| 1472 | if (LOGS_ENABLED) DEBUG_D("not found request; msgid=0x%" PRIx64, originalMessageId); |
| 1473 | } |
| 1474 | } else { |
| 1475 | if (LOGS_ENABLED) DEBUG_D("not found dropAnswer; msgid=0x%" PRIx64, request->messageId); |
| 1476 | } |
| 1477 | } |
| 1478 | } |
| 1479 | } |
| 1480 |
| 1481 | if (!discardResponse) { |
| 1482 | int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId; |
| 1483 | if (implicitError != nullptr || error2 != nullptr) { |
| 1484 | isError = true; |
| 1485 | request->onComplete(nullptr, implicitError != nullptr ? implicitError : error2, connection->currentNetworkType, timeMessage, request->messageId, dcId); |
| 1486 | delete error2; |
| 1487 | } else { |
| 1488 | request->onComplete(response->result.get(), nullptr, connection->currentNetworkType, timeMessage, request->messageId, dcId); |
| 1489 | } |
| 1490 | } |
| 1491 |
| 1492 | if (implicitError != nullptr) { |
| 1493 | if (implicitError->code == 401) { |
| 1494 | allowInitConnection = false; |
| 1495 | isError = true; |
| 1496 | static std::string sessionPasswordNeeded = "SESSION_PASSWORD_NEEDED"; |
| 1497 |
| 1498 | if (implicitError->text.find(sessionPasswordNeeded) != std::string::npos) { |
| 1499 | //ignore this error |
| 1500 | } else if (datacenter->getDatacenterId() == currentDatacenterId || datacenter->getDatacenterId() == movingToDatacenterId) { |
| 1501 | if (request->connectionType & ConnectionTypeGeneric && currentUserId) { |
| 1502 | currentUserId = 0; |
| 1503 | currentUserPremium = false; |
| 1504 | if (delegate != nullptr) { |
| 1505 | delegate->onLogout(instanceNum); |
| 1506 | } |
| 1507 | cleanUp(false, -1); |
| 1508 | } |
| 1509 | } else { |
| 1510 | datacenter->authorized = false; |
| 1511 | saveConfig(); |
| 1512 | discardResponse = true; |
| 1513 | if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) { |
| 1514 | retryRequestsFromDatacenter = datacenter->getDatacenterId(); |
| 1515 | retryRequestsConnections = request->connectionType; |
| 1516 | } |
| 1517 | } |
| 1518 | } else if (currentUserId == 0 && implicitError->code == 406) { |
| 1519 | static std::string authKeyDuplicated = "AUTH_KEY_DUPLICATED"; |
| 1520 | if (implicitError->text.find(authKeyDuplicated) != std::string::npos) { |
| 1521 | cleanUp(true, datacenter->getDatacenterId()); |
| 1522 | } |
| 1523 | } |
| 1524 | } |
| 1525 |
| 1526 | if (unpacked_data != nullptr) { |
| 1527 | unpacked_data->reuse(); |
| 1528 | } |
| 1529 | delete implicitError; |
| 1530 | } |
| 1531 |
| 1532 | if (!discardResponse) { |
| 1533 | if (allowInitConnection && !isError) { |
| 1534 | bool save = false; |
| 1535 | if (request->isInitRequest && datacenter->lastInitVersion != currentVersion) { |
| 1536 | datacenter->lastInitVersion = currentVersion; |
| 1537 | save = true; |
| 1538 | } else if (request->isInitMediaRequest && datacenter->lastInitMediaVersion != currentVersion) { |
| 1539 | datacenter->lastInitMediaVersion = currentVersion; |
| 1540 | save = true; |
| 1541 | } |
| 1542 | if (save) { |
| 1543 | saveConfig(); |
| 1544 | if (LOGS_ENABLED) DEBUG_D("dc%d init connection completed", datacenter->getDatacenterId()); |
| 1545 | } |
| 1546 | } |
| 1547 | request->completed = true; |
| 1548 | removeRequestFromGuid(request->requestToken); |
| 1549 | if (LOGS_ENABLED) DEBUG_D("5) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 1550 | runningRequests.erase(iter); |
| 1551 | } else { |
| 1552 | request->messageId = 0; |
| 1553 | request->messageSeqNo = 0; |
| 1554 | request->connectionToken = 0; |
| 1555 | } |
| 1556 | break; |
| 1557 | } |
| 1558 | } |
| 1559 |
| 1560 | if (retryRequestsFromDatacenter != DEFAULT_DATACENTER_ID - 1) { |
| 1561 | processRequestQueue(retryRequestsConnections, retryRequestsFromDatacenter); |
| 1562 | } else { |
| 1563 | processRequestQueue(0, 0); |
| 1564 | } |
| 1565 | } else if (typeInfo == typeid(TL_msgs_ack)) { |
| 1566 |
| 1567 | } else if (typeInfo == typeid(TL_bad_msg_notification)) { |
| 1568 | auto result = (TL_bad_msg_notification *) message; |
| 1569 | if (LOGS_ENABLED) DEBUG_E("bad message notification %d for messageId 0x%" PRIx64 ", seqno %d", result->error_code, result->bad_msg_id, result->bad_msg_seqno); |
| 1570 | switch (result->error_code) { |
| 1571 | case 16: |
| 1572 | case 17: |
| 1573 | case 19: |
| 1574 | case 32: |
| 1575 | case 33: |
| 1576 | case 64: { |
| 1577 | int64_t realId = messageId != 0 ? messageId : containerMessageId; |
| 1578 | if (realId == 0) { |
| 1579 | realId = innerMsgId; |
| 1580 | } |
| 1581 |
| 1582 | if (realId != 0) { |
| 1583 | auto time = (int64_t) (messageId / 4294967296.0 * 1000); |
| 1584 | int64_t currentTime = getCurrentTimeMillis(); |
| 1585 | timeDifference = (int32_t) ((time - currentTime) / 1000 - currentPingTime / 2); |
| 1586 | } |
| 1587 |
| 1588 | datacenter->recreateSessions(HandshakeTypeAll); |
| 1589 | saveConfig(); |
| 1590 |
| 1591 | lastOutgoingMessageId = 0; |
| 1592 | clearRequestsForDatacenter(datacenter, HandshakeTypeAll); |
| 1593 | break; |
| 1594 | } |
| 1595 | case 20: { |
| 1596 | for (auto & runningRequest : runningRequests) { |
| 1597 | Request *request = runningRequest.get(); |
| 1598 | if (request->respondsToMessageId(result->bad_msg_id)) { |
| 1599 | if (request->completed) { |
| 1600 | break; |
| 1601 | } |
| 1602 | connection->addMessageToConfirm(result->bad_msg_id); |
| 1603 | request->clear(true); |
| 1604 | break; |
| 1605 | } |
| 1606 | } |
| 1607 | } |
| 1608 | default: |
| 1609 | break; |
| 1610 | } |
| 1611 | } else if (typeInfo == typeid(TL_bad_server_salt)) { |
| 1612 | bool media = Connection::isMediaConnectionType(connection->getConnectionType()); |
| 1613 | requestSaltsForDatacenter(datacenter, media, connection->getConnectionType() == ConnectionTypeTemp); |
| 1614 | if (messageId != 0) { |
| 1615 | auto time = (int64_t) (messageId / 4294967296.0 * 1000); |
| 1616 | int64_t currentTime = getCurrentTimeMillis(); |
| 1617 | timeDifference = (int32_t) ((time - currentTime) / 1000 - currentPingTime / 2); |
| 1618 | lastOutgoingMessageId = (messageId > lastOutgoingMessageId ? messageId : lastOutgoingMessageId); |
| 1619 | } |
| 1620 | if ((connection->getConnectionType() & ConnectionTypeDownload) == 0 || !datacenter->containsServerSalt(messageSalt, media)) { |
| 1621 | auto response = (TL_bad_server_salt *) message; |
| 1622 | int64_t resultMid = response->bad_msg_id; |
| 1623 | if (resultMid != 0) { |
| 1624 | bool beginHandshake = false; |
| 1625 | for (auto & runningRequest : runningRequests) { |
| 1626 | Request *request = runningRequest.get(); |
| 1627 | if (!beginHandshake && request->datacenterId == datacenter->getDatacenterId() && typeid(*request->rawRequest) == typeid(TL_auth_bindTempAuthKey) && request->respondsToMessageId(response->bad_msg_id)) { |
| 1628 | beginHandshake = true; |
| 1629 | } |
| 1630 | if ((request->connectionType & ConnectionTypeDownload) == 0) { |
| 1631 | continue; |
| 1632 | } |
| 1633 | Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId); |
| 1634 | if (requestDatacenter != nullptr && requestDatacenter->getDatacenterId() == datacenter->getDatacenterId()) { |
| 1635 | request->retryCount = 0; |
| 1636 | request->failedBySalt = true; |
| 1637 | } |
| 1638 | } |
| 1639 | if (beginHandshake) { |
| 1640 | datacenter->beginHandshake(HandshakeTypeCurrent, false); |
| 1641 | } |
| 1642 | } |
| 1643 |
| 1644 | datacenter->clearServerSalts(media); |
| 1645 |
| 1646 | std::unique_ptr<TL_future_salt> salt = std::make_unique<TL_future_salt>(); |
| 1647 | salt->valid_until = salt->valid_since = getCurrentTime(); |
| 1648 | salt->valid_until += 30 * 60; |
| 1649 | salt->salt = messageSalt; |
| 1650 | datacenter->addServerSalt(salt, media); |
| 1651 | saveConfig(); |
| 1652 |
| 1653 | if (datacenter->hasAuthKey(ConnectionTypeGeneric, 1)) { |
| 1654 | processRequestQueue(AllConnectionTypes, datacenter->getDatacenterId()); |
| 1655 | } |
| 1656 | } |
| 1657 | } else if (typeInfo == typeid(MsgsStateInfo)) { |
| 1658 | auto response = (MsgsStateInfo *) message; |
| 1659 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) got %s for messageId 0x%" PRIx64, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), typeInfo.name(), response->req_msg_id); |
| 1660 |
| 1661 | auto mIter = resendRequests.find(response->req_msg_id); |
| 1662 | if (mIter != resendRequests.end()) { |
| 1663 | if (LOGS_ENABLED) DEBUG_D("found resend for messageId 0x%" PRIx64, mIter->second); |
| 1664 | connection->addMessageToConfirm(mIter->second); |
| 1665 | for (auto & runningRequest : runningRequests) { |
| 1666 | Request *request = runningRequest.get(); |
| 1667 | if (request->respondsToMessageId(mIter->second)) { |
| 1668 | if (request->completed) { |
| 1669 | break; |
| 1670 | } |
| 1671 | request->clear(true); |
| 1672 | break; |
| 1673 | } |
| 1674 | } |
| 1675 | resendRequests.erase(mIter); |
| 1676 | } |
| 1677 | } else if (dynamic_cast<MsgDetailedInfo *>(message)) { |
| 1678 | auto response = (MsgDetailedInfo *) message; |
| 1679 |
| 1680 | bool requestResend = false; |
| 1681 | bool confirm = true; |
| 1682 |
| 1683 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) got %s for messageId 0x%" PRIx64, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), typeInfo.name(), response->msg_id); |
| 1684 | if (typeInfo == typeid(TL_msg_detailed_info)) { |
| 1685 | for (auto & runningRequest : runningRequests) { |
| 1686 | Request *request = runningRequest.get(); |
| 1687 | if (request->respondsToMessageId(response->msg_id)) { |
| 1688 | if (request->completed) { |
| 1689 | break; |
| 1690 | } |
| 1691 | if (LOGS_ENABLED) DEBUG_D("got TL_msg_detailed_info for rpc request %p - %s", request->rawRequest, typeid(*request->rawRequest).name()); |
| 1692 | auto currentTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000); |
| 1693 | if (!request->cancelled && (request->lastResendTime == 0 || abs(currentTime - request->lastResendTime) >= 60)) { |
| 1694 | request->lastResendTime = currentTime; |
| 1695 | requestResend = true; |
| 1696 | } else { |
| 1697 | confirm = false; |
| 1698 | } |
| 1699 | break; |
| 1700 | } |
| 1701 | } |
| 1702 | } else { |
| 1703 | if (!connection->isMessageIdProcessed(messageId)) { |
| 1704 | requestResend = true; |
| 1705 | } |
| 1706 | } |
| 1707 |
| 1708 | if (requestResend) { |
| 1709 | auto request = new TL_msg_resend_req(); |
| 1710 | request->msg_ids.push_back(response->answer_msg_id); |
| 1711 | auto networkMessage = new NetworkMessage(); |
| 1712 | networkMessage->message = std::make_unique<TL_message>(); |
| 1713 | networkMessage->message->msg_id = generateMessageId(); |
| 1714 | networkMessage->message->bytes = request->getObjectSize(); |
| 1715 | networkMessage->message->body = std::unique_ptr<TLObject>(request); |
| 1716 | networkMessage->message->seqno = connection->generateMessageSeqNo(false); |
| 1717 | resendRequests[networkMessage->message->msg_id] = response->answer_msg_id; |
| 1718 |
| 1719 | std::vector<std::unique_ptr<NetworkMessage>> array; |
| 1720 | array.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 1721 |
| 1722 | sendMessagesToConnection(array, connection, false); |
| 1723 | } else if (confirm) { |
| 1724 | connection->addMessageToConfirm(response->answer_msg_id); |
| 1725 | } |
| 1726 | } else if (typeInfo == typeid(TL_gzip_packed)) { |
| 1727 | auto response = (TL_gzip_packed *) message; |
| 1728 | NativeByteBuffer *data = decompressGZip(response->packed_data.get()); |
| 1729 | TLObject *object = TLdeserialize(getRequestWithMessageId(messageId), data->limit(), data); |
| 1730 | if (object != nullptr) { |
| 1731 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received object %s", connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name()); |
| 1732 | processServerResponse(object, messageId, messageSeqNo, messageSalt, connection, innerMsgId, containerMessageId); |
| 1733 | delete object; |
| 1734 | } else { |
| 1735 | if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received unparsed from gzip object on 0x%" PRIx64, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), messageId); |
| 1736 | if (delegate != nullptr) { |
| 1737 | delegate->onUnparsedMessageReceived(messageId, data, connection->getConnectionType(), instanceNum); |
| 1738 | } |
| 1739 | } |
| 1740 | data->reuse(); |
| 1741 | } else if (typeInfo == typeid(TL_updatesTooLong)) { |
| 1742 | if (connection->connectionType == ConnectionTypePush) { |
| 1743 | if (networkPaused) { |
| 1744 | lastPauseTime = getCurrentTimeMonotonicMillis(); |
| 1745 | if (LOGS_ENABLED) DEBUG_D("received internal push: wakeup network in background"); |
| 1746 | } else if (lastPauseTime != 0) { |
| 1747 | lastPauseTime = getCurrentTimeMonotonicMillis(); |
| 1748 | if (LOGS_ENABLED) DEBUG_D("received internal push: reset sleep timeout"); |
| 1749 | } else { |
| 1750 | if (LOGS_ENABLED) DEBUG_D("received internal push"); |
| 1751 | } |
| 1752 | if (delegate != nullptr) { |
| 1753 | delegate->onInternalPushReceived(instanceNum); |
| 1754 | } |
| 1755 | } else { |
| 1756 | if (delegate != nullptr) { |
| 1757 | NativeByteBuffer *data = BuffersStorage::getInstance().getFreeBuffer(message->getObjectSize()); |
| 1758 | message->serializeToStream(data); |
| 1759 | data->position(0); |
| 1760 | delegate->onUnparsedMessageReceived(messageId, data, connection->getConnectionType(), instanceNum); |
| 1761 | data->reuse(); |
| 1762 | } |
| 1763 | } |
| 1764 | } |
| 1765 | } |
| 1766 |
| 1767 | void ConnectionsManager::sendPing(Datacenter *datacenter, bool usePushConnection) { |
| 1768 | if (usePushConnection && (currentUserId == 0 || !usePushConnection)) { |
| 1769 | return; |
| 1770 | } |
| 1771 | Connection *connection = nullptr; |
| 1772 | if (usePushConnection) { |
| 1773 | connection = datacenter->getPushConnection(true); |
| 1774 | } else { |
| 1775 | connection = datacenter->getGenericConnection(true, 0); |
| 1776 | } |
| 1777 | if (connection == nullptr || (!usePushConnection && connection->getConnectionToken() == 0)) { |
| 1778 | return; |
| 1779 | } |
| 1780 | auto request = new TL_ping_delay_disconnect(); |
| 1781 | request->ping_id = ++lastPingId; |
| 1782 | if (usePushConnection) { |
| 1783 | request->disconnect_delay = 60 * 7; |
| 1784 | sendingPushPingTime = getCurrentTimeMonotonicMillis(); |
| 1785 | } else { |
| 1786 | request->disconnect_delay = testBackend ? 10 : 35; |
| 1787 | pingTimeMs = getCurrentTimeMonotonicMillis(); |
| 1788 | pingTime = (int32_t) (pingTimeMs / 1000); |
| 1789 | } |
| 1790 |
| 1791 | auto networkMessage = new NetworkMessage(); |
| 1792 | networkMessage->message = std::make_unique<TL_message>(); |
| 1793 | networkMessage->message->msg_id = generateMessageId(); |
| 1794 | networkMessage->message->bytes = request->getObjectSize(); |
| 1795 | networkMessage->message->body = std::unique_ptr<TLObject>(request); |
| 1796 | networkMessage->message->seqno = connection->generateMessageSeqNo(false); |
| 1797 |
| 1798 | std::vector<std::unique_ptr<NetworkMessage>> array; |
| 1799 | array.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 1800 | NativeByteBuffer *transportData = datacenter->createRequestsData(array, nullptr, connection, false); |
| 1801 | if (usePushConnection) { |
| 1802 | if (LOGS_ENABLED) DEBUG_D("dc%d send ping to push connection", datacenter->getDatacenterId()); |
| 1803 | sendingPushPing = true; |
| 1804 | } else { |
| 1805 | sendingPing = true; |
| 1806 | } |
| 1807 | connection->sendData(transportData, false, true); |
| 1808 | } |
| 1809 |
| 1810 | uint8_t ConnectionsManager::getIpStratagy() { |
| 1811 | return ipStrategy; |
| 1812 | } |
| 1813 |
| 1814 | void ConnectionsManager::initDatacenters() { |
| 1815 | Datacenter *datacenter; |
| 1816 | if (!testBackend) { |
| 1817 | if (datacenters.find(1) == datacenters.end()) { |
| 1818 | datacenter = new Datacenter(instanceNum, 1); |
| 1819 | datacenter->addAddressAndPort("149.154.175.50", 443, 0, ""); |
| 1820 | datacenter->addAddressAndPort("2001:b28:f23d:f001:0000:0000:0000:000a", 443, 1, ""); |
| 1821 | datacenters[1] = datacenter; |
| 1822 | } |
| 1823 |
| 1824 | if (datacenters.find(2) == datacenters.end()) { |
| 1825 | datacenter = new Datacenter(instanceNum, 2); |
| 1826 | datacenter->addAddressAndPort("149.154.167.51", 443, 0, ""); |
| 1827 | datacenter->addAddressAndPort("95.161.76.100", 443, 0, ""); |
| 1828 | datacenter->addAddressAndPort("2001:67c:4e8:f002:0000:0000:0000:000a", 443, 1, ""); |
| 1829 | datacenters[2] = datacenter; |
| 1830 | } |
| 1831 |
| 1832 | if (datacenters.find(3) == datacenters.end()) { |
| 1833 | datacenter = new Datacenter(instanceNum, 3); |
| 1834 | datacenter->addAddressAndPort("149.154.175.100", 443, 0, ""); |
| 1835 | datacenter->addAddressAndPort("2001:b28:f23d:f003:0000:0000:0000:000a", 443, 1, ""); |
| 1836 | datacenters[3] = datacenter; |
| 1837 | } |
| 1838 |
| 1839 | if (datacenters.find(4) == datacenters.end()) { |
| 1840 | datacenter = new Datacenter(instanceNum, 4); |
| 1841 | datacenter->addAddressAndPort("149.154.167.91", 443, 0, ""); |
| 1842 | datacenter->addAddressAndPort("2001:67c:4e8:f004:0000:0000:0000:000a", 443, 1, ""); |
| 1843 | datacenters[4] = datacenter; |
| 1844 | } |
| 1845 |
| 1846 | if (datacenters.find(5) == datacenters.end()) { |
| 1847 | datacenter = new Datacenter(instanceNum, 5); |
| 1848 | datacenter->addAddressAndPort("149.154.171.5", 443, 0, ""); |
| 1849 | datacenter->addAddressAndPort("2001:b28:f23f:f005:0000:0000:0000:000a", 443, 1, ""); |
| 1850 | datacenters[5] = datacenter; |
| 1851 | } |
| 1852 | } else { |
| 1853 | if (datacenters.find(1) == datacenters.end()) { |
| 1854 | datacenter = new Datacenter(instanceNum, 1); |
| 1855 | datacenter->addAddressAndPort("149.154.175.40", 443, 0, ""); |
| 1856 | datacenter->addAddressAndPort("2001:b28:f23d:f001:0000:0000:0000:000e", 443, 1, ""); |
| 1857 | datacenters[1] = datacenter; |
| 1858 | } |
| 1859 |
| 1860 | if (datacenters.find(2) == datacenters.end()) { |
| 1861 | datacenter = new Datacenter(instanceNum, 2); |
| 1862 | datacenter->addAddressAndPort("149.154.167.40", 443, 0, ""); |
| 1863 | datacenter->addAddressAndPort("2001:67c:4e8:f002:0000:0000:0000:000e", 443, 1, ""); |
| 1864 | datacenters[2] = datacenter; |
| 1865 | } |
| 1866 |
| 1867 | if (datacenters.find(3) == datacenters.end()) { |
| 1868 | datacenter = new Datacenter(instanceNum, 3); |
| 1869 | datacenter->addAddressAndPort("149.154.175.117", 443, 0, ""); |
| 1870 | datacenter->addAddressAndPort("2001:b28:f23d:f003:0000:0000:0000:000e", 443, 1, ""); |
| 1871 | datacenters[3] = datacenter; |
| 1872 | } |
| 1873 | } |
| 1874 | } |
| 1875 |
| 1876 | void ConnectionsManager::attachConnection(ConnectionSocket *connection) { |
| 1877 | if (std::find(activeConnections.begin(), activeConnections.end(), connection) != activeConnections.end()) { |
| 1878 | return; |
| 1879 | } |
| 1880 | activeConnections.push_back(connection); |
| 1881 | } |
| 1882 |
| 1883 | void ConnectionsManager::detachConnection(ConnectionSocket *connection) { |
| 1884 | auto iter = std::find(activeConnections.begin(), activeConnections.end(), connection); |
| 1885 | if (iter != activeConnections.end()) { |
| 1886 | activeConnections.erase(iter); |
| 1887 | } |
| 1888 | } |
| 1889 |
| 1890 | int32_t ConnectionsManager::sendRequestInternal(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate) { |
| 1891 | auto request = new Request(instanceNum, lastRequestToken++, connectionType, flags, datacenterId, onComplete, onQuickAck, nullptr, onClear); |
| 1892 | request->rawRequest = object; |
| 1893 | request->rpcRequest = wrapInLayer(object, getDatacenterWithId(datacenterId), request); |
| 1894 | auto cancelledIterator = tokensToBeCancelled.find(request->requestToken); |
| 1895 | if (cancelledIterator != tokensToBeCancelled.end()) { |
| 1896 | if (LOGS_ENABLED) DEBUG_D("(3) request is cancelled before sending, token %d", request->requestToken); |
| 1897 | tokensToBeCancelled.erase(cancelledIterator); |
| 1898 | delete request; |
| 1899 | return request->requestToken; |
| 1900 | } |
| 1901 | if (!currentUserId && !(flags & RequestFlagWithoutLogin)) { |
| 1902 | if (LOGS_ENABLED) DEBUG_D("can't do request without login %s, reschedule token %d", typeid(*object).name(), request->requestToken); |
| 1903 | waitingLoginRequests.push_back(std::unique_ptr<Request>(request)); |
| 1904 | } else { |
| 1905 | requestsQueue.push_back(std::unique_ptr<Request>(request)); |
| 1906 | if (immediate) { |
| 1907 | processRequestQueue(0, 0); |
| 1908 | } |
| 1909 | } |
| 1910 | return request->requestToken; |
| 1911 | } |
| 1912 |
| 1913 | int32_t ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate) { |
| 1914 | int32_t requestToken = lastRequestToken++; |
| 1915 | return sendRequest(object, onComplete, onQuickAck, onClear, flags, datacenterId, connectionType, immediate, requestToken); |
| 1916 | } |
| 1917 |
| 1918 | int32_t ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate, int32_t requestToken) { |
| 1919 | if (requestToken == 0) { |
| 1920 | requestToken = lastRequestToken++; |
| 1921 | } |
| 1922 | scheduleTask([&, requestToken, object, onComplete, onQuickAck, onClear, flags, datacenterId, connectionType, immediate] { |
| 1923 | auto request = new Request(instanceNum, requestToken, connectionType, flags, datacenterId, onComplete, onQuickAck, nullptr, onClear); |
| 1924 | request->rawRequest = object; |
| 1925 | request->rpcRequest = wrapInLayer(object, getDatacenterWithId(datacenterId), request); |
| 1926 | auto cancelledIterator = tokensToBeCancelled.find(request->requestToken); |
| 1927 | if (cancelledIterator != tokensToBeCancelled.end()) { |
| 1928 | if (LOGS_ENABLED) DEBUG_D("(1) request is cancelled before sending, token %d", requestToken); |
| 1929 | tokensToBeCancelled.erase(cancelledIterator); |
| 1930 | delete request; |
| 1931 | } |
| 1932 | if (!currentUserId && !(flags & RequestFlagWithoutLogin)) { |
| 1933 | if (LOGS_ENABLED) DEBUG_D("can't do request without login %s, reschedule token %d", typeid(*object).name(), requestToken); |
| 1934 | waitingLoginRequests.push_back(std::unique_ptr<Request>(request)); |
| 1935 | } else { |
| 1936 | requestsQueue.push_back(std::unique_ptr<Request>(request)); |
| 1937 | if (immediate) { |
| 1938 | processRequestQueue(0, 0); |
| 1939 | } |
| 1940 | } |
| 1941 | }); |
| 1942 | return requestToken; |
| 1943 | } |
| 1944 |
| 1945 | #ifdef ANDROID |
| 1946 | void ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onWriteToSocketFunc onWriteToSocket, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate, int32_t requestToken) { |
| 1947 | scheduleTask([&, requestToken, object, onComplete, onQuickAck, onWriteToSocket, onClear, flags, datacenterId, connectionType, immediate] { |
| 1948 | if (LOGS_ENABLED) DEBUG_D("send request %p - %s", object, typeid(*object).name()); |
| 1949 | auto request = new Request(instanceNum, requestToken, connectionType, flags, datacenterId, onComplete, onQuickAck, onWriteToSocket, onClear); |
| 1950 | request->rawRequest = object; |
| 1951 | request->rpcRequest = wrapInLayer(object, getDatacenterWithId(datacenterId), request); |
| 1952 | if (LOGS_ENABLED) DEBUG_D("send request wrapped %p - %s", request->rpcRequest.get(), typeid(*(request->rpcRequest.get())).name()); |
| 1953 | auto cancelledIterator = tokensToBeCancelled.find(request->requestToken); |
| 1954 | if (cancelledIterator != tokensToBeCancelled.end()) { |
| 1955 | if (LOGS_ENABLED) DEBUG_D("(2) request is cancelled before sending, token %d", requestToken); |
| 1956 | tokensToBeCancelled.erase(cancelledIterator); |
| 1957 | delete request; |
| 1958 | return; |
| 1959 | } |
| 1960 | if (!currentUserId && !(flags & RequestFlagWithoutLogin)) { |
| 1961 | if (LOGS_ENABLED) DEBUG_D("can't do request without login %s, reschedule token %d", typeid(*object).name(), request->requestToken); |
| 1962 | waitingLoginRequests.push_back(std::unique_ptr<Request>(request)); |
| 1963 | } else { |
| 1964 | requestsQueue.push_back(std::unique_ptr<Request>(request)); |
| 1965 | if (immediate) { |
| 1966 | processRequestQueue(0, 0); |
| 1967 | } |
| 1968 | } |
| 1969 | }); |
| 1970 | } |
| 1971 | #endif |
| 1972 |
| 1973 | void ConnectionsManager::cancelRequestsForGuid(int32_t guid) { |
| 1974 | scheduleTask([&, guid] { |
| 1975 | auto iter = requestsByGuids.find(guid); |
| 1976 | if (iter != requestsByGuids.end()) { |
| 1977 | std::vector<int32_t> &requests = iter->second; |
| 1978 | size_t count = requests.size(); |
| 1979 | for (uint32_t a = 0; a < count; a++) { |
| 1980 | cancelRequestInternal(requests[a], 0, true, false, nullptr); |
| 1981 | auto iter2 = guidsByRequests.find(requests[a]); |
| 1982 | if (iter2 != guidsByRequests.end()) { |
| 1983 | guidsByRequests.erase(iter2); |
| 1984 | } |
| 1985 | } |
| 1986 | requestsByGuids.erase(iter); |
| 1987 | } |
| 1988 | }); |
| 1989 | } |
| 1990 |
| 1991 | void ConnectionsManager::bindRequestToGuid(int32_t requestToken, int32_t guid) { |
| 1992 | scheduleTask([&, requestToken, guid] { |
| 1993 | auto iter = requestsByGuids.find(guid); |
| 1994 | if (iter != requestsByGuids.end()) { |
| 1995 | iter->second.push_back(requestToken); |
| 1996 | } else { |
| 1997 | std::vector<int32_t> array; |
| 1998 | array.push_back(requestToken); |
| 1999 | requestsByGuids[guid] = array; |
| 2000 | } |
| 2001 | guidsByRequests[requestToken] = guid; |
| 2002 | }); |
| 2003 | } |
| 2004 |
| 2005 | void ConnectionsManager::setUserPremium(bool premium) { |
| 2006 | scheduleTask([&, premium] { |
| 2007 | currentUserPremium = premium; |
| 2008 | }); |
| 2009 | } |
| 2010 |
| 2011 | void ConnectionsManager::setUserId(int64_t userId) { |
| 2012 | scheduleTask([&, userId] { |
| 2013 | int32_t oldUserId = currentUserId; |
| 2014 | currentUserId = userId; |
| 2015 | if (oldUserId == userId && userId != 0) { |
| 2016 | registerForInternalPushUpdates(); |
| 2017 | } |
| 2018 | if (currentUserId != userId && userId != 0) { |
| 2019 | updateDcSettings(0, false, false); |
| 2020 | } |
| 2021 | if (currentUserId != 0 && pushConnectionEnabled) { |
| 2022 | Datacenter *datacenter = getDatacenterWithId(currentDatacenterId); |
| 2023 | if (datacenter != nullptr) { |
| 2024 | datacenter->createPushConnection()->setSessionId(pushSessionId); |
| 2025 | sendPing(datacenter, true); |
| 2026 | } |
| 2027 | } |
| 2028 | if (LOGS_ENABLED) DEBUG_D("set user %lld", userId); |
| 2029 | if (currentUserId != 0 && !waitingLoginRequests.empty()) { |
| 2030 | for (auto iter = waitingLoginRequests.begin(); iter != waitingLoginRequests.end(); iter++) { |
| 2031 | Request *request = iter->get(); |
| 2032 | if (LOGS_ENABLED) DEBUG_D("run rescheduled request %d", request->requestToken); |
| 2033 | requestsQueue.push_back(std::move(*iter)); |
| 2034 | } |
| 2035 | processRequestQueue(0, 0); |
| 2036 | waitingLoginRequests.clear(); |
| 2037 | } |
| 2038 | }); |
| 2039 | } |
| 2040 |
| 2041 | void ConnectionsManager::switchBackend(bool restart) { |
| 2042 | scheduleTask([&, restart] { |
| 2043 | currentDatacenterId = 1; |
| 2044 | testBackend = !testBackend; |
| 2045 | if (!restart) { |
| 2046 | Handshake::cleanupServerKeys(); |
| 2047 | } |
| 2048 | datacenters.clear(); |
| 2049 | initDatacenters(); |
| 2050 | saveConfig(); |
| 2051 | if (restart) { |
| 2052 | exit(1); |
| 2053 | } |
| 2054 | }); |
| 2055 | } |
| 2056 |
| 2057 | void ConnectionsManager::removeRequestFromGuid(int32_t requestToken) { |
| 2058 | auto iter2 = guidsByRequests.find(requestToken); |
| 2059 | if (iter2 != guidsByRequests.end()) { |
| 2060 | auto iter = requestsByGuids.find(iter2->first); |
| 2061 | if (iter != requestsByGuids.end()) { |
| 2062 | auto iter3 = std::find(iter->second.begin(), iter->second.end(), iter->first); |
| 2063 | if (iter3 != iter->second.end()) { |
| 2064 | iter->second.erase(iter3); |
| 2065 | if (iter->second.empty()) { |
| 2066 | requestsByGuids.erase(iter); |
| 2067 | } |
| 2068 | } |
| 2069 | } |
| 2070 | guidsByRequests.erase(iter2); |
| 2071 | } |
| 2072 | } |
| 2073 |
| 2074 | bool ConnectionsManager::cancelRequestInternal(int32_t token, int64_t messageId, bool notifyServer, bool removeFromClass, onRequestCancelDoneFunc onCancelled) { |
| 2075 | if (!tokensToBeCancelled.empty() && (connectionState != ConnectionStateWaitingForNetwork || tokensToBeCancelled.size() > 5000)) { |
| 2076 | tokensToBeCancelled.clear(); |
| 2077 | } |
| 2078 |
| 2079 | for (auto iter = requestsQueue.begin(); iter != requestsQueue.end(); iter++) { |
| 2080 | Request *request = iter->get(); |
| 2081 | if ((token != 0 && request->requestToken == token) || (messageId != 0 && request->respondsToMessageId(messageId))) { |
| 2082 | request->cancelled = true; |
| 2083 | const char* type = request->rawRequest == nullptr ? "" : typeid(*request->rawRequest).name(); |
| 2084 | if (LOGS_ENABLED) DEBUG_D("cancelled queued rpc request %p - %s of messageId 0x%" PRIx64, request->rawRequest, type, request->messageId); |
| 2085 | requestsQueue.erase(iter); |
| 2086 | if (removeFromClass) { |
| 2087 | removeRequestFromGuid(token); |
| 2088 | } |
| 2089 | return true; |
| 2090 | } |
| 2091 | } |
| 2092 |
| 2093 | for (auto iter = waitingLoginRequests.begin(); iter != waitingLoginRequests.end(); iter++) { |
| 2094 | Request *request = iter->get(); |
| 2095 | if ((token != 0 && request->requestToken == token) || (messageId != 0 && request->respondsToMessageId(messageId))) { |
| 2096 | request->cancelled = true; |
| 2097 | const char* type = request->rawRequest == nullptr ? "" : typeid(*request->rawRequest).name(); |
| 2098 | if (LOGS_ENABLED) DEBUG_D("cancelled waiting login rpc request %p - %s", request->rawRequest, type); |
| 2099 | waitingLoginRequests.erase(iter); |
| 2100 | if (removeFromClass) { |
| 2101 | removeRequestFromGuid(token); |
| 2102 | } |
| 2103 | return true; |
| 2104 | } |
| 2105 | } |
| 2106 |
| 2107 | for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { |
| 2108 | Request *request = iter->get(); |
| 2109 | if (request == nullptr) continue; |
| 2110 | if ((token != 0 && request->requestToken == token) || (messageId != 0 && request->respondsToMessageId(messageId))) { |
| 2111 | request->cancelled = true; |
| 2112 | bool erase = true; |
| 2113 | if ((request->requestFlags & RequestFlagListenAfterCancel) != 0) { |
| 2114 | int32_t token = request->requestToken; |
| 2115 | auto oldOnCancelled = onCancelled; |
| 2116 | if (onCancelled != nullptr) { |
| 2117 | request->disableClearCallback = true; |
| 2118 | } |
| 2119 | onCancelled = [this, oldOnCancelled, token]() -> void { |
| 2120 | for (auto iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) { |
| 2121 | Request *request2 = iter2->get(); |
| 2122 | if (request2->requestToken == token && !request2->doNotClearOnDrop) { |
| 2123 | request2->disableClearCallback = true; |
| 2124 | if (LOGS_ENABLED) DEBUG_D("6) erase request %d 0x%" PRIx64, request2->requestToken, request2->messageId); |
| 2125 | runningRequests.erase(iter2); |
| 2126 | break; |
| 2127 | } |
| 2128 | } |
| 2129 | if (oldOnCancelled != nullptr) { |
| 2130 | oldOnCancelled(); |
| 2131 | } |
| 2132 | }; |
| 2133 | erase = false; |
| 2134 | } |
| 2135 | if (notifyServer) { |
| 2136 | auto dropAnswer = new TL_rpc_drop_answer(); |
| 2137 | dropAnswer->req_msg_id = request->messageId; |
| 2138 | if (onCancelled != nullptr) { |
| 2139 | sendRequest(dropAnswer, ([onCancelled](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) -> void { |
| 2140 | if (onCancelled != nullptr) { |
| 2141 | onCancelled(); |
| 2142 | } |
| 2143 | }), nullptr, ([onCancelled]() -> void { |
| 2144 | if (onCancelled != nullptr) { |
| 2145 | onCancelled(); |
| 2146 | } |
| 2147 | }), RequestFlagEnableUnauthorized | RequestFlagWithoutLogin | RequestFlagFailOnServerErrors | RequestFlagIsCancel, request->datacenterId, request->connectionType, true); |
| 2148 | } else { |
| 2149 | sendRequest(dropAnswer, nullptr, nullptr, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin | RequestFlagFailOnServerErrors | RequestFlagIsCancel, request->datacenterId, request->connectionType, true); |
| 2150 | } |
| 2151 | } else if (onCancelled != nullptr) { |
| 2152 | onCancelled(); |
| 2153 | } |
| 2154 | const char* type = request->rawRequest == nullptr ? "" : typeid(*request->rawRequest).name(); |
| 2155 | if (LOGS_ENABLED) DEBUG_D("cancelled running rpc request %p - %s, of messageId 0x%" PRIx64 " notify=%d", request->rawRequest, type, request->messageId, notifyServer); |
| 2156 | if (erase) { |
| 2157 | if (LOGS_ENABLED) DEBUG_D("7) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 2158 | runningRequests.erase(iter); |
| 2159 | } |
| 2160 | if (removeFromClass) { |
| 2161 | removeRequestFromGuid(token); |
| 2162 | } |
| 2163 | return true; |
| 2164 | } |
| 2165 | } |
| 2166 |
| 2167 | if (token != 0 && connectionState == ConnectionStateWaitingForNetwork) { |
| 2168 | if (LOGS_ENABLED) DEBUG_D("request is tried to be cancelled, but it does not even exist, token %d", token); |
| 2169 | tokensToBeCancelled.insert(token); |
| 2170 | } |
| 2171 |
| 2172 | return false; |
| 2173 | } |
| 2174 |
| 2175 | void ConnectionsManager::cancelRequest(int32_t token, bool notifyServer, onRequestCancelDoneFunc onCancelled) { |
| 2176 | if (token == 0) { |
| 2177 | return; |
| 2178 | } |
| 2179 | scheduleTask([&, token, notifyServer, onCancelled] { |
| 2180 | cancelRequestInternal(token, 0, notifyServer, true, onCancelled); |
| 2181 | }); |
| 2182 | } |
| 2183 |
| 2184 | void ConnectionsManager::failNotRunningRequest(int32_t token) { |
| 2185 | if (token == 0) { |
| 2186 | return; |
| 2187 | } |
| 2188 |
| 2189 | scheduleTask([&, token] { |
| 2190 | for (auto iter = requestsQueue.begin(); iter != requestsQueue.end(); iter++) { |
| 2191 | Request *request = iter->get(); |
| 2192 | if ((token != 0 && request->requestToken == token)) { |
| 2193 | auto error = new TL_error(); |
| 2194 | error->code = -2000; |
| 2195 | error->text = "CANCELLED_REQUEST"; |
| 2196 | int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId; |
| 2197 | request->onComplete(nullptr, error, 0, 0, request->messageId, dcId); |
| 2198 |
| 2199 | request->cancelled = true; |
| 2200 | if (LOGS_ENABLED) DEBUG_D("cancelled queued rpc request %p - %s", request->rawRequest, typeid(*request->rawRequest).name()); |
| 2201 | requestsQueue.erase(iter); |
| 2202 | removeRequestFromGuid(token); |
| 2203 | return true; |
| 2204 | } |
| 2205 | } |
| 2206 | }); |
| 2207 | } |
| 2208 |
| 2209 | void ConnectionsManager::receivedIntegrityCheckClassic(int32_t requestToken, std::string nonce, std::string token) { |
| 2210 | scheduleTask([&, requestToken, nonce, token] { |
| 2211 | for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { |
| 2212 | Request *request = iter->get(); |
| 2213 | if (requestToken != 0 && request->requestToken == requestToken) { |
| 2214 | auto invokeIntegrity = new invokeWithGooglePlayIntegrity(); |
| 2215 | invokeIntegrity->nonce = nonce; |
| 2216 | invokeIntegrity->token = token; |
| 2217 | invokeIntegrity->query = std::move(request->rpcRequest); |
| 2218 | request->rpcRequest = std::unique_ptr<invokeWithGooglePlayIntegrity>(invokeIntegrity); |
| 2219 | request->serializedLength = request->rpcRequest->getObjectSize(); |
| 2220 |
| 2221 | request->awaitingIntegrityCheck = false; |
| 2222 | request->requestFlags &=~ RequestFlagFailOnServerErrors; |
| 2223 |
| 2224 | if (LOGS_ENABLED) DEBUG_D("account%d: received integrity token, wrapping %s", instanceNum, token.c_str()); |
| 2225 |
| 2226 | processRequestQueue(request->connectionType, request->datacenterId); |
| 2227 |
| 2228 | return; |
| 2229 | } |
| 2230 | } |
| 2231 |
| 2232 | if (LOGS_ENABLED) DEBUG_E("account%d: received integrity token but no request %d found", instanceNum, requestToken); |
| 2233 | }); |
| 2234 | } |
| 2235 |
| 2236 | void ConnectionsManager::receivedCaptchaResult(int32_t requestTokensCount, int32_t* requestTokens, std::string token) { |
| 2237 | scheduleTask([&, requestTokensCount, requestTokens, token] { |
| 2238 | for (int i = 0; i < requestTokensCount; ++i) { |
| 2239 | auto requestToken = requestTokens[i]; |
| 2240 | for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { |
| 2241 | Request *request = iter->get(); |
| 2242 | if (requestToken != 0 && request->requestToken == requestToken) { |
| 2243 | auto invoke = new invokeWithReCaptcha(); |
| 2244 | invoke->token = token; |
| 2245 | invoke->query = std::move(request->rpcRequest); |
| 2246 | request->rpcRequest = std::unique_ptr<invokeWithReCaptcha>(invoke); |
| 2247 | request->serializedLength = request->rpcRequest->getObjectSize(); |
| 2248 |
| 2249 | request->awaitingCaptchaCheck = false; |
| 2250 | request->requestFlags &=~ RequestFlagFailOnServerErrors; |
| 2251 |
| 2252 | if (LOGS_ENABLED) DEBUG_D("account%d: received captcha result token, wrapping %s", instanceNum, token.c_str()); |
| 2253 |
| 2254 | processRequestQueue(request->connectionType, request->datacenterId); |
| 2255 |
| 2256 | return; |
| 2257 | } |
| 2258 | } |
| 2259 |
| 2260 | if (LOGS_ENABLED) DEBUG_E("account%d: received captcha result token but no request %d found", instanceNum, requestToken); |
| 2261 | } |
| 2262 |
| 2263 | delete[] requestTokens; |
| 2264 | }); |
| 2265 | } |
| 2266 |
| 2267 | void ConnectionsManager::onDatacenterHandshakeComplete(Datacenter *datacenter, HandshakeType type, int32_t timeDiff) { |
| 2268 | saveConfig(); |
| 2269 | uint32_t datacenterId = datacenter->getDatacenterId(); |
| 2270 | if (datacenterId == currentDatacenterId || datacenterId == movingToDatacenterId || updatingDcSettingsWorkaround || updatingDcSettings) { |
| 2271 | timeDifference = timeDiff; |
| 2272 | datacenter->recreateSessions(type); |
| 2273 | clearRequestsForDatacenter(datacenter, type); |
| 2274 | } |
| 2275 | processRequestQueue(AllConnectionTypes, datacenterId); |
| 2276 | if (type == HandshakeTypeTemp && !proxyCheckQueue.empty()) { |
| 2277 | ProxyCheckInfo *proxyCheckInfo = proxyCheckQueue[0].release(); |
| 2278 | proxyCheckQueue.erase(proxyCheckQueue.begin()); |
| 2279 | scheduleCheckProxyInternal(proxyCheckInfo); |
| 2280 | } |
| 2281 | } |
| 2282 |
| 2283 | void ConnectionsManager::onDatacenterExportAuthorizationComplete(Datacenter *datacenter) { |
| 2284 | saveConfig(); |
| 2285 | scheduleTask([&, datacenter] { |
| 2286 | processRequestQueue(AllConnectionTypes, datacenter->getDatacenterId()); |
| 2287 | }); |
| 2288 | } |
| 2289 |
| 2290 | void ConnectionsManager::sendMessagesToConnection(std::vector<std::unique_ptr<NetworkMessage>> &messages, Connection *connection, bool reportAck) { |
| 2291 | if (messages.empty() || connection == nullptr) { |
| 2292 | return; |
| 2293 | } |
| 2294 |
| 2295 | std::vector<std::unique_ptr<NetworkMessage>> currentMessages; |
| 2296 | Datacenter *datacenter = connection->getDatacenter(); |
| 2297 |
| 2298 | uint32_t currentSize = 0; |
| 2299 | size_t count = messages.size(); |
| 2300 | for (uint32_t a = 0; a < count; a++) { |
| 2301 | NetworkMessage *networkMessage = messages[a].get(); |
| 2302 | currentMessages.push_back(std::move(messages[a])); |
| 2303 | currentSize += networkMessage->message->bytes; |
| 2304 |
| 2305 | if (currentSize >= 3 * 1024 || a == count - 1) { |
| 2306 | int32_t quickAckId = 0; |
| 2307 | NativeByteBuffer *transportData = datacenter->createRequestsData(currentMessages, reportAck ? &quickAckId : nullptr, connection, false); |
| 2308 |
| 2309 | if (transportData != nullptr) { |
| 2310 | if (reportAck && quickAckId != 0) { |
| 2311 | std::vector<int32_t> requestIds; |
| 2312 |
| 2313 | size_t count2 = currentMessages.size(); |
| 2314 | for (uint32_t b = 0; b < count2; b++) { |
| 2315 | NetworkMessage *message = currentMessages[b].get(); |
| 2316 | if (message->requestId != 0) { |
| 2317 | requestIds.push_back(message->requestId); |
| 2318 | } |
| 2319 | } |
| 2320 |
| 2321 | if (!requestIds.empty()) { |
| 2322 | auto iter = quickAckIdToRequestIds.find(quickAckId); |
| 2323 | if (iter == quickAckIdToRequestIds.end()) { |
| 2324 | quickAckIdToRequestIds[quickAckId] = requestIds; |
| 2325 | } else { |
| 2326 | iter->second.insert(iter->second.end(), requestIds.begin(), requestIds.end()); |
| 2327 | } |
| 2328 | } |
| 2329 | } |
| 2330 |
| 2331 | connection->sendData(transportData, reportAck, true); |
| 2332 | } else { |
| 2333 | if (LOGS_ENABLED) DEBUG_E("connection(%p) connection data is empty", connection); |
| 2334 | } |
| 2335 |
| 2336 | currentSize = 0; |
| 2337 | currentMessages.clear(); |
| 2338 | } |
| 2339 | } |
| 2340 | } |
| 2341 |
| 2342 | void ConnectionsManager::sendMessagesToConnectionWithConfirmation(std::vector<std::unique_ptr<NetworkMessage>> &messages, Connection *connection, bool reportAck) { |
| 2343 | NetworkMessage *networkMessage = connection->generateConfirmationRequest(); |
| 2344 | if (networkMessage != nullptr) { |
| 2345 | messages.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 2346 | } |
| 2347 | sendMessagesToConnection(messages, connection, reportAck); |
| 2348 | } |
| 2349 |
| 2350 | void ConnectionsManager::requestSaltsForDatacenter(Datacenter *datacenter, bool media, bool useTempConnection) { |
| 2351 | uint32_t id = datacenter->getDatacenterId(); |
| 2352 | if (useTempConnection) { |
| 2353 | id |= 0x80000000; |
| 2354 | } |
| 2355 | if (media) { |
| 2356 | id |= 0x40000000; |
| 2357 | } |
| 2358 | if (std::find(requestingSaltsForDc.begin(), requestingSaltsForDc.end(), id) != requestingSaltsForDc.end()) { |
| 2359 | return; |
| 2360 | } |
| 2361 | ConnectionType connectionType; |
| 2362 | if (media) { |
| 2363 | connectionType = ConnectionTypeGenericMedia; |
| 2364 | } else if (useTempConnection) { |
| 2365 | connectionType = ConnectionTypeTemp; |
| 2366 | } else { |
| 2367 | connectionType = ConnectionTypeGeneric; |
| 2368 | } |
| 2369 | requestingSaltsForDc.push_back(id); |
| 2370 | auto request = new TL_get_future_salts(); |
| 2371 | request->num = 32; |
| 2372 | sendRequest(request, [&, datacenter, id, media](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) { |
| 2373 | auto iter = std::find(requestingSaltsForDc.begin(), requestingSaltsForDc.end(), id); |
| 2374 | if (iter != requestingSaltsForDc.end()) { |
| 2375 | requestingSaltsForDc.erase(iter); |
| 2376 | } |
| 2377 | if (response != nullptr) { |
| 2378 | datacenter->mergeServerSalts((TL_future_salts *) response, media); |
| 2379 | saveConfig(); |
| 2380 | } |
| 2381 | }, nullptr, nullptr, RequestFlagWithoutLogin | RequestFlagEnableUnauthorized | RequestFlagUseUnboundKey, datacenter->getDatacenterId(), connectionType, true); |
| 2382 | } |
| 2383 |
| 2384 | void ConnectionsManager::clearRequestsForDatacenter(Datacenter *datacenter, HandshakeType type) { |
| 2385 | if (datacenter == nullptr) return; |
| 2386 | for (auto & runningRequest : runningRequests) { |
| 2387 | Request *request = runningRequest.get(); |
| 2388 | Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId); |
| 2389 | if (requestDatacenter->getDatacenterId() != datacenter->getDatacenterId()) { |
| 2390 | continue; |
| 2391 | } |
| 2392 | if (type == HandshakeTypePerm || type == HandshakeTypeAll || (type == HandshakeTypeMediaTemp && request->isMediaRequest()) || (type == HandshakeTypeTemp && !request->isMediaRequest())) { |
| 2393 | request->clear(true); |
| 2394 | } |
| 2395 | } |
| 2396 | } |
| 2397 |
| 2398 | void ConnectionsManager::registerForInternalPushUpdates() { |
| 2399 | if (registeringForPush || !currentUserId) { |
| 2400 | return; |
| 2401 | } |
| 2402 | registeredForInternalPush = false; |
| 2403 | registeringForPush = true; |
| 2404 | auto request = new TL_account_registerDevice(); |
| 2405 | request->token_type = 7; |
| 2406 | request->token = to_string_uint64((uint64_t) pushSessionId); |
| 2407 |
| 2408 | sendRequest(request, [&](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) { |
| 2409 | if (error == nullptr) { |
| 2410 | registeredForInternalPush = true; |
| 2411 | if (LOGS_ENABLED) DEBUG_D("registered for internal push"); |
| 2412 | } else { |
| 2413 | registeredForInternalPush = false; |
| 2414 | if (LOGS_ENABLED) DEBUG_E("unable to registering for internal push"); |
| 2415 | } |
| 2416 | saveConfig(); |
| 2417 | registeringForPush = false; |
| 2418 | }, nullptr, nullptr, 0, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true); |
| 2419 | } |
| 2420 |
| 2421 |
| 2422 | inline void addMessageToDatacenter(uint32_t datacenterId, NetworkMessage *networkMessage, std::map<uint32_t, std::vector<std::unique_ptr<NetworkMessage>>> &messagesToDatacenters) { |
| 2423 | auto iter = messagesToDatacenters.find(datacenterId); |
| 2424 | if (iter == messagesToDatacenters.end()) { |
| 2425 | std::vector<std::unique_ptr<NetworkMessage>> &array = messagesToDatacenters[datacenterId] = std::vector<std::unique_ptr<NetworkMessage>>(); |
| 2426 | array.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 2427 | } else { |
| 2428 | iter->second.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 2429 | } |
| 2430 | } |
| 2431 |
| 2432 | // since we no longer save 3 global refs per request, can we make request count limits higher? |
| 2433 | #define MAX_GENERAL_REQUESTS 60 * 8 |
| 2434 | #define MAX_DOWNLOAD_REQUESTS_CANCELS 24 * 2 |
| 2435 | #define MAX_DOWNLOAD_REQUESTS_PREMIUM 32 * 2 |
| 2436 | #define MAX_DOWNLOAD_REQUESTS 16 * 2 |
| 2437 | #define MAX_UPLOAD_REQUESTS 10 * 3 |
| 2438 |
| 2439 | void ConnectionsManager::processRequestQueue(uint32_t connectionTypes, uint32_t dc) { |
| 2440 | genericMessagesToDatacenters.clear(); |
| 2441 | genericMediaMessagesToDatacenters.clear(); |
| 2442 | tempMessagesToDatacenters.clear(); |
| 2443 | unknownDatacenterIds.clear(); |
| 2444 | neededDatacenters.clear(); |
| 2445 | unauthorizedDatacenters.clear(); |
| 2446 | downloadRunningRequestCount.clear(); |
| 2447 | downloadCancelRunningRequestCount.clear(); |
| 2448 |
| 2449 | int64_t currentTimeMillis = getCurrentTimeMonotonicMillis(); |
| 2450 | auto currentTime = (int32_t) (currentTimeMillis / 1000); |
| 2451 | uint32_t genericRunningRequestCount = 0; |
| 2452 | uint32_t uploadRunningRequestCount = 0; |
| 2453 | bool hasInvokeAfterMessage = false; |
| 2454 | bool hasInvokeWaitMessage = false; |
| 2455 |
| 2456 | for (auto iter = runningRequests.begin(); iter != runningRequests.end();) { |
| 2457 | Request *request = iter->get(); |
| 2458 | if (request->cancelled) { |
| 2459 | if (request->doNotClearOnDrop && currentTime > request->clearAfter) { |
| 2460 | DEBUG_D("16) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 2461 | iter = runningRequests.erase(iter); |
| 2462 | } else { |
| 2463 | iter++; |
| 2464 | } |
| 2465 | continue; |
| 2466 | } |
| 2467 | const std::type_info &typeInfo = typeid(*request->rawRequest); |
| 2468 |
| 2469 | uint32_t datacenterId = request->datacenterId; |
| 2470 | if (datacenterId == DEFAULT_DATACENTER_ID) { |
| 2471 | if (movingToDatacenterId != DEFAULT_DATACENTER_ID) { |
| 2472 | iter++; |
| 2473 | continue; |
| 2474 | } |
| 2475 | datacenterId = currentDatacenterId; |
| 2476 | } |
| 2477 | if ((request->requestFlags & RequestFlagResendAfter) != 0) { |
| 2478 | hasInvokeWaitMessage = true; |
| 2479 | if (hasInvokeAfterMessage) { |
| 2480 | iter++; |
| 2481 | continue; |
| 2482 | } |
| 2483 | } |
| 2484 | if (!hasInvokeAfterMessage && (request->requestFlags & RequestFlagInvokeAfter) != 0) { |
| 2485 | hasInvokeAfterMessage = true; |
| 2486 | } |
| 2487 |
| 2488 | switch (request->connectionType & 0x0000ffff) { |
| 2489 | case ConnectionTypeGeneric: |
| 2490 | if (!request->failedByFloodWait) { |
| 2491 | genericRunningRequestCount++; |
| 2492 | } |
| 2493 | break; |
| 2494 | case ConnectionTypeDownload: { |
| 2495 | auto map = request->isCancelRequest() ? downloadCancelRunningRequestCount : downloadRunningRequestCount; |
| 2496 | uint32_t currentCount; |
| 2497 | auto dcIter = map.find(datacenterId); |
| 2498 | if (dcIter != map.end()) { |
| 2499 | currentCount = dcIter->second; |
| 2500 | } else { |
| 2501 | currentCount = 0; |
| 2502 | } |
| 2503 | map[datacenterId] = currentCount + 1; |
| 2504 | break; |
| 2505 | } |
| 2506 | case ConnectionTypeUpload: |
| 2507 | uploadRunningRequestCount++; |
| 2508 | break; |
| 2509 | default: |
| 2510 | break; |
| 2511 | } |
| 2512 |
| 2513 | if (request->requestFlags & RequestFlagTryDifferentDc) { |
| 2514 | int32_t requestStartTime = request->startTime; |
| 2515 | int32_t timeout = 30; |
| 2516 | if (updatingDcSettings && dynamic_cast<TL_help_getConfig *>(request->rawRequest)) { |
| 2517 | requestStartTime = updatingDcStartTime; |
| 2518 | updatingDcStartTime = currentTime; |
| 2519 | timeout = 60; |
| 2520 | } |
| 2521 | if (request->startTime != 0 && abs(currentTime - requestStartTime) >= timeout) { |
| 2522 | if (LOGS_ENABLED) DEBUG_D("move %s to requestsQueue", typeid(*request->rawRequest).name()); |
| 2523 | requestsQueue.push_back(std::move(*iter)); |
| 2524 | DEBUG_D("10) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 2525 | iter = runningRequests.erase(iter); |
| 2526 | continue; |
| 2527 | } |
| 2528 | } |
| 2529 | int32_t canUseUnboundKey = 0; |
| 2530 | if ((request->requestFlags & RequestFlagUseUnboundKey) != 0) { |
| 2531 | canUseUnboundKey |= 1; |
| 2532 | } |
| 2533 |
| 2534 | Datacenter *requestDatacenter = getDatacenterWithId(datacenterId); |
| 2535 | if (requestDatacenter == nullptr) { |
| 2536 | if (std::find(unknownDatacenterIds.begin(), unknownDatacenterIds.end(), datacenterId) == unknownDatacenterIds.end()) { |
| 2537 | unknownDatacenterIds.push_back(datacenterId); |
| 2538 | } |
| 2539 | iter++; |
| 2540 | continue; |
| 2541 | } else { |
| 2542 | if (requestDatacenter->isCdnDatacenter) { |
| 2543 | request->requestFlags |= RequestFlagEnableUnauthorized; |
| 2544 | } |
| 2545 | if (request->needInitRequest(requestDatacenter, currentVersion) && !request->hasInitFlag() && request->rawRequest->isNeedLayer()) { |
| 2546 | if (LOGS_ENABLED) DEBUG_D("move %p - %s to requestsQueue because of initConnection", request->rawRequest, typeid(*request->rawRequest).name()); |
| 2547 | requestsQueue.push_back(std::move(*iter)); |
| 2548 | DEBUG_D("11) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 2549 | iter = runningRequests.erase(iter); |
| 2550 | continue; |
| 2551 | } |
| 2552 |
| 2553 | if (!requestDatacenter->hasAuthKey(request->connectionType, canUseUnboundKey)) { |
| 2554 | std::pair<Datacenter *, ConnectionType> pair = std::make_pair(requestDatacenter, request->connectionType); |
| 2555 | if (std::find(neededDatacenters.begin(), neededDatacenters.end(), pair) == neededDatacenters.end()) { |
| 2556 | neededDatacenters.push_back(pair); |
| 2557 | } |
| 2558 | iter++; |
| 2559 | continue; |
| 2560 | } else if (!(request->requestFlags & RequestFlagEnableUnauthorized) && !requestDatacenter->authorized && request->datacenterId != DEFAULT_DATACENTER_ID && request->datacenterId != currentDatacenterId) { |
| 2561 | if (std::find(unauthorizedDatacenters.begin(), unauthorizedDatacenters.end(), requestDatacenter) == unauthorizedDatacenters.end()) { |
| 2562 | unauthorizedDatacenters.push_back(requestDatacenter); |
| 2563 | } |
| 2564 | iter++; |
| 2565 | continue; |
| 2566 | } |
| 2567 | } |
| 2568 |
| 2569 | Connection *connection = requestDatacenter->getConnectionByType(request->connectionType, true, canUseUnboundKey); |
| 2570 | int32_t maxTimeout = request->connectionType & ConnectionTypeGeneric ? 8 : 30; |
| 2571 | if (!networkAvailable || connection->getConnectionToken() == 0) { |
| 2572 | iter++; |
| 2573 | continue; |
| 2574 | } |
| 2575 |
| 2576 | uint32_t requestConnectionType = request->connectionType & 0x0000ffff; |
| 2577 |
| 2578 | bool forceThisRequest = (connectionTypes & requestConnectionType) && requestDatacenter->getDatacenterId() == dc; |
| 2579 |
| 2580 | if (typeInfo == typeid(TL_get_future_salts)) { |
| 2581 | if (request->messageId != 0) { |
| 2582 | request->addRespondMessageId(request->messageId); |
| 2583 | } |
| 2584 | request->clear(false); |
| 2585 | forceThisRequest = false; |
| 2586 | } |
| 2587 |
| 2588 | bool failedButTimeToTryAgain = ( |
| 2589 | abs(currentTime - request->startTime) > maxTimeout && ( |
| 2590 | currentTime >= request->minStartTime || |
| 2591 | (request->failedByFloodWait != 0 && (request->minStartTime - currentTime) > request->failedByFloodWait) || |
| 2592 | (request->failedByFloodWait == 0 && abs(currentTime - request->minStartTime) >= 60) |
| 2593 | ) |
| 2594 | ); |
| 2595 |
| 2596 | if ((forceThisRequest || failedButTimeToTryAgain) && !request->awaitingIntegrityCheck && !request->awaitingCaptchaCheck) { |
| 2597 | if (!forceThisRequest && request->connectionToken > 0) { |
| 2598 | if ((request->connectionType & ConnectionTypeGeneric || request->connectionType & ConnectionTypeTemp) && request->connectionToken == connection->getConnectionToken()) { |
| 2599 | // if (LOGS_ENABLED) DEBUG_D("request token is valid, not retrying %s (%p)", typeInfo.name(), request->rawRequest); |
| 2600 | iter++; |
| 2601 | continue; |
| 2602 | } else { |
| 2603 | if (connection->getConnectionToken() != 0 && request->connectionToken == connection->getConnectionToken()) { |
| 2604 | // if (LOGS_ENABLED) DEBUG_D("request download token is valid, not retrying %s (%p)", typeInfo.name(), request->rawRequest); |
| 2605 | iter++; |
| 2606 | continue; |
| 2607 | } |
| 2608 | } |
| 2609 | } |
| 2610 |
| 2611 | if (request->connectionToken != 0 && request->connectionToken != connection->getConnectionToken()) { |
| 2612 | request->lastResendTime = 0; |
| 2613 | request->isResending = true; |
| 2614 | } |
| 2615 |
| 2616 | request->retryCount++; |
| 2617 |
| 2618 | if (!request->failedBySalt) { |
| 2619 | if (request->connectionType & ConnectionTypeDownload && (!request->failedByFloodWait || !failedButTimeToTryAgain)) { |
| 2620 | uint32_t retryMax; |
| 2621 | if (request->requestFlags & RequestFlagForceDownload) { |
| 2622 | retryMax = 10; |
| 2623 | } else { |
| 2624 | retryMax = 6; |
| 2625 | } |
| 2626 | if (request->retryCount >= retryMax && !request->premiumFloodWait) { |
| 2627 | if (LOGS_ENABLED) DEBUG_E("timed out %s (%d/%d), req_id = %d, message_id = 0x%" PRIx64, typeInfo.name(), request->retryCount, retryMax, request->requestToken, request->messageId); |
| 2628 | auto error = new TL_error(); |
| 2629 | error->code = -123; |
| 2630 | error->text = "RETRY_LIMIT"; |
| 2631 | int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId; |
| 2632 | request->onComplete(nullptr, error, connection->currentNetworkType, 0, request->messageId, dcId); |
| 2633 | delete error; |
| 2634 | DEBUG_D("12) erase request %d 0x%" PRIx64, request->requestToken, request->messageId); |
| 2635 | iter = runningRequests.erase(iter); |
| 2636 | continue; |
| 2637 | } |
| 2638 | } |
| 2639 | } else { |
| 2640 | request->failedBySalt = false; |
| 2641 | } |
| 2642 |
| 2643 | if (request->messageSeqNo == 0) { |
| 2644 | request->messageSeqNo = connection->generateMessageSeqNo((request->connectionType & ConnectionTypeProxy) == 0); |
| 2645 | request->messageId = generateMessageId(); |
| 2646 | if (request->rawRequest->initFunc != nullptr) { |
| 2647 | request->rawRequest->initFunc(request->messageId); |
| 2648 | } |
| 2649 | } |
| 2650 | request->startTime = currentTime; |
| 2651 | request->startTimeMillis = currentTimeMillis; |
| 2652 |
| 2653 | auto networkMessage = new NetworkMessage(); |
| 2654 | networkMessage->forceContainer = request->isResending; |
| 2655 | networkMessage->message = std::make_unique<TL_message>(); |
| 2656 | networkMessage->message->msg_id = request->messageId; |
| 2657 | networkMessage->message->bytes = request->serializedLength; |
| 2658 | networkMessage->message->outgoingBody = request->getRpcRequest(); |
| 2659 | networkMessage->message->seqno = request->messageSeqNo; |
| 2660 | networkMessage->requestId = request->requestToken; |
| 2661 | networkMessage->invokeAfter = (request->requestFlags & RequestFlagInvokeAfter) != 0 && (request->requestFlags & RequestFlagResendAfter) == 0; |
| 2662 | networkMessage->needQuickAck = (request->requestFlags & RequestFlagNeedQuickAck) != 0; |
| 2663 |
| 2664 | request->connectionToken = connection->getConnectionToken(); |
| 2665 | switch (requestConnectionType) { |
| 2666 | case ConnectionTypeGeneric: |
| 2667 | addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters); |
| 2668 | break; |
| 2669 | case ConnectionTypeGenericMedia: |
| 2670 | addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMediaMessagesToDatacenters); |
| 2671 | break; |
| 2672 | case ConnectionTypeTemp: |
| 2673 | addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, tempMessagesToDatacenters); |
| 2674 | break; |
| 2675 | case ConnectionTypeProxy: { |
| 2676 | std::vector<std::unique_ptr<NetworkMessage>> array; |
| 2677 | array.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 2678 | sendMessagesToConnection(array, connection, false); |
| 2679 | break; |
| 2680 | } |
| 2681 | case ConnectionTypeDownload: |
| 2682 | case ConnectionTypeUpload: { |
| 2683 | std::vector<std::unique_ptr<NetworkMessage>> array; |
| 2684 | array.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 2685 | sendMessagesToConnectionWithConfirmation(array, connection, false); |
| 2686 | request->onWriteToSocket(); |
| 2687 | break; |
| 2688 | } |
| 2689 | default: |
| 2690 | delete networkMessage; |
| 2691 | } |
| 2692 | } |
| 2693 | iter++; |
| 2694 | } |
| 2695 |
| 2696 | Connection *genericConnection = nullptr; |
| 2697 | Datacenter *defaultDatacenter = getDatacenterWithId(currentDatacenterId); |
| 2698 | if (defaultDatacenter != nullptr) { |
| 2699 | genericConnection = defaultDatacenter->getGenericConnection(true, 0); |
| 2700 | if (genericConnection != nullptr && !sessionsToDestroy.empty() && genericConnection->getConnectionToken() != 0) { |
| 2701 | auto iter = sessionsToDestroy.begin(); |
| 2702 |
| 2703 | if (abs(currentTime - lastDestroySessionRequestTime) > 2) { |
| 2704 | lastDestroySessionRequestTime = currentTime; |
| 2705 | auto request = new TL_destroy_session(); |
| 2706 | request->session_id = *iter; |
| 2707 |
| 2708 | auto networkMessage = new NetworkMessage(); |
| 2709 | networkMessage->message = std::make_unique<TL_message>(); |
| 2710 | networkMessage->message->msg_id = generateMessageId(); |
| 2711 | networkMessage->message->bytes = request->getObjectSize(); |
| 2712 | networkMessage->message->body = std::unique_ptr<TLObject>(request); |
| 2713 | networkMessage->message->seqno = genericConnection->generateMessageSeqNo(false); |
| 2714 | addMessageToDatacenter(defaultDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters); |
| 2715 | } |
| 2716 | sessionsToDestroy.erase(iter); |
| 2717 | } |
| 2718 | } |
| 2719 |
| 2720 | for (auto iter = requestsQueue.begin(); iter != requestsQueue.end();) { |
| 2721 | Request *request = iter->get(); |
| 2722 | if (request->cancelled) { |
| 2723 | iter = requestsQueue.erase(iter); |
| 2724 | if (LOGS_ENABLED) |
| 2725 | DEBUG_D("skip queue, token = %d: cancelled", request->requestToken); |
| 2726 | continue; |
| 2727 | } |
| 2728 | if (hasInvokeWaitMessage && (request->requestFlags & RequestFlagInvokeAfter) != 0 && (request->requestFlags & RequestFlagResendAfter) == 0) { |
| 2729 | request->requestFlags |= RequestFlagResendAfter; |
| 2730 | } |
| 2731 | if (hasInvokeAfterMessage && (request->requestFlags & RequestFlagResendAfter) != 0) { |
| 2732 | iter++; |
| 2733 | continue; |
| 2734 | } |
| 2735 | if (!hasInvokeAfterMessage && (request->requestFlags & RequestFlagInvokeAfter) != 0) { |
| 2736 | hasInvokeAfterMessage = true; |
| 2737 | } |
| 2738 |
| 2739 | uint32_t datacenterId = request->datacenterId; |
| 2740 | if (datacenterId == DEFAULT_DATACENTER_ID) { |
| 2741 | if (movingToDatacenterId != DEFAULT_DATACENTER_ID) { |
| 2742 | iter++; |
| 2743 | if (LOGS_ENABLED) |
| 2744 | DEBUG_D("skip queue, token = %d: moving dc", request->requestToken); |
| 2745 | continue; |
| 2746 | } |
| 2747 | datacenterId = currentDatacenterId; |
| 2748 | } |
| 2749 |
| 2750 | int32_t canUseUnboundKey = 0; |
| 2751 | if ((request->requestFlags & RequestFlagUseUnboundKey) != 0) { |
| 2752 | canUseUnboundKey |= 1; |
| 2753 | } |
| 2754 |
| 2755 | if (request->requestFlags & RequestFlagTryDifferentDc) { |
| 2756 | int32_t requestStartTime = request->startTime; |
| 2757 | int32_t timeout = 30; |
| 2758 | if (updatingDcSettings && dynamic_cast<TL_help_getConfig *>(request->rawRequest)) { |
| 2759 | requestStartTime = updatingDcStartTime; |
| 2760 | timeout = 60; |
| 2761 | } else { |
| 2762 | request->startTime = 0; |
| 2763 | request->startTimeMillis = 0; |
| 2764 | } |
| 2765 | if (requestStartTime != 0 && abs(currentTime - requestStartTime) >= timeout) { |
| 2766 | std::vector<uint32_t> allDc; |
| 2767 | for (auto & datacenter : datacenters) { |
| 2768 | if (datacenter.first == datacenterId || datacenter.second->isCdnDatacenter) { |
| 2769 | continue; |
| 2770 | } |
| 2771 | allDc.push_back(datacenter.first); |
| 2772 | } |
| 2773 | uint8_t index; |
| 2774 | RAND_bytes(&index, 1); |
| 2775 | datacenterId = allDc[index % allDc.size()]; |
| 2776 | if (dynamic_cast<TL_help_getConfig *>(request->rawRequest)) { |
| 2777 | updatingDcStartTime = currentTime; |
| 2778 | request->datacenterId = datacenterId; |
| 2779 | } else { |
| 2780 | currentDatacenterId = datacenterId; |
| 2781 | } |
| 2782 | } |
| 2783 | } |
| 2784 |
| 2785 | Datacenter *requestDatacenter = getDatacenterWithId(datacenterId); |
| 2786 | if (requestDatacenter == nullptr) { |
| 2787 | if (std::find(unknownDatacenterIds.begin(), unknownDatacenterIds.end(), datacenterId) == unknownDatacenterIds.end()) { |
| 2788 | unknownDatacenterIds.push_back(datacenterId); |
| 2789 | } |
| 2790 | if (LOGS_ENABLED) |
| 2791 | DEBUG_D("skip queue, token = %d: unknown dc", request->requestToken); |
| 2792 | iter++; |
| 2793 | continue; |
| 2794 | } else { |
| 2795 | if (request->needInitRequest(requestDatacenter, currentVersion) && !request->hasInitFlag()) { |
| 2796 | request->rpcRequest.release(); |
| 2797 | request->rpcRequest = wrapInLayer(request->rawRequest, requestDatacenter, request); |
| 2798 | } |
| 2799 |
| 2800 | if (!requestDatacenter->hasAuthKey(request->connectionType, canUseUnboundKey)) { |
| 2801 | std::pair<Datacenter *, ConnectionType> pair = std::make_pair(requestDatacenter, request->connectionType); |
| 2802 | if (std::find(neededDatacenters.begin(), neededDatacenters.end(), pair) == neededDatacenters.end()) { |
| 2803 | neededDatacenters.push_back(pair); |
| 2804 | } |
| 2805 | if (LOGS_ENABLED) |
| 2806 | DEBUG_D("skip queue, token = %d: no authkey for dc", request->requestToken); |
| 2807 | iter++; |
| 2808 | continue; |
| 2809 | } else if (!(request->requestFlags & RequestFlagEnableUnauthorized) && !requestDatacenter->authorized && request->datacenterId != DEFAULT_DATACENTER_ID && request->datacenterId != currentDatacenterId) { |
| 2810 | if (std::find(unauthorizedDatacenters.begin(), unauthorizedDatacenters.end(), requestDatacenter) == unauthorizedDatacenters.end()) { |
| 2811 | unauthorizedDatacenters.push_back(requestDatacenter); |
| 2812 | } |
| 2813 | if (LOGS_ENABLED) |
| 2814 | DEBUG_D("skip queue, token = %d: dc is unauthorized", request->requestToken); |
| 2815 | iter++; |
| 2816 | continue; |
| 2817 | } |
| 2818 | } |
| 2819 |
| 2820 | Connection *connection = requestDatacenter->getConnectionByType(request->connectionType, true, canUseUnboundKey); |
| 2821 |
| 2822 | if (request->connectionType & ConnectionTypeGeneric && connection->getConnectionToken() == 0) { |
| 2823 | iter++; |
| 2824 | continue; |
| 2825 | } |
| 2826 |
| 2827 | switch (request->connectionType & 0x0000ffff) { |
| 2828 | case ConnectionTypeGeneric: |
| 2829 | case ConnectionTypeGenericMedia: |
| 2830 | if (!canUseUnboundKey && genericRunningRequestCount >= MAX_GENERAL_REQUESTS) { |
| 2831 | iter++; |
| 2832 | // if (LOGS_ENABLED) |
| 2833 | // DEBUG_D("skip queue, token = %d: generic type: running generic requests >= %d", request->requestToken, MAX_GENERAL_REQUESTS); |
| 2834 | continue; |
| 2835 | } |
| 2836 | genericRunningRequestCount++; |
| 2837 | break; |
| 2838 | case ConnectionTypeDownload: { |
| 2839 | uint32_t currentCount; |
| 2840 | auto map = request->isCancelRequest() ? downloadCancelRunningRequestCount : downloadRunningRequestCount; |
| 2841 | auto dcIter = map.find(datacenterId); |
| 2842 | if (dcIter != map.end()) { |
| 2843 | currentCount = dcIter->second; |
| 2844 | } else { |
| 2845 | currentCount = 0; |
| 2846 | } |
| 2847 | if (!networkAvailable) { |
| 2848 | iter++; |
| 2849 | if (LOGS_ENABLED) |
| 2850 | DEBUG_D("skip queue, token = %d: download type: network unavailable", request->requestToken); |
| 2851 | continue; |
| 2852 | } |
| 2853 | int max; |
| 2854 | if (request->isCancelRequest()) { |
| 2855 | max = MAX_DOWNLOAD_REQUESTS_CANCELS; |
| 2856 | } else if (currentUserPremium) { |
| 2857 | max = MAX_DOWNLOAD_REQUESTS_PREMIUM; |
| 2858 | } else { |
| 2859 | max = MAX_DOWNLOAD_REQUESTS; |
| 2860 | } |
| 2861 | if (currentCount >= max) { |
| 2862 | iter++; |
| 2863 | if (LOGS_ENABLED) |
| 2864 | DEBUG_D("skip queue, token = %d: download type: running download requests >= %d", request->requestToken, max); |
| 2865 | continue; |
| 2866 | } |
| 2867 | downloadRunningRequestCount[datacenterId] = currentCount + 1; |
| 2868 | break; |
| 2869 | } |
| 2870 | case ConnectionTypeProxy: |
| 2871 | case ConnectionTypeTemp: |
| 2872 | if (!networkAvailable) { |
| 2873 | iter++; |
| 2874 | if (LOGS_ENABLED) |
| 2875 | DEBUG_D("skip queue, token = %d: proxy/temp type: network unavailable", request->requestToken); |
| 2876 | continue; |
| 2877 | } |
| 2878 | break; |
| 2879 | case ConnectionTypeUpload: |
| 2880 | if (!networkAvailable) { |
| 2881 | iter++; |
| 2882 | if (LOGS_ENABLED) |
| 2883 | DEBUG_D("skip queue, token = %d: upload type: network unavailable", request->requestToken); |
| 2884 | continue; |
| 2885 | } |
| 2886 | if (uploadRunningRequestCount >= MAX_UPLOAD_REQUESTS) { |
| 2887 | iter++; |
| 2888 | if (LOGS_ENABLED) |
| 2889 | DEBUG_D("skip queue, token = %d: upload type: running upload requests >= 10", request->requestToken); |
| 2890 | continue; |
| 2891 | } |
| 2892 | uploadRunningRequestCount++; |
| 2893 | break; |
| 2894 | default: |
| 2895 | break; |
| 2896 | } |
| 2897 |
| 2898 | request->messageId = generateMessageId(); |
| 2899 | if (request->rawRequest->initFunc != nullptr) { |
| 2900 | request->rawRequest->initFunc(request->messageId); |
| 2901 | } |
| 2902 | if (LOGS_ENABLED) DEBUG_D("messageId for token = %d, 0x%" PRIx64, request->requestToken, request->messageId); |
| 2903 |
| 2904 | uint32_t requestLength = request->rpcRequest->getObjectSize(); |
| 2905 | if (request->requestFlags & RequestFlagCanCompress) { |
| 2906 | request->requestFlags &= ~RequestFlagCanCompress; |
| 2907 | NativeByteBuffer *original = BuffersStorage::getInstance().getFreeBuffer(requestLength); |
| 2908 | request->rpcRequest->serializeToStream(original); |
| 2909 | NativeByteBuffer *buffer = compressGZip(original); |
| 2910 | if (buffer != nullptr) { |
| 2911 | auto packed = new TL_gzip_packed(); |
| 2912 | packed->originalRequest = std::move(request->rpcRequest); |
| 2913 | packed->packed_data_to_send = buffer; |
| 2914 | request->rpcRequest = std::unique_ptr<TLObject>(packed); |
| 2915 | requestLength = packed->getObjectSize(); |
| 2916 | } |
| 2917 | original->reuse(); |
| 2918 | } |
| 2919 |
| 2920 | request->serializedLength = requestLength; |
| 2921 | request->messageSeqNo = connection->generateMessageSeqNo((request->connectionType & ConnectionTypeProxy) == 0); |
| 2922 | request->startTime = currentTime; |
| 2923 | request->startTimeMillis = currentTimeMillis; |
| 2924 | request->connectionToken = connection->getConnectionToken(); |
| 2925 |
| 2926 | auto networkMessage = new NetworkMessage(); |
| 2927 | networkMessage->message = std::make_unique<TL_message>(); |
| 2928 | networkMessage->forceContainer = request->isResending; |
| 2929 | networkMessage->message->msg_id = request->messageId; |
| 2930 | networkMessage->message->bytes = request->serializedLength; |
| 2931 | networkMessage->message->outgoingBody = request->getRpcRequest(); |
| 2932 | networkMessage->message->seqno = request->messageSeqNo; |
| 2933 | networkMessage->requestId = request->requestToken; |
| 2934 | networkMessage->invokeAfter = (request->requestFlags & RequestFlagInvokeAfter) != 0 && (request->requestFlags & RequestFlagResendAfter) == 0; |
| 2935 | networkMessage->needQuickAck = (request->requestFlags & RequestFlagNeedQuickAck) != 0; |
| 2936 |
| 2937 | if (!hasPendingRequestsForConnection(connection)) { |
| 2938 | connection->resetLastEventTime(); |
| 2939 | } |
| 2940 | runningRequests.push_back(std::move(*iter)); |
| 2941 |
| 2942 | switch (request->connectionType & 0x0000ffff) { |
| 2943 | case ConnectionTypeGeneric: |
| 2944 | addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters); |
| 2945 | break; |
| 2946 | case ConnectionTypeGenericMedia: |
| 2947 | addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMediaMessagesToDatacenters); |
| 2948 | break; |
| 2949 | case ConnectionTypeTemp: |
| 2950 | addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, tempMessagesToDatacenters); |
| 2951 | break; |
| 2952 | case ConnectionTypeProxy: { |
| 2953 | std::vector<std::unique_ptr<NetworkMessage>> array; |
| 2954 | array.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 2955 | sendMessagesToConnection(array, connection, false); |
| 2956 | break; |
| 2957 | } |
| 2958 | case ConnectionTypeDownload: |
| 2959 | case ConnectionTypeUpload: { |
| 2960 | std::vector<std::unique_ptr<NetworkMessage>> array; |
| 2961 | array.push_back(std::unique_ptr<NetworkMessage>(networkMessage)); |
| 2962 | sendMessagesToConnectionWithConfirmation(array, connection, false); |
| 2963 | break; |
| 2964 | } |
| 2965 | default: |
| 2966 | delete networkMessage; |
| 2967 | } |
| 2968 |
| 2969 | iter = requestsQueue.erase(iter); |
| 2970 | } |
| 2971 |
| 2972 | for (auto & iter : datacenters) { |
| 2973 | Datacenter *datacenter = iter.second; |
| 2974 | auto iter2 = genericMessagesToDatacenters.find(datacenter->getDatacenterId()); |
| 2975 | if (iter2 == genericMessagesToDatacenters.end()) { |
| 2976 | Connection *connection = datacenter->getGenericConnection(false, 1); |
| 2977 | if (connection != nullptr && connection->getConnectionToken() != 0 && connection->hasMessagesToConfirm()) { |
| 2978 | genericMessagesToDatacenters[datacenter->getDatacenterId()] = std::vector<std::unique_ptr<NetworkMessage>>(); |
| 2979 | } |
| 2980 | } |
| 2981 |
| 2982 | iter2 = genericMediaMessagesToDatacenters.find(datacenter->getDatacenterId()); |
| 2983 | if (iter2 == genericMediaMessagesToDatacenters.end()) { |
| 2984 | Connection *connection = datacenter->getGenericMediaConnection(false, 1); |
| 2985 | if (connection != nullptr && connection->getConnectionToken() != 0 && connection->hasMessagesToConfirm()) { |
| 2986 | genericMediaMessagesToDatacenters[datacenter->getDatacenterId()] = std::vector<std::unique_ptr<NetworkMessage>>(); |
| 2987 | } |
| 2988 | } |
| 2989 |
| 2990 | iter2 = tempMessagesToDatacenters.find(datacenter->getDatacenterId()); |
| 2991 | if (iter2 == tempMessagesToDatacenters.end()) { |
| 2992 | Connection *connection = datacenter->getTempConnection(false); |
| 2993 | if (connection != nullptr && connection->getConnectionToken() != 0 && connection->hasMessagesToConfirm()) { |
| 2994 | tempMessagesToDatacenters[datacenter->getDatacenterId()] = std::vector<std::unique_ptr<NetworkMessage>>(); |
| 2995 | } |
| 2996 | } |
| 2997 | } |
| 2998 |
| 2999 | for (auto & genericMessagesToDatacenter : genericMessagesToDatacenters) { |
| 3000 | Datacenter *datacenter = getDatacenterWithId(genericMessagesToDatacenter.first); |
| 3001 | if (datacenter != nullptr) { |
| 3002 | bool scannedPreviousRequests = false; |
| 3003 | bool needQuickAck = false; |
| 3004 | int64_t lastSentMessageRpcId = 0; |
| 3005 | std::vector<std::unique_ptr<NetworkMessage>> &array = genericMessagesToDatacenter.second; |
| 3006 | size_t count = array.size(); |
| 3007 | for (uint32_t b = 0; b < count; b++) { |
| 3008 | NetworkMessage *networkMessage = array[b].get(); |
| 3009 | if (networkMessage->needQuickAck) { |
| 3010 | needQuickAck = true; |
| 3011 | } |
| 3012 | if (networkMessage->invokeAfter) { |
| 3013 | if (!scannedPreviousRequests) { |
| 3014 | scannedPreviousRequests = true; |
| 3015 |
| 3016 | std::vector<int64_t> currentRequests; |
| 3017 | for (uint32_t a = 0; a < count; a++) { |
| 3018 | NetworkMessage *currentNetworkMessage = array[a].get(); |
| 3019 | if (currentNetworkMessage->invokeAfter) { |
| 3020 | currentRequests.push_back(currentNetworkMessage->message->msg_id); |
| 3021 | } |
| 3022 | } |
| 3023 |
| 3024 | int64_t maxRequestId = 0; |
| 3025 | if (lastInvokeAfterMessageId != 0) { |
| 3026 | auto timeMessage = (int64_t) (lastInvokeAfterMessageId / 4294967296.0); |
| 3027 | if (getCurrentTime() - timeMessage <= 5) { |
| 3028 | maxRequestId = lastInvokeAfterMessageId; |
| 3029 | } |
| 3030 | } |
| 3031 | for (auto & runningRequest : runningRequests) { |
| 3032 | Request *request = runningRequest.get(); |
| 3033 | if (request->requestFlags & RequestFlagInvokeAfter) { |
| 3034 | if (request->messageId > maxRequestId && std::find(currentRequests.begin(), currentRequests.end(), request->messageId) == currentRequests.end()) { |
| 3035 | maxRequestId = request->messageId; |
| 3036 | } |
| 3037 | } |
| 3038 | } |
| 3039 |
| 3040 | lastSentMessageRpcId = maxRequestId; |
| 3041 | } |
| 3042 |
| 3043 | TL_message *message = networkMessage->message.get(); |
| 3044 |
| 3045 | if (lastSentMessageRpcId != 0 && lastSentMessageRpcId != message->msg_id) { |
| 3046 | auto request = new TL_invokeAfterMsg(); |
| 3047 | request->msg_id = lastSentMessageRpcId; |
| 3048 | if (message->outgoingBody != nullptr) { |
| 3049 | if (LOGS_ENABLED) DEBUG_D("wrap outgoingBody(%p, %s) to TL_invokeAfterMsg, token = %d, after 0x%" PRIx64, message->outgoingBody, typeid(*message->outgoingBody).name(), networkMessage->requestId, request->msg_id); |
| 3050 | request->outgoingQuery = message->outgoingBody; |
| 3051 | message->outgoingBody = nullptr; |
| 3052 | } else { |
| 3053 | if (LOGS_ENABLED) DEBUG_D("wrap body(%p, %s) to TL_invokeAfterMsg, token = %d, after 0x%" PRIx64, message->body.get(), typeid(*(message->body.get())).name(), networkMessage->requestId, request->msg_id); |
| 3054 | request->query = std::move(message->body); |
| 3055 | } |
| 3056 | message->body = std::unique_ptr<TLObject>(request); |
| 3057 | message->bytes += 4 + 8; |
| 3058 | } |
| 3059 |
| 3060 | lastSentMessageRpcId = message->msg_id; |
| 3061 | lastInvokeAfterMessageId = message->msg_id; |
| 3062 | } |
| 3063 | } |
| 3064 |
| 3065 | sendMessagesToConnectionWithConfirmation(array, datacenter->getGenericConnection(true, 1), needQuickAck); |
| 3066 | } |
| 3067 | } |
| 3068 |
| 3069 | for (auto & tempMessagesToDatacenter : tempMessagesToDatacenters) { |
| 3070 | Datacenter *datacenter = getDatacenterWithId(tempMessagesToDatacenter.first); |
| 3071 | if (datacenter != nullptr) { |
| 3072 | std::vector<std::unique_ptr<NetworkMessage>> &array = tempMessagesToDatacenter.second; |
| 3073 | sendMessagesToConnectionWithConfirmation(array, datacenter->getTempConnection(true), false); |
| 3074 | } |
| 3075 | } |
| 3076 |
| 3077 | for (auto & genericMediaMessagesToDatacenter : genericMediaMessagesToDatacenters) { |
| 3078 | Datacenter *datacenter = getDatacenterWithId(genericMediaMessagesToDatacenter.first); |
| 3079 | if (datacenter != nullptr) { |
| 3080 | std::vector<std::unique_ptr<NetworkMessage>> &array = genericMediaMessagesToDatacenter.second; |
| 3081 | sendMessagesToConnectionWithConfirmation(array, datacenter->getGenericMediaConnection(true, 1), false); |
| 3082 | } |
| 3083 | } |
| 3084 |
| 3085 | if (connectionTypes == ConnectionTypeGeneric && dc == currentDatacenterId) { |
| 3086 | auto iter2 = genericMessagesToDatacenters.find(currentDatacenterId); |
| 3087 | if (iter2 == genericMessagesToDatacenters.end()) { |
| 3088 | sendPing(getDatacenterWithId(currentDatacenterId), false); |
| 3089 | } |
| 3090 | } |
| 3091 |
| 3092 | if (!unknownDatacenterIds.empty()) { |
| 3093 | updateDcSettings(0, false, false); |
| 3094 | } |
| 3095 |
| 3096 | size_t count = neededDatacenters.size(); |
| 3097 | for (uint32_t a = 0; a < count; a++) { |
| 3098 | Datacenter *datacenter = neededDatacenters[a].first; |
| 3099 | bool media = Connection::isMediaConnectionType(neededDatacenters[a].second) && datacenter->hasMediaAddress(); |
| 3100 | if (datacenter->getDatacenterId() != movingToDatacenterId && !datacenter->isHandshaking(media) && !datacenter->hasAuthKey(neededDatacenters[a].second, 1)) { |
| 3101 | datacenter->beginHandshake(media ? HandshakeTypeMediaTemp : HandshakeTypeTemp, true); |
| 3102 | } |
| 3103 | } |
| 3104 |
| 3105 | if (currentUserId) { |
| 3106 | count = unauthorizedDatacenters.size(); |
| 3107 | for (uint32_t a = 0; a < count; a++) { |
| 3108 | Datacenter *datacenter = unauthorizedDatacenters[a]; |
| 3109 | uint32_t id = datacenter->getDatacenterId(); |
| 3110 | if (id != currentDatacenterId && id != movingToDatacenterId && !datacenter->isExportingAuthorization()) { |
| 3111 | datacenter->exportAuthorization(); |
| 3112 | } |
| 3113 | } |
| 3114 | } |
| 3115 | } |
| 3116 |
| 3117 | Datacenter *ConnectionsManager::getDatacenterWithId(uint32_t datacenterId) { |
| 3118 | if (datacenterId == DEFAULT_DATACENTER_ID) { |
| 3119 | return datacenters[currentDatacenterId]; |
| 3120 | } |
| 3121 | auto iter = datacenters.find(datacenterId); |
| 3122 | return iter != datacenters.end() ? iter->second : nullptr; |
| 3123 | } |
| 3124 |
| 3125 | std::unique_ptr<TLObject> ConnectionsManager::wrapInLayer(TLObject *object, Datacenter *datacenter, Request *baseRequest) { |
| 3126 | if (object->isNeedLayer()) { |
| 3127 | bool media = PFS_ENABLED && datacenter != nullptr && baseRequest->isMediaRequest() && datacenter->hasMediaAddress(); |
| 3128 | if (datacenter == nullptr || baseRequest->needInitRequest(datacenter, currentVersion)) { |
| 3129 | if (datacenter != nullptr && datacenter->getDatacenterId() == currentDatacenterId) { |
| 3130 | registerForInternalPushUpdates(); |
| 3131 | } |
| 3132 | if (media) { |
| 3133 | baseRequest->isInitMediaRequest = true; |
| 3134 | } else { |
| 3135 | baseRequest->isInitRequest = true; |
| 3136 | } |
| 3137 | auto request = new initConnection(); |
| 3138 | if (delegate != nullptr) { |
| 3139 | request->flags = delegate->getInitFlags(instanceNum); |
| 3140 | } else { |
| 3141 | request->flags = 0; |
| 3142 | } |
| 3143 | request->query = std::unique_ptr<TLObject>(object); |
| 3144 | request->api_id = currentApiId; |
| 3145 | request->app_version = currentAppVersion; |
| 3146 | request->lang_code = currentLangCode; |
| 3147 | request->lang_pack = "android"; |
| 3148 | request->system_lang_code = currentSystemLangCode; |
| 3149 |
| 3150 |
| 3151 | auto jsonObject = new TL_jsonObject(); |
| 3152 | request->params = std::unique_ptr<JSONValue>(jsonObject); |
| 3153 |
| 3154 | if (!currentRegId.empty()) { |
| 3155 | auto objectValue = new TL_jsonObjectValue(); |
| 3156 | jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue)); |
| 3157 |
| 3158 | auto jsonString = new TL_jsonString(); |
| 3159 | jsonString->value = currentRegId; |
| 3160 | objectValue->key = "device_token"; |
| 3161 | objectValue->value = std::unique_ptr<JSONValue>(jsonString); |
| 3162 | } |
| 3163 | if (!certFingerprint.empty()) { |
| 3164 | auto objectValue = new TL_jsonObjectValue(); |
| 3165 | jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue)); |
| 3166 |
| 3167 | auto jsonString = new TL_jsonString(); |
| 3168 | jsonString->value = certFingerprint; |
| 3169 | objectValue->key = "data"; |
| 3170 | objectValue->value = std::unique_ptr<JSONValue>(jsonString); |
| 3171 | } |
| 3172 |
| 3173 | auto objectValue = new TL_jsonObjectValue(); |
| 3174 | jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue)); |
| 3175 | auto jsonString = new TL_jsonString(); |
| 3176 | jsonString->value = installer; |
| 3177 | objectValue->key = "installer"; |
| 3178 | objectValue->value = std::unique_ptr<JSONValue>(jsonString); |
| 3179 |
| 3180 | objectValue = new TL_jsonObjectValue(); |
| 3181 | jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue)); |
| 3182 | jsonString = new TL_jsonString(); |
| 3183 | jsonString->value = package; |
| 3184 | objectValue->key = "package_id"; |
| 3185 | objectValue->value = std::unique_ptr<JSONValue>(jsonString); |
| 3186 |
| 3187 | objectValue = new TL_jsonObjectValue(); |
| 3188 | jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue)); |
| 3189 |
| 3190 | auto jsonNumber = new TL_jsonNumber(); |
| 3191 | jsonNumber->value = currentDeviceTimezone; |
| 3192 | objectValue->key = "tz_offset"; |
| 3193 | objectValue->value = std::unique_ptr<JSONValue>(jsonNumber); |
| 3194 |
| 3195 | if (currentPerformanceClass != -1) { |
| 3196 | objectValue = new TL_jsonObjectValue(); |
| 3197 | jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue)); |
| 3198 |
| 3199 | auto jsonNumber = new TL_jsonNumber(); |
| 3200 | jsonNumber->value = currentPerformanceClass + 1; |
| 3201 | objectValue->key = "perf_cat"; |
| 3202 | objectValue->value = std::unique_ptr<JSONValue>(jsonNumber); |
| 3203 | } |
| 3204 |
| 3205 | request->flags |= 2; |
| 3206 |
| 3207 | if (!proxyAddress.empty() && !proxySecret.empty()) { |
| 3208 | request->flags |= 1; |
| 3209 | request->proxy = std::make_unique<TL_inputClientProxy>(); |
| 3210 | request->proxy->address = proxyAddress; |
| 3211 | request->proxy->port = proxyPort; |
| 3212 | } |
| 3213 |
| 3214 | if (datacenter == nullptr || datacenter->isCdnDatacenter) { |
| 3215 | request->device_model = "n/a"; |
| 3216 | request->system_version = "n/a"; |
| 3217 | } else { |
| 3218 | request->device_model = currentDeviceModel; |
| 3219 | request->system_version = currentSystemVersion; |
| 3220 | } |
| 3221 | if (request->lang_code.empty()) { |
| 3222 | request->lang_code = "en"; |
| 3223 | } |
| 3224 | if (request->device_model.empty()) { |
| 3225 | request->device_model = "n/a"; |
| 3226 | } |
| 3227 | if (request->app_version.empty()) { |
| 3228 | request->app_version = "n/a"; |
| 3229 | } |
| 3230 | if (request->system_version.empty()) { |
| 3231 | request->system_version = "n/a"; |
| 3232 | } |
| 3233 | auto request2 = new invokeWithLayer(); |
| 3234 | request2->layer = currentLayer; |
| 3235 | request2->query = std::unique_ptr<TLObject>(request); |
| 3236 | if (LOGS_ENABLED) DEBUG_D("wrap in layer %s, flags = %d", typeid(*object).name(), request->flags); |
| 3237 | return std::unique_ptr<TLObject>(request2); |
| 3238 | } |
| 3239 | } |
| 3240 | return std::unique_ptr<TLObject>(object); |
| 3241 | } |
| 3242 |
| 3243 | static const char *const url_symbols64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; |
| 3244 | static unsigned char url_char_to_value[256]; |
| 3245 | static void init_base64url_table() { |
| 3246 | static bool is_inited = []() { |
| 3247 | std::fill(std::begin(url_char_to_value), std::end(url_char_to_value), static_cast<unsigned char>(64)); |
| 3248 | for (unsigned char i = 0; i < 64; i++) { |
| 3249 | url_char_to_value[static_cast<size_t>(url_symbols64[i])] = i; |
| 3250 | } |
| 3251 | return true; |
| 3252 | }(); |
| 3253 | assert(is_inited); |
| 3254 | } |
| 3255 |
| 3256 | std::string base64UrlDecode(std::string base64) { |
| 3257 | init_base64url_table(); |
| 3258 |
| 3259 | size_t padding_length = 0; |
| 3260 | while (!base64.empty() && base64.back() == '=') { |
| 3261 | base64.pop_back(); |
| 3262 | padding_length++; |
| 3263 | } |
| 3264 | if (padding_length >= 3 || (padding_length > 0 && ((base64.size() + padding_length) & 3) != 0)) { |
| 3265 | return ""; |
| 3266 | } |
| 3267 |
| 3268 | if ((base64.size() & 3) == 1) { |
| 3269 | return ""; |
| 3270 | } |
| 3271 |
| 3272 | std::string output; |
| 3273 | output.reserve(((base64.size() + 3) >> 2) * 3); |
| 3274 | for (size_t i = 0; i < base64.size();) { |
| 3275 | size_t left = std::min(base64.size() - i, static_cast<size_t>(4)); |
| 3276 | int c = 0; |
| 3277 | for (size_t t = 0; t < left; t++) { |
| 3278 | auto value = url_char_to_value[base64.c_str()[i++]]; |
| 3279 | if (value == 64) { |
| 3280 | return ""; |
| 3281 | } |
| 3282 | c |= value << ((3 - t) * 6); |
| 3283 | } |
| 3284 | output += static_cast<char>(static_cast<unsigned char>(c >> 16)); |
| 3285 | if (left == 2) { |
| 3286 | if ((c & ((1 << 16) - 1)) != 0) { |
| 3287 | return ""; |
| 3288 | } |
| 3289 | } else { |
| 3290 | output += static_cast<char>(static_cast<unsigned char>(c >> 8)); |
| 3291 | if (left == 3) { |
| 3292 | if ((c & ((1 << 8) - 1)) != 0) { |
| 3293 | return ""; |
| 3294 | } |
| 3295 | } else { |
| 3296 | output += static_cast<char>(static_cast<unsigned char>(c)); |
| 3297 | } |
| 3298 | } |
| 3299 | } |
| 3300 | return output; |
| 3301 | } |
| 3302 |
| 3303 | inline std::string decodeSecret(std::string secret) { |
| 3304 | bool allHex = true; |
| 3305 | for (char i : secret) { |
| 3306 | if (!((i >= '0' && i <= '9') || (i >= 'a' && i <= 'f') || (i >= 'A' && i <= 'F'))) { |
| 3307 | allHex = false; |
| 3308 | break; |
| 3309 | } |
| 3310 | } |
| 3311 | if (allHex) { |
| 3312 | size_t size = secret.size() / 2; |
| 3313 | char *result = new char[size]; |
| 3314 | for (int32_t i = 0; i < size; i++) { |
| 3315 | result[i] = (char) (char2int(secret[i * 2]) * 16 + char2int(secret[i * 2 + 1])); |
| 3316 | } |
| 3317 | secret = std::string(result, size); |
| 3318 | delete[] result; |
| 3319 | return secret; |
| 3320 | } |
| 3321 | return base64UrlDecode(secret); |
| 3322 | } |
| 3323 |
| 3324 | void ConnectionsManager::updateDcSettings(uint32_t dcNum, bool workaround, bool ifLoadingTryAgain) { |
| 3325 | if (workaround) { |
| 3326 | if (updatingDcSettingsWorkaround) { |
| 3327 | return; |
| 3328 | } |
| 3329 | updatingDcSettingsWorkaround = true; |
| 3330 | } else { |
| 3331 | if (updatingDcSettings) { |
| 3332 | if (ifLoadingTryAgain) { |
| 3333 | updatingDcSettingsAgain = true; |
| 3334 | updatingDcSettingsAgainDcNum = dcNum; |
| 3335 | } |
| 3336 | return; |
| 3337 | } |
| 3338 | updatingDcSettings = true; |
| 3339 | updatingDcStartTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000); |
| 3340 | } |
| 3341 |
| 3342 | auto request = new TL_help_getConfig(); |
| 3343 | sendRequest(request, [&, workaround](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) { |
| 3344 | if ((!workaround && !updatingDcSettings) || (workaround && !updatingDcSettingsWorkaround)) { |
| 3345 | return; |
| 3346 | } |
| 3347 | if (!workaround && updatingDcSettingsAgain) { |
| 3348 | updatingDcSettings = false; |
| 3349 | updatingDcSettingsAgain = false; |
| 3350 | for (auto & datacenter : datacenters) { |
| 3351 | datacenter.second->resetInitVersion(); |
| 3352 | } |
| 3353 | updateDcSettings(0, false, false); |
| 3354 | return; |
| 3355 | } |
| 3356 |
| 3357 | if (response != nullptr) { |
| 3358 | auto config = (TL_config *) response; |
| 3359 | clientBlocked = (config->flags & 256) != 0; |
| 3360 | if (!workaround) { |
| 3361 | int32_t updateIn = config->expires - getCurrentTime(); |
| 3362 | if (updateIn <= 0) { |
| 3363 | updateIn = 120; |
| 3364 | } |
| 3365 | lastDcUpdateTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000) - DC_UPDATE_TIME + updateIn; |
| 3366 | } |
| 3367 |
| 3368 | struct DatacenterInfo { |
| 3369 | std::vector<TcpAddress> addressesIpv4; |
| 3370 | std::vector<TcpAddress> addressesIpv6; |
| 3371 | std::vector<TcpAddress> addressesIpv4Download; |
| 3372 | std::vector<TcpAddress> addressesIpv6Download; |
| 3373 | bool isCdn = false; |
| 3374 | bool forceTryIpV6; |
| 3375 |
| 3376 | void addAddressAndPort(TL_dcOption *dcOption) { |
| 3377 | std::vector<TcpAddress> *addresses; |
| 3378 | if (!isCdn) { |
| 3379 | isCdn = dcOption->cdn; |
| 3380 | } |
| 3381 | forceTryIpV6 = dcOption->force_try_ipv6; |
| 3382 | if (dcOption->media_only) { |
| 3383 | if (dcOption->ipv6) { |
| 3384 | addresses = &addressesIpv6Download; |
| 3385 | } else { |
| 3386 | addresses = &addressesIpv4Download; |
| 3387 | } |
| 3388 | } else { |
| 3389 | if (dcOption->ipv6) { |
| 3390 | addresses = &addressesIpv6; |
| 3391 | } else { |
| 3392 | addresses = &addressesIpv4; |
| 3393 | } |
| 3394 | } |
| 3395 | for (auto & addresse : *addresses) { |
| 3396 | if (addresse.address == dcOption->ip_address && addresse.port == dcOption->port) { |
| 3397 | return; |
| 3398 | } |
| 3399 | } |
| 3400 | std::string secret; |
| 3401 | if (dcOption->secret != nullptr) { |
| 3402 | secret = std::string((const char *) dcOption->secret->bytes, dcOption->secret->length); |
| 3403 | } |
| 3404 | if (LOGS_ENABLED) DEBUG_D("getConfig add %s:%d to dc%d, flags %d, has_secret = %d[%d], try_this_port_only = %d, force_try_ipv6 = %d", dcOption->ip_address.c_str(), dcOption->port, dcOption->id, dcOption->flags, dcOption->secret != nullptr ? 1 : 0, dcOption->secret != nullptr ? dcOption->secret->length : 0, dcOption->thisPortOnly ? 1 : 0, dcOption->force_try_ipv6 ? 1 : 0); |
| 3405 | if (dcOption->thisPortOnly) { |
| 3406 | addresses->insert(addresses->begin(), TcpAddress(dcOption->ip_address, dcOption->port, dcOption->flags, secret)); |
| 3407 | } else { |
| 3408 | addresses->push_back(TcpAddress(dcOption->ip_address, dcOption->port, dcOption->flags, secret)); |
| 3409 | } |
| 3410 |
| 3411 | } |
| 3412 | }; |
| 3413 |
| 3414 | std::map<uint32_t, std::unique_ptr<DatacenterInfo>> map; |
| 3415 | size_t count = config->dc_options.size(); |
| 3416 | for (uint32_t a = 0; a < count; a++) { |
| 3417 | TL_dcOption *dcOption = config->dc_options[a].get(); |
| 3418 | auto iter = map.find((uint32_t) dcOption->id); |
| 3419 | DatacenterInfo *info; |
| 3420 | if (iter == map.end()) { |
| 3421 | map[dcOption->id] = std::unique_ptr<DatacenterInfo>(info = new DatacenterInfo); |
| 3422 | } else { |
| 3423 | info = iter->second.get(); |
| 3424 | } |
| 3425 | info->addAddressAndPort(dcOption); |
| 3426 | } |
| 3427 |
| 3428 | if (!map.empty()) { |
| 3429 | for (auto & iter : map) { |
| 3430 | Datacenter *datacenter = getDatacenterWithId(iter.first); |
| 3431 | DatacenterInfo *info = iter.second.get(); |
| 3432 | if (datacenter == nullptr) { |
| 3433 | datacenter = new Datacenter(instanceNum, iter.first); |
| 3434 | datacenters[iter.first] = datacenter; |
| 3435 | } |
| 3436 | datacenter->replaceAddresses(info->addressesIpv4, info->isCdn ? 8 : 0); |
| 3437 | datacenter->replaceAddresses(info->addressesIpv6, info->isCdn ? 9 : 1); |
| 3438 | datacenter->replaceAddresses(info->addressesIpv4Download, info->isCdn ? 10 : 2); |
| 3439 | datacenter->replaceAddresses(info->addressesIpv6Download, info->isCdn ? 11 : 3); |
| 3440 | if (iter.first == movingToDatacenterId) { |
| 3441 | movingToDatacenterId = DEFAULT_DATACENTER_ID; |
| 3442 | moveToDatacenter(iter.first); |
| 3443 | } |
| 3444 | } |
| 3445 | saveConfig(); |
| 3446 | scheduleTask([&] { |
| 3447 | processRequestQueue(AllConnectionTypes, 0); |
| 3448 | }); |
| 3449 | } |
| 3450 | if (delegate != nullptr) { |
| 3451 | delegate->onUpdateConfig(config, instanceNum); |
| 3452 | } |
| 3453 | } |
| 3454 | if (workaround) { |
| 3455 | updatingDcSettingsWorkaround = false; |
| 3456 | } else { |
| 3457 | updatingDcSettings = false; |
| 3458 | } |
| 3459 | }, nullptr, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin | RequestFlagUseUnboundKey | (workaround ? 0 : RequestFlagTryDifferentDc), dcNum == 0 ? currentDatacenterId : dcNum, workaround ? ConnectionTypeTemp : ConnectionTypeGeneric, true); |
| 3460 | } |
| 3461 |
| 3462 | void ConnectionsManager::moveToDatacenter(uint32_t datacenterId) { |
| 3463 | if (movingToDatacenterId == datacenterId) { |
| 3464 | return; |
| 3465 | } |
| 3466 | movingToDatacenterId = datacenterId; |
| 3467 |
| 3468 | Datacenter *currentDatacenter = getDatacenterWithId(currentDatacenterId); |
| 3469 | clearRequestsForDatacenter(currentDatacenter, HandshakeTypeAll); |
| 3470 | authorizeOnMovingDatacenter(); |
| 3471 | } |
| 3472 |
| 3473 | void ConnectionsManager::authorizeOnMovingDatacenter() { |
| 3474 | Datacenter *datacenter = getDatacenterWithId(movingToDatacenterId); |
| 3475 | if (datacenter == nullptr) { |
| 3476 | updateDcSettings(0, false, false); |
| 3477 | return; |
| 3478 | } |
| 3479 | datacenter->recreateSessions(HandshakeTypeAll); |
| 3480 | clearRequestsForDatacenter(datacenter, HandshakeTypeAll); |
| 3481 |
| 3482 | if (!datacenter->hasAuthKey(ConnectionTypeGeneric, 0) && !datacenter->isHandshakingAny()) { |
| 3483 | datacenter->clearServerSalts(false); |
| 3484 | datacenter->clearServerSalts(true); |
| 3485 | datacenter->beginHandshake(HandshakeTypeAll, true); |
| 3486 | } |
| 3487 |
| 3488 | if (movingAuthorization != nullptr) { |
| 3489 | auto request = new TL_auth_importAuthorization(); |
| 3490 | request->id = currentUserId; |
| 3491 | request->bytes = std::move(movingAuthorization); |
| 3492 | sendRequest(request, [&](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) { |
| 3493 | if (error == nullptr) { |
| 3494 | authorizedOnMovingDatacenter(); |
| 3495 | } else { |
| 3496 | moveToDatacenter(movingToDatacenterId); |
| 3497 | } |
| 3498 | }, nullptr, nullptr, RequestFlagWithoutLogin, datacenter->getDatacenterId(), ConnectionTypeGeneric, true); |
| 3499 | } else { |
| 3500 | authorizedOnMovingDatacenter(); |
| 3501 | } |
| 3502 | } |
| 3503 |
| 3504 | void ConnectionsManager::authorizedOnMovingDatacenter() { |
| 3505 | movingAuthorization.reset(); |
| 3506 | currentDatacenterId = movingToDatacenterId; |
| 3507 | movingToDatacenterId = DEFAULT_DATACENTER_ID; |
| 3508 | saveConfig(); |
| 3509 | scheduleTask([&] { |
| 3510 | processRequestQueue(0, 0); |
| 3511 | }); |
| 3512 | } |
| 3513 |
| 3514 | void ConnectionsManager::applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port) { |
| 3515 | scheduleTask([&, datacenterId, ipAddress, port] { |
| 3516 | Datacenter *datacenter = getDatacenterWithId(datacenterId); |
| 3517 | if (datacenter != nullptr) { |
| 3518 | std::vector<TcpAddress> addresses; |
| 3519 | addresses.emplace_back(ipAddress, port, 0, ""); |
| 3520 | datacenter->suspendConnections(true); |
| 3521 | datacenter->replaceAddresses(addresses, 0); |
| 3522 | datacenter->resetAddressAndPortNum(); |
| 3523 | saveConfig(); |
| 3524 | if (datacenter->isHandshakingAny()) { |
| 3525 | datacenter->beginHandshake(HandshakeTypeCurrent, true); |
| 3526 | } |
| 3527 | updateDcSettings(datacenterId, false, false); |
| 3528 | } |
| 3529 | }); |
| 3530 | } |
| 3531 |
| 3532 | ConnectionState ConnectionsManager::getConnectionState() { |
| 3533 | return connectionState; |
| 3534 | } |
| 3535 |
| 3536 | void ConnectionsManager::setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate) { |
| 3537 | delegate = connectiosManagerDelegate; |
| 3538 | } |
| 3539 |
| 3540 | void ConnectionsManager::setPushConnectionEnabled(bool value) { |
| 3541 | pushConnectionEnabled = value; |
| 3542 | Datacenter *datacenter = getDatacenterWithId(currentDatacenterId); |
| 3543 | if (datacenter != nullptr) { |
| 3544 | if (!pushConnectionEnabled) { |
| 3545 | Connection *connection = datacenter->getPushConnection(false); |
| 3546 | if (connection != nullptr) { |
| 3547 | connection->suspendConnection(); |
| 3548 | } |
| 3549 | } else { |
| 3550 | datacenter->createPushConnection()->setSessionId(pushSessionId); |
| 3551 | sendPing(datacenter, true); |
| 3552 | } |
| 3553 | } |
| 3554 | } |
| 3555 |
| 3556 | inline bool checkPhoneByPrefixesRules(std::string phone, std::string rules) { |
| 3557 | if (rules.empty() || phone.empty()) { |
| 3558 | return true; |
| 3559 | } |
| 3560 | bool found = false; |
| 3561 |
| 3562 | std::stringstream ss(rules); |
| 3563 | std::string prefix; |
| 3564 | while (std::getline(ss, prefix, ',')) { |
| 3565 | if (prefix.empty()) { |
| 3566 | found = true; |
| 3567 | } else if (prefix[0] == '+' && phone.find(prefix.substr(1)) == 0) { |
| 3568 | found = true; |
| 3569 | } else if (prefix[0] == '-' && phone.find(prefix.substr(1)) == 0) { |
| 3570 | return false; |
| 3571 | } |
| 3572 | } |
| 3573 | return found; |
| 3574 | } |
| 3575 |
| 3576 | void ConnectionsManager::applyDnsConfig(NativeByteBuffer *buffer, std::string phone, int32_t date) { |
| 3577 | scheduleTask([&, buffer, phone, date] { |
| 3578 | int32_t realDate = date; |
| 3579 | if (LOGS_ENABLED) DEBUG_D("trying to decrypt config %d", requestingSecondAddress); |
| 3580 | TL_help_configSimple *config = Datacenter::decodeSimpleConfig(buffer); |
| 3581 | if (config != nullptr && realDate == 0) { |
| 3582 | realDate = config->date; |
| 3583 | } |
| 3584 | int currentDate = getCurrentTime(); |
| 3585 | if (config != nullptr && config->date <= currentDate && currentDate <= config->expires) { |
| 3586 | if (realDate > 0 && requestingSecondAddressByTlsHashMismatch) { |
| 3587 | timeDifference += (realDate - currentDate); |
| 3588 | requestingSecondAddressByTlsHashMismatch = false; |
| 3589 | } |
| 3590 | for (auto & iter : config->rules) { |
| 3591 | TL_accessPointRule *rule = iter.get(); |
| 3592 | if (!checkPhoneByPrefixesRules(phone, rule->phone_prefix_rules)) { |
| 3593 | continue; |
| 3594 | } |
| 3595 | Datacenter *datacenter = getDatacenterWithId(rule->dc_id); |
| 3596 | if (datacenter != nullptr) { |
| 3597 | std::vector<TcpAddress> addresses; |
| 3598 | for (auto iter2 = rule->ips.begin(); iter2 != rule->ips.end(); iter2++) { |
| 3599 | IpPort *port = iter2->get(); |
| 3600 | const std::type_info &typeInfo = typeid(*port); |
| 3601 | if (typeInfo == typeid(TL_ipPort)) { |
| 3602 | auto ipPort = (TL_ipPort *) port; |
| 3603 | addresses.emplace_back(ipPort->ipv4, ipPort->port, 0, ""); |
| 3604 | if (LOGS_ENABLED) DEBUG_D("got address %s and port %d for dc%d", ipPort->ipv4.c_str(), ipPort->port, rule->dc_id); |
| 3605 | } else if (typeInfo == typeid(TL_ipPortSecret)) { |
| 3606 | auto ipPort = (TL_ipPortSecret *) port; |
| 3607 | addresses.emplace_back(ipPort->ipv4, ipPort->port, 0, std::string((const char *) ipPort->secret->bytes, ipPort->secret->length)); |
| 3608 | if (LOGS_ENABLED) DEBUG_D("got address %s and port %d for dc%d with secret", ipPort->ipv4.c_str(), ipPort->port, rule->dc_id); |
| 3609 | } |
| 3610 | } |
| 3611 | if (!addresses.empty()) { |
| 3612 | datacenter->replaceAddresses(addresses, TcpAddressFlagTemp); |
| 3613 | Connection *connection = datacenter->getTempConnection(false); |
| 3614 | if (connection != nullptr) { |
| 3615 | connection->suspendConnection(); |
| 3616 | } |
| 3617 | if (datacenter->isHandshakingAny()) { |
| 3618 | datacenter->beginHandshake(HandshakeTypeCurrent, true); |
| 3619 | } |
| 3620 | updateDcSettings(rule->dc_id, true, false); |
| 3621 | } |
| 3622 | } else { |
| 3623 | if (LOGS_ENABLED) DEBUG_D("config datacenter %d not found", rule->dc_id); |
| 3624 | } |
| 3625 | } |
| 3626 | delete config; |
| 3627 | } else { |
| 3628 | if (config == nullptr) { |
| 3629 | if (LOGS_ENABLED) DEBUG_D("can't decrypt dns config"); |
| 3630 | } else { |
| 3631 | delete config; |
| 3632 | if (LOGS_ENABLED) DEBUG_D("dns config not valid due to date or expire, current date = %d, config date = %d, config expired = %d", currentDate, config->date, config->expires); |
| 3633 | } |
| 3634 | if (requestingSecondAddress == 1) { |
| 3635 | requestingSecondAddress = 2; |
| 3636 | delegate->onRequestNewServerIpAndPort(requestingSecondAddress, instanceNum); |
| 3637 | } else if (requestingSecondAddress == 0) { |
| 3638 | requestingSecondAddress = 1; |
| 3639 | delegate->onRequestNewServerIpAndPort(requestingSecondAddress, instanceNum); |
| 3640 | } else { |
| 3641 | requestingSecondAddress = 0; |
| 3642 | } |
| 3643 | } |
| 3644 | buffer->reuse(); |
| 3645 | }); |
| 3646 | } |
| 3647 |
| 3648 | void ConnectionsManager::init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerpting, std::string installerId, std::string packageId, int32_t timezoneOffset, int64_t userId, bool userPremium, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType, int32_t performanceClass) { |
| 3649 | currentVersion = version; |
| 3650 | currentLayer = layer; |
| 3651 | currentApiId = apiId; |
| 3652 | currentConfigPath = configPath; |
| 3653 | currentDeviceModel = deviceModel; |
| 3654 | currentSystemVersion = systemVersion; |
| 3655 | currentAppVersion = appVersion; |
| 3656 | currentLangCode = langCode; |
| 3657 | currentRegId = regId; |
| 3658 | certFingerprint = cFingerpting; |
| 3659 | installer = installerId; |
| 3660 | package = packageId; |
| 3661 | currentDeviceTimezone = timezoneOffset; |
| 3662 | currentSystemLangCode = systemLangCode; |
| 3663 | currentUserId = userId; |
| 3664 | currentUserPremium = userPremium; |
| 3665 | currentLogPath = logPath; |
| 3666 | pushConnectionEnabled = enablePushConnection; |
| 3667 | currentNetworkType = networkType; |
| 3668 | networkAvailable = hasNetwork; |
| 3669 | currentPerformanceClass = performanceClass; |
| 3670 | if (isPaused) { |
| 3671 | lastPauseTime = getCurrentTimeMonotonicMillis(); |
| 3672 | } |
| 3673 |
| 3674 | if (!currentConfigPath.empty() && currentConfigPath.find_last_of('/') != currentConfigPath.size() - 1) { |
| 3675 | currentConfigPath += "/"; |
| 3676 | } |
| 3677 |
| 3678 | if (!logPath.empty()) { |
| 3679 | LOGS_ENABLED = true; |
| 3680 | FileLog::getInstance().init(logPath); |
| 3681 | } |
| 3682 |
| 3683 | loadConfig(); |
| 3684 |
| 3685 | bool needLoadConfig = false; |
| 3686 | if (systemLangCode.compare(lastInitSystemLangcode) != 0) { |
| 3687 | lastInitSystemLangcode = systemLangCode; |
| 3688 | for (auto & datacenter : datacenters) { |
| 3689 | datacenter.second->resetInitVersion(); |
| 3690 | } |
| 3691 | needLoadConfig = true; |
| 3692 | saveConfig(); |
| 3693 | } |
| 3694 | if (!needLoadConfig && currentUserId != 0) { |
| 3695 | Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID); |
| 3696 | if (datacenter != nullptr && datacenter->lastInitVersion != currentVersion) { |
| 3697 | needLoadConfig = true; |
| 3698 | } |
| 3699 | } |
| 3700 |
| 3701 | pthread_create(&networkThread, nullptr, (ConnectionsManager::ThreadProc), this); |
| 3702 |
| 3703 | if (needLoadConfig) { |
| 3704 | updateDcSettings(0, false, false); |
| 3705 | } |
| 3706 | } |
| 3707 |
| 3708 | void ConnectionsManager::setProxySettings(std::string address, uint16_t port, std::string username, std::string password, std::string secret) { |
| 3709 | scheduleTask([&, address, port, username, password, secret] { |
| 3710 | std::string newSecret = decodeSecret(secret); |
| 3711 | bool secretChanged = proxySecret != newSecret; |
| 3712 | bool reconnect = proxyAddress != address || proxyPort != port || username != proxyUser || proxyPassword != password || secretChanged; |
| 3713 | proxyAddress = address; |
| 3714 | proxyPort = port; |
| 3715 | proxyUser = username; |
| 3716 | proxyPassword = password; |
| 3717 | proxySecret = std::move(newSecret); |
| 3718 | if (!proxyAddress.empty() && connectionState == ConnectionStateConnecting) { |
| 3719 | connectionState = ConnectionStateConnectingViaProxy; |
| 3720 | if (delegate != nullptr) { |
| 3721 | delegate->onConnectionStateChanged(connectionState, instanceNum); |
| 3722 | } |
| 3723 | } else if (proxyAddress.empty() && connectionState == ConnectionStateConnectingViaProxy) { |
| 3724 | connectionState = ConnectionStateConnecting; |
| 3725 | if (delegate != nullptr) { |
| 3726 | delegate->onConnectionStateChanged(connectionState, instanceNum); |
| 3727 | } |
| 3728 | } |
| 3729 | if (secretChanged) { |
| 3730 | Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID); |
| 3731 | if (datacenter != nullptr) { |
| 3732 | datacenter->resetInitVersion(); |
| 3733 | } |
| 3734 | } |
| 3735 | if (reconnect) { |
| 3736 | for (auto & datacenter : datacenters) { |
| 3737 | datacenter.second->suspendConnections(true); |
| 3738 | } |
| 3739 | Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID); |
| 3740 | if (datacenter != nullptr && datacenter->isHandshakingAny()) { |
| 3741 | datacenter->beginHandshake(HandshakeTypeCurrent, true); |
| 3742 | } |
| 3743 | processRequestQueue(0, 0); |
| 3744 | } |
| 3745 | }); |
| 3746 | } |
| 3747 |
| 3748 | void ConnectionsManager::setLangCode(std::string langCode) { |
| 3749 | scheduleTask([&, langCode] { |
| 3750 | if (currentLangCode == langCode) { |
| 3751 | return; |
| 3752 | } |
| 3753 | currentLangCode = langCode; |
| 3754 | for (auto & datacenter : datacenters) { |
| 3755 | datacenter.second->resetInitVersion(); |
| 3756 | } |
| 3757 | saveConfig(); |
| 3758 | }); |
| 3759 | } |
| 3760 |
| 3761 | void ConnectionsManager::setRegId(std::string regId) { |
| 3762 | scheduleTask([&, regId] { |
| 3763 | if (currentRegId == regId) { |
| 3764 | return; |
| 3765 | } |
| 3766 | currentRegId = regId; |
| 3767 | for (auto & datacenter : datacenters) { |
| 3768 | datacenter.second->resetInitVersion(); |
| 3769 | } |
| 3770 | updateDcSettings(0, false, true); |
| 3771 | saveConfig(); |
| 3772 | }); |
| 3773 | } |
| 3774 |
| 3775 | void ConnectionsManager::setSystemLangCode(std::string langCode) { |
| 3776 | scheduleTask([&, langCode] { |
| 3777 | if (currentSystemLangCode == langCode) { |
| 3778 | return; |
| 3779 | } |
| 3780 | lastInitSystemLangcode = currentSystemLangCode = langCode; |
| 3781 | for (auto & datacenter : datacenters) { |
| 3782 | datacenter.second->resetInitVersion(); |
| 3783 | } |
| 3784 | saveConfig(); |
| 3785 | updateDcSettings(0, false, false); |
| 3786 | }); |
| 3787 | } |
| 3788 |
| 3789 | void ConnectionsManager::resumeNetwork(bool partial) { |
| 3790 | scheduleTask([&, partial] { |
| 3791 | if (lastMonotonicPauseTime != 0) { |
| 3792 | int64_t diff = (getCurrentTimeMonotonicMillis() - lastMonotonicPauseTime) / 1000; |
| 3793 | int64_t systemDiff = getCurrentTime() - lastSystemPauseTime; |
| 3794 | if (systemDiff < 0 || abs(systemDiff - diff) > 2) { |
| 3795 | timeDifference -= (systemDiff - diff); |
| 3796 | } |
| 3797 | } |
| 3798 | if (partial) { |
| 3799 | if (networkPaused) { |
| 3800 | lastMonotonicPauseTime = lastPauseTime = getCurrentTimeMonotonicMillis(); |
| 3801 | lastSystemPauseTime = getCurrentTime(); |
| 3802 | networkPaused = false; |
| 3803 | if (LOGS_ENABLED) DEBUG_D("wakeup network in background account%u", instanceNum); |
| 3804 | } else if (lastPauseTime != 0) { |
| 3805 | lastMonotonicPauseTime = lastPauseTime = getCurrentTimeMonotonicMillis(); |
| 3806 | lastSystemPauseTime = getCurrentTime(); |
| 3807 | networkPaused = false; |
| 3808 | if (LOGS_ENABLED) DEBUG_D("reset sleep timeout account%u", instanceNum); |
| 3809 | } |
| 3810 | } else { |
| 3811 | lastPauseTime = 0; |
| 3812 | lastMonotonicPauseTime = 0; |
| 3813 | lastSystemPauseTime = 0; |
| 3814 | networkPaused = false; |
| 3815 | if (LOGS_ENABLED) DEBUG_D("wakeup network account%u", instanceNum); |
| 3816 | } |
| 3817 | if (!networkPaused) { |
| 3818 | for (auto & datacenter : datacenters) { |
| 3819 | if (datacenter.second->isHandshaking(false)) { |
| 3820 | datacenter.second->createGenericConnection()->connect(); |
| 3821 | } else if (datacenter.second->isHandshaking(true)) { |
| 3822 | datacenter.second->createGenericMediaConnection()->connect(); |
| 3823 | } |
| 3824 | } |
| 3825 | } |
| 3826 | }); |
| 3827 | } |
| 3828 |
| 3829 | void ConnectionsManager::pauseNetwork() { |
| 3830 | if (lastPauseTime != 0) { |
| 3831 | return; |
| 3832 | } |
| 3833 | lastMonotonicPauseTime = lastPauseTime = getCurrentTimeMonotonicMillis(); |
| 3834 | lastSystemPauseTime = getCurrentTime(); |
| 3835 | saveConfig(); |
| 3836 | } |
| 3837 |
| 3838 | void ConnectionsManager::setNetworkAvailable(bool value, int32_t type, bool slow) { |
| 3839 | scheduleTask([&, value, type, slow] { |
| 3840 | networkAvailable = value; |
| 3841 | currentNetworkType = type; |
| 3842 | networkSlow = slow; |
| 3843 | if (!networkAvailable) { |
| 3844 | connectionState = ConnectionStateWaitingForNetwork; |
| 3845 | } else { |
| 3846 | for (auto & datacenter : datacenters) { |
| 3847 | if (datacenter.second->isHandshaking(false)) { |
| 3848 | datacenter.second->createGenericConnection()->connect(); |
| 3849 | } else if (datacenter.second->isHandshaking(true)) { |
| 3850 | datacenter.second->createGenericMediaConnection()->connect(); |
| 3851 | } |
| 3852 | } |
| 3853 | } |
| 3854 | if (delegate != nullptr) { |
| 3855 | delegate->onConnectionStateChanged(connectionState, instanceNum); |
| 3856 | } |
| 3857 | }); |
| 3858 | } |
| 3859 |
| 3860 | void ConnectionsManager::setIpStrategy(uint8_t value) { |
| 3861 | scheduleTask([&, value] { |
| 3862 | lastProtocolUsefullData = false; |
| 3863 | ipStrategy = value; |
| 3864 | }); |
| 3865 | } |
| 3866 |
| 3867 | int64_t ConnectionsManager::checkProxy(std::string address, uint16_t port, std::string username, std::string password, std::string secret, onRequestTimeFunc requestTimeFunc, jobject ptr1) { |
| 3868 | auto proxyCheckInfo = new ProxyCheckInfo(); |
| 3869 | proxyCheckInfo->address = address; |
| 3870 | proxyCheckInfo->port = port; |
| 3871 | proxyCheckInfo->username = username; |
| 3872 | proxyCheckInfo->password = password; |
| 3873 | proxyCheckInfo->secret = decodeSecret(secret); |
| 3874 | proxyCheckInfo->onRequestTime = requestTimeFunc; |
| 3875 | proxyCheckInfo->pingId = ++lastPingProxyId; |
| 3876 | proxyCheckInfo->instanceNum = instanceNum; |
| 3877 | proxyCheckInfo->ptr1 = ptr1; |
| 3878 |
| 3879 | scheduleCheckProxyInternal(proxyCheckInfo); |
| 3880 |
| 3881 | return proxyCheckInfo->pingId; |
| 3882 | } |
| 3883 |
| 3884 | void ConnectionsManager::scheduleCheckProxyInternal(ProxyCheckInfo *proxyCheckInfo) { |
| 3885 | scheduleTask([&, proxyCheckInfo] { |
| 3886 | checkProxyInternal(proxyCheckInfo); |
| 3887 | }); |
| 3888 | } |
| 3889 |
| 3890 | void ConnectionsManager::checkProxyInternal(ProxyCheckInfo *proxyCheckInfo) { |
| 3891 | int32_t freeConnectionNum = -1; |
| 3892 | if (proxyActiveChecks.size() != PROXY_CONNECTIONS_COUNT) { |
| 3893 | for (int32_t a = 0; a < PROXY_CONNECTIONS_COUNT; a++) { |
| 3894 | bool found = false; |
| 3895 | for (auto & proxyActiveCheck : proxyActiveChecks) { |
| 3896 | if (proxyActiveCheck.get()->connectionNum == a) { |
| 3897 | found = true; |
| 3898 | break; |
| 3899 | } |
| 3900 | } |
| 3901 | if (!found) { |
| 3902 | freeConnectionNum = a; |
| 3903 | break; |
| 3904 | } |
| 3905 | } |
| 3906 | } |
| 3907 | if (freeConnectionNum == -1) { |
| 3908 | proxyCheckQueue.push_back(std::unique_ptr<ProxyCheckInfo>(proxyCheckInfo)); |
| 3909 | } else { |
| 3910 | auto connectionType = (ConnectionType) (ConnectionTypeProxy | (freeConnectionNum << 16)); |
| 3911 | Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID); |
| 3912 | Connection *connection = datacenter->getProxyConnection((uint8_t) freeConnectionNum, true, false); |
| 3913 | if (connection != nullptr) { |
| 3914 | connection->setOverrideProxy(proxyCheckInfo->address, proxyCheckInfo->port, proxyCheckInfo->username, proxyCheckInfo->password, proxyCheckInfo->secret); |
| 3915 | connection->suspendConnection(); |
| 3916 | proxyCheckInfo->connectionNum = freeConnectionNum; |
| 3917 | auto request = new TL_ping(); |
| 3918 | request->ping_id = proxyCheckInfo->pingId; |
| 3919 | proxyCheckInfo->requestToken = sendRequest(request, nullptr, nullptr, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin, DEFAULT_DATACENTER_ID, connectionType, true, 0); |
| 3920 | proxyActiveChecks.push_back(std::unique_ptr<ProxyCheckInfo>(proxyCheckInfo)); |
| 3921 | } else if (PFS_ENABLED) { |
| 3922 | if (datacenter->isHandshaking(false)) { |
| 3923 | datacenter->beginHandshake(HandshakeTypeTemp, false); |
| 3924 | } |
| 3925 | proxyCheckQueue.push_back(std::unique_ptr<ProxyCheckInfo>(proxyCheckInfo)); |
| 3926 | } |
| 3927 | } |
| 3928 | } |
| 3929 |
| 3930 | #ifdef ANDROID |
| 3931 | void ConnectionsManager::useJavaVM(JavaVM *vm, bool useJavaByteBuffers) { |
| 3932 | javaVm = vm; |
| 3933 | if (useJavaByteBuffers) { |
| 3934 | JNIEnv *env = nullptr; |
| 3935 | if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { |
| 3936 | if (LOGS_ENABLED) DEBUG_E("can't get jnienv"); |
| 3937 | exit(1); |
| 3938 | } |
| 3939 | DEBUG_REF("connectionsmanager byte buffer"); |
| 3940 | jclass_ByteBuffer = (jclass) env->NewGlobalRef(env->FindClass("java/nio/ByteBuffer")); |
| 3941 | if (jclass_ByteBuffer == nullptr) { |
| 3942 | if (LOGS_ENABLED) DEBUG_E("can't find java ByteBuffer class"); |
| 3943 | exit(1); |
| 3944 | } |
| 3945 | jclass_ByteBuffer_allocateDirect = env->GetStaticMethodID(jclass_ByteBuffer, "allocateDirect", "(I)Ljava/nio/ByteBuffer;"); |
| 3946 | if (jclass_ByteBuffer_allocateDirect == nullptr) { |
| 3947 | if (LOGS_ENABLED) DEBUG_E("can't find java ByteBuffer allocateDirect"); |
| 3948 | exit(1); |
| 3949 | } |
| 3950 | if (LOGS_ENABLED) DEBUG_D("using java ByteBuffer"); |
| 3951 | } |
| 3952 | } |
| 3953 |
| 3954 | void ConnectionsManager::reconnect(int32_t dcId, int32_t connectionType) { |
| 3955 | scheduleTask([&, dcId, connectionType] { |
| 3956 | scheduleTask([&, dcId, connectionType] { |
| 3957 | Datacenter *datacenter = getDatacenterWithId(dcId); |
| 3958 | if (datacenter != nullptr) { |
| 3959 | Connection *connection = datacenter->getConnectionByType(connectionType, false, |
| 3960 | 0); |
| 3961 | if (connection != nullptr) { |
| 3962 | if (LOGS_ENABLED) DEBUG_D("discard connection dcId=%d connectionType=%d", dcId, |
| 3963 | connectionType); |
| 3964 | connection->suspendConnection(true); |
| 3965 | } |
| 3966 | } |
| 3967 | }); |
| 3968 | }); |
| 3969 | } |
| 3970 |
| 3971 | #endif |
| 3972 |