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