Telegram-Android/TMessagesProj/jni/tgnet/ConnectionsManager.cpp

3919 lines
177 KiB
C++
Raw Permalink Normal View History

2015-09-24 22:52:02 +02:00
/*
2018-07-30 04:07:02 +02:00
* This is the source code of tgnet library v. 1.1
2015-09-24 22:52:02 +02:00
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
2018-07-30 04:07:02 +02:00
* Copyright Nikolai Kudashov, 2015-2018.
2015-09-24 22:52:02 +02:00
*/
2021-06-25 02:43:10 +02:00
#include <cassert>
#include <cstdlib>
2015-09-24 22:52:02 +02:00
#include <sys/eventfd.h>
#include <unistd.h>
#include <chrono>
#include <algorithm>
#include <fcntl.h>
#include <memory.h>
#include <openssl/rand.h>
#include <zlib.h>
2021-07-15 16:24:57 +02:00
#include <memory>
2018-07-30 04:07:02 +02:00
#include <string>
2021-06-25 02:43:10 +02:00
#include <cinttypes>
2015-09-24 22:52:02 +02:00
#include "ConnectionsManager.h"
#include "FileLog.h"
#include "EventObject.h"
#include "MTProtoScheme.h"
2016-10-11 13:57:01 +02:00
#include "ApiScheme.h"
2015-09-24 22:52:02 +02:00
#include "NativeByteBuffer.h"
#include "Connection.h"
#include "Datacenter.h"
#include "Request.h"
#include "BuffersStorage.h"
#include "ByteArray.h"
#include "Config.h"
2018-07-30 04:07:02 +02:00
#include "ProxyCheckInfo.h"
2022-09-16 20:48:21 +02:00
#include "Handshake.h"
2015-09-24 22:52:02 +02:00
#ifdef ANDROID
#include <jni.h>
JavaVM *javaVm = nullptr;
2018-07-30 04:07:02 +02:00
JNIEnv *jniEnv[MAX_ACCOUNT_COUNT];
2015-09-24 22:52:02 +02:00
jclass jclass_ByteBuffer = nullptr;
2021-07-15 16:24:57 +02:00
jmethodID jclass_ByteBuffer_allocateDirect = nullptr;
2015-09-24 22:52:02 +02:00
#endif
static bool done = false;
2018-07-30 04:07:02 +02:00
ConnectionsManager::ConnectionsManager(int32_t instance) {
instanceNum = instance;
if ((epolFd = epoll_create(128)) == -1) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("unable to create epoll instance");
2015-09-24 22:52:02 +02:00
exit(1);
}
int flags;
if ((flags = fcntl(epolFd, F_GETFD, NULL)) < 0) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_W("fcntl(%d, F_GETFD)", epolFd);
2015-09-24 22:52:02 +02:00
}
if (!(flags & FD_CLOEXEC)) {
if (fcntl(epolFd, F_SETFD, flags | FD_CLOEXEC) == -1) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_W("fcntl(%d, F_SETFD)", epolFd);
2015-09-24 22:52:02 +02:00
}
}
if ((epollEvents = new epoll_event[128]) == nullptr) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("unable to allocate epoll events");
2015-09-24 22:52:02 +02:00
exit(1);
}
2016-10-11 13:57:01 +02:00
eventFd = eventfd(0, EFD_NONBLOCK);
if (eventFd != -1) {
struct epoll_event event = {0};
event.data.ptr = new EventObject(&eventFd, EventObjectTypeEvent);
event.events = EPOLLIN | EPOLLET;
if (epoll_ctl(epolFd, EPOLL_CTL_ADD, eventFd, &event) == -1) {
eventFd = -1;
FileLog::e("unable to add eventfd");
}
}
2016-10-11 13:57:01 +02:00
if (eventFd == -1) {
pipeFd = new int[2];
if (pipe(pipeFd) != 0) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("unable to create pipe");
2016-10-11 13:57:01 +02:00
exit(1);
}
flags = fcntl(pipeFd[0], F_GETFL);
if (flags == -1) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("fcntl get pipefds[0] failed");
2016-10-11 13:57:01 +02:00
exit(1);
}
if (fcntl(pipeFd[0], F_SETFL, flags | O_NONBLOCK) == -1) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("fcntl set pipefds[0] failed");
2016-10-11 13:57:01 +02:00
exit(1);
}
2016-10-11 13:57:01 +02:00
flags = fcntl(pipeFd[1], F_GETFL);
if (flags == -1) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("fcntl get pipefds[1] failed");
2016-10-11 13:57:01 +02:00
exit(1);
}
if (fcntl(pipeFd[1], F_SETFL, flags | O_NONBLOCK) == -1) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("fcntl set pipefds[1] failed");
2016-10-11 13:57:01 +02:00
exit(1);
}
2021-07-15 16:24:57 +02:00
auto eventObject = new EventObject(pipeFd, EventObjectTypePipe);
2016-10-11 13:57:01 +02:00
epoll_event eventMask = {};
eventMask.events = EPOLLIN;
eventMask.data.ptr = eventObject;
if (epoll_ctl(epolFd, EPOLL_CTL_ADD, pipeFd[0], &eventMask) != 0) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("can't add pipe to epoll");
2016-10-11 13:57:01 +02:00
exit(1);
}
}
2015-09-24 22:52:02 +02:00
2018-07-30 04:07:02 +02:00
sizeCalculator = new NativeByteBuffer(true);
2015-09-24 22:52:02 +02:00
networkBuffer = new NativeByteBuffer((uint32_t) READ_BUFFER_SIZE);
if (networkBuffer == nullptr) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("unable to allocate read buffer");
2015-09-24 22:52:02 +02:00
exit(1);
}
2021-07-15 16:24:57 +02:00
pthread_mutex_init(&mutex, nullptr);
2015-09-24 22:52:02 +02:00
}
ConnectionsManager::~ConnectionsManager() {
if (epolFd != 0) {
close(epolFd);
epolFd = 0;
}
if (pipeFd != nullptr) {
delete[] pipeFd;
pipeFd = nullptr;
}
2015-09-24 22:52:02 +02:00
pthread_mutex_destroy(&mutex);
}
2018-07-30 04:07:02 +02:00
ConnectionsManager& ConnectionsManager::getInstance(int32_t instanceNum) {
switch (instanceNum) {
case 0:
static ConnectionsManager instance0(0);
return instance0;
case 1:
static ConnectionsManager instance1(1);
return instance1;
case 2:
static ConnectionsManager instance2(2);
return instance2;
2022-06-21 04:51:00 +02:00
case 3:
static ConnectionsManager instance3(3);
return instance3;
case 4:
default:
static ConnectionsManager instance4(4);
return instance4;
2018-07-30 04:07:02 +02:00
}
2015-09-24 22:52:02 +02:00
}
int ConnectionsManager::callEvents(int64_t now) {
if (!events.empty()) {
2021-07-15 16:24:57 +02:00
for (auto iter = events.begin(); iter != events.end();) {
2015-09-24 22:52:02 +02:00
EventObject *eventObject = (*iter);
if (eventObject->time <= now) {
iter = events.erase(iter);
eventObject->onEvent(0);
} else {
int diff = (int) (eventObject->time - now);
2017-03-31 01:58:05 +02:00
return diff > 1000 || diff < 0 ? 1000 : diff;
2015-09-24 22:52:02 +02:00
}
}
}
if (!networkPaused) {
return 1000;
}
2021-07-15 16:24:57 +02:00
auto timeToPushPing = (int32_t) ((sendingPushPing ? 30000 : nextPingTimeOffset) - llabs(now - lastPushPingTime));
2015-09-24 22:52:02 +02:00
if (timeToPushPing <= 0) {
return 1000;
}
return timeToPushPing;
}
void ConnectionsManager::checkPendingTasks() {
2019-05-14 14:08:05 +02:00
int32_t count = INT_MAX;
2015-09-24 22:52:02 +02:00
while (true) {
std::function<void()> task;
pthread_mutex_lock(&mutex);
2019-05-14 14:08:05 +02:00
if (pendingTasks.empty() || count <= 0) {
2015-09-24 22:52:02 +02:00
pthread_mutex_unlock(&mutex);
return;
}
2019-05-14 14:08:05 +02:00
if (count == INT_MAX) {
count = (int32_t) pendingTasks.size();
} else {
count--;
}
2015-09-24 22:52:02 +02:00
task = pendingTasks.front();
pendingTasks.pop();
pthread_mutex_unlock(&mutex);
task();
}
}
void ConnectionsManager::select() {
checkPendingTasks();
2017-03-31 01:58:05 +02:00
int eventsCount = epoll_wait(epolFd, epollEvents, 128, callEvents(getCurrentTimeMonotonicMillis()));
2015-09-24 22:52:02 +02:00
checkPendingTasks();
2017-03-31 01:58:05 +02:00
int64_t now = getCurrentTimeMonotonicMillis();
2015-09-24 22:52:02 +02:00
callEvents(now);
for (int32_t a = 0; a < eventsCount; a++) {
2021-07-15 16:24:57 +02:00
auto eventObject = (EventObject *) epollEvents[a].data.ptr;
2015-09-24 22:52:02 +02:00
eventObject->onEvent(epollEvents[a].events);
}
2020-01-23 13:58:50 +01:00
activeConnectionsCopy.resize(activeConnections.size());
std::copy(std::begin(activeConnections), std::end(activeConnections), std::begin(activeConnectionsCopy));
for (auto connection : activeConnectionsCopy) {
connection->checkTimeout(now);
2015-09-24 22:52:02 +02:00
}
Datacenter *datacenter = getDatacenterWithId(currentDatacenterId);
2016-04-22 15:49:00 +02:00
if (pushConnectionEnabled) {
2019-05-14 14:08:05 +02:00
if ((sendingPushPing && llabs(now - lastPushPingTime) >= 30000) || llabs(now - lastPushPingTime) >= nextPingTimeOffset + 10000) {
2016-04-22 15:49:00 +02:00
lastPushPingTime = 0;
sendingPushPing = false;
if (datacenter != nullptr) {
Connection *connection = datacenter->getPushConnection(false);
if (connection != nullptr) {
connection->suspendConnection();
}
2015-09-24 22:52:02 +02:00
}
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("push ping timeout");
2015-09-24 22:52:02 +02:00
}
2019-05-14 14:08:05 +02:00
if (llabs(now - lastPushPingTime) >= nextPingTimeOffset) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("time for push ping");
2016-04-22 15:49:00 +02:00
lastPushPingTime = now;
2019-05-14 14:08:05 +02:00
uint8_t offset;
RAND_bytes(&offset, 1);
nextPingTimeOffset = 60000 * 3 + (offset % 40) - 20;
2016-04-22 15:49:00 +02:00
if (datacenter != nullptr) {
sendPing(datacenter, true);
}
2015-09-24 22:52:02 +02:00
}
}
2017-03-31 01:58:05 +02:00
if (lastPauseTime != 0 && llabs(now - lastPauseTime) >= nextSleepTimeout) {
2015-09-24 22:52:02 +02:00
bool dontSleep = !requestingSaltsForDc.empty();
if (!dontSleep) {
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2015-09-24 22:52:02 +02:00
if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) {
dontSleep = true;
break;
}
}
}
if (!dontSleep) {
2021-07-15 16:24:57 +02:00
for (auto & iter : requestsQueue) {
Request *request = iter.get();
2015-09-24 22:52:02 +02:00
if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) {
dontSleep = true;
break;
}
}
}
if (!dontSleep) {
if (!networkPaused) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("pausing network and timers by sleep time = %d", nextSleepTimeout);
2021-07-15 16:24:57 +02:00
for (auto & dc : datacenters) {
dc.second->suspendConnections(false);
2015-09-24 22:52:02 +02:00
}
}
networkPaused = true;
return;
} else {
lastPauseTime = now;
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("don't sleep because of salt, upload or download request");
2015-09-24 22:52:02 +02:00
}
}
if (networkPaused) {
networkPaused = false;
2021-07-15 16:24:57 +02:00
for (auto & dc : datacenters) {
if (dc.second->isHandshaking(false)) {
dc.second->createGenericConnection()->connect();
} else if (dc.second->isHandshaking(true)) {
dc.second->createGenericMediaConnection()->connect();
2019-12-31 14:08:08 +01:00
}
}
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("resume network and timers");
2015-09-24 22:52:02 +02:00
}
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onUpdate(instanceNum);
2015-09-24 22:52:02 +02:00
}
if (datacenter != nullptr) {
2018-07-30 04:07:02 +02:00
if (datacenter->hasAuthKey(ConnectionTypeGeneric, 1)) {
2021-03-19 11:25:58 +01:00
if (llabs(now - lastPingTime) >= (testBackend ? 2000 : 19000)) {
2015-09-24 22:52:02 +02:00
lastPingTime = now;
sendPing(datacenter, false);
}
if (abs((int32_t) (now / 1000) - lastDcUpdateTime) >= DC_UPDATE_TIME) {
2023-05-04 14:25:48 +02:00
updateDcSettings(0, false, false);
2015-09-24 22:52:02 +02:00
}
processRequestQueue(0, 0);
2018-07-30 04:07:02 +02:00
} else if (!datacenter->isHandshakingAny()) {
datacenter->beginHandshake(HandshakeTypeAll, true);
2015-09-24 22:52:02 +02:00
}
}
}
void ConnectionsManager::scheduleTask(std::function<void()> task) {
pthread_mutex_lock(&mutex);
pendingTasks.push(task);
pthread_mutex_unlock(&mutex);
wakeup();
}
void ConnectionsManager::scheduleEvent(EventObject *eventObject, uint32_t time) {
2017-03-31 01:58:05 +02:00
eventObject->time = getCurrentTimeMonotonicMillis() + time;
2015-09-24 22:52:02 +02:00
std::list<EventObject *>::iterator iter;
for (iter = events.begin(); iter != events.end(); iter++) {
if ((*iter)->time > eventObject->time) {
break;
}
}
events.insert(iter, eventObject);
}
void ConnectionsManager::removeEvent(EventObject *eventObject) {
2021-07-15 16:24:57 +02:00
for (auto iter = events.begin(); iter != events.end(); iter++) {
2015-09-24 22:52:02 +02:00
if (*iter == eventObject) {
events.erase(iter);
break;
}
}
}
void ConnectionsManager::wakeup() {
2016-10-11 13:57:01 +02:00
if (pipeFd == nullptr) {
eventfd_write(eventFd, 1);
} else {
char ch = 'x';
write(pipeFd[1], &ch, 1);
}
2015-09-24 22:52:02 +02:00
}
void *ConnectionsManager::ThreadProc(void *data) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("network thread started");
2021-07-15 16:24:57 +02:00
auto networkManager = (ConnectionsManager *) (data);
2015-09-24 22:52:02 +02:00
#ifdef ANDROID
2021-07-15 16:24:57 +02:00
javaVm->AttachCurrentThread(&jniEnv[networkManager->instanceNum], nullptr);
2015-09-24 22:52:02 +02:00
#endif
2016-04-22 15:49:00 +02:00
if (networkManager->currentUserId != 0 && networkManager->pushConnectionEnabled) {
2015-09-24 22:52:02 +02:00
Datacenter *datacenter = networkManager->getDatacenterWithId(networkManager->currentDatacenterId);
if (datacenter != nullptr) {
datacenter->createPushConnection()->setSessionId(networkManager->pushSessionId);
networkManager->sendPing(datacenter, true);
}
}
do {
networkManager->select();
} while (!done);
return nullptr;
}
void ConnectionsManager::loadConfig() {
if (config == nullptr) {
2018-07-30 04:07:02 +02:00
config = new Config(instanceNum, "tgnet.dat");
2015-09-24 22:52:02 +02:00
}
NativeByteBuffer *buffer = config->readConfig();
if (buffer != nullptr) {
uint32_t version = buffer->readUint32(nullptr);
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("config version = %u", version);
2015-09-24 22:52:02 +02:00
if (version <= configVersion) {
testBackend = buffer->readBool(nullptr);
2018-07-30 04:07:02 +02:00
if (version >= 3) {
clientBlocked = buffer->readBool(nullptr);
}
2019-01-23 18:03:33 +01:00
if (version >= 4) {
lastInitSystemLangcode = buffer->readString(nullptr);
}
2015-09-24 22:52:02 +02:00
if (buffer->readBool(nullptr)) {
currentDatacenterId = buffer->readUint32(nullptr);
timeDifference = buffer->readInt32(nullptr);
lastDcUpdateTime = buffer->readInt32(nullptr);
pushSessionId = buffer->readInt64(nullptr);
if (version >= 2) {
registeredForInternalPush = buffer->readBool(nullptr);
}
2019-12-31 14:08:08 +01:00
if (version >= 5) {
int32_t lastServerTime = buffer->readInt32(nullptr);
int32_t currentTime = getCurrentTime();
2020-01-05 19:39:58 +01:00
if (currentTime > timeDifference && currentTime < lastServerTime) {
timeDifference += (lastServerTime - currentTime);
2019-12-31 14:08:08 +01:00
}
}
2015-09-24 22:52:02 +02:00
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("current dc id = %u, time difference = %d, registered for push = %d", currentDatacenterId, timeDifference, (int32_t) registeredForInternalPush);
2015-09-24 22:52:02 +02:00
uint32_t count = buffer->readUint32(nullptr);
for (uint32_t a = 0; a < count; a++) {
sessionsToDestroy.push_back(buffer->readInt64(nullptr));
}
count = buffer->readUint32(nullptr);
for (uint32_t a = 0; a < count; a++) {
2021-07-15 16:24:57 +02:00
auto datacenter = new Datacenter(instanceNum, buffer);
2015-09-24 22:52:02 +02:00
datacenters[datacenter->getDatacenterId()] = datacenter;
2019-07-18 15:01:39 +02:00
if (LOGS_ENABLED) DEBUG_D("datacenter(%p) %u loaded (hasAuthKey = %d, 0x%" PRIx64 ")", datacenter, datacenter->getDatacenterId(), (int) datacenter->hasPermanentAuthKey(), datacenter->getPermanentAuthKeyId());
2023-04-25 07:51:03 +02:00
if (datacenter->isCdnDatacenter && !datacenter->hasPermanentAuthKey()) {
datacenter->clearAuthKey(HandshakeTypePerm);
}
2015-09-24 22:52:02 +02:00
}
}
}
buffer->reuse();
}
if (currentDatacenterId != 0 && currentUserId) {
Datacenter *datacenter = getDatacenterWithId(currentDatacenterId);
2018-07-30 04:07:02 +02:00
if (datacenter == nullptr || !datacenter->hasPermanentAuthKey()) {
2015-09-24 22:52:02 +02:00
if (datacenter != nullptr) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("reset authorization because of dc %d", currentDatacenterId);
2015-09-24 22:52:02 +02:00
}
currentDatacenterId = 0;
datacenters.clear();
scheduleTask([&] {
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onLogout(instanceNum);
2015-09-24 22:52:02 +02:00
}
});
}
}
initDatacenters();
2021-07-15 16:24:57 +02:00
if ((!datacenters.empty() && currentDatacenterId == 0) || pushSessionId == 0) {
2015-09-24 22:52:02 +02:00
if (pushSessionId == 0) {
RAND_bytes((uint8_t *) &pushSessionId, 8);
}
if (currentDatacenterId == 0) {
currentDatacenterId = 2;
}
saveConfig();
}
movingToDatacenterId = DEFAULT_DATACENTER_ID;
}
2017-07-08 18:32:04 +02:00
void ConnectionsManager::saveConfigInternal(NativeByteBuffer *buffer) {
2015-09-24 22:52:02 +02:00
buffer->writeInt32(configVersion);
buffer->writeBool(testBackend);
2018-07-30 04:07:02 +02:00
buffer->writeBool(clientBlocked);
2019-01-23 18:03:33 +01:00
buffer->writeString(lastInitSystemLangcode);
2015-09-24 22:52:02 +02:00
Datacenter *currentDatacenter = getDatacenterWithId(currentDatacenterId);
buffer->writeBool(currentDatacenter != nullptr);
if (currentDatacenter != nullptr) {
buffer->writeInt32(currentDatacenterId);
buffer->writeInt32(timeDifference);
buffer->writeInt32(lastDcUpdateTime);
buffer->writeInt64(pushSessionId);
buffer->writeBool(registeredForInternalPush);
2019-12-31 14:08:08 +01:00
buffer->writeInt32(getCurrentTime());
2015-09-24 22:52:02 +02:00
std::vector<int64_t> sessions;
currentDatacenter->getSessions(sessions);
2021-07-15 16:24:57 +02:00
auto count = (uint32_t) sessions.size();
2015-09-24 22:52:02 +02:00
buffer->writeInt32(count);
for (uint32_t a = 0; a < count; a++) {
buffer->writeInt64(sessions[a]);
}
count = (uint32_t) datacenters.size();
buffer->writeInt32(count);
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
datacenter.second->serializeToStream(buffer);
2015-09-24 22:52:02 +02:00
}
}
2017-07-08 18:32:04 +02:00
}
void ConnectionsManager::saveConfig() {
if (config == nullptr) {
2018-07-30 04:07:02 +02:00
config = new Config(instanceNum, "tgnet.dat");
2017-07-08 18:32:04 +02:00
}
sizeCalculator->clearCapacity();
saveConfigInternal(sizeCalculator);
NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(sizeCalculator->capacity());
saveConfigInternal(buffer);
2015-09-24 22:52:02 +02:00
config->writeConfig(buffer);
buffer->reuse();
}
inline NativeByteBuffer *decompressGZip(NativeByteBuffer *data) {
int retCode;
z_stream stream;
memset(&stream, 0, sizeof(z_stream));
stream.avail_in = data->limit();
stream.next_in = data->bytes();
retCode = inflateInit2(&stream, 15 + 32);
if (retCode != Z_OK) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("can't decompress data");
2015-09-24 22:52:02 +02:00
exit(1);
}
NativeByteBuffer *result = BuffersStorage::getInstance().getFreeBuffer(data->limit() * 4);
stream.avail_out = result->capacity();
stream.next_out = result->bytes();
while (1) {
retCode = inflate(&stream, Z_NO_FLUSH);
if (retCode == Z_STREAM_END) {
break;
}
if (retCode == Z_OK) {
NativeByteBuffer *newResult = BuffersStorage::getInstance().getFreeBuffer(result->capacity() * 2);
memcpy(newResult->bytes(), result->bytes(), result->capacity());
stream.avail_out = newResult->capacity() - result->capacity();
stream.next_out = newResult->bytes() + result->capacity();
result->reuse();
result = newResult;
} else {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("can't decompress data");
2015-09-24 22:52:02 +02:00
exit(1);
}
}
result->limit((uint32_t) stream.total_out);
inflateEnd(&stream);
return result;
}
inline NativeByteBuffer *compressGZip(NativeByteBuffer *buffer) {
if (buffer == nullptr || buffer->limit() == 0) {
return nullptr;
}
z_stream stream;
int retCode;
memset(&stream, 0, sizeof(z_stream));
stream.avail_in = buffer->limit();
stream.next_in = buffer->bytes();
retCode = deflateInit2(&stream, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY);
if (retCode != Z_OK) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("%s: deflateInit2() failed with error %i", __PRETTY_FUNCTION__, retCode);
2015-09-24 22:52:02 +02:00
return nullptr;
}
NativeByteBuffer *result = BuffersStorage::getInstance().getFreeBuffer(buffer->limit());
stream.avail_out = result->limit();
stream.next_out = result->bytes();
retCode = deflate(&stream, Z_FINISH);
if ((retCode != Z_OK) && (retCode != Z_STREAM_END)) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("%s: deflate() failed with error %i", __PRETTY_FUNCTION__, retCode);
2015-09-24 22:52:02 +02:00
deflateEnd(&stream);
result->reuse();
return nullptr;
}
if (retCode != Z_STREAM_END || stream.total_out >= buffer->limit() - 4) {
deflateEnd(&stream);
result->reuse();
return nullptr;
}
result->limit((uint32_t) stream.total_out);
deflateEnd(&stream);
return result;
}
int64_t ConnectionsManager::getCurrentTimeMillis() {
clock_gettime(CLOCK_REALTIME, &timeSpec);
return (int64_t) timeSpec.tv_sec * 1000 + (int64_t) timeSpec.tv_nsec / 1000000;
}
2017-03-31 01:58:05 +02:00
int64_t ConnectionsManager::getCurrentTimeMonotonicMillis() {
2020-02-15 19:17:30 +01:00
clock_gettime(CLOCK_BOOTTIME, &timeSpecMonotonic);
2017-03-31 01:58:05 +02:00
return (int64_t) timeSpecMonotonic.tv_sec * 1000 + (int64_t) timeSpecMonotonic.tv_nsec / 1000000;
}
2015-09-24 22:52:02 +02:00
int32_t ConnectionsManager::getCurrentTime() {
return (int32_t) (getCurrentTimeMillis() / 1000) + timeDifference;
}
2024-11-20 15:15:52 +01:00
int32_t ConnectionsManager::getCurrentPingTime() {
return (int32_t) currentPingTimeLive;
}
2020-10-30 11:26:29 +01:00
uint32_t ConnectionsManager::getCurrentDatacenterId() {
Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID);
return datacenter != nullptr ? datacenter->getDatacenterId() : INT_MAX;
}
2017-07-08 18:32:04 +02:00
bool ConnectionsManager::isTestBackend() {
return testBackend;
}
2015-09-24 22:52:02 +02:00
int32_t ConnectionsManager::getTimeDifference() {
return timeDifference;
}
int64_t ConnectionsManager::generateMessageId() {
2021-07-15 16:24:57 +02:00
auto messageId = (int64_t) ((((double) getCurrentTimeMillis() + ((double) timeDifference) * 1000) * 4294967296.0) / 1000.0);
2015-09-24 22:52:02 +02:00
if (messageId <= lastOutgoingMessageId) {
messageId = lastOutgoingMessageId + 1;
}
while (messageId % 4 != 0) {
messageId++;
}
lastOutgoingMessageId = messageId;
return messageId;
}
bool ConnectionsManager::isNetworkAvailable() {
return networkAvailable;
}
2020-09-30 15:48:47 +02:00
void ConnectionsManager::cleanUp(bool resetKeys, int32_t datacenterId) {
scheduleTask([&, resetKeys, datacenterId] {
2021-07-15 16:24:57 +02:00
for (auto iter = requestsQueue.begin(); iter != requestsQueue.end();) {
2015-09-24 22:52:02 +02:00
Request *request = iter->get();
2020-09-30 15:48:47 +02:00
if (datacenterId != -1) {
Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId);
if (requestDatacenter != nullptr && requestDatacenter->getDatacenterId() != datacenterId) {
iter++;
continue;
}
}
2015-09-24 22:52:02 +02:00
if (request->requestFlags & RequestFlagWithoutLogin) {
iter++;
continue;
}
if (request->onCompleteRequestCallback != nullptr) {
2021-07-15 16:24:57 +02:00
auto error = new TL_error();
2015-09-24 22:52:02 +02:00
error->code = -1000;
error->text = "";
2024-10-17 22:04:16 +02:00
int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId;
request->onComplete(nullptr, error, 0, 0, request->messageId, dcId);
2015-09-24 22:52:02 +02:00
delete error;
}
iter = requestsQueue.erase(iter);
}
2021-07-15 16:24:57 +02:00
for (auto iter = runningRequests.begin(); iter != runningRequests.end();) {
2015-09-24 22:52:02 +02:00
Request *request = iter->get();
2020-09-30 15:48:47 +02:00
if (datacenterId != -1) {
Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId);
if (requestDatacenter != nullptr && requestDatacenter->getDatacenterId() != datacenterId) {
iter++;
continue;
}
}
2015-09-24 22:52:02 +02:00
if (request->requestFlags & RequestFlagWithoutLogin) {
iter++;
continue;
}
if (request->onCompleteRequestCallback != nullptr) {
2021-07-15 16:24:57 +02:00
auto error = new TL_error();
2015-09-24 22:52:02 +02:00
error->code = -1000;
error->text = "";
2024-10-17 22:04:16 +02:00
int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId;
request->onComplete(nullptr, error, 0, 0, request->messageId, dcId);
2015-09-24 22:52:02 +02:00
delete error;
}
2024-03-08 15:32:16 +01:00
DEBUG_D("1) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
2015-09-24 22:52:02 +02:00
iter = runningRequests.erase(iter);
}
quickAckIdToRequestIds.clear();
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
if (datacenterId != -1 && datacenter.second->getDatacenterId() != datacenterId) {
2020-09-30 15:48:47 +02:00
continue;
}
2018-07-30 04:07:02 +02:00
if (resetKeys) {
2021-07-15 16:24:57 +02:00
datacenter.second->clearAuthKey(HandshakeTypeAll);
2018-07-30 04:07:02 +02:00
}
2021-07-15 16:24:57 +02:00
datacenter.second->recreateSessions(HandshakeTypeAll);
datacenter.second->authorized = false;
2015-09-24 22:52:02 +02:00
}
2020-09-30 15:48:47 +02:00
if (datacenterId == -1) {
sessionsToDestroy.clear();
currentUserId = 0;
2023-10-28 22:52:06 +02:00
currentUserPremium = false;
2020-09-30 15:48:47 +02:00
registeredForInternalPush = false;
}
2015-09-24 22:52:02 +02:00
saveConfig();
});
}
2017-07-08 18:32:04 +02:00
void ConnectionsManager::onConnectionClosed(Connection *connection, int reason) {
2023-05-27 14:04:37 +02:00
if (reason == 1) {
lastProtocolUsefullData = false;
}
2015-09-24 22:52:02 +02:00
Datacenter *datacenter = connection->getDatacenter();
2018-07-30 04:07:02 +02:00
if ((connection->getConnectionType() == ConnectionTypeGeneric || connection->getConnectionType() == ConnectionTypeGenericMedia) && datacenter->isHandshakingAny()) {
datacenter->onHandshakeConnectionClosed(connection);
}
2015-09-24 22:52:02 +02:00
if (connection->getConnectionType() == ConnectionTypeGeneric) {
2018-07-30 04:07:02 +02:00
if (datacenter->getDatacenterId() == currentDatacenterId) {
2019-01-23 18:03:33 +01:00
sendingPing = false;
2019-08-22 01:53:26 +02:00
if (!connection->isSuspended() && (proxyAddress.empty() || connection->hasTlsHashMismatch())) {
2018-07-30 04:07:02 +02:00
if (reason == 2) {
disconnectTimeoutAmount += connection->getTimeout();
} else {
disconnectTimeoutAmount += 4;
}
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("increase disconnect timeout %d", disconnectTimeoutAmount);
2018-07-30 04:07:02 +02:00
int32_t maxTimeout;
if (clientBlocked) {
maxTimeout = 5;
} else {
maxTimeout = 20;
}
if (disconnectTimeoutAmount >= maxTimeout) {
if (!connection->hasUsefullData()) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("start requesting new address and port due to timeout reach");
2019-08-22 01:53:26 +02:00
requestingSecondAddressByTlsHashMismatch = connection->hasTlsHashMismatch();
2020-01-05 19:39:58 +01:00
if (requestingSecondAddressByTlsHashMismatch) {
requestingSecondAddress = 1;
} else {
requestingSecondAddress = 0;
}
2018-07-30 04:07:02 +02:00
delegate->onRequestNewServerIpAndPort(requestingSecondAddress, instanceNum);
} else {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("connection has usefull data, don't request anything");
2018-07-30 04:07:02 +02:00
}
disconnectTimeoutAmount = 0;
2017-07-08 18:32:04 +02:00
}
}
2018-07-30 04:07:02 +02:00
2015-09-24 22:52:02 +02:00
if (networkAvailable) {
2017-07-08 18:32:04 +02:00
if (proxyAddress.empty()) {
if (connectionState != ConnectionStateConnecting) {
connectionState = ConnectionStateConnecting;
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onConnectionStateChanged(connectionState, instanceNum);
2017-07-08 18:32:04 +02:00
}
}
} else {
if (connectionState != ConnectionStateConnectingViaProxy) {
connectionState = ConnectionStateConnectingViaProxy;
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onConnectionStateChanged(connectionState, instanceNum);
2017-07-08 18:32:04 +02:00
}
2015-09-24 22:52:02 +02:00
}
}
} else {
if (connectionState != ConnectionStateWaitingForNetwork) {
connectionState = ConnectionStateWaitingForNetwork;
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onConnectionStateChanged(connectionState, instanceNum);
2015-09-24 22:52:02 +02:00
}
}
}
}
} else if (connection->getConnectionType() == ConnectionTypePush) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("connection(%p) push connection closed", connection);
2015-09-24 22:52:02 +02:00
sendingPushPing = false;
2019-05-14 14:08:05 +02:00
lastPushPingTime = getCurrentTimeMonotonicMillis() - nextPingTimeOffset + 4000;
2018-07-30 04:07:02 +02:00
} else if (connection->getConnectionType() == ConnectionTypeProxy) {
2019-07-18 15:01:39 +02:00
scheduleTask([&, connection] {
2021-07-15 16:24:57 +02:00
for (auto iter = proxyActiveChecks.begin(); iter != proxyActiveChecks.end(); iter++) {
2019-07-18 15:01:39 +02:00
ProxyCheckInfo *proxyCheckInfo = iter->get();
if (proxyCheckInfo->connectionNum == connection->getConnectionNum()) {
bool found = false;
2021-07-15 16:24:57 +02:00
for (auto iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) {
2019-07-18 15:01:39 +02:00
Request *request = iter2->get();
if (connection->getConnectionToken() == request->connectionToken && request->requestToken == proxyCheckInfo->requestToken && (request->connectionType & 0x0000ffff) == ConnectionTypeProxy) {
request->completed = true;
2024-03-08 15:32:16 +01:00
DEBUG_D("2) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
2019-07-18 15:01:39 +02:00
runningRequests.erase(iter2);
proxyCheckInfo->onRequestTime(-1);
found = true;
break;
}
2018-07-30 04:07:02 +02:00
}
2019-07-18 15:01:39 +02:00
if (found) {
proxyActiveChecks.erase(iter);
if (!proxyCheckQueue.empty()) {
proxyCheckInfo = proxyCheckQueue[0].release();
proxyCheckQueue.erase(proxyCheckQueue.begin());
checkProxyInternal(proxyCheckInfo);
}
2018-07-30 04:07:02 +02:00
}
2019-07-18 15:01:39 +02:00
break;
2018-07-30 04:07:02 +02:00
}
}
2019-07-18 15:01:39 +02:00
});
2015-09-24 22:52:02 +02:00
}
}
void ConnectionsManager::onConnectionConnected(Connection *connection) {
Datacenter *datacenter = connection->getDatacenter();
2019-01-23 18:03:33 +01:00
ConnectionType connectionType = connection->getConnectionType();
if ((connectionType == ConnectionTypeGeneric || connectionType == ConnectionTypeGenericMedia) && datacenter->isHandshakingAny()) {
2018-07-30 04:07:02 +02:00
datacenter->onHandshakeConnectionConnected(connection);
return;
2015-09-24 22:52:02 +02:00
}
2019-01-23 18:03:33 +01:00
if (datacenter->hasAuthKey(connectionType, 1)) {
if (connectionType == ConnectionTypePush) {
2015-09-24 22:52:02 +02:00
sendingPushPing = false;
2017-03-31 01:58:05 +02:00
lastPushPingTime = getCurrentTimeMonotonicMillis();
2015-09-24 22:52:02 +02:00
sendPing(datacenter, true);
} else {
2019-01-23 18:03:33 +01:00
if (connectionType == ConnectionTypeGeneric && datacenter->getDatacenterId() == currentDatacenterId) {
sendingPing = false;
}
2015-09-24 22:52:02 +02:00
if (networkPaused && lastPauseTime != 0) {
2017-03-31 01:58:05 +02:00
lastPauseTime = getCurrentTimeMonotonicMillis();
2015-09-24 22:52:02 +02:00
}
processRequestQueue(connection->getConnectionType(), datacenter->getDatacenterId());
}
}
}
void ConnectionsManager::onConnectionQuickAckReceived(Connection *connection, int32_t ack) {
2021-07-15 16:24:57 +02:00
auto iter = quickAckIdToRequestIds.find(ack);
2015-09-24 22:52:02 +02:00
if (iter == quickAckIdToRequestIds.end()) {
return;
}
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2015-09-24 22:52:02 +02:00
if (std::find(iter->second.begin(), iter->second.end(), request->requestToken) != iter->second.end()) {
request->onQuickAck();
}
}
quickAckIdToRequestIds.erase(iter);
}
void ConnectionsManager::onConnectionDataReceived(Connection *connection, NativeByteBuffer *data, uint32_t length) {
bool error = false;
2018-07-30 04:07:02 +02:00
if (length <= 24 + 32) {
2015-09-24 22:52:02 +02:00
int32_t code = data->readInt32(&error);
2018-07-30 04:07:02 +02:00
if (code == 0) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("mtproto noop");
2018-07-30 04:07:02 +02:00
} else if (code == -1) {
int32_t ackId = data->readInt32(&error);
if (!error) {
onConnectionQuickAckReceived(connection, ackId & (~(1 << 31)));
}
2017-07-08 18:32:04 +02:00
} else {
2018-07-30 04:07:02 +02:00
Datacenter *datacenter = connection->getDatacenter();
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_W("mtproto error = %d", code);
2018-07-30 04:07:02 +02:00
if (code == -444 && connection->getConnectionType() == ConnectionTypeGeneric && !proxyAddress.empty() && !proxySecret.empty()) {
if (delegate != nullptr) {
delegate->onProxyError(instanceNum);
}
} else if (code == -404 && (datacenter->isCdnDatacenter || PFS_ENABLED)) {
2023-04-25 07:51:03 +02:00
if (!datacenter->isHandshaking(connection->isMediaConnection) || datacenter->isCdnDatacenter) {
2018-07-30 04:07:02 +02:00
datacenter->clearAuthKey(connection->isMediaConnection ? HandshakeTypeMediaTemp : HandshakeTypeTemp);
datacenter->beginHandshake(connection->isMediaConnection ? HandshakeTypeMediaTemp : HandshakeTypeTemp, true);
2019-01-23 18:03:33 +01:00
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());
2018-07-30 04:07:02 +02:00
}
} else {
connection->reconnect();
}
2017-07-08 18:32:04 +02:00
}
2015-09-24 22:52:02 +02:00
return;
}
uint32_t mark = data->position();
int64_t keyId = data->readInt64(&error);
if (error) {
connection->reconnect();
return;
}
Datacenter *datacenter = connection->getDatacenter();
if (connectionState != ConnectionStateConnected && connection->getConnectionType() == ConnectionTypeGeneric && datacenter->getDatacenterId() == currentDatacenterId) {
connectionState = ConnectionStateConnected;
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onConnectionStateChanged(connectionState, instanceNum);
2015-09-24 22:52:02 +02:00
}
}
if (keyId == 0) {
int64_t messageId = data->readInt64(&error);
if (error) {
connection->reconnect();
return;
}
if (connection->isMessageIdProcessed(messageId)) {
return;
}
uint32_t messageLength = data->readUint32(&error);
if (error) {
connection->reconnect();
return;
}
2018-07-30 04:07:02 +02:00
if (!connection->allowsCustomPadding()) {
if (messageLength != data->remaining()) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("connection(%p) received incorrect message length", connection);
2018-07-30 04:07:02 +02:00
connection->reconnect();
return;
}
2015-09-24 22:52:02 +02:00
}
2018-07-30 04:07:02 +02:00
2015-09-24 22:52:02 +02:00
TLObject *request;
2018-07-30 04:07:02 +02:00
if (datacenter->isHandshaking(connection->isMediaConnection)) {
request = datacenter->getCurrentHandshakeRequest(connection->isMediaConnection);
2024-06-03 08:21:03 +02:00
if (request == nullptr) {
return;
}
2015-09-24 22:52:02 +02:00
} else {
2024-06-03 08:21:03 +02:00
return;
2015-09-24 22:52:02 +02:00
}
2018-07-30 04:07:02 +02:00
deserializingDatacenter = datacenter;
2023-03-18 14:33:38 +01:00
TLObject *object = TLdeserialize(request, messageLength, data);
2015-09-24 22:52:02 +02:00
if (object != nullptr) {
2018-07-30 04:07:02 +02:00
if (datacenter->isHandshaking(connection->isMediaConnection)) {
2023-02-03 20:11:36 +01:00
if (LOGS_ENABLED) DEBUG_E("process handshake");
2018-07-30 04:07:02 +02:00
datacenter->processHandshakeResponse(connection->isMediaConnection, object, messageId);
2015-09-24 22:52:02 +02:00
} else {
2023-02-03 20:11:36 +01:00
if (LOGS_ENABLED) DEBUG_E("connection(%p) received incorrect unencrypted message type", connection);
connection->reconnect();
return;
2015-09-24 22:52:02 +02:00
}
2021-02-25 17:58:14 +01:00
lastProtocolUsefullData = true;
2017-07-08 18:32:04 +02:00
connection->setHasUsefullData();
2015-09-24 22:52:02 +02:00
delete object;
}
} else {
2018-07-30 04:07:02 +02:00
if (connection->allowsCustomPadding()) {
uint32_t padding = (length - 24) % 16;
if (padding != 0) {
length -= padding;
}
}
2021-07-15 16:24:57 +02:00
if (length < 24 + 32 || (!connection->allowsCustomPadding() && (length - 24) % 16 != 0) || !datacenter->decryptServerResponse(keyId, data->bytes() + mark + 8, data->bytes() + mark + 24, length - 24, connection)) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("connection(%p) unable to decrypt server response", connection);
2017-12-08 18:35:59 +01:00
connection->reconnect();
2015-09-24 22:52:02 +02:00
return;
}
data->position(mark + 24);
int64_t messageServerSalt = data->readInt64(&error);
int64_t messageSessionId = data->readInt64(&error);
2018-07-30 04:07:02 +02:00
if (messageSessionId != connection->getSessionId()) {
2019-01-23 18:03:33 +01:00
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());
2015-09-24 22:52:02 +02:00
return;
}
int64_t messageId = data->readInt64(&error);
int32_t messageSeqNo = data->readInt32(&error);
uint32_t messageLength = data->readUint32(&error);
2019-01-23 18:03:33 +01:00
int32_t processedStatus = connection->isMessageIdProcessed(messageId);
2015-09-24 22:52:02 +02:00
if (messageSeqNo % 2 != 0) {
connection->addMessageToConfirm(messageId);
}
2019-01-23 18:03:33 +01:00
TLObject *object = nullptr;
2024-03-08 15:32:16 +01:00
long req_msg_id = 0;
2019-01-23 18:03:33 +01:00
if (processedStatus != 1) {
2018-07-30 04:07:02 +02:00
deserializingDatacenter = datacenter;
2019-01-23 18:03:33 +01:00
object = TLdeserialize(nullptr, messageLength, data);
2024-03-08 15:32:16 +01:00
TL_rpc_result* res = dynamic_cast<TL_rpc_result*>(object);
if (res != nullptr) {
req_msg_id = res->req_msg_id;
}
2019-01-23 18:03:33 +01:00
if (processedStatus == 2) {
if (object == nullptr) {
connection->recreateSession();
connection->reconnect();
return;
} else {
delete object;
object = nullptr;
}
}
}
if (!processedStatus) {
2015-09-24 22:52:02 +02:00
if (object != nullptr) {
2021-02-25 17:58:14 +01:00
lastProtocolUsefullData = true;
2017-07-08 18:32:04 +02:00
connection->setHasUsefullData();
2019-01-23 18:03:33 +01:00
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());
2015-09-24 22:52:02 +02:00
processServerResponse(object, messageId, messageSeqNo, messageServerSalt, connection, 0, 0);
connection->addProcessedMessageId(messageId);
delete object;
if (connection->getConnectionType() == ConnectionTypePush) {
std::vector<std::unique_ptr<NetworkMessage>> messages;
sendMessagesToConnectionWithConfirmation(messages, connection, false);
}
} else {
2024-03-08 15:32:16 +01:00
if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received unparsed packet on 0x%" PRIx64, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), req_msg_id);
2015-09-24 22:52:02 +02:00
if (delegate != nullptr) {
2023-09-13 19:27:29 +02:00
delegate->onUnparsedMessageReceived(messageId, data, connection->getConnectionType(), instanceNum);
2015-09-24 22:52:02 +02:00
}
}
} else {
2024-03-08 15:32:16 +01:00
if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received unprocessed packet on 0x%" PRIx64, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), req_msg_id);
2015-09-24 22:52:02 +02:00
std::vector<std::unique_ptr<NetworkMessage>> messages;
sendMessagesToConnectionWithConfirmation(messages, connection, false);
}
}
}
2019-01-23 18:03:33 +01:00
bool ConnectionsManager::hasPendingRequestsForConnection(Connection *connection) {
ConnectionType type = connection->getConnectionType();
if (type == ConnectionTypeGeneric || type == ConnectionTypeTemp || type == ConnectionTypeGenericMedia) {
Datacenter *datacenter = connection->getDatacenter();
int8_t num = connection->getConnectionNum();
uint32_t token = connection->getConnectionToken();
if (type == ConnectionTypeGeneric) {
if (sendingPing && type == ConnectionTypeGeneric && datacenter->getDatacenterId() == currentDatacenterId) {
return true;
} else if (datacenter->isHandshaking(false)) {
return true;
}
} else if (type == ConnectionTypeGenericMedia) {
if (datacenter->isHandshaking(true)) {
return true;
}
}
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
auto connectionNum = (uint8_t) (request->connectionType >> 16);
auto connectionType = (ConnectionType) (request->connectionType & 0x0000ffff);
if ((connectionType == type && connectionNum == num) || request->connectionToken == token) {
2019-01-23 18:03:33 +01:00
return true;
}
}
return false;
}
return true;
}
2015-09-24 22:52:02 +02:00
TLObject *ConnectionsManager::getRequestWithMessageId(int64_t messageId) {
2024-03-08 15:32:16 +01:00
for (auto & iter : runningRequests) {
Request *request = iter.get();
2015-09-24 22:52:02 +02:00
if (request->messageId == messageId) {
return request->rawRequest;
}
}
return nullptr;
}
TLObject *ConnectionsManager::TLdeserialize(TLObject *request, uint32_t bytes, NativeByteBuffer *data) {
bool error = false;
uint32_t position = data->position();
uint32_t constructor = data->readUint32(&error);
if (error) {
data->position(position);
return nullptr;
}
2018-07-30 04:07:02 +02:00
TLObject *object = TLClassStore::TLdeserialize(data, bytes, constructor, instanceNum, error);
2015-09-24 22:52:02 +02:00
if (error) {
2021-07-15 16:24:57 +02:00
delete object;
2015-09-24 22:52:02 +02:00
data->position(position);
return nullptr;
}
if (object == nullptr) {
if (request != nullptr) {
2021-07-15 16:24:57 +02:00
auto apiRequest = dynamic_cast<TL_api_request *>(request);
2015-09-24 22:52:02 +02:00
if (apiRequest != nullptr) {
2019-08-22 01:53:26 +02:00
object = apiRequest->deserializeResponse(data, bytes, instanceNum, error);
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("api request constructor 0x%x, don't parse", constructor);
2015-09-24 22:52:02 +02:00
} else {
2018-07-30 04:07:02 +02:00
object = request->deserializeResponse(data, constructor, instanceNum, error);
2015-09-24 22:52:02 +02:00
if (object != nullptr && error) {
delete object;
object = nullptr;
}
}
} else {
2024-02-20 09:03:54 +01:00
if (constructor == 0x96a18d5) {
if (LOGS_ENABLED) DEBUG_D("not found file 0x%x", constructor);
}
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("not found request to parse constructor 0x%x", constructor);
2015-09-24 22:52:02 +02:00
}
}
if (object == nullptr) {
data->position(position);
}
return object;
}
void ConnectionsManager::processServerResponse(TLObject *message, int64_t messageId, int32_t messageSeqNo, int64_t messageSalt, Connection *connection, int64_t innerMsgId, int64_t containerMessageId) {
const std::type_info &typeInfo = typeid(*message);
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("process server response %p - %s", message, typeInfo.name());
2021-07-15 16:24:57 +02:00
auto timeMessage = (int64_t) ((messageId != 0 ? messageId : innerMsgId) / 4294967296.0 * 1000);
2019-01-23 18:03:33 +01:00
2015-09-24 22:52:02 +02:00
Datacenter *datacenter = connection->getDatacenter();
if (typeInfo == typeid(TL_new_session_created)) {
2021-07-15 16:24:57 +02:00
auto response = (TL_new_session_created *) message;
2015-09-24 22:52:02 +02:00
if (!connection->isSessionProcessed(response->unique_id)) {
2019-01-23 18:03:33 +01:00
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);
2015-09-24 22:52:02 +02:00
2021-07-15 16:24:57 +02:00
std::unique_ptr<TL_future_salt> salt = std::make_unique<TL_future_salt>();
2015-09-24 22:52:02 +02:00
salt->valid_until = salt->valid_since = getCurrentTime();
salt->valid_until += 30 * 60;
salt->salt = response->server_salt;
2019-12-31 14:08:08 +01:00
datacenter->addServerSalt(salt, Connection::isMediaConnectionType(connection->getConnectionType()));
2015-09-24 22:52:02 +02:00
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2015-10-29 18:10:07 +01:00
Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId);
if (request->messageId < response->first_msg_id && request->connectionType & connection->getConnectionType() && requestDatacenter != nullptr && requestDatacenter->getDatacenterId() == datacenter->getDatacenterId()) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("clear request %p - %s", request->rawRequest, typeid(*request->rawRequest).name());
2015-09-24 22:52:02 +02:00
request->clear(true);
}
}
saveConfig();
if (datacenter->getDatacenterId() == currentDatacenterId && currentUserId) {
if (connection->getConnectionType() == ConnectionTypePush) {
registerForInternalPushUpdates();
} else if (connection->getConnectionType() == ConnectionTypeGeneric) {
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onSessionCreated(instanceNum);
2015-09-24 22:52:02 +02:00
}
}
}
connection->addProcessedSession(response->unique_id);
}
} else if (typeInfo == typeid(TL_msg_container)) {
2021-07-15 16:24:57 +02:00
auto response = (TL_msg_container *) message;
2015-09-24 22:52:02 +02:00
size_t count = response->messages.size();
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("received container with %d items", (int32_t) count);
2015-09-24 22:52:02 +02:00
for (uint32_t a = 0; a < count; a++) {
TL_message *innerMessage = response->messages[a].get();
int64_t innerMessageId = innerMessage->msg_id;
if (innerMessage->seqno % 2 != 0) {
connection->addMessageToConfirm(innerMessageId);
}
2019-01-23 18:03:33 +01:00
int32_t processedStatus = connection->isMessageIdProcessed(innerMessageId);
if (processedStatus == 2) {
if (innerMessage->unparsedBody != nullptr) {
connection->recreateSession();
connection->reconnect();
return;
}
processedStatus = 0;
}
if (processedStatus) {
if (LOGS_ENABLED) DEBUG_D("inner message %d id 0x%" PRIx64 " already processed", a, innerMessageId);
2015-09-24 22:52:02 +02:00
continue;
}
if (innerMessage->unparsedBody != nullptr) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("inner message %d id 0x%" PRIx64 " is unparsed", a, innerMessageId);
2015-09-24 22:52:02 +02:00
if (delegate != nullptr) {
2023-09-13 19:27:29 +02:00
delegate->onUnparsedMessageReceived(innerMessageId, innerMessage->unparsedBody.get(), connection->getConnectionType(), instanceNum);
2015-09-24 22:52:02 +02:00
}
} else {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("inner message %d id 0x%" PRIx64 " process", a, innerMessageId);
2015-09-24 22:52:02 +02:00
processServerResponse(innerMessage->body.get(), 0, innerMessage->seqno, messageSalt, connection, innerMessageId, messageId);
}
connection->addProcessedMessageId(innerMessageId);
}
} else if (typeInfo == typeid(TL_pong)) {
if (connection->getConnectionType() == ConnectionTypePush) {
if (!registeredForInternalPush) {
registerForInternalPushUpdates();
}
2024-11-20 15:15:52 +01:00
int32_t diff = getCurrentTimeMonotonicMillis() - sendingPushPingTime;
currentPingTimeLive = (diff + currentPingTimeLive) / 2;
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received push ping", connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType());
2015-09-24 22:52:02 +02:00
sendingPushPing = false;
} else {
2021-07-15 16:24:57 +02:00
auto response = (TL_pong *) message;
2018-07-30 04:07:02 +02:00
if (response->ping_id >= 2000000) {
2021-07-15 16:24:57 +02:00
for (auto iter = proxyActiveChecks.begin(); iter != proxyActiveChecks.end(); iter++) {
2018-07-30 04:07:02 +02:00
ProxyCheckInfo *proxyCheckInfo = iter->get();
if (proxyCheckInfo->pingId == response->ping_id) {
2021-07-15 16:24:57 +02:00
for (auto iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) {
2018-07-30 04:07:02 +02:00
Request *request = iter2->get();
if (request->requestToken == proxyCheckInfo->requestToken) {
int64_t ping = llabs(getCurrentTimeMonotonicMillis() - request->startTimeMillis);
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("got ping response for request %p, %" PRId64, request->rawRequest, ping);
2018-07-30 04:07:02 +02:00
request->completed = true;
proxyCheckInfo->onRequestTime(ping);
2024-03-08 15:32:16 +01:00
DEBUG_D("3) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
2018-07-30 04:07:02 +02:00
runningRequests.erase(iter2);
break;
}
}
proxyActiveChecks.erase(iter);
if (!proxyCheckQueue.empty()) {
proxyCheckInfo = proxyCheckQueue[0].release();
proxyCheckQueue.erase(proxyCheckQueue.begin());
2019-07-18 15:01:39 +02:00
scheduleCheckProxyInternal(proxyCheckInfo);
2018-07-30 04:07:02 +02:00
}
break;
}
}
} else if (response->ping_id == lastPingId) {
2017-03-31 01:58:05 +02:00
int32_t diff = (int32_t) (getCurrentTimeMonotonicMillis() / 1000) - pingTime;
2024-11-20 15:15:52 +01:00
currentPingTimeLive = ((getCurrentTimeMonotonicMillis() - pingTimeMs) + currentPingTimeLive) / 2;
2015-09-24 22:52:02 +02:00
if (abs(diff) < 10) {
currentPingTime = (diff + currentPingTime) / 2;
if (messageId != 0) {
2017-03-31 01:58:05 +02:00
timeDifference = (int32_t) ((timeMessage - getCurrentTimeMillis()) / 1000 - currentPingTime / 2);
2015-09-24 22:52:02 +02:00
}
}
2019-01-23 18:03:33 +01:00
sendingPing = false;
2015-09-24 22:52:02 +02:00
}
}
} else if (typeInfo == typeid(TL_future_salts)) {
2021-07-15 16:24:57 +02:00
auto response = (TL_future_salts *) message;
2015-09-24 22:52:02 +02:00
int64_t requestMid = response->req_msg_id;
2021-07-15 16:24:57 +02:00
for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) {
2015-09-24 22:52:02 +02:00
Request *request = iter->get();
if (request->respondsToMessageId(requestMid)) {
2024-10-17 22:04:16 +02:00
int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId;
request->onComplete(response, nullptr, connection->currentNetworkType, timeMessage, requestMid, dcId);
2015-09-24 22:52:02 +02:00
request->completed = true;
2024-03-08 15:32:16 +01:00
DEBUG_D("4) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
2015-09-24 22:52:02 +02:00
runningRequests.erase(iter);
break;
}
}
} else if (dynamic_cast<DestroySessionRes *>(message)) {
2021-07-15 16:24:57 +02:00
auto response = (DestroySessionRes *) message;
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("destroyed session 0x%" PRIx64 " (%s)", (uint64_t) response->session_id, typeInfo == typeid(TL_destroy_session_ok) ? "ok" : "not found");
2015-09-24 22:52:02 +02:00
} else if (typeInfo == typeid(TL_rpc_result)) {
2021-07-15 16:24:57 +02:00
auto response = (TL_rpc_result *) message;
2015-09-24 22:52:02 +02:00
int64_t resultMid = response->req_msg_id;
2021-04-17 01:59:59 +02:00
if (resultMid == lastInvokeAfterMessageId) {
lastInvokeAfterMessageId = 0;
}
2015-09-24 22:52:02 +02:00
2021-07-15 16:24:57 +02:00
bool hasResult = response->result != nullptr;
2015-09-24 22:52:02 +02:00
bool ignoreResult = false;
if (hasResult) {
TLObject *object = response->result.get();
2022-11-12 09:41:35 +01:00
if (LOGS_ENABLED) DEBUG_D("message_id %lld connection(%p, account%u, dc%u, type %d) received rpc_result with %s", messageId, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name());
2015-09-24 22:52:02 +02:00
}
RpcError *error = hasResult ? dynamic_cast<RpcError *>(response->result.get()) : nullptr;
if (error != nullptr) {
2022-11-12 09:41:35 +01:00
if (LOGS_ENABLED) DEBUG_E("message_id %lld connection(%p, account%u, dc%u, type %d) rpc error %d: %s", messageId, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), error->error_code, error->error_message.c_str());
2015-09-24 22:52:02 +02:00
if (error->error_code == 303) {
2015-10-29 18:10:07 +01:00
uint32_t migrateToDatacenterId = DEFAULT_DATACENTER_ID;
2018-07-30 04:07:02 +02:00
static std::vector<std::string> migrateErrors = {"NETWORK_MIGRATE_", "PHONE_MIGRATE_", "USER_MIGRATE_"};
2015-09-24 22:52:02 +02:00
size_t count = migrateErrors.size();
for (uint32_t a = 0; a < count; a++) {
std::string &possibleError = migrateErrors[a];
if (error->error_message.find(possibleError) != std::string::npos) {
std::string num = error->error_message.substr(possibleError.size(), error->error_message.size() - possibleError.size());
2021-07-15 16:24:57 +02:00
auto val = (uint32_t) atoi(num.c_str());
2015-09-24 22:52:02 +02:00
migrateToDatacenterId = val;
}
}
2018-07-30 04:07:02 +02:00
2015-10-29 18:10:07 +01:00
if (migrateToDatacenterId != DEFAULT_DATACENTER_ID) {
ignoreResult = true;
moveToDatacenter(migrateToDatacenterId);
}
2015-09-24 22:52:02 +02:00
}
}
uint32_t retryRequestsFromDatacenter = DEFAULT_DATACENTER_ID - 1;
uint32_t retryRequestsConnections = 0;
if (!ignoreResult) {
2021-07-15 16:24:57 +02:00
for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) {
2015-09-24 22:52:02 +02:00
Request *request = iter->get();
2019-01-23 18:03:33 +01:00
if (!request->respondsToMessageId(resultMid)) {
continue;
}
2023-11-02 11:51:24 +01:00
if (LOGS_ENABLED) DEBUG_D("got response for request %p - %s (messageId = 0x%" PRIx64 ")", request->rawRequest, typeid(*request->rawRequest).name(), request->messageId);
2019-01-23 18:03:33 +01:00
bool discardResponse = false;
bool isError = false;
bool allowInitConnection = true;
if (request->onCompleteRequestCallback != nullptr) {
TL_error *implicitError = nullptr;
NativeByteBuffer *unpacked_data = nullptr;
TLObject *result = response->result.get();
if (typeid(*result) == typeid(TL_gzip_packed)) {
2021-07-15 16:24:57 +02:00
auto innerResponse = (TL_gzip_packed *) result;
2019-01-23 18:03:33 +01:00
unpacked_data = decompressGZip(innerResponse->packed_data.get());
TLObject *object = TLdeserialize(request->rawRequest, unpacked_data->limit(), unpacked_data);
if (object != nullptr) {
response->result = std::unique_ptr<TLObject>(object);
} else {
response->result = std::unique_ptr<TLObject>(nullptr);
2015-09-24 22:52:02 +02:00
}
2019-01-23 18:03:33 +01:00
}
2015-09-24 22:52:02 +02:00
2021-07-15 16:24:57 +02:00
hasResult = response->result != nullptr;
2019-01-23 18:03:33 +01:00
error = hasResult ? dynamic_cast<RpcError *>(response->result.get()) : nullptr;
TL_error *error2 = hasResult ? dynamic_cast<TL_error *>(response->result.get()) : nullptr;
if (error != nullptr) {
allowInitConnection = false;
static std::string authRestart = "AUTH_RESTART";
static std::string authKeyPermEmpty = "AUTH_KEY_PERM_EMPTY";
static std::string workerBusy = "WORKER_BUSY_TOO_LONG_RETRY";
2024-06-03 08:21:03 +02:00
static std::string integrityCheckClassic = "INTEGRITY_CHECK_CLASSIC_";
2019-01-23 18:03:33 +01:00
bool processEvenFailed = error->error_code == 500 && error->error_message.find(authRestart) != std::string::npos;
bool isWorkerBusy = error->error_code == 500 && error->error_message.find(workerBusy) != std::string::npos;
if (LOGS_ENABLED) DEBUG_E("request %p rpc error %d: %s", request, error->error_code, error->error_message.c_str());
if (error->error_code == 401 && error->error_message.find(authKeyPermEmpty) != std::string::npos) {
discardResponse = true;
request->minStartTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000 + 1);
request->startTime = 0;
if (!datacenter->isHandshaking(connection->isMediaConnection)) {
datacenter->clearAuthKey(connection->isMediaConnection ? HandshakeTypeMediaTemp : HandshakeTypeTemp);
saveConfig();
datacenter->beginHandshake(connection->isMediaConnection ? HandshakeTypeMediaTemp : HandshakeTypeTemp, false);
}
2024-06-03 08:21:03 +02:00
} else if (error->error_code == 403 && error->error_message.find(integrityCheckClassic) != std::string::npos) {
discardResponse = true;
2024-06-30 16:27:03 +02:00
std::string err = error->error_message;
int index = err.find('_', integrityCheckClassic.size());
std::string project = err.substr(integrityCheckClassic.size(), index - integrityCheckClassic.size());
std::string nonce = err.substr(integrityCheckClassic.size() + project.size() + 1, err.size() - (integrityCheckClassic.size() + project.size() + 1));
2024-06-03 08:21:03 +02:00
request->awaitingIntegrityCheck = true;
request->startTime = 0;
request->startTimeMillis = 0;
if (delegate != nullptr) {
2024-06-30 16:27:03 +02:00
delegate->onIntegrityCheckClassic(instanceNum, request->requestToken, project, nonce);
2024-06-03 08:21:03 +02:00
}
} else {
bool failServerErrors = (request->requestFlags & RequestFlagFailOnServerErrors) == 0 || processEvenFailed;
bool exceptFloodWait = (request->requestFlags & RequestFlagFailOnServerErrorsExceptFloodWait) != 0;
if (failServerErrors && (error->error_code == 500 || error->error_code < 0)) {
2021-04-17 01:59:59 +02:00
static std::string waitFailed = "MSG_WAIT_FAILED";
2021-07-15 16:24:57 +02:00
static std::string waitTimeout = "MSG_WAIT_TIMEOUT";
2021-04-17 01:59:59 +02:00
if (error->error_message.find(waitFailed) != std::string::npos) {
request->startTime = 0;
request->startTimeMillis = 0;
2021-07-15 16:24:57 +02:00
request->requestFlags |= RequestFlagResendAfter;
2019-01-23 18:03:33 +01:00
} else {
2021-04-17 01:59:59 +02:00
if (isWorkerBusy) {
request->minStartTime = 0;
} else {
request->minStartTime = request->startTime + (request->serverFailureCount > 10 ? 10 : request->serverFailureCount);
}
request->serverFailureCount++;
2019-01-23 18:03:33 +01:00
}
2021-04-17 01:59:59 +02:00
discardResponse = true;
2024-06-03 08:21:03 +02:00
} else if (failServerErrors && error->error_code == -504) {
2023-04-21 17:06:46 +02:00
discardResponse = (request->requestFlags & RequestFlagIgnoreFloodWait) == 0;
request->failedByFloodWait = 2;
request->startTime = 0;
request->startTimeMillis = 0;
request->minStartTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000 + 2);
2024-03-31 21:10:51 +02:00
} else if (
2024-06-03 08:21:03 +02:00
(failServerErrors || exceptFloodWait) &&
2024-03-31 21:10:51 +02:00
error->error_code == 420 && (request->requestFlags & RequestFlagIgnoreFloodWait) == 0 &&
error->error_message.find("STORY_SEND_FLOOD") == std::string::npos
) {
2019-01-23 18:03:33 +01:00
int32_t waitTime = 2;
static std::string floodWait = "FLOOD_WAIT_";
2024-03-31 21:10:51 +02:00
static std::string premiumFloodWait = "FLOOD_PREMIUM_WAIT_";
2019-08-22 01:53:26 +02:00
static std::string slowmodeWait = "SLOWMODE_WAIT_";
2024-03-31 21:10:51 +02:00
bool isPremiumFloodWait = false;
2023-08-24 20:30:23 +02:00
discardResponse = true;
2024-03-31 21:10:51 +02:00
if (error->error_message.find(premiumFloodWait) != std::string::npos) {
isPremiumFloodWait = true;
std::string num = error->error_message.substr(premiumFloodWait.size(), error->error_message.size() - premiumFloodWait.size());
waitTime = atoi(num.c_str());
if (waitTime <= 0) {
waitTime = 2;
}
} else if (error->error_message.find(floodWait) != std::string::npos) {
2019-01-23 18:03:33 +01:00
std::string num = error->error_message.substr(floodWait.size(), error->error_message.size() - floodWait.size());
waitTime = atoi(num.c_str());
if (waitTime <= 0) {
waitTime = 2;
2015-09-24 22:52:02 +02:00
}
2019-08-22 01:53:26 +02:00
} else if (error->error_message.find(slowmodeWait) != std::string::npos) {
std::string num = error->error_message.substr(slowmodeWait.size(), error->error_message.size() - slowmodeWait.size());
waitTime = atoi(num.c_str());
if (waitTime <= 0) {
waitTime = 2;
}
discardResponse = false;
2019-01-23 18:03:33 +01:00
}
2024-03-31 21:10:51 +02:00
request->premiumFloodWait = isPremiumFloodWait;
2019-01-23 18:03:33 +01:00
request->failedByFloodWait = waitTime;
request->startTime = 0;
request->startTimeMillis = 0;
request->minStartTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000 + waitTime);
2024-03-31 21:10:51 +02:00
if (isPremiumFloodWait && delegate != nullptr) {
delegate->onPremiumFloodWait(instanceNum, request->requestToken, (request->connectionType & ConnectionTypeUpload) != 0);
}
2024-06-03 08:21:03 +02:00
} else if (failServerErrors && error->error_code == 400) {
2019-01-23 18:03:33 +01:00
static std::string waitFailed = "MSG_WAIT_FAILED";
2019-12-31 14:08:08 +01:00
static std::string bindFailed = "ENCRYPTED_MESSAGE_INVALID";
2021-07-15 16:24:57 +02:00
static std::string waitTimeout = "MSG_WAIT_TIMEOUT";
if (error->error_message.find(waitTimeout) != std::string::npos || error->error_message.find(waitFailed) != std::string::npos) {
2015-09-24 22:52:02 +02:00
discardResponse = true;
2015-11-26 22:04:02 +01:00
request->startTime = 0;
2018-07-30 04:07:02 +02:00
request->startTimeMillis = 0;
2021-07-15 16:24:57 +02:00
request->requestFlags |= RequestFlagResendAfter;
2019-12-31 14:08:08 +01:00
} else if (error->error_message.find(bindFailed) != std::string::npos && typeid(*request->rawRequest) == typeid(TL_auth_bindTempAuthKey)) {
2020-09-30 15:48:47 +02:00
int datacenterId;
if (delegate != nullptr && getDatacenterWithId(DEFAULT_DATACENTER_ID) == datacenter) {
2019-12-31 14:08:08 +01:00
delegate->onLogout(instanceNum);
2020-09-30 15:48:47 +02:00
datacenterId = -1;
} else {
datacenterId = datacenter->getDatacenterId();
2019-12-31 14:08:08 +01:00
}
2020-09-30 15:48:47 +02:00
cleanUp(true, datacenterId);
2015-09-24 22:52:02 +02:00
}
}
}
if (!discardResponse) {
2019-01-23 18:03:33 +01:00
implicitError = new TL_error();
implicitError->code = error->error_code;
implicitError->text = error->error_message;
}
} else if (error2 == nullptr) {
if (request->rawRequest == nullptr || response->result == nullptr) {
allowInitConnection = false;
if (LOGS_ENABLED) DEBUG_E("rawRequest is null");
implicitError = new TL_error();
implicitError->code = -1000;
implicitError->text = "";
}
2024-03-08 15:32:16 +01:00
if (hasResult) {
// when receiving TL_rpc_answer_dropped_running, we want to still listen for a little for the response, as it may come
TL_rpc_answer_dropped_running* droppedRunning = dynamic_cast<TL_rpc_answer_dropped_running*>(response->result.get());
if (droppedRunning != nullptr) {
TL_rpc_drop_answer* dropAnswer = dynamic_cast<TL_rpc_drop_answer*>(request->rawRequest);
if (dropAnswer != nullptr) {
int64_t originalMessageId = dropAnswer->req_msg_id;
Request* originalRequest = nullptr;
for (auto iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) {
Request *request2 = iter2->get();
if (request2->messageId == originalMessageId) {
originalRequest = request2;
break;
}
}
if (originalRequest != nullptr && (originalRequest->requestFlags & RequestFlagListenAfterCancel) != 0) {
if (LOGS_ENABLED) DEBUG_D("doNotClearOnDrop = true; msgid=0x%" PRIx64, originalMessageId);
originalRequest->disableClearCallback = false;
originalRequest->doNotClearOnDrop = true;
originalRequest->clearAfter = (int32_t) (getCurrentTimeMonotonicMillis() / 1000) + 25;
originalRequest->onRequestClearCallback = request->onRequestClearCallback;
request->onRequestClearCallback = nullptr;
} else {
if (LOGS_ENABLED) DEBUG_D("not found request; msgid=0x%" PRIx64, originalMessageId);
}
} else {
if (LOGS_ENABLED) DEBUG_D("not found dropAnswer; msgid=0x%" PRIx64, request->messageId);
}
}
}
2019-01-23 18:03:33 +01:00
}
if (!discardResponse) {
2024-10-17 22:04:16 +02:00
int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId;
2019-01-23 18:03:33 +01:00
if (implicitError != nullptr || error2 != nullptr) {
isError = true;
2024-10-17 22:04:16 +02:00
request->onComplete(nullptr, implicitError != nullptr ? implicitError : error2, connection->currentNetworkType, timeMessage, request->messageId, dcId);
2021-07-15 16:24:57 +02:00
delete error2;
2019-01-23 18:03:33 +01:00
} else {
2024-10-17 22:04:16 +02:00
request->onComplete(response->result.get(), nullptr, connection->currentNetworkType, timeMessage, request->messageId, dcId);
2015-09-24 22:52:02 +02:00
}
2019-01-23 18:03:33 +01:00
}
2015-09-24 22:52:02 +02:00
2019-01-23 18:03:33 +01:00
if (implicitError != nullptr) {
if (implicitError->code == 401) {
allowInitConnection = false;
isError = true;
static std::string sessionPasswordNeeded = "SESSION_PASSWORD_NEEDED";
if (implicitError->text.find(sessionPasswordNeeded) != std::string::npos) {
//ignore this error
} else if (datacenter->getDatacenterId() == currentDatacenterId || datacenter->getDatacenterId() == movingToDatacenterId) {
if (request->connectionType & ConnectionTypeGeneric && currentUserId) {
currentUserId = 0;
2023-10-28 22:52:06 +02:00
currentUserPremium = false;
2019-01-23 18:03:33 +01:00
if (delegate != nullptr) {
delegate->onLogout(instanceNum);
2015-09-24 22:52:02 +02:00
}
2020-09-30 15:48:47 +02:00
cleanUp(false, -1);
2015-09-24 22:52:02 +02:00
}
2019-01-23 18:03:33 +01:00
} else {
datacenter->authorized = false;
saveConfig();
discardResponse = true;
if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) {
2020-09-30 15:48:47 +02:00
retryRequestsFromDatacenter = datacenter->getDatacenterId();
2019-01-23 18:03:33 +01:00
retryRequestsConnections = request->connectionType;
2015-09-24 22:52:02 +02:00
}
}
2019-01-23 18:03:33 +01:00
} else if (currentUserId == 0 && implicitError->code == 406) {
static std::string authKeyDuplicated = "AUTH_KEY_DUPLICATED";
if (implicitError->text.find(authKeyDuplicated) != std::string::npos) {
2020-09-30 15:48:47 +02:00
cleanUp(true, datacenter->getDatacenterId());
2019-01-23 18:03:33 +01:00
}
2015-09-24 22:52:02 +02:00
}
2019-01-23 18:03:33 +01:00
}
2015-09-24 22:52:02 +02:00
2019-01-23 18:03:33 +01:00
if (unpacked_data != nullptr) {
unpacked_data->reuse();
}
2021-07-15 16:24:57 +02:00
delete implicitError;
2019-01-23 18:03:33 +01:00
}
2015-09-24 22:52:02 +02:00
2019-01-23 18:03:33 +01:00
if (!discardResponse) {
if (allowInitConnection && !isError) {
bool save = false;
if (request->isInitRequest && datacenter->lastInitVersion != currentVersion) {
datacenter->lastInitVersion = currentVersion;
save = true;
} else if (request->isInitMediaRequest && datacenter->lastInitMediaVersion != currentVersion) {
datacenter->lastInitMediaVersion = currentVersion;
save = true;
}
if (save) {
saveConfig();
if (LOGS_ENABLED) DEBUG_D("dc%d init connection completed", datacenter->getDatacenterId());
2015-09-24 22:52:02 +02:00
}
}
2019-01-23 18:03:33 +01:00
request->completed = true;
removeRequestFromGuid(request->requestToken);
2024-03-08 15:32:16 +01:00
if (LOGS_ENABLED) DEBUG_D("5) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
2019-01-23 18:03:33 +01:00
runningRequests.erase(iter);
} else {
request->messageId = 0;
request->messageSeqNo = 0;
request->connectionToken = 0;
2015-09-24 22:52:02 +02:00
}
2019-01-23 18:03:33 +01:00
break;
2015-09-24 22:52:02 +02:00
}
}
if (retryRequestsFromDatacenter != DEFAULT_DATACENTER_ID - 1) {
processRequestQueue(retryRequestsConnections, retryRequestsFromDatacenter);
} else {
processRequestQueue(0, 0);
}
} else if (typeInfo == typeid(TL_msgs_ack)) {
} else if (typeInfo == typeid(TL_bad_msg_notification)) {
2021-07-15 16:24:57 +02:00
auto result = (TL_bad_msg_notification *) message;
2019-01-23 18:03:33 +01:00
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);
2015-09-24 22:52:02 +02:00
switch (result->error_code) {
case 16:
case 17:
case 19:
case 32:
case 33:
case 64: {
int64_t realId = messageId != 0 ? messageId : containerMessageId;
if (realId == 0) {
realId = innerMsgId;
}
if (realId != 0) {
2021-07-15 16:24:57 +02:00
auto time = (int64_t) (messageId / 4294967296.0 * 1000);
2015-09-24 22:52:02 +02:00
int64_t currentTime = getCurrentTimeMillis();
timeDifference = (int32_t) ((time - currentTime) / 1000 - currentPingTime / 2);
}
2018-07-30 04:07:02 +02:00
datacenter->recreateSessions(HandshakeTypeAll);
2015-09-24 22:52:02 +02:00
saveConfig();
lastOutgoingMessageId = 0;
2018-07-30 04:07:02 +02:00
clearRequestsForDatacenter(datacenter, HandshakeTypeAll);
2015-09-24 22:52:02 +02:00
break;
}
2017-12-08 18:35:59 +01:00
case 20: {
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2017-12-08 18:35:59 +01:00
if (request->respondsToMessageId(result->bad_msg_id)) {
if (request->completed) {
break;
}
connection->addMessageToConfirm(result->bad_msg_id);
request->clear(true);
break;
}
}
}
2015-09-24 22:52:02 +02:00
default:
break;
}
} else if (typeInfo == typeid(TL_bad_server_salt)) {
2019-12-31 14:08:08 +01:00
bool media = Connection::isMediaConnectionType(connection->getConnectionType());
requestSaltsForDatacenter(datacenter, media, connection->getConnectionType() == ConnectionTypeTemp);
2015-09-24 22:52:02 +02:00
if (messageId != 0) {
2021-07-15 16:24:57 +02:00
auto time = (int64_t) (messageId / 4294967296.0 * 1000);
2015-09-24 22:52:02 +02:00
int64_t currentTime = getCurrentTimeMillis();
timeDifference = (int32_t) ((time - currentTime) / 1000 - currentPingTime / 2);
2020-01-02 16:08:53 +01:00
lastOutgoingMessageId = (messageId > lastOutgoingMessageId ? messageId : lastOutgoingMessageId);
2015-09-24 22:52:02 +02:00
}
2019-12-31 14:08:08 +01:00
if ((connection->getConnectionType() & ConnectionTypeDownload) == 0 || !datacenter->containsServerSalt(messageSalt, media)) {
2021-07-15 16:24:57 +02:00
auto response = (TL_bad_server_salt *) message;
2019-12-31 14:08:08 +01:00
int64_t resultMid = response->bad_msg_id;
if (resultMid != 0) {
2019-12-31 20:46:59 +01:00
bool beginHandshake = false;
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2020-09-30 15:48:47 +02:00
if (!beginHandshake && request->datacenterId == datacenter->getDatacenterId() && typeid(*request->rawRequest) == typeid(TL_auth_bindTempAuthKey) && request->respondsToMessageId(response->bad_msg_id)) {
2019-12-31 20:46:59 +01:00
beginHandshake = true;
2019-12-31 14:08:08 +01:00
}
if ((request->connectionType & ConnectionTypeDownload) == 0) {
continue;
}
Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId);
if (requestDatacenter != nullptr && requestDatacenter->getDatacenterId() == datacenter->getDatacenterId()) {
request->retryCount = 0;
request->failedBySalt = true;
}
2015-09-24 22:52:02 +02:00
}
2019-12-31 20:46:59 +01:00
if (beginHandshake) {
datacenter->beginHandshake(HandshakeTypeCurrent, false);
}
2015-09-24 22:52:02 +02:00
}
2019-12-31 14:08:08 +01:00
datacenter->clearServerSalts(media);
2015-09-24 22:52:02 +02:00
2021-07-15 16:24:57 +02:00
std::unique_ptr<TL_future_salt> salt = std::make_unique<TL_future_salt>();
2019-12-31 14:08:08 +01:00
salt->valid_until = salt->valid_since = getCurrentTime();
salt->valid_until += 30 * 60;
salt->salt = messageSalt;
datacenter->addServerSalt(salt, media);
saveConfig();
2015-09-24 22:52:02 +02:00
2019-12-31 14:08:08 +01:00
if (datacenter->hasAuthKey(ConnectionTypeGeneric, 1)) {
processRequestQueue(AllConnectionTypes, datacenter->getDatacenterId());
}
2015-09-24 22:52:02 +02:00
}
2017-12-08 18:35:59 +01:00
} else if (typeInfo == typeid(MsgsStateInfo)) {
2021-07-15 16:24:57 +02:00
auto response = (MsgsStateInfo *) message;
2019-01-23 18:03:33 +01:00
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);
2017-12-08 18:35:59 +01:00
2021-07-15 16:24:57 +02:00
auto mIter = resendRequests.find(response->req_msg_id);
2017-12-08 18:35:59 +01:00
if (mIter != resendRequests.end()) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("found resend for messageId 0x%" PRIx64, mIter->second);
2017-12-08 18:35:59 +01:00
connection->addMessageToConfirm(mIter->second);
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2017-12-08 18:35:59 +01:00
if (request->respondsToMessageId(mIter->second)) {
if (request->completed) {
break;
}
request->clear(true);
break;
}
}
resendRequests.erase(mIter);
}
2015-09-24 22:52:02 +02:00
} else if (dynamic_cast<MsgDetailedInfo *>(message)) {
2021-07-15 16:24:57 +02:00
auto response = (MsgDetailedInfo *) message;
2015-09-24 22:52:02 +02:00
bool requestResend = false;
bool confirm = true;
2019-01-23 18:03:33 +01:00
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);
2015-09-24 22:52:02 +02:00
if (typeInfo == typeid(TL_msg_detailed_info)) {
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2015-09-24 22:52:02 +02:00
if (request->respondsToMessageId(response->msg_id)) {
if (request->completed) {
break;
}
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("got TL_msg_detailed_info for rpc request %p - %s", request->rawRequest, typeid(*request->rawRequest).name());
2021-07-15 16:24:57 +02:00
auto currentTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000);
2024-03-08 15:32:16 +01:00
if (!request->cancelled && (request->lastResendTime == 0 || abs(currentTime - request->lastResendTime) >= 60)) {
2015-09-24 22:52:02 +02:00
request->lastResendTime = currentTime;
requestResend = true;
} else {
confirm = false;
}
break;
}
}
} else {
if (!connection->isMessageIdProcessed(messageId)) {
requestResend = true;
}
}
if (requestResend) {
2021-07-15 16:24:57 +02:00
auto request = new TL_msg_resend_req();
2015-09-24 22:52:02 +02:00
request->msg_ids.push_back(response->answer_msg_id);
2021-07-15 16:24:57 +02:00
auto networkMessage = new NetworkMessage();
networkMessage->message = std::make_unique<TL_message>();
2015-09-24 22:52:02 +02:00
networkMessage->message->msg_id = generateMessageId();
networkMessage->message->bytes = request->getObjectSize();
networkMessage->message->body = std::unique_ptr<TLObject>(request);
networkMessage->message->seqno = connection->generateMessageSeqNo(false);
2017-12-09 01:45:38 +01:00
resendRequests[networkMessage->message->msg_id] = response->answer_msg_id;
2015-09-24 22:52:02 +02:00
std::vector<std::unique_ptr<NetworkMessage>> array;
array.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
sendMessagesToConnection(array, connection, false);
} else if (confirm) {
connection->addMessageToConfirm(response->answer_msg_id);
}
} else if (typeInfo == typeid(TL_gzip_packed)) {
2021-07-15 16:24:57 +02:00
auto response = (TL_gzip_packed *) message;
2015-09-24 22:52:02 +02:00
NativeByteBuffer *data = decompressGZip(response->packed_data.get());
TLObject *object = TLdeserialize(getRequestWithMessageId(messageId), data->limit(), data);
if (object != nullptr) {
2019-01-23 18:03:33 +01:00
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());
2015-09-24 22:52:02 +02:00
processServerResponse(object, messageId, messageSeqNo, messageSalt, connection, innerMsgId, containerMessageId);
delete object;
} else {
2024-02-20 09:03:54 +01:00
if (LOGS_ENABLED) DEBUG_D("connection(%p, account%u, dc%u, type %d) received unparsed from gzip object on %0x" PRIx64, connection, instanceNum, datacenter->getDatacenterId(), connection->getConnectionType(), messageId);
2015-09-24 22:52:02 +02:00
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onUnparsedMessageReceived(messageId, data, connection->getConnectionType(), instanceNum);
2015-09-24 22:52:02 +02:00
}
}
data->reuse();
} else if (typeInfo == typeid(TL_updatesTooLong)) {
if (connection->connectionType == ConnectionTypePush) {
if (networkPaused) {
2017-03-31 01:58:05 +02:00
lastPauseTime = getCurrentTimeMonotonicMillis();
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("received internal push: wakeup network in background");
} else if (lastPauseTime != 0) {
2017-03-31 01:58:05 +02:00
lastPauseTime = getCurrentTimeMonotonicMillis();
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("received internal push: reset sleep timeout");
} else {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("received internal push");
}
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onInternalPushReceived(instanceNum);
}
2015-09-24 22:52:02 +02:00
} else {
if (delegate != nullptr) {
NativeByteBuffer *data = BuffersStorage::getInstance().getFreeBuffer(message->getObjectSize());
message->serializeToStream(data);
data->position(0);
2023-09-13 19:27:29 +02:00
delegate->onUnparsedMessageReceived(messageId, data, connection->getConnectionType(), instanceNum);
data->reuse();
}
2015-09-24 22:52:02 +02:00
}
}
}
void ConnectionsManager::sendPing(Datacenter *datacenter, bool usePushConnection) {
2016-04-22 15:49:00 +02:00
if (usePushConnection && (currentUserId == 0 || !usePushConnection)) {
2015-09-24 22:52:02 +02:00
return;
}
Connection *connection = nullptr;
if (usePushConnection) {
connection = datacenter->getPushConnection(true);
} else {
2018-07-30 04:07:02 +02:00
connection = datacenter->getGenericConnection(true, 0);
2015-09-24 22:52:02 +02:00
}
if (connection == nullptr || (!usePushConnection && connection->getConnectionToken() == 0)) {
return;
}
2021-07-15 16:24:57 +02:00
auto request = new TL_ping_delay_disconnect();
2015-09-24 22:52:02 +02:00
request->ping_id = ++lastPingId;
if (usePushConnection) {
request->disconnect_delay = 60 * 7;
2024-11-20 15:15:52 +01:00
sendingPushPingTime = getCurrentTimeMonotonicMillis();
2015-09-24 22:52:02 +02:00
} else {
2021-03-19 11:25:58 +01:00
request->disconnect_delay = testBackend ? 10 : 35;
2024-11-20 15:15:52 +01:00
pingTimeMs = getCurrentTimeMonotonicMillis();
pingTime = (int32_t) (pingTimeMs / 1000);
2015-09-24 22:52:02 +02:00
}
2021-07-15 16:24:57 +02:00
auto networkMessage = new NetworkMessage();
networkMessage->message = std::make_unique<TL_message>();
2015-09-24 22:52:02 +02:00
networkMessage->message->msg_id = generateMessageId();
networkMessage->message->bytes = request->getObjectSize();
networkMessage->message->body = std::unique_ptr<TLObject>(request);
networkMessage->message->seqno = connection->generateMessageSeqNo(false);
std::vector<std::unique_ptr<NetworkMessage>> array;
array.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
2018-07-30 04:07:02 +02:00
NativeByteBuffer *transportData = datacenter->createRequestsData(array, nullptr, connection, false);
2015-09-24 22:52:02 +02:00
if (usePushConnection) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("dc%d send ping to push connection", datacenter->getDatacenterId());
2015-09-24 22:52:02 +02:00
sendingPushPing = true;
2019-01-23 18:03:33 +01:00
} else {
sendingPing = true;
2015-09-24 22:52:02 +02:00
}
2018-07-30 04:07:02 +02:00
connection->sendData(transportData, false, true);
2015-09-24 22:52:02 +02:00
}
2021-02-24 02:02:54 +01:00
uint8_t ConnectionsManager::getIpStratagy() {
return ipStrategy;
2015-09-24 22:52:02 +02:00
}
void ConnectionsManager::initDatacenters() {
Datacenter *datacenter;
if (!testBackend) {
if (datacenters.find(1) == datacenters.end()) {
2018-07-30 04:07:02 +02:00
datacenter = new Datacenter(instanceNum, 1);
datacenter->addAddressAndPort("149.154.175.50", 443, 0, "");
datacenter->addAddressAndPort("2001:b28:f23d:f001:0000:0000:0000:000a", 443, 1, "");
2015-09-24 22:52:02 +02:00
datacenters[1] = datacenter;
}
if (datacenters.find(2) == datacenters.end()) {
2018-07-30 04:07:02 +02:00
datacenter = new Datacenter(instanceNum, 2);
datacenter->addAddressAndPort("149.154.167.51", 443, 0, "");
datacenter->addAddressAndPort("95.161.76.100", 443, 0, "");
2018-07-30 04:07:02 +02:00
datacenter->addAddressAndPort("2001:67c:4e8:f002:0000:0000:0000:000a", 443, 1, "");
2015-09-24 22:52:02 +02:00
datacenters[2] = datacenter;
}
if (datacenters.find(3) == datacenters.end()) {
2018-07-30 04:07:02 +02:00
datacenter = new Datacenter(instanceNum, 3);
datacenter->addAddressAndPort("149.154.175.100", 443, 0, "");
datacenter->addAddressAndPort("2001:b28:f23d:f003:0000:0000:0000:000a", 443, 1, "");
2015-09-24 22:52:02 +02:00
datacenters[3] = datacenter;
}
if (datacenters.find(4) == datacenters.end()) {
2018-07-30 04:07:02 +02:00
datacenter = new Datacenter(instanceNum, 4);
datacenter->addAddressAndPort("149.154.167.91", 443, 0, "");
datacenter->addAddressAndPort("2001:67c:4e8:f004:0000:0000:0000:000a", 443, 1, "");
2015-09-24 22:52:02 +02:00
datacenters[4] = datacenter;
}
if (datacenters.find(5) == datacenters.end()) {
2018-07-30 04:07:02 +02:00
datacenter = new Datacenter(instanceNum, 5);
datacenter->addAddressAndPort("149.154.171.5", 443, 0, "");
datacenter->addAddressAndPort("2001:b28:f23f:f005:0000:0000:0000:000a", 443, 1, "");
2015-09-24 22:52:02 +02:00
datacenters[5] = datacenter;
}
} else {
if (datacenters.find(1) == datacenters.end()) {
2018-07-30 04:07:02 +02:00
datacenter = new Datacenter(instanceNum, 1);
datacenter->addAddressAndPort("149.154.175.40", 443, 0, "");
datacenter->addAddressAndPort("2001:b28:f23d:f001:0000:0000:0000:000e", 443, 1, "");
2015-09-24 22:52:02 +02:00
datacenters[1] = datacenter;
}
if (datacenters.find(2) == datacenters.end()) {
2018-07-30 04:07:02 +02:00
datacenter = new Datacenter(instanceNum, 2);
datacenter->addAddressAndPort("149.154.167.40", 443, 0, "");
datacenter->addAddressAndPort("2001:67c:4e8:f002:0000:0000:0000:000e", 443, 1, "");
2015-09-24 22:52:02 +02:00
datacenters[2] = datacenter;
}
if (datacenters.find(3) == datacenters.end()) {
2018-07-30 04:07:02 +02:00
datacenter = new Datacenter(instanceNum, 3);
datacenter->addAddressAndPort("149.154.175.117", 443, 0, "");
datacenter->addAddressAndPort("2001:b28:f23d:f003:0000:0000:0000:000e", 443, 1, "");
2015-09-24 22:52:02 +02:00
datacenters[3] = datacenter;
}
}
}
void ConnectionsManager::attachConnection(ConnectionSocket *connection) {
if (std::find(activeConnections.begin(), activeConnections.end(), connection) != activeConnections.end()) {
return;
}
activeConnections.push_back(connection);
}
void ConnectionsManager::detachConnection(ConnectionSocket *connection) {
2021-07-15 16:24:57 +02:00
auto iter = std::find(activeConnections.begin(), activeConnections.end(), connection);
2015-09-24 22:52:02 +02:00
if (iter != activeConnections.end()) {
activeConnections.erase(iter);
}
}
2024-03-08 15:32:16 +01:00
int32_t ConnectionsManager::sendRequestInternal(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate) {
auto request = new Request(instanceNum, lastRequestToken++, connectionType, flags, datacenterId, onComplete, onQuickAck, nullptr, onClear);
2016-10-11 13:57:01 +02:00
request->rawRequest = object;
request->rpcRequest = wrapInLayer(object, getDatacenterWithId(datacenterId), request);
2023-02-25 09:01:39 +01:00
auto cancelledIterator = tokensToBeCancelled.find(request->requestToken);
if (cancelledIterator != tokensToBeCancelled.end()) {
2023-03-08 08:27:18 +01:00
if (LOGS_ENABLED) DEBUG_D("(3) request is cancelled before sending, token %d", request->requestToken);
2023-02-25 09:01:39 +01:00
tokensToBeCancelled.erase(cancelledIterator);
delete request;
return request->requestToken;
}
2023-07-20 22:15:36 +02:00
if (!currentUserId && !(flags & RequestFlagWithoutLogin)) {
if (LOGS_ENABLED) DEBUG_D("can't do request without login %s, reschedule token %d", typeid(*object).name(), request->requestToken);
waitingLoginRequests.push_back(std::unique_ptr<Request>(request));
} else {
requestsQueue.push_back(std::unique_ptr<Request>(request));
if (immediate) {
processRequestQueue(0, 0);
}
2016-10-11 13:57:01 +02:00
}
return request->requestToken;
}
2024-03-08 15:32:16 +01:00
int32_t ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate) {
2015-09-24 22:52:02 +02:00
int32_t requestToken = lastRequestToken++;
2024-03-08 15:32:16 +01:00
return sendRequest(object, onComplete, onQuickAck, onClear, flags, datacenterId, connectionType, immediate, requestToken);
2015-09-24 22:52:02 +02:00
}
2024-03-08 15:32:16 +01:00
int32_t ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate, int32_t requestToken) {
2018-07-30 04:07:02 +02:00
if (requestToken == 0) {
requestToken = lastRequestToken++;
2015-09-24 22:52:02 +02:00
}
2024-03-08 15:32:16 +01:00
scheduleTask([&, requestToken, object, onComplete, onQuickAck, onClear, flags, datacenterId, connectionType, immediate] {
auto request = new Request(instanceNum, requestToken, connectionType, flags, datacenterId, onComplete, onQuickAck, nullptr, onClear);
2015-09-24 22:52:02 +02:00
request->rawRequest = object;
request->rpcRequest = wrapInLayer(object, getDatacenterWithId(datacenterId), request);
2023-02-25 09:01:39 +01:00
auto cancelledIterator = tokensToBeCancelled.find(request->requestToken);
if (cancelledIterator != tokensToBeCancelled.end()) {
2023-03-08 08:27:18 +01:00
if (LOGS_ENABLED) DEBUG_D("(1) request is cancelled before sending, token %d", requestToken);
2023-02-25 09:01:39 +01:00
tokensToBeCancelled.erase(cancelledIterator);
delete request;
}
2023-07-20 22:15:36 +02:00
if (!currentUserId && !(flags & RequestFlagWithoutLogin)) {
if (LOGS_ENABLED) DEBUG_D("can't do request without login %s, reschedule token %d", typeid(*object).name(), requestToken);
waitingLoginRequests.push_back(std::unique_ptr<Request>(request));
} else {
requestsQueue.push_back(std::unique_ptr<Request>(request));
if (immediate) {
processRequestQueue(0, 0);
}
2015-09-24 22:52:02 +02:00
}
});
2018-07-30 04:07:02 +02:00
return requestToken;
2015-09-24 22:52:02 +02:00
}
#ifdef ANDROID
2024-03-08 15:32:16 +01:00
void ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onWriteToSocketFunc onWriteToSocket, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate, int32_t requestToken) {
scheduleTask([&, requestToken, object, onComplete, onQuickAck, onWriteToSocket, onClear, flags, datacenterId, connectionType, immediate] {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("send request %p - %s", object, typeid(*object).name());
2024-03-08 15:32:16 +01:00
auto request = new Request(instanceNum, requestToken, connectionType, flags, datacenterId, onComplete, onQuickAck, onWriteToSocket, onClear);
2015-09-24 22:52:02 +02:00
request->rawRequest = object;
request->rpcRequest = wrapInLayer(object, getDatacenterWithId(datacenterId), request);
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("send request wrapped %p - %s", request->rpcRequest.get(), typeid(*(request->rpcRequest.get())).name());
2023-02-25 09:01:39 +01:00
auto cancelledIterator = tokensToBeCancelled.find(request->requestToken);
if (cancelledIterator != tokensToBeCancelled.end()) {
2023-03-08 08:27:18 +01:00
if (LOGS_ENABLED) DEBUG_D("(2) request is cancelled before sending, token %d", requestToken);
2023-02-25 09:01:39 +01:00
tokensToBeCancelled.erase(cancelledIterator);
delete request;
return;
}
2023-07-20 22:15:36 +02:00
if (!currentUserId && !(flags & RequestFlagWithoutLogin)) {
if (LOGS_ENABLED) DEBUG_D("can't do request without login %s, reschedule token %d", typeid(*object).name(), request->requestToken);
waitingLoginRequests.push_back(std::unique_ptr<Request>(request));
} else {
requestsQueue.push_back(std::unique_ptr<Request>(request));
if (immediate) {
processRequestQueue(0, 0);
}
2015-09-24 22:52:02 +02:00
}
});
}
#endif
void ConnectionsManager::cancelRequestsForGuid(int32_t guid) {
scheduleTask([&, guid] {
2021-07-15 16:24:57 +02:00
auto iter = requestsByGuids.find(guid);
2015-09-24 22:52:02 +02:00
if (iter != requestsByGuids.end()) {
std::vector<int32_t> &requests = iter->second;
size_t count = requests.size();
for (uint32_t a = 0; a < count; a++) {
2024-03-08 15:32:16 +01:00
cancelRequestInternal(requests[a], 0, true, false, nullptr);
2021-07-15 16:24:57 +02:00
auto iter2 = guidsByRequests.find(requests[a]);
2015-09-24 22:52:02 +02:00
if (iter2 != guidsByRequests.end()) {
guidsByRequests.erase(iter2);
}
}
requestsByGuids.erase(iter);
}
});
}
void ConnectionsManager::bindRequestToGuid(int32_t requestToken, int32_t guid) {
scheduleTask([&, requestToken, guid] {
2021-07-15 16:24:57 +02:00
auto iter = requestsByGuids.find(guid);
2015-09-24 22:52:02 +02:00
if (iter != requestsByGuids.end()) {
iter->second.push_back(requestToken);
} else {
std::vector<int32_t> array;
array.push_back(requestToken);
requestsByGuids[guid] = array;
}
guidsByRequests[requestToken] = guid;
});
}
2023-10-28 22:52:06 +02:00
void ConnectionsManager::setUserPremium(bool premium) {
scheduleTask([&, premium] {
currentUserPremium = premium;
});
}
2021-09-20 07:54:41 +02:00
void ConnectionsManager::setUserId(int64_t userId) {
2015-09-24 22:52:02 +02:00
scheduleTask([&, userId] {
int32_t oldUserId = currentUserId;
currentUserId = userId;
if (oldUserId == userId && userId != 0) {
registerForInternalPushUpdates();
}
if (currentUserId != userId && userId != 0) {
2023-05-04 14:25:48 +02:00
updateDcSettings(0, false, false);
2015-09-24 22:52:02 +02:00
}
2016-04-22 15:49:00 +02:00
if (currentUserId != 0 && pushConnectionEnabled) {
2015-09-24 22:52:02 +02:00
Datacenter *datacenter = getDatacenterWithId(currentDatacenterId);
if (datacenter != nullptr) {
datacenter->createPushConnection()->setSessionId(pushSessionId);
sendPing(datacenter, true);
}
}
2023-07-20 22:15:36 +02:00
if (LOGS_ENABLED) DEBUG_D("set user %lld", userId);
if (currentUserId != 0 && !waitingLoginRequests.empty()) {
for (auto iter = waitingLoginRequests.begin(); iter != waitingLoginRequests.end(); iter++) {
Request *request = iter->get();
if (LOGS_ENABLED) DEBUG_D("run rescheduled request %d", request->requestToken);
requestsQueue.push_back(std::move(*iter));
}
processRequestQueue(0, 0);
waitingLoginRequests.clear();
}
2015-09-24 22:52:02 +02:00
});
}
2021-07-30 16:49:55 +02:00
void ConnectionsManager::switchBackend(bool restart) {
scheduleTask([&, restart] {
2017-07-08 18:32:04 +02:00
currentDatacenterId = 1;
2015-09-24 22:52:02 +02:00
testBackend = !testBackend;
2022-09-16 20:48:21 +02:00
if (!restart) {
Handshake::cleanupServerKeys();
}
2015-09-24 22:52:02 +02:00
datacenters.clear();
initDatacenters();
saveConfig();
2021-07-30 16:49:55 +02:00
if (restart) {
exit(1);
}
2015-09-24 22:52:02 +02:00
});
}
void ConnectionsManager::removeRequestFromGuid(int32_t requestToken) {
2021-07-15 16:24:57 +02:00
auto iter2 = guidsByRequests.find(requestToken);
2015-09-24 22:52:02 +02:00
if (iter2 != guidsByRequests.end()) {
2021-07-15 16:24:57 +02:00
auto iter = requestsByGuids.find(iter2->first);
2015-09-24 22:52:02 +02:00
if (iter != requestsByGuids.end()) {
2021-07-15 16:24:57 +02:00
auto iter3 = std::find(iter->second.begin(), iter->second.end(), iter->first);
2015-09-24 22:52:02 +02:00
if (iter3 != iter->second.end()) {
iter->second.erase(iter3);
if (iter->second.empty()) {
requestsByGuids.erase(iter);
}
}
}
guidsByRequests.erase(iter2);
}
}
2024-03-08 15:32:16 +01:00
bool ConnectionsManager::cancelRequestInternal(int32_t token, int64_t messageId, bool notifyServer, bool removeFromClass, onRequestCancelDoneFunc onCancelled) {
2023-02-25 09:01:39 +01:00
if (!tokensToBeCancelled.empty() && (connectionState != ConnectionStateWaitingForNetwork || tokensToBeCancelled.size() > 5000)) {
tokensToBeCancelled.clear();
}
2021-07-15 16:24:57 +02:00
for (auto iter = requestsQueue.begin(); iter != requestsQueue.end(); iter++) {
2015-09-24 22:52:02 +02:00
Request *request = iter->get();
2021-07-15 16:24:57 +02:00
if ((token != 0 && request->requestToken == token) || (messageId != 0 && request->respondsToMessageId(messageId))) {
2015-09-24 22:52:02 +02:00
request->cancelled = true;
2024-03-08 15:32:16 +01:00
const char* type = request->rawRequest == nullptr ? "" : typeid(*request->rawRequest).name();
if (LOGS_ENABLED) DEBUG_D("cancelled queued rpc request %p - %s of messageId 0x%" PRIx64, request->rawRequest, type, request->messageId);
2015-09-24 22:52:02 +02:00
requestsQueue.erase(iter);
if (removeFromClass) {
removeRequestFromGuid(token);
}
2016-10-11 13:57:01 +02:00
return true;
2015-09-24 22:52:02 +02:00
}
}
2023-07-20 22:15:36 +02:00
for (auto iter = waitingLoginRequests.begin(); iter != waitingLoginRequests.end(); iter++) {
Request *request = iter->get();
if ((token != 0 && request->requestToken == token) || (messageId != 0 && request->respondsToMessageId(messageId))) {
request->cancelled = true;
2024-03-08 15:32:16 +01:00
const char* type = request->rawRequest == nullptr ? "" : typeid(*request->rawRequest).name();
if (LOGS_ENABLED) DEBUG_D("cancelled waiting login rpc request %p - %s", request->rawRequest, type);
2023-07-20 22:15:36 +02:00
waitingLoginRequests.erase(iter);
if (removeFromClass) {
removeRequestFromGuid(token);
}
return true;
}
}
2021-07-15 16:24:57 +02:00
for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) {
2015-09-24 22:52:02 +02:00
Request *request = iter->get();
2024-03-08 15:32:16 +01:00
if (request == nullptr) continue;
2021-07-15 16:24:57 +02:00
if ((token != 0 && request->requestToken == token) || (messageId != 0 && request->respondsToMessageId(messageId))) {
2024-03-08 15:32:16 +01:00
request->cancelled = true;
bool erase = true;
if ((request->requestFlags & RequestFlagListenAfterCancel) != 0) {
int32_t token = request->requestToken;
auto oldOnCancelled = onCancelled;
if (onCancelled != nullptr) {
request->disableClearCallback = true;
}
onCancelled = [this, oldOnCancelled, token]() -> void {
for (auto iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) {
Request *request2 = iter2->get();
if (request2->requestToken == token && !request2->doNotClearOnDrop) {
request2->disableClearCallback = true;
if (LOGS_ENABLED) DEBUG_D("6) erase request %d 0x%" PRIx64, request2->requestToken, request2->messageId);
runningRequests.erase(iter2);
break;
}
}
if (oldOnCancelled != nullptr) {
oldOnCancelled();
}
};
erase = false;
}
2015-09-24 22:52:02 +02:00
if (notifyServer) {
2021-07-15 16:24:57 +02:00
auto dropAnswer = new TL_rpc_drop_answer();
2015-09-24 22:52:02 +02:00
dropAnswer->req_msg_id = request->messageId;
2024-03-08 15:32:16 +01:00
if (onCancelled != nullptr) {
2024-10-17 22:04:16 +02:00
sendRequest(dropAnswer, ([onCancelled](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) -> void {
2024-03-08 15:32:16 +01:00
if (onCancelled != nullptr) {
onCancelled();
}
}), nullptr, ([onCancelled]() -> void {
if (onCancelled != nullptr) {
onCancelled();
}
}), RequestFlagEnableUnauthorized | RequestFlagWithoutLogin | RequestFlagFailOnServerErrors | RequestFlagIsCancel, request->datacenterId, request->connectionType, true);
} else {
sendRequest(dropAnswer, nullptr, nullptr, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin | RequestFlagFailOnServerErrors | RequestFlagIsCancel, request->datacenterId, request->connectionType, true);
}
} else if (onCancelled != nullptr) {
onCancelled();
}
const char* type = request->rawRequest == nullptr ? "" : typeid(*request->rawRequest).name();
if (LOGS_ENABLED) DEBUG_D("cancelled running rpc request %p - %s, of messageId 0x%" PRIx64 " notify=%d", request->rawRequest, type, request->messageId, notifyServer);
if (erase) {
if (LOGS_ENABLED) DEBUG_D("7) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
runningRequests.erase(iter);
2015-09-24 22:52:02 +02:00
}
if (removeFromClass) {
removeRequestFromGuid(token);
}
2016-10-11 13:57:01 +02:00
return true;
2015-09-24 22:52:02 +02:00
}
}
2023-02-25 09:01:39 +01:00
if (token != 0 && connectionState == ConnectionStateWaitingForNetwork) {
2023-03-08 08:27:18 +01:00
if (LOGS_ENABLED) DEBUG_D("request is tried to be cancelled, but it does not even exist, token %d", token);
2023-02-25 09:01:39 +01:00
tokensToBeCancelled.insert(token);
}
2016-10-11 13:57:01 +02:00
return false;
2015-09-24 22:52:02 +02:00
}
2024-03-08 15:32:16 +01:00
void ConnectionsManager::cancelRequest(int32_t token, bool notifyServer, onRequestCancelDoneFunc onCancelled) {
2015-09-24 22:52:02 +02:00
if (token == 0) {
return;
}
2024-03-08 15:32:16 +01:00
scheduleTask([&, token, notifyServer, onCancelled] {
cancelRequestInternal(token, 0, notifyServer, true, onCancelled);
2015-09-24 22:52:02 +02:00
});
}
2023-07-20 22:15:36 +02:00
void ConnectionsManager::failNotRunningRequest(int32_t token) {
if (token == 0) {
return;
}
scheduleTask([&, token] {
for (auto iter = requestsQueue.begin(); iter != requestsQueue.end(); iter++) {
Request *request = iter->get();
if ((token != 0 && request->requestToken == token)) {
auto error = new TL_error();
error->code = -2000;
error->text = "CANCELLED_REQUEST";
2024-10-17 22:04:16 +02:00
int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId;
request->onComplete(nullptr, error, 0, 0, request->messageId, dcId);
2023-07-20 22:15:36 +02:00
request->cancelled = true;
if (LOGS_ENABLED) DEBUG_D("cancelled queued rpc request %p - %s", request->rawRequest, typeid(*request->rawRequest).name());
requestsQueue.erase(iter);
removeRequestFromGuid(token);
return true;
}
}
});
}
2024-06-03 08:21:03 +02:00
void ConnectionsManager::receivedIntegrityCheckClassic(int32_t requestToken, std::string nonce, std::string token) {
scheduleTask([&, requestToken, nonce, token] {
for (auto iter = runningRequests.begin(); iter != runningRequests.end(); iter++) {
Request *request = iter->get();
if (requestToken != 0 && request->requestToken == requestToken) {
auto invokeIntegrity = new invokeWithGooglePlayIntegrity();
invokeIntegrity->nonce = nonce;
invokeIntegrity->token = token;
invokeIntegrity->query = std::move(request->rpcRequest);
request->rpcRequest = std::unique_ptr<invokeWithGooglePlayIntegrity>(invokeIntegrity);
request->awaitingIntegrityCheck = false;
request->requestFlags &=~ RequestFlagFailOnServerErrors;
if (LOGS_ENABLED) DEBUG_D("account%d: received integrity token, wrapping %s", instanceNum, token.c_str());
processRequestQueue(request->connectionType, request->datacenterId);
return;
}
}
if (LOGS_ENABLED) DEBUG_E("account%d: received integrity token but no request %d found", instanceNum, requestToken);
});
}
2018-07-30 04:07:02 +02:00
void ConnectionsManager::onDatacenterHandshakeComplete(Datacenter *datacenter, HandshakeType type, int32_t timeDiff) {
2015-09-24 22:52:02 +02:00
saveConfig();
uint32_t datacenterId = datacenter->getDatacenterId();
2019-08-22 01:53:26 +02:00
if (datacenterId == currentDatacenterId || datacenterId == movingToDatacenterId || updatingDcSettingsWorkaround || updatingDcSettings) {
2015-09-24 22:52:02 +02:00
timeDifference = timeDiff;
2018-07-30 04:07:02 +02:00
datacenter->recreateSessions(type);
clearRequestsForDatacenter(datacenter, type);
2015-09-24 22:52:02 +02:00
}
processRequestQueue(AllConnectionTypes, datacenterId);
2018-07-30 04:07:02 +02:00
if (type == HandshakeTypeTemp && !proxyCheckQueue.empty()) {
ProxyCheckInfo *proxyCheckInfo = proxyCheckQueue[0].release();
proxyCheckQueue.erase(proxyCheckQueue.begin());
2019-07-18 15:01:39 +02:00
scheduleCheckProxyInternal(proxyCheckInfo);
2018-07-30 04:07:02 +02:00
}
2015-09-24 22:52:02 +02:00
}
void ConnectionsManager::onDatacenterExportAuthorizationComplete(Datacenter *datacenter) {
saveConfig();
2018-07-30 04:07:02 +02:00
scheduleTask([&, datacenter] {
processRequestQueue(AllConnectionTypes, datacenter->getDatacenterId());
});
2015-09-24 22:52:02 +02:00
}
void ConnectionsManager::sendMessagesToConnection(std::vector<std::unique_ptr<NetworkMessage>> &messages, Connection *connection, bool reportAck) {
if (messages.empty() || connection == nullptr) {
return;
}
std::vector<std::unique_ptr<NetworkMessage>> currentMessages;
Datacenter *datacenter = connection->getDatacenter();
uint32_t currentSize = 0;
size_t count = messages.size();
for (uint32_t a = 0; a < count; a++) {
NetworkMessage *networkMessage = messages[a].get();
currentMessages.push_back(std::move(messages[a]));
currentSize += networkMessage->message->bytes;
if (currentSize >= 3 * 1024 || a == count - 1) {
int32_t quickAckId = 0;
2018-07-30 04:07:02 +02:00
NativeByteBuffer *transportData = datacenter->createRequestsData(currentMessages, reportAck ? &quickAckId : nullptr, connection, false);
2015-09-24 22:52:02 +02:00
if (transportData != nullptr) {
if (reportAck && quickAckId != 0) {
std::vector<int32_t> requestIds;
size_t count2 = currentMessages.size();
for (uint32_t b = 0; b < count2; b++) {
NetworkMessage *message = currentMessages[b].get();
if (message->requestId != 0) {
requestIds.push_back(message->requestId);
}
}
if (!requestIds.empty()) {
2021-07-15 16:24:57 +02:00
auto iter = quickAckIdToRequestIds.find(quickAckId);
2015-09-24 22:52:02 +02:00
if (iter == quickAckIdToRequestIds.end()) {
quickAckIdToRequestIds[quickAckId] = requestIds;
} else {
iter->second.insert(iter->second.end(), requestIds.begin(), requestIds.end());
}
}
}
2018-07-30 04:07:02 +02:00
connection->sendData(transportData, reportAck, true);
2015-09-24 22:52:02 +02:00
} else {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("connection(%p) connection data is empty", connection);
2015-09-24 22:52:02 +02:00
}
currentSize = 0;
currentMessages.clear();
}
}
}
void ConnectionsManager::sendMessagesToConnectionWithConfirmation(std::vector<std::unique_ptr<NetworkMessage>> &messages, Connection *connection, bool reportAck) {
NetworkMessage *networkMessage = connection->generateConfirmationRequest();
if (networkMessage != nullptr) {
messages.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
}
sendMessagesToConnection(messages, connection, reportAck);
}
2019-12-31 14:08:08 +01:00
void ConnectionsManager::requestSaltsForDatacenter(Datacenter *datacenter, bool media, bool useTempConnection) {
2019-08-22 01:53:26 +02:00
uint32_t id = datacenter->getDatacenterId();
if (useTempConnection) {
id |= 0x80000000;
}
2019-12-31 14:08:08 +01:00
if (media) {
id |= 0x40000000;
}
2019-08-22 01:53:26 +02:00
if (std::find(requestingSaltsForDc.begin(), requestingSaltsForDc.end(), id) != requestingSaltsForDc.end()) {
2015-09-24 22:52:02 +02:00
return;
}
2019-12-31 14:08:08 +01:00
ConnectionType connectionType;
if (media) {
connectionType = ConnectionTypeGenericMedia;
} else if (useTempConnection) {
connectionType = ConnectionTypeTemp;
} else {
connectionType = ConnectionTypeGeneric;
}
requestingSaltsForDc.push_back(id);
2021-07-15 16:24:57 +02:00
auto request = new TL_get_future_salts();
2015-09-24 22:52:02 +02:00
request->num = 32;
2024-10-17 22:04:16 +02:00
sendRequest(request, [&, datacenter, id, media](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) {
2021-07-15 16:24:57 +02:00
auto iter = std::find(requestingSaltsForDc.begin(), requestingSaltsForDc.end(), id);
2015-09-24 22:52:02 +02:00
if (iter != requestingSaltsForDc.end()) {
requestingSaltsForDc.erase(iter);
}
if (response != nullptr) {
datacenter->mergeServerSalts((TL_future_salts *) response, media);
2015-09-24 22:52:02 +02:00
saveConfig();
}
2024-03-08 15:32:16 +01:00
}, nullptr, nullptr, RequestFlagWithoutLogin | RequestFlagEnableUnauthorized | RequestFlagUseUnboundKey, datacenter->getDatacenterId(), connectionType, true);
2015-09-24 22:52:02 +02:00
}
2018-07-30 04:07:02 +02:00
void ConnectionsManager::clearRequestsForDatacenter(Datacenter *datacenter, HandshakeType type) {
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2015-09-24 22:52:02 +02:00
Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId);
2018-07-30 04:07:02 +02:00
if (requestDatacenter->getDatacenterId() != datacenter->getDatacenterId()) {
continue;
}
2021-07-15 16:24:57 +02:00
if (type == HandshakeTypePerm || type == HandshakeTypeAll || (type == HandshakeTypeMediaTemp && request->isMediaRequest()) || (type == HandshakeTypeTemp && !request->isMediaRequest())) {
2015-09-24 22:52:02 +02:00
request->clear(true);
}
}
}
void ConnectionsManager::registerForInternalPushUpdates() {
if (registeringForPush || !currentUserId) {
return;
}
registeredForInternalPush = false;
registeringForPush = true;
2021-07-15 16:24:57 +02:00
auto request = new TL_account_registerDevice();
2015-09-24 22:52:02 +02:00
request->token_type = 7;
2018-07-30 04:07:02 +02:00
request->token = to_string_uint64((uint64_t) pushSessionId);
2015-09-24 22:52:02 +02:00
2024-10-17 22:04:16 +02:00
sendRequest(request, [&](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) {
2015-09-24 22:52:02 +02:00
if (error == nullptr) {
registeredForInternalPush = true;
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("registered for internal push");
2015-09-24 22:52:02 +02:00
} else {
registeredForInternalPush = false;
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("unable to registering for internal push");
2015-09-24 22:52:02 +02:00
}
saveConfig();
registeringForPush = false;
2024-03-08 15:32:16 +01:00
}, nullptr, nullptr, 0, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true);
2015-09-24 22:52:02 +02:00
}
2017-07-08 18:32:04 +02:00
inline void addMessageToDatacenter(uint32_t datacenterId, NetworkMessage *networkMessage, std::map<uint32_t, std::vector<std::unique_ptr<NetworkMessage>>> &messagesToDatacenters) {
2021-07-15 16:24:57 +02:00
auto iter = messagesToDatacenters.find(datacenterId);
2017-07-08 18:32:04 +02:00
if (iter == messagesToDatacenters.end()) {
std::vector<std::unique_ptr<NetworkMessage>> &array = messagesToDatacenters[datacenterId] = std::vector<std::unique_ptr<NetworkMessage>>();
2015-09-24 22:52:02 +02:00
array.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
} else {
iter->second.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
}
}
2024-03-08 15:32:16 +01:00
// since we no longer save 3 global refs per request, can we make request count limits higher?
#define MAX_GENERAL_REQUESTS 60 * 8
#define MAX_DOWNLOAD_REQUESTS_CANCELS 24 * 2
#define MAX_DOWNLOAD_REQUESTS_PREMIUM 32 * 2
#define MAX_DOWNLOAD_REQUESTS 16 * 2
#define MAX_UPLOAD_REQUESTS 10 * 3
2015-09-24 22:52:02 +02:00
void ConnectionsManager::processRequestQueue(uint32_t connectionTypes, uint32_t dc) {
genericMessagesToDatacenters.clear();
2018-07-30 04:07:02 +02:00
genericMediaMessagesToDatacenters.clear();
2017-07-08 18:32:04 +02:00
tempMessagesToDatacenters.clear();
2015-09-24 22:52:02 +02:00
unknownDatacenterIds.clear();
neededDatacenters.clear();
unauthorizedDatacenters.clear();
2018-07-30 04:07:02 +02:00
downloadRunningRequestCount.clear();
2023-10-28 22:52:06 +02:00
downloadCancelRunningRequestCount.clear();
2015-09-24 22:52:02 +02:00
2018-07-30 04:07:02 +02:00
int64_t currentTimeMillis = getCurrentTimeMonotonicMillis();
2021-07-15 16:24:57 +02:00
auto currentTime = (int32_t) (currentTimeMillis / 1000);
2015-09-24 22:52:02 +02:00
uint32_t genericRunningRequestCount = 0;
uint32_t uploadRunningRequestCount = 0;
2021-07-15 16:24:57 +02:00
bool hasInvokeAfterMessage = false;
bool hasInvokeWaitMessage = false;
2015-09-24 22:52:02 +02:00
2021-07-15 16:24:57 +02:00
for (auto iter = runningRequests.begin(); iter != runningRequests.end();) {
2015-09-24 22:52:02 +02:00
Request *request = iter->get();
2024-03-08 15:32:16 +01:00
if (request->cancelled) {
if (request->doNotClearOnDrop && currentTime > request->clearAfter) {
DEBUG_D("16) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
iter = runningRequests.erase(iter);
} else {
iter++;
}
continue;
}
2015-09-24 22:52:02 +02:00
const std::type_info &typeInfo = typeid(*request->rawRequest);
2018-07-30 04:07:02 +02:00
uint32_t datacenterId = request->datacenterId;
if (datacenterId == DEFAULT_DATACENTER_ID) {
if (movingToDatacenterId != DEFAULT_DATACENTER_ID) {
iter++;
continue;
}
datacenterId = currentDatacenterId;
}
2021-07-15 16:24:57 +02:00
if ((request->requestFlags & RequestFlagResendAfter) != 0) {
hasInvokeWaitMessage = true;
if (hasInvokeAfterMessage) {
iter++;
continue;
}
}
if (!hasInvokeAfterMessage && (request->requestFlags & RequestFlagInvokeAfter) != 0) {
hasInvokeAfterMessage = true;
}
2018-07-30 04:07:02 +02:00
2015-09-24 22:52:02 +02:00
switch (request->connectionType & 0x0000ffff) {
case ConnectionTypeGeneric:
2023-11-15 13:23:35 +01:00
if (!request->failedByFloodWait) {
genericRunningRequestCount++;
}
2015-09-24 22:52:02 +02:00
break;
2018-07-30 04:07:02 +02:00
case ConnectionTypeDownload: {
2023-10-28 22:52:06 +02:00
auto map = request->isCancelRequest() ? downloadCancelRunningRequestCount : downloadRunningRequestCount;
2018-07-30 04:07:02 +02:00
uint32_t currentCount;
2023-10-28 22:52:06 +02:00
auto dcIter = map.find(datacenterId);
if (dcIter != map.end()) {
2018-07-30 04:07:02 +02:00
currentCount = dcIter->second;
} else {
currentCount = 0;
}
2023-10-28 22:52:06 +02:00
map[datacenterId] = currentCount + 1;
2015-09-24 22:52:02 +02:00
break;
2018-07-30 04:07:02 +02:00
}
2015-09-24 22:52:02 +02:00
case ConnectionTypeUpload:
uploadRunningRequestCount++;
break;
default:
break;
}
if (request->requestFlags & RequestFlagTryDifferentDc) {
int32_t requestStartTime = request->startTime;
int32_t timeout = 30;
if (updatingDcSettings && dynamic_cast<TL_help_getConfig *>(request->rawRequest)) {
requestStartTime = updatingDcStartTime;
updatingDcStartTime = currentTime;
timeout = 60;
}
if (request->startTime != 0 && abs(currentTime - requestStartTime) >= timeout) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("move %s to requestsQueue", typeid(*request->rawRequest).name());
2015-09-24 22:52:02 +02:00
requestsQueue.push_back(std::move(*iter));
2024-03-08 15:32:16 +01:00
DEBUG_D("10) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
2015-09-24 22:52:02 +02:00
iter = runningRequests.erase(iter);
continue;
}
}
2018-07-30 04:07:02 +02:00
int32_t canUseUnboundKey = 0;
if ((request->requestFlags & RequestFlagUseUnboundKey) != 0) {
canUseUnboundKey |= 1;
}
2015-09-24 22:52:02 +02:00
Datacenter *requestDatacenter = getDatacenterWithId(datacenterId);
if (requestDatacenter == nullptr) {
if (std::find(unknownDatacenterIds.begin(), unknownDatacenterIds.end(), datacenterId) == unknownDatacenterIds.end()) {
unknownDatacenterIds.push_back(datacenterId);
}
iter++;
continue;
2017-07-08 18:32:04 +02:00
} else {
if (requestDatacenter->isCdnDatacenter) {
request->requestFlags |= RequestFlagEnableUnauthorized;
2015-09-24 22:52:02 +02:00
}
2018-07-30 04:07:02 +02:00
if (request->needInitRequest(requestDatacenter, currentVersion) && !request->hasInitFlag() && request->rawRequest->isNeedLayer()) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("move %p - %s to requestsQueue because of initConnection", request->rawRequest, typeid(*request->rawRequest).name());
2017-12-08 18:35:59 +01:00
requestsQueue.push_back(std::move(*iter));
2024-03-08 15:32:16 +01:00
DEBUG_D("11) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
2017-12-08 18:35:59 +01:00
iter = runningRequests.erase(iter);
continue;
2017-07-08 18:32:04 +02:00
}
2018-07-30 04:07:02 +02:00
if (!requestDatacenter->hasAuthKey(request->connectionType, canUseUnboundKey)) {
std::pair<Datacenter *, ConnectionType> pair = std::make_pair(requestDatacenter, request->connectionType);
if (std::find(neededDatacenters.begin(), neededDatacenters.end(), pair) == neededDatacenters.end()) {
neededDatacenters.push_back(pair);
2017-07-08 18:32:04 +02:00
}
iter++;
continue;
} else if (!(request->requestFlags & RequestFlagEnableUnauthorized) && !requestDatacenter->authorized && request->datacenterId != DEFAULT_DATACENTER_ID && request->datacenterId != currentDatacenterId) {
if (std::find(unauthorizedDatacenters.begin(), unauthorizedDatacenters.end(), requestDatacenter) == unauthorizedDatacenters.end()) {
unauthorizedDatacenters.push_back(requestDatacenter);
}
iter++;
continue;
2015-09-24 22:52:02 +02:00
}
}
2018-07-30 04:07:02 +02:00
Connection *connection = requestDatacenter->getConnectionByType(request->connectionType, true, canUseUnboundKey);
2015-09-24 22:52:02 +02:00
int32_t maxTimeout = request->connectionType & ConnectionTypeGeneric ? 8 : 30;
if (!networkAvailable || connection->getConnectionToken() == 0) {
iter++;
continue;
}
2015-10-29 18:10:07 +01:00
uint32_t requestConnectionType = request->connectionType & 0x0000ffff;
2018-07-30 04:07:02 +02:00
2015-10-29 18:10:07 +01:00
bool forceThisRequest = (connectionTypes & requestConnectionType) && requestDatacenter->getDatacenterId() == dc;
2015-09-24 22:52:02 +02:00
2020-01-02 16:08:53 +01:00
if (typeInfo == typeid(TL_get_future_salts)) {
2015-09-24 22:52:02 +02:00
if (request->messageId != 0) {
request->addRespondMessageId(request->messageId);
}
request->clear(false);
forceThisRequest = false;
}
2024-06-03 08:21:03 +02:00
if ((forceThisRequest || (
2024-02-20 09:03:54 +01:00
abs(currentTime - request->startTime) > maxTimeout && (
currentTime >= request->minStartTime ||
(request->failedByFloodWait != 0 && (request->minStartTime - currentTime) > request->failedByFloodWait) ||
(request->failedByFloodWait == 0 && abs(currentTime - request->minStartTime) >= 60)
)
2024-06-03 08:21:03 +02:00
)) && !request->awaitingIntegrityCheck) {
2015-09-24 22:52:02 +02:00
if (!forceThisRequest && request->connectionToken > 0) {
2017-07-08 18:32:04 +02:00
if ((request->connectionType & ConnectionTypeGeneric || request->connectionType & ConnectionTypeTemp) && request->connectionToken == connection->getConnectionToken()) {
2024-11-20 15:15:52 +01:00
// if (LOGS_ENABLED) DEBUG_D("request token is valid, not retrying %s (%p)", typeInfo.name(), request->rawRequest);
2015-09-24 22:52:02 +02:00
iter++;
continue;
} else {
if (connection->getConnectionToken() != 0 && request->connectionToken == connection->getConnectionToken()) {
2024-11-20 15:15:52 +01:00
// if (LOGS_ENABLED) DEBUG_D("request download token is valid, not retrying %s (%p)", typeInfo.name(), request->rawRequest);
2015-09-24 22:52:02 +02:00
iter++;
continue;
}
}
}
if (request->connectionToken != 0 && request->connectionToken != connection->getConnectionToken()) {
request->lastResendTime = 0;
2021-07-15 16:24:57 +02:00
request->isResending = true;
2015-09-24 22:52:02 +02:00
}
request->retryCount++;
2015-11-26 22:04:02 +01:00
if (!request->failedBySalt) {
if (request->connectionType & ConnectionTypeDownload) {
uint32_t retryMax = 10;
if (!(request->requestFlags & RequestFlagForceDownload)) {
if (request->failedByFloodWait) {
2020-01-05 12:50:11 +01:00
retryMax = 2;
2015-11-26 22:04:02 +01:00
} else {
retryMax = 6;
}
}
2024-03-31 21:10:51 +02:00
if (request->retryCount >= retryMax && !request->premiumFloodWait) {
2024-02-06 17:34:03 +01:00
if (LOGS_ENABLED) DEBUG_E("timed out %s, message_id = 0x%" PRIx64, typeInfo.name(), request->messageId);
2021-07-15 16:24:57 +02:00
auto error = new TL_error();
2015-11-26 22:04:02 +01:00
error->code = -123;
error->text = "RETRY_LIMIT";
2024-10-17 22:04:16 +02:00
int32_t dcId = request->datacenterId != DEFAULT_DATACENTER_ID ? request->datacenterId : currentDatacenterId;
request->onComplete(nullptr, error, connection->currentNetworkType, 0, request->messageId, dcId);
2015-11-26 22:04:02 +01:00
delete error;
2024-03-08 15:32:16 +01:00
DEBUG_D("12) erase request %d 0x%" PRIx64, request->requestToken, request->messageId);
2015-11-26 22:04:02 +01:00
iter = runningRequests.erase(iter);
continue;
2015-09-24 22:52:02 +02:00
}
}
2015-11-26 22:04:02 +01:00
} else {
request->failedBySalt = false;
2015-09-24 22:52:02 +02:00
}
if (request->messageSeqNo == 0) {
2018-07-30 04:07:02 +02:00
request->messageSeqNo = connection->generateMessageSeqNo((request->connectionType & ConnectionTypeProxy) == 0);
2015-09-24 22:52:02 +02:00
request->messageId = generateMessageId();
2018-07-30 04:07:02 +02:00
if (request->rawRequest->initFunc != nullptr) {
request->rawRequest->initFunc(request->messageId);
}
2015-09-24 22:52:02 +02:00
}
request->startTime = currentTime;
2018-07-30 04:07:02 +02:00
request->startTimeMillis = currentTimeMillis;
2015-09-24 22:52:02 +02:00
2021-07-15 16:24:57 +02:00
auto networkMessage = new NetworkMessage();
networkMessage->forceContainer = request->isResending;
networkMessage->message = std::make_unique<TL_message>();
2015-09-24 22:52:02 +02:00
networkMessage->message->msg_id = request->messageId;
networkMessage->message->bytes = request->serializedLength;
networkMessage->message->outgoingBody = request->getRpcRequest();
networkMessage->message->seqno = request->messageSeqNo;
networkMessage->requestId = request->requestToken;
2021-07-15 16:24:57 +02:00
networkMessage->invokeAfter = (request->requestFlags & RequestFlagInvokeAfter) != 0 && (request->requestFlags & RequestFlagResendAfter) == 0;
2015-09-24 22:52:02 +02:00
networkMessage->needQuickAck = (request->requestFlags & RequestFlagNeedQuickAck) != 0;
request->connectionToken = connection->getConnectionToken();
2015-10-29 18:10:07 +01:00
switch (requestConnectionType) {
2015-09-24 22:52:02 +02:00
case ConnectionTypeGeneric:
addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters);
break;
2018-07-30 04:07:02 +02:00
case ConnectionTypeGenericMedia:
addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMediaMessagesToDatacenters);
break;
2017-07-08 18:32:04 +02:00
case ConnectionTypeTemp:
addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, tempMessagesToDatacenters);
break;
2018-07-30 04:07:02 +02:00
case ConnectionTypeProxy: {
std::vector<std::unique_ptr<NetworkMessage>> array;
array.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
sendMessagesToConnection(array, connection, false);
break;
}
2015-09-24 22:52:02 +02:00
case ConnectionTypeDownload:
case ConnectionTypeUpload: {
std::vector<std::unique_ptr<NetworkMessage>> array;
array.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
sendMessagesToConnectionWithConfirmation(array, connection, false);
2017-07-08 18:32:04 +02:00
request->onWriteToSocket();
2015-09-24 22:52:02 +02:00
break;
}
default:
delete networkMessage;
}
}
iter++;
}
2018-07-30 04:07:02 +02:00
Connection *genericConnection = nullptr;
Datacenter *defaultDatacenter = getDatacenterWithId(currentDatacenterId);
if (defaultDatacenter != nullptr) {
genericConnection = defaultDatacenter->getGenericConnection(true, 0);
if (genericConnection != nullptr && !sessionsToDestroy.empty() && genericConnection->getConnectionToken() != 0) {
2021-07-15 16:24:57 +02:00
auto iter = sessionsToDestroy.begin();
2015-09-24 22:52:02 +02:00
2018-07-30 04:07:02 +02:00
if (abs(currentTime - lastDestroySessionRequestTime) > 2) {
lastDestroySessionRequestTime = currentTime;
2021-07-15 16:24:57 +02:00
auto request = new TL_destroy_session();
2018-07-30 04:07:02 +02:00
request->session_id = *iter;
2015-09-24 22:52:02 +02:00
2021-07-15 16:24:57 +02:00
auto networkMessage = new NetworkMessage();
networkMessage->message = std::make_unique<TL_message>();
2018-07-30 04:07:02 +02:00
networkMessage->message->msg_id = generateMessageId();
networkMessage->message->bytes = request->getObjectSize();
networkMessage->message->body = std::unique_ptr<TLObject>(request);
networkMessage->message->seqno = genericConnection->generateMessageSeqNo(false);
addMessageToDatacenter(defaultDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters);
}
sessionsToDestroy.erase(iter);
2015-09-24 22:52:02 +02:00
}
}
2021-07-15 16:24:57 +02:00
for (auto iter = requestsQueue.begin(); iter != requestsQueue.end();) {
2015-09-24 22:52:02 +02:00
Request *request = iter->get();
if (request->cancelled) {
iter = requestsQueue.erase(iter);
2023-10-28 22:52:06 +02:00
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: cancelled", request->requestToken);
2015-09-24 22:52:02 +02:00
continue;
}
2021-07-15 16:24:57 +02:00
if (hasInvokeWaitMessage && (request->requestFlags & RequestFlagInvokeAfter) != 0 && (request->requestFlags & RequestFlagResendAfter) == 0) {
request->requestFlags |= RequestFlagResendAfter;
}
if (hasInvokeAfterMessage && (request->requestFlags & RequestFlagResendAfter) != 0) {
iter++;
continue;
}
if (!hasInvokeAfterMessage && (request->requestFlags & RequestFlagInvokeAfter) != 0) {
hasInvokeAfterMessage = true;
}
2015-09-24 22:52:02 +02:00
uint32_t datacenterId = request->datacenterId;
if (datacenterId == DEFAULT_DATACENTER_ID) {
if (movingToDatacenterId != DEFAULT_DATACENTER_ID) {
iter++;
2023-10-28 22:52:06 +02:00
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: moving dc", request->requestToken);
2015-09-24 22:52:02 +02:00
continue;
}
datacenterId = currentDatacenterId;
}
2018-07-30 04:07:02 +02:00
int32_t canUseUnboundKey = 0;
if ((request->requestFlags & RequestFlagUseUnboundKey) != 0) {
canUseUnboundKey |= 1;
}
2015-09-24 22:52:02 +02:00
if (request->requestFlags & RequestFlagTryDifferentDc) {
int32_t requestStartTime = request->startTime;
int32_t timeout = 30;
if (updatingDcSettings && dynamic_cast<TL_help_getConfig *>(request->rawRequest)) {
requestStartTime = updatingDcStartTime;
timeout = 60;
} else {
request->startTime = 0;
2018-07-30 04:07:02 +02:00
request->startTimeMillis = 0;
2015-09-24 22:52:02 +02:00
}
if (requestStartTime != 0 && abs(currentTime - requestStartTime) >= timeout) {
std::vector<uint32_t> allDc;
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
if (datacenter.first == datacenterId || datacenter.second->isCdnDatacenter) {
2015-09-24 22:52:02 +02:00
continue;
}
2021-07-15 16:24:57 +02:00
allDc.push_back(datacenter.first);
2015-09-24 22:52:02 +02:00
}
uint8_t index;
RAND_bytes(&index, 1);
datacenterId = allDc[index % allDc.size()];
if (dynamic_cast<TL_help_getConfig *>(request->rawRequest)) {
updatingDcStartTime = currentTime;
request->datacenterId = datacenterId;
} else {
currentDatacenterId = datacenterId;
}
}
}
Datacenter *requestDatacenter = getDatacenterWithId(datacenterId);
if (requestDatacenter == nullptr) {
if (std::find(unknownDatacenterIds.begin(), unknownDatacenterIds.end(), datacenterId) == unknownDatacenterIds.end()) {
unknownDatacenterIds.push_back(datacenterId);
}
2023-10-28 22:52:06 +02:00
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: unknown dc", request->requestToken);
2015-09-24 22:52:02 +02:00
iter++;
continue;
2017-07-08 18:32:04 +02:00
} else {
2018-07-30 04:07:02 +02:00
if (request->needInitRequest(requestDatacenter, currentVersion) && !request->hasInitFlag()) {
2017-07-08 18:32:04 +02:00
request->rpcRequest.release();
request->rpcRequest = wrapInLayer(request->rawRequest, requestDatacenter, request);
2015-09-24 22:52:02 +02:00
}
2017-07-08 18:32:04 +02:00
2018-07-30 04:07:02 +02:00
if (!requestDatacenter->hasAuthKey(request->connectionType, canUseUnboundKey)) {
std::pair<Datacenter *, ConnectionType> pair = std::make_pair(requestDatacenter, request->connectionType);
if (std::find(neededDatacenters.begin(), neededDatacenters.end(), pair) == neededDatacenters.end()) {
neededDatacenters.push_back(pair);
2017-07-08 18:32:04 +02:00
}
2023-10-28 22:52:06 +02:00
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: no authkey for dc", request->requestToken);
2017-07-08 18:32:04 +02:00
iter++;
continue;
} else if (!(request->requestFlags & RequestFlagEnableUnauthorized) && !requestDatacenter->authorized && request->datacenterId != DEFAULT_DATACENTER_ID && request->datacenterId != currentDatacenterId) {
if (std::find(unauthorizedDatacenters.begin(), unauthorizedDatacenters.end(), requestDatacenter) == unauthorizedDatacenters.end()) {
unauthorizedDatacenters.push_back(requestDatacenter);
}
2023-10-28 22:52:06 +02:00
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: dc is unauthorized", request->requestToken);
2017-07-08 18:32:04 +02:00
iter++;
continue;
2015-09-24 22:52:02 +02:00
}
}
2018-07-30 04:07:02 +02:00
Connection *connection = requestDatacenter->getConnectionByType(request->connectionType, true, canUseUnboundKey);
2015-09-24 22:52:02 +02:00
if (request->connectionType & ConnectionTypeGeneric && connection->getConnectionToken() == 0) {
iter++;
continue;
}
switch (request->connectionType & 0x0000ffff) {
case ConnectionTypeGeneric:
2018-07-30 04:07:02 +02:00
case ConnectionTypeGenericMedia:
2024-03-08 15:32:16 +01:00
if (!canUseUnboundKey && genericRunningRequestCount >= MAX_GENERAL_REQUESTS) {
2015-09-24 22:52:02 +02:00
iter++;
2024-09-10 23:07:16 +02:00
// if (LOGS_ENABLED)
// DEBUG_D("skip queue, token = %d: generic type: running generic requests >= %d", request->requestToken, MAX_GENERAL_REQUESTS);
2015-09-24 22:52:02 +02:00
continue;
}
genericRunningRequestCount++;
break;
2018-07-30 04:07:02 +02:00
case ConnectionTypeDownload: {
uint32_t currentCount;
2023-10-28 22:52:06 +02:00
auto map = request->isCancelRequest() ? downloadCancelRunningRequestCount : downloadRunningRequestCount;
auto dcIter = map.find(datacenterId);
if (dcIter != map.end()) {
2018-07-30 04:07:02 +02:00
currentCount = dcIter->second;
} else {
currentCount = 0;
}
2023-10-28 22:52:06 +02:00
if (!networkAvailable) {
iter++;
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: download type: network unavailable", request->requestToken);
continue;
}
int max;
if (request->isCancelRequest()) {
2024-03-08 15:32:16 +01:00
max = MAX_DOWNLOAD_REQUESTS_CANCELS;
2023-10-28 22:52:06 +02:00
} else if (currentUserPremium) {
2024-03-08 15:32:16 +01:00
max = MAX_DOWNLOAD_REQUESTS_PREMIUM;
2023-10-28 22:52:06 +02:00
} else {
2024-03-08 15:32:16 +01:00
max = MAX_DOWNLOAD_REQUESTS;
2023-10-28 22:52:06 +02:00
}
if (currentCount >= max) {
2018-07-30 04:07:02 +02:00
iter++;
2023-10-28 22:52:06 +02:00
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: download type: running download requests >= %d", request->requestToken, max);
2018-07-30 04:07:02 +02:00
continue;
}
downloadRunningRequestCount[datacenterId] = currentCount + 1;
break;
}
case ConnectionTypeProxy:
case ConnectionTypeTemp:
if (!networkAvailable) {
2015-09-24 22:52:02 +02:00
iter++;
2023-10-28 22:52:06 +02:00
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: proxy/temp type: network unavailable", request->requestToken);
2015-09-24 22:52:02 +02:00
continue;
}
break;
case ConnectionTypeUpload:
2023-10-28 22:52:06 +02:00
if (!networkAvailable) {
2015-09-24 22:52:02 +02:00
iter++;
2023-10-28 22:52:06 +02:00
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: upload type: network unavailable", request->requestToken);
continue;
}
2024-03-08 15:32:16 +01:00
if (uploadRunningRequestCount >= MAX_UPLOAD_REQUESTS) {
2023-10-28 22:52:06 +02:00
iter++;
if (LOGS_ENABLED)
DEBUG_D("skip queue, token = %d: upload type: running upload requests >= 10", request->requestToken);
2015-09-24 22:52:02 +02:00
continue;
}
uploadRunningRequestCount++;
break;
default:
break;
}
2018-07-30 04:07:02 +02:00
request->messageId = generateMessageId();
if (request->rawRequest->initFunc != nullptr) {
request->rawRequest->initFunc(request->messageId);
}
2021-04-14 03:44:46 +02:00
if (LOGS_ENABLED) DEBUG_D("messageId for token = %d, 0x%" PRIx64, request->requestToken, request->messageId);
2018-07-30 04:07:02 +02:00
2015-09-24 22:52:02 +02:00
uint32_t requestLength = request->rpcRequest->getObjectSize();
if (request->requestFlags & RequestFlagCanCompress) {
request->requestFlags &= ~RequestFlagCanCompress;
NativeByteBuffer *original = BuffersStorage::getInstance().getFreeBuffer(requestLength);
request->rpcRequest->serializeToStream(original);
NativeByteBuffer *buffer = compressGZip(original);
if (buffer != nullptr) {
2021-07-15 16:24:57 +02:00
auto packed = new TL_gzip_packed();
2015-09-24 22:52:02 +02:00
packed->originalRequest = std::move(request->rpcRequest);
packed->packed_data_to_send = buffer;
request->rpcRequest = std::unique_ptr<TLObject>(packed);
requestLength = packed->getObjectSize();
}
original->reuse();
}
2018-07-30 04:07:02 +02:00
2015-09-24 22:52:02 +02:00
request->serializedLength = requestLength;
2018-07-30 04:07:02 +02:00
request->messageSeqNo = connection->generateMessageSeqNo((request->connectionType & ConnectionTypeProxy) == 0);
request->startTime = currentTime;
request->startTimeMillis = currentTimeMillis;
2015-09-24 22:52:02 +02:00
request->connectionToken = connection->getConnectionToken();
2021-07-15 16:24:57 +02:00
auto networkMessage = new NetworkMessage();
networkMessage->message = std::make_unique<TL_message>();
networkMessage->forceContainer = request->isResending;
2015-09-24 22:52:02 +02:00
networkMessage->message->msg_id = request->messageId;
networkMessage->message->bytes = request->serializedLength;
networkMessage->message->outgoingBody = request->getRpcRequest();
networkMessage->message->seqno = request->messageSeqNo;
networkMessage->requestId = request->requestToken;
2021-07-15 16:24:57 +02:00
networkMessage->invokeAfter = (request->requestFlags & RequestFlagInvokeAfter) != 0 && (request->requestFlags & RequestFlagResendAfter) == 0;
2015-09-24 22:52:02 +02:00
networkMessage->needQuickAck = (request->requestFlags & RequestFlagNeedQuickAck) != 0;
2019-05-14 14:08:05 +02:00
if (!hasPendingRequestsForConnection(connection)) {
connection->resetLastEventTime();
}
2015-09-24 22:52:02 +02:00
runningRequests.push_back(std::move(*iter));
switch (request->connectionType & 0x0000ffff) {
case ConnectionTypeGeneric:
addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters);
break;
2018-07-30 04:07:02 +02:00
case ConnectionTypeGenericMedia:
addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMediaMessagesToDatacenters);
break;
2017-07-08 18:32:04 +02:00
case ConnectionTypeTemp:
addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, tempMessagesToDatacenters);
break;
2018-07-30 04:07:02 +02:00
case ConnectionTypeProxy: {
std::vector<std::unique_ptr<NetworkMessage>> array;
array.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
sendMessagesToConnection(array, connection, false);
break;
}
2015-09-24 22:52:02 +02:00
case ConnectionTypeDownload:
case ConnectionTypeUpload: {
std::vector<std::unique_ptr<NetworkMessage>> array;
array.push_back(std::unique_ptr<NetworkMessage>(networkMessage));
sendMessagesToConnectionWithConfirmation(array, connection, false);
break;
}
default:
delete networkMessage;
}
iter = requestsQueue.erase(iter);
}
2021-07-15 16:24:57 +02:00
for (auto & iter : datacenters) {
Datacenter *datacenter = iter.second;
auto iter2 = genericMessagesToDatacenters.find(datacenter->getDatacenterId());
2015-09-24 22:52:02 +02:00
if (iter2 == genericMessagesToDatacenters.end()) {
2018-07-30 04:07:02 +02:00
Connection *connection = datacenter->getGenericConnection(false, 1);
2015-09-24 22:52:02 +02:00
if (connection != nullptr && connection->getConnectionToken() != 0 && connection->hasMessagesToConfirm()) {
genericMessagesToDatacenters[datacenter->getDatacenterId()] = std::vector<std::unique_ptr<NetworkMessage>>();
}
}
2017-07-08 18:32:04 +02:00
2018-07-30 04:07:02 +02:00
iter2 = genericMediaMessagesToDatacenters.find(datacenter->getDatacenterId());
if (iter2 == genericMediaMessagesToDatacenters.end()) {
Connection *connection = datacenter->getGenericMediaConnection(false, 1);
if (connection != nullptr && connection->getConnectionToken() != 0 && connection->hasMessagesToConfirm()) {
genericMediaMessagesToDatacenters[datacenter->getDatacenterId()] = std::vector<std::unique_ptr<NetworkMessage>>();
}
}
2017-07-08 18:32:04 +02:00
iter2 = tempMessagesToDatacenters.find(datacenter->getDatacenterId());
if (iter2 == tempMessagesToDatacenters.end()) {
Connection *connection = datacenter->getTempConnection(false);
if (connection != nullptr && connection->getConnectionToken() != 0 && connection->hasMessagesToConfirm()) {
tempMessagesToDatacenters[datacenter->getDatacenterId()] = std::vector<std::unique_ptr<NetworkMessage>>();
}
}
2015-09-24 22:52:02 +02:00
}
2021-07-15 16:24:57 +02:00
for (auto & genericMessagesToDatacenter : genericMessagesToDatacenters) {
Datacenter *datacenter = getDatacenterWithId(genericMessagesToDatacenter.first);
2015-09-24 22:52:02 +02:00
if (datacenter != nullptr) {
bool scannedPreviousRequests = false;
bool needQuickAck = false;
2021-04-14 03:44:46 +02:00
int64_t lastSentMessageRpcId = 0;
2021-07-15 16:24:57 +02:00
std::vector<std::unique_ptr<NetworkMessage>> &array = genericMessagesToDatacenter.second;
2015-09-24 22:52:02 +02:00
size_t count = array.size();
for (uint32_t b = 0; b < count; b++) {
NetworkMessage *networkMessage = array[b].get();
if (networkMessage->needQuickAck) {
needQuickAck = true;
}
if (networkMessage->invokeAfter) {
if (!scannedPreviousRequests) {
scannedPreviousRequests = true;
std::vector<int64_t> currentRequests;
for (uint32_t a = 0; a < count; a++) {
NetworkMessage *currentNetworkMessage = array[a].get();
if (currentNetworkMessage->invokeAfter) {
2021-04-14 03:44:46 +02:00
currentRequests.push_back(currentNetworkMessage->message->msg_id);
2015-09-24 22:52:02 +02:00
}
}
int64_t maxRequestId = 0;
2021-04-14 03:44:46 +02:00
if (lastInvokeAfterMessageId != 0) {
2021-07-15 16:24:57 +02:00
auto timeMessage = (int64_t) (lastInvokeAfterMessageId / 4294967296.0);
2021-04-17 01:59:59 +02:00
if (getCurrentTime() - timeMessage <= 5) {
2021-04-14 03:44:46 +02:00
maxRequestId = lastInvokeAfterMessageId;
}
}
2021-07-15 16:24:57 +02:00
for (auto & runningRequest : runningRequests) {
Request *request = runningRequest.get();
2015-09-24 22:52:02 +02:00
if (request->requestFlags & RequestFlagInvokeAfter) {
if (request->messageId > maxRequestId && std::find(currentRequests.begin(), currentRequests.end(), request->messageId) == currentRequests.end()) {
maxRequestId = request->messageId;
}
}
}
lastSentMessageRpcId = maxRequestId;
}
TL_message *message = networkMessage->message.get();
if (lastSentMessageRpcId != 0 && lastSentMessageRpcId != message->msg_id) {
2021-07-15 16:24:57 +02:00
auto request = new TL_invokeAfterMsg();
2015-09-24 22:52:02 +02:00
request->msg_id = lastSentMessageRpcId;
if (message->outgoingBody != nullptr) {
2021-04-14 03:44:46 +02:00
if (LOGS_ENABLED) DEBUG_D("wrap outgoingBody(%p, %s) to TL_invokeAfterMsg, token = %d, after 0x%" PRIx64, message->outgoingBody, typeid(*message->outgoingBody).name(), networkMessage->requestId, request->msg_id);
2015-09-24 22:52:02 +02:00
request->outgoingQuery = message->outgoingBody;
message->outgoingBody = nullptr;
} else {
2021-04-14 03:44:46 +02:00
if (LOGS_ENABLED) DEBUG_D("wrap body(%p, %s) to TL_invokeAfterMsg, token = %d, after 0x%" PRIx64, message->body.get(), typeid(*(message->body.get())).name(), networkMessage->requestId, request->msg_id);
2015-09-24 22:52:02 +02:00
request->query = std::move(message->body);
}
message->body = std::unique_ptr<TLObject>(request);
message->bytes += 4 + 8;
}
lastSentMessageRpcId = message->msg_id;
2021-04-14 03:44:46 +02:00
lastInvokeAfterMessageId = message->msg_id;
2015-09-24 22:52:02 +02:00
}
}
2018-07-30 04:07:02 +02:00
sendMessagesToConnectionWithConfirmation(array, datacenter->getGenericConnection(true, 1), needQuickAck);
2015-09-24 22:52:02 +02:00
}
}
2021-07-15 16:24:57 +02:00
for (auto & tempMessagesToDatacenter : tempMessagesToDatacenters) {
Datacenter *datacenter = getDatacenterWithId(tempMessagesToDatacenter.first);
2017-07-08 18:32:04 +02:00
if (datacenter != nullptr) {
2021-07-15 16:24:57 +02:00
std::vector<std::unique_ptr<NetworkMessage>> &array = tempMessagesToDatacenter.second;
2017-07-08 18:32:04 +02:00
sendMessagesToConnectionWithConfirmation(array, datacenter->getTempConnection(true), false);
}
}
2021-07-15 16:24:57 +02:00
for (auto & genericMediaMessagesToDatacenter : genericMediaMessagesToDatacenters) {
Datacenter *datacenter = getDatacenterWithId(genericMediaMessagesToDatacenter.first);
2018-07-30 04:07:02 +02:00
if (datacenter != nullptr) {
2021-07-15 16:24:57 +02:00
std::vector<std::unique_ptr<NetworkMessage>> &array = genericMediaMessagesToDatacenter.second;
2018-07-30 04:07:02 +02:00
sendMessagesToConnectionWithConfirmation(array, datacenter->getGenericMediaConnection(true, 1), false);
}
}
2015-09-24 22:52:02 +02:00
if (connectionTypes == ConnectionTypeGeneric && dc == currentDatacenterId) {
2021-07-15 16:24:57 +02:00
auto iter2 = genericMessagesToDatacenters.find(currentDatacenterId);
2015-09-24 22:52:02 +02:00
if (iter2 == genericMessagesToDatacenters.end()) {
sendPing(getDatacenterWithId(currentDatacenterId), false);
}
}
if (!unknownDatacenterIds.empty()) {
2023-05-04 14:25:48 +02:00
updateDcSettings(0, false, false);
2015-09-24 22:52:02 +02:00
}
size_t count = neededDatacenters.size();
for (uint32_t a = 0; a < count; a++) {
2018-07-30 04:07:02 +02:00
Datacenter *datacenter = neededDatacenters[a].first;
bool media = Connection::isMediaConnectionType(neededDatacenters[a].second) && datacenter->hasMediaAddress();
if (datacenter->getDatacenterId() != movingToDatacenterId && !datacenter->isHandshaking(media) && !datacenter->hasAuthKey(neededDatacenters[a].second, 1)) {
datacenter->beginHandshake(media ? HandshakeTypeMediaTemp : HandshakeTypeTemp, true);
2015-09-24 22:52:02 +02:00
}
}
if (currentUserId) {
count = unauthorizedDatacenters.size();
for (uint32_t a = 0; a < count; a++) {
Datacenter *datacenter = unauthorizedDatacenters[a];
uint32_t id = datacenter->getDatacenterId();
if (id != currentDatacenterId && id != movingToDatacenterId && !datacenter->isExportingAuthorization()) {
datacenter->exportAuthorization();
}
}
}
}
Datacenter *ConnectionsManager::getDatacenterWithId(uint32_t datacenterId) {
if (datacenterId == DEFAULT_DATACENTER_ID) {
return datacenters[currentDatacenterId];
}
2021-07-15 16:24:57 +02:00
auto iter = datacenters.find(datacenterId);
2015-09-24 22:52:02 +02:00
return iter != datacenters.end() ? iter->second : nullptr;
}
std::unique_ptr<TLObject> ConnectionsManager::wrapInLayer(TLObject *object, Datacenter *datacenter, Request *baseRequest) {
if (object->isNeedLayer()) {
2018-07-30 04:07:02 +02:00
bool media = PFS_ENABLED && datacenter != nullptr && baseRequest->isMediaRequest() && datacenter->hasMediaAddress();
if (datacenter == nullptr || baseRequest->needInitRequest(datacenter, currentVersion)) {
2017-07-08 18:32:04 +02:00
if (datacenter != nullptr && datacenter->getDatacenterId() == currentDatacenterId) {
2015-09-24 22:52:02 +02:00
registerForInternalPushUpdates();
}
2018-07-30 04:07:02 +02:00
if (media) {
baseRequest->isInitMediaRequest = true;
} else {
baseRequest->isInitRequest = true;
}
2021-07-15 16:24:57 +02:00
auto request = new initConnection();
2018-07-30 04:07:02 +02:00
if (delegate != nullptr) {
request->flags = delegate->getInitFlags(instanceNum);
} else {
request->flags = 0;
}
2015-09-24 22:52:02 +02:00
request->query = std::unique_ptr<TLObject>(object);
request->api_id = currentApiId;
request->app_version = currentAppVersion;
request->lang_code = currentLangCode;
2017-07-08 18:32:04 +02:00
request->lang_pack = "android";
request->system_lang_code = currentSystemLangCode;
2019-07-18 15:01:39 +02:00
2021-07-15 16:24:57 +02:00
auto jsonObject = new TL_jsonObject();
2020-04-24 11:21:58 +02:00
request->params = std::unique_ptr<JSONValue>(jsonObject);
2019-12-31 14:08:08 +01:00
2020-04-24 11:21:58 +02:00
if (!currentRegId.empty()) {
2021-07-15 16:24:57 +02:00
auto objectValue = new TL_jsonObjectValue();
2020-04-24 11:21:58 +02:00
jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue));
2019-12-31 14:08:08 +01:00
2021-07-15 16:24:57 +02:00
auto jsonString = new TL_jsonString();
2020-04-24 11:21:58 +02:00
jsonString->value = currentRegId;
objectValue->key = "device_token";
objectValue->value = std::unique_ptr<JSONValue>(jsonString);
}
if (!certFingerprint.empty()) {
2021-07-15 16:24:57 +02:00
auto objectValue = new TL_jsonObjectValue();
2020-04-24 11:21:58 +02:00
jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue));
2019-12-31 14:08:08 +01:00
2021-07-15 16:24:57 +02:00
auto jsonString = new TL_jsonString();
2020-04-24 11:21:58 +02:00
jsonString->value = certFingerprint;
objectValue->key = "data";
objectValue->value = std::unique_ptr<JSONValue>(jsonString);
2019-07-18 15:01:39 +02:00
}
2020-04-24 11:21:58 +02:00
2021-07-15 16:24:57 +02:00
auto objectValue = new TL_jsonObjectValue();
2020-04-24 11:21:58 +02:00
jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue));
2021-07-15 16:24:57 +02:00
auto jsonString = new TL_jsonString();
2020-07-26 10:03:38 +02:00
jsonString->value = installer;
objectValue->key = "installer";
objectValue->value = std::unique_ptr<JSONValue>(jsonString);
2021-04-14 03:44:46 +02:00
objectValue = new TL_jsonObjectValue();
jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue));
jsonString = new TL_jsonString();
jsonString->value = package;
objectValue->key = "package_id";
objectValue->value = std::unique_ptr<JSONValue>(jsonString);
2020-07-26 10:03:38 +02:00
objectValue = new TL_jsonObjectValue();
jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue));
2020-04-24 11:21:58 +02:00
2021-07-15 16:24:57 +02:00
auto jsonNumber = new TL_jsonNumber();
2020-04-24 11:21:58 +02:00
jsonNumber->value = currentDeviceTimezone;
objectValue->key = "tz_offset";
objectValue->value = std::unique_ptr<JSONValue>(jsonNumber);
2023-02-18 22:24:25 +01:00
if (currentPerformanceClass != -1) {
objectValue = new TL_jsonObjectValue();
jsonObject->value.push_back(std::unique_ptr<TL_jsonObjectValue>(objectValue));
auto jsonNumber = new TL_jsonNumber();
jsonNumber->value = currentPerformanceClass + 1;
objectValue->key = "perf_cat";
objectValue->value = std::unique_ptr<JSONValue>(jsonNumber);
}
2020-04-24 11:21:58 +02:00
request->flags |= 2;
2018-07-30 04:07:02 +02:00
if (!proxyAddress.empty() && !proxySecret.empty()) {
request->flags |= 1;
2021-07-15 16:24:57 +02:00
request->proxy = std::make_unique<TL_inputClientProxy>();
2018-07-30 04:07:02 +02:00
request->proxy->address = proxyAddress;
request->proxy->port = proxyPort;
}
2017-07-08 18:32:04 +02:00
if (datacenter == nullptr || datacenter->isCdnDatacenter) {
request->device_model = "n/a";
request->system_version = "n/a";
} else {
request->device_model = currentDeviceModel;
request->system_version = currentSystemVersion;
}
2015-09-24 22:52:02 +02:00
if (request->lang_code.empty()) {
request->lang_code = "en";
}
if (request->device_model.empty()) {
2017-07-08 18:32:04 +02:00
request->device_model = "n/a";
2015-09-24 22:52:02 +02:00
}
if (request->app_version.empty()) {
2017-07-08 18:32:04 +02:00
request->app_version = "n/a";
2015-09-24 22:52:02 +02:00
}
if (request->system_version.empty()) {
2017-07-08 18:32:04 +02:00
request->system_version = "n/a";
2015-09-24 22:52:02 +02:00
}
2021-07-15 16:24:57 +02:00
auto request2 = new invokeWithLayer();
2015-09-24 22:52:02 +02:00
request2->layer = currentLayer;
request2->query = std::unique_ptr<TLObject>(request);
2020-10-30 11:26:29 +01:00
if (LOGS_ENABLED) DEBUG_D("wrap in layer %s, flags = %d", typeid(*object).name(), request->flags);
2015-09-24 22:52:02 +02:00
return std::unique_ptr<TLObject>(request2);
}
}
return std::unique_ptr<TLObject>(object);
}
2019-08-22 01:53:26 +02:00
static const char *const url_symbols64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
static unsigned char url_char_to_value[256];
static void init_base64url_table() {
static bool is_inited = []() {
std::fill(std::begin(url_char_to_value), std::end(url_char_to_value), static_cast<unsigned char>(64));
for (unsigned char i = 0; i < 64; i++) {
url_char_to_value[static_cast<size_t>(url_symbols64[i])] = i;
}
return true;
}();
assert(is_inited);
}
std::string base64UrlDecode(std::string base64) {
init_base64url_table();
size_t padding_length = 0;
while (!base64.empty() && base64.back() == '=') {
2019-09-10 12:56:11 +02:00
base64.pop_back();
2019-08-22 01:53:26 +02:00
padding_length++;
2018-07-30 04:07:02 +02:00
}
2019-08-22 01:53:26 +02:00
if (padding_length >= 3 || (padding_length > 0 && ((base64.size() + padding_length) & 3) != 0)) {
return "";
}
if ((base64.size() & 3) == 1) {
return "";
}
std::string output;
output.reserve(((base64.size() + 3) >> 2) * 3);
2019-09-10 12:56:11 +02:00
for (size_t i = 0; i < base64.size();) {
size_t left = std::min(base64.size() - i, static_cast<size_t>(4));
2019-08-22 01:53:26 +02:00
int c = 0;
for (size_t t = 0; t < left; t++) {
auto value = url_char_to_value[base64.c_str()[i++]];
if (value == 64) {
return "";
}
c |= value << ((3 - t) * 6);
}
output += static_cast<char>(static_cast<unsigned char>(c >> 16));
if (left == 2) {
if ((c & ((1 << 16) - 1)) != 0) {
return "";
}
} else {
output += static_cast<char>(static_cast<unsigned char>(c >> 8));
if (left == 3) {
if ((c & ((1 << 8) - 1)) != 0) {
return "";
}
} else {
output += static_cast<char>(static_cast<unsigned char>(c));
}
}
}
return output;
}
inline std::string decodeSecret(std::string secret) {
bool allHex = true;
2021-07-15 16:24:57 +02:00
for (char i : secret) {
if (!((i >= '0' && i <= '9') || (i >= 'a' && i <= 'f') || (i >= 'A' && i <= 'F'))) {
2019-08-22 01:53:26 +02:00
allHex = false;
break;
}
}
if (allHex) {
size_t size = secret.size() / 2;
char *result = new char[size];
for (int32_t i = 0; i < size; i++) {
result[i] = (char) (char2int(secret[i * 2]) * 16 + char2int(secret[i * 2 + 1]));
}
secret = std::string(result, size);
delete[] result;
return secret;
}
return base64UrlDecode(secret);
2018-07-30 04:07:02 +02:00
}
2023-05-04 14:25:48 +02:00
void ConnectionsManager::updateDcSettings(uint32_t dcNum, bool workaround, bool ifLoadingTryAgain) {
2017-07-08 18:32:04 +02:00
if (workaround) {
if (updatingDcSettingsWorkaround) {
return;
}
updatingDcSettingsWorkaround = true;
} else {
if (updatingDcSettings) {
2023-05-04 14:25:48 +02:00
if (ifLoadingTryAgain) {
updatingDcSettingsAgain = true;
updatingDcSettingsAgainDcNum = dcNum;
}
2017-07-08 18:32:04 +02:00
return;
}
updatingDcSettings = true;
updatingDcStartTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000);
2015-09-24 22:52:02 +02:00
}
2021-07-15 16:24:57 +02:00
auto request = new TL_help_getConfig();
2024-10-17 22:04:16 +02:00
sendRequest(request, [&, workaround](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) {
2021-07-15 16:24:57 +02:00
if ((!workaround && !updatingDcSettings) || (workaround && !updatingDcSettingsWorkaround)) {
2015-09-24 22:52:02 +02:00
return;
}
2023-10-28 22:52:06 +02:00
if (!workaround && updatingDcSettingsAgain) {
updatingDcSettings = false;
2023-05-04 14:25:48 +02:00
updatingDcSettingsAgain = false;
for (auto & datacenter : datacenters) {
2023-10-28 22:52:06 +02:00
datacenter.second->resetInitVersion();
2023-05-04 14:25:48 +02:00
}
2023-10-28 22:52:06 +02:00
updateDcSettings(0, false, false);
2023-05-04 14:25:48 +02:00
return;
}
2015-09-24 22:52:02 +02:00
if (response != nullptr) {
2021-07-15 16:24:57 +02:00
auto config = (TL_config *) response;
2018-07-30 04:07:02 +02:00
clientBlocked = (config->flags & 256) != 0;
2017-07-08 18:32:04 +02:00
if (!workaround) {
int32_t updateIn = config->expires - getCurrentTime();
if (updateIn <= 0) {
updateIn = 120;
}
lastDcUpdateTime = (int32_t) (getCurrentTimeMonotonicMillis() / 1000) - DC_UPDATE_TIME + updateIn;
2015-09-24 22:52:02 +02:00
}
struct DatacenterInfo {
2017-07-08 18:32:04 +02:00
std::vector<TcpAddress> addressesIpv4;
std::vector<TcpAddress> addressesIpv6;
std::vector<TcpAddress> addressesIpv4Download;
std::vector<TcpAddress> addressesIpv6Download;
bool isCdn = false;
2023-03-24 12:38:14 +01:00
bool forceTryIpV6;
2017-07-08 18:32:04 +02:00
void addAddressAndPort(TL_dcOption *dcOption) {
std::vector<TcpAddress> *addresses;
if (!isCdn) {
isCdn = dcOption->cdn;
}
2023-03-24 12:38:14 +01:00
forceTryIpV6 = dcOption->force_try_ipv6;
2017-07-08 18:32:04 +02:00
if (dcOption->media_only) {
if (dcOption->ipv6) {
2015-09-24 22:52:02 +02:00
addresses = &addressesIpv6Download;
} else {
addresses = &addressesIpv4Download;
}
} else {
2017-07-08 18:32:04 +02:00
if (dcOption->ipv6) {
2015-09-24 22:52:02 +02:00
addresses = &addressesIpv6;
} else {
addresses = &addressesIpv4;
}
}
2021-07-15 16:24:57 +02:00
for (auto & addresse : *addresses) {
if (addresse.address == dcOption->ip_address && addresse.port == dcOption->port) {
2017-07-08 18:32:04 +02:00
return;
}
2015-09-24 22:52:02 +02:00
}
2018-07-30 04:07:02 +02:00
std::string secret;
if (dcOption->secret != nullptr) {
2019-08-22 01:53:26 +02:00
secret = std::string((const char *) dcOption->secret->bytes, dcOption->secret->length);
2018-07-30 04:07:02 +02:00
}
2023-03-24 12:38:14 +01:00
if (LOGS_ENABLED) DEBUG_D("getConfig add %s:%d to dc%d, flags %d, has_secret = %d[%d], try_this_port_only = %d, force_try_ipv6 = %d", dcOption->ip_address.c_str(), dcOption->port, dcOption->id, dcOption->flags, dcOption->secret != nullptr ? 1 : 0, dcOption->secret != nullptr ? dcOption->secret->length : 0, dcOption->thisPortOnly ? 1 : 0, dcOption->force_try_ipv6 ? 1 : 0);
2022-06-21 04:51:00 +02:00
if (dcOption->thisPortOnly) {
addresses->insert(addresses->begin(), TcpAddress(dcOption->ip_address, dcOption->port, dcOption->flags, secret));
} else {
addresses->push_back(TcpAddress(dcOption->ip_address, dcOption->port, dcOption->flags, secret));
}
2015-09-24 22:52:02 +02:00
}
};
std::map<uint32_t, std::unique_ptr<DatacenterInfo>> map;
size_t count = config->dc_options.size();
for (uint32_t a = 0; a < count; a++) {
TL_dcOption *dcOption = config->dc_options[a].get();
2021-07-15 16:24:57 +02:00
auto iter = map.find((uint32_t) dcOption->id);
2015-09-24 22:52:02 +02:00
DatacenterInfo *info;
if (iter == map.end()) {
map[dcOption->id] = std::unique_ptr<DatacenterInfo>(info = new DatacenterInfo);
} else {
info = iter->second.get();
}
2017-07-08 18:32:04 +02:00
info->addAddressAndPort(dcOption);
2015-09-24 22:52:02 +02:00
}
if (!map.empty()) {
2021-07-15 16:24:57 +02:00
for (auto & iter : map) {
Datacenter *datacenter = getDatacenterWithId(iter.first);
DatacenterInfo *info = iter.second.get();
2015-09-24 22:52:02 +02:00
if (datacenter == nullptr) {
2021-07-15 16:24:57 +02:00
datacenter = new Datacenter(instanceNum, iter.first);
datacenters[iter.first] = datacenter;
2015-09-24 22:52:02 +02:00
}
2017-07-08 18:32:04 +02:00
datacenter->replaceAddresses(info->addressesIpv4, info->isCdn ? 8 : 0);
datacenter->replaceAddresses(info->addressesIpv6, info->isCdn ? 9 : 1);
datacenter->replaceAddresses(info->addressesIpv4Download, info->isCdn ? 10 : 2);
datacenter->replaceAddresses(info->addressesIpv6Download, info->isCdn ? 11 : 3);
2021-07-15 16:24:57 +02:00
if (iter.first == movingToDatacenterId) {
2015-09-24 22:52:02 +02:00
movingToDatacenterId = DEFAULT_DATACENTER_ID;
2021-07-15 16:24:57 +02:00
moveToDatacenter(iter.first);
2015-09-24 22:52:02 +02:00
}
}
saveConfig();
2018-07-30 04:07:02 +02:00
scheduleTask([&] {
processRequestQueue(AllConnectionTypes, 0);
});
2015-09-24 22:52:02 +02:00
}
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onUpdateConfig(config, instanceNum);
2015-09-24 22:52:02 +02:00
}
}
2017-07-08 18:32:04 +02:00
if (workaround) {
updatingDcSettingsWorkaround = false;
} else {
updatingDcSettings = false;
}
2024-03-08 15:32:16 +01:00
}, nullptr, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin | RequestFlagUseUnboundKey | (workaround ? 0 : RequestFlagTryDifferentDc), dcNum == 0 ? currentDatacenterId : dcNum, workaround ? ConnectionTypeTemp : ConnectionTypeGeneric, true);
2015-09-24 22:52:02 +02:00
}
void ConnectionsManager::moveToDatacenter(uint32_t datacenterId) {
if (movingToDatacenterId == datacenterId) {
return;
}
movingToDatacenterId = datacenterId;
Datacenter *currentDatacenter = getDatacenterWithId(currentDatacenterId);
2018-07-30 04:07:02 +02:00
clearRequestsForDatacenter(currentDatacenter, HandshakeTypeAll);
2023-04-25 07:51:03 +02:00
authorizeOnMovingDatacenter();
2015-09-24 22:52:02 +02:00
}
void ConnectionsManager::authorizeOnMovingDatacenter() {
Datacenter *datacenter = getDatacenterWithId(movingToDatacenterId);
if (datacenter == nullptr) {
2023-05-04 14:25:48 +02:00
updateDcSettings(0, false, false);
2015-09-24 22:52:02 +02:00
return;
}
2018-07-30 04:07:02 +02:00
datacenter->recreateSessions(HandshakeTypeAll);
clearRequestsForDatacenter(datacenter, HandshakeTypeAll);
2015-09-24 22:52:02 +02:00
2018-07-30 04:07:02 +02:00
if (!datacenter->hasAuthKey(ConnectionTypeGeneric, 0) && !datacenter->isHandshakingAny()) {
2019-12-31 14:08:08 +01:00
datacenter->clearServerSalts(false);
datacenter->clearServerSalts(true);
2018-07-30 04:07:02 +02:00
datacenter->beginHandshake(HandshakeTypeAll, true);
2015-09-24 22:52:02 +02:00
}
if (movingAuthorization != nullptr) {
2021-07-15 16:24:57 +02:00
auto request = new TL_auth_importAuthorization();
2015-09-24 22:52:02 +02:00
request->id = currentUserId;
request->bytes = std::move(movingAuthorization);
2024-10-17 22:04:16 +02:00
sendRequest(request, [&](TLObject *response, TL_error *error, int32_t networkType, int64_t responseTime, int64_t msgId, int32_t dcId) {
2015-09-24 22:52:02 +02:00
if (error == nullptr) {
authorizedOnMovingDatacenter();
} else {
moveToDatacenter(movingToDatacenterId);
}
2024-03-08 15:32:16 +01:00
}, nullptr, nullptr, RequestFlagWithoutLogin, datacenter->getDatacenterId(), ConnectionTypeGeneric, true);
2015-09-24 22:52:02 +02:00
} else {
authorizedOnMovingDatacenter();
}
}
void ConnectionsManager::authorizedOnMovingDatacenter() {
movingAuthorization.reset();
currentDatacenterId = movingToDatacenterId;
movingToDatacenterId = DEFAULT_DATACENTER_ID;
saveConfig();
2018-07-30 04:07:02 +02:00
scheduleTask([&] {
processRequestQueue(0, 0);
});
2015-09-24 22:52:02 +02:00
}
void ConnectionsManager::applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port) {
scheduleTask([&, datacenterId, ipAddress, port] {
Datacenter *datacenter = getDatacenterWithId(datacenterId);
if (datacenter != nullptr) {
2017-07-08 18:32:04 +02:00
std::vector<TcpAddress> addresses;
2021-07-15 16:24:57 +02:00
addresses.emplace_back(ipAddress, port, 0, "");
2019-01-23 18:03:33 +01:00
datacenter->suspendConnections(true);
2017-07-08 18:32:04 +02:00
datacenter->replaceAddresses(addresses, 0);
2017-03-31 01:58:05 +02:00
datacenter->resetAddressAndPortNum();
saveConfig();
2018-07-30 04:07:02 +02:00
if (datacenter->isHandshakingAny()) {
datacenter->beginHandshake(HandshakeTypeCurrent, true);
2017-07-08 18:32:04 +02:00
}
2023-05-04 14:25:48 +02:00
updateDcSettings(datacenterId, false, false);
2015-09-24 22:52:02 +02:00
}
});
}
ConnectionState ConnectionsManager::getConnectionState() {
return connectionState;
}
void ConnectionsManager::setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate) {
delegate = connectiosManagerDelegate;
}
2016-04-22 15:49:00 +02:00
void ConnectionsManager::setPushConnectionEnabled(bool value) {
pushConnectionEnabled = value;
Datacenter *datacenter = getDatacenterWithId(currentDatacenterId);
if (datacenter != nullptr) {
if (!pushConnectionEnabled) {
Connection *connection = datacenter->getPushConnection(false);
if (connection != nullptr) {
connection->suspendConnection();
}
} else {
datacenter->createPushConnection()->setSessionId(pushSessionId);
sendPing(datacenter, true);
}
}
}
2018-07-30 04:07:02 +02:00
inline bool checkPhoneByPrefixesRules(std::string phone, std::string rules) {
if (rules.empty() || phone.empty()) {
return true;
}
bool found = false;
std::stringstream ss(rules);
std::string prefix;
while (std::getline(ss, prefix, ',')) {
2021-07-15 16:24:57 +02:00
if (prefix.empty()) {
2018-07-30 04:07:02 +02:00
found = true;
} else if (prefix[0] == '+' && phone.find(prefix.substr(1)) == 0) {
found = true;
} else if (prefix[0] == '-' && phone.find(prefix.substr(1)) == 0) {
return false;
}
}
return found;
}
2019-08-22 01:53:26 +02:00
void ConnectionsManager::applyDnsConfig(NativeByteBuffer *buffer, std::string phone, int32_t date) {
scheduleTask([&, buffer, phone, date] {
int32_t realDate = date;
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("trying to decrypt config %d", requestingSecondAddress);
2017-07-08 18:32:04 +02:00
TL_help_configSimple *config = Datacenter::decodeSimpleConfig(buffer);
2019-08-22 01:53:26 +02:00
if (config != nullptr && realDate == 0) {
realDate = config->date;
}
2017-07-08 18:32:04 +02:00
int currentDate = getCurrentTime();
if (config != nullptr && config->date <= currentDate && currentDate <= config->expires) {
2019-08-22 01:53:26 +02:00
if (realDate > 0 && requestingSecondAddressByTlsHashMismatch) {
2020-01-05 19:39:58 +01:00
timeDifference += (realDate - currentDate);
2019-08-22 01:53:26 +02:00
requestingSecondAddressByTlsHashMismatch = false;
}
2021-07-15 16:24:57 +02:00
for (auto & iter : config->rules) {
TL_accessPointRule *rule = iter.get();
2018-07-30 04:07:02 +02:00
if (!checkPhoneByPrefixesRules(phone, rule->phone_prefix_rules)) {
continue;
}
Datacenter *datacenter = getDatacenterWithId(rule->dc_id);
if (datacenter != nullptr) {
std::vector<TcpAddress> addresses;
2021-07-15 16:24:57 +02:00
for (auto iter2 = rule->ips.begin(); iter2 != rule->ips.end(); iter2++) {
2018-07-30 04:07:02 +02:00
IpPort *port = iter2->get();
const std::type_info &typeInfo = typeid(*port);
if (typeInfo == typeid(TL_ipPort)) {
2021-07-15 16:24:57 +02:00
auto ipPort = (TL_ipPort *) port;
addresses.emplace_back(ipPort->ipv4, ipPort->port, 0, "");
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("got address %s and port %d for dc%d", ipPort->ipv4.c_str(), ipPort->port, rule->dc_id);
2018-07-30 04:07:02 +02:00
} else if (typeInfo == typeid(TL_ipPortSecret)) {
2021-07-15 16:24:57 +02:00
auto ipPort = (TL_ipPortSecret *) port;
addresses.emplace_back(ipPort->ipv4, ipPort->port, 0, std::string((const char *) ipPort->secret->bytes, ipPort->secret->length));
2019-01-23 18:03:33 +01:00
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);
2018-07-30 04:07:02 +02:00
}
2017-07-08 18:32:04 +02:00
}
2018-07-30 04:07:02 +02:00
if (!addresses.empty()) {
datacenter->replaceAddresses(addresses, TcpAddressFlagTemp);
Connection *connection = datacenter->getTempConnection(false);
if (connection != nullptr) {
connection->suspendConnection();
}
if (datacenter->isHandshakingAny()) {
datacenter->beginHandshake(HandshakeTypeCurrent, true);
}
2023-05-04 14:25:48 +02:00
updateDcSettings(rule->dc_id, true, false);
2017-07-08 18:32:04 +02:00
}
2018-07-30 04:07:02 +02:00
} else {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("config datacenter %d not found", rule->dc_id);
2017-07-08 18:32:04 +02:00
}
}
delete config;
2018-07-30 04:07:02 +02:00
} else {
if (config == nullptr) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("can't decrypt dns config");
2018-07-30 04:07:02 +02:00
} else {
delete config;
2024-06-03 08:21:03 +02:00
if (LOGS_ENABLED) DEBUG_D("dns config not valid due to date or expire, current date = %d, config date = %d, config expired = %d", currentDate, config->date, config->expires);
2018-07-30 04:07:02 +02:00
}
2024-06-03 08:21:03 +02:00
if (requestingSecondAddress == 1) {
2019-12-31 14:08:08 +01:00
requestingSecondAddress = 2;
delegate->onRequestNewServerIpAndPort(requestingSecondAddress, instanceNum);
} else if (requestingSecondAddress == 0) {
2018-07-30 04:07:02 +02:00
requestingSecondAddress = 1;
delegate->onRequestNewServerIpAndPort(requestingSecondAddress, instanceNum);
} else {
requestingSecondAddress = 0;
}
2017-07-08 18:32:04 +02:00
}
buffer->reuse();
});
}
2023-10-28 22:52:06 +02:00
void ConnectionsManager::init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerpting, std::string installerId, std::string packageId, int32_t timezoneOffset, int64_t userId, bool userPremium, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType, int32_t performanceClass) {
2015-09-24 22:52:02 +02:00
currentVersion = version;
currentLayer = layer;
currentApiId = apiId;
currentConfigPath = configPath;
currentDeviceModel = deviceModel;
currentSystemVersion = systemVersion;
currentAppVersion = appVersion;
currentLangCode = langCode;
2019-07-18 15:01:39 +02:00
currentRegId = regId;
2019-12-31 14:08:08 +01:00
certFingerprint = cFingerpting;
2020-07-26 10:03:38 +02:00
installer = installerId;
2021-04-14 03:44:46 +02:00
package = packageId;
2020-04-24 11:21:58 +02:00
currentDeviceTimezone = timezoneOffset;
2017-07-08 18:32:04 +02:00
currentSystemLangCode = systemLangCode;
2015-09-24 22:52:02 +02:00
currentUserId = userId;
2023-10-28 22:52:06 +02:00
currentUserPremium = userPremium;
2015-10-29 18:10:07 +01:00
currentLogPath = logPath;
2016-04-22 15:49:00 +02:00
pushConnectionEnabled = enablePushConnection;
2017-03-31 01:58:05 +02:00
currentNetworkType = networkType;
networkAvailable = hasNetwork;
2023-02-18 22:24:25 +01:00
currentPerformanceClass = performanceClass;
2015-09-24 22:52:02 +02:00
if (isPaused) {
2017-03-31 01:58:05 +02:00
lastPauseTime = getCurrentTimeMonotonicMillis();
2015-09-24 22:52:02 +02:00
}
if (!currentConfigPath.empty() && currentConfigPath.find_last_of('/') != currentConfigPath.size() - 1) {
currentConfigPath += "/";
}
2018-07-30 04:07:02 +02:00
2015-10-29 18:10:07 +01:00
if (!logPath.empty()) {
2019-01-23 18:03:33 +01:00
LOGS_ENABLED = true;
2018-07-30 04:07:02 +02:00
FileLog::getInstance().init(logPath);
2015-10-29 18:10:07 +01:00
}
2015-09-24 22:52:02 +02:00
loadConfig();
2019-01-23 18:03:33 +01:00
bool needLoadConfig = false;
if (systemLangCode.compare(lastInitSystemLangcode) != 0) {
lastInitSystemLangcode = systemLangCode;
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
datacenter.second->resetInitVersion();
2019-01-23 18:03:33 +01:00
}
needLoadConfig = true;
saveConfig();
}
2019-12-31 14:08:08 +01:00
if (!needLoadConfig && currentUserId != 0) {
Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID);
if (datacenter != nullptr && datacenter->lastInitVersion != currentVersion) {
needLoadConfig = true;
}
}
2019-01-23 18:03:33 +01:00
2021-07-15 16:24:57 +02:00
pthread_create(&networkThread, nullptr, (ConnectionsManager::ThreadProc), this);
2019-01-23 18:03:33 +01:00
if (needLoadConfig) {
2023-05-04 14:25:48 +02:00
updateDcSettings(0, false, false);
2019-01-23 18:03:33 +01:00
}
2015-09-24 22:52:02 +02:00
}
2018-07-30 04:07:02 +02:00
void ConnectionsManager::setProxySettings(std::string address, uint16_t port, std::string username, std::string password, std::string secret) {
scheduleTask([&, address, port, username, password, secret] {
2019-08-22 01:53:26 +02:00
std::string newSecret = decodeSecret(secret);
bool secretChanged = proxySecret != newSecret;
2018-07-30 04:07:02 +02:00
bool reconnect = proxyAddress != address || proxyPort != port || username != proxyUser || proxyPassword != password || secretChanged;
2017-07-08 18:32:04 +02:00
proxyAddress = address;
proxyPort = port;
proxyUser = username;
proxyPassword = password;
2019-08-22 01:53:26 +02:00
proxySecret = std::move(newSecret);
2018-07-30 04:07:02 +02:00
if (!proxyAddress.empty() && connectionState == ConnectionStateConnecting) {
connectionState = ConnectionStateConnectingViaProxy;
if (delegate != nullptr) {
delegate->onConnectionStateChanged(connectionState, instanceNum);
}
} else if (proxyAddress.empty() && connectionState == ConnectionStateConnectingViaProxy) {
connectionState = ConnectionStateConnecting;
if (delegate != nullptr) {
delegate->onConnectionStateChanged(connectionState, instanceNum);
}
}
if (secretChanged) {
Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID);
if (datacenter != nullptr) {
datacenter->resetInitVersion();
}
}
2017-07-08 18:32:04 +02:00
if (reconnect) {
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
datacenter.second->suspendConnections(true);
2017-07-08 18:32:04 +02:00
}
2018-07-30 04:07:02 +02:00
Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID);
if (datacenter != nullptr && datacenter->isHandshakingAny()) {
datacenter->beginHandshake(HandshakeTypeCurrent, true);
}
2017-07-08 18:32:04 +02:00
processRequestQueue(0, 0);
}
});
}
void ConnectionsManager::setLangCode(std::string langCode) {
scheduleTask([&, langCode] {
2021-07-15 16:24:57 +02:00
if (currentLangCode == langCode) {
2017-12-08 18:35:59 +01:00
return;
}
2017-07-08 18:32:04 +02:00
currentLangCode = langCode;
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
datacenter.second->resetInitVersion();
2017-07-08 18:32:04 +02:00
}
saveConfig();
});
}
2019-07-18 15:01:39 +02:00
void ConnectionsManager::setRegId(std::string regId) {
scheduleTask([&, regId] {
2021-07-15 16:24:57 +02:00
if (currentRegId == regId) {
2019-07-18 15:01:39 +02:00
return;
}
currentRegId = regId;
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
datacenter.second->resetInitVersion();
2019-07-18 15:01:39 +02:00
}
2023-05-04 14:25:48 +02:00
updateDcSettings(0, false, true);
2019-07-18 15:01:39 +02:00
saveConfig();
});
}
2019-01-23 18:03:33 +01:00
void ConnectionsManager::setSystemLangCode(std::string langCode) {
scheduleTask([&, langCode] {
2021-07-15 16:24:57 +02:00
if (currentSystemLangCode == langCode) {
2019-01-23 18:03:33 +01:00
return;
}
lastInitSystemLangcode = currentSystemLangCode = langCode;
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
datacenter.second->resetInitVersion();
2019-01-23 18:03:33 +01:00
}
saveConfig();
2023-05-04 14:25:48 +02:00
updateDcSettings(0, false, false);
2019-01-23 18:03:33 +01:00
});
}
2015-09-24 22:52:02 +02:00
void ConnectionsManager::resumeNetwork(bool partial) {
scheduleTask([&, partial] {
2020-02-13 19:26:53 +01:00
if (lastMonotonicPauseTime != 0) {
int64_t diff = (getCurrentTimeMonotonicMillis() - lastMonotonicPauseTime) / 1000;
int64_t systemDiff = getCurrentTime() - lastSystemPauseTime;
if (systemDiff < 0 || abs(systemDiff - diff) > 2) {
timeDifference -= (systemDiff - diff);
}
}
2015-09-24 22:52:02 +02:00
if (partial) {
if (networkPaused) {
2020-02-13 19:26:53 +01:00
lastMonotonicPauseTime = lastPauseTime = getCurrentTimeMonotonicMillis();
lastSystemPauseTime = getCurrentTime();
2015-09-24 22:52:02 +02:00
networkPaused = false;
2019-12-31 14:08:08 +01:00
if (LOGS_ENABLED) DEBUG_D("wakeup network in background account%u", instanceNum);
2015-09-24 22:52:02 +02:00
} else if (lastPauseTime != 0) {
2020-02-13 19:26:53 +01:00
lastMonotonicPauseTime = lastPauseTime = getCurrentTimeMonotonicMillis();
lastSystemPauseTime = getCurrentTime();
2015-09-24 22:52:02 +02:00
networkPaused = false;
2019-12-31 14:08:08 +01:00
if (LOGS_ENABLED) DEBUG_D("reset sleep timeout account%u", instanceNum);
2015-09-24 22:52:02 +02:00
}
} else {
lastPauseTime = 0;
2020-02-13 19:26:53 +01:00
lastMonotonicPauseTime = 0;
lastSystemPauseTime = 0;
2015-09-24 22:52:02 +02:00
networkPaused = false;
2019-12-31 14:08:08 +01:00
if (LOGS_ENABLED) DEBUG_D("wakeup network account%u", instanceNum);
}
if (!networkPaused) {
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
if (datacenter.second->isHandshaking(false)) {
datacenter.second->createGenericConnection()->connect();
} else if (datacenter.second->isHandshaking(true)) {
datacenter.second->createGenericMediaConnection()->connect();
2019-12-31 14:08:08 +01:00
}
}
2015-09-24 22:52:02 +02:00
}
});
}
void ConnectionsManager::pauseNetwork() {
if (lastPauseTime != 0) {
return;
}
2020-02-13 19:26:53 +01:00
lastMonotonicPauseTime = lastPauseTime = getCurrentTimeMonotonicMillis();
lastSystemPauseTime = getCurrentTime();
2020-02-13 21:45:02 +01:00
saveConfig();
2015-09-24 22:52:02 +02:00
}
2018-07-30 04:07:02 +02:00
void ConnectionsManager::setNetworkAvailable(bool value, int32_t type, bool slow) {
2019-06-04 12:14:50 +02:00
scheduleTask([&, value, type, slow] {
2015-09-24 22:52:02 +02:00
networkAvailable = value;
2017-03-31 01:58:05 +02:00
currentNetworkType = type;
2018-07-30 04:07:02 +02:00
networkSlow = slow;
2015-09-24 22:52:02 +02:00
if (!networkAvailable) {
connectionState = ConnectionStateWaitingForNetwork;
} else {
2021-07-15 16:24:57 +02:00
for (auto & datacenter : datacenters) {
if (datacenter.second->isHandshaking(false)) {
datacenter.second->createGenericConnection()->connect();
} else if (datacenter.second->isHandshaking(true)) {
datacenter.second->createGenericMediaConnection()->connect();
}
}
2015-09-24 22:52:02 +02:00
}
if (delegate != nullptr) {
2018-07-30 04:07:02 +02:00
delegate->onConnectionStateChanged(connectionState, instanceNum);
2015-09-24 22:52:02 +02:00
}
});
}
2021-02-24 02:02:54 +01:00
void ConnectionsManager::setIpStrategy(uint8_t value) {
2015-09-24 22:52:02 +02:00
scheduleTask([&, value] {
2023-05-27 14:04:37 +02:00
lastProtocolUsefullData = false;
2021-02-24 02:02:54 +01:00
ipStrategy = value;
2015-09-24 22:52:02 +02:00
});
}
2018-07-30 04:07:02 +02:00
int64_t ConnectionsManager::checkProxy(std::string address, uint16_t port, std::string username, std::string password, std::string secret, onRequestTimeFunc requestTimeFunc, jobject ptr1) {
2021-07-15 16:24:57 +02:00
auto proxyCheckInfo = new ProxyCheckInfo();
2018-07-30 04:07:02 +02:00
proxyCheckInfo->address = address;
proxyCheckInfo->port = port;
proxyCheckInfo->username = username;
proxyCheckInfo->password = password;
2019-08-22 01:53:26 +02:00
proxyCheckInfo->secret = decodeSecret(secret);
2018-07-30 04:07:02 +02:00
proxyCheckInfo->onRequestTime = requestTimeFunc;
proxyCheckInfo->pingId = ++lastPingProxyId;
proxyCheckInfo->instanceNum = instanceNum;
proxyCheckInfo->ptr1 = ptr1;
2019-07-18 15:01:39 +02:00
scheduleCheckProxyInternal(proxyCheckInfo);
2018-07-30 04:07:02 +02:00
return proxyCheckInfo->pingId;
}
2019-07-18 15:01:39 +02:00
void ConnectionsManager::scheduleCheckProxyInternal(ProxyCheckInfo *proxyCheckInfo) {
2018-07-30 04:07:02 +02:00
scheduleTask([&, proxyCheckInfo] {
2019-07-18 15:01:39 +02:00
checkProxyInternal(proxyCheckInfo);
});
}
void ConnectionsManager::checkProxyInternal(ProxyCheckInfo *proxyCheckInfo) {
int32_t freeConnectionNum = -1;
if (proxyActiveChecks.size() != PROXY_CONNECTIONS_COUNT) {
for (int32_t a = 0; a < PROXY_CONNECTIONS_COUNT; a++) {
bool found = false;
2021-07-15 16:24:57 +02:00
for (auto & proxyActiveCheck : proxyActiveChecks) {
if (proxyActiveCheck.get()->connectionNum == a) {
2019-07-18 15:01:39 +02:00
found = true;
2018-07-30 04:07:02 +02:00
break;
}
}
2019-07-18 15:01:39 +02:00
if (!found) {
freeConnectionNum = a;
break;
}
2018-07-30 04:07:02 +02:00
}
2019-07-18 15:01:39 +02:00
}
if (freeConnectionNum == -1) {
proxyCheckQueue.push_back(std::unique_ptr<ProxyCheckInfo>(proxyCheckInfo));
} else {
2021-07-15 16:24:57 +02:00
auto connectionType = (ConnectionType) (ConnectionTypeProxy | (freeConnectionNum << 16));
2019-07-18 15:01:39 +02:00
Datacenter *datacenter = getDatacenterWithId(DEFAULT_DATACENTER_ID);
Connection *connection = datacenter->getProxyConnection((uint8_t) freeConnectionNum, true, false);
if (connection != nullptr) {
connection->setOverrideProxy(proxyCheckInfo->address, proxyCheckInfo->port, proxyCheckInfo->username, proxyCheckInfo->password, proxyCheckInfo->secret);
connection->suspendConnection();
proxyCheckInfo->connectionNum = freeConnectionNum;
2021-07-15 16:24:57 +02:00
auto request = new TL_ping();
2019-07-18 15:01:39 +02:00
request->ping_id = proxyCheckInfo->pingId;
2024-03-08 15:32:16 +01:00
proxyCheckInfo->requestToken = sendRequest(request, nullptr, nullptr, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin, DEFAULT_DATACENTER_ID, connectionType, true, 0);
2019-07-18 15:01:39 +02:00
proxyActiveChecks.push_back(std::unique_ptr<ProxyCheckInfo>(proxyCheckInfo));
} else if (PFS_ENABLED) {
if (datacenter->isHandshaking(false)) {
datacenter->beginHandshake(HandshakeTypeTemp, false);
2018-07-30 04:07:02 +02:00
}
2019-07-18 15:01:39 +02:00
proxyCheckQueue.push_back(std::unique_ptr<ProxyCheckInfo>(proxyCheckInfo));
2018-07-30 04:07:02 +02:00
}
2019-07-18 15:01:39 +02:00
}
2018-07-30 04:07:02 +02:00
}
2015-09-24 22:52:02 +02:00
#ifdef ANDROID
void ConnectionsManager::useJavaVM(JavaVM *vm, bool useJavaByteBuffers) {
javaVm = vm;
if (useJavaByteBuffers) {
2021-07-15 16:24:57 +02:00
JNIEnv *env = nullptr;
2015-09-24 22:52:02 +02:00
if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("can't get jnienv");
2015-09-24 22:52:02 +02:00
exit(1);
}
2023-03-24 12:38:14 +01:00
DEBUG_REF("connectionsmanager byte buffer");
2015-09-24 22:52:02 +02:00
jclass_ByteBuffer = (jclass) env->NewGlobalRef(env->FindClass("java/nio/ByteBuffer"));
2021-07-15 16:24:57 +02:00
if (jclass_ByteBuffer == nullptr) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("can't find java ByteBuffer class");
2015-09-24 22:52:02 +02:00
exit(1);
}
jclass_ByteBuffer_allocateDirect = env->GetStaticMethodID(jclass_ByteBuffer, "allocateDirect", "(I)Ljava/nio/ByteBuffer;");
2021-07-15 16:24:57 +02:00
if (jclass_ByteBuffer_allocateDirect == nullptr) {
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_E("can't find java ByteBuffer allocateDirect");
2015-09-24 22:52:02 +02:00
exit(1);
}
2019-01-23 18:03:33 +01:00
if (LOGS_ENABLED) DEBUG_D("using java ByteBuffer");
2015-09-24 22:52:02 +02:00
}
}
2023-07-20 22:15:36 +02:00
void ConnectionsManager::reconnect(int32_t dcId, int32_t connectionType) {
scheduleTask([&, dcId, connectionType] {
scheduleTask([&, dcId, connectionType] {
Datacenter *datacenter = getDatacenterWithId(dcId);
if (datacenter != nullptr) {
Connection *connection = datacenter->getConnectionByType(connectionType, false,
0);
if (connection != nullptr) {
2024-03-08 15:32:16 +01:00
if (LOGS_ENABLED) DEBUG_D("discard connection dcId=%d connectionType=%d", dcId,
2023-10-28 22:52:06 +02:00
connectionType);
2023-07-20 22:15:36 +02:00
connection->suspendConnection(true);
}
}
});
});
}
2015-09-24 22:52:02 +02:00
#endif