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