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