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