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