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