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