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