diff --git a/TMessagesProj/jni/Android.mk b/TMessagesProj/jni/Android.mk index 4a142597c..5f2fd36aa 100644 --- a/TMessagesProj/jni/Android.mk +++ b/TMessagesProj/jni/Android.mk @@ -956,40 +956,6 @@ LOCAL_SRC_FILES := \ include $(BUILD_STATIC_LIBRARY) -################################################################################ -# tgnet -################################################################################ - - -include $(CLEAR_VARS) - -LOCAL_CPPFLAGS := -Wall -std=c++11 -DANDROID -frtti -DHAVE_PTHREAD -finline-functions -ffast-math -Os -LOCAL_C_INCLUDES += $(LOCAL_PATH)/openssl/include/ -LOCAL_ARM_MODE := arm -LOCAL_MODULE := tgnet -LOCAL_STATIC_LIBRARIES := crypto - -LOCAL_SRC_FILES := \ -./tgnet/BuffersStorage.cpp \ -./tgnet/ByteArray.cpp \ -./tgnet/ByteStream.cpp \ -./tgnet/Connection.cpp \ -./tgnet/ConnectionSession.cpp \ -./tgnet/ConnectionsManager.cpp \ -./tgnet/ConnectionSocket.cpp \ -./tgnet/Datacenter.cpp \ -./tgnet/EventObject.cpp \ -./tgnet/FileLog.cpp \ -./tgnet/MTProtoScheme.cpp \ -./tgnet/NativeByteBuffer.cpp \ -./tgnet/Request.cpp \ -./tgnet/Timer.cpp \ -./tgnet/TLObject.cpp \ -./tgnet/Config.cpp - -include $(BUILD_STATIC_LIBRARY) - - ################################################################################ # webp ################################################################################ @@ -1347,7 +1313,7 @@ LOCAL_CFLAGS += -Drestrict='' -D__EMX__ -DOPUS_BUILD -DFIXED_POINT -DUSE_ALLOCA LOCAL_CFLAGS += -DANDROID_NDK -DDISABLE_IMPORTGL -fno-strict-aliasing -fprefetch-loop-arrays -DAVOID_TABLES -DANDROID_TILE_BASED_DECODE -DANDROID_ARMV6_IDCT -ffast-math -D__STDC_CONSTANT_MACROS LOCAL_CPPFLAGS := -DBSD=1 -ffast-math -Os -funroll-loops -std=c++11 LOCAL_LDLIBS := -ljnigraphics -llog -lz -latomic -LOCAL_STATIC_LIBRARIES := etpan sasl2 webp sqlite tgnet breakpad avformat avcodec avutil libiconv +LOCAL_STATIC_LIBRARIES := etpan sasl2 webp sqlite crypto breakpad avformat avcodec avutil libiconv # if you get "undefined reference" errors, the reason for this may be the _order_! Eg. libiconv as the first library does not work! LOCAL_SRC_FILES := \ @@ -1637,7 +1603,6 @@ LOCAL_SRC_FILES += \ ./image.c \ ./video.c \ ./gifvideo.cpp \ -./TgNetWrapper.cpp \ ../../../messenger-backend/src/mrchat.c \ ../../../messenger-backend/src/mrchatlist.c \ ../../../messenger-backend/src/mrcontact.c \ diff --git a/TMessagesProj/jni/TgNetWrapper.cpp b/TMessagesProj/jni/TgNetWrapper.cpp deleted file mode 100644 index decb50bd9..000000000 --- a/TMessagesProj/jni/TgNetWrapper.cpp +++ /dev/null @@ -1,336 +0,0 @@ -#include -#include "tgnet/BuffersStorage.h" -#include "tgnet/NativeByteBuffer.h" -#include "tgnet/ConnectionsManager.h" -#include "tgnet/MTProtoScheme.h" -#include "tgnet/FileLog.h" - -JavaVM *java; -jclass jclass_RequestDelegateInternal; -jmethodID jclass_RequestDelegateInternal_run; - -jclass jclass_QuickAckDelegate; -jmethodID jclass_QuickAckDelegate_run; - -jclass jclass_ConnectionsManager; -jmethodID jclass_ConnectionsManager_onUnparsedMessageReceived; -jmethodID jclass_ConnectionsManager_onUpdate; -jmethodID jclass_ConnectionsManager_onSessionCreated; -jmethodID jclass_ConnectionsManager_onLogout; -jmethodID jclass_ConnectionsManager_onConnectionStateChanged; -jmethodID jclass_ConnectionsManager_onInternalPushReceived; -jmethodID jclass_ConnectionsManager_onUpdateConfig; - -jint getFreeBuffer(JNIEnv *env, jclass c, jint length) { - return (jint) BuffersStorage::getInstance().getFreeBuffer(length); -} - -jint limit(JNIEnv *env, jclass c, jint address) { - NativeByteBuffer *buffer = (NativeByteBuffer *) address; - return buffer->limit(); -} - -jint position(JNIEnv *env, jclass c, jint address) { - NativeByteBuffer *buffer = (NativeByteBuffer *) address; - return buffer->position(); -} - -void reuse(JNIEnv *env, jclass c, jint address) { - NativeByteBuffer *buffer = (NativeByteBuffer *) address; - buffer->reuse(); -} - -jobject getJavaByteBuffer(JNIEnv *env, jclass c, jint address) { - NativeByteBuffer *buffer = (NativeByteBuffer *) address; - return buffer->getJavaByteBuffer(); -} - -static const char *NativeByteBufferClassPathName = "org/telegram/tgnet/NativeByteBuffer"; -static JNINativeMethod NativeByteBufferMethods[] = { - {"native_getFreeBuffer", "(I)I", (void *) getFreeBuffer}, - {"native_limit", "(I)I", (void *) limit}, - {"native_position", "(I)I", (void *) position}, - {"native_reuse", "(I)V", (void *) reuse}, - {"native_getJavaByteBuffer", "(I)Ljava/nio/ByteBuffer;", (void *) getJavaByteBuffer} -}; - -jlong getCurrentTimeMillis(JNIEnv *env, jclass c) { - return ConnectionsManager::getInstance().getCurrentTimeMillis(); -} - -jint getCurrentTime(JNIEnv *env, jclass c) { - return ConnectionsManager::getInstance().getCurrentTime(); -} - -jint getTimeDifference(JNIEnv *env, jclass c) { - return ConnectionsManager::getInstance().getTimeDifference(); -} - -void sendRequest(JNIEnv *env, jclass c, jint object, jobject onComplete, jobject onQuickAck, jint flags, jint datacenterId, jint connetionType, jboolean immediate, jint token) { - TL_api_request *request = new TL_api_request(); - request->request = (NativeByteBuffer *) object; - if (onComplete != nullptr) { - onComplete = env->NewGlobalRef(onComplete); - } - if (onQuickAck != nullptr) { - onQuickAck = env->NewGlobalRef(onQuickAck); - } - ConnectionsManager::getInstance().sendRequest(request, ([onComplete](TLObject *response, TL_error *error) { - TL_api_response *resp = (TL_api_response *) response; - jint ptr = 0; - jint errorCode = 0; - jstring errorText = nullptr; - if (resp != nullptr) { - ptr = (jint) resp->response.get(); - } else if (error != nullptr) { - errorCode = error->code; - errorText = jniEnv->NewStringUTF(error->text.c_str()); - } - if (onComplete != nullptr) { - jniEnv->CallVoidMethod(onComplete, jclass_RequestDelegateInternal_run, ptr, errorCode, errorText); - } - if (errorText != nullptr) { - jniEnv->DeleteLocalRef(errorText); - } - }), ([onQuickAck] { - if (onQuickAck != nullptr) { - jniEnv->CallVoidMethod(onQuickAck, jclass_QuickAckDelegate_run); - } - }), flags, datacenterId, (ConnectionType) connetionType, immediate, token, onComplete, onQuickAck); -} - -void cancelRequest(JNIEnv *env, jclass c, jint token, jboolean notifyServer) { - return ConnectionsManager::getInstance().cancelRequest(token, notifyServer); -} - -void cleanUp(JNIEnv *env, jclass c) { - return ConnectionsManager::getInstance().cleanUp(); -} - -void cancelRequestsForGuid(JNIEnv *env, jclass c, jint guid) { - return ConnectionsManager::getInstance().cancelRequestsForGuid(guid); -} - -void bindRequestToGuid(JNIEnv *env, jclass c, jint requestToken, jint guid) { - return ConnectionsManager::getInstance().bindRequestToGuid(requestToken, guid); -} - -void applyDatacenterAddress(JNIEnv *env, jclass c, jint datacenterId, jstring ipAddress, jint port) { - const char *valueStr = env->GetStringUTFChars(ipAddress, 0); - - ConnectionsManager::getInstance().applyDatacenterAddress(datacenterId, std::string(valueStr), port); - - if (valueStr != 0) { - env->ReleaseStringUTFChars(ipAddress, valueStr); - } -} - -jint getConnectionState(JNIEnv *env, jclass c) { - return ConnectionsManager::getInstance().getConnectionState(); -} - -void setUserId(JNIEnv *env, jclass c, int32_t id) { - ConnectionsManager::getInstance().setUserId(id); -} - -void switchBackend(JNIEnv *env, jclass c) { - ConnectionsManager::getInstance().switchBackend(); -} - -void pauseNetwork(JNIEnv *env, jclass c) { - ConnectionsManager::getInstance().pauseNetwork(); -} - -void resumeNetwork(JNIEnv *env, jclass c, jboolean partial) { - ConnectionsManager::getInstance().resumeNetwork(partial); -} - -void updateDcSettings(JNIEnv *env, jclass c) { - ConnectionsManager::getInstance().updateDcSettings(0); -} - -void setUseIpv6(JNIEnv *env, jclass c, bool value) { - ConnectionsManager::getInstance().setUseIpv6(value); -} - -void setNetworkAvailable(JNIEnv *env, jclass c, jboolean value) { - ConnectionsManager::getInstance().setNetworkAvailable(value); -} - -void setPushConnectionEnabled(JNIEnv *env, jclass c, jboolean value) { - ConnectionsManager::getInstance().setPushConnectionEnabled(value); -} - -class Delegate : public ConnectiosManagerDelegate { - - void onUpdate() { - jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUpdate); - } - - void onSessionCreated() { - jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onSessionCreated); - } - - void onConnectionStateChanged(ConnectionState state) { - jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onConnectionStateChanged, state); - } - - void onUnparsedMessageReceived(int64_t reqMessageId, NativeByteBuffer *buffer, ConnectionType connectionType) { - if (connectionType == ConnectionTypeGeneric) { - jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUnparsedMessageReceived, buffer); - } - } - - void onLogout() { - jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onLogout); - } - - void onUpdateConfig(TL_config *config) { - NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(config->getObjectSize()); - config->serializeToStream(buffer); - buffer->position(0); - jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onUpdateConfig, buffer); - buffer->reuse(); - } - - void onInternalPushReceived() { - jniEnv->CallStaticVoidMethod(jclass_ConnectionsManager, jclass_ConnectionsManager_onInternalPushReceived); - } -}; - -void init(JNIEnv *env, jclass c, jint version, jint layer, jint apiId, jstring deviceModel, jstring systemVersion, jstring appVersion, jstring langCode, jstring configPath, jstring logPath, jint userId, jboolean enablePushConnection) { - const char *deviceModelStr = env->GetStringUTFChars(deviceModel, 0); - const char *systemVersionStr = env->GetStringUTFChars(systemVersion, 0); - const char *appVersionStr = env->GetStringUTFChars(appVersion, 0); - const char *langCodeStr = env->GetStringUTFChars(langCode, 0); - const char *configPathStr = env->GetStringUTFChars(configPath, 0); - const char *logPathStr = env->GetStringUTFChars(logPath, 0); - - ConnectionsManager::getInstance().init(version, layer, apiId, std::string(deviceModelStr), std::string(systemVersionStr), std::string(appVersionStr), std::string(langCodeStr), std::string(configPathStr), std::string(logPathStr), userId, true, enablePushConnection); - - if (deviceModelStr != 0) { - env->ReleaseStringUTFChars(deviceModel, deviceModelStr); - } - if (systemVersionStr != 0) { - env->ReleaseStringUTFChars(systemVersion, systemVersionStr); - } - if (appVersionStr != 0) { - env->ReleaseStringUTFChars(appVersion, appVersionStr); - } - if (langCodeStr != 0) { - env->ReleaseStringUTFChars(langCode, langCodeStr); - } - if (configPathStr != 0) { - env->ReleaseStringUTFChars(configPath, configPathStr); - } - if (logPathStr != 0) { - env->ReleaseStringUTFChars(logPath, logPathStr); - } -} - -void setJava(JNIEnv *env, jclass c, jboolean useJavaByteBuffers) { - ConnectionsManager::useJavaVM(java, useJavaByteBuffers); - ConnectionsManager::getInstance().setDelegate(new Delegate()); -} - -static const char *ConnectionsManagerClassPathName = "org/telegram/tgnet/ConnectionsManager"; -static JNINativeMethod ConnectionsManagerMethods[] = { - {"native_getCurrentTimeMillis", "()J", (void *) getCurrentTimeMillis}, - {"native_getCurrentTime", "()I", (void *) getCurrentTime}, - {"native_getTimeDifference", "()I", (void *) getTimeDifference}, - {"native_sendRequest", "(ILorg/telegram/tgnet/RequestDelegateInternal;Lorg/telegram/tgnet/QuickAckDelegate;IIIZI)V", (void *) sendRequest}, - {"native_cancelRequest", "(IZ)V", (void *) cancelRequest}, - {"native_cleanUp", "()V", (void *) cleanUp}, - {"native_cancelRequestsForGuid", "(I)V", (void *) cancelRequestsForGuid}, - {"native_bindRequestToGuid", "(II)V", (void *) bindRequestToGuid}, - {"native_applyDatacenterAddress", "(ILjava/lang/String;I)V", (void *) applyDatacenterAddress}, - {"native_getConnectionState", "()I", (void *) getConnectionState}, - {"native_setUserId", "(I)V", (void *) setUserId}, - {"native_init", "(IIILjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;IZ)V", (void *) init}, - {"native_switchBackend", "()V", (void *) switchBackend}, - {"native_pauseNetwork", "()V", (void *) pauseNetwork}, - {"native_resumeNetwork", "(Z)V", (void *) resumeNetwork}, - {"native_updateDcSettings", "()V", (void *) updateDcSettings}, - {"native_setUseIpv6", "(Z)V", (void *) setUseIpv6}, - {"native_setNetworkAvailable", "(Z)V", (void *) setNetworkAvailable}, - {"native_setPushConnectionEnabled", "(Z)V", (void *) setPushConnectionEnabled}, - {"native_setJava", "(Z)V", (void *) setJava} -}; - -inline int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *methods, int methodsCount) { - jclass clazz; - clazz = env->FindClass(className); - if (clazz == NULL) { - return JNI_FALSE; - } - if (env->RegisterNatives(clazz, methods, methodsCount) < 0) { - return JNI_FALSE; - } - return JNI_TRUE; -} - -extern "C" int registerNativeTgNetFunctions(JavaVM *vm, JNIEnv *env) { - java = vm; - - if (!registerNativeMethods(env, NativeByteBufferClassPathName, NativeByteBufferMethods, sizeof(NativeByteBufferMethods) / sizeof(NativeByteBufferMethods[0]))) { - return JNI_FALSE; - } - - if (!registerNativeMethods(env, ConnectionsManagerClassPathName, ConnectionsManagerMethods, sizeof(ConnectionsManagerMethods) / sizeof(ConnectionsManagerMethods[0]))) { - return JNI_FALSE; - } - - jclass_RequestDelegateInternal = (jclass) env->NewGlobalRef(env->FindClass("org/telegram/tgnet/RequestDelegateInternal")); - if (jclass_RequestDelegateInternal == 0) { - return JNI_FALSE; - } - jclass_RequestDelegateInternal_run = env->GetMethodID(jclass_RequestDelegateInternal, "run", "(IILjava/lang/String;)V"); - if (jclass_RequestDelegateInternal_run == 0) { - return JNI_FALSE; - } - - jclass_QuickAckDelegate = (jclass) env->NewGlobalRef(env->FindClass("org/telegram/tgnet/QuickAckDelegate")); - if (jclass_RequestDelegateInternal == 0) { - return JNI_FALSE; - } - jclass_QuickAckDelegate_run = env->GetMethodID(jclass_QuickAckDelegate, "run", "()V"); - if (jclass_QuickAckDelegate_run == 0) { - return JNI_FALSE; - } - - jclass_ConnectionsManager = (jclass) env->NewGlobalRef(env->FindClass("org/telegram/tgnet/ConnectionsManager")); - if (jclass_ConnectionsManager == 0) { - return JNI_FALSE; - } - jclass_ConnectionsManager_onUnparsedMessageReceived = env->GetStaticMethodID(jclass_ConnectionsManager, "onUnparsedMessageReceived", "(I)V"); - if (jclass_ConnectionsManager_onUnparsedMessageReceived == 0) { - return JNI_FALSE; - } - jclass_ConnectionsManager_onUpdate = env->GetStaticMethodID(jclass_ConnectionsManager, "onUpdate", "()V"); - if (jclass_ConnectionsManager_onUpdate == 0) { - return JNI_FALSE; - } - jclass_ConnectionsManager_onSessionCreated = env->GetStaticMethodID(jclass_ConnectionsManager, "onSessionCreated", "()V"); - if (jclass_ConnectionsManager_onSessionCreated == 0) { - return JNI_FALSE; - } - jclass_ConnectionsManager_onLogout = env->GetStaticMethodID(jclass_ConnectionsManager, "onLogout", "()V"); - if (jclass_ConnectionsManager_onLogout == 0) { - return JNI_FALSE; - } - jclass_ConnectionsManager_onConnectionStateChanged = env->GetStaticMethodID(jclass_ConnectionsManager, "onConnectionStateChanged", "(I)V"); - if (jclass_ConnectionsManager_onConnectionStateChanged == 0) { - return JNI_FALSE; - } - jclass_ConnectionsManager_onInternalPushReceived = env->GetStaticMethodID(jclass_ConnectionsManager, "onInternalPushReceived", "()V"); - if (jclass_ConnectionsManager_onInternalPushReceived == 0) { - return JNI_FALSE; - } - jclass_ConnectionsManager_onUpdateConfig = env->GetStaticMethodID(jclass_ConnectionsManager, "onUpdateConfig", "(I)V"); - if (jclass_ConnectionsManager_onUpdateConfig == 0) { - return JNI_FALSE; - } - ConnectionsManager::getInstance().setDelegate(new Delegate()); - - return JNI_TRUE; -} diff --git a/TMessagesProj/jni/jni.c b/TMessagesProj/jni/jni.c index 1589a61e9..eff16764d 100644 --- a/TMessagesProj/jni/jni.c +++ b/TMessagesProj/jni/jni.c @@ -9,7 +9,7 @@ #include "utils.h" #include "image.h" -int registerNativeTgNetFunctions(JavaVM *vm, JNIEnv *env); +//int registerNativeTgNetFunctions(JavaVM *vm, JNIEnv *env); int gifvideoOnJNILoad(JavaVM *vm, JNIEnv *env); jint JNI_OnLoad(JavaVM *vm, void *reserved) { @@ -28,9 +28,11 @@ jint JNI_OnLoad(JavaVM *vm, void *reserved) { return -1; } + /* if (registerNativeTgNetFunctions(vm, env) != JNI_TRUE) { return -1; } + */ return JNI_VERSION_1_6; } @@ -39,6 +41,7 @@ void JNI_OnUnload(JavaVM *vm, void *reserved) { } +/* JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *env, jclass class, jobject buffer, jbyteArray key, jbyteArray iv, jboolean encrypt, int offset, int length) { jbyte *what = (*env)->GetDirectBufferAddress(env, buffer) + offset; unsigned char *keyBuff = (unsigned char *)(*env)->GetByteArrayElements(env, key, NULL); @@ -55,6 +58,7 @@ JNIEXPORT void Java_org_telegram_messenger_Utilities_aesIgeEncryption(JNIEnv *en (*env)->ReleaseByteArrayElements(env, key, keyBuff, JNI_ABORT); (*env)->ReleaseByteArrayElements(env, iv, ivBuff, 0); } +*/ JNIEXPORT jstring Java_org_telegram_messenger_Utilities_readlink(JNIEnv *env, jclass class, jstring path) { static char buf[1000]; diff --git a/TMessagesProj/jni/mr_wrapper.c b/TMessagesProj/jni/mr_wrapper.c index 3f654c55d..a795f4131 100644 --- a/TMessagesProj/jni/mr_wrapper.c +++ b/TMessagesProj/jni/mr_wrapper.c @@ -674,5 +674,14 @@ JNIEXPORT jstring Java_org_telegram_messenger_MrMailbox_MrGetVersionStr(JNIEnv * } +#include +JNIEXPORT jlong Java_org_telegram_messenger_MrMailbox_getCurrentTimeMillis(JNIEnv *env, jclass c) { + struct timespec ts; + clock_gettime(CLOCK_REALTIME, &ts); + return (jlong) ts.tv_sec * 1000 + (int64_t) ts.tv_nsec / 1000000; +} +JNIEXPORT jint Java_org_telegram_messenger_MrMailbox_getCurrentTime(JNIEnv *env, jclass c) { + return (jint) (Java_org_telegram_messenger_MrMailbox_getCurrentTimeMillis(env, c) / 1000); +} diff --git a/TMessagesProj/jni/tgnet/BuffersStorage.cpp b/TMessagesProj/jni/tgnet/BuffersStorage.cpp deleted file mode 100644 index 7d7395bcc..000000000 --- a/TMessagesProj/jni/tgnet/BuffersStorage.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include "BuffersStorage.h" -#include "FileLog.h" -#include "NativeByteBuffer.h" - -BuffersStorage &BuffersStorage::getInstance() { - static BuffersStorage instance(true); - return instance; -} - -BuffersStorage::BuffersStorage(bool threadSafe) { - isThreadSafe = threadSafe; - if (isThreadSafe) { - pthread_mutex_init(&mutex, NULL); - } - for (uint32_t a = 0; a < 4; a++) { - freeBuffers8.push_back(new NativeByteBuffer((uint32_t) 8)); - } - for (uint32_t a = 0; a < 5; a++) { - freeBuffers128.push_back(new NativeByteBuffer((uint32_t) 128)); - } -} - -NativeByteBuffer *BuffersStorage::getFreeBuffer(uint32_t size) { - uint32_t byteCount = 0; - std::vector *arrayToGetFrom = nullptr; - NativeByteBuffer *buffer = nullptr; - if (size <= 8) { - arrayToGetFrom = &freeBuffers8; - byteCount = 8; - } else if (size <= 128) { - arrayToGetFrom = &freeBuffers128; - byteCount = 128; - } else if (size <= 1024 + 200) { - arrayToGetFrom = &freeBuffers1024; - byteCount = 1024 + 200; - } else if (size <= 4096 + 200) { - arrayToGetFrom = &freeBuffers4096; - byteCount = 4096 + 200; - } else if (size <= 16384 + 200) { - arrayToGetFrom = &freeBuffers16384; - byteCount = 16384 + 200; - } else if (size <= 40000) { - arrayToGetFrom = &freeBuffers32768; - byteCount = 40000; - } else if (size <= 160000) { - arrayToGetFrom = &freeBuffersBig; - byteCount = 160000; - } else { - buffer = new NativeByteBuffer(size); - } - - if (arrayToGetFrom != nullptr) { - if (isThreadSafe) { - pthread_mutex_lock(&mutex); - } - if (arrayToGetFrom->size() > 0) { - buffer = (*arrayToGetFrom)[0]; - arrayToGetFrom->erase(arrayToGetFrom->begin()); - } - if (isThreadSafe) { - pthread_mutex_unlock(&mutex); - } - if (buffer == nullptr) { - buffer = new NativeByteBuffer(byteCount); - DEBUG_D("create new %u buffer", byteCount); - } - } - if (buffer != nullptr) { - buffer->limit(size); - buffer->rewind(); - } - return buffer; -} - -void BuffersStorage::reuseFreeBuffer(NativeByteBuffer *buffer) { - if (buffer == nullptr) { - return; - } - std::vector *arrayToReuse = nullptr; - uint32_t capacity = buffer->capacity(); - uint32_t maxCount = 10; - if (capacity == 8) { - arrayToReuse = &freeBuffers8; - maxCount = 80; - } else if (capacity == 128) { - arrayToReuse = &freeBuffers128; - maxCount = 80; - } else if (capacity == 1024 + 200) { - arrayToReuse = &freeBuffers1024; - } else if (capacity == 4096 + 200) { - arrayToReuse = &freeBuffers4096; - } else if (capacity == 16384 + 200) { - arrayToReuse = &freeBuffers16384; - } else if (capacity == 40000) { - arrayToReuse = &freeBuffers32768; - } else if (capacity == 160000) { - arrayToReuse = &freeBuffersBig; - } - if (arrayToReuse != nullptr) { - if (isThreadSafe) { - pthread_mutex_lock(&mutex); - } - if (arrayToReuse->size() < maxCount) { - arrayToReuse->push_back(buffer); - } else { - DEBUG_D("too more %d buffers", capacity); - delete buffer; - } - if (isThreadSafe) { - pthread_mutex_unlock(&mutex); - } - } else { - delete buffer; - } -} diff --git a/TMessagesProj/jni/tgnet/BuffersStorage.h b/TMessagesProj/jni/tgnet/BuffersStorage.h deleted file mode 100644 index 57c4f3f85..000000000 --- a/TMessagesProj/jni/tgnet/BuffersStorage.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef BUFFERSSTORAGE_H -#define BUFFERSSTORAGE_H - -#include -#include -#include - -class NativeByteBuffer; - -class BuffersStorage { - -public: - BuffersStorage(bool threadSafe); - NativeByteBuffer *getFreeBuffer(uint32_t size); - void reuseFreeBuffer(NativeByteBuffer *buffer); - static BuffersStorage &getInstance(); - -private: - std::vector freeBuffers8; - std::vector freeBuffers128; - std::vector freeBuffers1024; - std::vector freeBuffers4096; - std::vector freeBuffers16384; - std::vector freeBuffers32768; - std::vector freeBuffersBig; - bool isThreadSafe = true; - pthread_mutex_t mutex; -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/ByteArray.cpp b/TMessagesProj/jni/tgnet/ByteArray.cpp deleted file mode 100644 index 3be5b36fd..000000000 --- a/TMessagesProj/jni/tgnet/ByteArray.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include "ByteArray.h" -#include "FileLog.h" - -ByteArray::ByteArray() { - bytes = nullptr; - length = 0; -} - -ByteArray::ByteArray(uint32_t len) { - bytes = new uint8_t[len]; - if (bytes == nullptr) { - DEBUG_E("unable to allocate byte buffer %u", len); - exit(1); - } - length = len; -} - - -ByteArray::ByteArray(ByteArray *byteArray) { - bytes = new uint8_t[byteArray->length]; - if (bytes == nullptr) { - DEBUG_E("unable to allocate byte buffer %u", byteArray->length); - exit(1); - } - length = byteArray->length; - memcpy(bytes, byteArray->bytes, length); -} - -ByteArray::ByteArray(uint8_t *buffer, uint32_t len) { - bytes = new uint8_t[len]; - if (bytes == nullptr) { - DEBUG_E("unable to allocate byte buffer %u", len); - exit(1); - } - length = len; - memcpy(bytes, buffer, length); -} - -ByteArray::~ByteArray() { - if (bytes != nullptr) { - delete[] bytes; - bytes = nullptr; - } -} - -void ByteArray::alloc(uint32_t len) { - if (bytes != nullptr) { - delete[] bytes; - bytes = nullptr; - } - bytes = new uint8_t[len]; - if (bytes == nullptr) { - DEBUG_E("unable to allocate byte buffer %u", len); - exit(1); - } - length = len; -} - -bool ByteArray::isEqualTo(ByteArray *byteArray) { - return byteArray->length == length && !memcmp(byteArray->bytes, bytes, length); -} diff --git a/TMessagesProj/jni/tgnet/ByteArray.h b/TMessagesProj/jni/tgnet/ByteArray.h deleted file mode 100644 index 2bb6f13fb..000000000 --- a/TMessagesProj/jni/tgnet/ByteArray.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef BYTEARRAY_H -#define BYTEARRAY_H - -#include - -class ByteArray { - -public: - ByteArray(); - ByteArray(uint32_t len); - ByteArray(ByteArray *byteArray); - ByteArray(uint8_t *buffer, uint32_t len); - ~ByteArray(); - void alloc(uint32_t len); - - uint32_t length; - uint8_t *bytes; - - bool isEqualTo(ByteArray *byteArray); - -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/ByteStream.cpp b/TMessagesProj/jni/tgnet/ByteStream.cpp deleted file mode 100644 index 2b2209d75..000000000 --- a/TMessagesProj/jni/tgnet/ByteStream.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include "ByteStream.h" -#include "NativeByteBuffer.h" - -ByteStream::ByteStream() { - -} - -ByteStream::~ByteStream() { - -} - -void ByteStream::append(NativeByteBuffer *buffer) { - if (buffer == nullptr) { - return; - } - buffersQueue.push_back(buffer); -} - -bool ByteStream::hasData() { - size_t size = buffersQueue.size(); - for (uint32_t a = 0; a < size; a++) { - if (buffersQueue[a]->hasRemaining()) { - return true; - } - } - return false; -} - -void ByteStream::get(NativeByteBuffer *dst) { - if (dst == nullptr) { - return; - } - - size_t size = buffersQueue.size(); - NativeByteBuffer *buffer; - for (uint32_t a = 0; a < size; a++) { - buffer = buffersQueue[a]; - if (buffer->remaining() > dst->remaining()) { - dst->writeBytes(buffer->bytes(), buffer->position(), dst->remaining()); - break; - } - dst->writeBytes(buffer->bytes(), buffer->position(), buffer->remaining()); - if (!dst->hasRemaining()) { - break; - } - } -} - -void ByteStream::discard(uint32_t count) { - uint32_t remaining; - NativeByteBuffer *buffer; - while (count > 0) { - buffer = buffersQueue[0]; - remaining = buffer->remaining(); - if (count < remaining) { - buffer->position(buffer->position() + count); - break; - } - buffer->reuse(); - buffersQueue.erase(buffersQueue.begin()); - count -= remaining; - } -} - -void ByteStream::clean() { - if (buffersQueue.empty()) { - return; - } - size_t size = buffersQueue.size(); - for (uint32_t a = 0; a < size; a++) { - NativeByteBuffer *buffer = buffersQueue[a]; - buffer->reuse(); - } - buffersQueue.clear(); -} diff --git a/TMessagesProj/jni/tgnet/ByteStream.h b/TMessagesProj/jni/tgnet/ByteStream.h deleted file mode 100644 index 56c3e4401..000000000 --- a/TMessagesProj/jni/tgnet/ByteStream.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef BYTESTREAM_H -#define BYTESTREAM_H - -#include -#include - -class NativeByteBuffer; - -class ByteStream { - -public: - ByteStream(); - ~ByteStream(); - void append(NativeByteBuffer *buffer); - bool hasData(); - void get(NativeByteBuffer *dst); - void discard(uint32_t count); - void clean(); - -private: - std::vector buffersQueue; -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/Config.cpp b/TMessagesProj/jni/tgnet/Config.cpp deleted file mode 100644 index 6da1995e6..000000000 --- a/TMessagesProj/jni/tgnet/Config.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include "Config.h" -#include "ConnectionsManager.h" -#include "FileLog.h" -#include "BuffersStorage.h" - -Config::Config(std::string fileName) { - configPath = ConnectionsManager::getInstance().currentConfigPath + fileName; - backupPath = configPath + ".bak"; - FILE *backup = fopen(backupPath.c_str(), "rb"); - if (backup != nullptr) { - DEBUG_D("Config(%p, %s) backup file found %s", this, configPath.c_str(), backupPath.c_str()); - fclose(backup); - remove(configPath.c_str()); - rename(backupPath.c_str(), configPath.c_str()); - } -} - -NativeByteBuffer *Config::readConfig() { - NativeByteBuffer *buffer = nullptr; - FILE *file = fopen(configPath.c_str(), "rb"); - if (file != nullptr) { - fseek(file, 0, SEEK_END); - long fileSize = ftell(file); - if (fseek(file, 0, SEEK_SET)) { - DEBUG_E("Config(%p, %s) failed fseek to begin, reopen it", this, configPath.c_str()); - fclose(file); - file = fopen(configPath.c_str(), "rb"); - } - uint32_t size = 0; - int bytesRead = fread(&size, sizeof(uint32_t), 1, file); - DEBUG_D("Config(%p, %s) load, size = %u, fileSize = %u", this, configPath.c_str(), size, (uint32_t) fileSize); - if (bytesRead > 0 && size > 0 && (int32_t) size < fileSize) { - buffer = BuffersStorage::getInstance().getFreeBuffer(size); - if (fread(buffer->bytes(), sizeof(uint8_t), size, file) != size) { - buffer->reuse(); - buffer = nullptr; - } - } - fclose(file); - } - return buffer; -} - -void Config::writeConfig(NativeByteBuffer *buffer) { - DEBUG_D("Config(%p, %s) start write config", this, configPath.c_str()); - FILE *file = fopen(configPath.c_str(), "rb"); - FILE *backup = fopen(backupPath.c_str(), "rb"); - bool error = false; - if (file != nullptr) { - if (backup == nullptr) { - fclose(file); - if (rename(configPath.c_str(), backupPath.c_str()) != 0) { - DEBUG_E("Config(%p) unable to rename file %s to backup file %s", this, configPath.c_str(), backupPath.c_str()); - error = true; - } - } else { - fclose(file); - fclose(backup); - remove(configPath.c_str()); - } - } - if (error) { - return; - } - file = fopen(configPath.c_str(), "wb"); - if (chmod(configPath.c_str(), 0660)) { - DEBUG_E("Config(%p, %s) chmod failed", this, configPath.c_str()); - } - if (file == nullptr) { - DEBUG_E("Config(%p, %s) unable to open file for writing", this, configPath.c_str()); - return; - } - uint32_t size = buffer->position(); - if (fwrite(&size, sizeof(uint32_t), 1, file) == 1) { - if (fwrite(buffer->bytes(), sizeof(uint8_t), size, file) != size) { - DEBUG_E("Config(%p, %s) failed to write config data to file", this, configPath.c_str()); - error = true; - } - } else { - DEBUG_E("Config(%p, %s) failed to write config size to file", this, configPath.c_str()); - error = true; - } - if (fflush(file)) { - DEBUG_E("Config(%p, %s) fflush failed", this, configPath.c_str()); - error = true; - } - int fd = fileno(file); - if (fd == -1) { - DEBUG_E("Config(%p, %s) fileno failed", this, configPath.c_str()); - error = true; - } else { - DEBUG_D("Config(%p, %s) fileno = %d", this, configPath.c_str(), fd); - } - if (fd != -1 && fsync(fd) == -1) { - DEBUG_E("Config(%p, %s) fsync failed", this, configPath.c_str()); - error = true; - } - if (fclose(file)) { - DEBUG_E("Config(%p, %s) fclose failed", this, configPath.c_str()); - error = true; - } - if (error) { - DEBUG_E("Config(%p, %s) failed to write config", this, configPath.c_str()); - if (remove(configPath.c_str())) { - DEBUG_E("Config(%p, %s) remove config failed", this, configPath.c_str()); - } - } else { - if (remove(backupPath.c_str())) { - DEBUG_E("Config(%p, %s) remove backup failed failed", this, configPath.c_str()); - } - } - if (!error) { - DEBUG_D("Config(%p, %s) config write ok", this, configPath.c_str()); - } -} diff --git a/TMessagesProj/jni/tgnet/Config.h b/TMessagesProj/jni/tgnet/Config.h deleted file mode 100644 index 783ec65f1..000000000 --- a/TMessagesProj/jni/tgnet/Config.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef CONFIG_H -#define CONFIG_H - -#include -#include "NativeByteBuffer.h" - -class Config { - -public: - Config(std::string fileName); - - NativeByteBuffer *readConfig(); - void writeConfig(NativeByteBuffer *buffer); - -private: - std::string configPath; - std::string backupPath; -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/Connection.cpp b/TMessagesProj/jni/tgnet/Connection.cpp deleted file mode 100644 index 9ea752b8d..000000000 --- a/TMessagesProj/jni/tgnet/Connection.cpp +++ /dev/null @@ -1,438 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include "Connection.h" -#include "ConnectionsManager.h" -#include "BuffersStorage.h" -#include "FileLog.h" -#include "Timer.h" -#include "Datacenter.h" -#include "NativeByteBuffer.h" - -static uint32_t lastConnectionToken = 1; - -Connection::Connection(Datacenter *datacenter, ConnectionType type) { - currentDatacenter = datacenter; - connectionType = type; - genereateNewSessionId(); - connectionState = TcpConnectionStageIdle; - reconnectTimer = new Timer([&] { - reconnectTimer->stop(); - connect(); - }); -} - -Connection::~Connection() { - if (reconnectTimer != nullptr) { - reconnectTimer->stop(); - delete reconnectTimer; - reconnectTimer = nullptr; - } -} - -void Connection::suspendConnection() { - reconnectTimer->stop(); - if (connectionState == TcpConnectionStageIdle || connectionState == TcpConnectionStageSuspended) { - return; - } - DEBUG_D("connection(%p, dc%u, type %d) suspend", this, currentDatacenter->getDatacenterId(), connectionType); - connectionState = TcpConnectionStageSuspended; - dropConnection(); - ConnectionsManager::getInstance().onConnectionClosed(this); - firstPacketSent = false; - if (restOfTheData != nullptr) { - restOfTheData->reuse(); - restOfTheData = nullptr; - } - lastPacketLength = 0; - connectionToken = 0; - wasConnected = false; -} - -void Connection::onReceivedData(NativeByteBuffer *buffer) { - AES_ctr128_encrypt(buffer->bytes(), buffer->bytes(), buffer->limit(), &decryptKey, decryptIv, decryptCount, &decryptNum); - - failedConnectionCount = 0; - - NativeByteBuffer *parseLaterBuffer = nullptr; - if (restOfTheData != nullptr) { - if (lastPacketLength == 0) { - if (restOfTheData->capacity() - restOfTheData->position() >= buffer->limit()) { - restOfTheData->limit(restOfTheData->position() + buffer->limit()); - restOfTheData->writeBytes(buffer); - buffer = restOfTheData; - } else { - NativeByteBuffer *newBuffer = BuffersStorage::getInstance().getFreeBuffer(restOfTheData->limit() + buffer->limit()); - restOfTheData->rewind(); - newBuffer->writeBytes(restOfTheData); - newBuffer->writeBytes(buffer); - buffer = newBuffer; - restOfTheData->reuse(); - restOfTheData = newBuffer; - } - } else { - uint32_t len; - if (lastPacketLength - restOfTheData->position() <= buffer->limit()) { - len = lastPacketLength - restOfTheData->position(); - } else { - len = buffer->limit(); - } - uint32_t oldLimit = buffer->limit(); - buffer->limit(len); - restOfTheData->writeBytes(buffer); - buffer->limit(oldLimit); - if (restOfTheData->position() == lastPacketLength) { - parseLaterBuffer = buffer->hasRemaining() ? buffer : nullptr; - buffer = restOfTheData; - } else { - return; - } - } - } - - buffer->rewind(); - - while (buffer->hasRemaining()) { - if (!hasSomeDataSinceLastConnect) { - currentDatacenter->storeCurrentAddressAndPortNum(); - isTryingNextPort = false; - if (connectionType == ConnectionTypePush) { - setTimeout(60 * 15); - } else { - setTimeout(25); - } - } - hasSomeDataSinceLastConnect = true; - - uint32_t currentPacketLength = 0; - uint32_t mark = buffer->position(); - uint8_t fByte = buffer->readByte(nullptr); - - if ((fByte & (1 << 7)) != 0) { - buffer->position(mark); - if (buffer->remaining() < 4) { - NativeByteBuffer *reuseLater = restOfTheData; - restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384); - restOfTheData->writeBytes(buffer); - restOfTheData->limit(restOfTheData->position()); - lastPacketLength = 0; - if (reuseLater != nullptr) { - reuseLater->reuse(); - } - break; - } - int32_t ackId = buffer->readBigInt32(nullptr) & (~(1 << 31)); - ConnectionsManager::getInstance().onConnectionQuickAckReceived(this, ackId); - continue; - } - - if (fByte != 0x7f) { - currentPacketLength = ((uint32_t) fByte) * 4; - } else { - buffer->position(mark); - if (buffer->remaining() < 4) { - if (restOfTheData == nullptr || (restOfTheData != nullptr && restOfTheData->position() != 0)) { - NativeByteBuffer *reuseLater = restOfTheData; - restOfTheData = BuffersStorage::getInstance().getFreeBuffer(16384); - restOfTheData->writeBytes(buffer); - restOfTheData->limit(restOfTheData->position()); - lastPacketLength = 0; - if (reuseLater != nullptr) { - reuseLater->reuse(); - } - } else { - restOfTheData->position(restOfTheData->limit()); - } - break; - } - currentPacketLength = ((uint32_t) buffer->readInt32(nullptr) >> 8) * 4; - } - - if (currentPacketLength % 4 != 0 || currentPacketLength > 2 * 1024 * 1024) { - DEBUG_E("connection(%p, dc%u, type %d) received invalid packet length", this, currentDatacenter->getDatacenterId(), connectionType); - reconnect(); - return; - } - - if (currentPacketLength < buffer->remaining()) { - DEBUG_E("connection(%p, dc%u, type %d) received message len %u but packet larger %u", this, currentDatacenter->getDatacenterId(), connectionType, currentPacketLength, buffer->remaining()); - } else if (currentPacketLength == buffer->remaining()) { - DEBUG_E("connection(%p, dc%u, type %d) received message len %u equal to packet size", this, currentDatacenter->getDatacenterId(), connectionType, currentPacketLength); - } else { - DEBUG_E("connection(%p, dc%u, type %d) received packet size less(%u) then message size(%u)", this, currentDatacenter->getDatacenterId(), connectionType, buffer->remaining(), currentPacketLength); - - NativeByteBuffer *reuseLater = nullptr; - uint32_t len = currentPacketLength + (fByte != 0x7f ? 1 : 4); - if (restOfTheData != nullptr && restOfTheData->capacity() < len) { - reuseLater = restOfTheData; - restOfTheData = nullptr; - } - if (restOfTheData == nullptr) { - buffer->position(mark); - restOfTheData = BuffersStorage::getInstance().getFreeBuffer(len); - restOfTheData->writeBytes(buffer); - } else { - restOfTheData->position(restOfTheData->limit()); - restOfTheData->limit(len); - } - lastPacketLength = len; - if (reuseLater != nullptr) { - reuseLater->reuse(); - } - return; - } - - uint32_t old = buffer->limit(); - buffer->limit(buffer->position() + currentPacketLength); - ConnectionsManager::getInstance().onConnectionDataReceived(this, buffer, currentPacketLength); - buffer->position(buffer->limit()); - buffer->limit(old); - - if (restOfTheData != nullptr) { - if ((lastPacketLength != 0 && restOfTheData->position() == lastPacketLength) || (lastPacketLength == 0 && !restOfTheData->hasRemaining())) { - restOfTheData->reuse(); - restOfTheData = nullptr; - } else { - DEBUG_E("compact occured"); - restOfTheData->compact(); - restOfTheData->limit(restOfTheData->position()); - restOfTheData->position(0); - } - } - - if (parseLaterBuffer != nullptr) { - buffer = parseLaterBuffer; - parseLaterBuffer = nullptr; - } - } -} - -void Connection::connect() { - if (!ConnectionsManager::getInstance().isNetworkAvailable()) { - ConnectionsManager::getInstance().onConnectionClosed(this); - return; - } - if ((connectionState == TcpConnectionStageConnected || connectionState == TcpConnectionStageConnecting)) { - return; - } - connectionState = TcpConnectionStageConnecting; - bool ipv6 = ConnectionsManager::getInstance().isIpv6Enabled(); - if (connectionType == ConnectionTypeDownload) { - currentAddressFlags = 2; - hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | (ipv6 ? 1 : 0)); - if (hostAddress.empty()) { - currentAddressFlags = 0; - hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | (ipv6 ? 1 : 0)); - } - if (hostAddress.empty() && ipv6) { - currentAddressFlags = 2; - hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); - if (hostAddress.empty()) { - currentAddressFlags = 0; - hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); - } - } - } else { - currentAddressFlags = 0; - hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags | (ipv6 ? 1 : 0)); - if (ipv6 && hostAddress.empty()) { - hostAddress = currentDatacenter->getCurrentAddress(currentAddressFlags); - } - } - hostPort = (uint16_t) currentDatacenter->getCurrentPort(currentAddressFlags); - - reconnectTimer->stop(); - - DEBUG_D("connection(%p, dc%u, type %d) connecting (%s:%hu)", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); - firstPacketSent = false; - if (restOfTheData != nullptr) { - restOfTheData->reuse(); - restOfTheData = nullptr; - } - lastPacketLength = 0; - wasConnected = false; - hasSomeDataSinceLastConnect = false; - openConnection(hostAddress, hostPort, ipv6); - if (connectionType == ConnectionTypePush) { - if (isTryingNextPort) { - setTimeout(20); - } else { - setTimeout(30); - } - } else { - if (isTryingNextPort) { - setTimeout(8); - } else { - if (connectionType == ConnectionTypeUpload) { - setTimeout(25); - } else { - setTimeout(15); - } - } - } -} - -void Connection::reconnect() { - suspendConnection(); - connectionState = TcpConnectionStageReconnecting; - connect(); -} - -void Connection::sendData(NativeByteBuffer *buff, bool reportAck) { - if (buff == nullptr) { - return; - } - buff->rewind(); - if (connectionState == TcpConnectionStageIdle || connectionState == TcpConnectionStageReconnecting || connectionState == TcpConnectionStageSuspended) { - connect(); - } - - if (isDisconnected()) { - buff->reuse(); - DEBUG_D("connection(%p, dc%u, type %d) disconnected, don't send data", this, currentDatacenter->getDatacenterId(), connectionType); - return; - } - - uint32_t bufferLen = 0; - uint32_t packetLength = buff->limit() / 4; - - if (packetLength < 0x7f) { - bufferLen++; - } else { - bufferLen += 4; - } - if (!firstPacketSent) { - bufferLen += 64; - } - - NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(bufferLen); - uint8_t *bytes = buffer->bytes(); - - if (!firstPacketSent) { - buffer->position(64); - static uint8_t temp[64]; - while (true) { - RAND_bytes(bytes, 64); - uint32_t val = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | (bytes[0]); - uint32_t val2 = (bytes[7] << 24) | (bytes[6] << 16) | (bytes[5] << 8) | (bytes[4]); - if (bytes[0] != 0xef && val != 0x44414548 && val != 0x54534f50 && val != 0x20544547 && val != 0x4954504f && val != 0xeeeeeeee && val2 != 0x00000000) { - bytes[56] = bytes[57] = bytes[58] = bytes[59] = 0xef; - break; - } - } - for (int a = 0; a < 48; a++) { - temp[a] = bytes[55 - a]; - } - - encryptNum = decryptNum = 0; - memset(encryptCount, 0, 16); - memset(decryptCount, 0, 16); - - if (AES_set_encrypt_key(bytes + 8, 256, &encryptKey) < 0) { - DEBUG_E("unable to set encryptKey"); - exit(1); - } - memcpy(encryptIv, bytes + 40, 16); - - if (AES_set_encrypt_key(temp, 256, &decryptKey) < 0) { - DEBUG_E("unable to set decryptKey"); - exit(1); - } - memcpy(decryptIv, temp + 32, 16); - - AES_ctr128_encrypt(bytes, temp, 64, &encryptKey, encryptIv, encryptCount, &encryptNum); - memcpy(bytes + 56, temp + 56, 8); - - firstPacketSent = true; - } - if (packetLength < 0x7f) { - if (reportAck) { - packetLength |= (1 << 7); - } - buffer->writeByte((uint8_t) packetLength); - bytes += (buffer->limit() - 1); - AES_ctr128_encrypt(bytes, bytes, 1, &encryptKey, encryptIv, encryptCount, &encryptNum); - } else { - packetLength = (packetLength << 8) + 0x7f; - if (reportAck) { - packetLength |= (1 << 7); - } - buffer->writeInt32(packetLength); - bytes += (buffer->limit() - 4); - AES_ctr128_encrypt(bytes, bytes, 4, &encryptKey, encryptIv, encryptCount, &encryptNum); - } - - buffer->rewind(); - writeBuffer(buffer); - buff->rewind(); - AES_ctr128_encrypt(buff->bytes(), buff->bytes(), buff->limit(), &encryptKey, encryptIv, encryptCount, &encryptNum); - writeBuffer(buff); -} - -void Connection::onDisconnected(int reason) { - reconnectTimer->stop(); - DEBUG_D("connection(%p, dc%u, type %d) disconnected with reason %d", this, currentDatacenter->getDatacenterId(), connectionType, reason); - bool switchToNextPort = wasConnected && !hasSomeDataSinceLastConnect && reason == 2; - firstPacketSent = false; - if (restOfTheData != nullptr) { - restOfTheData->reuse(); - restOfTheData = nullptr; - } - connectionToken = 0; - lastPacketLength = 0; - wasConnected = false; - if (connectionState != TcpConnectionStageSuspended && connectionState != TcpConnectionStageIdle) { - connectionState = TcpConnectionStageIdle; - } - ConnectionsManager::getInstance().onConnectionClosed(this); - - uint32_t datacenterId = currentDatacenter->getDatacenterId(); - if (connectionState == TcpConnectionStageIdle && connectionType == ConnectionTypeGeneric && (currentDatacenter->isHandshaking() || datacenterId == ConnectionsManager::getInstance().currentDatacenterId || datacenterId == ConnectionsManager::getInstance().movingToDatacenterId)) { - connectionState = TcpConnectionStageReconnecting; - failedConnectionCount++; - if (failedConnectionCount == 1) { - if (hasSomeDataSinceLastConnect) { - willRetryConnectCount = 5; - } else { - willRetryConnectCount = 1; - } - } - if (ConnectionsManager::getInstance().isNetworkAvailable()) { - isTryingNextPort = true; - if (failedConnectionCount > willRetryConnectCount || switchToNextPort) { - currentDatacenter->nextAddressOrPort(currentAddressFlags); - failedConnectionCount = 0; - } - } - DEBUG_D("connection(%p, dc%u, type %d) reconnect %s:%hu", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); - reconnectTimer->setTimeout(1000, false); - reconnectTimer->start(); - } -} - -void Connection::onConnected() { - connectionState = TcpConnectionStageConnected; - connectionToken = lastConnectionToken++; - wasConnected = true; - DEBUG_D("connection(%p, dc%u, type %d) connected to %s:%hu", this, currentDatacenter->getDatacenterId(), connectionType, hostAddress.c_str(), hostPort); - ConnectionsManager::getInstance().onConnectionConnected(this); -} - -Datacenter *Connection::getDatacenter() { - return currentDatacenter; -} - -ConnectionType Connection::getConnectionType() { - return connectionType; -} - -uint32_t Connection::getConnectionToken() { - return connectionToken; -} diff --git a/TMessagesProj/jni/tgnet/Connection.h b/TMessagesProj/jni/tgnet/Connection.h deleted file mode 100644 index 76da54f4f..000000000 --- a/TMessagesProj/jni/tgnet/Connection.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef CONNECTION_H -#define CONNECTION_H - -#include -#include -#include -#include -#include "ConnectionSession.h" -#include "ConnectionSocket.h" -#include "Defines.h" - -class Datacenter; -class Timer; -class ByteStream; - -class Connection : public ConnectionSession, public ConnectionSocket { - -public: - - Connection(Datacenter *datacenter, ConnectionType type); - ~Connection(); - - void connect(); - void suspendConnection(); - void sendData(NativeByteBuffer *buffer, bool reportAck); - uint32_t getConnectionToken(); - ConnectionType getConnectionType(); - Datacenter *getDatacenter(); - -protected: - - void onReceivedData(NativeByteBuffer *buffer) override; - void onDisconnected(int reason) override; - void onConnected() override; - void reconnect(); - -private: - - enum TcpConnectionState { - TcpConnectionStageIdle, - TcpConnectionStageConnecting, - TcpConnectionStageReconnecting, - TcpConnectionStageConnected, - TcpConnectionStageSuspended - }; - - TcpConnectionState connectionState = TcpConnectionStageIdle; - uint32_t connectionToken = 0; - std::string hostAddress; - uint16_t hostPort; - uint16_t failedConnectionCount; - Datacenter *currentDatacenter; - uint32_t currentAddressFlags; - ConnectionType connectionType; - bool firstPacketSent = false; - NativeByteBuffer *restOfTheData = nullptr; - uint32_t lastPacketLength = 0; - bool hasSomeDataSinceLastConnect = false; - bool isTryingNextPort = false; - bool wasConnected = false; - uint32_t willRetryConnectCount = 5; - Timer *reconnectTimer; - - AES_KEY encryptKey; - uint8_t encryptIv[16]; - uint32_t encryptNum; - uint8_t encryptCount[16]; - - AES_KEY decryptKey; - uint8_t decryptIv[16]; - uint32_t decryptNum; - uint8_t decryptCount[16]; - - friend class ConnectionsManager; -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/ConnectionSession.cpp b/TMessagesProj/jni/tgnet/ConnectionSession.cpp deleted file mode 100644 index 8a215e40f..000000000 --- a/TMessagesProj/jni/tgnet/ConnectionSession.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include "ConnectionSession.h" -#include "MTProtoScheme.h" -#include "ConnectionsManager.h" -#include "NativeByteBuffer.h" - -void ConnectionSession::recreateSession() { - processedMessageIds.clear(); - messagesIdsForConfirmation.clear(); - processedSessionChanges.clear(); - nextSeqNo = 0; - - genereateNewSessionId(); -} - -void ConnectionSession::genereateNewSessionId() { - int64_t newSessionId; - RAND_bytes((uint8_t *) &newSessionId, 8); -#if USE_DEBUG_SESSION - sessionId = (0xabcd000000000000L | (newSessionId & 0x0000ffffffffffffL)); -#else - sessionId = newSessionId; -#endif -} - -void ConnectionSession::setSessionId(int64_t id) { - sessionId = id; -} - -int64_t ConnectionSession::getSissionId() { - return sessionId; -} - -uint32_t ConnectionSession::generateMessageSeqNo(bool increment) { - uint32_t value = nextSeqNo; - if (increment) { - nextSeqNo++; - } - return value * 2 + (increment ? 1 : 0); -} - -bool ConnectionSession::isMessageIdProcessed(int64_t messageId) { - return std::find(processedMessageIds.begin(), processedMessageIds.end(), messageId) != processedMessageIds.end(); -} - -void ConnectionSession::addProcessedMessageId(int64_t messageId) { - if (processedMessageIds.size() > 300) { - processedMessageIds.erase(processedMessageIds.begin(), processedMessageIds.begin() + 100); - } - processedMessageIds.push_back(messageId); -} - -bool ConnectionSession::hasMessagesToConfirm() { - return !messagesIdsForConfirmation.empty(); -} - -void ConnectionSession::addMessageToConfirm(int64_t messageId) { - if (std::find(processedMessageIds.begin(), processedMessageIds.end(), messageId) != processedMessageIds.end()) { - return; - } - messagesIdsForConfirmation.push_back(messageId); -} - -NetworkMessage *ConnectionSession::generateConfirmationRequest() { - NetworkMessage *networkMessage = nullptr; - - if (!messagesIdsForConfirmation.empty()) { - TL_msgs_ack *msgAck = new TL_msgs_ack(); - msgAck->msg_ids.insert(msgAck->msg_ids.begin(), messagesIdsForConfirmation.begin(), messagesIdsForConfirmation.end()); - NativeByteBuffer *os = new NativeByteBuffer(true); - msgAck->serializeToStream(os); - networkMessage = new NetworkMessage(); - networkMessage->message = std::unique_ptr(new TL_message); - networkMessage->message->msg_id = ConnectionsManager::getInstance().generateMessageId(); - networkMessage->message->seqno = generateMessageSeqNo(false); - networkMessage->message->bytes = os->capacity(); - networkMessage->message->body = std::unique_ptr(msgAck); - messagesIdsForConfirmation.clear(); - } - - return networkMessage; -} - -bool ConnectionSession::isSessionProcessed(int64_t sessionId) { - return std::find(processedSessionChanges.begin(), processedSessionChanges.end(), sessionId) != processedSessionChanges.end(); -} - -void ConnectionSession::addProcessedSession(int64_t sessionId) { - processedSessionChanges.push_back(sessionId); -} diff --git a/TMessagesProj/jni/tgnet/ConnectionSession.h b/TMessagesProj/jni/tgnet/ConnectionSession.h deleted file mode 100644 index 380304a97..000000000 --- a/TMessagesProj/jni/tgnet/ConnectionSession.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef CONNECTIONSESSION_H -#define CONNECTIONSESSION_H - -#include -#include -#include "Defines.h" - -class ConnectionSession { - -public: - void recreateSession(); - void genereateNewSessionId(); - void setSessionId(int64_t id); - int64_t getSissionId(); - uint32_t generateMessageSeqNo(bool increment); - bool isMessageIdProcessed(int64_t messageId); - void addProcessedMessageId(int64_t messageId); - bool hasMessagesToConfirm(); - void addMessageToConfirm(int64_t messageId); - NetworkMessage *generateConfirmationRequest(); - bool isSessionProcessed(int64_t sessionId); - void addProcessedSession(int64_t sessionId); - -private: - int64_t sessionId; - uint32_t nextSeqNo = 0; - - std::vector processedMessageIds; - std::vector messagesIdsForConfirmation; - std::vector processedSessionChanges; -}; - - -#endif diff --git a/TMessagesProj/jni/tgnet/ConnectionSocket.cpp b/TMessagesProj/jni/tgnet/ConnectionSocket.cpp deleted file mode 100644 index 095ecd484..000000000 --- a/TMessagesProj/jni/tgnet/ConnectionSocket.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include -#include -#include -#include -#include -#include "ByteStream.h" -#include "ConnectionSocket.h" -#include "FileLog.h" -#include "Defines.h" -#include "ConnectionsManager.h" -#include "EventObject.h" -#include "Timer.h" -#include "NativeByteBuffer.h" - -#ifndef EPOLLRDHUP -#define EPOLLRDHUP 0x2000 -#endif - -ConnectionSocket::ConnectionSocket() { - outgoingByteStream = new ByteStream(); - lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis(); - eventObject = new EventObject(this, EventObjectTypeConnection); -} - -ConnectionSocket::~ConnectionSocket() { - if (outgoingByteStream != nullptr) { - delete outgoingByteStream; - outgoingByteStream = nullptr; - } - if (eventObject != nullptr) { - delete eventObject; - eventObject = nullptr; - } -} - -void ConnectionSocket::openConnection(std::string address, uint16_t port, bool ipv6) { - int epolFd = ConnectionsManager::getInstance().epolFd; - - if ((socketFd = socket(ipv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0)) < 0) { - DEBUG_E("connection(%p) can't create socket", this); - closeSocket(1); - return; - } - - memset(&socketAddress, 0, sizeof(sockaddr_in)); - memset(&socketAddress6, 0, sizeof(sockaddr_in6)); - - if (ipv6) { - socketAddress6.sin6_family = AF_INET6; - socketAddress6.sin6_port = htons(port); - if (inet_pton(AF_INET6, address.c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) { - DEBUG_E("connection(%p) bad ipv6 %s", this, address.c_str()); - closeSocket(1); - return; - } - } else { - socketAddress.sin_family = AF_INET; - socketAddress.sin_port = htons(port); - if (inet_pton(AF_INET, address.c_str(), &socketAddress.sin_addr.s_addr) != 1) { - DEBUG_E("connection(%p) bad ipv4 %s", this, address.c_str()); - closeSocket(1); - return; - } - } - - int yes = 1; - if (setsockopt(socketFd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int))) { - DEBUG_E("connection(%p) set TCP_NODELAY failed", this); - } - - if (fcntl(socketFd, F_SETFL, O_NONBLOCK) == -1) { - DEBUG_E("connection(%p) set O_NONBLOCK failed", this); - closeSocket(1); - return; - } - - if (connect(socketFd, (ipv6 ? (sockaddr *) &socketAddress6 : (sockaddr *) &socketAddress), (socklen_t) (ipv6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) == -1 && errno != EINPROGRESS) { - closeSocket(1); - } else { - eventMask.events = EPOLLOUT | EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; - eventMask.data.ptr = eventObject; - if (epoll_ctl(epolFd, EPOLL_CTL_ADD, socketFd, &eventMask) != 0) { - DEBUG_E("connection(%p) epoll_ctl, adding socket failed", this); - closeSocket(1); - } - } -} - -bool ConnectionSocket::checkSocketError() { - if (socketFd < 0) { - return true; - } - int ret; - int code; - socklen_t len = sizeof(int); - ret = getsockopt(socketFd, SOL_SOCKET, SO_ERROR, &code, &len); - return (ret || code) != 0; -} - -void ConnectionSocket::closeSocket(int reason) { - lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis(); - ConnectionsManager::getInstance().detachConnection(this); - if (socketFd >= 0) { - epoll_ctl(ConnectionsManager::getInstance().epolFd, EPOLL_CTL_DEL, socketFd, NULL); - if (close(socketFd) != 0) { - DEBUG_E("connection(%p) unable to close socket", this); - } - socketFd = -1; - } - onConnectedSent = false; - outgoingByteStream->clean(); - onDisconnected(reason); -} - -void ConnectionSocket::onEvent(uint32_t events) { - if (events & EPOLLIN) { - if (checkSocketError()) { - closeSocket(1); - return; - } else { - ssize_t readCount; - NativeByteBuffer *buffer = ConnectionsManager::getInstance().networkBuffer; - while (true) { - buffer->rewind(); - readCount = recv(socketFd, buffer->bytes(), READ_BUFFER_SIZE, 0); - if (readCount < 0) { - closeSocket(1); - DEBUG_E("connection(%p) recv failed", this); - return; - } - if (readCount > 0) { - buffer->limit((uint32_t) readCount); - lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis(); - onReceivedData(buffer); - } - if (readCount != READ_BUFFER_SIZE) { - break; - } - } - } - } - if (events & EPOLLOUT) { - if (checkSocketError() != 0) { - closeSocket(1); - return; - } else { - if (!onConnectedSent) { - ConnectionsManager::getInstance().attachConnection(this); - lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis(); - onConnected(); - onConnectedSent = true; - } - NativeByteBuffer *buffer = ConnectionsManager::getInstance().networkBuffer; - buffer->clear(); - outgoingByteStream->get(buffer); - buffer->flip(); - - uint32_t remaining = buffer->remaining(); - if (remaining) { - ssize_t sentLength; - if ((sentLength = send(socketFd, buffer->bytes(), remaining, 0)) < 0) { - DEBUG_E("connection(%p) send failed", this); - closeSocket(1); - return; - } else { - outgoingByteStream->discard((uint32_t) sentLength); - adjustWriteOp(); - } - } - } - } - if ((events & EPOLLRDHUP) || (events & EPOLLHUP)) { - closeSocket(1); - return; - } - if (events & EPOLLERR) { - DEBUG_E("connection(%p) epoll error", this); - return; - } -} - -void ConnectionSocket::writeBuffer(NativeByteBuffer *buffer) { - outgoingByteStream->append(buffer); - adjustWriteOp(); -} - -void ConnectionSocket::adjustWriteOp() { - eventMask.events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; - if (outgoingByteStream->hasData()) { - eventMask.events |= EPOLLOUT; - } - eventMask.data.ptr = eventObject; - if (epoll_ctl(ConnectionsManager::getInstance().epolFd, EPOLL_CTL_MOD, socketFd, &eventMask) != 0) { - DEBUG_E("connection(%p) epoll_ctl, modify socket failed", this); - closeSocket(1); - } -} - -void ConnectionSocket::setTimeout(time_t time) { - timeout = time; - lastEventTime = ConnectionsManager::getInstance().getCurrentTimeMillis(); -} - -void ConnectionSocket::checkTimeout(int64_t now) { - if (timeout != 0 && (now - lastEventTime) > (int64_t) timeout * 1000) { - closeSocket(2); - } -} - -bool ConnectionSocket::isDisconnected() { - return socketFd < 0; -} - -void ConnectionSocket::dropConnection() { - closeSocket(0); -} diff --git a/TMessagesProj/jni/tgnet/ConnectionSocket.h b/TMessagesProj/jni/tgnet/ConnectionSocket.h deleted file mode 100644 index ca452faee..000000000 --- a/TMessagesProj/jni/tgnet/ConnectionSocket.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef CONNECTIONSOCKET_H -#define CONNECTIONSOCKET_H - -#include -#include -#include - -class NativeByteBuffer; -class ConnectionsManager; -class ByteStream; -class EventObject; - -class ConnectionSocket { - -public: - ConnectionSocket(); - virtual ~ConnectionSocket(); - - void writeBuffer(NativeByteBuffer *buffer); - void openConnection(std::string address, uint16_t port, bool ipv6); - void setTimeout(time_t timeout); - bool isDisconnected(); - void dropConnection(); - -protected: - void onEvent(uint32_t events); - void checkTimeout(int64_t now); - virtual void onReceivedData(NativeByteBuffer *buffer) = 0; - virtual void onDisconnected(int reason) = 0; - virtual void onConnected() = 0; - -private: - ByteStream *outgoingByteStream = nullptr; - struct epoll_event eventMask; - struct sockaddr_in socketAddress; - struct sockaddr_in6 socketAddress6; - int socketFd = -1; - time_t timeout = 15; - bool onConnectedSent = false; - int64_t lastEventTime = 0; - EventObject *eventObject; - - bool checkSocketError(); - void closeSocket(int reason); - void adjustWriteOp(); - - friend class EventObject; - friend class ConnectionsManager; -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/ConnectionsManager.cpp b/TMessagesProj/jni/tgnet/ConnectionsManager.cpp deleted file mode 100644 index 982ba2497..000000000 --- a/TMessagesProj/jni/tgnet/ConnectionsManager.cpp +++ /dev/null @@ -1,2538 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ConnectionsManager.h" -#include "FileLog.h" -#include "EventObject.h" -#include "MTProtoScheme.h" -#include "NativeByteBuffer.h" -#include "Connection.h" -#include "Datacenter.h" -#include "Request.h" -#include "BuffersStorage.h" -#include "ByteArray.h" -#include "Config.h" - -#ifdef ANDROID -#include -JavaVM *javaVm = nullptr; -JNIEnv *jniEnv = nullptr; -jclass jclass_ByteBuffer = nullptr; -jmethodID jclass_ByteBuffer_allocateDirect = 0; -#endif - -static bool done = false; - -ConnectionsManager::ConnectionsManager() { - if ((epolFd = epoll_create(128)) == -1) { - DEBUG_E("unable to create epoll instance"); - exit(1); - } - int flags; - if ((flags = fcntl(epolFd, F_GETFD, NULL)) < 0) { - DEBUG_W("fcntl(%d, F_GETFD)", epolFd); - } - if (!(flags & FD_CLOEXEC)) { - if (fcntl(epolFd, F_SETFD, flags | FD_CLOEXEC) == -1) { - DEBUG_W("fcntl(%d, F_SETFD)", epolFd); - } - } - - if ((epollEvents = new epoll_event[128]) == nullptr) { - DEBUG_E("unable to allocate epoll events"); - exit(1); - } - - pipeFd = new int[2]; - if (pipe(pipeFd) != 0) { - DEBUG_E("unable to create pipe"); - exit(1); - } - - flags = fcntl(pipeFd[0], F_GETFL); - if (flags == -1) { - DEBUG_E("fcntl get pipefds[0] failed"); - exit(1); - } - if (fcntl(pipeFd[0], F_SETFL, flags | O_NONBLOCK) == -1) { - DEBUG_E("fcntl set pipefds[0] failed"); - exit(1); - } - - flags = fcntl(pipeFd[1], F_GETFL); - if (flags == -1) { - DEBUG_E("fcntl get pipefds[1] failed"); - exit(1); - } - if (fcntl(pipeFd[1], F_SETFL, flags | O_NONBLOCK) == -1) { - DEBUG_E("fcntl set pipefds[1] failed"); - exit(1); - } - - EventObject *eventObject = new EventObject(pipeFd, EventObjectPipe); - - epoll_event eventMask = {}; - eventMask.events = EPOLLIN; - eventMask.data.ptr = eventObject; - if (epoll_ctl(epolFd, EPOLL_CTL_ADD, pipeFd[0], &eventMask) != 0) { - DEBUG_E("can't add pipe to epoll"); - exit(1); - } - - networkBuffer = new NativeByteBuffer((uint32_t) READ_BUFFER_SIZE); - if (networkBuffer == nullptr) { - DEBUG_E("unable to allocate read buffer"); - exit(1); - } - - pthread_mutex_init(&mutex, NULL); -} - -ConnectionsManager::~ConnectionsManager() { - if (epolFd != 0) { - close(epolFd); - epolFd = 0; - } - pthread_mutex_destroy(&mutex); -} - -ConnectionsManager& ConnectionsManager::getInstance() { - static ConnectionsManager instance; - return instance; -} - -int ConnectionsManager::callEvents(int64_t now) { - if (!events.empty()) { - for (std::list::iterator iter = events.begin(); iter != events.end();) { - EventObject *eventObject = (*iter); - if (eventObject->time <= now) { - iter = events.erase(iter); - eventObject->onEvent(0); - } else { - int diff = (int) (eventObject->time - now); - return diff > 1000 ? 1000 : diff; - } - } - } - if (!networkPaused) { - return 1000; - } - int32_t timeToPushPing = (sendingPushPing ? 30000 : 60000 * 3) - abs(now - lastPushPingTime); - if (timeToPushPing <= 0) { - return 1000; - } - DEBUG_D("schedule next epoll wakeup in %d ms", timeToPushPing); - - return timeToPushPing; -} - -void ConnectionsManager::checkPendingTasks() { - while (true) { - std::function task; - pthread_mutex_lock(&mutex); - if (pendingTasks.empty()) { - pthread_mutex_unlock(&mutex); - return; - } - task = pendingTasks.front(); - pendingTasks.pop(); - pthread_mutex_unlock(&mutex); - task(); - } -} - -void ConnectionsManager::select() { - checkPendingTasks(); - int eventsCount = epoll_wait(epolFd, epollEvents, 128, callEvents(getCurrentTimeMillis())); - checkPendingTasks(); - int64_t now = getCurrentTimeMillis(); - callEvents(now); - for (int32_t a = 0; a < eventsCount; a++) { - EventObject *eventObject = (EventObject *) epollEvents[a].data.ptr; - eventObject->onEvent(epollEvents[a].events); - } - size_t count = activeConnections.size(); - for (uint32_t a = 0; a < count; a++) { - activeConnections[a]->checkTimeout(now); - } - - Datacenter *datacenter = getDatacenterWithId(currentDatacenterId); - if (pushConnectionEnabled) { - if ((sendingPushPing && abs(now - lastPushPingTime) >= 30000) || abs(now - lastPushPingTime) >= 60000 * 3 + 10000) { - lastPushPingTime = 0; - sendingPushPing = false; - if (datacenter != nullptr) { - Connection *connection = datacenter->getPushConnection(false); - if (connection != nullptr) { - connection->suspendConnection(); - } - } - DEBUG_D("push ping timeout"); - } - if (abs(now - lastPushPingTime) >= 60000 * 3) { - DEBUG_D("time for push ping"); - lastPushPingTime = now; - if (datacenter != nullptr) { - sendPing(datacenter, true); - } - } - } - - if (lastPauseTime != 0 && abs(now - lastPauseTime) >= nextSleepTimeout) { - bool dontSleep = !requestingSaltsForDc.empty(); - if (!dontSleep) { - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) { - dontSleep = true; - break; - } - } - } - if (!dontSleep) { - for (requestsIter iter = requestsQueue.begin(); iter != requestsQueue.end(); iter++) { - Request *request = iter->get(); - if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) { - dontSleep = true; - break; - } - } - } - if (!dontSleep) { - if (!networkPaused) { - DEBUG_D("pausing network and timers by sleep time = %d", nextSleepTimeout); - for (std::map::iterator iter = datacenters.begin(); iter != datacenters.end(); iter++) { - iter->second->suspendConnections(); - } - } - networkPaused = true; - return; - } else { - lastPauseTime = now; - DEBUG_D("don't sleep because of salt, upload or download request"); - } - } - if (networkPaused) { - networkPaused = false; - DEBUG_D("resume network and timers"); - } - - if (delegate != nullptr) { - delegate->onUpdate(); - } - if (datacenter != nullptr) { - if (datacenter->hasAuthKey()) { - if (abs(now - lastPingTime) >= 19000) { - lastPingTime = now; - sendPing(datacenter, false); - } - if (abs((int32_t) (now / 1000) - lastDcUpdateTime) >= DC_UPDATE_TIME) { - updateDcSettings(0); - } - processRequestQueue(0, 0); - } else if (!datacenter->isHandshaking()) { - datacenter->beginHandshake(true); - } - } -} - -void ConnectionsManager::scheduleTask(std::function task) { - pthread_mutex_lock(&mutex); - pendingTasks.push(task); - pthread_mutex_unlock(&mutex); - wakeup(); -} - -void ConnectionsManager::scheduleEvent(EventObject *eventObject, uint32_t time) { - eventObject->time = getCurrentTimeMillis() + time; - std::list::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) { - for (std::list::iterator iter = events.begin(); iter != events.end(); iter++) { - if (*iter == eventObject) { - events.erase(iter); - break; - } - } -} - -void ConnectionsManager::wakeup() { - char ch = 'x'; - write(pipeFd[1], &ch, 1); -} - -void *ConnectionsManager::ThreadProc(void *data) { - DEBUG_D("network thread started"); -#ifdef ANDROID - javaVm->AttachCurrentThread(&jniEnv, NULL); -#endif - ConnectionsManager *networkManager = (ConnectionsManager *) (data); - if (networkManager->currentUserId != 0 && networkManager->pushConnectionEnabled) { - 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) { - config = new Config("tgnet.dat"); - } - NativeByteBuffer *buffer = config->readConfig(); - if (buffer != nullptr) { - uint32_t version = buffer->readUint32(nullptr); - DEBUG_D("config version = %u", version); - if (version <= configVersion) { - testBackend = buffer->readBool(nullptr); - 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); - } - - DEBUG_D("current dc id = %u, time difference = %d, registered for push = %d", currentDatacenterId, timeDifference, (int32_t) registeredForInternalPush); - - 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++) { - Datacenter *datacenter = new Datacenter(buffer); - datacenters[datacenter->getDatacenterId()] = datacenter; - DEBUG_D("datacenter(%p) %u loaded (hasAuthKey = %d)", datacenter, datacenter->getDatacenterId(), (int) datacenter->hasAuthKey()); - } - } - } - buffer->reuse(); - } - - if (currentDatacenterId != 0 && currentUserId) { - Datacenter *datacenter = getDatacenterWithId(currentDatacenterId); - if (datacenter == nullptr || !datacenter->hasAuthKey()) { - if (datacenter != nullptr) { - DEBUG_D("reset authorization because of dc %p", datacenter); - } - currentDatacenterId = 0; - datacenters.clear(); - scheduleTask([&] { - if (delegate != nullptr) { - delegate->onLogout(); - } - }); - } - } - - initDatacenters(); - - if ((datacenters.size() != 0 && currentDatacenterId == 0) || pushSessionId == 0) { - if (pushSessionId == 0) { - RAND_bytes((uint8_t *) &pushSessionId, 8); - } - if (currentDatacenterId == 0) { - currentDatacenterId = 2; - } - saveConfig(); - } - movingToDatacenterId = DEFAULT_DATACENTER_ID; -} - -void ConnectionsManager::saveConfig() { - if (config == nullptr) { - config = new Config("tgnet.dat"); - } - NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(32 * 1024); - buffer->writeInt32(configVersion); - buffer->writeBool(testBackend); - 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); - - std::vector sessions; - currentDatacenter->getSessions(sessions); - - uint32_t count = (uint32_t) sessions.size(); - buffer->writeInt32(count); - for (uint32_t a = 0; a < count; a++) { - buffer->writeInt64(sessions[a]); - } - count = (uint32_t) datacenters.size(); - buffer->writeInt32(count); - for (std::map::iterator iter = datacenters.begin(); iter != datacenters.end(); iter++) { - iter->second->serializeToStream(buffer); - } - } - 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) { - DEBUG_E("can't decompress data"); - 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 { - DEBUG_E("can't decompress data"); - 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) { - DEBUG_E("%s: deflateInit2() failed with error %i", __PRETTY_FUNCTION__, retCode); - 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)) { - DEBUG_E("%s: deflate() failed with error %i", __PRETTY_FUNCTION__, retCode); - 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; -} - -int32_t ConnectionsManager::getCurrentTime() { - return (int32_t) (getCurrentTimeMillis() / 1000) + timeDifference; -} - -int32_t ConnectionsManager::getTimeDifference() { - return timeDifference; -} - -int64_t ConnectionsManager::generateMessageId() { - int64_t messageId = (int64_t) ((((double) getCurrentTimeMillis() + ((double) timeDifference) * 1000) * 4294967296.0) / 1000.0); - if (messageId <= lastOutgoingMessageId) { - messageId = lastOutgoingMessageId + 1; - } - while (messageId % 4 != 0) { - messageId++; - } - lastOutgoingMessageId = messageId; - return messageId; -} - -bool ConnectionsManager::isNetworkAvailable() { - return networkAvailable; -} - -void ConnectionsManager::cleanUp() { - scheduleTask([&] { - for (requestsIter iter = requestsQueue.begin(); iter != requestsQueue.end();) { - Request *request = iter->get(); - if (request->requestFlags & RequestFlagWithoutLogin) { - iter++; - continue; - } - if (request->onCompleteRequestCallback != nullptr) { - TL_error *error = new TL_error(); - error->code = -1000; - error->text = ""; - request->onComplete(nullptr, error); - delete error; - } - iter = requestsQueue.erase(iter); - } - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end();) { - Request *request = iter->get(); - if (request->requestFlags & RequestFlagWithoutLogin) { - iter++; - continue; - } - if (request->onCompleteRequestCallback != nullptr) { - TL_error *error = new TL_error(); - error->code = -1000; - error->text = ""; - request->onComplete(nullptr, error); - delete error; - } - iter = runningRequests.erase(iter); - } - quickAckIdToRequestIds.clear(); - - for (std::map::iterator iter = datacenters.begin(); iter != datacenters.end(); iter++) { - iter->second->recreateSessions(); - iter->second->authorized = false; - } - sessionsToDestroy.clear(); - currentUserId = 0; - registeredForInternalPush = false; - saveConfig(); - }); -} - -void ConnectionsManager::onConnectionClosed(Connection *connection) { - Datacenter *datacenter = connection->getDatacenter(); - if (connection->getConnectionType() == ConnectionTypeGeneric) { - if (datacenter->isHandshaking()) { - datacenter->onHandshakeConnectionClosed(connection); - } - if (datacenter->getDatacenterId() == currentDatacenterId) { - if (networkAvailable) { - if (connectionState != ConnectionStateConnecting) { - connectionState = ConnectionStateConnecting; - if (delegate != nullptr) { - delegate->onConnectionStateChanged(connectionState); - } - } - } else { - if (connectionState != ConnectionStateWaitingForNetwork) { - connectionState = ConnectionStateWaitingForNetwork; - if (delegate != nullptr) { - delegate->onConnectionStateChanged(connectionState); - } - } - } - } - } else if (connection->getConnectionType() == ConnectionTypePush) { - DEBUG_D("connection(%p) push connection closed", connection); - sendingPushPing = false; - lastPushPingTime = getCurrentTimeMillis() - 60000 * 3 + 4000; - } -} - -void ConnectionsManager::onConnectionConnected(Connection *connection) { - Datacenter *datacenter = connection->getDatacenter(); - if (connection->getConnectionType() == ConnectionTypeGeneric) { - if (datacenter->isHandshaking()) { - datacenter->onHandshakeConnectionConnected(connection); - return; - } - } - - if (datacenter->hasAuthKey()) { - if (connection->getConnectionType() == ConnectionTypePush) { - sendingPushPing = false; - lastPushPingTime = getCurrentTimeMillis(); - sendPing(datacenter, true); - } else { - if (networkPaused && lastPauseTime != 0) { - lastPauseTime = getCurrentTimeMillis(); - } - processRequestQueue(connection->getConnectionType(), datacenter->getDatacenterId()); - } - } -} - -void ConnectionsManager::onConnectionQuickAckReceived(Connection *connection, int32_t ack) { - std::map>::iterator iter = quickAckIdToRequestIds.find(ack); - if (iter == quickAckIdToRequestIds.end()) { - return; - } - for (requestsIter iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) { - Request *request = iter2->get(); - 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; - if (length == 4) { - int32_t code = data->readInt32(&error); - DEBUG_E("mtproto error = %d", code); - connection->reconnect(); - 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) { - delegate->onConnectionStateChanged(connectionState); - } - } - - 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; - } - - if (messageLength != data->remaining()) { - DEBUG_E("connection(%p) received incorrect message length", connection); - connection->reconnect(); - return; - } - TLObject *request; - if (datacenter->isHandshaking()) { - request = datacenter->getCurrentHandshakeRequest(); - } else { - request = getRequestWithMessageId(messageId); - } - - TLObject *object = TLdeserialize(request, messageLength, data); - - if (object != nullptr) { - if (datacenter->isHandshaking()) { - datacenter->processHandshakeResponse(object, messageId); - } else { - processServerResponse(object, messageId, 0, 0, connection, 0, 0); - connection->addProcessedMessageId(messageId); - } - delete object; - } - } else { - if (length < 24 + 32 || !datacenter->decryptServerResponse(keyId, data->bytes() + mark + 8, data->bytes() + mark + 24, length - 24)) { - DEBUG_E("connection(%p) unable to decrypt server response", connection); - datacenter->switchTo443Port(); - connection->suspendConnection(); - connection->connect(); - return; - } - data->position(mark + 24); - - int64_t messageServerSalt = data->readInt64(&error); - int64_t messageSessionId = data->readInt64(&error); - - if (messageSessionId != connection->getSissionId()) { - DEBUG_E("connection(%p) received invalid message session id (0x%llx instead of 0x%llx)", connection, (uint64_t) messageSessionId, (uint64_t) connection->getSissionId()); - return; - } - - bool doNotProcess = false; - - int64_t messageId = data->readInt64(&error); - int32_t messageSeqNo = data->readInt32(&error); - uint32_t messageLength = data->readUint32(&error); - - if (connection->isMessageIdProcessed(messageId)) { - doNotProcess = true; - } - - if (messageSeqNo % 2 != 0) { - connection->addMessageToConfirm(messageId); - } - - if (!doNotProcess) { - TLObject *object = TLdeserialize(nullptr, messageLength, data); - if (object != nullptr) { - DEBUG_D("connection(%p, dc%u, type %d) received object %s", connection, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name()); - processServerResponse(object, messageId, messageSeqNo, messageServerSalt, connection, 0, 0); - connection->addProcessedMessageId(messageId); - delete object; - if (connection->getConnectionType() == ConnectionTypePush) { - std::vector> messages; - sendMessagesToConnectionWithConfirmation(messages, connection, false); - } - } else { - if (delegate != nullptr) { - delegate->onUnparsedMessageReceived(0, data, connection->getConnectionType()); - } - } - } else { - std::vector> messages; - sendMessagesToConnectionWithConfirmation(messages, connection, false); - } - } -} - -TLObject *ConnectionsManager::getRequestWithMessageId(int64_t messageId) { - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - 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; - } - - TLObject *object = TLClassStore::TLdeserialize(data, bytes, constructor, error); - - if (error) { - if (object != nullptr) { - delete object; - } - data->position(position); - return nullptr; - } - - if (object == nullptr) { - if (request != nullptr) { - TL_api_request *apiRequest = dynamic_cast(request); - if (apiRequest != nullptr) { - object = apiRequest->deserializeResponse(data, bytes, error); - DEBUG_D("api request constructor 0x%x, don't parse", constructor); - } else { - object = request->deserializeResponse(data, constructor, error); - if (object != nullptr && error) { - delete object; - object = nullptr; - } - } - } else { - DEBUG_D("not found request to parse constructor 0x%x", constructor); - } - } - 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); - - Datacenter *datacenter = connection->getDatacenter(); - - if (typeInfo == typeid(TL_new_session_created)) { - TL_new_session_created *response = (TL_new_session_created *) message; - - if (!connection->isSessionProcessed(response->unique_id)) { - DEBUG_D("connection(%p, dc%u, type %d) new session created (first message id: 0x%llx, server salt: 0x%llx, unique id: 0x%llx)", connection, datacenter->getDatacenterId(), connection->getConnectionType(), (uint64_t) response->first_msg_id, (uint64_t) response->server_salt, (uint64_t) response->unique_id); - - std::unique_ptr salt = std::unique_ptr(new TL_future_salt()); - salt->valid_until = salt->valid_since = getCurrentTime(); - salt->valid_until += 30 * 60; - salt->salt = response->server_salt; - datacenter->addServerSalt(salt); - - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId); - if (request->messageId < response->first_msg_id && request->connectionType & connection->getConnectionType() && requestDatacenter != nullptr && requestDatacenter->getDatacenterId() == datacenter->getDatacenterId()) { - DEBUG_D("clear request %p - %s", request->rawRequest, typeid(*request->rawRequest).name()); - request->clear(true); - } - } - - saveConfig(); - - if (datacenter->getDatacenterId() == currentDatacenterId && currentUserId) { - if (connection->getConnectionType() == ConnectionTypePush) { - registerForInternalPushUpdates(); - } else if (connection->getConnectionType() == ConnectionTypeGeneric) { - if (delegate != nullptr) { - delegate->onSessionCreated(); - } - } - } - connection->addProcessedSession(response->unique_id); - } - } else if (typeInfo == typeid(TL_msg_container)) { - TL_msg_container *response = (TL_msg_container *) message; - size_t count = response->messages.size(); - 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); - } - if (connection->isMessageIdProcessed(innerMessageId)) { - continue; - } - if (innerMessage->unparsedBody != nullptr) { - if (delegate != nullptr) { - delegate->onUnparsedMessageReceived(0, innerMessage->unparsedBody.get(), connection->getConnectionType()); - } - } else { - 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(); - } - DEBUG_D("connection(%p, dc%u, type %d) received push ping", connection, datacenter->getDatacenterId(), connection->getConnectionType()); - sendingPushPing = false; - } else { - TL_pong *response = (TL_pong *) message; - if (response->ping_id == lastPingId) { - int64_t currentTime = getCurrentTimeMillis(); - int32_t diff = (int32_t) (currentTime / 1000) - pingTime; - - if (abs(diff) < 10) { - currentPingTime = (diff + currentPingTime) / 2; - if (messageId != 0) { - int64_t timeMessage = (int64_t) (messageId / 4294967296.0 * 1000); - timeDifference = (int32_t) ((timeMessage - currentTime) / 1000 - currentPingTime / 2); - } - } - } - } - } else if (typeInfo == typeid(TL_future_salts)) { - TL_future_salts *response = (TL_future_salts *) message; - int64_t requestMid = response->req_msg_id; - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - if (request->respondsToMessageId(requestMid)) { - request->onComplete(response, nullptr); - request->completed = true; - runningRequests.erase(iter); - break; - } - } - } else if (dynamic_cast(message)) { - DestroySessionRes *response = (DestroySessionRes *) message; - DEBUG_D("destroyed session 0x%llx (%s)", (uint64_t) response->session_id, typeInfo == typeid(TL_destroy_session_ok) ? "ok" : "not found"); - } else if (typeInfo == typeid(TL_rpc_result)) { - TL_rpc_result *response = (TL_rpc_result *) message; - int64_t resultMid = response->req_msg_id; - - bool hasResult = response->result.get() != nullptr; - bool ignoreResult = false; - if (hasResult) { - TLObject *object = response->result.get(); - DEBUG_D("connection(%p, dc%u, type %d) received rpc_result with %s", connection, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name()); - } - RpcError *error = hasResult ? dynamic_cast(response->result.get()) : nullptr; - if (error != nullptr) { - DEBUG_E("connection(%p, dc%u, type %d) rpc error %d: %s", connection, datacenter->getDatacenterId(), connection->getConnectionType(), error->error_code, error->error_message.c_str()); - if (error->error_code == 303) { - uint32_t migrateToDatacenterId = DEFAULT_DATACENTER_ID; - - static std::vector migrateErrors; - if (migrateErrors.empty()) { - migrateErrors.push_back("NETWORK_MIGRATE_"); - migrateErrors.push_back("PHONE_MIGRATE_"); - migrateErrors.push_back("USER_MIGRATE_"); - } - - 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()); - uint32_t val = (uint32_t) atoi(num.c_str()); - migrateToDatacenterId = val; - } - } - - if (migrateToDatacenterId != DEFAULT_DATACENTER_ID) { - ignoreResult = true; - moveToDatacenter(migrateToDatacenterId); - } - } - } - - uint32_t retryRequestsFromDatacenter = DEFAULT_DATACENTER_ID - 1; - uint32_t retryRequestsConnections = 0; - - if (!ignoreResult) { - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - if (request->respondsToMessageId(resultMid)) { - DEBUG_D("got response for request %p - %s", request->rawRequest, typeid(*request->rawRequest).name()); - 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)) { - TL_gzip_packed *innerResponse = (TL_gzip_packed *) result; - 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(object); - } else { - response->result = std::unique_ptr(nullptr); - } - } - - hasResult = response->result.get() != nullptr; - error = hasResult ? dynamic_cast(response->result.get()) : nullptr; - TL_error *error2 = hasResult ? dynamic_cast(response->result.get()) : nullptr; - if (error != nullptr) { - allowInitConnection = false; - DEBUG_E("request %p rpc error %d: %s", request, error->error_code, error->error_message.c_str()); - - if ((request->requestFlags & RequestFlagFailOnServerErrors) == 0) { - if (error->error_code == 500 || error->error_code < 0) { - discardResponse = true; - request->minStartTime = request->startTime + (request->serverFailureCount > 10 ? 10 : request->serverFailureCount); - request->serverFailureCount++; - } else if (error->error_code == 420) { - int32_t waitTime = 2; - static std::string floodWait = "FLOOD_WAIT_"; - if (error->error_message.find(floodWait) != std::string::npos) { - 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; - } - } - - discardResponse = true; - request->failedByFloodWait = waitTime; - request->startTime = 0; - request->minStartTime = (int32_t) (getCurrentTimeMillis() / 1000 + waitTime); - } else if (error->error_code == 400) { - static std::string waitFailed = "MSG_WAIT_FAILED"; - if (error->error_message.find(waitFailed) != std::string::npos) { - discardResponse = true; - request->minStartTime = (int32_t) (getCurrentTimeMillis() / 1000 + 1); - request->startTime = 0; - } - } - } - if (!discardResponse) { - 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; - DEBUG_E("rawRequest is null"); - implicitError = new TL_error(); - implicitError->code = -1000; - implicitError->text = ""; - } - } - - if (!discardResponse) { - if (implicitError != nullptr || error2 != nullptr) { - isError = true; - request->onComplete(nullptr, implicitError != nullptr ? implicitError : error2); - if (error2 != nullptr) { - delete error2; - } - } else { - request->onComplete(response->result.get(), nullptr); - } - } - - if (implicitError != nullptr && 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; - if (delegate != nullptr) { - delegate->onLogout(); - } - cleanUp(); - } - } else { - datacenter->authorized = false; - saveConfig(); - discardResponse = true; - if (request->connectionType & ConnectionTypeDownload || request->connectionType & ConnectionTypeUpload) { - retryRequestsFromDatacenter = datacenter->datacenterId; - retryRequestsConnections = request->connectionType; - } - } - } - - if (unpacked_data != nullptr) { - unpacked_data->reuse(); - } - if (implicitError != nullptr) { - delete implicitError; - } - } - - if (!discardResponse) { - if (allowInitConnection && request->isInitRequest && !isError) { - if (datacenter->lastInitVersion != currentVersion) { - datacenter->lastInitVersion = currentVersion; - saveConfig(); - DEBUG_D("dc%d init connection completed", datacenter->getDatacenterId()); - } else { - DEBUG_D("dc%d rpc is init, but init connection already completed", datacenter->getDatacenterId()); - } - } - request->completed = true; - removeRequestFromGuid(request->requestToken); - runningRequests.erase(iter); - } else { - request->messageId = 0; - request->messageSeqNo = 0; - request->connectionToken = 0; - } - break; - } - } - } - - 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)) { - TL_bad_msg_notification *result = (TL_bad_msg_notification *) message; - DEBUG_E("bad message: %d", result->error_code); - 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) { - int64_t time = (int64_t) (messageId / 4294967296.0 * 1000); - int64_t currentTime = getCurrentTimeMillis(); - timeDifference = (int32_t) ((time - currentTime) / 1000 - currentPingTime / 2); - } - - datacenter->recreateSessions(); - saveConfig(); - - lastOutgoingMessageId = 0; - clearRequestsForDatacenter(datacenter); - break; - } - default: - break; - } - } else if (typeInfo == typeid(TL_bad_server_salt)) { - TL_bad_server_salt *response = (TL_bad_server_salt *) message; - if (messageId != 0) { - int64_t time = (int64_t) (messageId / 4294967296.0 * 1000); - int64_t currentTime = getCurrentTimeMillis(); - timeDifference = (int32_t) ((time - currentTime) / 1000 - currentPingTime / 2); - lastOutgoingMessageId = messageId > (lastOutgoingMessageId ? messageId : lastOutgoingMessageId); - } - int64_t resultMid = response->bad_msg_id; - if (resultMid != 0) { - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - if ((request->connectionType & ConnectionTypeDownload) == 0) { - continue; - } - Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId); - if (requestDatacenter != nullptr && requestDatacenter->getDatacenterId() == datacenter->getDatacenterId()) { - request->retryCount = 0; - request->failedBySalt = true; - } - } - } - - datacenter->clearServerSalts(); - - std::unique_ptr salt = std::unique_ptr(new TL_future_salt()); - salt->valid_until = salt->valid_since = getCurrentTime(); - salt->valid_until += 30 * 60; - salt->salt = messageSalt; - datacenter->addServerSalt(salt); - saveConfig(); - - requestSaltsForDatacenter(datacenter); - if (datacenter->hasAuthKey()) { - processRequestQueue(AllConnectionTypes, datacenter->getDatacenterId()); - } - } else if (dynamic_cast(message)) { - MsgDetailedInfo *response = (MsgDetailedInfo *) message; - - bool requestResend = false; - bool confirm = true; - - if (typeInfo == typeid(TL_msg_detailed_info)) { - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - if (request->respondsToMessageId(response->msg_id)) { - if (request->completed) { - break; - } - int32_t currentTime = (int32_t) (getCurrentTimeMillis() / 1000); - if (request->lastResendTime == 0 || abs(currentTime - request->lastResendTime) >= 60) { - request->lastResendTime = currentTime; - requestResend = true; - } else { - confirm = false; - } - break; - } - } - } else { - if (!connection->isMessageIdProcessed(messageId)) { - requestResend = true; - } - } - - if (requestResend) { - TL_msg_resend_req *request = new TL_msg_resend_req(); - request->msg_ids.push_back(response->answer_msg_id); - NetworkMessage *networkMessage = new NetworkMessage(); - networkMessage->message = std::unique_ptr(new TL_message()); - networkMessage->message->msg_id = generateMessageId(); - networkMessage->message->bytes = request->getObjectSize(); - networkMessage->message->body = std::unique_ptr(request); - networkMessage->message->seqno = connection->generateMessageSeqNo(false); - - std::vector> array; - array.push_back(std::unique_ptr(networkMessage)); - - sendMessagesToConnection(array, connection, false); - } else if (confirm) { - connection->addMessageToConfirm(response->answer_msg_id); - } - } else if (typeInfo == typeid(TL_gzip_packed)) { - TL_gzip_packed *response = (TL_gzip_packed *) message; - NativeByteBuffer *data = decompressGZip(response->packed_data.get()); - TLObject *object = TLdeserialize(getRequestWithMessageId(messageId), data->limit(), data); - if (object != nullptr) { - DEBUG_D("connection(%p, dc%u, type %d) received object %s", connection, datacenter->getDatacenterId(), connection->getConnectionType(), typeid(*object).name()); - processServerResponse(object, messageId, messageSeqNo, messageSalt, connection, innerMsgId, containerMessageId); - delete object; - } else { - if (delegate != nullptr) { - delegate->onUnparsedMessageReceived(messageId, data, connection->getConnectionType()); - } - } - data->reuse(); - } else if (typeInfo == typeid(TL_updatesTooLong)) { - if (connection->connectionType == ConnectionTypePush) { - if (networkPaused) { - lastPauseTime = getCurrentTimeMillis(); - DEBUG_D("received internal push: wakeup network in background"); - } else if (lastPauseTime != 0) { - lastPauseTime = getCurrentTimeMillis(); - DEBUG_D("received internal push: reset sleep timeout"); - } else { - DEBUG_D("received internal push"); - } - if (delegate != nullptr) { - delegate->onInternalPushReceived(); - } - } else { - if (delegate != nullptr) { - NativeByteBuffer *data = BuffersStorage::getInstance().getFreeBuffer(message->getObjectSize()); - message->serializeToStream(data); - data->position(0); - delegate->onUnparsedMessageReceived(0, data, connection->getConnectionType()); - data->reuse(); - } - } - } -} - -void ConnectionsManager::sendPing(Datacenter *datacenter, bool usePushConnection) { - if (usePushConnection && (currentUserId == 0 || !usePushConnection)) { - return; - } - Connection *connection = nullptr; - if (usePushConnection) { - connection = datacenter->getPushConnection(true); - } else { - connection = datacenter->getGenericConnection(true); - } - if (connection == nullptr || (!usePushConnection && connection->getConnectionToken() == 0)) { - return; - } - TL_ping_delay_disconnect *request = new TL_ping_delay_disconnect(); - request->ping_id = ++lastPingId; - if (usePushConnection) { - request->disconnect_delay = 60 * 7; - } else { - request->disconnect_delay = 35; - pingTime = (int32_t) (getCurrentTimeMillis() / 1000); - } - - NetworkMessage *networkMessage = new NetworkMessage(); - networkMessage->message = std::unique_ptr(new TL_message()); - networkMessage->message->msg_id = generateMessageId(); - networkMessage->message->bytes = request->getObjectSize(); - networkMessage->message->body = std::unique_ptr(request); - networkMessage->message->seqno = connection->generateMessageSeqNo(false); - - std::vector> array; - array.push_back(std::unique_ptr(networkMessage)); - NativeByteBuffer *transportData = datacenter->createRequestsData(array, nullptr, connection); - if (usePushConnection) { - DEBUG_D("dc%d send ping to push connection", datacenter->getDatacenterId()); - sendingPushPing = true; - } - connection->sendData(transportData, false); -} - -bool ConnectionsManager::isIpv6Enabled() { - return ipv6Enabled; -} - -void ConnectionsManager::initDatacenters() { - Datacenter *datacenter; - if (!testBackend) { - if (datacenters.find(1) == datacenters.end()) { - datacenter = new Datacenter(1); - datacenter->addAddressAndPort("149.154.175.50", 443, 0); - datacenter->addAddressAndPort("2001:b28:f23d:f001:0000:0000:0000:000a", 443, 1); - datacenters[1] = datacenter; - } - - if (datacenters.find(2) == datacenters.end()) { - datacenter = new Datacenter(2); - datacenter->addAddressAndPort("149.154.167.51", 443, 0); - datacenter->addAddressAndPort("2001:67c:4e8:f002:0000:0000:0000:000a", 443, 1); - datacenters[2] = datacenter; - } - - if (datacenters.find(3) == datacenters.end()) { - datacenter = new Datacenter(3); - datacenter->addAddressAndPort("149.154.175.100", 443, 0); - datacenter->addAddressAndPort("2001:b28:f23d:f003:0000:0000:0000:000a", 443, 1); - datacenters[3] = datacenter; - } - - if (datacenters.find(4) == datacenters.end()) { - datacenter = new Datacenter(4); - datacenter->addAddressAndPort("149.154.167.91", 443, 0); - datacenter->addAddressAndPort("2001:67c:4e8:f004:0000:0000:0000:000a", 443, 1); - datacenters[4] = datacenter; - } - - if (datacenters.find(5) == datacenters.end()) { - datacenter = new Datacenter(5); - datacenter->addAddressAndPort("149.154.171.5", 443, 0); - datacenter->addAddressAndPort("2001:b28:f23f:f005:0000:0000:0000:000a", 443, 1); - datacenters[5] = datacenter; - } - } else { - if (datacenters.find(1) == datacenters.end()) { - datacenter = new Datacenter(1); - datacenter->addAddressAndPort("149.154.175.10", 443, 0); - datacenter->addAddressAndPort("2001:b28:f23d:f001:0000:0000:0000:000e", 443, 1); - datacenters[1] = datacenter; - } - - if (datacenters.find(2) == datacenters.end()) { - datacenter = new Datacenter(2); - datacenter->addAddressAndPort("149.154.167.40", 443, 0); - datacenter->addAddressAndPort("2001:67c:4e8:f002:0000:0000:0000:000e", 443, 1); - datacenters[2] = datacenter; - } - - if (datacenters.find(3) == datacenters.end()) { - datacenter = new Datacenter(3); - datacenter->addAddressAndPort("149.154.175.117", 443, 0); - datacenter->addAddressAndPort("2001:b28:f23d:f003:0000:0000:0000:000e", 443, 1); - 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) { - std::vector::iterator iter = std::find(activeConnections.begin(), activeConnections.end(), connection); - if (iter != activeConnections.end()) { - activeConnections.erase(iter); - } -} - -int32_t ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate) { - int32_t requestToken = lastRequestToken++; - sendRequest(object, onComplete, onQuickAck, flags, datacenterId, connetionType, immediate, requestToken); - return requestToken; -} - -void ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate, int32_t requestToken) { - if (!currentUserId && !(flags & RequestFlagWithoutLogin)) { - DEBUG_D("can't do request without login %s", typeid(*object).name()); - delete object; - return; - } - scheduleTask([&, requestToken, object, onComplete, onQuickAck, flags, datacenterId, connetionType, immediate] { - Request *request = new Request(requestToken, connetionType, flags, datacenterId, onComplete, onQuickAck); - request->rawRequest = object; - request->rpcRequest = wrapInLayer(object, getDatacenterWithId(datacenterId), request); - requestsQueue.push_back(std::unique_ptr(request)); - if (immediate) { - processRequestQueue(0, 0); - } - }); -} - -#ifdef ANDROID -void ConnectionsManager::sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate, int32_t requestToken, jobject ptr1, jobject ptr2) { - if (!currentUserId && !(flags & RequestFlagWithoutLogin)) { - DEBUG_D("can't do request without login %s", typeid(*object).name()); - delete object; - JNIEnv *env = 0; - if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { - DEBUG_E("can't get jnienv"); - exit(1); - } - if (ptr1 != nullptr) { - env->DeleteGlobalRef(ptr1); - ptr1 = nullptr; - } - if (ptr2 != nullptr) { - env->DeleteGlobalRef(ptr2); - ptr2 = nullptr; - } - return; - } - scheduleTask([&, requestToken, object, onComplete, onQuickAck, flags, datacenterId, connetionType, immediate, ptr1, ptr2] { - DEBUG_D("send request %p - %s", object, typeid(*object).name()); - Request *request = new Request(requestToken, connetionType, flags, datacenterId, onComplete, onQuickAck); - request->rawRequest = object; - request->ptr1 = ptr1; - request->ptr2 = ptr2; - request->rpcRequest = wrapInLayer(object, getDatacenterWithId(datacenterId), request); - DEBUG_D("send request wrapped %p - %s", request->rpcRequest.get(), typeid(*(request->rpcRequest.get())).name()); - requestsQueue.push_back(std::unique_ptr(request)); - if (immediate) { - processRequestQueue(0, 0); - } - }); -} -#endif - -void ConnectionsManager::cancelRequestsForGuid(int32_t guid) { - scheduleTask([&, guid] { - std::map>::iterator iter = requestsByGuids.find(guid); - if (iter != requestsByGuids.end()) { - std::vector &requests = iter->second; - size_t count = requests.size(); - for (uint32_t a = 0; a < count; a++) { - cancelRequestInternal(requests[a], true, false); - std::map::iterator iter2 = guidsByRequests.find(requests[a]); - if (iter2 != guidsByRequests.end()) { - guidsByRequests.erase(iter2); - } - } - requestsByGuids.erase(iter); - } - }); -} - -void ConnectionsManager::bindRequestToGuid(int32_t requestToken, int32_t guid) { - scheduleTask([&, requestToken, guid] { - std::map>::iterator iter = requestsByGuids.find(guid); - if (iter != requestsByGuids.end()) { - iter->second.push_back(requestToken); - } else { - std::vector array; - array.push_back(requestToken); - requestsByGuids[guid] = array; - } - guidsByRequests[requestToken] = guid; - }); -} - -void ConnectionsManager::setUserId(int32_t userId) { - scheduleTask([&, userId] { - int32_t oldUserId = currentUserId; - currentUserId = userId; - if (oldUserId == userId && userId != 0) { - registerForInternalPushUpdates(); - } - if (currentUserId != userId && userId != 0) { - updateDcSettings(0); - } - if (currentUserId != 0 && pushConnectionEnabled) { - Datacenter *datacenter = getDatacenterWithId(currentDatacenterId); - if (datacenter != nullptr) { - datacenter->createPushConnection()->setSessionId(pushSessionId); - sendPing(datacenter, true); - } - } - }); -} - -void ConnectionsManager::switchBackend() { - scheduleTask([&] { - testBackend = !testBackend; - datacenters.clear(); - initDatacenters(); - saveConfig(); - exit(1); - }); -} - -void ConnectionsManager::removeRequestFromGuid(int32_t requestToken) { - std::map::iterator iter2 = guidsByRequests.find(requestToken); - if (iter2 != guidsByRequests.end()) { - std::map>::iterator iter = requestsByGuids.find(iter2->first); - if (iter != requestsByGuids.end()) { - std::vector::iterator iter3 = std::find(iter->second.begin(), iter->second.end(), iter->first); - if (iter3 != iter->second.end()) { - iter->second.erase(iter3); - if (iter->second.empty()) { - requestsByGuids.erase(iter); - } - } - } - guidsByRequests.erase(iter2); - } -} - -void ConnectionsManager::cancelRequestInternal(int32_t token, bool notifyServer, bool removeFromClass) { - for (requestsIter iter = requestsQueue.begin(); iter != requestsQueue.end(); iter++) { - Request *request = iter->get(); - if (request->requestToken == token) { - request->cancelled = true; - DEBUG_D("cancelled queued rpc request %p - %s", request->rawRequest, typeid(*request->rawRequest).name()); - requestsQueue.erase(iter); - if (removeFromClass) { - removeRequestFromGuid(token); - } - return; - } - } - - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - if (request->requestToken == token) { - if (notifyServer) { - TL_rpc_drop_answer *dropAnswer = new TL_rpc_drop_answer(); - dropAnswer->req_msg_id = request->messageId; - sendRequest(dropAnswer, nullptr, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin | RequestFlagFailOnServerErrors, request->datacenterId, request->connectionType, true); - } - request->cancelled = true; - DEBUG_D("cancelled running rpc request %p - %s", request->rawRequest, typeid(*request->rawRequest).name()); - runningRequests.erase(iter); - if (removeFromClass) { - removeRequestFromGuid(token); - } - return; - } - } -} - -void ConnectionsManager::cancelRequest(int32_t token, bool notifyServer) { - if (token == 0) { - return; - } - scheduleTask([&, token, notifyServer] { - cancelRequestInternal(token, notifyServer, true); - }); -} - -void ConnectionsManager::onDatacenterHandshakeComplete(Datacenter *datacenter, int32_t timeDiff) { - saveConfig(); - uint32_t datacenterId = datacenter->getDatacenterId(); - if (datacenterId == currentDatacenterId || datacenterId == movingToDatacenterId) { - timeDifference = timeDiff; - datacenter->recreateSessions(); - clearRequestsForDatacenter(datacenter); - } - processRequestQueue(AllConnectionTypes, datacenterId); -} - -void ConnectionsManager::onDatacenterExportAuthorizationComplete(Datacenter *datacenter) { - saveConfig(); - processRequestQueue(AllConnectionTypes, datacenter->getDatacenterId()); -} - -void ConnectionsManager::sendMessagesToConnection(std::vector> &messages, Connection *connection, bool reportAck) { - if (messages.empty() || connection == nullptr) { - return; - } - - std::vector> 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; - NativeByteBuffer *transportData = datacenter->createRequestsData(currentMessages, reportAck ? &quickAckId : nullptr, connection); - - if (transportData != nullptr) { - if (reportAck && quickAckId != 0) { - std::vector 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()) { - std::map>::iterator iter = quickAckIdToRequestIds.find(quickAckId); - if (iter == quickAckIdToRequestIds.end()) { - quickAckIdToRequestIds[quickAckId] = requestIds; - } else { - iter->second.insert(iter->second.end(), requestIds.begin(), requestIds.end()); - } - } - } - - connection->sendData(transportData, reportAck); - } else { - DEBUG_E("connection(%p) connection data is empty", connection); - } - - currentSize = 0; - currentMessages.clear(); - } - } -} - -void ConnectionsManager::sendMessagesToConnectionWithConfirmation(std::vector> &messages, Connection *connection, bool reportAck) { - NetworkMessage *networkMessage = connection->generateConfirmationRequest(); - if (networkMessage != nullptr) { - messages.push_back(std::unique_ptr(networkMessage)); - } - sendMessagesToConnection(messages, connection, reportAck); -} - -void ConnectionsManager::requestSaltsForDatacenter(Datacenter *datacenter) { - if (std::find(requestingSaltsForDc.begin(), requestingSaltsForDc.end(), datacenter->getDatacenterId()) != requestingSaltsForDc.end()) { - return; - } - requestingSaltsForDc.push_back(datacenter->getDatacenterId()); - TL_get_future_salts *request = new TL_get_future_salts(); - request->num = 32; - sendRequest(request, [&, datacenter](TLObject *response, TL_error *error) { - std::vector::iterator iter = std::find(requestingSaltsForDc.begin(), requestingSaltsForDc.end(), datacenter->getDatacenterId()); - if (iter != requestingSaltsForDc.end()) { - requestingSaltsForDc.erase(iter); - } - if (error == nullptr) { - TL_future_salts *res = (TL_future_salts *) response; - datacenter->mergeServerSalts(res->salts); - saveConfig(); - } - }, nullptr, RequestFlagWithoutLogin | RequestFlagEnableUnauthorized, datacenter->getDatacenterId(), ConnectionTypeGeneric, true); -} - -void ConnectionsManager::clearRequestsForDatacenter(Datacenter *datacenter) { - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end(); iter++) { - Request *request = iter->get(); - Datacenter *requestDatacenter = getDatacenterWithId(request->datacenterId); - if (requestDatacenter->getDatacenterId() == datacenter->getDatacenterId()) { - request->clear(true); - } - } -} - -void ConnectionsManager::registerForInternalPushUpdates() { - if (registeringForPush || !currentUserId) { - return; - } - registeredForInternalPush = false; - registeringForPush = true; - TL_account_registerDevice *request = new TL_account_registerDevice(); - request->token_type = 7; - request->token = to_string_uint64(pushSessionId); - request->app_sandbox = false; - - request->app_version = currentAppVersion; - request->device_model = currentDeviceModel; - request->lang_code = currentLangCode; - request->system_version = currentSystemVersion; - if (request->lang_code.empty()) { - request->lang_code = "en"; - } - if (request->device_model.empty()) { - request->device_model = "device model unknown"; - } - if (request->app_version.empty()) { - request->app_version = "app version unknown"; - } - if (request->system_version.empty()) { - request->system_version = "system version unknown"; - } - - sendRequest(request, [&](TLObject *response, TL_error *error) { - if (error == nullptr) { - registeredForInternalPush = true; - DEBUG_D("registered for internal push"); - } else { - registeredForInternalPush = false; - DEBUG_E("unable to registering for internal push"); - } - saveConfig(); - registeringForPush = false; - }, nullptr, 0, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true); -} - - -inline void addMessageToDatacenter(uint32_t datacenterId, NetworkMessage *networkMessage, std::map>> &genericMessagesToDatacenters) { - std::map>>::iterator iter = genericMessagesToDatacenters.find(datacenterId); - if (iter == genericMessagesToDatacenters.end()) { - std::vector> &array = genericMessagesToDatacenters[datacenterId] = std::vector>(); - array.push_back(std::unique_ptr(networkMessage)); - } else { - iter->second.push_back(std::unique_ptr(networkMessage)); - } -} - -void ConnectionsManager::processRequestQueue(uint32_t connectionTypes, uint32_t dc) { - static std::map>> genericMessagesToDatacenters; - static std::vector unknownDatacenterIds; - static std::vector neededDatacenters; - static std::vector unauthorizedDatacenters; - - genericMessagesToDatacenters.clear(); - unknownDatacenterIds.clear(); - neededDatacenters.clear(); - unauthorizedDatacenters.clear(); - - Connection *genericConnection = nullptr; - Datacenter *defaultDatacenter = getDatacenterWithId(currentDatacenterId); - if (defaultDatacenter != nullptr) { - genericConnection = defaultDatacenter->getGenericConnection(true); - } - - int32_t currentTime = (int32_t) (getCurrentTimeMillis() / 1000); - uint32_t genericRunningRequestCount = 0; - uint32_t uploadRunningRequestCount = 0; - uint32_t downloadRunningRequestCount = 0; - - for (requestsIter iter = runningRequests.begin(); iter != runningRequests.end();) { - Request *request = iter->get(); - const std::type_info &typeInfo = typeid(*request->rawRequest); - - switch (request->connectionType & 0x0000ffff) { - case ConnectionTypeGeneric: - genericRunningRequestCount++; - break; - case ConnectionTypeDownload: - downloadRunningRequestCount++; - break; - case ConnectionTypeUpload: - uploadRunningRequestCount++; - break; - default: - break; - } - - uint32_t datacenterId = request->datacenterId; - if (datacenterId == DEFAULT_DATACENTER_ID) { - if (movingToDatacenterId != DEFAULT_DATACENTER_ID) { - iter++; - continue; - } - datacenterId = currentDatacenterId; - } - - if (request->requestFlags & RequestFlagTryDifferentDc) { - int32_t requestStartTime = request->startTime; - int32_t timeout = 30; - if (updatingDcSettings && dynamic_cast(request->rawRequest)) { - requestStartTime = updatingDcStartTime; - updatingDcStartTime = currentTime; - timeout = 60; - } - if (request->startTime != 0 && abs(currentTime - requestStartTime) >= timeout) { - DEBUG_D("move %s to requestsQueue", typeid(*request->rawRequest).name()); - requestsQueue.push_back(std::move(*iter)); - iter = runningRequests.erase(iter); - continue; - } - } - - Datacenter *requestDatacenter = getDatacenterWithId(datacenterId); - if (requestDatacenter->lastInitVersion != currentVersion && !request->isInitRequest) { - request->rpcRequest.release(); - request->rpcRequest = wrapInLayer(request->rawRequest, requestDatacenter, request); - request->serializedLength = request->getRpcRequest()->getObjectSize(); - } - - if (requestDatacenter == nullptr) { - if (std::find(unknownDatacenterIds.begin(), unknownDatacenterIds.end(), datacenterId) == unknownDatacenterIds.end()) { - unknownDatacenterIds.push_back(datacenterId); - } - iter++; - continue; - } else if (!requestDatacenter->hasAuthKey()) { - if (std::find(neededDatacenters.begin(), neededDatacenters.end(), requestDatacenter) == neededDatacenters.end()) { - neededDatacenters.push_back(requestDatacenter); - } - 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; - } - - Connection *connection = requestDatacenter->getConnectionByType(request->connectionType, true); - int32_t maxTimeout = request->connectionType & ConnectionTypeGeneric ? 8 : 30; - if (!networkAvailable || connection->getConnectionToken() == 0) { - iter++; - continue; - } - - uint32_t requestConnectionType = request->connectionType & 0x0000ffff; - - bool forceThisRequest = (connectionTypes & requestConnectionType) && requestDatacenter->getDatacenterId() == dc; - - if (typeInfo == typeid(TL_get_future_salts) || typeInfo == typeid(TL_destroy_session)) { - if (request->messageId != 0) { - request->addRespondMessageId(request->messageId); - } - request->clear(false); - forceThisRequest = false; - } - - if (forceThisRequest || (abs(currentTime - request->startTime) > maxTimeout && - (currentTime >= request->minStartTime || - (request->failedByFloodWait != 0 && (request->minStartTime - currentTime) > request->failedByFloodWait) || - (request->failedByFloodWait == 0 && abs(currentTime - request->minStartTime) >= 60)) - ) - ) { - if (!forceThisRequest && request->connectionToken > 0) { - if (request->connectionType & ConnectionTypeGeneric && request->connectionToken == connection->getConnectionToken()) { - DEBUG_D("request token is valid, not retrying %s", typeInfo.name()); - iter++; - continue; - } else { - if (connection->getConnectionToken() != 0 && request->connectionToken == connection->getConnectionToken()) { - DEBUG_D("request download token is valid, not retrying %s", typeInfo.name()); - iter++; - continue; - } - } - } - - if (request->connectionToken != 0 && request->connectionToken != connection->getConnectionToken()) { - request->lastResendTime = 0; - } - - request->retryCount++; - - if (!request->failedBySalt) { - if (request->connectionType & ConnectionTypeDownload) { - uint32_t retryMax = 10; - if (!(request->requestFlags & RequestFlagForceDownload)) { - if (request->failedByFloodWait) { - retryMax = 1; - } else { - retryMax = 6; - } - } - if (request->retryCount >= retryMax) { - DEBUG_E("timed out %s", typeInfo.name()); - TL_error *error = new TL_error(); - error->code = -123; - error->text = "RETRY_LIMIT"; - request->onComplete(nullptr, error); - delete error; - iter = runningRequests.erase(iter); - continue; - } - } - } else { - request->failedBySalt = false; - } - - if (request->messageSeqNo == 0) { - request->messageSeqNo = connection->generateMessageSeqNo(true); - request->messageId = generateMessageId(); - } - request->startTime = currentTime; - - NetworkMessage *networkMessage = new NetworkMessage(); - networkMessage->message = std::unique_ptr(new TL_message()); - 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; - networkMessage->invokeAfter = (request->requestFlags & RequestFlagInvokeAfter) != 0; - networkMessage->needQuickAck = (request->requestFlags & RequestFlagNeedQuickAck) != 0; - - request->connectionToken = connection->getConnectionToken(); - switch (requestConnectionType) { - case ConnectionTypeGeneric: - addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters); - break; - case ConnectionTypeDownload: - case ConnectionTypeUpload: { - std::vector> array; - array.push_back(std::unique_ptr(networkMessage)); - sendMessagesToConnectionWithConfirmation(array, connection, false); - break; - } - default: - delete networkMessage; - } - } - iter++; - } - - if (genericConnection != nullptr && !sessionsToDestroy.empty() && genericConnection->getConnectionToken() != 0) { - std::vector::iterator iter = sessionsToDestroy.begin(); - - sessionsToDestroy.erase(iter); - - if (abs(currentTime - lastDestroySessionRequestTime) > 2) { - lastDestroySessionRequestTime = currentTime; - TL_destroy_session *request = new TL_destroy_session(); - request->session_id = *iter; - - NetworkMessage *networkMessage = new NetworkMessage(); - networkMessage->message = std::unique_ptr(new TL_message()); - networkMessage->message->msg_id = generateMessageId(); - networkMessage->message->bytes = request->getObjectSize(); - networkMessage->message->body = std::unique_ptr(request); - networkMessage->message->seqno = genericConnection->generateMessageSeqNo(false); - addMessageToDatacenter(defaultDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters); - } - } - - for (requestsIter iter = requestsQueue.begin(); iter != requestsQueue.end();) { - Request *request = iter->get(); - if (request->cancelled) { - iter = requestsQueue.erase(iter); - continue; - } - - uint32_t datacenterId = request->datacenterId; - if (datacenterId == DEFAULT_DATACENTER_ID) { - if (movingToDatacenterId != DEFAULT_DATACENTER_ID) { - iter++; - continue; - } - datacenterId = currentDatacenterId; - } - - if (request->requestFlags & RequestFlagTryDifferentDc) { - int32_t requestStartTime = request->startTime; - int32_t timeout = 30; - if (updatingDcSettings && dynamic_cast(request->rawRequest)) { - requestStartTime = updatingDcStartTime; - timeout = 60; - } else { - request->startTime = 0; - } - if (requestStartTime != 0 && abs(currentTime - requestStartTime) >= timeout) { - std::vector allDc; - for (std::map::iterator iter2 = datacenters.begin(); iter2 != datacenters.end(); iter2++) { - if (iter2->first == datacenterId) { - continue; - } - allDc.push_back(iter2->first); - } - uint8_t index; - RAND_bytes(&index, 1); - datacenterId = allDc[index % allDc.size()]; - if (dynamic_cast(request->rawRequest)) { - updatingDcStartTime = currentTime; - request->datacenterId = datacenterId; - } else { - currentDatacenterId = datacenterId; - } - } - } - - Datacenter *requestDatacenter = getDatacenterWithId(datacenterId); - if (requestDatacenter->lastInitVersion != currentVersion && !request->isInitRequest) { - request->rpcRequest.release(); - request->rpcRequest = wrapInLayer(request->rawRequest, requestDatacenter, request); - } - - if (requestDatacenter == nullptr) { - if (std::find(unknownDatacenterIds.begin(), unknownDatacenterIds.end(), datacenterId) == unknownDatacenterIds.end()) { - unknownDatacenterIds.push_back(datacenterId); - } - iter++; - continue; - } else if (!requestDatacenter->hasAuthKey()) { - if (std::find(neededDatacenters.begin(), neededDatacenters.end(), requestDatacenter) == neededDatacenters.end()) { - neededDatacenters.push_back(requestDatacenter); - } - 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; - } - - Connection *connection = requestDatacenter->getConnectionByType(request->connectionType, true); - - if (request->connectionType & ConnectionTypeGeneric && connection->getConnectionToken() == 0) { - iter++; - continue; - } - - switch (request->connectionType & 0x0000ffff) { - case ConnectionTypeGeneric: - if (genericRunningRequestCount >= 60) { - iter++; - continue; - } - genericRunningRequestCount++; - break; - case ConnectionTypeDownload: - if (!networkAvailable || downloadRunningRequestCount >= 5) { - iter++; - continue; - } - downloadRunningRequestCount++; - break; - case ConnectionTypeUpload: - if (!networkAvailable || uploadRunningRequestCount >= 5) { - iter++; - continue; - } - uploadRunningRequestCount++; - break; - default: - break; - } - - 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) { - TL_gzip_packed *packed = new TL_gzip_packed(); - packed->originalRequest = std::move(request->rpcRequest); - packed->packed_data_to_send = buffer; - request->rpcRequest = std::unique_ptr(packed); - requestLength = packed->getObjectSize(); - } - original->reuse(); - } - request->messageId = generateMessageId(); - request->serializedLength = requestLength; - request->messageSeqNo = connection->generateMessageSeqNo(true); - request->startTime = (int32_t) (getCurrentTimeMillis() / 1000); - request->connectionToken = connection->getConnectionToken(); - - NetworkMessage *networkMessage = new NetworkMessage(); - networkMessage->message = std::unique_ptr(new TL_message()); - 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; - networkMessage->invokeAfter = (request->requestFlags & RequestFlagInvokeAfter) != 0; - networkMessage->needQuickAck = (request->requestFlags & RequestFlagNeedQuickAck) != 0; - - runningRequests.push_back(std::move(*iter)); - - switch (request->connectionType & 0x0000ffff) { - case ConnectionTypeGeneric: - addMessageToDatacenter(requestDatacenter->getDatacenterId(), networkMessage, genericMessagesToDatacenters); - break; - case ConnectionTypeDownload: - case ConnectionTypeUpload: { - std::vector> array; - array.push_back(std::unique_ptr(networkMessage)); - sendMessagesToConnectionWithConfirmation(array, connection, false); - break; - } - default: - delete networkMessage; - } - - iter = requestsQueue.erase(iter); - } - - for (std::map::iterator iter = datacenters.begin(); iter != datacenters.end(); iter++) { - Datacenter *datacenter = iter->second; - std::map>>::iterator iter2 = genericMessagesToDatacenters.find(datacenter->getDatacenterId()); - if (iter2 == genericMessagesToDatacenters.end()) { - Connection *connection = datacenter->getGenericConnection(false); - if (connection != nullptr && connection->getConnectionToken() != 0 && connection->hasMessagesToConfirm()) { - genericMessagesToDatacenters[datacenter->getDatacenterId()] = std::vector>(); - } - } - } - - for (std::map>>::iterator iter = genericMessagesToDatacenters.begin(); iter != genericMessagesToDatacenters.end(); iter++) { - Datacenter *datacenter = getDatacenterWithId(iter->first); - if (datacenter != nullptr) { - bool scannedPreviousRequests = false; - int64_t lastSentMessageRpcId = 0; - bool needQuickAck = false; - std::vector> &array = iter->second; - 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 currentRequests; - for (uint32_t a = 0; a < count; a++) { - NetworkMessage *currentNetworkMessage = array[a].get(); - TL_message *currentMessage = currentNetworkMessage->message.get(); - if (currentNetworkMessage->invokeAfter) { - currentRequests.push_back(currentMessage->msg_id); - } - } - - int64_t maxRequestId = 0; - for (requestsIter iter2 = runningRequests.begin(); iter2 != runningRequests.end(); iter2++) { - Request *request = iter2->get(); - 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) { - TL_invokeAfterMsg *request = new TL_invokeAfterMsg(); - request->msg_id = lastSentMessageRpcId; - if (message->outgoingBody != nullptr) { - DEBUG_D("wrap outgoingBody(%p, %s) to TL_invokeAfterMsg", message->outgoingBody, typeid(*message->outgoingBody).name()); - request->outgoingQuery = message->outgoingBody; - message->outgoingBody = nullptr; - } else { - DEBUG_D("wrap body(%p, %s) to TL_invokeAfterMsg", message->body.get(), typeid(*(message->body.get())).name()); - request->query = std::move(message->body); - } - message->body = std::unique_ptr(request); - message->bytes += 4 + 8; - } - - lastSentMessageRpcId = message->msg_id; - } - } - - sendMessagesToConnectionWithConfirmation(array, datacenter->getGenericConnection(true), needQuickAck); - } - } - - if (connectionTypes == ConnectionTypeGeneric && dc == currentDatacenterId) { - std::map>>::iterator iter2 = genericMessagesToDatacenters.find(currentDatacenterId); - if (iter2 == genericMessagesToDatacenters.end()) { - sendPing(getDatacenterWithId(currentDatacenterId), false); - } - } - - if (!unknownDatacenterIds.empty()) { - updateDcSettings(0); - } - - size_t count = neededDatacenters.size(); - for (uint32_t a = 0; a < count; a++) { - Datacenter *datacenter = neededDatacenters[a]; - if (datacenter->getDatacenterId() != movingToDatacenterId && !datacenter->isHandshaking() && !datacenter->hasAuthKey()) { - datacenter->beginHandshake(true); - } - } - - 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]; - } - std::map::iterator iter = datacenters.find(datacenterId); - return iter != datacenters.end() ? iter->second : nullptr; -} - -std::unique_ptr ConnectionsManager::wrapInLayer(TLObject *object, Datacenter *datacenter, Request *baseRequest) { - if (object->isNeedLayer()) { - if (datacenter == nullptr || datacenter->lastInitVersion != currentVersion) { - if (datacenter->getDatacenterId() == currentDatacenterId) { - registerForInternalPushUpdates(); - } - baseRequest->isInitRequest = true; - initConnection *request = new initConnection(); - request->query = std::unique_ptr(object); - request->api_id = currentApiId; - request->app_version = currentAppVersion; - request->device_model = currentDeviceModel; - request->lang_code = currentLangCode; - request->system_version = currentSystemVersion; - if (request->lang_code.empty()) { - request->lang_code = "en"; - } - if (request->device_model.empty()) { - request->device_model = "device model unknown"; - } - if (request->app_version.empty()) { - request->app_version = "app version unknown"; - } - if (request->system_version.empty()) { - request->system_version = "system version unknown"; - } - invokeWithLayer *request2 = new invokeWithLayer(); - request2->layer = currentLayer; - request2->query = std::unique_ptr(request); - DEBUG_D("wrap in layer %s", typeid(*object).name()); - return std::unique_ptr(request2); - } - } - return std::unique_ptr(object); -} - -void ConnectionsManager::updateDcSettings(uint32_t dcNum) { - if (updatingDcSettings) { - return; - } - updatingDcStartTime = (int32_t) (getCurrentTimeMillis() / 1000); - updatingDcSettings = true; - TL_help_getConfig *request = new TL_help_getConfig(); - - sendRequest(request, [&](TLObject *response, TL_error *error) { - if (!updatingDcSettings) { - return; - } - - if (response != nullptr) { - TL_config *config = (TL_config *) response; - int32_t updateIn = config->expires - getCurrentTime(); - if (updateIn <= 0) { - updateIn = 120; - } - lastDcUpdateTime = (int32_t) (getCurrentTimeMillis() / 1000) - DC_UPDATE_TIME + updateIn; - - struct DatacenterInfo { - std::vector addressesIpv4; - std::vector addressesIpv6; - std::vector addressesIpv4Download; - std::vector addressesIpv6Download; - std::map ports; - - void addAddressAndPort(std::string address, uint32_t port, uint32_t flags) { - std::vector *addresses; - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - addresses = &addressesIpv6Download; - } else { - addresses = &addressesIpv4Download; - } - } else { - if ((flags & 1) != 0) { - addresses = &addressesIpv6; - } else { - addresses = &addressesIpv4; - } - } - if (std::find(addresses->begin(), addresses->end(), address) != addresses->end()) { - return; - } - addresses->push_back(address); - ports[address] = port; - } - }; - - std::map> map; - size_t count = config->dc_options.size(); - for (uint32_t a = 0; a < count; a++) { - TL_dcOption *dcOption = config->dc_options[a].get(); - std::map>::iterator iter = map.find((uint32_t) dcOption->id); - DatacenterInfo *info; - if (iter == map.end()) { - map[dcOption->id] = std::unique_ptr(info = new DatacenterInfo); - } else { - info = iter->second.get(); - } - info->addAddressAndPort(dcOption->ip_address, (uint32_t) dcOption->port, (uint32_t) dcOption->flags); - } - - if (!map.empty()) { - for (std::map>::iterator iter = map.begin(); iter != map.end(); iter++) { - Datacenter *datacenter = getDatacenterWithId(iter->first); - DatacenterInfo *info = iter->second.get(); - if (datacenter == nullptr) { - datacenter = new Datacenter(iter->first); - datacenters[iter->first] = datacenter; - } - datacenter->replaceAddressesAndPorts(info->addressesIpv4, info->ports, 0); - datacenter->replaceAddressesAndPorts(info->addressesIpv6, info->ports, 1); - datacenter->replaceAddressesAndPorts(info->addressesIpv4Download, info->ports, 2); - datacenter->replaceAddressesAndPorts(info->addressesIpv6Download, info->ports, 3); - if (iter->first == movingToDatacenterId) { - movingToDatacenterId = DEFAULT_DATACENTER_ID; - moveToDatacenter(iter->first); - } - } - saveConfig(); - processRequestQueue(AllConnectionTypes, 0); - } - if (delegate != nullptr) { - delegate->onUpdateConfig(config); - } - } - updatingDcSettings = false; - }, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin | RequestFlagTryDifferentDc, dcNum == 0 ? currentDatacenterId : dcNum, ConnectionTypeGeneric, true); -} - -void ConnectionsManager::moveToDatacenter(uint32_t datacenterId) { - if (movingToDatacenterId == datacenterId) { - return; - } - movingToDatacenterId = datacenterId; - - Datacenter *currentDatacenter = getDatacenterWithId(currentDatacenterId); - clearRequestsForDatacenter(currentDatacenter); - - if (currentUserId) { - TL_auth_exportAuthorization *request = new TL_auth_exportAuthorization(); - request->dc_id = datacenterId; - sendRequest(request, [&, datacenterId](TLObject *response, TL_error *error) { - if (error == nullptr) { - movingAuthorization = std::move(((TL_auth_exportedAuthorization *) response)->bytes); - authorizeOnMovingDatacenter(); - } else { - moveToDatacenter(datacenterId); - } - }, nullptr, RequestFlagWithoutLogin, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true); - } else { - authorizeOnMovingDatacenter(); - } -} - -void ConnectionsManager::authorizeOnMovingDatacenter() { - Datacenter *datacenter = getDatacenterWithId(movingToDatacenterId); - if (datacenter == nullptr) { - updateDcSettings(0); - return; - } - datacenter->recreateSessions(); - clearRequestsForDatacenter(datacenter); - - if (!datacenter->hasAuthKey() && !datacenter->isHandshaking()) { - datacenter->clearServerSalts(); - datacenter->beginHandshake(true); - } - - if (movingAuthorization != nullptr) { - TL_auth_importAuthorization *request = new TL_auth_importAuthorization(); - request->id = currentUserId; - request->bytes = std::move(movingAuthorization); - sendRequest(request, [&](TLObject *response, TL_error *error) { - if (error == nullptr) { - authorizedOnMovingDatacenter(); - } else { - moveToDatacenter(movingToDatacenterId); - } - }, nullptr, RequestFlagWithoutLogin, datacenter->getDatacenterId(), ConnectionTypeGeneric, true); - } else { - authorizedOnMovingDatacenter(); - } -} - -void ConnectionsManager::authorizedOnMovingDatacenter() { - movingAuthorization.reset(); - currentDatacenterId = movingToDatacenterId; - movingToDatacenterId = DEFAULT_DATACENTER_ID; - saveConfig(); - processRequestQueue(0, 0); -} - -void ConnectionsManager::applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port) { - scheduleTask([&, datacenterId, ipAddress, port] { - Datacenter *datacenter = getDatacenterWithId(datacenterId); - if (datacenter != nullptr) { - std::vector addresses; - std::map ports; - addresses.push_back(ipAddress); - ports[ipAddress] = port; - datacenter->replaceAddressesAndPorts(addresses, ports, 0); - datacenter->suspendConnections(); - updateDcSettings(datacenterId); - } - }); -} - -ConnectionState ConnectionsManager::getConnectionState() { - return connectionState; -} - -void ConnectionsManager::setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate) { - delegate = connectiosManagerDelegate; -} - -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); - } - } -} - -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 configPath, std::string logPath, int32_t userId, bool isPaused, bool enablePushConnection) { - currentVersion = version; - currentLayer = layer; - currentApiId = apiId; - currentConfigPath = configPath; - currentDeviceModel = deviceModel; - currentSystemVersion = systemVersion; - currentAppVersion = appVersion; - currentLangCode = langCode; - currentUserId = userId; - currentLogPath = logPath; - pushConnectionEnabled = enablePushConnection; - if (isPaused) { - lastPauseTime = getCurrentTimeMillis(); - } - - if (!currentConfigPath.empty() && currentConfigPath.find_last_of('/') != currentConfigPath.size() - 1) { - currentConfigPath += "/"; - } - - if (!logPath.empty()) { - FileLog::init(logPath); - } - - loadConfig(); - - pthread_create(&networkThread, NULL, (ConnectionsManager::ThreadProc), this); -} - -void ConnectionsManager::resumeNetwork(bool partial) { - scheduleTask([&, partial] { - if (partial) { - if (networkPaused) { - lastPauseTime = getCurrentTimeMillis(); - networkPaused = false; - DEBUG_D("wakeup network in background"); - } else if (lastPauseTime != 0) { - lastPauseTime = getCurrentTimeMillis(); - networkPaused = false; - DEBUG_D("reset sleep timeout"); - } - } else { - lastPauseTime = 0; - networkPaused = false; - } - }); -} - -void ConnectionsManager::pauseNetwork() { - if (lastPauseTime != 0) { - return; - } - lastPauseTime = getCurrentTimeMillis(); -} - -void ConnectionsManager::setNetworkAvailable(bool value) { - scheduleTask([&, value] { - networkAvailable = value; - if (!networkAvailable) { - connectionState = ConnectionStateWaitingForNetwork; - } else { - for (std::map::iterator iter = datacenters.begin(); iter != datacenters.end(); iter++) { - if (iter->second->isHandshaking()) { - iter->second->createGenericConnection()->connect(); - } - } - } - if (delegate != nullptr) { - delegate->onConnectionStateChanged(connectionState); - } - }); -} - -void ConnectionsManager::setUseIpv6(bool value) { - scheduleTask([&, value] { - ipv6Enabled = value; - }); -} - -#ifdef ANDROID -void ConnectionsManager::useJavaVM(JavaVM *vm, bool useJavaByteBuffers) { - javaVm = vm; - - JNIEnv *env = 0; - if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { - DEBUG_E("can't get jnienv"); - exit(1); - } - - if (useJavaByteBuffers) { - jclass_ByteBuffer = (jclass) env->NewGlobalRef(env->FindClass("java/nio/ByteBuffer")); - if (jclass_ByteBuffer == 0) { - DEBUG_E("can't find java ByteBuffer class"); - exit(1); - } - jclass_ByteBuffer_allocateDirect = env->GetStaticMethodID(jclass_ByteBuffer, "allocateDirect", "(I)Ljava/nio/ByteBuffer;"); - if (jclass_ByteBuffer_allocateDirect == 0) { - DEBUG_E("can't find java ByteBuffer allocateDirect"); - exit(1); - } - DEBUG_D("using java ByteBuffer"); - } -} -#endif - -/* - public void applyCountryPortNumber(final String phone) { - if (phone == null || phone.length() == 0) { - return; - } - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - if (phone.startsWith("968")) { - for (HashMap.Entry entry : datacenters.entrySet()) { - Datacenter datacenter = entry.getValue(); - datacenter.overridePort = 8888; - datacenter.suspendConnections(); - } - } else { - for (HashMap.Entry entry : datacenters.entrySet()) { - Datacenter datacenter = entry.getValue(); - datacenter.overridePort = -1; - } - } - } - }); - } -*/ diff --git a/TMessagesProj/jni/tgnet/ConnectionsManager.h b/TMessagesProj/jni/tgnet/ConnectionsManager.h deleted file mode 100644 index ecfad29d1..000000000 --- a/TMessagesProj/jni/tgnet/ConnectionsManager.h +++ /dev/null @@ -1,197 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef CONNECTIONSMANAGER_H -#define CONNECTIONSMANAGER_H - -#include -#include -#include -#include -#include -#include -#include -#include "Defines.h" - -#ifdef ANDROID -#include -#endif - -class NativeByteBuffer; -class Connection; -class Datacenter; -class Request; -class DatacenterHandshake; -class TLObject; -class ConnectionSocket; -class TL_auth_exportedAuthorization; -class ByteArray; -class TL_config; -class EventObject; -class Config; - -class ConnectionsManager { - -public: - ConnectionsManager(); - ~ConnectionsManager(); - - static ConnectionsManager &getInstance(); - int64_t getCurrentTimeMillis(); - int32_t getCurrentTime(); - int32_t getTimeDifference(); - int32_t sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate); - void sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate, int32_t requestToken); - void cancelRequest(int32_t token, bool notifyServer); - void cleanUp(); - void cancelRequestsForGuid(int32_t guid); - void bindRequestToGuid(int32_t requestToken, int32_t guid); - void applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port); - void setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate); - ConnectionState getConnectionState(); - void setUserId(int32_t userId); - void switchBackend(); - void resumeNetwork(bool partial); - void pauseNetwork(); - void setNetworkAvailable(bool value); - void setUseIpv6(bool value); - void init(uint32_t version, int32_t layer, int32_t apiId, std::string deviceModel, std::string systemVersion, std::string appVersion, std::string langCode, std::string configPath, std::string logPath, int32_t userId, bool isPaused, bool enablePushConnection); - void updateDcSettings(uint32_t datacenterId); - void setPushConnectionEnabled(bool value); - -#ifdef ANDROID - void sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate, int32_t requestToken, jobject ptr1, jobject ptr2); - static void useJavaVM(JavaVM *vm, bool useJavaByteBuffers); -#endif - -private: - static void *ThreadProc(void *data); - - void initDatacenters(); - void loadConfig(); - void saveConfig(); - void select(); - void wakeup(); - void processServerResponse(TLObject *message, int64_t messageId, int32_t messageSeqNo, int64_t messageSalt, Connection *connection, int64_t innerMsgId, int64_t containerMessageId); - void sendPing(Datacenter *datacenter, bool usePushConnection); - void sendMessagesToConnection(std::vector> &messages, Connection *connection, bool reportAck); - void sendMessagesToConnectionWithConfirmation(std::vector> &messages, Connection *connection, bool reportAck); - void requestSaltsForDatacenter(Datacenter *datacenter); - void clearRequestsForDatacenter(Datacenter *datacenter); - void registerForInternalPushUpdates(); - void processRequestQueue(uint32_t connectionType, uint32_t datacenterId); - void moveToDatacenter(uint32_t datacenterId); - void authorizeOnMovingDatacenter(); - void authorizedOnMovingDatacenter(); - Datacenter *getDatacenterWithId(uint32_t datacenterId); - std::unique_ptr wrapInLayer(TLObject *object, Datacenter *datacenter, Request *baseRequest); - void removeRequestFromGuid(int32_t requestToken); - void cancelRequestInternal(int32_t token, bool notifyServer, bool removeFromClass); - int callEvents(int64_t now); - - void checkPendingTasks(); - void scheduleTask(std::function task); - void scheduleEvent(EventObject *eventObject, uint32_t time); - void removeEvent(EventObject *eventObject); - void onConnectionClosed(Connection *connection); - void onConnectionConnected(Connection *connection); - void onConnectionQuickAckReceived(Connection *connection, int32_t ack); - void onConnectionDataReceived(Connection *connection, NativeByteBuffer *data, uint32_t length); - void attachConnection(ConnectionSocket *connection); - void detachConnection(ConnectionSocket *connection); - TLObject *TLdeserialize(TLObject *request, uint32_t bytes, NativeByteBuffer *data); - TLObject *getRequestWithMessageId(int64_t messageId); - void onDatacenterHandshakeComplete(Datacenter *datacenter, int32_t timeDiff); - void onDatacenterExportAuthorizationComplete(Datacenter *datacenter); - int64_t generateMessageId(); - bool isIpv6Enabled(); - bool isNetworkAvailable(); - - uint32_t configVersion = 2; - Config *config = nullptr; - - std::list events; - - std::map datacenters; - std::map> quickAckIdToRequestIds; - int32_t pingTime; - bool testBackend = false; - std::atomic lastRequestToken{1}; - uint32_t currentDatacenterId = 0; - uint32_t movingToDatacenterId = DEFAULT_DATACENTER_ID; - int64_t pushSessionId = 0; - int32_t currentPingTime = 0; - bool registeringForPush = false; - int64_t lastPushPingTime = 0; - bool sendingPushPing = false; - bool updatingDcSettings = false; - int32_t updatingDcStartTime = 0; - int32_t lastDcUpdateTime = 0; - int64_t lastPingTime = getCurrentTimeMillis(); - bool networkPaused = false; - int32_t nextSleepTimeout = CONNECTION_BACKGROUND_KEEP_TIME; - int64_t lastPauseTime = 0; - ConnectionState connectionState = ConnectionStateConnecting; - std::unique_ptr movingAuthorization; - std::vector sessionsToDestroy; - int32_t lastDestroySessionRequestTime; - std::map> requestsByGuids; - std::map guidsByRequests; - - pthread_t networkThread; - pthread_mutex_t mutex; - std::queue> pendingTasks; - struct epoll_event *epollEvents; - timespec timeSpec; - int32_t timeDifference = 0; - int64_t lastOutgoingMessageId = 0; - bool networkAvailable = true; - bool ipv6Enabled = false; - std::vector activeConnections; - int epolFd; - int *pipeFd; - NativeByteBuffer *networkBuffer; - - requestsList requestsQueue; - requestsList runningRequests; - std::vector requestingSaltsForDc; - int32_t lastPingId = 0; - - uint32_t currentVersion = 1; - int32_t currentLayer = 34; - int32_t currentApiId = 6; - std::string currentDeviceModel; - std::string currentSystemVersion; - std::string currentAppVersion; - std::string currentLangCode; - std::string currentConfigPath; - std::string currentLogPath; - int32_t currentUserId = 0; - bool registeredForInternalPush = false; - bool pushConnectionEnabled = true; - - ConnectiosManagerDelegate *delegate; - - friend class ConnectionSocket; - friend class ConnectionSession; - friend class Connection; - friend class Timer; - friend class Datacenter; - friend class TL_message; - friend class TL_rpc_result; - friend class Config; -}; - -#ifdef ANDROID -extern JavaVM *javaVm; -extern JNIEnv *jniEnv; -extern jclass jclass_ByteBuffer; -extern jmethodID jclass_ByteBuffer_allocateDirect; -#endif - -#endif diff --git a/TMessagesProj/jni/tgnet/Datacenter.cpp b/TMessagesProj/jni/tgnet/Datacenter.cpp deleted file mode 100644 index fc0cecdd7..000000000 --- a/TMessagesProj/jni/tgnet/Datacenter.cpp +++ /dev/null @@ -1,1593 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "Datacenter.h" -#include "Connection.h" -#include "MTProtoScheme.h" -#include "FileLog.h" -#include "NativeByteBuffer.h" -#include "ByteArray.h" -#include "BuffersStorage.h" -#include "ConnectionsManager.h" -#include "Config.h" - -static std::vector serverPublicKeys; -static std::vector serverPublicKeysFingerprints; -static BN_CTX *bnContext; - -Datacenter::Datacenter(uint32_t id) { - datacenterId = id; - for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { - downloadConnections[a] = nullptr; - } -} - -Datacenter::Datacenter(NativeByteBuffer *data) { - for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { - downloadConnections[a] = nullptr; - } - uint32_t currentVersion = data->readUint32(nullptr); - if (currentVersion >= 2 && currentVersion <= 5) { - datacenterId = data->readUint32(nullptr); - if (currentVersion >= 3) { - lastInitVersion = data->readUint32(nullptr); - } - uint32_t len = data->readUint32(nullptr); - for (uint32_t a = 0; a < len; a++) { - std::string address = data->readString(nullptr); - addressesIpv4.push_back(address); - ports[address] = data->readUint32(nullptr); - } - if (currentVersion >= 5) { - len = data->readUint32(nullptr); - for (uint32_t a = 0; a < len; a++) { - std::string address = data->readString(nullptr); - addressesIpv6.push_back(address); - ports[address] = data->readUint32(nullptr); - } - len = data->readUint32(nullptr); - for (uint32_t a = 0; a < len; a++) { - std::string address = data->readString(nullptr); - addressesIpv4Download.push_back(address); - ports[address] = data->readUint32(nullptr); - } - len = data->readUint32(nullptr); - for (uint32_t a = 0; a < len; a++) { - std::string address = data->readString(nullptr); - addressesIpv6Download.push_back(address); - ports[address] = data->readUint32(nullptr); - } - } - len = data->readUint32(nullptr); - if (len != 0) { - authKey = data->readBytes(len, nullptr); - } - if (currentVersion >= 4) { - authKeyId = data->readInt64(nullptr); - } else { - len = data->readUint32(nullptr); - if (len != 0) { - authKeyId = data->readInt64(nullptr); - } - } - authorized = data->readInt32(nullptr) != 0; - len = data->readUint32(nullptr); - for (uint32_t a = 0; a < len; a++) { - TL_future_salt *salt = new TL_future_salt(); - salt->valid_since = data->readInt32(nullptr); - salt->valid_until = data->readInt32(nullptr); - salt->salt = data->readInt64(nullptr); - serverSalts.push_back(std::unique_ptr(salt)); - } - } - - if (config == nullptr) { - config = new Config("dc" + to_string_int32(datacenterId) + "conf.dat"); - } - NativeByteBuffer *buffer = config->readConfig(); - if (buffer != nullptr) { - uint32_t version = buffer->readUint32(nullptr); - if (version <= paramsConfigVersion) { - currentPortNumIpv4 = buffer->readUint32(nullptr); - currentAddressNumIpv4 = buffer->readUint32(nullptr); - currentPortNumIpv6 = buffer->readUint32(nullptr); - currentAddressNumIpv6 = buffer->readUint32(nullptr); - currentPortNumIpv4Download = buffer->readUint32(nullptr); - currentAddressNumIpv4Download = buffer->readUint32(nullptr); - currentPortNumIpv6Download = buffer->readUint32(nullptr); - currentAddressNumIpv6Download = buffer->readUint32(nullptr); - } - buffer->reuse(); - } else { - currentPortNumIpv4 = 0; - currentAddressNumIpv4 = 0; - currentPortNumIpv6 = 0; - currentAddressNumIpv6 = 0; - currentPortNumIpv4Download = 0; - currentAddressNumIpv4Download = 0; - currentPortNumIpv6Download = 0; - currentAddressNumIpv6Download = 0; - } -} - -void Datacenter::switchTo443Port() { - for (uint32_t a = 0; a < addressesIpv4.size(); a++) { - if (ports[addressesIpv4[a]] == 443) { - currentAddressNumIpv4 = a; - currentPortNumIpv4 = 0; - break; - } - } - for (uint32_t a = 0; a < addressesIpv6.size(); a++) { - if (ports[addressesIpv6[a]] == 443) { - currentAddressNumIpv6 = a; - currentPortNumIpv6 = 0; - break; - } - } - for (uint32_t a = 0; a < addressesIpv4Download.size(); a++) { - if (ports[addressesIpv4Download[a]] == 443) { - currentAddressNumIpv4Download = a; - currentPortNumIpv4Download = 0; - break; - } - } - for (uint32_t a = 0; a < addressesIpv6Download.size(); a++) { - if (ports[addressesIpv6Download[a]] == 443) { - currentAddressNumIpv6Download = a; - currentPortNumIpv6Download = 0; - break; - } - } -} - -std::string Datacenter::getCurrentAddress(uint32_t flags) { - uint32_t currentAddressNum; - std::vector *addresses; - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - currentAddressNum = currentAddressNumIpv6Download; - addresses = &addressesIpv6Download; - } else { - currentAddressNum = currentAddressNumIpv4Download; - addresses = &addressesIpv4Download; - } - } else { - if ((flags & 1) != 0) { - currentAddressNum = currentAddressNumIpv6; - addresses = &addressesIpv6; - } else { - currentAddressNum = currentAddressNumIpv4; - addresses = &addressesIpv4; - } - } - if (addresses->empty()) { - return std::string(""); - } - if (currentAddressNum >= addresses->size()) { - currentAddressNum = 0; - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - currentAddressNumIpv6Download = currentAddressNum; - } else { - currentAddressNumIpv4Download = currentAddressNum; - } - } else { - if ((flags & 1) != 0) { - currentAddressNumIpv6 = currentAddressNum; - } else { - currentAddressNumIpv4 = currentAddressNum; - } - } - } - return (*addresses)[currentAddressNum]; -} - -int32_t Datacenter::getCurrentPort(uint32_t flags) { - if (ports.empty()) { - return overridePort == -1 ? 443 : overridePort; - } - - const int32_t *portsArray = overridePort == 8888 ? defaultPorts8888 : defaultPorts; - - uint32_t currentPortNum; - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - currentPortNum = currentPortNumIpv6Download; - } else { - currentPortNum = currentPortNumIpv4Download; - } - } else { - if ((flags & 1) != 0) { - currentPortNum = currentPortNumIpv6; - } else { - currentPortNum = currentPortNumIpv4; - } - } - - if (currentPortNum >= 11) { - currentPortNum = 0; - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - currentPortNumIpv6Download = currentPortNum; - } else { - currentPortNumIpv4Download = currentPortNum; - } - } else { - if ((flags & 1) != 0) { - currentPortNumIpv6 = currentPortNum; - } else { - currentPortNumIpv4 = currentPortNum; - } - } - } - int32_t port = portsArray[currentPortNum]; - if (port == -1) { - if (overridePort != -1) { - return overridePort; - } - std::string address = getCurrentAddress(flags); - return ports[address]; - } - return port; -} - -void Datacenter::addAddressAndPort(std::string address, uint32_t port, uint32_t flags) { - std::vector *addresses; - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - addresses = &addressesIpv6Download; - } else { - addresses = &addressesIpv4Download; - } - } else { - if ((flags & 1) != 0) { - addresses = &addressesIpv6; - } else { - addresses = &addressesIpv4; - } - } - if (std::find(addresses->begin(), addresses->end(), address) != addresses->end()) { - return; - } - addresses->push_back(address); - ports[address] = port; -} - -void Datacenter::nextAddressOrPort(uint32_t flags) { - uint32_t currentPortNum; - uint32_t currentAddressNum; - std::vector *addresses; - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - currentPortNum = currentPortNumIpv6Download; - currentAddressNum = currentAddressNumIpv6Download; - addresses = &addressesIpv6Download; - } else { - currentPortNum = currentPortNumIpv4Download; - currentAddressNum = currentAddressNumIpv4Download; - addresses = &addressesIpv4Download; - } - } else { - if ((flags & 1) != 0) { - currentPortNum = currentPortNumIpv6; - currentAddressNum = currentAddressNumIpv6; - addresses = &addressesIpv6; - } else { - currentPortNum = currentPortNumIpv4; - currentAddressNum = currentAddressNumIpv4; - addresses = &addressesIpv4; - } - } - if (currentPortNum + 1 < 11) { - currentPortNum++; - } else { - if (currentAddressNum + 1 < addresses->size()) { - currentAddressNum++; - } else { - currentAddressNum = 0; - } - currentPortNum = 0; - } - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - currentPortNumIpv6Download = currentPortNum; - currentAddressNumIpv6Download = currentAddressNum; - } else { - currentPortNumIpv4Download = currentPortNum; - currentAddressNumIpv4Download = currentAddressNum; - } - } else { - if ((flags & 1) != 0) { - currentPortNumIpv6 = currentPortNum; - currentAddressNumIpv6 = currentAddressNum; - } else { - currentPortNumIpv4 = currentPortNum; - currentAddressNumIpv4 = currentAddressNum; - } - } -} - -void Datacenter::storeCurrentAddressAndPortNum() { - if (config == nullptr) { - config = new Config("dc" + to_string_int32(datacenterId) + "conf.dat"); - } - NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(128); - buffer->writeInt32(paramsConfigVersion); - buffer->writeInt32(currentPortNumIpv4); - buffer->writeInt32(currentAddressNumIpv4); - buffer->writeInt32(currentPortNumIpv6); - buffer->writeInt32(currentAddressNumIpv6); - buffer->writeInt32(currentPortNumIpv4Download); - buffer->writeInt32(currentAddressNumIpv4Download); - buffer->writeInt32(currentPortNumIpv6Download); - buffer->writeInt32(currentAddressNumIpv6Download); - config->writeConfig(buffer); - buffer->reuse(); -} - -void Datacenter::replaceAddressesAndPorts(std::vector &newAddresses, std::map &newPorts, uint32_t flags) { - std::vector *addresses; - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - addresses = &addressesIpv6Download; - } else { - addresses = &addressesIpv4Download; - } - } else { - if ((flags & 1) != 0) { - addresses = &addressesIpv6; - } else { - addresses = &addressesIpv4; - } - } - size_t size = addresses->size(); - for (uint32_t a = 0; a < size; a++) { - std::map::iterator iter = ports.find((*addresses)[a]); - if (iter != ports.end()) { - ports.erase(iter); - } - } - if ((flags & 2) != 0) { - if ((flags & 1) != 0) { - addressesIpv6Download = newAddresses; - } else { - addressesIpv4Download = newAddresses; - } - } else { - if ((flags & 1) != 0) { - addressesIpv6 = newAddresses; - } else { - addressesIpv4 = newAddresses; - } - } - ports.insert(newPorts.begin(), newPorts.end()); -} - -void Datacenter::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(configVersion); - stream->writeInt32(datacenterId); - stream->writeInt32(lastInitVersion); - size_t size; - stream->writeInt32((int32_t) (size = addressesIpv4.size())); - for (uint32_t a = 0; a < size; a++) { - stream->writeString(addressesIpv4[a]); - stream->writeInt32(ports[addressesIpv4[a]]); - } - stream->writeInt32((int32_t) (size = addressesIpv6.size())); - for (uint32_t a = 0; a < size; a++) { - stream->writeString(addressesIpv6[a]); - stream->writeInt32(ports[addressesIpv6[a]]); - } - stream->writeInt32((int32_t) (size = addressesIpv4Download.size())); - for (uint32_t a = 0; a < size; a++) { - stream->writeString(addressesIpv4Download[a]); - stream->writeInt32(ports[addressesIpv4Download[a]]); - } - stream->writeInt32((int32_t) (size = addressesIpv6Download.size())); - for (uint32_t a = 0; a < size; a++) { - stream->writeString(addressesIpv6Download[a]); - stream->writeInt32(ports[addressesIpv6Download[a]]); - } - if (authKey != nullptr) { - stream->writeInt32(authKey->length); - stream->writeBytes(authKey); - } else { - stream->writeInt32(0); - } - stream->writeInt64(authKeyId); - stream->writeInt32(authorized ? 1 : 0); - stream->writeInt32((int32_t) (size = serverSalts.size())); - for (uint32_t a = 0; a < size; a++) { - stream->writeInt32(serverSalts[a]->valid_since); - stream->writeInt32(serverSalts[a]->valid_until); - stream->writeInt64(serverSalts[a]->salt); - } -} - -void Datacenter::clear() { - authKey = nullptr; - authKeyId = 0; - authorized = false; - serverSalts.clear(); -} - -void Datacenter::clearServerSalts() { - serverSalts.clear(); -} - -int64_t Datacenter::getServerSalt() { - int32_t date = ConnectionsManager::getInstance().getCurrentTime(); - - bool cleanupNeeded = false; - - int64_t result = 0; - int32_t maxRemainingInterval = 0; - - size_t size = serverSalts.size(); - for (uint32_t a = 0; a < size; a++) { - TL_future_salt *salt = serverSalts[a].get(); - if (salt->valid_until < date) { - cleanupNeeded = true; - } else if (salt->valid_since <= date && salt->valid_until > date) { - if (maxRemainingInterval == 0 || abs(salt->valid_until - date) > maxRemainingInterval) { - maxRemainingInterval = abs(salt->valid_until - date); - result = salt->salt; - } - } - } - - if (cleanupNeeded) { - size = serverSalts.size(); - for (uint32_t i = 0; i < size; i++) { - if (serverSalts[i]->valid_until < date) { - serverSalts.erase(serverSalts.begin() + i); - size--; - i--; - } - } - } - - if (result == 0) { - DEBUG_D("dc%u valid salt not found", datacenterId); - } - - return result; -} - -void Datacenter::mergeServerSalts(std::vector> &salts) { - if (salts.empty()) { - return; - } - int32_t date = ConnectionsManager::getInstance().getCurrentTime(); - std::vector existingSalts(serverSalts.size()); - size_t size = serverSalts.size(); - for (uint32_t a = 0; a < size; a++) { - existingSalts.push_back(serverSalts[a]->salt); - } - bool added = false; - size = salts.size(); - for (uint32_t a = 0; a < size; a++) { - int64_t value = salts[a]->salt; - if (std::find(existingSalts.begin(), existingSalts.end(), value) == existingSalts.end() && salts[a]->valid_until > date) { - serverSalts.push_back(std::unique_ptr(std::move(salts[a]))); - added = true; - } - } - if (added) { - std::sort(serverSalts.begin(), serverSalts.end(), [](const std::unique_ptr &x, const std::unique_ptr &y) { return x->valid_since < y->valid_since; }); - } -} - -void Datacenter::addServerSalt(std::unique_ptr &serverSalt) { - size_t size = serverSalts.size(); - for (uint32_t a = 0; a < size; a++) { - if (serverSalts[a]->salt == serverSalt->salt) { - return; - } - } - serverSalts.push_back(std::move(serverSalt)); - std::sort(serverSalts.begin(), serverSalts.end(), [](const std::unique_ptr &x, const std::unique_ptr &y) { return x->valid_since < y->valid_since; }); -} - -bool Datacenter::containsServerSalt(int64_t value) { - size_t size = serverSalts.size(); - for (uint32_t a = 0; a < size; a++) { - if (serverSalts[a]->salt == value) { - return true; - } - } - return false; -} - -void Datacenter::suspendConnections() { - if (genericConnection != nullptr) { - genericConnection->suspendConnection(); - } - if (uploadConnection != nullptr) { - uploadConnection->suspendConnection(); - } - for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { - if (downloadConnections[a] != nullptr) { - downloadConnections[a]->suspendConnection(); - } - } -} - -void Datacenter::getSessions(std::vector &sessions) { - if (genericConnection != nullptr) { - sessions.push_back(genericConnection->getSissionId()); - } - if (uploadConnection != nullptr) { - sessions.push_back(uploadConnection->getSissionId()); - } - for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { - if (downloadConnections[a] != nullptr) { - sessions.push_back(downloadConnections[a]->getSissionId()); - } - } -} - -void Datacenter::recreateSessions() { - if (genericConnection != nullptr) { - genericConnection->recreateSession(); - } - if (uploadConnection != nullptr) { - uploadConnection->recreateSession(); - } - for (uint32_t a = 0; a < DOWNLOAD_CONNECTIONS_COUNT; a++) { - if (downloadConnections[a] != nullptr) { - downloadConnections[a]->recreateSession(); - } - } -} - -Connection *Datacenter::createDownloadConnection(uint32_t num) { - if (downloadConnections[num] == nullptr) { - downloadConnections[num] = new Connection(this, ConnectionTypeDownload); - } - return downloadConnections[num]; -} - -Connection *Datacenter::createUploadConnection() { - if (uploadConnection == nullptr) { - uploadConnection = new Connection(this, ConnectionTypeUpload); - } - return uploadConnection; -} - -Connection *Datacenter::createGenericConnection() { - if (genericConnection == nullptr) { - genericConnection = new Connection(this, ConnectionTypeGeneric); - } - return genericConnection; -} - -Connection *Datacenter::createPushConnection() { - if (pushConnection == nullptr) { - pushConnection = new Connection(this, ConnectionTypePush); - } - return pushConnection; -} - -uint32_t Datacenter::getDatacenterId() { - return datacenterId; -} - -bool Datacenter::isHandshaking() { - return handshakeState != 0; -} - -void Datacenter::beginHandshake(bool reconnect) { - DEBUG_D("dc%u handshake: begin", datacenterId); - cleanupHandshake(); - createGenericConnection()->recreateSession(); - handshakeState = 1; - - if (reconnect) { - createGenericConnection()->suspendConnection(); - createGenericConnection()->connect(); - } - - TL_req_pq *request = new TL_req_pq(); - request->nonce = std::unique_ptr(new ByteArray(16)); - RAND_bytes(request->nonce->bytes, 16); - authNonce = new ByteArray(request->nonce.get()); - sendRequestData(request, true); -} - -void Datacenter::cleanupHandshake() { - handshakeState = 0; - if (handshakeRequest != nullptr) { - delete handshakeRequest; - handshakeRequest = nullptr; - } - if (handshakeServerSalt != nullptr) { - delete handshakeServerSalt; - handshakeServerSalt = nullptr; - } - if (authNonce != nullptr) { - delete authNonce; - authNonce = nullptr; - } - if (authServerNonce != nullptr) { - delete authServerNonce; - authServerNonce = nullptr; - } - if (authNewNonce != nullptr) { - delete authNewNonce; - authNewNonce = nullptr; - } - if (handshakeAuthKey != nullptr) { - delete handshakeAuthKey; - handshakeAuthKey = nullptr; - } -} - -void Datacenter::sendRequestData(TLObject *object, bool important) { - uint32_t messageLength = object->getObjectSize(); - NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(20 + messageLength); - buffer->writeInt64(0); - buffer->writeInt64(ConnectionsManager::getInstance().generateMessageId()); - buffer->writeInt32(messageLength); - object->serializeToStream(buffer); - createGenericConnection()->sendData(buffer, false); - if (important) { - if (handshakeRequest != object) { - if (handshakeRequest != nullptr) { - delete handshakeRequest; - } - handshakeRequest = object; - } - } else { - delete object; - } -} - -void Datacenter::onHandshakeConnectionClosed(Connection *connection) { - if (handshakeState == 0) { - return; - } - needResendData = true; -} - -void Datacenter::onHandshakeConnectionConnected(Connection *connection) { - if (handshakeState == 0 || !needResendData) { - return; - } - beginHandshake(false); -} - -inline uint64_t gcd(uint64_t a, uint64_t b) { - while (a != 0 && b != 0) { - while ((b & 1) == 0) { - b >>= 1; - } - while ((a & 1) == 0) { - a >>= 1; - } - if (a > b) { - a -= b; - } else { - b -= a; - } - } - return b == 0 ? a : b; -} - -inline bool factorizeValue(uint64_t what, uint32_t &p, uint32_t &q) { - int32_t it = 0, i, j; - uint64_t g = 0; - for (i = 0; i < 3 || it < 1000; i++) { - uint64_t t = ((lrand48() & 15) + 17) % what; - uint64_t x = (long long) lrand48() % (what - 1) + 1, y = x; - int32_t lim = 1 << (i + 18); - for (j = 1; j < lim; j++) { - ++it; - uint64_t a = x, b = x, c = t; - while (b) { - if (b & 1) { - c += a; - if (c >= what) { - c -= what; - } - } - a += a; - if (a >= what) { - a -= what; - } - b >>= 1; - } - x = c; - uint64_t z = x < y ? what + x - y : x - y; - g = gcd(z, what); - if (g != 1) { - break; - } - if (!(j & (j - 1))) { - y = x; - } - } - if (g > 1 && g < what) { - break; - } - } - - if (g > 1 && g < what) { - p = (uint32_t) g; - q = (uint32_t) (what / g); - if (p > q) { - uint32_t tmp = p; - p = q; - q = tmp; - } - return true; - } else { - DEBUG_E("factorization failed for %llu", what); - p = 0; - q = 0; - return false; - } -} - -inline bool check_prime(BIGNUM *p) { - switch (BN_is_prime_fasttest_ex(p, BN_prime_checks, bnContext, 0, NULL)) { - case 1: - return 1; - case 0: - return 0; - default: - DEBUG_E("OpenSSL error at BN_is_prime_fasttest_ex"); - return 0; - } -} - -inline bool isGoodPrime(BIGNUM *p, uint32_t g) { - //TODO check against known good primes - if (g < 2 || g > 7 || BN_num_bits(p) != 2048) { - return false; - } - - BIGNUM *t = BN_new(); - BIGNUM *dh_g = BN_new(); - - if (!BN_set_word(dh_g, 4 * g)) { - DEBUG_E("OpenSSL error at BN_set_word(dh_g, 4 * g)"); - BN_free(t); - BN_free(dh_g); - return false; - } - if (!BN_mod(t, p, dh_g, bnContext)) { - DEBUG_E("OpenSSL error at BN_mod"); - BN_free(t); - BN_free(dh_g); - return false; - } - uint64_t x = BN_get_word(t); - if (x >= 4 * g) { - DEBUG_E("OpenSSL error at BN_get_word"); - BN_free(t); - BN_free(dh_g); - return false; - } - - BN_free(dh_g); - - bool result = true; - switch (g) { - case 2: - if (x != 7) { - result = false; - } - break; - case 3: - if (x % 3 != 2) { - result = false; - } - break; - case 5: - if (x % 5 != 1 && x % 5 != 4) { - result = false; - } - break; - case 6: - if (x != 19 && x != 23) { - result = false; - } - break; - case 7: - if (x % 7 != 3 && x % 7 != 5 && x % 7 != 6) { - result = false; - } - break; - default: - break; - } - - char *prime = BN_bn2hex(p); - static const char *goodPrime = "c71caeb9c6b1c9048e6c522f70f13f73980d40238e3e21c14934d037563d930f48198a0aa7c14058229493d22530f4dbfa336f6e0ac925139543aed44cce7c3720fd51f69458705ac68cd4fe6b6b13abdc9746512969328454f18faf8c595f642477fe96bb2a941d5bcd1d4ac8cc49880708fa9b378e3c4f3a9060bee67cf9a4a4a695811051907e162753b56b0f6b410dba74d8a84b2a14b3144e0ef1284754fd17ed950d5965b4b9dd46582db1178d169c6bc465b0d6ff9ca3928fef5b9ae4e418fc15e83ebea0f87fa9ff5eed70050ded2849f47bf959d956850ce929851f0d8115f635b105ee2e4e15d04b2454bf6f4fadf034b10403119cd8e3b92fcc5b"; - if (!strcasecmp(prime, goodPrime)) { - delete [] prime; - BN_free(t); - return true; - } - delete [] prime; - - if (!result || !check_prime(p)) { - BN_free(t); - return false; - } - - BIGNUM *b = BN_new(); - if (!BN_set_word(b, 2)) { - DEBUG_E("OpenSSL error at BN_set_word(b, 2)"); - BN_free(b); - BN_free(t); - return false; - } - if (!BN_div(t, 0, p, b, bnContext)) { - DEBUG_E("OpenSSL error at BN_div"); - BN_free(b); - BN_free(t); - return false; - } - if (!check_prime(t)) { - result = false; - } - BN_free(b); - BN_free(t); - return result; -} - -inline bool isGoodGaAndGb(BIGNUM *g_a, BIGNUM *p) { - if (BN_num_bytes(g_a) > 256 || BN_num_bits(g_a) < 2048 - 64 || BN_cmp(p, g_a) <= 0) { - return false; - } - BIGNUM *dif = BN_new(); - BN_sub(dif, p, g_a); - if (BN_num_bits(dif) < 2048 - 64) { - BN_free(dif); - return false; - } - BN_free(dif); - return true; -} - -void Datacenter::aesIgeEncryption(uint8_t *buffer, uint8_t *key, uint8_t *iv, bool encrypt, bool changeIv, uint32_t length) { - uint8_t *ivBytes = iv; - if (!changeIv) { - ivBytes = new uint8_t[32]; - memcpy(ivBytes, iv, 32); - } - AES_KEY akey; - if (!encrypt) { - AES_set_decrypt_key(key, 32 * 8, &akey); - AES_ige_encrypt(buffer, buffer, length, &akey, ivBytes, AES_DECRYPT); - } else { - AES_set_encrypt_key(key, 32 * 8, &akey); - AES_ige_encrypt(buffer, buffer, length, &akey, ivBytes, AES_ENCRYPT); - } - if (!changeIv) { - delete [] ivBytes; - } -} - -int32_t Datacenter::selectPublicKey(std::vector &fingerprints) { - if (serverPublicKeys.empty()) { - serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" - "MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6\n" - "lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS\n" - "an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw\n" - "Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+\n" - "8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n\n" - "Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB\n" - "-----END RSA PUBLIC KEY-----"); - serverPublicKeysFingerprints.push_back(0xc3b42b026ce86b21LL); - - serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" - "MIIBCgKCAQEAxq7aeLAqJR20tkQQMfRn+ocfrtMlJsQ2Uksfs7Xcoo77jAid0bRt\n" - "ksiVmT2HEIJUlRxfABoPBV8wY9zRTUMaMA654pUX41mhyVN+XoerGxFvrs9dF1Ru\n" - "vCHbI02dM2ppPvyytvvMoefRoL5BTcpAihFgm5xCaakgsJ/tH5oVl74CdhQw8J5L\n" - "xI/K++KJBUyZ26Uba1632cOiq05JBUW0Z2vWIOk4BLysk7+U9z+SxynKiZR3/xdi\n" - "XvFKk01R3BHV+GUKM2RYazpS/P8v7eyKhAbKxOdRcFpHLlVwfjyM1VlDQrEZxsMp\n" - "NTLYXb6Sce1Uov0YtNx5wEowlREH1WOTlwIDAQAB\n" - "-----END RSA PUBLIC KEY-----"); - serverPublicKeysFingerprints.push_back(0x9a996a1db11c729bLL); - - serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" - "MIIBCgKCAQEAsQZnSWVZNfClk29RcDTJQ76n8zZaiTGuUsi8sUhW8AS4PSbPKDm+\n" - "DyJgdHDWdIF3HBzl7DHeFrILuqTs0vfS7Pa2NW8nUBwiaYQmPtwEa4n7bTmBVGsB\n" - "1700/tz8wQWOLUlL2nMv+BPlDhxq4kmJCyJfgrIrHlX8sGPcPA4Y6Rwo0MSqYn3s\n" - "g1Pu5gOKlaT9HKmE6wn5Sut6IiBjWozrRQ6n5h2RXNtO7O2qCDqjgB2vBxhV7B+z\n" - "hRbLbCmW0tYMDsvPpX5M8fsO05svN+lKtCAuz1leFns8piZpptpSCFn7bWxiA9/f\n" - "x5x17D7pfah3Sy2pA+NDXyzSlGcKdaUmwQIDAQAB\n" - "-----END RSA PUBLIC KEY-----"); - serverPublicKeysFingerprints.push_back(0xb05b2a6f70cdea78LL); - - serverPublicKeys.push_back("-----BEGIN RSA PUBLIC KEY-----\n" - "MIIBCgKCAQEAwqjFW0pi4reKGbkc9pK83Eunwj/k0G8ZTioMMPbZmW99GivMibwa\n" - "xDM9RDWabEMyUtGoQC2ZcDeLWRK3W8jMP6dnEKAlvLkDLfC4fXYHzFO5KHEqF06i\n" - "qAqBdmI1iBGdQv/OQCBcbXIWCGDY2AsiqLhlGQfPOI7/vvKc188rTriocgUtoTUc\n" - "/n/sIUzkgwTqRyvWYynWARWzQg0I9olLBBC2q5RQJJlnYXZwyTL3y9tdb7zOHkks\n" - "WV9IMQmZmyZh/N7sMbGWQpt4NMchGpPGeJ2e5gHBjDnlIf2p1yZOYeUYrdbwcS0t\n" - "UiggS4UeE8TzIuXFQxw7fzEIlmhIaq3FnwIDAQAB\n" - "-----END RSA PUBLIC KEY-----"); - serverPublicKeysFingerprints.push_back(0x71e025b6c76033e3LL); - } - - size_t count1 = fingerprints.size(); - size_t count2 = serverPublicKeysFingerprints.size(); - for (uint32_t a = 0; a < count1; a++) { - for (uint32_t b = 0; b < count2; b++) { - if ((uint64_t) fingerprints[a] == serverPublicKeysFingerprints[b]) { - return b; - } - } - } - return -1; -} - -void Datacenter::processHandshakeResponse(TLObject *message, int64_t messageId) { - if (handshakeState == 0) { - return; - } - const std::type_info &typeInfo = typeid(*message); - if (typeInfo == typeid(TL_resPQ)) { - if (handshakeState != 1) { - sendAckRequest(messageId); - return; - } - - handshakeState = 2; - TL_resPQ *result = (TL_resPQ *) message; - if (authNonce->isEqualTo(result->nonce.get())) { - int32_t keyIndex = selectPublicKey(result->server_public_key_fingerprints); - if (keyIndex < 0) { - DEBUG_E("dc%u handshake: can't find valid server public key", datacenterId); - beginHandshake(false); - return; - } - - authServerNonce = new ByteArray(result->server_nonce.get()); - - //TODO run in different thread? - uint64_t pq = ((uint64_t) (result->pq->bytes[0] & 0xff) << 56) | - ((uint64_t) (result->pq->bytes[1] & 0xff) << 48) | - ((uint64_t) (result->pq->bytes[2] & 0xff) << 40) | - ((uint64_t) (result->pq->bytes[3] & 0xff) << 32) | - ((uint64_t) (result->pq->bytes[4] & 0xff) << 24) | - ((uint64_t) (result->pq->bytes[5] & 0xff) << 16) | - ((uint64_t) (result->pq->bytes[6] & 0xff) << 8) | - ((uint64_t) (result->pq->bytes[7] & 0xff)); - uint32_t p, q; - if (!factorizeValue(pq, p, q)) { - beginHandshake(false); - return; - } - - TL_req_DH_params *request = new TL_req_DH_params(); - request->nonce = std::unique_ptr(new ByteArray(authNonce)); - request->server_nonce = std::unique_ptr(new ByteArray(authServerNonce)); - request->p = std::unique_ptr(new ByteArray(4)); - request->p->bytes[3] = (uint8_t) p; - request->p->bytes[2] = (uint8_t) (p >> 8); - request->p->bytes[1] = (uint8_t) (p >> 16); - request->p->bytes[0] = (uint8_t) (p >> 24); - request->q = std::unique_ptr(new ByteArray(4)); - request->q->bytes[3] = (uint8_t) q; - request->q->bytes[2] = (uint8_t) (q >> 8); - request->q->bytes[1] = (uint8_t) (q >> 16); - request->q->bytes[0] = (uint8_t) (q >> 24); - request->public_key_fingerprint = (int64_t) serverPublicKeysFingerprints[keyIndex]; - - TL_p_q_inner_data *innerData = new TL_p_q_inner_data(); - innerData->nonce = std::unique_ptr(new ByteArray(authNonce)); - innerData->server_nonce = std::unique_ptr(new ByteArray(authServerNonce)); - innerData->pq = std::unique_ptr(new ByteArray(result->pq.get())); - innerData->p = std::unique_ptr(new ByteArray(request->p.get())); - innerData->q = std::unique_ptr(new ByteArray(request->q.get())); - innerData->new_nonce = std::unique_ptr(new ByteArray(32)); - RAND_bytes(innerData->new_nonce->bytes, 32); - authNewNonce = new ByteArray(innerData->new_nonce.get()); - - uint32_t innerDataSize = innerData->getObjectSize(); - uint32_t additionalSize = innerDataSize + SHA_DIGEST_LENGTH < 255 ? 255 - (innerDataSize + SHA_DIGEST_LENGTH) : 0; - NativeByteBuffer *innerDataBuffer = BuffersStorage::getInstance().getFreeBuffer(innerDataSize + additionalSize + SHA_DIGEST_LENGTH); - innerDataBuffer->position(SHA_DIGEST_LENGTH); - innerData->serializeToStream(innerDataBuffer); - delete innerData; - - SHA1(innerDataBuffer->bytes() + SHA_DIGEST_LENGTH, innerDataSize, innerDataBuffer->bytes()); - if (additionalSize != 0) { - RAND_bytes(innerDataBuffer->bytes() + SHA_DIGEST_LENGTH + innerDataSize, additionalSize); - } - - std::string &key = serverPublicKeys[keyIndex]; - - BIO *keyBio = BIO_new(BIO_s_mem()); - BIO_write(keyBio, key.c_str(), (int) key.length()); - RSA *rsaKey = PEM_read_bio_RSAPublicKey(keyBio, NULL, NULL, NULL); - BIO_free(keyBio); - if (bnContext == nullptr) { - bnContext = BN_CTX_new(); - } - BIGNUM *a = BN_bin2bn(innerDataBuffer->bytes(), innerDataBuffer->limit(), NULL); - BIGNUM *r = BN_new(); - BN_mod_exp(r, a, rsaKey->e, rsaKey->n, bnContext); - uint32_t size = BN_num_bytes(r); - ByteArray *rsaEncryptedData = new ByteArray(size >= 256 ? size : 256); - size_t resLen = BN_bn2bin(r, rsaEncryptedData->bytes); - if (256 - resLen > 0) { - memset(rsaEncryptedData + resLen, 0, 256 - resLen); - } - BN_free(a); - BN_free(r); - RSA_free(rsaKey); - innerDataBuffer->reuse(); - - request->encrypted_data = std::unique_ptr(rsaEncryptedData); - - sendAckRequest(messageId); - sendRequestData(request, true); - } else { - DEBUG_E("dc%u handshake: invalid client nonce", datacenterId); - beginHandshake(false); - } - } else if (dynamic_cast(message)) { - if (typeInfo == typeid(TL_server_DH_params_ok)) { - if (handshakeState != 2) { - sendAckRequest(messageId); - return; - } - - handshakeState = 3; - - TL_server_DH_params_ok *result = (TL_server_DH_params_ok *) message; - - NativeByteBuffer *tmpAesKeyAndIv = BuffersStorage::getInstance().getFreeBuffer(84); - - NativeByteBuffer *newNonceAndServerNonce = BuffersStorage::getInstance().getFreeBuffer(authNewNonce->length + authServerNonce->length); - newNonceAndServerNonce->writeBytes(authNewNonce); - newNonceAndServerNonce->writeBytes(authServerNonce); - SHA1(newNonceAndServerNonce->bytes(), newNonceAndServerNonce->limit(), tmpAesKeyAndIv->bytes()); - newNonceAndServerNonce->reuse(); - - NativeByteBuffer *serverNonceAndNewNonce = BuffersStorage::getInstance().getFreeBuffer(authServerNonce->length + authNewNonce->length); - serverNonceAndNewNonce->writeBytes(authServerNonce); - serverNonceAndNewNonce->writeBytes(authNewNonce); - SHA1(serverNonceAndNewNonce->bytes(), serverNonceAndNewNonce->limit(), tmpAesKeyAndIv->bytes() + 20); - serverNonceAndNewNonce->reuse(); - - NativeByteBuffer *newNonceAndNewNonce = BuffersStorage::getInstance().getFreeBuffer(authNewNonce->length + authNewNonce->length); - newNonceAndNewNonce->writeBytes(authNewNonce); - newNonceAndNewNonce->writeBytes(authNewNonce); - SHA1(newNonceAndNewNonce->bytes(), newNonceAndNewNonce->limit(), tmpAesKeyAndIv->bytes() + 40); - newNonceAndNewNonce->reuse(); - - memcpy(tmpAesKeyAndIv->bytes() + 60, authNewNonce->bytes, 4); - aesIgeEncryption(result->encrypted_answer->bytes, tmpAesKeyAndIv->bytes(), tmpAesKeyAndIv->bytes() + 32, false, false, result->encrypted_answer->length); - - bool hashVerified = false; - for (uint32_t i = 0; i < 16; i++) { - SHA1(result->encrypted_answer->bytes + SHA_DIGEST_LENGTH, result->encrypted_answer->length - i - SHA_DIGEST_LENGTH, tmpAesKeyAndIv->bytes() + 64); - if (!memcmp(tmpAesKeyAndIv->bytes() + 64, result->encrypted_answer->bytes, SHA_DIGEST_LENGTH)) { - hashVerified = true; - break; - } - } - - if (!hashVerified) { - DEBUG_E("dc%u handshake: can't decode DH params", datacenterId); - beginHandshake(false); - return; - } - - bool error = false; - NativeByteBuffer *answerWithHash = new NativeByteBuffer(result->encrypted_answer->bytes + SHA_DIGEST_LENGTH, result->encrypted_answer->length - SHA_DIGEST_LENGTH); - uint32_t constructor = answerWithHash->readUint32(&error); - TL_server_DH_inner_data *dhInnerData = TL_server_DH_inner_data::TLdeserialize(answerWithHash, constructor, error); - delete answerWithHash; - - if (error) { - DEBUG_E("dc%u handshake: can't parse decoded DH params", datacenterId); - beginHandshake(false); - return; - } - - if (!authNonce->isEqualTo(dhInnerData->nonce.get())) { - DEBUG_E("dc%u handshake: invalid DH nonce", datacenterId); - beginHandshake(false); - return; - } - - if (!authServerNonce->isEqualTo(dhInnerData->server_nonce.get())) { - DEBUG_E("dc%u handshake: invalid DH server nonce", datacenterId); - beginHandshake(false); - return; - } - - BIGNUM *p = BN_bin2bn(dhInnerData->dh_prime->bytes, dhInnerData->dh_prime->length, NULL); - if (p == nullptr) { - DEBUG_E("can't allocate BIGNUM p"); - exit(1); - } - if (!isGoodPrime(p, dhInnerData->g)) { - DEBUG_E("dc%u handshake: bad prime", datacenterId); - beginHandshake(false); - BN_free(p); - return; - } - - BIGNUM *g_a = BN_new(); - if (g_a == nullptr) { - DEBUG_E("can't allocate BIGNUM g_a"); - exit(1); - } - BN_bin2bn(dhInnerData->g_a->bytes, dhInnerData->g_a->length, g_a); - if (!isGoodGaAndGb(g_a, p)) { - DEBUG_E("dc%u handshake: bad prime and g_a", datacenterId); - beginHandshake(false); - BN_free(p); - BN_free(g_a); - return; - } - - BIGNUM *g = BN_new(); - if (g == nullptr) { - DEBUG_E("can't allocate BIGNUM g"); - exit(1); - } - if (!BN_set_word(g, dhInnerData->g)) { - DEBUG_E("OpenSSL error at BN_set_word(g_b, dhInnerData->g)"); - beginHandshake(false); - BN_free(g); - BN_free(g_a); - BN_free(p); - return; - } - static uint8_t bytes[256]; - RAND_bytes(bytes, 256); - BIGNUM *b = BN_bin2bn(bytes, 256, NULL); - if (b == nullptr) { - DEBUG_E("can't allocate BIGNUM b"); - exit(1); - } - - BIGNUM *g_b = BN_new(); - if (!BN_mod_exp(g_b, g, b, p, bnContext)) { - DEBUG_E("OpenSSL error at BN_mod_exp(g_b, g, b, p, bnContext)"); - beginHandshake(false); - BN_free(g); - BN_free(g_a); - BN_free(g_b); - BN_free(b); - BN_free(p); - return; - } - - TL_client_DH_inner_data *clientInnerData = new TL_client_DH_inner_data(); - clientInnerData->g_b = std::unique_ptr(new ByteArray(BN_num_bytes(g_b))); - BN_bn2bin(g_b, clientInnerData->g_b->bytes); - clientInnerData->nonce = std::unique_ptr(new ByteArray(authNonce)); - clientInnerData->server_nonce = std::unique_ptr(new ByteArray(authServerNonce)); - clientInnerData->retry_id = 0; - BN_free(g_b); - BN_free(g); - - BIGNUM *authKeyNum = BN_new(); - BN_mod_exp(authKeyNum, g_a, b, p, bnContext); - size_t l = BN_num_bytes(authKeyNum); - handshakeAuthKey = new ByteArray(256); - BN_bn2bin(authKeyNum, handshakeAuthKey->bytes); - if (l < 256) { - memmove(handshakeAuthKey->bytes + 256 - l, handshakeAuthKey->bytes, l); - memset(handshakeAuthKey->bytes, 0, 256 - l); - } - - BN_free(authKeyNum); - BN_free(g_a); - BN_free(b); - BN_free(p); - - uint32_t clientInnerDataSize = clientInnerData->getObjectSize(); - uint32_t additionalSize = (clientInnerDataSize + SHA_DIGEST_LENGTH) % 16; - if (additionalSize != 0) { - additionalSize = 16 - additionalSize; - } - NativeByteBuffer *clientInnerDataBuffer = BuffersStorage::getInstance().getFreeBuffer(clientInnerDataSize + additionalSize + SHA_DIGEST_LENGTH); - clientInnerDataBuffer->position(SHA_DIGEST_LENGTH); - clientInnerData->serializeToStream(clientInnerDataBuffer); - delete clientInnerData; - - SHA1(clientInnerDataBuffer->bytes() + SHA_DIGEST_LENGTH, clientInnerDataSize, clientInnerDataBuffer->bytes()); - - if (additionalSize != 0) { - RAND_bytes(clientInnerDataBuffer->bytes() + SHA_DIGEST_LENGTH + clientInnerDataSize, additionalSize); - } - - TL_set_client_DH_params *setClientDhParams = new TL_set_client_DH_params(); - setClientDhParams->nonce = std::unique_ptr(new ByteArray(authNonce)); - setClientDhParams->server_nonce = std::unique_ptr(new ByteArray(authServerNonce)); - aesIgeEncryption(clientInnerDataBuffer->bytes(), tmpAesKeyAndIv->bytes(), tmpAesKeyAndIv->bytes() + 32, true, false, clientInnerDataBuffer->limit()); - setClientDhParams->encrypted_data = std::unique_ptr(new ByteArray(clientInnerDataBuffer->bytes(), clientInnerDataBuffer->limit())); - clientInnerDataBuffer->reuse(); - tmpAesKeyAndIv->reuse(); - - sendAckRequest(messageId); - sendRequestData(setClientDhParams, true); - - int32_t currentTime = (int32_t) (ConnectionsManager::getInstance().getCurrentTimeMillis() / 1000); - timeDifference = dhInnerData->server_time - currentTime; - - handshakeServerSalt = new TL_future_salt(); - handshakeServerSalt->valid_since = currentTime + timeDifference - 5; - handshakeServerSalt->valid_until = handshakeServerSalt->valid_since + 30 * 60; - for (int32_t a = 7; a >= 0; a--) { - handshakeServerSalt->salt <<= 8; - handshakeServerSalt->salt |= (authNewNonce->bytes[a] ^ authServerNonce->bytes[a]); - } - } else { - DEBUG_E("dc%u handshake: can't set DH params", datacenterId); - beginHandshake(false); - } - } else if (dynamic_cast(message)) { - if (handshakeState != 3) { - sendAckRequest(messageId); - return; - } - - handshakeState = 4; - - Set_client_DH_params_answer *result = (Set_client_DH_params_answer *) message; - - if (!authNonce->isEqualTo(result->nonce.get())) { - DEBUG_E("dc%u handshake: invalid DH answer nonce", datacenterId); - beginHandshake(false); - return; - } - if (!authServerNonce->isEqualTo(result->server_nonce.get())) { - DEBUG_E("dc%u handshake: invalid DH answer server nonce", datacenterId); - beginHandshake(false); - return; - } - - sendAckRequest(messageId); - - uint32_t authKeyAuxHashLength = authNewNonce->length + SHA_DIGEST_LENGTH + 1; - NativeByteBuffer *authKeyAuxHashBuffer = BuffersStorage::getInstance().getFreeBuffer(authKeyAuxHashLength + SHA_DIGEST_LENGTH); - authKeyAuxHashBuffer->writeBytes(authNewNonce); - SHA1(handshakeAuthKey->bytes, handshakeAuthKey->length, authKeyAuxHashBuffer->bytes() + authNewNonce->length + 1); - - if (typeInfo == typeid(TL_dh_gen_ok)) { - authKeyAuxHashBuffer->writeByte(1); - SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); - - if (memcmp(result->new_nonce_hash1->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { - DEBUG_E("dc%u handshake: invalid DH answer nonce hash 1", datacenterId); - authKeyAuxHashBuffer->reuse(); - beginHandshake(false); - } else { - DEBUG_D("dc%u handshake: completed, time difference = %d", datacenterId, timeDifference); - authKey = handshakeAuthKey; - handshakeAuthKey = nullptr; - authKeyAuxHashBuffer->position(authNewNonce->length + 1 + 12); - authKeyId = authKeyAuxHashBuffer->readInt64(nullptr); - std::unique_ptr salt = std::unique_ptr(handshakeServerSalt); - addServerSalt(salt); - handshakeServerSalt = nullptr; - ConnectionsManager::getInstance().onDatacenterHandshakeComplete(this, timeDifference); - cleanupHandshake(); - } - authKeyAuxHashBuffer->reuse(); - } else if (typeInfo == typeid(TL_dh_gen_retry)) { - authKeyAuxHashBuffer->writeByte(2); - SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); - - if (memcmp(result->new_nonce_hash2->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { - DEBUG_E("dc%u handshake: invalid DH answer nonce hash 2", datacenterId); - beginHandshake(false); - } else { - DEBUG_D("dc%u handshake: retry DH", datacenterId); - beginHandshake(false); - } - authKeyAuxHashBuffer->reuse(); - } else if (typeInfo == typeid(TL_dh_gen_fail)) { - authKeyAuxHashBuffer->writeByte(3); - SHA1(authKeyAuxHashBuffer->bytes(), authKeyAuxHashLength - 12, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength); - - if (memcmp(result->new_nonce_hash3->bytes, authKeyAuxHashBuffer->bytes() + authKeyAuxHashLength + SHA_DIGEST_LENGTH - 16, 16)) { - DEBUG_E("dc%u handshake: invalid DH answer nonce hash 3", datacenterId); - beginHandshake(false); - } else { - DEBUG_E("dc%u handshake: server declined DH params", datacenterId); - beginHandshake(false); - } - authKeyAuxHashBuffer->reuse(); - } - } -} - -TLObject *Datacenter::getCurrentHandshakeRequest() { - return handshakeRequest; -} - -void Datacenter::sendAckRequest(int64_t messageId) { - TL_msgs_ack *msgsAck = new TL_msgs_ack(); - msgsAck->msg_ids.push_back(messageId); - sendRequestData(msgsAck, false); -} - -inline void generateMessageKey(uint8_t *authKey, uint8_t *messageKey, uint8_t *result, bool incoming) { - uint32_t x = incoming ? 8 : 0; - - static uint8_t sha[68]; - - memcpy(sha + 20, messageKey, 16); - memcpy(sha + 20 + 16, authKey + x, 32); - SHA1(sha + 20, 48, sha); - memcpy(result, sha, 8); - memcpy(result + 32, sha + 8, 12); - - memcpy(sha + 20, authKey + 32 + x, 16); - memcpy(sha + 20 + 16, messageKey, 16); - memcpy(sha + 20 + 16 + 16, authKey + 48 + x, 16); - SHA1(sha + 20, 48, sha); - memcpy(result + 8, sha + 8, 12); - memcpy(result + 32 + 12, sha, 8); - - memcpy(sha + 20, authKey + 64 + x, 32); - memcpy(sha + 20 + 32, messageKey, 16); - SHA1(sha + 20, 48, sha); - memcpy(result + 8 + 12, sha + 4, 12); - memcpy(result + 32 + 12 + 8, sha + 16, 4); - - memcpy(sha + 20, messageKey, 16); - memcpy(sha + 20 + 16, authKey + 96 + x, 32); - SHA1(sha + 20, 48, sha); - memcpy(result + 32 + 12 + 8 + 4, sha, 8); -} - -NativeByteBuffer *Datacenter::createRequestsData(std::vector> &requests, int32_t *quickAckId, Connection *connection) { - if (authKey == nullptr || connection == nullptr) { - return nullptr; - } - - int64_t messageId; - TLObject *messageBody; - bool freeMessageBody = false; - int32_t messageSeqNo; - - if (requests.size() == 1) { - NetworkMessage *networkMessage = requests[0].get(); - - if (networkMessage->message->outgoingBody != nullptr) { - messageBody = networkMessage->message->outgoingBody; - } else { - messageBody = networkMessage->message->body.get(); - } - DEBUG_D("connection(%p, dc%u, type %d) send message (session: 0x%llx, seqno: %d, messageid: 0x%llx): %s(%p)", connection, datacenterId, connection->getConnectionType(), (uint64_t) connection->getSissionId(), networkMessage->message->seqno, (uint64_t) networkMessage->message->msg_id, typeid(*messageBody).name(), messageBody); - - int64_t messageTime = (int64_t) (networkMessage->message->msg_id / 4294967296.0 * 1000); - int64_t currentTime = ConnectionsManager::getInstance().getCurrentTimeMillis() + (int64_t) ConnectionsManager::getInstance().getTimeDifference() * 1000; - - if (messageTime < currentTime - 30000 || messageTime > currentTime + 25000) { - DEBUG_D("wrap message in container"); - TL_msg_container *messageContainer = new TL_msg_container(); - messageContainer->messages.push_back(std::move(networkMessage->message)); - - messageId = ConnectionsManager::getInstance().generateMessageId(); - messageBody = messageContainer; - messageSeqNo = connection->generateMessageSeqNo(false); - freeMessageBody = true; - } else { - messageId = networkMessage->message->msg_id; - messageSeqNo = networkMessage->message->seqno; - } - } else { - DEBUG_D("start write messages to container"); - TL_msg_container *messageContainer = new TL_msg_container(); - size_t count = requests.size(); - for (uint32_t a = 0; a < count; a++) { - NetworkMessage *networkMessage = requests[a].get(); - if (networkMessage->message->outgoingBody != nullptr) { - messageBody = networkMessage->message->outgoingBody; - } else { - messageBody = networkMessage->message->body.get(); - } - DEBUG_D("connection(%p, dc%u, type %d) send message (session: 0x%llx, seqno: %d, messageid: 0x%llx): %s(%p)", connection, datacenterId, connection->getConnectionType(), (uint64_t) connection->getSissionId(), networkMessage->message->seqno, (uint64_t) networkMessage->message->msg_id, typeid(*messageBody).name(), messageBody); - messageContainer->messages.push_back(std::unique_ptr(std::move(networkMessage->message))); - } - messageId = ConnectionsManager::getInstance().generateMessageId(); - messageBody = messageContainer; - freeMessageBody = true; - messageSeqNo = connection->generateMessageSeqNo(false); - } - - uint32_t messageSize = messageBody->getObjectSize(); - uint32_t additionalSize = (32 + messageSize) % 16; - if (additionalSize != 0) { - additionalSize = 16 - additionalSize; - } - NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(24 + 32 + messageSize + additionalSize); - buffer->writeInt64(authKeyId); - buffer->position(24); - - int64_t serverSalt = getServerSalt(); - buffer->writeInt64(serverSalt); - buffer->writeInt64(connection->getSissionId()); - buffer->writeInt64(messageId); - buffer->writeInt32(messageSeqNo); - buffer->writeInt32(messageSize); - messageBody->serializeToStream(buffer); - if (freeMessageBody) { - delete messageBody; - } - - if (additionalSize != 0) { - RAND_bytes(buffer->bytes() + 24 + 32 + messageSize, additionalSize); - } - static uint8_t messageKey[84]; - SHA1(buffer->bytes() + 24, 32 + messageSize, messageKey); - memcpy(buffer->bytes() + 8, messageKey + 4, 16); - - if (quickAckId != nullptr) { - *quickAckId = (((messageKey[0] & 0xff)) | - ((messageKey[1] & 0xff) << 8) | - ((messageKey[2] & 0xff) << 16) | - ((messageKey[3] & 0xff) << 24)) & 0x7fffffff; - } - - generateMessageKey(authKey->bytes, messageKey + 4, messageKey + 20, false); - aesIgeEncryption(buffer->bytes() + 24, messageKey + 20, messageKey + 52, true, false, buffer->limit() - 24); - - return buffer; -} - -bool Datacenter::decryptServerResponse(int64_t keyId, uint8_t *key, uint8_t *data, uint32_t length) { - if (authKeyId != keyId || length % 16 != 0) { - return false; - } - static uint8_t messageKey[84]; - generateMessageKey(authKey->bytes, key, messageKey + 20, true); - aesIgeEncryption(data, messageKey + 20, messageKey + 52, false, false, length); - - uint32_t messageLength; - memcpy(&messageLength, data + 28, sizeof(uint32_t)); - if (messageLength > length - 32) { - return false; - } - messageLength += 32; - if (messageLength > length) { - messageLength = length; - } - - SHA1(data, messageLength, messageKey); - - return memcmp(messageKey + 4, key, 16) == 0; -} - -bool Datacenter::hasAuthKey() { - return authKey != nullptr; -} - -Connection *Datacenter::createConnectionByType(uint32_t connectionType) { - uint32_t connectionNum = connectionType >> 16; - connectionType = connectionType & 0x0000ffff; - switch (connectionType) { - case ConnectionTypeGeneric: - return createGenericConnection(); - case ConnectionTypeDownload: - return createDownloadConnection(connectionNum); - case ConnectionTypeUpload: - return createUploadConnection(); - case ConnectionTypePush: - return createPushConnection(); - default: - return nullptr; - } -} - -Connection *Datacenter::getDownloadConnection(uint32_t num, bool create) { - if (authKey == nullptr) { - return nullptr; - } - if (create) { - createDownloadConnection(num)->connect(); - } - return downloadConnections[num]; -} - -Connection *Datacenter::getUploadConnection(bool create) { - if (authKey == nullptr) { - return nullptr; - } - if (create) { - createUploadConnection()->connect(); - } - return uploadConnection; -} - -Connection *Datacenter::getGenericConnection(bool create) { - if (authKey == nullptr) { - return nullptr; - } - if (create) { - createGenericConnection()->connect(); - } - return genericConnection; -} - -Connection *Datacenter::getPushConnection(bool create) { - if (authKey == nullptr) { - return nullptr; - } - if (create) { - createPushConnection()->connect(); - } - return pushConnection; -} - -Connection *Datacenter::getConnectionByType(uint32_t connectionType, bool create) { - uint32_t connectionNum = connectionType >> 16; - connectionType = connectionType & 0x0000ffff; - switch (connectionType) { - case ConnectionTypeGeneric: - return getGenericConnection(create); - case ConnectionTypeDownload: - return getDownloadConnection(connectionNum, create); - case ConnectionTypeUpload: - return getUploadConnection(create); - case ConnectionTypePush: - return getPushConnection(create); - default: - return nullptr; - } -} - -void Datacenter::exportAuthorization() { - if (exportingAuthorization) { - return; - } - exportingAuthorization = true; - TL_auth_exportAuthorization *request = new TL_auth_exportAuthorization(); - request->dc_id = datacenterId; - DEBUG_D("dc%u begin export authorization", datacenterId); - ConnectionsManager::getInstance().sendRequest(request, [&](TLObject *response, TL_error *error) { - if (error == nullptr) { - TL_auth_exportedAuthorization *res = (TL_auth_exportedAuthorization *) response; - TL_auth_importAuthorization *request2 = new TL_auth_importAuthorization(); - request2->bytes = std::move(res->bytes); - request2->id = res->id; - DEBUG_D("dc%u begin import authorization", datacenterId); - ConnectionsManager::getInstance().sendRequest(request2, [&](TLObject *response2, TL_error *error2) { - if (error2 == nullptr) { - authorized = true; - ConnectionsManager::getInstance().onDatacenterExportAuthorizationComplete(this); - } else { - DEBUG_D("dc%u failed import authorization", datacenterId); - } - exportingAuthorization = false; - }, nullptr, RequestFlagEnableUnauthorized | RequestFlagWithoutLogin, datacenterId, ConnectionTypeGeneric, true); - } else { - DEBUG_D("dc%u failed export authorization", datacenterId); - exportingAuthorization = false; - } - }, nullptr, 0, DEFAULT_DATACENTER_ID, ConnectionTypeGeneric, true); -} - -bool Datacenter::isExportingAuthorization() { - return exportingAuthorization; -} diff --git a/TMessagesProj/jni/tgnet/Datacenter.h b/TMessagesProj/jni/tgnet/Datacenter.h deleted file mode 100644 index d7b70aa8a..000000000 --- a/TMessagesProj/jni/tgnet/Datacenter.h +++ /dev/null @@ -1,129 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef DATACENTER_H -#define DATACENTER_H - -#include -#include -#include -#include -#include "Defines.h" - -class TL_future_salt; -class Connection; -class NativeByteBuffer; -class TL_future_salt; -class ByteArray; -class TLObject; -class Config; - -class Datacenter { - -public: - Datacenter(uint32_t id); - Datacenter(NativeByteBuffer *data); - void switchTo443Port(); - uint32_t getDatacenterId(); - std::string getCurrentAddress(uint32_t flags); - int32_t getCurrentPort(uint32_t flags); - void addAddressAndPort(std::string address, uint32_t port, uint32_t flags); - void nextAddressOrPort(uint32_t flags); - void storeCurrentAddressAndPortNum(); - void replaceAddressesAndPorts(std::vector &newAddresses, std::map &newPorts, uint32_t flags); - void serializeToStream(NativeByteBuffer *stream); - void clear(); - void clearServerSalts(); - int64_t getServerSalt(); - void mergeServerSalts(std::vector> &salts); - void addServerSalt(std::unique_ptr &serverSalt); - bool containsServerSalt(int64_t value); - void suspendConnections(); - void getSessions(std::vector &sessions); - void recreateSessions(); - bool isHandshaking(); - bool hasAuthKey(); - bool isExportingAuthorization(); - - Connection *getDownloadConnection(uint32_t num, bool create); - Connection *getUploadConnection(bool create); - Connection *getGenericConnection(bool create); - Connection *getPushConnection(bool create); - Connection *getConnectionByType(uint32_t connectionType, bool create); - -private: - void onHandshakeConnectionClosed(Connection *connection); - void onHandshakeConnectionConnected(Connection *connection); - void processHandshakeResponse(TLObject *message, int64_t messageId); - void aesIgeEncryption(uint8_t *buffer, uint8_t *key, uint8_t *iv, bool encrypt, bool changeIv, uint32_t length); - NativeByteBuffer *createRequestsData(std::vector> &requests, int32_t *quickAckId, Connection *connection); - bool decryptServerResponse(int64_t keyId, uint8_t *key, uint8_t *data, uint32_t length); - TLObject *getCurrentHandshakeRequest(); - - const int32_t *defaultPorts = new int32_t[11] {-1, 80, -1, 443, -1, 443, -1, 80, -1, 443, -1}; - const int32_t *defaultPorts8888 = new int32_t[11] {-1, 8888, -1, 443, -1, 8888, -1, 80, -1, 8888, -1}; - - uint32_t datacenterId; - Connection *genericConnection = nullptr; - Connection *downloadConnections[DOWNLOAD_CONNECTIONS_COUNT]; - Connection *uploadConnection = nullptr; - Connection *pushConnection = nullptr; - - uint32_t lastInitVersion = 0; - bool authorized = false; - - std::vector addressesIpv4; - std::vector addressesIpv6; - std::vector addressesIpv4Download; - std::vector addressesIpv6Download; - std::map ports; - std::vector> serverSalts; - uint32_t currentPortNumIpv4 = 0; - uint32_t currentAddressNumIpv4 = 0; - uint32_t currentPortNumIpv6 = 0; - uint32_t currentAddressNumIpv6 = 0; - uint32_t currentPortNumIpv4Download = 0; - uint32_t currentAddressNumIpv4Download = 0; - uint32_t currentPortNumIpv6Download = 0; - uint32_t currentAddressNumIpv6Download = 0; - ByteArray *authKey = nullptr; - int64_t authKeyId = 0; - int32_t overridePort = -1; - Config *config = nullptr; - - const uint32_t configVersion = 5; - const uint32_t paramsConfigVersion = 1; - - Connection *createDownloadConnection(uint32_t num); - Connection *createUploadConnection(); - Connection *createGenericConnection(); - Connection *createPushConnection(); - Connection *createConnectionByType(uint32_t connectionType); - - uint8_t handshakeState = 0; - TLObject *handshakeRequest = nullptr; - ByteArray *authNonce = nullptr; - ByteArray *authServerNonce = nullptr; - ByteArray *authNewNonce = nullptr; - ByteArray *handshakeAuthKey = nullptr; - TL_future_salt *handshakeServerSalt = nullptr; - int32_t timeDifference = 0; - bool needResendData = false; - void beginHandshake(bool reconnect); - void sendRequestData(TLObject *object, bool important); - void cleanupHandshake(); - void sendAckRequest(int64_t messageId); - int32_t selectPublicKey(std::vector &fingerprints); - - bool exportingAuthorization = false; - void exportAuthorization(); - - friend class ConnectionsManager; -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/Defines.h b/TMessagesProj/jni/tgnet/Defines.h deleted file mode 100644 index 168199bdb..000000000 --- a/TMessagesProj/jni/tgnet/Defines.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef DEFINES_H -#define DEFINES_H - -#include -#include -#include -#include -#include - -#define USE_DEBUG_SESSION false -#define READ_BUFFER_SIZE 1024 * 128 -//#define DEBUG_VERSION -#define DEFAULT_DATACENTER_ID INT_MAX -#define DC_UPDATE_TIME 60 * 60 -#define DOWNLOAD_CONNECTIONS_COUNT 2 -#define CONNECTION_BACKGROUND_KEEP_TIME 10000 - -class TLObject; -class TL_error; -class Request; -class TL_message; -class TL_config; -class NativeByteBuffer; - -typedef std::function onCompleteFunc; -typedef std::function onQuickAckFunc; -typedef std::list> requestsList; -typedef requestsList::iterator requestsIter; - -typedef struct NetworkMessage { - std::unique_ptr message; - bool invokeAfter = false; - bool needQuickAck = false; - int32_t requestId; -} NetworkMessage; - -enum ConnectionType { - ConnectionTypeGeneric = 1, - ConnectionTypeDownload = 2, - ConnectionTypeUpload = 4, - ConnectionTypePush = 8, -}; - -enum ConnectionState { - ConnectionStateConnecting = 1, - ConnectionStateWaitingForNetwork = 2, - ConnectionStateConnected = 3 -}; - -enum EventObjectType { - EventObjectTypeConnection, - EventObjectTypeTimer, - EventObjectPipe -}; - -typedef struct ConnectiosManagerDelegate { - virtual void onUpdate() = 0; - virtual void onSessionCreated() = 0; - virtual void onConnectionStateChanged(ConnectionState state) = 0; - virtual void onUnparsedMessageReceived(int64_t reqMessageId, NativeByteBuffer *buffer, ConnectionType connectionType) = 0; - virtual void onLogout() = 0; - virtual void onUpdateConfig(TL_config *config) = 0; - virtual void onInternalPushReceived() = 0; -} ConnectiosManagerDelegate; - -#define AllConnectionTypes ConnectionTypeGeneric | ConnectionTypeDownload | ConnectionTypeUpload - -enum RequestFlag { - RequestFlagEnableUnauthorized = 1, - RequestFlagFailOnServerErrors = 2, - RequestFlagCanCompress = 4, - RequestFlagWithoutLogin = 8, - RequestFlagTryDifferentDc = 16, - RequestFlagForceDownload = 32, - RequestFlagInvokeAfter = 64, - RequestFlagNeedQuickAck = 128 -}; - -inline std::string to_string_int32(int32_t value) { - char buf[30]; - int len = sprintf(buf, "%d", value); - return std::string(buf, len); -} - -inline std::string to_string_uint64(uint64_t value) { - char buf[30]; - int len = sprintf(buf, "%llu", value); - return std::string(buf, len); -} - -#endif diff --git a/TMessagesProj/jni/tgnet/EventObject.cpp b/TMessagesProj/jni/tgnet/EventObject.cpp deleted file mode 100644 index 490ab8b0e..000000000 --- a/TMessagesProj/jni/tgnet/EventObject.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include "EventObject.h" -#include "Connection.h" -#include "Timer.h" - -EventObject::EventObject(void *object, EventObjectType type) { - eventObject = object; - eventType = type; -} - -void EventObject::onEvent(uint32_t events) { - switch (eventType) { - case EventObjectTypeConnection: { - Connection *connection = (Connection *) eventObject; - connection->onEvent(events); - break; - } - case EventObjectTypeTimer: { - Timer *timer = (Timer *) eventObject; - timer->onEvent(); - break; - } - case EventObjectPipe: { - int *pipe = (int *) eventObject; - char ch; - ssize_t size = 1; - while (size > 0) { - size = read(pipe[0], &ch, 1); - } - break; - } - default: - break; - } -} diff --git a/TMessagesProj/jni/tgnet/EventObject.h b/TMessagesProj/jni/tgnet/EventObject.h deleted file mode 100644 index 18b803a48..000000000 --- a/TMessagesProj/jni/tgnet/EventObject.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef EVENTOBJECT_H -#define EVENTOBJECT_H - -#include -#include "Defines.h" - -class EventObject { - -public: - EventObject(void *object, EventObjectType type); - void onEvent(uint32_t events); - - int64_t time; - void *eventObject; - EventObjectType eventType; -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/FileLog.cpp b/TMessagesProj/jni/tgnet/FileLog.cpp deleted file mode 100644 index 044a1dc85..000000000 --- a/TMessagesProj/jni/tgnet/FileLog.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include -#include "FileLog.h" - -#ifdef ANDROID -#include -#endif - -FILE *logFile = nullptr; - -void FileLog::init(std::string path) { - if (path.size() > 0) { - logFile = fopen(path.c_str(), "w"); - } -} - -void FileLog::e(const char *message, ...) { - va_list argptr; - va_start(argptr, message); - time_t t = time(0); - struct tm *now = localtime(&t); -#ifdef ANDROID - __android_log_vprint(ANDROID_LOG_ERROR, "tgnet", message, argptr); -#else - printf("%d-%d %02d:%02d:%02d error: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec); - vprintf(message, argptr); - printf("\n"); - fflush(stdout); -#endif - if (logFile) { - fprintf(logFile, "%d-%d %02d:%02d:%02d error: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec); - vfprintf(logFile, message, argptr); - fprintf(logFile, "\n"); - fflush(logFile); - } - - va_end(argptr); -} - -void FileLog::w(const char *message, ...) { - va_list argptr; - va_start(argptr, message); - time_t t = time(0); - struct tm *now = localtime(&t); -#ifdef ANDROID - __android_log_vprint(ANDROID_LOG_WARN, "tgnet", message, argptr); -#else - printf("%d-%d %02d:%02d:%02d warning: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec); - vprintf(message, argptr); - printf("\n"); - fflush(stdout); -#endif - if (logFile) { - fprintf(logFile, "%d-%d %02d:%02d:%02d warning: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec); - vfprintf(logFile, message, argptr); - fprintf(logFile, "\n"); - fflush(logFile); - } - - va_end(argptr); -} - -void FileLog::d(const char *message, ...) { - va_list argptr; - va_start(argptr, message); - time_t t = time(0); - struct tm *now = localtime(&t); -#ifdef ANDROID - __android_log_vprint(ANDROID_LOG_DEBUG, "tgnet", message, argptr); -#else - printf("%d-%d %02d:%02d:%02d debug: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec); - vprintf(message, argptr); - printf("\n"); - fflush(stdout); -#endif - if (logFile) { - fprintf(logFile, "%d-%d %02d:%02d:%02d debug: ", now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec); - vfprintf(logFile, message, argptr); - fprintf(logFile, "\n"); - fflush(logFile); - } - - va_end(argptr); -} diff --git a/TMessagesProj/jni/tgnet/FileLog.h b/TMessagesProj/jni/tgnet/FileLog.h deleted file mode 100644 index 7cf8ce34c..000000000 --- a/TMessagesProj/jni/tgnet/FileLog.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef FILELOG_H -#define FILELOG_H - -#include "Defines.h" - -class FileLog { -public: - static void init(std::string path); - static void e(const char *message, ...) __attribute__((format (printf, 1, 2))); - static void w(const char *message, ...) __attribute__((format (printf, 1, 2))); - static void d(const char *message, ...) __attribute__((format (printf, 1, 2))); -}; - -#ifdef DEBUG_VERSION -#define DEBUG_E FileLog::e -#define DEBUG_W FileLog::w -#define DEBUG_D FileLog::d -#else -#define DEBUG_E -#define DEBUG_W -#define DEBUG_D -#endif - -#endif diff --git a/TMessagesProj/jni/tgnet/MTProtoScheme.cpp b/TMessagesProj/jni/tgnet/MTProtoScheme.cpp deleted file mode 100644 index efe399897..000000000 --- a/TMessagesProj/jni/tgnet/MTProtoScheme.cpp +++ /dev/null @@ -1,1423 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include "MTProtoScheme.h" -#include "FileLog.h" -#include "ByteArray.h" -#include "NativeByteBuffer.h" -#include "BuffersStorage.h" -#include "ConnectionsManager.h" - -TLObject *TLClassStore::TLdeserialize(NativeByteBuffer *stream, uint32_t bytes, uint32_t constructor, bool &error) { - TLObject *object = nullptr; - switch (constructor) { - case TL_msgs_ack::constructor: - object = new TL_msgs_ack(); - break; - case TL_msg_container::constructor: - object = new TL_msg_container(); - break; - case TL_pong::constructor: - object = new TL_pong(); - break; - case TL_new_session_created::constructor: - object = new TL_new_session_created(); - break; - case TL_rpc_result::constructor: - object = new TL_rpc_result(); - ((TL_rpc_result *) object)->readParamsEx(stream, bytes, error); - return object; - case TL_bad_msg_notification::constructor: - object = new TL_bad_msg_notification(); - break; - case TL_bad_server_salt::constructor: - object = new TL_bad_server_salt(); - break; - case TL_msg_detailed_info::constructor: - object = new TL_msg_detailed_info(); - break; - case TL_msg_new_detailed_info::constructor: - object = new TL_msg_new_detailed_info(); - break; - case TL_gzip_packed::constructor: - object = new TL_gzip_packed(); - break; - case TL_error::constructor: - object = new TL_error(); - break; - case TL_rpc_error::constructor: - object = new TL_rpc_error(); - break; - case TL_rpc_req_error::constructor: - object = new TL_rpc_req_error(); - break; - case TL_future_salts::constructor: - object = new TL_future_salts(); - break; - case TL_destroy_session_ok::constructor: - object = new TL_destroy_session_ok(); - break; - case TL_destroy_session_none::constructor: - object = new TL_destroy_session_none(); - break; - case TL_updatesTooLong::constructor: - object = new TL_updatesTooLong(); - break; - default: - return nullptr; - } - object->readParams(stream, error); - return object; -} - -TL_api_request::~TL_api_request() { - if (request != nullptr) { - request->reuse(); - request = nullptr; - } -} - -bool TL_api_request::isNeedLayer() { - return true; -} - -TLObject *TL_api_request::deserializeResponse(NativeByteBuffer *stream, uint32_t bytes, bool &error) { - TL_api_response *result = new TL_api_response(); - result->readParamsEx(stream, bytes, error); - return result; -} - -void TL_api_request::serializeToStream(NativeByteBuffer *stream) { - request->rewind(); - stream->writeBytes(request); -} - -void TL_api_response::readParamsEx(NativeByteBuffer *stream, uint32_t bytes, bool &error) { - response = std::unique_ptr(new NativeByteBuffer(stream->bytes() + stream->position() - 4, bytes)); - stream->skip((uint32_t) (bytes - 4)); -} - -TL_future_salt *TL_future_salt::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_future_salt::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_future_salt", constructor); - return nullptr; - } - TL_future_salt *result = new TL_future_salt(); - result->readParams(stream, error); - return result; -} - -void TL_future_salt::readParams(NativeByteBuffer *stream, bool &error) { - valid_since = stream->readInt32(&error); - valid_until = stream->readInt32(&error); - salt = stream->readInt64(&error); -} - -TL_msgs_state_info *TL_msgs_state_info::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_msgs_state_info::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_msgs_state_info", constructor); - return nullptr; - } - TL_msgs_state_info *result = new TL_msgs_state_info(); - result->readParams(stream, error); - return result; -} - -void TL_msgs_state_info::readParams(NativeByteBuffer *stream, bool &error) { - req_msg_id = stream->readInt64(&error); - info = std::unique_ptr(stream->readByteArray(&error)); -} - -void TL_msgs_state_info::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt64(req_msg_id); - stream->writeByteArray(info.get()); -} - -Server_DH_Params *Server_DH_Params::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - Server_DH_Params *result = nullptr; - switch (constructor) { - case 0x79cb045d: - result = new TL_server_DH_params_fail(); - break; - case 0xd0e8075c: - result = new TL_server_DH_params_ok(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in Server_DH_Params", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_server_DH_params_fail::readParams(NativeByteBuffer *stream, bool &error) { - nonce = std::unique_ptr(stream->readBytes(16, &error)); - server_nonce = std::unique_ptr(stream->readBytes(16, &error)); - new_nonce_hash = std::unique_ptr(stream->readBytes(16, &error)); -} - -void TL_server_DH_params_ok::readParams(NativeByteBuffer *stream, bool &error) { - nonce = std::unique_ptr(stream->readBytes(16, &error)); - server_nonce = std::unique_ptr(stream->readBytes(16, &error)); - encrypted_answer = std::unique_ptr(stream->readByteArray(&error)); -} - -TL_resPQ *TL_resPQ::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_resPQ::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_resPQ", constructor); - return nullptr; - } - TL_resPQ *result = new TL_resPQ(); - result->readParams(stream, error); - return result; -} - -void TL_resPQ::readParams(NativeByteBuffer *stream, bool &error) { - nonce = std::unique_ptr(stream->readBytes(16, &error)); - server_nonce = std::unique_ptr(stream->readBytes(16, &error)); - pq = std::unique_ptr(stream->readByteArray(&error)); - uint32_t magic = stream->readUint32(&error); - if (magic != 0x1cb5c415) { - error = true; - DEBUG_E("wrong Vector magic, got %x", magic); - return; - } - uint32_t count = stream->readUint32(&error); - if (count * sizeof(int64_t) + stream->position() > stream->limit()) { - error = true; - return; - } - for (uint32_t a = 0; a < count; a++) { - server_public_key_fingerprints.push_back(stream->readInt64(&error)); - } -} - -void TL_p_q_inner_data::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeByteArray(pq.get()); - stream->writeByteArray(p.get()); - stream->writeByteArray(q.get()); - stream->writeBytes(nonce.get()); - stream->writeBytes(server_nonce.get()); - stream->writeBytes(new_nonce.get()); -} - -TL_pong *TL_pong::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_pong::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_pong", constructor); - return nullptr; - } - TL_pong *result = new TL_pong(); - result->readParams(stream, error); - return result; -} - -void TL_pong::readParams(NativeByteBuffer *stream, bool &error) { - msg_id = stream->readInt64(&error); - ping_id = stream->readInt64(&error); -} - -TL_future_salts *TL_future_salts::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_future_salts::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_future_salts", constructor); - return nullptr; - } - TL_future_salts *result = new TL_future_salts(); - result->readParams(stream, error); - return result; -} - -void TL_future_salts::readParams(NativeByteBuffer *stream, bool &error) { - req_msg_id = stream->readInt64(&error); - now = stream->readInt32(&error); - uint32_t count = stream->readUint32(&error); - for (uint32_t a = 0; a < count; a++) { - TL_future_salt *object = new TL_future_salt(); - object->readParams(stream, error); - if (error) { - return; - } - salts.push_back(std::unique_ptr(object)); - } -} - -RpcDropAnswer *RpcDropAnswer::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - RpcDropAnswer *result = nullptr; - switch (constructor) { - case 0x5e2ad36e: - result = new TL_rpc_answer_unknown(); - break; - case 0xa43ad8b7: - result = new TL_rpc_answer_dropped(); - break; - case 0xcd78e586: - result = new TL_rpc_answer_dropped_running(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in RpcDropAnswer", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_rpc_answer_unknown::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -void TL_rpc_answer_dropped::readParams(NativeByteBuffer *stream, bool &error) { - msg_id = stream->readInt64(&error); - seq_no = stream->readInt32(&error); - bytes = stream->readInt32(&error); -} - -void TL_rpc_answer_dropped_running::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -Set_client_DH_params_answer *Set_client_DH_params_answer::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - Set_client_DH_params_answer *result = nullptr; - switch (constructor) { - case 0x46dc1fb9: - result = new TL_dh_gen_retry(); - break; - case 0xa69dae02: - result = new TL_dh_gen_fail(); - break; - case 0x3bcbf734: - result = new TL_dh_gen_ok(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in Set_client_DH_params_answer", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_dh_gen_retry::readParams(NativeByteBuffer *stream, bool &error) { - nonce = std::unique_ptr(stream->readBytes(16, &error)); - server_nonce = std::unique_ptr(stream->readBytes(16, &error)); - new_nonce_hash2 = std::unique_ptr(stream->readBytes(16, &error)); -} - -void TL_dh_gen_fail::readParams(NativeByteBuffer *stream, bool &error) { - nonce = std::unique_ptr(stream->readBytes(16, &error)); - server_nonce = std::unique_ptr(stream->readBytes(16, &error)); - new_nonce_hash3 = std::unique_ptr(stream->readBytes(16, &error)); -} - -void TL_dh_gen_ok::readParams(NativeByteBuffer *stream, bool &error) { - nonce = std::unique_ptr(stream->readBytes(16, &error)); - server_nonce = std::unique_ptr(stream->readBytes(16, &error)); - new_nonce_hash1 = std::unique_ptr(stream->readBytes(16, &error)); -} - -BadMsgNotification *BadMsgNotification::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - BadMsgNotification *result = nullptr; - switch (constructor) { - case 0xa7eff811: - result = new TL_bad_msg_notification(); - break; - case 0xedab447b: - result = new TL_bad_server_salt(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in BadMsgNotification", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_bad_msg_notification::readParams(NativeByteBuffer *stream, bool &error) { - bad_msg_id = stream->readInt64(&error); - bad_msg_seqno = stream->readInt32(&error); - error_code = stream->readInt32(&error); -} - -void TL_bad_server_salt::readParams(NativeByteBuffer *stream, bool &error) { - bad_msg_id = stream->readInt64(&error); - bad_msg_seqno = stream->readInt32(&error); - error_code = stream->readInt32(&error); - new_server_salt = stream->readInt64(&error); -} - -TL_msgs_state_req *TL_msgs_state_req::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_msgs_state_req::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_msgs_state_req", constructor); - return nullptr; - } - TL_msgs_state_req *result = new TL_msgs_state_req(); - result->readParams(stream, error); - return result; -} - -void TL_msgs_state_req::readParams(NativeByteBuffer *stream, bool &error) { - uint32_t magic = stream->readUint32(&error); - if (magic != 0x1cb5c415) { - error = true; - DEBUG_E("wrong Vector magic, got %x", magic); - return; - } - uint32_t count = stream->readUint32(&error); - if (count * sizeof(int64_t) + stream->position() > stream->limit()) { - error = true; - return; - } - for (uint32_t a = 0; a < count; a++) { - msg_ids.push_back(stream->readInt64(&error)); - } -} - -void TL_msgs_state_req::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(0x1cb5c415); - uint32_t count = (uint32_t) msg_ids.size(); - stream->writeInt32(count); - for (uint32_t a = 0; a < count; a++) { - stream->writeInt64(msg_ids[a]); - } -} - -MsgDetailedInfo *MsgDetailedInfo::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - MsgDetailedInfo *result = nullptr; - switch (constructor) { - case 0x809db6df: - result = new TL_msg_new_detailed_info(); - break; - case 0x276d3ec6: - result = new TL_msg_detailed_info(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in MsgDetailedInfo", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_msg_new_detailed_info::readParams(NativeByteBuffer *stream, bool &error) { - answer_msg_id = stream->readInt64(&error); - bytes = stream->readInt32(&error); - status = stream->readInt32(&error); -} - -void TL_msg_detailed_info::readParams(NativeByteBuffer *stream, bool &error) { - msg_id = stream->readInt64(&error); - answer_msg_id = stream->readInt64(&error); - bytes = stream->readInt32(&error); - status = stream->readInt32(&error); -} - -TL_msg_copy *TL_msg_copy::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_msg_copy::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_msg_copy", constructor); - return nullptr; - } - TL_msg_copy *result = new TL_msg_copy(); - result->readParams(stream, error); - return result; -} - -void TL_msg_copy::readParams(NativeByteBuffer *stream, bool &error) { - orig_message = std::unique_ptr(TL_message::TLdeserialize(stream, stream->readUint32(&error), error)); -} - -void TL_msg_copy::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - orig_message->serializeToStream(stream); -} - -TL_msgs_all_info *TL_msgs_all_info::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_msgs_all_info::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_msgs_all_info", constructor); - return nullptr; - } - TL_msgs_all_info *result = new TL_msgs_all_info(); - result->readParams(stream, error); - return result; -} - -void TL_msgs_all_info::readParams(NativeByteBuffer *stream, bool &error) { - uint32_t magic = stream->readUint32(&error); - if (magic != 0x1cb5c415) { - error = true; - DEBUG_E("wrong Vector magic, got %x", magic); - return; - } - uint32_t count = stream->readUint32(&error); - if (count * sizeof(int64_t) + stream->position() > stream->limit()) { - error = true; - return; - } - for (uint32_t a = 0; a < count; a++) { - msg_ids.push_back(stream->readInt64(&error)); - } - info = std::unique_ptr(stream->readByteArray(&error)); -} - -void TL_rpc_result::readParamsEx(NativeByteBuffer *stream, uint32_t bytes, bool &error) { - req_msg_id = stream->readInt64(&error); - TLObject *object = ConnectionsManager::getInstance().TLdeserialize(ConnectionsManager::getInstance().getRequestWithMessageId(req_msg_id), bytes - 12, stream); - if (object != nullptr) { - result = std::unique_ptr(object); - } else { - error = true; - } -} - -void TL_new_session_created::readParams(NativeByteBuffer *stream, bool &error) { - first_msg_id = stream->readInt64(&error); - unique_id = stream->readInt64(&error); - server_salt = stream->readInt64(&error); -} - -DestroySessionRes *DestroySessionRes::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - DestroySessionRes *result = nullptr; - switch (constructor) { - case 0xe22045fc: - result = new TL_destroy_session_ok(); - break; - case 0x62d350c9: - result = new TL_destroy_session_none(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in DestroySessionRes", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_destroy_session_ok::readParams(NativeByteBuffer *stream, bool &error) { - session_id = stream->readInt64(&error); -} - -void TL_destroy_session_none::readParams(NativeByteBuffer *stream, bool &error) { - session_id = stream->readInt64(&error); -} - -TL_msgs_ack *TL_msgs_ack::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_msgs_ack::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_msgs_ack", constructor); - return nullptr; - } - TL_msgs_ack *result = new TL_msgs_ack(); - result->readParams(stream, error); - return result; -} - -void TL_msgs_ack::readParams(NativeByteBuffer *stream, bool &error) { - uint32_t magic = stream->readUint32(&error); - if (magic != 0x1cb5c415) { - error = true; - DEBUG_E("wrong Vector magic, got %x", magic); - return; - } - uint32_t count = stream->readUint32(&error); - if (count * sizeof(int64_t) + stream->position() > stream->limit()) { - error = true; - return; - } - for (uint32_t a = 0; a < count; a++) { - msg_ids.push_back(stream->readInt64(&error)); - } -} - -void TL_msgs_ack::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(0x1cb5c415); - uint32_t count = (uint32_t) msg_ids.size(); - stream->writeInt32(count); - for (uint32_t a = 0; a < count; a++) { - stream->writeInt64(msg_ids[a]); - } -} - -TL_msg_container *TL_msg_container::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_msg_container::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_msg_container", constructor); - return nullptr; - } - TL_msg_container *result = new TL_msg_container(); - result->readParams(stream, error); - return result; -} - -void TL_msg_container::readParams(NativeByteBuffer *stream, bool &error) { - uint32_t count = stream->readUint32(&error); - for (uint32_t a = 0; a < count; a++) { - TL_message *object = new TL_message(); - object->readParams(stream, error); - if (error) { - return; - } - messages.push_back(std::unique_ptr(object)); - } -} - -void TL_msg_container::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - uint32_t count = (uint32_t) messages.size(); - stream->writeInt32(count); - for (uint32_t a = 0; a < count; a++) { - messages[a]->serializeToStream(stream); - } -} - -TL_message *TL_message::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_message::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_message", constructor); - return nullptr; - } - TL_message *result = new TL_message(); - result->readParams(stream, error); - return result; -} - -void TL_message::readParams(NativeByteBuffer *stream, bool &error) { - msg_id = stream->readInt64(&error); - seqno = stream->readInt32(&error); - bytes = stream->readInt32(&error); - TLObject *object = ConnectionsManager::getInstance().TLdeserialize(nullptr, (uint32_t) bytes, stream); - if (object == nullptr) { - unparsedBody = std::unique_ptr(new NativeByteBuffer(stream->bytes() + stream->position(), (uint32_t) bytes)); - stream->skip((uint32_t) bytes); - } else { - body = std::unique_ptr(object); - } -} - -void TL_message::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt64(msg_id); - stream->writeInt32(seqno); - stream->writeInt32(bytes); - if (outgoingBody != nullptr) { - outgoingBody->serializeToStream(stream); - } else { - body->serializeToStream(stream); - } -} - -TL_msg_resend_req *TL_msg_resend_req::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_msg_resend_req::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_msg_resend_req", constructor); - return nullptr; - } - TL_msg_resend_req *result = new TL_msg_resend_req(); - result->readParams(stream, error); - return result; -} - -void TL_msg_resend_req::readParams(NativeByteBuffer *stream, bool &error) { - uint32_t magic = stream->readUint32(&error); - if (magic != 0x1cb5c415) { - error = true; - DEBUG_E("wrong Vector magic, got %x", magic); - return; - } - uint32_t count = stream->readUint32(&error); - if (count * sizeof(int64_t) + stream->position() > stream->limit()) { - error = true; - return; - } - for (uint32_t a = 0; a < count; a++) { - msg_ids.push_back(stream->readInt64(&error)); - } -} - -void TL_msg_resend_req::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(0x1cb5c415); - uint32_t count = (uint32_t) msg_ids.size(); - stream->writeInt32(count); - for (uint32_t a = 0; a < count; a++) { - stream->writeInt64(msg_ids[a]); - } -} - -void TL_rpc_error::readParams(NativeByteBuffer *stream, bool &error) { - error_code = stream->readInt32(&error); - error_message = stream->readString(&error); -} - -void TL_rpc_req_error::readParams(NativeByteBuffer *stream, bool &error) { - query_id = stream->readInt64(&error); - error_code = stream->readInt32(&error); - error_message = stream->readString(&error); -} - -void TL_client_DH_inner_data::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeBytes(nonce.get()); - stream->writeBytes(server_nonce.get()); - stream->writeInt64(retry_id); - stream->writeByteArray(g_b.get()); -} - -TL_server_DH_inner_data *TL_server_DH_inner_data::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_server_DH_inner_data::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_server_DH_inner_data", constructor); - return nullptr; - } - TL_server_DH_inner_data *result = new TL_server_DH_inner_data(); - result->readParams(stream, error); - return result; -} - -void TL_server_DH_inner_data::readParams(NativeByteBuffer *stream, bool &error) { - nonce = std::unique_ptr(stream->readBytes(16, &error)); - server_nonce = std::unique_ptr(stream->readBytes(16, &error)); - g = stream->readUint32(&error); - dh_prime = std::unique_ptr(stream->readByteArray(&error)); - g_a = std::unique_ptr(stream->readByteArray(&error)); - server_time = stream->readInt32(&error); -} - -void TL_server_DH_inner_data::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeBytes(nonce.get()); - stream->writeBytes(server_nonce.get()); - stream->writeInt32(g); - stream->writeByteArray(dh_prime.get()); - stream->writeByteArray(g_a.get()); - stream->writeInt32(server_time); -} - -TLObject *TL_req_pq::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return TL_resPQ::TLdeserialize(stream, constructor, error); -} - -void TL_req_pq::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeBytes(nonce.get()); -} - -TLObject *TL_req_DH_params::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return Server_DH_Params::TLdeserialize(stream, constructor, error); -} - -void TL_req_DH_params::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeBytes(nonce.get()); - stream->writeBytes(server_nonce.get()); - stream->writeByteArray(p.get()); - stream->writeByteArray(q.get()); - stream->writeInt64(public_key_fingerprint); - stream->writeByteArray(encrypted_data.get()); -} - -TLObject *TL_set_client_DH_params::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return Set_client_DH_params_answer::TLdeserialize(stream, constructor, error); -} - -void TL_set_client_DH_params::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeBytes(nonce.get()); - stream->writeBytes(server_nonce.get()); - stream->writeByteArray(encrypted_data.get()); -} - -TLObject *TL_rpc_drop_answer::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return RpcDropAnswer::TLdeserialize(stream, constructor, error); -} - -void TL_rpc_drop_answer::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt64(req_msg_id); -} - -TLObject *TL_get_future_salts::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return TL_future_salts::TLdeserialize(stream, constructor, error); -} - -void TL_get_future_salts::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(num); -} - -TLObject *TL_ping::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return TL_pong::TLdeserialize(stream, constructor, error); -} - -void TL_ping::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt64(ping_id); -} - -TLObject *TL_ping_delay_disconnect::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return TL_pong::TLdeserialize(stream, constructor, error); -} - -void TL_ping_delay_disconnect::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt64(ping_id); - stream->writeInt32(disconnect_delay); -} - -TLObject *TL_destroy_session::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return DestroySessionRes::TLdeserialize(stream, constructor, error); -} - -void TL_destroy_session::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt64(session_id); -} - -TL_gzip_packed::~TL_gzip_packed() { - if (packed_data_to_send != nullptr) { - packed_data_to_send->reuse(); - packed_data_to_send = nullptr; - } -} - -void TL_gzip_packed::readParams(NativeByteBuffer *stream, bool &error) { - packed_data = std::unique_ptr(stream->readByteBuffer(false, &error)); -} - -void TL_gzip_packed::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeByteArray(packed_data_to_send); -} - -TL_error *TL_error::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_error::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_error", constructor); - return nullptr; - } - TL_error *result = new TL_error(); - result->readParams(stream, error); - return result; -} - -void TL_error::readParams(NativeByteBuffer *stream, bool &error) { - code = stream->readInt32(&error); - text = stream->readString(&error); -} - -void TL_error::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(code); - stream->writeString(text); -} - -void TL_invokeAfterMsg::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt64(msg_id); - if (outgoingQuery != nullptr) { - outgoingQuery->serializeToStream(stream); - } else { - query->serializeToStream(stream); - } -} - -void invokeWithLayer::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(layer); - query->serializeToStream(stream); -} - -void initConnection::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(api_id); - stream->writeString(device_model); - stream->writeString(system_version); - stream->writeString(app_version); - stream->writeString(lang_code); - query->serializeToStream(stream); -} - -TL_dcOption *TL_dcOption::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_dcOption::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_dcOption", constructor); - return nullptr; - } - TL_dcOption *result = new TL_dcOption(); - result->readParams(stream, error); - return result; -} - -void TL_dcOption::readParams(NativeByteBuffer *stream, bool &error) { - flags = stream->readInt32(&error); - id = stream->readInt32(&error); - ip_address = stream->readString(&error); - port = stream->readInt32(&error); -} - -void TL_dcOption::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(flags); - stream->writeInt32(id); - stream->writeString(ip_address); - stream->writeInt32(port); -} - -TL_disabledFeature *TL_disabledFeature::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_disabledFeature::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_disabledFeature", constructor); - return nullptr; - } - TL_disabledFeature *result = new TL_disabledFeature(); - result->readParams(stream, error); - return result; -} - -void TL_disabledFeature::readParams(NativeByteBuffer *stream, bool &error) { - feature = stream->readString(&error); - description = stream->readString(&error); -} - -void TL_disabledFeature::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeString(feature); - stream->writeString(description); -} - -TL_config *TL_config::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_config::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_config", constructor); - return nullptr; - } - TL_config *result = new TL_config(); - result->readParams(stream, error); - return result; -} - -void TL_config::readParams(NativeByteBuffer *stream, bool &error) { - date = stream->readInt32(&error); - expires = stream->readInt32(&error); - test_mode = stream->readBool(&error); - this_dc = stream->readInt32(&error); - uint32_t magic = stream->readUint32(&error); - if (magic != 0x1cb5c415) { - error = true; - DEBUG_E("wrong Vector magic, got %x", magic); - return; - } - int32_t count = stream->readInt32(&error); - for (int32_t a = 0; a < count; a++) { - TL_dcOption *object = TL_dcOption::TLdeserialize(stream, stream->readUint32(&error), error); - if (object == nullptr) { - return; - } - dc_options.push_back(std::unique_ptr(object)); - } - chat_size_max = stream->readInt32(&error); - megagroup_size_max = stream->readInt32(&error); - forwarded_count_max = stream->readInt32(&error); - online_update_period_ms = stream->readInt32(&error); - offline_blur_timeout_ms = stream->readInt32(&error); - offline_idle_timeout_ms = stream->readInt32(&error); - online_cloud_timeout_ms = stream->readInt32(&error); - notify_cloud_delay_ms = stream->readInt32(&error); - notify_default_delay_ms = stream->readInt32(&error); - chat_big_size = stream->readInt32(&error); - push_chat_period_ms = stream->readInt32(&error); - push_chat_limit = stream->readInt32(&error); - saved_gifs_limit = stream->readInt32(&error); - edit_time_limit = stream->readInt32(&error); - rating_e_decay = stream->readInt32(&error); - magic = stream->readUint32(&error); - if (magic != 0x1cb5c415) { - error = true; - DEBUG_E("wrong Vector magic, got %x", magic); - return; - } - count = stream->readInt32(&error); - for (int32_t a = 0; a < count; a++) { - TL_disabledFeature *object = TL_disabledFeature::TLdeserialize(stream, stream->readUint32(&error), error); - if (object == nullptr) { - return; - } - disabled_features.push_back(std::unique_ptr(object)); - } -} - -void TL_config::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(date); - stream->writeInt32(expires); - stream->writeBool(test_mode); - stream->writeInt32(this_dc); - stream->writeInt32(0x1cb5c415); - uint32_t count = (uint32_t) dc_options.size(); - stream->writeInt32(count); - for (uint32_t a = 0; a < count; a++) { - dc_options[a]->serializeToStream(stream); - } - stream->writeInt32(chat_size_max); - stream->writeInt32(megagroup_size_max); - stream->writeInt32(forwarded_count_max); - stream->writeInt32(online_update_period_ms); - stream->writeInt32(offline_blur_timeout_ms); - stream->writeInt32(offline_idle_timeout_ms); - stream->writeInt32(online_cloud_timeout_ms); - stream->writeInt32(notify_cloud_delay_ms); - stream->writeInt32(notify_default_delay_ms); - stream->writeInt32(chat_big_size); - stream->writeInt32(push_chat_period_ms); - stream->writeInt32(push_chat_limit); - stream->writeInt32(saved_gifs_limit); - stream->writeInt32(edit_time_limit); - stream->writeInt32(rating_e_decay); - stream->writeInt32(0x1cb5c415); - count = (uint32_t) disabled_features.size(); - stream->writeInt32(count); - for (uint32_t a = 0; a < count; a++) { - disabled_features[a]->serializeToStream(stream); - } -} - -TLObject *TL_help_getConfig::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return TL_config::TLdeserialize(stream, constructor, error); -} - -void TL_help_getConfig::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -bool TL_help_getConfig::isNeedLayer() { - return true; -} - -Bool *Bool::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - Bool *result = nullptr; - switch (constructor) { - case 0x997275b5: - result = new TL_boolTrue(); - break; - case 0xbc799737: - result = new TL_boolFalse(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in Bool", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_boolTrue::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -void TL_boolFalse::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -bool TL_account_registerDevice::isNeedLayer() { - return true; -} - -TLObject *TL_account_registerDevice::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return Bool::TLdeserialize(stream, constructor, error); -} - -void TL_account_registerDevice::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(token_type); - stream->writeString(token); - stream->writeString(device_model); - stream->writeString(system_version); - stream->writeString(app_version); - stream->writeBool(app_sandbox); - stream->writeString(lang_code); -} - -User *User::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - User *result = nullptr; - switch (constructor) { - case 0x200250ba: - result = new TL_userEmpty(); - break; - case 0xd10d979a: - result = new TL_user(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in User", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_userEmpty::readParams(NativeByteBuffer *stream, bool &error) { - id = stream->readInt32(&error); -} - -void TL_userEmpty::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(id); -} - -void TL_user::readParams(NativeByteBuffer *stream, bool &error) { - flags = stream->readInt32(&error); - id = stream->readInt32(&error); - if ((flags & 1) != 0) { - access_hash = stream->readInt64(&error); - } - if ((flags & 2) != 0) { - first_name = stream->readString(&error); - } - if ((flags & 4) != 0) { - last_name = stream->readString(&error); - } - if ((flags & 8) != 0) { - username = stream->readString(&error); - } - if ((flags & 16) != 0) { - phone = stream->readString(&error); - } - if ((flags & 32) != 0) { - photo = std::unique_ptr(UserProfilePhoto::TLdeserialize(stream, stream->readUint32(&error), error)); - } - if ((flags & 64) != 0) { - status = std::unique_ptr(UserStatus::TLdeserialize(stream, stream->readUint32(&error), error)); - } - if ((flags & 16384) != 0) { - bot_info_version = stream->readInt32(&error); - } - if ((flags & 262144) != 0) { - restriction_reason = stream->readString(&error); - } - if ((flags & 524288) != 0) { - bot_inline_placeholder = stream->readString(&error); - } -} - -void TL_user::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(flags); - stream->writeInt32(id); - if ((flags & 1) != 0) { - stream->writeInt64(access_hash); - } - if ((flags & 2) != 0) { - stream->writeString(first_name); - } - if ((flags & 4) != 0) { - stream->writeString(last_name); - } - if ((flags & 8) != 0) { - stream->writeString(username); - } - if ((flags & 16) != 0) { - stream->writeString(phone); - } - if ((flags & 32) != 0) { - photo->serializeToStream(stream); - } - if ((flags & 64) != 0) { - status->serializeToStream(stream); - } - if ((flags & 16384) != 0) { - stream->writeInt32(bot_info_version); - } - if ((flags & 262144) != 0) { - stream->writeString(restriction_reason); - } - if ((flags & 524288) != 0) { - stream->writeString(bot_inline_placeholder); - } -} - -TL_auth_authorization *TL_auth_authorization::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_auth_authorization::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_auth_authorization", constructor); - return nullptr; - } - TL_auth_authorization *result = new TL_auth_authorization(); - result->readParams(stream, error); - return result; -} - -void TL_auth_authorization::readParams(NativeByteBuffer *stream, bool &error) { - user = std::unique_ptr(User::TLdeserialize(stream, stream->readUint32(&error), error)); -} - -TL_auth_exportedAuthorization *TL_auth_exportedAuthorization::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - if (TL_auth_exportedAuthorization::constructor != constructor) { - error = true; - DEBUG_E("can't parse magic %x in TL_auth_exportedAuthorization", constructor); - return nullptr; - } - TL_auth_exportedAuthorization *result = new TL_auth_exportedAuthorization(); - result->readParams(stream, error); - return result; -} - -void TL_auth_exportedAuthorization::readParams(NativeByteBuffer *stream, bool &error) { - id = stream->readInt32(&error); - bytes = std::unique_ptr(stream->readByteArray(&error)); -} - -bool TL_auth_exportAuthorization::isNeedLayer() { - return true; -} - -TLObject *TL_auth_exportAuthorization::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return TL_auth_exportedAuthorization::TLdeserialize(stream, constructor, error); -} - -void TL_auth_exportAuthorization::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(dc_id); -} - -bool TL_auth_importAuthorization::isNeedLayer() { - return true; -} - -TLObject *TL_auth_importAuthorization::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return TL_auth_authorization::TLdeserialize(stream, constructor, error); -} - -void TL_auth_importAuthorization::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(id); - stream->writeByteArray(bytes.get()); -} - -UserStatus *UserStatus::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - UserStatus *result = nullptr; - switch (constructor) { - case 0x8c703f: - result = new TL_userStatusOffline(); - break; - case 0x7bf09fc: - result = new TL_userStatusLastWeek(); - break; - case 0x9d05049: - result = new TL_userStatusEmpty(); - break; - case 0x77ebc742: - result = new TL_userStatusLastMonth(); - break; - case 0xedb93949: - result = new TL_userStatusOnline(); - break; - case 0xe26f42f1: - result = new TL_userStatusRecently(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in UserStatus", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_userStatusOffline::readParams(NativeByteBuffer *stream, bool &error) { - expires = stream->readInt32(&error); -} - -void TL_userStatusOffline::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(expires); -} - -void TL_userStatusLastWeek::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -void TL_userStatusEmpty::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -void TL_userStatusLastMonth::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -void TL_userStatusOnline::readParams(NativeByteBuffer *stream, bool &error) { - expires = stream->readInt32(&error); -} - -void TL_userStatusOnline::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(expires); -} - -void TL_userStatusRecently::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -FileLocation *FileLocation::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - FileLocation *result = nullptr; - switch (constructor) { - case 0x53d69076: - result = new TL_fileLocation(); - break; - case 0x7c596b46: - result = new TL_fileLocationUnavailable(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in FileLocation", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_fileLocation::readParams(NativeByteBuffer *stream, bool &error) { - dc_id = stream->readInt32(&error); - volume_id = stream->readInt64(&error); - local_id = stream->readInt32(&error); - secret = stream->readInt64(&error); -} - -void TL_fileLocation::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt32(dc_id); - stream->writeInt64(volume_id); - stream->writeInt32(local_id); - stream->writeInt64(secret); -} - -void TL_fileLocationUnavailable::readParams(NativeByteBuffer *stream, bool &error) { - volume_id = stream->readInt64(&error); - local_id = stream->readInt32(&error); - secret = stream->readInt64(&error); -} - -void TL_fileLocationUnavailable::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt64(volume_id); - stream->writeInt32(local_id); - stream->writeInt64(secret); -} - -UserProfilePhoto *UserProfilePhoto::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - UserProfilePhoto *result = nullptr; - switch (constructor) { - case 0x4f11bae1: - result = new TL_userProfilePhotoEmpty(); - break; - case 0xd559d8c8: - result = new TL_userProfilePhoto(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in UserProfilePhoto", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_userProfilePhotoEmpty::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} - -void TL_userProfilePhoto::readParams(NativeByteBuffer *stream, bool &error) { - photo_id = stream->readInt64(&error); - photo_small = std::unique_ptr(FileLocation::TLdeserialize(stream, stream->readUint32(&error), error)); - photo_big = std::unique_ptr(FileLocation::TLdeserialize(stream, stream->readUint32(&error), error)); -} - -void TL_userProfilePhoto::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeInt64(photo_id); - photo_small->serializeToStream(stream); - photo_big->serializeToStream(stream); -} - -auth_SentCode *auth_SentCode::TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - auth_SentCode *result = nullptr; - switch (constructor) { - case 0xe325edcf: - result = new TL_auth_sentAppCode(); - break; - case 0xefed51d9: - result = new TL_auth_sentCode(); - break; - default: - error = true; - DEBUG_E("can't parse magic %x in auth_SentCode", constructor); - return nullptr; - } - result->readParams(stream, error); - return result; -} - -void TL_auth_sentAppCode::readParams(NativeByteBuffer *stream, bool &error) { - phone_registered = stream->readBool(&error); - phone_code_hash = stream->readString(&error); - send_call_timeout = stream->readInt32(&error); - is_password = stream->readBool(&error); -} - -void TL_auth_sentAppCode::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeBool(phone_registered); - stream->writeString(phone_code_hash); - stream->writeInt32(send_call_timeout); - stream->writeBool(is_password); -} - -void TL_auth_sentCode::readParams(NativeByteBuffer *stream, bool &error) { - phone_registered = stream->readBool(&error); - phone_code_hash = stream->readString(&error); - send_call_timeout = stream->readInt32(&error); - is_password = stream->readBool(&error); -} - -void TL_auth_sentCode::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeBool(phone_registered); - stream->writeString(phone_code_hash); - stream->writeInt32(send_call_timeout); - stream->writeBool(is_password); -} - -TLObject *TL_auth_sendCode::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return auth_SentCode::TLdeserialize(stream, constructor, error); -} - -void TL_auth_sendCode::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); - stream->writeString(phone_number); - stream->writeInt32(sms_type); - stream->writeInt32(api_id); - stream->writeString(api_hash); - stream->writeString(lang_code); -} - -void TL_updatesTooLong::serializeToStream(NativeByteBuffer *stream) { - stream->writeInt32(constructor); -} diff --git a/TMessagesProj/jni/tgnet/MTProtoScheme.h b/TMessagesProj/jni/tgnet/MTProtoScheme.h deleted file mode 100644 index cb6b92148..000000000 --- a/TMessagesProj/jni/tgnet/MTProtoScheme.h +++ /dev/null @@ -1,990 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef MTPROTOSCHEME_H -#define MTPROTOSCHEME_H - -#include -#include -#include -#include -#include "TLObject.h" - -class ByteArray; -class NativeByteBuffer; - -class TLClassStore { - -public: - static TLObject *TLdeserialize(NativeByteBuffer *stream, uint32_t bytes, uint32_t constructor, bool &error); - -}; - -class TL_api_request : public TLObject { - -public: - NativeByteBuffer *request = nullptr; - - ~TL_api_request(); - bool isNeedLayer(); - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t bytes, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_api_response : public TLObject { - -public: - std::unique_ptr response; - - void readParamsEx(NativeByteBuffer *stream, uint32_t bytes, bool &error); -}; - -class TL_future_salt : public TLObject { - -public: - static const uint32_t constructor = 0x0949d9dc; - - int32_t valid_since; - int32_t valid_until; - int64_t salt; - - static TL_future_salt *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_msgs_state_info : public TLObject { - -public: - static const uint32_t constructor = 0x04deb57d; - - int64_t req_msg_id; - std::unique_ptr info; - - static TL_msgs_state_info *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class Server_DH_Params : public TLObject { - -public: - std::unique_ptr nonce; - std::unique_ptr server_nonce; - std::unique_ptr new_nonce_hash; - std::unique_ptr encrypted_answer; - - static Server_DH_Params *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_server_DH_params_fail : public Server_DH_Params { - -public: - static const uint32_t constructor = 0x79cb045d; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_server_DH_params_ok : public Server_DH_Params { - -public: - static const uint32_t constructor = 0xd0e8075c; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_resPQ : public TLObject { - -public: - static const uint32_t constructor = 0x05162463; - - std::unique_ptr nonce; - std::unique_ptr server_nonce; - std::unique_ptr pq; - std::vector server_public_key_fingerprints; - - static TL_resPQ *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_p_q_inner_data : public TLObject { - -public: - static const uint32_t constructor = 0x83c95aec; - - std::unique_ptr pq; - std::unique_ptr p; - std::unique_ptr q; - std::unique_ptr nonce; - std::unique_ptr server_nonce; - std::unique_ptr new_nonce; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_pong : public TLObject { - -public: - static const uint32_t constructor = 0x347773c5; - - int64_t msg_id; - int64_t ping_id; - - static TL_pong *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_future_salts : public TLObject { - -public: - static const uint32_t constructor = 0xae500895; - - int64_t req_msg_id; - int32_t now; - std::vector> salts; - - static TL_future_salts *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class RpcDropAnswer : public TLObject { - -public: - int64_t msg_id; - int32_t seq_no; - int32_t bytes; - - static RpcDropAnswer *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_rpc_answer_unknown : public RpcDropAnswer { - -public: - static const uint32_t constructor = 0x5e2ad36e; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_rpc_answer_dropped : public RpcDropAnswer { - -public: - static const uint32_t constructor = 0xa43ad8b7; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_rpc_answer_dropped_running : public RpcDropAnswer { - -public: - static const uint32_t constructor = 0xcd78e586; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class Set_client_DH_params_answer : public TLObject { - -public: - std::unique_ptr nonce; - std::unique_ptr server_nonce; - std::unique_ptr new_nonce_hash2; - std::unique_ptr new_nonce_hash3; - std::unique_ptr new_nonce_hash1; - - static Set_client_DH_params_answer *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_message : public TLObject { - -public: - static const uint32_t constructor = 0x5bb8e511; - - int64_t msg_id; - int32_t seqno; - int32_t bytes; - std::unique_ptr body; - TLObject *outgoingBody = nullptr; - std::unique_ptr unparsedBody; - - static TL_message *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_dh_gen_retry : public Set_client_DH_params_answer { - -public: - static const uint32_t constructor = 0x46dc1fb9; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_dh_gen_fail : public Set_client_DH_params_answer { - -public: - static const uint32_t constructor = 0xa69dae02; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_dh_gen_ok : public Set_client_DH_params_answer { - -public: - static const uint32_t constructor = 0x3bcbf734; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class BadMsgNotification : public TLObject { - -public: - int64_t bad_msg_id; - int32_t bad_msg_seqno; - int32_t error_code; - int64_t new_server_salt; - - static BadMsgNotification *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_bad_msg_notification : public BadMsgNotification { - -public: - static const uint32_t constructor = 0xa7eff811; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_bad_server_salt : public BadMsgNotification { - -public: - static const uint32_t constructor = 0xedab447b; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_msgs_state_req : public TLObject { - -public: - static const uint32_t constructor = 0xda69fb52; - - std::vector msg_ids; - - static TL_msgs_state_req *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class MsgDetailedInfo : public TLObject { - -public: - int64_t answer_msg_id; - int32_t bytes; - int32_t status; - int64_t msg_id; - - static MsgDetailedInfo *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_msg_new_detailed_info : public MsgDetailedInfo { - -public: - static const uint32_t constructor = 0x809db6df; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_msg_detailed_info : public MsgDetailedInfo { - -public: - static const uint32_t constructor = 0x276d3ec6; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_msg_copy : public TLObject { - -public: - static const uint32_t constructor = 0xe06046b2; - - std::unique_ptr orig_message; - - static TL_msg_copy *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_msgs_all_info : public TLObject { - -public: - static const uint32_t constructor = 0x8cc0d131; - - std::vector msg_ids; - std::unique_ptr info; - - static TL_msgs_all_info *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_rpc_result : public TLObject { - -public: - static const uint32_t constructor = 0xf35c6d01; - - int64_t req_msg_id; - std::unique_ptr result; - - void readParamsEx(NativeByteBuffer *stream, uint32_t bytes, bool &error); -}; - -class TL_new_session_created : public TLObject { - -public: - static const uint32_t constructor = 0x9ec20908; - - int64_t first_msg_id; - int64_t unique_id; - int64_t server_salt; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class DestroySessionRes : public TLObject { - -public: - int64_t session_id; - - static DestroySessionRes *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_destroy_session_ok : public DestroySessionRes { - -public: - static const uint32_t constructor = 0xe22045fc; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_destroy_session_none : public DestroySessionRes { - -public: - static const uint32_t constructor = 0x62d350c9; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_msgs_ack : public TLObject { - -public: - static const uint32_t constructor = 0x62d6b459; - - std::vector msg_ids; - - static TL_msgs_ack *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_msg_container : public TLObject { - -public: - static const uint32_t constructor = 0x73f1f8dc; - - std::vector> messages; - - static TL_msg_container *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_msg_resend_req : public TLObject { - -public: - static const uint32_t constructor = 0x7d861a08; - - std::vector msg_ids; - - static TL_msg_resend_req *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class RpcError : public TLObject { - -public: - int32_t error_code; - std::string error_message; - int64_t query_id; -}; - -class TL_rpc_error : public RpcError { - -public: - static const uint32_t constructor = 0x2144ca19; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_rpc_req_error : public RpcError { - -public: - static const uint32_t constructor = 0x7ae432f5; - - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_client_DH_inner_data : public TLObject { - -public: - static const uint32_t constructor = 0x6643b654; - - std::unique_ptr nonce; - std::unique_ptr server_nonce; - int64_t retry_id; - std::unique_ptr g_b; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_server_DH_inner_data : public TLObject { - -public: - static const uint32_t constructor = 0xb5890dba; - - std::unique_ptr nonce; - std::unique_ptr server_nonce; - uint32_t g; - std::unique_ptr dh_prime; - std::unique_ptr g_a; - int32_t server_time; - - static TL_server_DH_inner_data *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_req_pq : public TLObject { - -public: - static const uint32_t constructor = 0x60469778; - - std::unique_ptr nonce; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_req_DH_params : public TLObject { - -public: - static const uint32_t constructor = 0xd712e4be; - - std::unique_ptr nonce; - std::unique_ptr server_nonce; - std::unique_ptr p; - std::unique_ptr q; - int64_t public_key_fingerprint; - std::unique_ptr encrypted_data; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_set_client_DH_params : public TLObject { - -public: - static const uint32_t constructor = 0xf5045f1f; - - std::unique_ptr nonce; - std::unique_ptr server_nonce; - std::unique_ptr encrypted_data; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_rpc_drop_answer : public TLObject { - -public: - static const uint32_t constructor = 0x58e4a740; - - int64_t req_msg_id; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_get_future_salts : public TLObject { - -public: - static const uint32_t constructor = 0xb921bd04; - - int32_t num; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_ping : public TLObject { - -public: - static const uint32_t constructor = 0x7abe77ec; - - int64_t ping_id; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_ping_delay_disconnect : public TLObject { - -public: - static const uint32_t constructor = 0xf3427b8c; - - int64_t ping_id; - int32_t disconnect_delay; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_destroy_session : public TLObject { - -public: - static const uint32_t constructor = 0xe7512126; - - int64_t session_id; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_gzip_packed : public TLObject { - -public: - static const uint32_t constructor = 0x3072cfa1; - - NativeByteBuffer *packed_data_to_send = nullptr; - std::unique_ptr packed_data; - std::unique_ptr originalRequest; - - ~TL_gzip_packed(); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_error : public TLObject { - -public: - static const uint32_t constructor = 0xc4b9f9bb; - - int32_t code; - std::string text; - - static TL_error *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_invokeAfterMsg : public TLObject { - -public: - static const uint32_t constructor = 0xcb9f372d; - - int64_t msg_id; - TLObject *outgoingQuery = nullptr; - std::unique_ptr query; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class invokeWithLayer : public TLObject { - -public: - static const uint32_t constructor = 0xda9b0d0d; - - int32_t layer; - std::unique_ptr query; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class initConnection : public TLObject { - -public: - static const uint32_t constructor = 0x69796de9; - - int32_t api_id; - std::string device_model; - std::string system_version; - std::string app_version; - std::string lang_code; - std::unique_ptr query; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_dcOption : public TLObject { - -public: - static const uint32_t constructor = 0x5d8c6cc; - - int32_t flags; - int32_t id; - std::string ip_address; - int32_t port; - - static TL_dcOption *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_disabledFeature : public TLObject { - -public: - static const uint32_t constructor = 0xae636f24; - - std::string feature; - std::string description; - - static TL_disabledFeature *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_config : public TLObject { - -public: - static const uint32_t constructor = 0xc9411388; - - int32_t date; - int32_t expires; - bool test_mode; - int32_t this_dc; - std::vector> dc_options; - int32_t chat_size_max; - int32_t megagroup_size_max; - int32_t forwarded_count_max; - int32_t online_update_period_ms; - int32_t offline_blur_timeout_ms; - int32_t offline_idle_timeout_ms; - int32_t online_cloud_timeout_ms; - int32_t notify_cloud_delay_ms; - int32_t notify_default_delay_ms; - int32_t chat_big_size; - int32_t push_chat_period_ms; - int32_t push_chat_limit; - int32_t saved_gifs_limit; - int32_t edit_time_limit; - int32_t rating_e_decay; - std::vector> disabled_features; - - static TL_config *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_help_getConfig : public TLObject { - -public: - static const uint32_t constructor = 0xc4f9186b; - - bool isNeedLayer(); - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class Bool : public TLObject { - -public: - static Bool *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_boolTrue : public Bool { - -public: - static const uint32_t constructor = 0x997275b5; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_boolFalse : public Bool { - -public: - static const uint32_t constructor = 0xbc799737; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_account_registerDevice : public TLObject { - -public: - static const uint32_t constructor = 0x446c712c; - - int32_t token_type; - std::string token; - std::string device_model; - std::string system_version; - std::string app_version; - bool app_sandbox; - std::string lang_code; - - bool isNeedLayer(); - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class UserStatus : public TLObject { - -public: - int32_t expires; - - static UserStatus *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_userStatusOffline : public UserStatus { - -public: - static const uint32_t constructor = 0x8c703f; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_userStatusLastWeek : public UserStatus { - -public: - static const uint32_t constructor = 0x7bf09fc; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_userStatusEmpty : public UserStatus { - -public: - static const uint32_t constructor = 0x9d05049; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_userStatusLastMonth : public UserStatus { - -public: - static const uint32_t constructor = 0x77ebc742; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_userStatusOnline : public UserStatus { - -public: - static const uint32_t constructor = 0xedb93949; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_userStatusRecently : public UserStatus { - -public: - static const uint32_t constructor = 0xe26f42f1; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class FileLocation : public TLObject { - -public: - int32_t dc_id; - int64_t volume_id; - int32_t local_id; - int64_t secret; - - static FileLocation *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_fileLocation : public FileLocation { - -public: - static const uint32_t constructor = 0x53d69076; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_fileLocationUnavailable : public FileLocation { - -public: - static const uint32_t constructor = 0x7c596b46; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class UserProfilePhoto : public TLObject { - -public: - int64_t photo_id; - std::unique_ptr photo_small; - std::unique_ptr photo_big; - - static UserProfilePhoto *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_userProfilePhotoEmpty : public UserProfilePhoto { - -public: - static const uint32_t constructor = 0x4f11bae1; - - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_userProfilePhoto : public UserProfilePhoto { - -public: - static const uint32_t constructor = 0xd559d8c8; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class User : public TLObject { - -public: - int32_t id; - std::string first_name; - std::string last_name; - std::string username; - int64_t access_hash; - std::string phone; - std::unique_ptr photo; - std::unique_ptr status; - int32_t flags; - int32_t bot_info_version; - std::string restriction_reason; - std::string bot_inline_placeholder; - - static User *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_userEmpty : public User { - -public: - static const uint32_t constructor = 0x200250ba; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_user : public User { - -public: - static const uint32_t constructor = 0xd10d979a; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_auth_authorization : public TLObject { - -public: - static const uint32_t constructor = 0xff036af1; - - std::unique_ptr user; - - static TL_auth_authorization *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_auth_exportedAuthorization : public TLObject { - -public: - static const uint32_t constructor = 0xdf969c2d; - - int32_t id; - std::unique_ptr bytes; - - static TL_auth_exportedAuthorization *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void readParams(NativeByteBuffer *stream, bool &error); -}; - -class TL_auth_exportAuthorization : public TLObject { - -public: - static const uint32_t constructor = 0xe5bfffcd; - - int32_t dc_id; - - bool isNeedLayer(); - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_auth_importAuthorization : public TLObject { - -public: - static const uint32_t constructor = 0xe3ef9613; - - int32_t id; - std::unique_ptr bytes; - - bool isNeedLayer(); - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class auth_SentCode : public TLObject { - -public: - bool phone_registered; - std::string phone_code_hash; - int32_t send_call_timeout; - bool is_password; - - static auth_SentCode *TLdeserialize(NativeByteBuffer *stream, uint32_t constructor, bool &error); -}; - -class TL_auth_sentAppCode : public auth_SentCode { - -public: - static const uint32_t constructor = 0xe325edcf; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_auth_sentCode : public auth_SentCode { - -public: - static const uint32_t constructor = 0xefed51d9; - - void readParams(NativeByteBuffer *stream, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_auth_sendCode : public TLObject { - -public: - static const uint32_t constructor = 0x768d5f4d; - - std::string phone_number; - int32_t sms_type; - int32_t api_id; - std::string api_hash; - std::string lang_code; - - TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - void serializeToStream(NativeByteBuffer *stream); -}; - -class TL_updatesTooLong : public TLObject { - -public: - static const uint32_t constructor = 0xe317af7e; - - void serializeToStream(NativeByteBuffer *stream); -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/NativeByteBuffer.cpp b/TMessagesProj/jni/tgnet/NativeByteBuffer.cpp deleted file mode 100644 index 19f36f067..000000000 --- a/TMessagesProj/jni/tgnet/NativeByteBuffer.cpp +++ /dev/null @@ -1,703 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include -#include "NativeByteBuffer.h" -#include "FileLog.h" -#include "ByteArray.h" -#include "ConnectionsManager.h" -#include "BuffersStorage.h" - -NativeByteBuffer::NativeByteBuffer(uint32_t size) { -#ifdef ANDROID - if (jclass_ByteBuffer != nullptr) { - JNIEnv *env = 0; - if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { - DEBUG_E("can't get jnienv"); - exit(1); - } - javaByteBuffer = env->CallStaticObjectMethod(jclass_ByteBuffer, jclass_ByteBuffer_allocateDirect, size); - if (javaByteBuffer == nullptr) { - DEBUG_E("can't create javaByteBuffer"); - exit(1); - } - jobject globalRef = env->NewGlobalRef(javaByteBuffer); - env->DeleteLocalRef(javaByteBuffer); - javaByteBuffer = globalRef; - buffer = (uint8_t *) env->GetDirectBufferAddress(javaByteBuffer); - bufferOwner = false; - } else { -#endif - buffer = new uint8_t[size]; - bufferOwner = true; -#ifdef ANDROID - } -#endif - if (buffer == nullptr) { - DEBUG_E("can't allocate NativeByteBuffer buffer"); - exit(1); - } - _limit = _capacity = size; -} - -NativeByteBuffer::NativeByteBuffer(bool calculate) { - calculateSizeOnly = calculate; -} - -NativeByteBuffer::NativeByteBuffer(uint8_t *buff, uint32_t length) { - buffer = buff; - sliced = true; - _limit = _capacity = length; -} - -NativeByteBuffer::~NativeByteBuffer() { -#ifdef ANDROID - if (javaByteBuffer != nullptr) { - JNIEnv *env = 0; - if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { - DEBUG_E("can't get jnienv"); - exit(1); - } - env->DeleteGlobalRef(javaByteBuffer); - javaByteBuffer = nullptr; - } -#endif - if (bufferOwner && !sliced && buffer != nullptr) { - delete[] buffer; - buffer = nullptr; - } -} - -uint32_t NativeByteBuffer::position() { - return _position; -} - -void NativeByteBuffer::position(uint32_t position) { - if (position > _limit) { - return; - } - _position = position; -} - -uint32_t NativeByteBuffer::capacity() { - return _capacity; -} - -uint32_t NativeByteBuffer::limit() { - return _limit; -} - -uint32_t NativeByteBuffer::remaining() { - return _limit - _position; -} - -void NativeByteBuffer::clearCapacity() { - if (!calculateSizeOnly) { - return; - } - _capacity = 0; -} - -void NativeByteBuffer::limit(uint32_t limit) { - if (limit > _capacity) { - return; - } - if (_position > limit) { - _position = limit; - } - _limit = limit; -} - -void NativeByteBuffer::flip() { - _limit = _position; - _position = 0; -} - -void NativeByteBuffer::clear() { - _position = 0; - _limit = _capacity; -} - -uint8_t *NativeByteBuffer::bytes() { - return buffer; -} - -void NativeByteBuffer::rewind() { - _position = 0; -} - -void NativeByteBuffer::compact() { - if (_position == _limit) { - return; - } - memmove(buffer, buffer + _position, sizeof(uint8_t) * (_limit - _position)); - _position = (_limit - _position); - _limit = _capacity; -} - -bool NativeByteBuffer::hasRemaining() { - return _position < _limit; -} - -void NativeByteBuffer::skip(uint32_t length) { - if (!calculateSizeOnly) { - if (_position + length > _limit) { - return; - } - _position += length; - } else { - _capacity += length; - } -} - -void NativeByteBuffer::writeInt32(int32_t x, bool *error) { - if (!calculateSizeOnly) { - if (_position + 4 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write int32 error"); - return; - } - buffer[_position++] = (uint8_t) x; - buffer[_position++] = (uint8_t) (x >> 8); - buffer[_position++] = (uint8_t) (x >> 16); - buffer[_position++] = (uint8_t) (x >> 24); - } else { - _capacity += 4; - } -} - -void NativeByteBuffer::writeInt64(int64_t x, bool *error) { - if (!calculateSizeOnly) { - if (_position + 8 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write int64 error"); - return; - } - buffer[_position++] = (uint8_t) x; - buffer[_position++] = (uint8_t) (x >> 8); - buffer[_position++] = (uint8_t) (x >> 16); - buffer[_position++] = (uint8_t) (x >> 24); - buffer[_position++] = (uint8_t) (x >> 32); - buffer[_position++] = (uint8_t) (x >> 40); - buffer[_position++] = (uint8_t) (x >> 48); - buffer[_position++] = (uint8_t) (x >> 56); - } else { - _capacity += 8; - } -} - -void NativeByteBuffer::writeBool(bool value, bool *error) { - if (!calculateSizeOnly) { - if (value) { - writeInt32(0x997275b5, error); - } else { - writeInt32(0xbc799737, error); - } - } else { - _capacity += 4; - } -} - -void NativeByteBuffer::writeBytes(uint8_t *b, uint32_t length, bool *error) { - if (!calculateSizeOnly) { - if (_position + length > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write bytes error"); - return; - } - writeBytesInternal(b, 0, length); - } else { - _capacity += length; - } -} - -void NativeByteBuffer::writeBytes(uint8_t *b, uint32_t offset, uint32_t length, bool *error) { - if (!calculateSizeOnly) { - if (_position + length > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write bytes error"); - return; - } - writeBytesInternal(b, offset, length); - } else { - _capacity += length; - } -} - -void NativeByteBuffer::writeBytes(NativeByteBuffer *b, bool *error) { - uint32_t length = b->_limit - b->_position; - if (length == 0) { - return; - } - if (!calculateSizeOnly) { - if (_position + length > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write bytes error"); - return; - } - writeBytesInternal(b->buffer + b->_position, 0, length); - b->position(b->limit()); - } else { - _capacity += length; - } -} - -void NativeByteBuffer::writeBytes(ByteArray *b, bool *error) { - if (!calculateSizeOnly) { - if (_position + b->length > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write bytes error"); - return; - } - writeBytesInternal(b->bytes, 0, b->length); - } else { - _capacity += b->length; - } -} - -void NativeByteBuffer::writeBytesInternal(uint8_t *b, uint32_t offset, uint32_t length) { - memcpy(buffer + _position, b + offset, sizeof(uint8_t) * length); - _position += length; -} - -void NativeByteBuffer::writeByte(uint8_t i, bool *error) { - if (!calculateSizeOnly) { - if (_position + 1 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write byte error"); - return; - } - buffer[_position++] = i; - } else { - _capacity += 1; - } -} - -void NativeByteBuffer::writeString(std::string s, bool *error) { - writeByteArray((uint8_t *) s.c_str(), (uint32_t) s.length(), error); -} - -void NativeByteBuffer::writeByteArray(uint8_t *b, uint32_t offset, uint32_t length, bool *error) { - if (length <= 253) { - if (!calculateSizeOnly) { - if (_position + 1 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write byte array error"); - return; - } - buffer[_position++] = (uint8_t) length; - } else { - _capacity += 1; - } - } else { - if (!calculateSizeOnly) { - if (_position + 4 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write byte array error"); - return; - } - buffer[_position++] = (uint8_t) 254; - buffer[_position++] = (uint8_t) length; - buffer[_position++] = (uint8_t) (length >> 8); - buffer[_position++] = (uint8_t) (length >> 16); - } else { - _capacity += 4; - } - } - if (!calculateSizeOnly) { - if (_position + length > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write byte array error"); - return; - } - writeBytesInternal(b, offset, length); - } else { - _capacity += length; - } - uint32_t addition = (length + (length <= 253 ? 1 : 4)) % 4; - if (addition != 0) { - addition = 4 - addition; - } - if (!calculateSizeOnly && _position + addition > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("write byte array error"); - return; - } - for (uint32_t a = 0; a < addition; a++) { - if (!calculateSizeOnly) { - buffer[_position++] = (uint8_t) 0; - } else { - _capacity += 1; - } - } -} - -void NativeByteBuffer::writeByteArray(uint8_t *b, uint32_t length, bool *error) { - writeByteArray(b, 0, length, error); -} - -void NativeByteBuffer::writeByteArray(NativeByteBuffer *b, bool *error) { - b->rewind(); - writeByteArray(b->buffer, 0, b->limit(), error); -} - -void NativeByteBuffer::writeByteArray(ByteArray *b, bool *error) { - writeByteArray(b->bytes, 0, b->length, error); -} - -void NativeByteBuffer::writeDouble(double d, bool *error) { - int64_t value; - memcpy(&value, &d, sizeof(int64_t)); - writeInt64(value, error); -} - -void NativeByteBuffer::writeInt32(int32_t x) { - writeInt32(x, nullptr); -} - -void NativeByteBuffer::writeInt64(int64_t x) { - writeInt64(x, nullptr); -} - -void NativeByteBuffer::writeBool(bool value) { - writeBool(value, nullptr); -} - -void NativeByteBuffer::writeBytes(uint8_t *b, uint32_t length) { - writeBytes(b, length, nullptr); -} - -void NativeByteBuffer::writeBytes(uint8_t *b, uint32_t offset, uint32_t length) { - writeBytes(b, offset, length, nullptr); -} - -void NativeByteBuffer::writeBytes(ByteArray *b) { - writeBytes(b, nullptr); -} - -void NativeByteBuffer::writeBytes(NativeByteBuffer *b) { - writeBytes(b, nullptr); -} - -void NativeByteBuffer::writeByte(uint8_t i) { - writeByte(i, nullptr); -} - -void NativeByteBuffer::writeString(std::string s) { - writeString(s, nullptr); -} - -void NativeByteBuffer::writeByteArray(uint8_t *b, uint32_t offset, uint32_t length) { - writeByteArray(b, offset, length, nullptr); -} - -void NativeByteBuffer::writeByteArray(uint8_t *b, uint32_t length) { - writeByteArray(b, length, nullptr); -} - -void NativeByteBuffer::writeByteArray(NativeByteBuffer *b) { - writeByteArray(b, nullptr); -} - -void NativeByteBuffer::writeByteArray(ByteArray *b) { - writeByteArray(b->bytes, b->length, nullptr); -} - -void NativeByteBuffer::writeDouble(double d) { - writeDouble(d, nullptr); -} - -int32_t NativeByteBuffer::readInt32(bool *error) { - if (_position + 4 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read int32 error"); - return 0; - } - int32_t result = ((buffer[_position] & 0xff)) | - ((buffer[_position + 1] & 0xff) << 8) | - ((buffer[_position + 2] & 0xff) << 16) | - ((buffer[_position + 3] & 0xff) << 24); - _position += 4; - return result; -} - -uint32_t NativeByteBuffer::readUint32(bool *error) { - return (uint32_t) readInt32(error); -} - -uint64_t NativeByteBuffer::readUint64(bool *error) { - return (uint64_t) readInt64(error); -} - -int32_t NativeByteBuffer::readBigInt32(bool *error) { - if (_position + 4 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read big int32 error"); - return 0; - } - int32_t result = ((buffer[_position] & 0xff) << 24) | - ((buffer[_position + 1] & 0xff) << 16) | - ((buffer[_position + 2] & 0xff) << 8) | - ((buffer[_position + 3] & 0xff)); - _position += 4; - return result; -} - -int64_t NativeByteBuffer::readInt64(bool *error) { - if (_position + 4 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read int64 error"); - return 0; - } - int64_t result = ((int64_t) (buffer[_position] & 0xff)) | - ((int64_t) (buffer[_position + 1] & 0xff) << 8) | - ((int64_t) (buffer[_position + 2] & 0xff) << 16) | - ((int64_t) (buffer[_position + 3] & 0xff) << 24) | - ((int64_t) (buffer[_position + 4] & 0xff) << 32) | - ((int64_t) (buffer[_position + 5] & 0xff) << 40) | - ((int64_t) (buffer[_position + 6] & 0xff) << 48) | - ((int64_t) (buffer[_position + 7] & 0xff) << 56); - _position += 8; - return result; -} - -uint8_t NativeByteBuffer::readByte(bool *error) { - if (_position + 1 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read byte error"); - return 0; - } - return buffer[_position++]; -} - -bool NativeByteBuffer::readBool(bool *error) { - uint32_t consructor = readUint32(error); - if (consructor == 0x997275b5) { - return true; - } else if (consructor == 0xbc799737) { - return false; - } - if (error != nullptr) { - *error = true; - DEBUG_E("read bool error"); - } - return false; -} - -void NativeByteBuffer::readBytes(uint8_t *b, uint32_t length, bool *error) { - if (_position + length > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read bytes error"); - return; - } - memcpy(b, buffer + _position, length); - _position += length; -} - -ByteArray *NativeByteBuffer::readBytes(uint32_t length, bool *error) { - if (_position + length > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read bytes error"); - return nullptr; - } - ByteArray *byteArray = new ByteArray(length); - memcpy(byteArray->bytes, buffer + _position, sizeof(uint8_t) * length); - _position += length; - return byteArray; -} - -std::string NativeByteBuffer::readString(bool *error) { - uint32_t sl = 1; - if (_position + 1 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read string error"); - return std::string(""); - } - uint32_t l = buffer[_position++]; - if (l >= 254) { - if (_position + 3 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read string error"); - return std::string(""); - } - l = buffer[_position] | (buffer[_position + 1] << 8) | (buffer[_position + 2] << 16); - _position += 3; - sl = 4; - } - uint32_t addition = (l + sl) % 4; - if (addition != 0) { - addition = 4 - addition; - } - if (_position + l + addition > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read string error"); - return std::string(""); - } - std::string result = std::string((const char *) (buffer + _position), l); - _position += l + addition; - return result; -} - -ByteArray *NativeByteBuffer::readByteArray(bool *error) { - uint32_t sl = 1; - if (_position + 1 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read byte array error"); - return nullptr; - } - uint32_t l = buffer[_position++]; - if (l >= 254) { - if (_position + 3 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read byte array error"); - return nullptr; - } - l = buffer[_position] | (buffer[_position + 1] << 8) | (buffer[_position + 2] << 16); - _position += 3; - sl = 4; - } - uint32_t addition = (l + sl) % 4; - if (addition != 0) { - addition = 4 - addition; - } - if (_position + l + addition > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read byte array error"); - return nullptr; - } - ByteArray *result = new ByteArray(l); - memcpy(result->bytes, buffer + _position, sizeof(uint8_t) * l); - _position += l + addition; - return result; -} - -NativeByteBuffer *NativeByteBuffer::readByteBuffer(bool copy, bool *error) { - uint32_t sl = 1; - if (_position + 1 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read byte buffer error"); - return nullptr; - } - uint32_t l = buffer[_position++]; - if (l >= 254) { - if (_position + 3 > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read byte buffer error"); - return nullptr; - } - l = buffer[_position] | (buffer[_position + 1] << 8) | (buffer[_position + 2] << 16); - _position += 3; - sl = 4; - } - uint32_t addition = (l + sl) % 4; - if (addition != 0) { - addition = 4 - addition; - } - if (_position + l + addition > _limit) { - if (error != nullptr) { - *error = true; - } - DEBUG_E("read byte buffer error"); - return nullptr; - } - NativeByteBuffer *result = nullptr; - if (copy) { - result = BuffersStorage::getInstance().getFreeBuffer(l); - memcpy(result->buffer, buffer + _position, sizeof(uint8_t) * l); - } else { - result = new NativeByteBuffer(buffer + _position, l); - } - _position += l + addition; - return result; -} - -double NativeByteBuffer::readDouble(bool *error) { - double value; - int64_t value2 = readInt64(error); - memcpy(&value, &value2, sizeof(double)); - return value; -} - -void NativeByteBuffer::reuse() { - if (sliced) { - return; - } - BuffersStorage::getInstance().reuseFreeBuffer(this); -} - -#ifdef ANDROID -jobject NativeByteBuffer::getJavaByteBuffer() { - if (javaByteBuffer == nullptr && javaVm != nullptr) { - JNIEnv *env = 0; - if (javaVm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { - DEBUG_E("can't get jnienv"); - exit(1); - } - javaByteBuffer = env->NewDirectByteBuffer(buffer, _capacity); - if (javaByteBuffer == nullptr) { - DEBUG_E("can't allocate NativeByteBuffer buffer"); - exit(1); - } - jobject globalRef = env->NewGlobalRef(javaByteBuffer); - env->DeleteLocalRef(javaByteBuffer); - javaByteBuffer = globalRef; - } - return javaByteBuffer; -} -#endif diff --git a/TMessagesProj/jni/tgnet/NativeByteBuffer.h b/TMessagesProj/jni/tgnet/NativeByteBuffer.h deleted file mode 100644 index 1abbbef11..000000000 --- a/TMessagesProj/jni/tgnet/NativeByteBuffer.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef NATIVEBYTEBUFFER_H -#define NATIVEBYTEBUFFER_H - -#include -#include - -#ifdef ANDROID -#include -#endif - -class ByteArray; - -class NativeByteBuffer { - -public: - NativeByteBuffer(uint32_t size); - NativeByteBuffer(bool calculate); - NativeByteBuffer(uint8_t *buff, uint32_t length); - ~NativeByteBuffer(); - - uint32_t position(); - void position(uint32_t position); - uint32_t limit(); - void limit(uint32_t limit); - uint32_t capacity(); - uint32_t remaining(); - bool hasRemaining(); - void rewind(); - void compact(); - void flip(); - void clear(); - void skip(uint32_t length); - void clearCapacity(); - uint8_t *bytes(); - - void writeInt32(int32_t x, bool *error); - void writeInt64(int64_t x, bool *error); - void writeBool(bool value, bool *error); - void writeBytes(uint8_t *b, uint32_t length, bool *error); - void writeBytes(uint8_t *b, uint32_t offset, uint32_t length, bool *error); - void writeBytes(ByteArray *b, bool *error); - void writeBytes(NativeByteBuffer *b, bool *error); - void writeByte(uint8_t i, bool *error); - void writeString(std::string s, bool *error); - void writeByteArray(uint8_t *b, uint32_t offset, uint32_t length, bool *error); - void writeByteArray(uint8_t *b, uint32_t length, bool *error); - void writeByteArray(NativeByteBuffer *b, bool *error); - void writeByteArray(ByteArray *b, bool *error); - void writeDouble(double d, bool *error); - void writeInt32(int32_t x); - void writeInt64(int64_t x); - void writeBool(bool value); - void writeBytes(uint8_t *b, uint32_t length); - void writeBytes(uint8_t *b, uint32_t offset, uint32_t length); - void writeBytes(ByteArray *b); - void writeBytes(NativeByteBuffer *b); - void writeByte(uint8_t i); - void writeString(std::string s); - void writeByteArray(uint8_t *b, uint32_t offset, uint32_t length); - void writeByteArray(uint8_t *b, uint32_t length); - void writeByteArray(NativeByteBuffer *b); - void writeByteArray(ByteArray *b); - void writeDouble(double d); - - uint32_t readUint32(bool *error); - uint64_t readUint64(bool *error); - int32_t readInt32(bool *error); - int32_t readBigInt32(bool *error); - int64_t readInt64(bool *error); - uint8_t readByte(bool *error); - bool readBool(bool *error); - void readBytes(uint8_t *b, uint32_t length, bool *error); - ByteArray *readBytes(uint32_t length, bool *error); - std::string readString(bool *error); - ByteArray *readByteArray(bool *error); - NativeByteBuffer *readByteBuffer(bool copy, bool *error); - double readDouble(bool *error); - - void reuse(); -#ifdef ANDROID - jobject getJavaByteBuffer(); -#endif - -private: - void writeBytesInternal(uint8_t *b, uint32_t offset, uint32_t length); - - uint8_t *buffer = nullptr; - bool calculateSizeOnly = false; - bool sliced = false; - uint32_t _position = 0; - uint32_t _limit = 0; - uint32_t _capacity = 0; - bool bufferOwner = true; -#ifdef ANDROID - jobject javaByteBuffer = nullptr; -#endif -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/Request.cpp b/TMessagesProj/jni/tgnet/Request.cpp deleted file mode 100644 index 583e8ffe1..000000000 --- a/TMessagesProj/jni/tgnet/Request.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include -#include "Request.h" -#include "TLObject.h" -#include "MTProtoScheme.h" -#include "ConnectionsManager.h" - -Request::Request(int32_t token, ConnectionType type, uint32_t flags, uint32_t datacenter, onCompleteFunc completeFunc, onQuickAckFunc quickAckFunc) { - requestToken = token; - connectionType = type; - requestFlags = flags; - datacenterId = datacenter; - onCompleteRequestCallback = completeFunc; - onQuickAckCallback = quickAckFunc; -} - -Request::~Request() { -#ifdef ANDROID - if (ptr1 != nullptr) { - jniEnv->DeleteGlobalRef(ptr1); - ptr1 = nullptr; - } - if (ptr2 != nullptr) { - jniEnv->DeleteGlobalRef(ptr2); - ptr2 = nullptr; - } -#endif -} - -void Request::addRespondMessageId(int64_t id) { - respondsToMessageIds.push_back(messageId); -} - -bool Request::respondsToMessageId(int64_t id) { - return messageId == id || std::find(respondsToMessageIds.begin(), respondsToMessageIds.end(), id) != respondsToMessageIds.end(); -} - -void Request::clear(bool time) { - messageId = 0; - messageSeqNo = 0; - connectionToken = 0; - if (time) { - startTime = 0; - minStartTime = 0; - } -} - -void Request::onComplete(TLObject *result, TL_error *error) { - if (onCompleteRequestCallback != nullptr && (result != nullptr || error != nullptr)) { - onCompleteRequestCallback(result, error); - } -} - -void Request::onQuickAck() { - if (onQuickAckCallback != nullptr) { - onQuickAckCallback(); - } -} - -TLObject *Request::getRpcRequest() { - return rpcRequest.get(); -} diff --git a/TMessagesProj/jni/tgnet/Request.h b/TMessagesProj/jni/tgnet/Request.h deleted file mode 100644 index 5ab9a0930..000000000 --- a/TMessagesProj/jni/tgnet/Request.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef REQUEST_H -#define REQUEST_H - -#include -#include -#include -#include "Defines.h" - -#ifdef ANDROID -#include -#endif - -class TLObject; -class TL_error; - -class Request { - -public: - Request(int32_t token, ConnectionType type, uint32_t flags, uint32_t datacenter, onCompleteFunc completeFunc, onQuickAckFunc quickAckFunc); - ~Request(); - - int64_t messageId = 0; - int32_t messageSeqNo = 0; - uint32_t datacenterId = 0; - uint32_t connectionToken = 0; - int32_t requestToken; - uint32_t retryCount = 0; - bool failedBySalt = false; - int32_t failedByFloodWait = 0; - ConnectionType connectionType; - uint32_t requestFlags; - bool completed = false; - bool cancelled = false; - bool isInitRequest = false; - int32_t serializedLength = 0; - int32_t startTime = 0; - int32_t minStartTime = 0; - int32_t lastResendTime = 0; - uint32_t serverFailureCount = 0; - TLObject *rawRequest; - std::unique_ptr rpcRequest; - onCompleteFunc onCompleteRequestCallback; - onQuickAckFunc onQuickAckCallback; - - void addRespondMessageId(int64_t id); - bool respondsToMessageId(int64_t id); - void clear(bool time); - void onComplete(TLObject *result, TL_error *error); - void onQuickAck(); - TLObject *getRpcRequest(); - -#ifdef ANDROID - jobject ptr1 = nullptr; - jobject ptr2 = nullptr; -#endif - -private: - std::vector respondsToMessageIds; -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/TLObject.cpp b/TMessagesProj/jni/tgnet/TLObject.cpp deleted file mode 100644 index ebb7f8f84..000000000 --- a/TMessagesProj/jni/tgnet/TLObject.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include "TLObject.h" -#include "NativeByteBuffer.h" - -thread_local NativeByteBuffer *sizeCalculatorBuffer = new NativeByteBuffer(true); - -TLObject::~TLObject() { - -} - -void TLObject::readParams(NativeByteBuffer *stream, bool &error) { - -} - -void TLObject::serializeToStream(NativeByteBuffer *stream) { - -} - -TLObject *TLObject::deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error) { - return nullptr; -} - -uint32_t TLObject::getObjectSize() { - sizeCalculatorBuffer->clearCapacity(); - serializeToStream(sizeCalculatorBuffer); - return sizeCalculatorBuffer->capacity(); -} - -bool TLObject::isNeedLayer() { - return false; -} diff --git a/TMessagesProj/jni/tgnet/TLObject.h b/TMessagesProj/jni/tgnet/TLObject.h deleted file mode 100644 index 58b972c63..000000000 --- a/TMessagesProj/jni/tgnet/TLObject.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef TLOBJECT_H -#define TLOBJECT_H - -#include - -class NativeByteBuffer; - -class TLObject { - -public: - virtual ~TLObject(); - virtual void readParams(NativeByteBuffer *stream, bool &error); - virtual void serializeToStream(NativeByteBuffer *stream); - virtual TLObject *deserializeResponse(NativeByteBuffer *stream, uint32_t constructor, bool &error); - uint32_t getObjectSize(); - virtual bool isNeedLayer(); -}; - -#endif diff --git a/TMessagesProj/jni/tgnet/Timer.cpp b/TMessagesProj/jni/tgnet/Timer.cpp deleted file mode 100644 index 0f9057808..000000000 --- a/TMessagesProj/jni/tgnet/Timer.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#include "Timer.h" -#include "FileLog.h" -#include "EventObject.h" -#include "ConnectionsManager.h" - -Timer::Timer(std::function function) { - eventObject = new EventObject(this, EventObjectTypeTimer); - callback = function; -} - -Timer::~Timer() { - stop(); - if (eventObject != nullptr) { - delete eventObject; - eventObject = nullptr; - } -} - -void Timer::start() { - if (started || timeout == 0) { - return; - } - started = true; - ConnectionsManager::getInstance().scheduleEvent(eventObject, timeout); -} - -void Timer::stop() { - if (!started) { - return; - } - started = false; - ConnectionsManager::getInstance().removeEvent(eventObject); -} - -void Timer::setTimeout(uint32_t ms, bool repeat) { - if (ms == timeout) { - return; - } - repeatable = repeat; - timeout = ms; - if (started) { - ConnectionsManager::getInstance().removeEvent(eventObject); - ConnectionsManager::getInstance().scheduleEvent(eventObject, timeout); - } -} - -void Timer::onEvent() { - callback(); - DEBUG_D("timer(%p) call", this); - if (started && repeatable && timeout != 0) { - ConnectionsManager::getInstance().scheduleEvent(eventObject, timeout); - } -} diff --git a/TMessagesProj/jni/tgnet/Timer.h b/TMessagesProj/jni/tgnet/Timer.h deleted file mode 100644 index 7146cc08c..000000000 --- a/TMessagesProj/jni/tgnet/Timer.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This is the source code of tgnet library v. 1.0 - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2015. - */ - -#ifndef TIMER_H -#define TIMER_H - -#include -#include -#include - -class EventObject; - -class Timer { - -public: - Timer(std::function function); - ~Timer(); - - void start(); - void stop(); - void setTimeout(uint32_t ms, bool repeat); - -private: - void onEvent(); - - bool started = false; - bool repeatable = false; - uint32_t timeout = 0; - std::function callback; - EventObject *eventObject; - - friend class EventObject; -}; - -#endif diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java b/TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java index 1e9374235..283a6be02 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ApplicationLoader.java @@ -275,7 +275,7 @@ public class ApplicationLoader extends Application { ConnectionsManager.getInstance().init(BuildVars.BUILD_VERSION, TLRPC.LAYER, BuildVars.APP_ID, deviceModel, systemVersion, appVersion, langCode, configPath, FileLog.getNetworkLogPath(), UserConfig.getClientUserId(), enablePushConnection); if (UserConfig.getCurrentUser() != null) { MessagesController.getInstance().putUser(UserConfig.getCurrentUser(), true); - ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone); + //ConnectionsManager.getInstance().applyCountryPortNumber(UserConfig.getCurrentUser().phone); MessagesController.getInstance().getBlockedUsers(true); SendMessagesHelper.getInstance().checkUnsentMessages(); } @@ -298,7 +298,7 @@ public class ApplicationLoader extends Application { applicationContext = getApplicationContext(); NativeLoader.initNativeLibs(ApplicationLoader.applicationContext); - ConnectionsManager.native_setJava(Build.VERSION.SDK_INT == 14 || Build.VERSION.SDK_INT == 15); + //ConnectionsManager.native_setJava(Build.VERSION.SDK_INT == 14 || Build.VERSION.SDK_INT == 15); new ForegroundDetector(this); // EDIT BY MR - create a MrMailbox object; as android stops the App by just killing it, we do never call MrMailboxUnref() diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java index d4c8d738c..c827035fa 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/ContactsController.java @@ -787,13 +787,13 @@ public class ContactsController { } }*/ - final HashMap contactsMapToSave = new HashMap<>(contactsMap); + //final HashMap contactsMapToSave = new HashMap<>(contactsMap); completedRequestsCount = 0; final int count = (int) Math.ceil(toImport.size() / 500.0f); for (int a = 0; a < count; a++) { ArrayList finalToImport = new ArrayList<>(); finalToImport.addAll(toImport.subList(a * 500, Math.min((a + 1) * 500, toImport.size()))); - TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts(); + /*TLRPC.TL_contacts_importContacts req = new TLRPC.TL_contacts_importContacts(); req.contacts = finalToImport; req.replace = false; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @@ -811,15 +811,15 @@ public class ContactsController { } if (completedRequestsCount == count && !contactsMapToSave.isEmpty()) { - //MessagesStorage.getInstance().putCachedPhoneBook(contactsMapToSave); + MessagesStorage.getInstance().putCachedPhoneBook(contactsMapToSave); } - /*if (BuildVars.DEBUG_VERSION) { + if (BuildVars.DEBUG_VERSION) { for (TLRPC.User user : res.users) { FileLog.e("tmessages", "received user " + user.first_name + " " + user.last_name + " " + user.phone); } - }*/ - //MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true); + } + MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true); ArrayList cArr = new ArrayList<>(); for (int a = 0; a < res.imported.size(); a++) { TLRPC.TL_contact contact = new TLRPC.TL_contact(); @@ -849,7 +849,7 @@ public class ContactsController { }); } } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress); + }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress);*/ } } else { Utilities.stageQueue.postRunnable(new Runnable() { @@ -916,7 +916,7 @@ public class ContactsController { //MessagesStorage.getInstance().getContacts(); } else { FileLog.e("tmessages", "load contacts from server"); - TLRPC.TL_contacts_getContacts req = new TLRPC.TL_contacts_getContacts(); + /*TLRPC.TL_contacts_getContacts req = new TLRPC.TL_contacts_getContacts(); req.hash = cacheEmpty ? "" : UserConfig.contactsHash; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -944,7 +944,7 @@ public class ContactsController { processLoadedContacts(res.contacts, res.users, 0); } } - }); + });*/ } } @@ -1676,20 +1676,20 @@ public class ContactsController { /*if (BuildVars.DEBUG_VERSION) { FileLog.e("tmessages", "add contact " + user.first_name + " " + user.last_name + " " + user.phone); }*/ - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error != null) { return; } final TLRPC.TL_contacts_importedContacts res = (TLRPC.TL_contacts_importedContacts) response; - //MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true); + MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true); - /*if (BuildVars.DEBUG_VERSION) { + if (BuildVars.DEBUG_VERSION) { for (TLRPC.User user : res.users) { FileLog.e("tmessages", "received user " + user.first_name + " " + user.last_name + " " + user.phone); } - }*/ + } for (int a = 0; a < res.users.size(); a++) { final TLRPC.User u = res.users.get(a); @@ -1735,7 +1735,7 @@ public class ContactsController { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress); + }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagCanCompress);*/ } public void deleteContact(final ArrayList users) { @@ -1752,7 +1752,7 @@ public class ContactsController { uids.add(user.id); req.id.add(inputUser); } - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error != null) { @@ -1802,7 +1802,7 @@ public class ContactsController { } }); } - }); + });*/ } public void reloadContactsStatuses() { @@ -1811,7 +1811,7 @@ public class ContactsController { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); final SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("needGetStatuses", true).commit(); - TLRPC.TL_contacts_getStatuses req = new TLRPC.TL_contacts_getStatuses(); + /*TLRPC.TL_contacts_getStatuses req = new TLRPC.TL_contacts_getStatuses(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, TLRPC.TL_error error) { @@ -1852,13 +1852,13 @@ public class ContactsController { }); } } - }); + });*/ } public void loadPrivacySettings() { if (loadingDeleteInfo == 0) { loadingDeleteInfo = 1; - TLRPC.TL_account_getAccountTTL req = new TLRPC.TL_account_getAccountTTL(); + /*TLRPC.TL_account_getAccountTTL req = new TLRPC.TL_account_getAccountTTL(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { @@ -1876,11 +1876,11 @@ public class ContactsController { } }); } - }); + });*/ } if (loadingLastSeenInfo == 0) { loadingLastSeenInfo = 1; - TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy(); + /*TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy(); req.key = new TLRPC.TL_inputPrivacyKeyStatusTimestamp(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -1900,11 +1900,11 @@ public class ContactsController { } }); } - }); + });*/ } if (loadingGroupInfo == 0) { loadingGroupInfo = 1; - TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy(); + /*TLRPC.TL_account_getPrivacy req = new TLRPC.TL_account_getPrivacy(); req.key = new TLRPC.TL_inputPrivacyKeyChatInvite(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -1924,7 +1924,7 @@ public class ContactsController { } }); } - }); + });*/ } NotificationCenter.getInstance().postNotificationName(NotificationCenter.privacyRulesUpdated); } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java index 272f083a5..39f68e1ce 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoadOperation.java @@ -24,7 +24,6 @@ public class FileLoadOperation { private static class RequestInfo { private int requestToken; private int offset; - private TLRPC.TL_upload_file response; } private final static int stateIdle = 0; @@ -345,10 +344,10 @@ public class FileLoadOperation { if (delayedRequestInfos != null) { for (int a = 0; a < delayedRequestInfos.size(); a++) { RequestInfo requestInfo = delayedRequestInfos.get(a); - if (requestInfo.response != null) { + /*if (requestInfo.response != null) { requestInfo.response.disableFree = false; requestInfo.response.freeResources(); - } + }*/ } delayedRequestInfos.clear(); } @@ -394,109 +393,7 @@ public class FileLoadOperation { delegate.didFinishLoadingFile(FileLoadOperation.this, cacheFileFinal); } - private void processRequestResult(RequestInfo requestInfo, TLRPC.TL_error error) { - requestInfos.remove(requestInfo); - if (error == null) { - try { - if (downloadedBytes != requestInfo.offset) { - if (state == stateDownloading) { - delayedRequestInfos.add(requestInfo); - requestInfo.response.disableFree = true; - } - return; - } - if (requestInfo.response.bytes == null || requestInfo.response.bytes.limit() == 0) { - onFinishLoadingFile(); - return; - } - int currentBytesSize = requestInfo.response.bytes.limit(); - downloadedBytes += currentBytesSize; - boolean finishedDownloading = currentBytesSize != currentDownloadChunkSize || (totalBytesCount == downloadedBytes || downloadedBytes % currentDownloadChunkSize != 0) && (totalBytesCount <= 0 || totalBytesCount <= downloadedBytes); - - if (key != null) { - Utilities.aesIgeEncryption(requestInfo.response.bytes.buffer, key, iv, false, true, 0, requestInfo.response.bytes.limit()); - if (finishedDownloading && bytesCountPadding != 0) { - requestInfo.response.bytes.limit(requestInfo.response.bytes.limit() - bytesCountPadding); - } - } - if (fileOutputStream != null) { - FileChannel channel = fileOutputStream.getChannel(); - channel.write(requestInfo.response.bytes.buffer); - } - if (fiv != null) { - fiv.seek(0); - fiv.write(iv); - } - if (totalBytesCount > 0 && state == stateDownloading) { - delegate.didChangedLoadProgress(FileLoadOperation.this, Math.min(1.0f, (float) downloadedBytes / (float) totalBytesCount)); - } - - for (int a = 0; a < delayedRequestInfos.size(); a++) { - RequestInfo delayedRequestInfo = delayedRequestInfos.get(a); - if (downloadedBytes == delayedRequestInfo.offset) { - delayedRequestInfos.remove(a); - processRequestResult(delayedRequestInfo, null); - delayedRequestInfo.response.disableFree = false; - delayedRequestInfo.response.freeResources(); - break; - } - } - - if (finishedDownloading) { - onFinishLoadingFile(); - } else { - startDownloadRequest(); - } - } catch (Exception e) { - cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this, 0); - FileLog.e("tmessages", e); - } - } else { - if (error.text.contains("FILE_MIGRATE_")) { - String errorMsg = error.text.replace("FILE_MIGRATE_", ""); - Scanner scanner = new Scanner(errorMsg); - scanner.useDelimiter(""); - Integer val; - try { - val = scanner.nextInt(); - } catch (Exception e) { - val = null; - } - if (val == null) { - cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this, 0); - } else { - datacenter_id = val; - nextDownloadOffset = 0; - startDownloadRequest(); - } - } else if (error.text.contains("OFFSET_INVALID")) { - if (downloadedBytes % currentDownloadChunkSize == 0) { - try { - onFinishLoadingFile(); - } catch (Exception e) { - FileLog.e("tmessages", e); - cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this, 0); - } - } else { - cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this, 0); - } - } else if (error.text.contains("RETRY_LIMIT")) { - cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this, 2); - } else { - if (location != null) { - FileLog.e("tmessages", "" + location + " id = " + location.id + " local_id = " + location.local_id + " access_hash = " + location.access_hash + " volume_id = " + location.volume_id + " secret = " + location.secret); - } - cleanup(); - delegate.didFailedLoadingFile(FileLoadOperation.this, 0); - } - } - } private void startDownloadRequest() { if (state != stateDownloading || totalBytesCount > 0 && nextDownloadOffset >= totalBytesCount || requestInfos.size() + delayedRequestInfos.size() >= currentMaxDownloadRequests) { @@ -512,22 +409,22 @@ public class FileLoadOperation { break; } boolean isLast = totalBytesCount <= 0 || a == count - 1 || totalBytesCount > 0 && nextDownloadOffset + currentDownloadChunkSize >= totalBytesCount; - TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile(); - req.location = location; - req.offset = nextDownloadOffset; - req.limit = currentDownloadChunkSize; + //TLRPC.TL_upload_getFile req = new TLRPC.TL_upload_getFile(); + //req.location = location; + //req.offset = nextDownloadOffset; + //req.limit = currentDownloadChunkSize; nextDownloadOffset += currentDownloadChunkSize; final RequestInfo requestInfo = new RequestInfo(); requestInfos.add(requestInfo); - requestInfo.offset = req.offset; - requestInfo.requestToken = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + requestInfo.offset = nextDownloadOffset; + requestInfo.requestToken = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { requestInfo.response = (TLRPC.TL_upload_file) response; processRequestResult(requestInfo, error); } - }, null, (isForceRequest ? ConnectionsManager.RequestFlagForceDownload : 0) | ConnectionsManager.RequestFlagFailOnServerErrors, datacenter_id, requestsCount % 2 == 0 ? ConnectionsManager.ConnectionTypeDownload : ConnectionsManager.ConnectionTypeDownload2, isLast); + }, null, (isForceRequest ? ConnectionsManager.RequestFlagForceDownload : 0) | ConnectionsManager.RequestFlagFailOnServerErrors, datacenter_id, requestsCount % 2 == 0 ? ConnectionsManager.ConnectionTypeDownload : ConnectionsManager.ConnectionTypeDownload2, isLast);*/ requestsCount++; } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java index f5118bd9e..ef06d9e92 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileLoader.java @@ -99,6 +99,7 @@ public class FileLoader { return dir; } + /* public void checkUploadNewDataAvailable(final String location, final boolean encrypted, final long finalSize) { fileLoaderQueue.postRunnable(new Runnable() { @Override @@ -117,6 +118,7 @@ public class FileLoader { } }); } + */ public void uploadFile(final String location, final boolean encrypted, final boolean small) { uploadFile(location, encrypted, small, 0); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/FileUploadOperation.java b/TMessagesProj/src/main/java/org/telegram/messenger/FileUploadOperation.java index 20f094ec3..d33bb9204 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/FileUploadOperation.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/FileUploadOperation.java @@ -12,44 +12,23 @@ import android.app.Activity; import android.content.SharedPreferences; import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.NativeByteBuffer; -import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import java.io.File; import java.io.FileInputStream; -import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.Locale; public class FileUploadOperation { - private int uploadChunkSize = 1024 * 32; - private String uploadingFilePath; + public int state = 0; - private byte[] readBuffer; public FileUploadOperationDelegate delegate; private int requestToken = 0; - private int currentPartNum = 0; - private long currentFileId; - private boolean isLastPart = false; private long totalFileSize = 0; - private int totalPartsCount = 0; - private long currentUploaded = 0; - private int saveInfoTimes = 0; - private byte[] key; - private byte[] iv; - private byte[] ivChange; private boolean isEncrypted = false; - private int fingerprint = 0; - private boolean isBigFile = false; - private String fileKey; private int estimatedSize = 0; - private int uploadStartTime = 0; private FileInputStream stream; - private MessageDigest mdEnc = null; - private boolean started = false; public interface FileUploadOperationDelegate { void didFinishUploadingFile(FileUploadOperation operation, TLRPC.InputFile inputFile, TLRPC.InputEncryptedFile inputEncryptedFile, byte[] key, byte[] iv); @@ -58,7 +37,6 @@ public class FileUploadOperation { } public FileUploadOperation(String location, boolean encrypted, int estimated) { - uploadingFilePath = location; isEncrypted = encrypted; estimatedSize = estimated; } @@ -68,16 +46,6 @@ public class FileUploadOperation { } public void start() { - if (state != 0) { - return; - } - state = 1; - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - startUploadRequest(); - } - }); } public void cancel() { @@ -93,24 +61,9 @@ public class FileUploadOperation { } private void cleanup() { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("uploadinfo", Activity.MODE_PRIVATE); - preferences.edit().remove(fileKey + "_time"). - remove(fileKey + "_size"). - remove(fileKey + "_uploaded"). - remove(fileKey + "_id"). - remove(fileKey + "_iv"). - remove(fileKey + "_key"). - remove(fileKey + "_ivc").commit(); - try { - if (stream != null) { - stream.close(); - stream = null; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } } + /* protected void checkNewDataAvailable(final long finalSize) { Utilities.stageQueue.postRunnable(new Runnable() { @Override @@ -130,292 +83,7 @@ public class FileUploadOperation { } }); } + */ - private void storeFileUploadInfo(SharedPreferences preferences) { - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt(fileKey + "_time", uploadStartTime); - editor.putLong(fileKey + "_size", totalFileSize); - editor.putLong(fileKey + "_id", currentFileId); - editor.remove(fileKey + "_uploaded"); - if (isEncrypted) { - editor.putString(fileKey + "_iv", Utilities.bytesToHex(iv)); - editor.putString(fileKey + "_ivc", Utilities.bytesToHex(ivChange)); - editor.putString(fileKey + "_key", Utilities.bytesToHex(key)); - } - editor.commit(); - } - private void startUploadRequest() { - if (state != 1) { - return; - } - - TLObject finalRequest; - - try { - started = true; - if (stream == null) { - File cacheFile = new File(uploadingFilePath); - stream = new FileInputStream(cacheFile); - if (estimatedSize != 0) { - totalFileSize = estimatedSize; - } else { - totalFileSize = cacheFile.length(); - } - if (totalFileSize > 10 * 1024 * 1024) { - isBigFile = true; - } else { - try { - mdEnc = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - FileLog.e("tmessages", e); - } - } - - uploadChunkSize = (int) Math.max(32, (totalFileSize + 1024 * 3000 - 1) / (1024 * 3000)); - if (1024 % uploadChunkSize != 0) { - int chunkSize = 64; - while (uploadChunkSize > chunkSize) { - chunkSize *= 2; - } - uploadChunkSize = chunkSize; - } - - uploadChunkSize *= 1024; - totalPartsCount = (int) (totalFileSize + uploadChunkSize - 1) / uploadChunkSize; - readBuffer = new byte[uploadChunkSize]; - - fileKey = Utilities.MD5(uploadingFilePath + (isEncrypted ? "enc" : "")); - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("uploadinfo", Activity.MODE_PRIVATE); - long fileSize = preferences.getLong(fileKey + "_size", 0); - uploadStartTime = (int)(System.currentTimeMillis() / 1000); - boolean rewrite = false; - if (estimatedSize == 0 && fileSize == totalFileSize) { - currentFileId = preferences.getLong(fileKey + "_id", 0); - int date = preferences.getInt(fileKey + "_time", 0); - long uploadedSize = preferences.getLong(fileKey + "_uploaded", 0); - if (isEncrypted) { - String ivString = preferences.getString(fileKey + "_iv", null); - String keyString = preferences.getString(fileKey + "_key", null); - if (ivString != null && keyString != null) { - key = Utilities.hexToBytes(keyString); - iv = Utilities.hexToBytes(ivString); - if (key != null && iv != null && key.length == 32 && iv.length == 32) { - ivChange = new byte[32]; - System.arraycopy(iv, 0, ivChange, 0, 32); - } else { - rewrite = true; - } - } else { - rewrite = true; - } - } - if (!rewrite && date != 0) { - if (isBigFile && date < uploadStartTime - 60 * 60 * 24) { - date = 0; - } else if (!isBigFile && date < uploadStartTime - 60 * 60 * 1.5f) { - date = 0; - } - if (date != 0) { - if (uploadedSize > 0) { - currentUploaded = uploadedSize; - currentPartNum = (int) (uploadedSize / uploadChunkSize); - if (!isBigFile) { - for (int b = 0; b < currentUploaded / uploadChunkSize; b++) { - int read = stream.read(readBuffer); - int toAdd = 0; - if (isEncrypted && read % 16 != 0) { - toAdd += 16 - read % 16; - } - NativeByteBuffer sendBuffer = new NativeByteBuffer(read + toAdd); - if (read != uploadChunkSize || totalPartsCount == currentPartNum + 1) { - isLastPart = true; - } - sendBuffer.writeBytes(readBuffer, 0, read); - if (isEncrypted) { - for (int a = 0; a < toAdd; a++) { - sendBuffer.writeByte(0); - } - Utilities.aesIgeEncryption(sendBuffer.buffer, key, ivChange, true, true, 0, read + toAdd); - } - sendBuffer.rewind(); - mdEnc.update(sendBuffer.buffer); - sendBuffer.reuse(); - } - } else { - stream.skip(uploadedSize); - if (isEncrypted) { - String ivcString = preferences.getString(fileKey + "_ivc", null); - if (ivcString != null) { - ivChange = Utilities.hexToBytes(ivcString); - if (ivChange == null || ivChange.length != 32) { - rewrite = true; - currentUploaded = 0; - currentPartNum = 0; - } - } else { - rewrite = true; - currentUploaded = 0; - currentPartNum = 0; - } - } - } - } else { - rewrite = true; - } - } - } else { - rewrite = true; - } - } else { - rewrite = true; - } - if (rewrite) { - if (isEncrypted) { - iv = new byte[32]; - key = new byte[32]; - ivChange = new byte[32]; - Utilities.random.nextBytes(iv); - Utilities.random.nextBytes(key); - System.arraycopy(iv, 0, ivChange, 0, 32); - } - currentFileId = Utilities.random.nextLong(); - if (estimatedSize == 0) { - storeFileUploadInfo(preferences); - } - } - - if (isEncrypted) { - try { - java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); - byte[] arr = new byte[64]; - System.arraycopy(key, 0, arr, 0, 32); - System.arraycopy(iv, 0, arr, 32, 32); - byte[] digest = md.digest(arr); - for (int a = 0; a < 4; a++) { - fingerprint |= ((digest[a] ^ digest[a + 4]) & 0xFF) << (a * 8); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - } else if (estimatedSize == 0) { - if (saveInfoTimes >= 4) { - saveInfoTimes = 0; - } - if (isBigFile && currentUploaded % (1024 * 1024) == 0 || !isBigFile && saveInfoTimes == 0) { - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("uploadinfo", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putLong(fileKey + "_uploaded", currentUploaded); - if (isEncrypted) { - editor.putString(fileKey + "_ivc", Utilities.bytesToHex(ivChange)); - } - editor.commit(); - } - saveInfoTimes++; - } - - if (estimatedSize != 0) { - long size = stream.getChannel().size(); - if (currentUploaded + uploadChunkSize > size) { - return; - } - } - - int read = stream.read(readBuffer); - int toAdd = 0; - if (isEncrypted && read % 16 != 0) { - toAdd += 16 - read % 16; - } - NativeByteBuffer sendBuffer = new NativeByteBuffer(read + toAdd); - if (read != uploadChunkSize || estimatedSize == 0 && totalPartsCount == currentPartNum + 1) { - isLastPart = true; - } - sendBuffer.writeBytes(readBuffer, 0, read); - if (isEncrypted) { - for (int a = 0; a < toAdd; a++) { - sendBuffer.writeByte(0); - } - Utilities.aesIgeEncryption(sendBuffer.buffer, key, ivChange, true, true, 0, read + toAdd); - } - sendBuffer.rewind(); - if (!isBigFile) { - mdEnc.update(sendBuffer.buffer); - } - if (isBigFile) { - TLRPC.TL_upload_saveBigFilePart req = new TLRPC.TL_upload_saveBigFilePart(); - req.file_part = currentPartNum; - req.file_id = currentFileId; - if (estimatedSize != 0) { - req.file_total_parts = -1; - } else { - req.file_total_parts = totalPartsCount; - } - req.bytes = sendBuffer; - finalRequest = req; - } else { - TLRPC.TL_upload_saveFilePart req = new TLRPC.TL_upload_saveFilePart(); - req.file_part = currentPartNum; - req.file_id = currentFileId; - req.bytes = sendBuffer; - finalRequest = req; - } - currentUploaded += read; - } catch (Exception e) { - FileLog.e("tmessages", e); - delegate.didFailedUploadingFile(this); - cleanup(); - return; - } - requestToken = ConnectionsManager.getInstance().sendRequest(finalRequest, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - requestToken = 0; - if (error == null) { - if (response instanceof TLRPC.TL_boolTrue) { - currentPartNum++; - delegate.didChangedUploadProgress(FileUploadOperation.this, currentUploaded / (float) totalFileSize); - if (isLastPart) { - state = 3; - if (key == null) { - TLRPC.InputFile result; - if (isBigFile) { - result = new TLRPC.TL_inputFileBig(); - } else { - result = new TLRPC.TL_inputFile(); - result.md5_checksum = String.format(Locale.US, "%32s", new BigInteger(1, mdEnc.digest()).toString(16)).replace(' ', '0'); - } - result.parts = currentPartNum; - result.id = currentFileId; - result.name = uploadingFilePath.substring(uploadingFilePath.lastIndexOf("/") + 1); - delegate.didFinishUploadingFile(FileUploadOperation.this, result, null, null, null); - cleanup(); - } else { - TLRPC.InputEncryptedFile result; - /*if (isBigFile) { - result = new TLRPC.TL_inputEncryptedFileBigUploaded(); - } else */ { - result = new TLRPC.TL_inputEncryptedFileUploaded(); - result.md5_checksum = String.format(Locale.US, "%32s", new BigInteger(1, mdEnc.digest()).toString(16)).replace(' ', '0'); - } - result.parts = currentPartNum; - result.id = currentFileId; - result.key_fingerprint = fingerprint; - delegate.didFinishUploadingFile(FileUploadOperation.this, null, result, key, iv); - cleanup(); - } - } else { - startUploadRequest(); - } - } else { - delegate.didFailedUploadingFile(FileUploadOperation.this); - cleanup(); - } - } else { - delegate.didFailedUploadingFile(FileUploadOperation.this); - cleanup(); - } - } - }, 0, ConnectionsManager.ConnectionTypeUpload); - } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MessageKeyData.java b/TMessagesProj/src/main/java/org/telegram/messenger/MessageKeyData.java deleted file mode 100644 index 594a63209..000000000 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MessageKeyData.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.messenger; - -import org.telegram.tgnet.SerializedData; - -public class MessageKeyData { - - public byte[] aesKey; - public byte[] aesIv; - - public static MessageKeyData generateMessageKeyData(byte[] authKey, byte[] messageKey, boolean incoming) { - MessageKeyData keyData = new MessageKeyData(); - if (authKey == null || authKey.length == 0) { - keyData.aesIv = null; - keyData.aesKey = null; - return keyData; - } - - int x = incoming ? 8 : 0; - - SerializedData data = new SerializedData(); - data.writeBytes(messageKey); - data.writeBytes(authKey, x, 32); - byte[] sha1_a = Utilities.computeSHA1(data.toByteArray()); - data.cleanup(); - - data = new SerializedData(); - data.writeBytes(authKey, 32 + x, 16); - data.writeBytes(messageKey); - data.writeBytes(authKey, 48 + x, 16); - byte[] sha1_b = Utilities.computeSHA1(data.toByteArray()); - data.cleanup(); - - data = new SerializedData(); - data.writeBytes(authKey, 64 + x, 32); - data.writeBytes(messageKey); - byte[] sha1_c = Utilities.computeSHA1(data.toByteArray()); - data.cleanup(); - - data = new SerializedData(); - data.writeBytes(messageKey); - data.writeBytes(authKey, 96 + x, 32); - byte[] sha1_d = Utilities.computeSHA1(data.toByteArray()); - data.cleanup(); - - data = new SerializedData(); - data.writeBytes(sha1_a, 0, 8); - data.writeBytes(sha1_b, 8, 12); - data.writeBytes(sha1_c, 4, 12); - keyData.aesKey = data.toByteArray(); - data.cleanup(); - - data = new SerializedData(); - data.writeBytes(sha1_a, 8, 12); - data.writeBytes(sha1_b, 0, 8); - data.writeBytes(sha1_c, 16, 4); - data.writeBytes(sha1_d, 0, 8); - keyData.aesIv = data.toByteArray(); - data.cleanup(); - - return keyData; - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java index 8630b04d2..4ebcd1681 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MessagesController.java @@ -23,8 +23,6 @@ import org.telegram.messenger.query.MessagesQuery; import org.telegram.messenger.query.SearchQuery; import org.telegram.messenger.query.StickersQuery; import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.NativeByteBuffer; -import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.SerializedData; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; @@ -36,7 +34,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; -import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Semaphore; @@ -78,7 +75,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter private SparseArray> channelViewsToSend = new SparseArray<>(); private SparseArray> channelViewsToReload = new SparseArray<>(); - private long lastViewsCheckTime; private HashMap> updatesQueueChannels = new HashMap<>(); private HashMap updatesStartWaitTimeChannels = new HashMap<>(); @@ -113,7 +109,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter private Runnable currentDeleteTaskRunnable = null; public boolean loadingDialogs = false; - private boolean migratingDialogs = false; public boolean dialogsEndReached = false; public boolean gettingDifference = false; public boolean updatingState = false; @@ -154,10 +149,8 @@ public class MessagesController implements NotificationCenter.NotificationCenter public static final int UPDATE_MASK_SEND_STATE = 4096; public static final int UPDATE_MASK_CHANNEL = 8192; public static final int UPDATE_MASK_CHAT_ADMINS = 16384; - public static final int UPDATE_MASK_ALL = UPDATE_MASK_AVATAR | UPDATE_MASK_STATUS | UPDATE_MASK_NAME | UPDATE_MASK_CHAT_AVATAR | UPDATE_MASK_CHAT_NAME | UPDATE_MASK_CHAT_MEMBERS | UPDATE_MASK_USER_PRINT | UPDATE_MASK_USER_PHONE | UPDATE_MASK_READ_DIALOG_MESSAGE | UPDATE_MASK_PHONE; public static class PrintingUser { - public long lastTime; public int userId; public TLRPC.SendMessageAction action; } @@ -232,45 +225,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } - public void updateConfig(final TLRPC.TL_config config) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - //maxBroadcastCount = config.broadcast_size_max; - maxMegagroupCount = config.megagroup_size_max; - maxGroupCount = config.chat_size_max; - groupBigSize = config.chat_big_size; - disabledFeatures = config.disabled_features; - maxEditTime = config.edit_time_limit; - ratingDecay = config.rating_e_decay; - - SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE); - SharedPreferences.Editor editor = preferences.edit(); - editor.putInt("maxGroupCount", maxGroupCount); - //editor.putInt("maxBroadcastCount", maxBroadcastCount); - editor.putInt("maxMegagroupCount", maxMegagroupCount); - editor.putInt("groupBigSize", groupBigSize); - editor.putInt("maxEditTime", maxEditTime); - editor.putInt("ratingDecay", ratingDecay); - try { - SerializedData data = new SerializedData(); - data.writeInt32(disabledFeatures.size()); - for (TLRPC.TL_disabledFeature disabledFeature : disabledFeatures) { - disabledFeature.serializeToStream(data); - } - String string = Base64.encodeToString(data.toByteArray(), Base64.DEFAULT); - if (string.length() != 0) { - editor.putString("disabledFeatures", string); - } - } catch (Exception e) { - editor.remove("disabledFeatures"); - FileLog.e("tmessages", e); - } - editor.commit(); - } - }); - } - public static boolean isFeatureEnabled(String feature, BaseFragment fragment) { if (feature == null || feature.length() == 0 || getInstance().disabledFeatures.isEmpty() || fragment == null) { return true; @@ -310,17 +264,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter return getInputUser(user); } - public static TLRPC.InputChannel getInputChannel(TLRPC.Chat chat) { - if (chat instanceof TLRPC.TL_channel || chat instanceof TLRPC.TL_channelForbidden) { - TLRPC.InputChannel inputChat = new TLRPC.TL_inputChannel(); - inputChat.channel_id = chat.id; - inputChat.access_hash = chat.access_hash; - return inputChat; - } else { - return new TLRPC.TL_inputChannelEmpty(); - } - } - public static TLRPC.InputPeer getInputPeer(int id) { TLRPC.InputPeer inputPeer; if (id < 0) { @@ -375,7 +318,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.crop = new TLRPC.TL_inputPhotoCropAuto(); req.file = file; req.geo_point = new TLRPC.TL_inputGeoPointEmpty(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { @@ -416,7 +359,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter }); } } - }); + });*/ } } else if (id == NotificationCenter.FileDidFailUpload) { final String location = (String) args[0]; @@ -524,7 +467,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter Utilities.stageQueue.postRunnable(new Runnable() { @Override public void run() { - ConnectionsManager.getInstance().setIsUpdating(false); + //ConnectionsManager.getInstance().setIsUpdating(false); updatesQueueChannels.clear(); updatesStartWaitTimeChannels.clear(); gettingDifferenceChannels.clear(); @@ -763,7 +706,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.offset = offset; req.max_id = (int) max_id; req.user_id = getInputUser(user); - int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + int reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { @@ -771,7 +714,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter processLoadedUserPhotos(res, did, offset, count, max_id, false, classGuid); } } - }); + });*/ ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); } else if (did < 0) { TLRPC.TL_messages_search req = new TLRPC.TL_messages_search(); @@ -781,7 +724,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter req.max_id = (int) max_id; req.q = ""; req.peer = MessagesController.getInputPeer(did); - int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + int reqId = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { @@ -799,7 +742,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter processLoadedUserPhotos(res, did, offset, count, max_id, false, classGuid); } } - }); + });*/ ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); } } @@ -819,7 +762,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded); TLRPC.TL_contacts_block req = new TLRPC.TL_contacts_block(); req.id = getInputUser(user); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { @@ -828,7 +771,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter //MessagesStorage.getInstance().putBlockedUsers(ids, false); } } - }); + });*/ } public void unblockUser(int user_id) { @@ -840,12 +783,12 @@ public class MessagesController implements NotificationCenter.NotificationCenter blockedUsers.remove((Integer) user.id); req.id = getInputUser(user); NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { //MessagesStorage.getInstance().deleteBlockedUser(user.id); } - }); + });*/ } public void getBlockedUsers(boolean cache) { @@ -859,7 +802,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter TLRPC.TL_contacts_getBlocked req = new TLRPC.TL_contacts_getBlocked(); req.offset = 0; req.limit = 200; - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { ArrayList blocked = new ArrayList<>(); @@ -875,106 +818,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter } processLoadedBlockedUsers(blocked, users, false); } - }); + });*/ } } - public void processLoadedBlockedUsers(final ArrayList ids, final ArrayList users, final boolean cache) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (users != null) { - putUsers(users, cache); - } - loadingBlockedUsers = false; - if (ids.isEmpty() && cache && !UserConfig.blockedUsersLoaded) { - getBlockedUsers(false); - return; - } else if (!cache) { - UserConfig.blockedUsersLoaded = true; - UserConfig.saveConfig(false); - } - blockedUsers = ids; - NotificationCenter.getInstance().postNotificationName(NotificationCenter.blockedUsersDidLoaded); - } - }); - } - - public void deleteUserPhoto(TLRPC.InputPhoto photo) { - if (photo == null) { - TLRPC.TL_photos_updateProfilePhoto req = new TLRPC.TL_photos_updateProfilePhoto(); - req.id = new TLRPC.TL_inputPhotoEmpty(); - req.crop = new TLRPC.TL_inputPhotoCropAuto(); - UserConfig.getCurrentUser().photo = new TLRPC.TL_userProfilePhotoEmpty(); - TLRPC.User user = getUser(UserConfig.getClientUserId()); - if (user == null) { - user = UserConfig.getCurrentUser(); - } - if (user == null) { - return; - } - user.photo = UserConfig.getCurrentUser().photo; - NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_ALL); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (error == null) { - TLRPC.User user = getUser(UserConfig.getClientUserId()); - if (user == null) { - user = UserConfig.getCurrentUser(); - putUser(user, false); - } else { - UserConfig.setCurrentUser(user); - } - if (user == null) { - return; - } - //MessagesStorage.getInstance().clearUserPhotos(user.id); - ArrayList users = new ArrayList<>(); - users.add(user); - //MessagesStorage.getInstance().putUsersAndChats(users, null, false, true); - user.photo = (TLRPC.UserProfilePhoto) response; - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_ALL); - UserConfig.saveConfig(true); - } - }); - } - } - }); - } else { - TLRPC.TL_photos_deletePhotos req = new TLRPC.TL_photos_deletePhotos(); - req.id.add(photo); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - - } - }); - } - } - - public void processLoadedUserPhotos(final TLRPC.photos_Photos res, final int did, final int offset, final int count, final long max_id, final boolean fromCache, final int classGuid) { - if (!fromCache) { - //MessagesStorage.getInstance().putUsersAndChats(res.users, null, true, true); - //MessagesStorage.getInstance().putDialogPhotos(did, res); - } else if (res == null || res.photos.isEmpty()) { - loadDialogPhotos(did, offset, count, max_id, false, classGuid); - return; - } - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - putUsers(res.users, fromCache); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogPhotosLoaded, did, offset, count, fromCache, classGuid, res.photos); - } - }); - } - public void deleteMessages(ArrayList messages, ArrayList randoms, TLRPC.EncryptedChat encryptedChat, final int channelId) { } @@ -997,7 +844,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter ArrayList arrayList = new ArrayList<>(); arrayList.add(searchImage); //MessagesStorage.getInstance().putWebRecent(arrayList); - TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif(); + /*TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif(); req.id = new TLRPC.TL_inputDocument(); req.id.id = searchImage.document.id; req.id.access_hash = searchImage.document.access_hash; @@ -1007,7 +854,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter public void run(TLObject response, TLRPC.TL_error error) { } - }); + });*/ return searchImage; } @@ -1015,184 +862,6 @@ public class MessagesController implements NotificationCenter.NotificationCenter //MessagesStorage.getInstance().loadChatInfo(chat_id, semaphore, force, false); } - public void updateTimerProc() { - long currentTime = System.currentTimeMillis(); - - //checkDeletingTask(false); - - if (UserConfig.isClientActivated()) { - if (ConnectionsManager.getInstance().getPauseTime() == 0 && ApplicationLoader.isScreenOn && !ApplicationLoader.mainInterfacePaused) { - if (statusSettingState != 1 && (lastStatusUpdateTime == 0 || Math.abs(System.currentTimeMillis() - lastStatusUpdateTime) >= 55000 || offlineSent)) { - statusSettingState = 1; - - if (statusRequest != 0) { - ConnectionsManager.getInstance().cancelRequest(statusRequest, true); - } - - TLRPC.TL_account_updateStatus req = new TLRPC.TL_account_updateStatus(); - req.offline = false; - statusRequest = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (error == null) { - lastStatusUpdateTime = System.currentTimeMillis(); - offlineSent = false; - statusSettingState = 0; - } else { - if (lastStatusUpdateTime != 0) { - lastStatusUpdateTime += 5000; - } - } - statusRequest = 0; - } - }); - } - } else if (statusSettingState != 2 && !offlineSent && Math.abs(System.currentTimeMillis() - ConnectionsManager.getInstance().getPauseTime()) >= 2000) { - statusSettingState = 2; - if (statusRequest != 0) { - ConnectionsManager.getInstance().cancelRequest(statusRequest, true); - } - TLRPC.TL_account_updateStatus req = new TLRPC.TL_account_updateStatus(); - req.offline = true; - statusRequest = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (error == null) { - offlineSent = true; - } else { - if (lastStatusUpdateTime != 0) { - lastStatusUpdateTime += 5000; - } - } - statusRequest = 0; - } - }); - } - - if (!updatesQueueChannels.isEmpty()) { - ArrayList keys = new ArrayList<>(updatesQueueChannels.keySet()); - for (int a = 0; a < keys.size(); a++) { - int key = keys.get(a); - Long updatesStartWaitTime = updatesStartWaitTimeChannels.get(key); - if (updatesStartWaitTime != null && updatesStartWaitTime + 1500 < currentTime) { - FileLog.e("tmessages", "QUEUE CHANNEL " + key + " UPDATES WAIT TIMEOUT - CHECK QUEUE"); - //processChannelsUpdatesQueue(key, 0); - } - } - } - - for (int a = 0; a < 3; a++) { - if (getUpdatesStartTime(a) != 0 && getUpdatesStartTime(a) + 1500 < currentTime) { - FileLog.e("tmessages", a + " QUEUE UPDATES WAIT TIMEOUT - CHECK QUEUE"); - //processUpdatesQueue(a, 0); - } - } - } - if ((channelViewsToSend.size() != 0 || channelViewsToReload.size() != 0) && Math.abs(System.currentTimeMillis() - lastViewsCheckTime) >= 5000) { - lastViewsCheckTime = System.currentTimeMillis(); - for (int b = 0; b < 2; b++) { - SparseArray> array = b == 0 ? channelViewsToSend : channelViewsToReload; - if (array.size() == 0) { - continue; - } - for (int a = 0; a < array.size(); a++) { - final int key = array.keyAt(a); - final TLRPC.TL_messages_getMessagesViews req = new TLRPC.TL_messages_getMessagesViews(); - req.peer = getInputPeer(key); - req.id = array.get(key); - req.increment = a == 0; - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (error == null) { - TLRPC.Vector vector = (TLRPC.Vector) response; - final SparseArray channelViews = new SparseArray<>(); - SparseIntArray array = channelViews.get(key); - if (array == null) { - array = new SparseIntArray(); - channelViews.put(key, array); - } - for (int a = 0; a < req.id.size(); a++) { - if (a >= vector.objects.size()) { - break; - } - array.put(req.id.get(a), (Integer) vector.objects.get(a)); - } - //MessagesStorage.getInstance().putChannelViews(channelViews, req.peer instanceof TLRPC.TL_inputPeerChannel); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedMessagesViews, channelViews); - } - }); - } - } - }); - } - array.clear(); - } - } - if (!onlinePrivacy.isEmpty()) { - ArrayList toRemove = null; - int currentServerTime = ConnectionsManager.getInstance().getCurrentTime(); - for (ConcurrentHashMap.Entry entry : onlinePrivacy.entrySet()) { - if (entry.getValue() < currentServerTime - 30) { - if (toRemove == null) { - toRemove = new ArrayList<>(); - } - toRemove.add(entry.getKey()); - } - } - if (toRemove != null) { - for (Integer uid : toRemove) { - onlinePrivacy.remove(uid); - } - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_STATUS); - } - }); - } - } - - if (!printingUsers.isEmpty() || lastPrintingStringCount != printingUsers.size()) { - boolean updated = false; - ArrayList keys = new ArrayList<>(printingUsers.keySet()); - for (int b = 0; b < keys.size(); b++) { - Long key = keys.get(b); - ArrayList arr = printingUsers.get(key); - for (int a = 0; a < arr.size(); a++) { - PrintingUser user = arr.get(a); - if (user.lastTime + 5900 < currentTime) { - updated = true; - arr.remove(user); - a--; - } - } - if (arr.isEmpty()) { - printingUsers.remove(key); - keys.remove(b); - b--; - } - } - - updatePrintingStrings(); - - if (updated) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, UPDATE_MASK_USER_PRINT); - } - }); - } - } - } - - private void updatePrintingStrings() { - } - public void cancelTyping(int action, long dialog_id) { } @@ -1217,7 +886,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter reloadingWebpages.put(url, arrayList); } arrayList.addAll(messages); - TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview(); + /*TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview(); req.message = url; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -1256,7 +925,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } }); } - }); + });*/ } } @@ -1299,7 +968,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter if (!found) { req.offset_peer = new TLRPC.TL_inputPeerEmpty(); } - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { @@ -1307,251 +976,10 @@ public class MessagesController implements NotificationCenter.NotificationCenter //processLoadedDialogs(dialogsRes, null, 0, count, 0, false, false); } } - }); + });*/ } } - protected void checkLastDialogMessage(final TLRPC.TL_dialog dialog, final TLRPC.InputPeer peer, long taskId) { - final int lower_id = (int) dialog.id; - if (lower_id == 0 || checkingLastMessagesDialogs.containsKey(lower_id)) { - return; - } - TLRPC.TL_messages_getHistory req = new TLRPC.TL_messages_getHistory(); - req.peer = peer == null ? getInputPeer(lower_id) : peer; - if (req.peer == null) { - return; - } - req.limit = 1; - checkingLastMessagesDialogs.put(lower_id, true); - - final long newTaskId; - if (taskId == 0) { - NativeByteBuffer data = null; - try { - data = new NativeByteBuffer(40 + peer.getObjectSize()); - data.writeInt32(2); - data.writeInt64(dialog.id); - data.writeInt32(dialog.top_message); - data.writeInt32(dialog.read_inbox_max_id); - data.writeInt32(dialog.read_outbox_max_id); - data.writeInt32(dialog.unread_count); - data.writeInt32(dialog.last_message_date); - data.writeInt32(dialog.pts); - data.writeInt32(dialog.flags); - peer.serializeToStream(data); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - newTaskId = 0;//MessagesStorage.getInstance().createPendingTask(data); - } else { - newTaskId = taskId; - } - - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { - @Override - public void run(TLObject response, TLRPC.TL_error error) { - if (response != null) { - TLRPC.messages_Messages res = (TLRPC.messages_Messages) response; - if (!res.messages.isEmpty()) { - TLRPC.TL_messages_dialogs dialogs = new TLRPC.TL_messages_dialogs(); - TLRPC.Message newMessage = res.messages.get(0); - TLRPC.TL_dialog newDialog = new TLRPC.TL_dialog(); - newDialog.flags = dialog.flags; - newDialog.top_message = newMessage.id; - newDialog.last_message_date = newMessage.date; - newDialog.notify_settings = dialog.notify_settings; - newDialog.pts = dialog.pts; - newDialog.unread_count = dialog.unread_count; - newDialog.read_inbox_max_id = dialog.read_inbox_max_id; - newDialog.read_outbox_max_id = dialog.read_outbox_max_id; - newMessage.dialog_id = newDialog.id = dialog.id; - dialogs.users.addAll(res.users); - dialogs.chats.addAll(res.chats); - dialogs.dialogs.add(newDialog); - dialogs.messages.addAll(res.messages); - dialogs.count = 1; - processDialogsUpdate(dialogs, null); - //MessagesStorage.getInstance().putMessages(res.messages, true, true, false, MediaController.getInstance().getAutodownloadMask(), true); - } else { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - TLRPC.TL_dialog currentDialog = dialogs_dict.get(dialog.id); - if (currentDialog != null && currentDialog.top_message == 0) { - deleteDialog(dialog.id, 3); - } - } - }); - } - } - if (newTaskId != 0) { - //MessagesStorage.getInstance().removePendingTask(newTaskId); - } - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - checkingLastMessagesDialogs.remove(lower_id); - } - }); - } - }); - } - - public void processDialogsUpdate(final TLRPC.messages_Dialogs dialogsRes, ArrayList encChats) { - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - final HashMap new_dialogs_dict = new HashMap<>(); - final HashMap new_dialogMessage = new HashMap<>(); - final HashMap usersDict = new HashMap<>(); - final HashMap chatsDict = new HashMap<>(); - final HashMap dialogsToUpdate = new HashMap<>(); - - for (int a = 0; a < dialogsRes.users.size(); a++) { - TLRPC.User u = dialogsRes.users.get(a); - usersDict.put(u.id, u); - } - for (int a = 0; a < dialogsRes.chats.size(); a++) { - TLRPC.Chat c = dialogsRes.chats.get(a); - chatsDict.put(c.id, c); - } - - for (int a = 0; a < dialogsRes.messages.size(); a++) { - TLRPC.Message message = dialogsRes.messages.get(a); - if (message.to_id.channel_id != 0) { - TLRPC.Chat chat = chatsDict.get(message.to_id.channel_id); - if (chat != null && chat.left) { - continue; - } - } else if (message.to_id.chat_id != 0) { - TLRPC.Chat chat = chatsDict.get(message.to_id.chat_id); - if (chat != null && chat.migrated_to != null) { - continue; - } - } - MessageObject messageObject = new MessageObject(message, usersDict, chatsDict, false); - new_dialogMessage.put(messageObject.getDialogId(), messageObject); - } - for (int a = 0; a < dialogsRes.dialogs.size(); a++) { - TLRPC.TL_dialog d = dialogsRes.dialogs.get(a); - if (d.id == 0) { - if (d.peer.user_id != 0) { - d.id = d.peer.user_id; - } else if (d.peer.chat_id != 0) { - d.id = -d.peer.chat_id; - } else if (d.peer.channel_id != 0) { - d.id = -d.peer.channel_id; - } - } - if (DialogObject.isChannel(d)) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); - if (chat != null && chat.left) { - continue; - } - } else if ((int) d.id < 0) { - TLRPC.Chat chat = chatsDict.get(-(int) d.id); - if (chat != null && chat.migrated_to != null) { - continue; - } - } - if (d.last_message_date == 0) { - MessageObject mess = new_dialogMessage.get(d.id); - if (mess != null) { - d.last_message_date = mess.messageOwner.date; - } - } - new_dialogs_dict.put(d.id, d); - dialogsToUpdate.put(d.id, d.unread_count); - - Integer value = dialogs_read_inbox_max.get(d.id); - if (value == null) { - value = 0; - } - dialogs_read_inbox_max.put(d.id, Math.max(value, d.read_inbox_max_id)); - - value = dialogs_read_outbox_max.get(d.id); - if (value == null) { - value = 0; - } - dialogs_read_outbox_max.put(d.id, Math.max(value, d.read_outbox_max_id)); - } - - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - putUsers(dialogsRes.users, true); - putChats(dialogsRes.chats, true); - - for (HashMap.Entry pair : new_dialogs_dict.entrySet()) { - Long key = pair.getKey(); - TLRPC.TL_dialog value = pair.getValue(); - TLRPC.TL_dialog currentDialog = dialogs_dict.get(key); - if (currentDialog == null) { - nextDialogsCacheOffset++; - dialogs_dict.put(key, value); - MessageObject messageObject = new_dialogMessage.get(value.id); - dialogMessage.put(key, messageObject); - if (messageObject != null && messageObject.messageOwner.to_id.channel_id == 0) { - dialogMessagesByIds.put(messageObject.getId(), messageObject); - if (messageObject.messageOwner.random_id != 0) { - dialogMessagesByRandomIds.put(messageObject.messageOwner.random_id, messageObject); - } - } - } else { - currentDialog.unread_count = value.unread_count; - MessageObject oldMsg = dialogMessage.get(key); - if (oldMsg == null || currentDialog.top_message > 0) { - if (oldMsg != null && oldMsg.deleted || value.top_message > currentDialog.top_message) { - dialogs_dict.put(key, value); - MessageObject messageObject = new_dialogMessage.get(value.id); - dialogMessage.put(key, messageObject); - if (messageObject != null && messageObject.messageOwner.to_id.channel_id == 0) { - dialogMessagesByIds.put(messageObject.getId(), messageObject); - if (messageObject.messageOwner.random_id != 0) { - dialogMessagesByRandomIds.put(messageObject.messageOwner.random_id, messageObject); - } - } - if (oldMsg != null) { - dialogMessagesByIds.remove(oldMsg.getId()); - if (oldMsg.messageOwner.random_id != 0) { - dialogMessagesByRandomIds.remove(oldMsg.messageOwner.random_id); - } - } - if (messageObject == null) { - checkLastDialogMessage(value, null, 0); - } - } - } else { - MessageObject newMsg = new_dialogMessage.get(value.id); - if (oldMsg.deleted || newMsg == null || newMsg.messageOwner.date > oldMsg.messageOwner.date) { - dialogs_dict.put(key, value); - dialogMessage.put(key, newMsg); - if (newMsg != null && newMsg.messageOwner.to_id.channel_id == 0) { - dialogMessagesByIds.put(newMsg.getId(), newMsg); - if (newMsg.messageOwner.random_id != 0) { - dialogMessagesByRandomIds.put(newMsg.messageOwner.random_id, newMsg); - } - } - dialogMessagesByIds.remove(oldMsg.getId()); - if (oldMsg.messageOwner.random_id != 0) { - dialogMessagesByRandomIds.remove(oldMsg.messageOwner.random_id); - } - } - } - } - } - - dialogs.clear(); - dialogs.addAll(dialogs_dict.values()); - sortDialogs(null); - NotificationCenter.getInstance().postNotificationName(NotificationCenter.dialogsNeedReload); - NotificationsController.getInstance().processDialogsUpdateRead(dialogsToUpdate); - } - }); - } - }); - } - public void markMessageContentAsRead(final MessageObject messageObject) { } @@ -1631,20 +1059,18 @@ public class MessagesController implements NotificationCenter.NotificationCenter } req.users.add(getInputUser(user)); } - return ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + return 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, final TLRPC.TL_error error) { if (error != null) { AndroidUtilities.runOnUIThread(new Runnable() { @Override public void run() { - /* EDIT BY MR if (error.text.startsWith("FLOOD_WAIT")) { AlertsCreator.showFloodWaitAlert(error.text, fragment); } else { AlertsCreator.showAddUserAlert(error.text, fragment, false); } - */ NotificationCenter.getInstance().postNotificationName(NotificationCenter.chatDidFailCreate); } }); @@ -1665,7 +1091,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors); */ } return 0; } @@ -1693,7 +1119,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter } request = req; } - ConnectionsManager.getInstance().sendRequest(request, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(request, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error != null) { @@ -1701,40 +1127,9 @@ public class MessagesController implements NotificationCenter.NotificationCenter } processUpdates((TLRPC.Updates) response, false); } - }, ConnectionsManager.RequestFlagInvokeAfter); + }, ConnectionsManager.RequestFlagInvokeAfter);*/ } - public long getUpdatesStartTime(int type) { - if (type == 0) { - return updatesStartWaitTimeSeq; - } else if (type == 1) { - return updatesStartWaitTimePts; - } else if (type == 2) { - return updatesStartWaitTimeQts; - } - return 0; - } - - public void getDifference() { - } - - private int getUpdateType(TLRPC.Update update) { - if (update instanceof TLRPC.TL_updateNewMessage || update instanceof TLRPC.TL_updateReadMessagesContents || update instanceof TLRPC.TL_updateReadHistoryInbox || - update instanceof TLRPC.TL_updateReadHistoryOutbox || update instanceof TLRPC.TL_updateDeleteMessages || update instanceof TLRPC.TL_updateWebPage || - update instanceof TLRPC.TL_updateEditMessage) { - return 0; - /*} else if (update instanceof TLRPC.TL_updateNewEncryptedMessage) { - return 1; - } else if (update instanceof TLRPC.TL_updateNewChannelMessage || update instanceof TLRPC.TL_updateDeleteChannelMessages || update instanceof TLRPC.TL_updateEditChannelMessage) { - return 2;*/ - } else { - return 3; - } - } - - public void processUpdates(final TLRPC.Updates updates, boolean fromQueue) { - } - public boolean isDialogMuted(long dialog_id) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); int mute_type = preferences.getInt("notify2_" + dialog_id, 0); @@ -1960,7 +1355,7 @@ public class MessagesController implements NotificationCenter.NotificationCenter TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername(); req.username = username; - final int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + final int reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -1984,19 +1379,18 @@ public class MessagesController implements NotificationCenter.NotificationCenter } } else { if (fragment != null && fragment.getParentActivity() != null) { - /* try { Toast.makeText(fragment.getParentActivity(), LocaleController.getString("NoUsernameFound", R.string.NoUsernameFound), Toast.LENGTH_SHORT).show(); } catch (Exception e) { FileLog.e("tmessages", e); } - */ } } } }); } }); + */ progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, LocaleController.getString("Cancel", R.string.Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MrMailbox.java b/TMessagesProj/src/main/java/org/telegram/messenger/MrMailbox.java index 6da85c34a..779d0552a 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MrMailbox.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MrMailbox.java @@ -26,7 +26,6 @@ ******************************************************************************/ -// EDIT BY MR package org.telegram.messenger; @@ -317,5 +316,7 @@ public class MrMailbox { public final static int MR_TITLE_USERNAME = 2; public final static int MR_TITLE_SELF = 3; + // some rest of Telegram ... + public native static long getCurrentTimeMillis (); + public native static int getCurrentTime (); } -// /EDIT BY MR \ No newline at end of file diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/MusicBrowserService.java b/TMessagesProj/src/main/java/org/telegram/messenger/MusicBrowserService.java index 2839f6aed..db40a6e6e 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/MusicBrowserService.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/MusicBrowserService.java @@ -34,11 +34,8 @@ import android.os.Message; import android.os.Process; import android.os.SystemClock; import android.service.media.MediaBrowserService; -import android.text.TextUtils; import org.telegram.messenger.audioinfo.AudioInfo; -import org.telegram.messenger.query.SharedMediaQuery; -import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.TLRPC; import org.telegram.ui.LaunchActivity; @@ -47,7 +44,6 @@ import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Locale; @TargetApi(Build.VERSION_CODES.LOLLIPOP) public class MusicBrowserService extends MediaBrowserService implements NotificationCenter.NotificationCenterDelegate { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java b/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java index b387e1d27..a5c30d502 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/SendMessagesHelper.java @@ -356,7 +356,7 @@ public class SendMessagesHelper implements NotificationCenter.NotificationCenter String finalPath = (String) args[1]; long finalSize = (Long) args[2]; boolean isEncrypted = ((int) messageObject.getDialogId()) == 0; - FileLoader.getInstance().checkUploadNewDataAvailable(finalPath, isEncrypted, finalSize); + //FileLoader.getInstance().checkUploadNewDataAvailable(finalPath, isEncrypted, finalSize); if (finalSize != 0) { /* ArrayList arr = delayedMessages.get(messageObject.messageOwner.attachPath); diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java index b11a5fc2b..8222baaa1 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/Utilities.java @@ -52,12 +52,14 @@ public class Utilities { public native static void calcCDT(ByteBuffer hsvBuffer, int width, int height, ByteBuffer buffer); public native static boolean loadWebpImage(Bitmap bitmap, ByteBuffer buffer, int len, BitmapFactory.Options options, boolean unpin); public native static int convertVideoFrame(ByteBuffer src, ByteBuffer dest, int destFormat, int width, int height, int padding, int swap); - private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); + //private native static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, int offset, int length); public native static String readlink(String path); + /* public static void aesIgeEncryption(ByteBuffer buffer, byte[] key, byte[] iv, boolean encrypt, boolean changeIv, int offset, int length) { aesIgeEncryption(buffer, key, changeIv ? iv : iv.clone(), encrypt, offset, length); } + */ public static Integer parseInt(String value) { if (value == null) { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/query/MessagesQuery.java b/TMessagesProj/src/main/java/org/telegram/messenger/query/MessagesQuery.java index dd33ac8a5..96dd8a3d4 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/query/MessagesQuery.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/query/MessagesQuery.java @@ -18,7 +18,6 @@ import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.FileLog; import org.telegram.messenger.Utilities; import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/query/MessagesSearchQuery.java b/TMessagesProj/src/main/java/org/telegram/messenger/query/MessagesSearchQuery.java index e2d66d2ee..250d1b1d4 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/query/MessagesSearchQuery.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/query/MessagesSearchQuery.java @@ -119,7 +119,7 @@ public class MessagesSearchQuery { req.limit = 1; req.q = query; req.filter = new TLRPC.TL_inputMessagesFilterEmpty(); - mergeReqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + mergeReqId = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -137,7 +137,7 @@ public class MessagesSearchQuery { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors);*/ return; } else { lastMergeDialogId = 0; @@ -157,7 +157,7 @@ public class MessagesSearchQuery { final int currentReqId = ++lastReqId; lastSearchQuery = query; final long queryWithDialogFinal = queryWithDialog; - reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + reqId = 0; /* ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -202,7 +202,7 @@ public class MessagesSearchQuery { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors);*/ } public static String getLastSearchQuery() { diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/query/SearchQuery.java b/TMessagesProj/src/main/java/org/telegram/messenger/query/SearchQuery.java index e39aafe20..bde8307ef 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/query/SearchQuery.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/query/SearchQuery.java @@ -122,6 +122,7 @@ public class SearchQuery { loaded = true; } else { loading = true; + /* TLRPC.TL_contacts_getTopPeers req = new TLRPC.TL_contacts_getTopPeers(); req.hash = 0; req.bots_pm = false; @@ -152,7 +153,6 @@ public class SearchQuery { NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadHints); NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadInlineHints); final HashMap inlineDatesCopy = new HashMap<>(inlineDates); - /* MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { @Override public void run() { @@ -205,12 +205,11 @@ public class SearchQuery { } } }); - */ } }); } } - }); + });*/ } } @@ -261,7 +260,7 @@ public class SearchQuery { for (int a = 0; a < inlineBots.size(); a++) { if (inlineBots.get(a).peer.user_id == uid) { inlineBots.remove(a); - TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating(); + /*TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating(); req.category = new TLRPC.TL_topPeerCategoryBotsInline(); req.peer = MessagesController.getInputPeer(uid); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @@ -271,6 +270,7 @@ public class SearchQuery { } }); deletePeer(uid, 1); + */ NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadInlineHints); return; } @@ -283,7 +283,7 @@ public class SearchQuery { if (hints.get(a).peer.user_id == uid) { hints.remove(a); NotificationCenter.getInstance().postNotificationName(NotificationCenter.reloadHints); - TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating(); + /*TLRPC.TL_contacts_resetTopPeerRating req = new TLRPC.TL_contacts_resetTopPeerRating(); req.category = new TLRPC.TL_topPeerCategoryCorrespondents(); req.peer = MessagesController.getInputPeer(uid); deletePeer(uid, 0); @@ -292,7 +292,7 @@ public class SearchQuery { public void run(TLObject response, TLRPC.TL_error error) { } - }); + });*/ return; } } @@ -400,19 +400,4 @@ public class SearchQuery { }); */ } - - private static void deletePeer(final int did, final int type) { - /* - MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() { - @Override - public void run() { - try { - MessagesStorage.getInstance().getDatabase().executeFast(String.format(Locale.US, "DELETE FROM chat_hints WHERE did = %d AND type = %d", did, type)).stepThis().dispose(); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - */ - } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/query/SharedMediaQuery.java b/TMessagesProj/src/main/java/org/telegram/messenger/query/SharedMediaQuery.java index 6e6de893e..ed936c022 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/query/SharedMediaQuery.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/query/SharedMediaQuery.java @@ -8,9 +8,6 @@ package org.telegram.messenger.query; -import android.text.TextUtils; - - import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.ChatObject; import org.telegram.messenger.ImageLoader; @@ -18,17 +15,12 @@ import org.telegram.messenger.MessageObject; import org.telegram.messenger.MessagesController; import org.telegram.messenger.MrMailbox; import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.FileLog; import org.telegram.messenger.Utilities; import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.NativeByteBuffer; -import org.telegram.tgnet.RequestDelegate; -import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import java.util.ArrayList; import java.util.HashMap; -import java.util.Locale; public class SharedMediaQuery { @@ -66,7 +58,7 @@ public class SharedMediaQuery { if (req.peer == null) { return; } - int reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + int reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { if (error == null) { @@ -81,7 +73,7 @@ public class SharedMediaQuery { processLoadedMedia(res, uid, offset, count, max_id, type, false, classGuid, isChannel, topReached); } } - }); + });*/ ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); } } diff --git a/TMessagesProj/src/main/java/org/telegram/messenger/query/StickersQuery.java b/TMessagesProj/src/main/java/org/telegram/messenger/query/StickersQuery.java index ad2e20bc4..4e74fc97a 100644 --- a/TMessagesProj/src/main/java/org/telegram/messenger/query/StickersQuery.java +++ b/TMessagesProj/src/main/java/org/telegram/messenger/query/StickersQuery.java @@ -17,7 +17,6 @@ import org.telegram.messenger.NotificationCenter; import org.telegram.messenger.FileLog; import org.telegram.messenger.R; import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.NativeByteBuffer; import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; @@ -205,7 +204,7 @@ public class StickersQuery { }); */ } else { - final TLRPC.TL_messages_getAllStickers req = new TLRPC.TL_messages_getAllStickers(); + /*final TLRPC.TL_messages_getAllStickers req = new TLRPC.TL_messages_getAllStickers(); req.hash = force ? 0 : loadHash; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -266,7 +265,7 @@ public class StickersQuery { } }); } - }); + });*/ } } @@ -477,7 +476,7 @@ public class StickersQuery { loadHash = calcStickersHash(stickerSets); putStickersToCache(stickerSets, loadDate, loadHash); NotificationCenter.getInstance().postNotificationName(NotificationCenter.stickersDidLoaded); - TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet(); + /*TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet(); req.stickerset = stickerSetID; req.disabled = hide == 1; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @@ -490,9 +489,9 @@ public class StickersQuery { } }, 1000); } - }); + });*/ } else { - TLRPC.TL_messages_uninstallStickerSet req = new TLRPC.TL_messages_uninstallStickerSet(); + /*TLRPC.TL_messages_uninstallStickerSet req = new TLRPC.TL_messages_uninstallStickerSet(); req.stickerset = stickerSetID; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -513,7 +512,7 @@ public class StickersQuery { } }); } - }); + });*/ } } } diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/AbstractSerializedData.java b/TMessagesProj/src/main/java/org/telegram/tgnet/AbstractSerializedData.java index 19409cac9..b2bf298c4 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/AbstractSerializedData.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/AbstractSerializedData.java @@ -8,24 +8,14 @@ public abstract class AbstractSerializedData { public abstract void writeBool(boolean value); - public abstract void writeBytes(byte[] b); - public abstract void writeBytes(byte[] b, int offset, int count); - public abstract void writeByte(int i); - - public abstract void writeByte(byte b); - public abstract void writeString(String s); - public abstract void writeByteArray(byte[] b, int offset, int count); - public abstract void writeByteArray(byte[] b); public abstract void writeDouble(double d); - public abstract void writeByteBuffer(NativeByteBuffer buffer); - public abstract int readInt32(boolean exception); public abstract boolean readBool(boolean exception); @@ -40,8 +30,6 @@ public abstract class AbstractSerializedData { public abstract byte[] readByteArray(boolean exception); - public abstract NativeByteBuffer readByteBuffer(boolean exception); - public abstract double readDouble(boolean exception); public abstract int length(); diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java b/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java index e45020687..440446b76 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/ConnectionsManager.java @@ -15,10 +15,8 @@ import org.telegram.messenger.BuildVars; import org.telegram.messenger.ContactsController; import org.telegram.messenger.ApplicationLoader; import org.telegram.messenger.FileLog; -import org.telegram.messenger.MessagesController; +import org.telegram.messenger.MrMailbox; import org.telegram.messenger.NotificationCenter; -import org.telegram.messenger.UserConfig; -import org.telegram.messenger.Utilities; import java.net.Inet4Address; import java.net.Inet6Address; @@ -27,38 +25,21 @@ import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.util.Enumeration; import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; public class ConnectionsManager { - public final static int ConnectionTypeGeneric = 1; - public final static int ConnectionTypeDownload = 2; - public final static int ConnectionTypeUpload = 4; - public final static int ConnectionTypePush = 8; - public final static int ConnectionTypeDownload2 = ConnectionTypeDownload | (1 << 16); - - public final static int RequestFlagEnableUnauthorized = 1; public final static int RequestFlagFailOnServerErrors = 2; - public final static int RequestFlagCanCompress = 4; - public final static int RequestFlagWithoutLogin = 8; - public final static int RequestFlagTryDifferentDc = 16; - public final static int RequestFlagForceDownload = 32; - public final static int RequestFlagInvokeAfter = 64; - public final static int RequestFlagNeedQuickAck = 128; public final static int ConnectionStateConnecting = 1; public final static int ConnectionStateWaitingForNetwork = 2; public final static int ConnectionStateConnected = 3; public final static int ConnectionStateUpdating = 4; - public final static int DEFAULT_DATACENTER_ID = Integer.MAX_VALUE; - private long lastPauseTime = System.currentTimeMillis(); private boolean appPaused = true; private int lastClassGuid = 1; private boolean isUpdating = false; - private int connectionState = native_getConnectionState(); - private AtomicInteger lastRequestToken = new AtomicInteger(1); + //private int connectionState = native_getConnectionState(); private PowerManager.WakeLock wakeLock = null; private static volatile ConnectionsManager Instance = null; @@ -87,17 +68,14 @@ public class ConnectionsManager { } public long getCurrentTimeMillis() { - return native_getCurrentTimeMillis(); + return MrMailbox.getCurrentTimeMillis(); } public int getCurrentTime() { - return native_getCurrentTime(); - } - - public int getTimeDifference() { - return native_getTimeDifference(); + return MrMailbox.getCurrentTime(); } + /* public int sendRequest(TLObject object, RequestDelegate completionBlock) { return sendRequest(object, completionBlock, null, 0); } @@ -115,78 +93,24 @@ public class ConnectionsManager { } public int sendRequest(final TLObject object, final RequestDelegate onComplete, final QuickAckDelegate onQuickAck, final int flags, final int datacenterId, final int connetionType, final boolean immediate) { - return 0; // EDIT BY MR - /* EDIT BY MR - final int requestToken = lastRequestToken.getAndIncrement(); - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - FileLog.d("tmessages", "send request " + object + " with token = " + requestToken); - try { - NativeByteBuffer buffer = new NativeByteBuffer(object.getObjectSize()); - object.serializeToStream(buffer); - object.freeResources(); - - native_sendRequest(buffer.address, new RequestDelegateInternal() { - @Override - public void run(int response, int errorCode, String errorText) { - try { - TLObject resp = null; - TLRPC.TL_error error = null; - if (response != 0) { - NativeByteBuffer buff = NativeByteBuffer.wrap(response); - buff.reused = true; - resp = object.deserializeResponse(buff, buff.readInt32(true), true); - } else if (errorText != null) { - error = new TLRPC.TL_error(); - error.code = errorCode; - error.text = errorText; - FileLog.e("tmessages", object + " got error " + error.code + " " + error.text); - } - FileLog.d("tmessages", "java received " + resp + " error = " + error); - final TLObject finalResponse = resp; - final TLRPC.TL_error finalError = error; - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - onComplete.run(finalResponse, finalError); - if (finalResponse != null) { - finalResponse.freeResources(); - } - } - }); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }, onQuickAck, flags, datacenterId, connetionType, immediate, requestToken); - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - return requestToken; - */ + return 0; // this is the old Telegram function to send a request, no longer needed } + */ public void cancelRequest(int token, boolean notifyServer) { - native_cancelRequest(token, notifyServer); + //native_cancelRequest(token, notifyServer); } public void cleanup() { - native_cleanUp(); + //native_cleanUp(); } public void cancelRequestsForGuid(int guid) { - native_cancelRequestsForGuid(guid); + //native_cancelRequestsForGuid(guid); } public void bindRequestToGuid(int requestToken, int guid) { - native_bindRequestToGuid(requestToken, guid); - } - - public void applyDatacenterAddress(int datacenterId, String ipAddress, int port) { - native_applyDatacenterAddress(datacenterId, ipAddress, port); + //native_bindRequestToGuid(requestToken, guid); } public int getConnectionState() { @@ -200,20 +124,20 @@ public class ConnectionsManager { } public void setUserId(int id) { - native_setUserId(id); + //native_setUserId(id); } private void checkConnection() { - native_setUseIpv6(useIpv6Address()); - native_setNetworkAvailable(isNetworkOnline()); + //native_setUseIpv6(useIpv6Address()); + //native_setNetworkAvailable(isNetworkOnline()); } public void setPushConnectionEnabled(boolean value) { - native_setPushConnectionEnabled(value); + //native_setPushConnectionEnabled(value); } public void init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String configPath, String logPath, int userId, boolean enablePushConnection) { - native_init(version, layer, apiId, deviceModel, systemVersion, appVersion, langCode, configPath, logPath, userId, enablePushConnection); + //native_init(version, layer, apiId, deviceModel, systemVersion, appVersion, langCode, configPath, logPath, userId, enablePushConnection); checkConnection(); BroadcastReceiver networkStateReceiver = new BroadcastReceiver() { @Override @@ -226,19 +150,11 @@ public class ConnectionsManager { } public void switchBackend() { - native_switchBackend(); + //native_switchBackend(); } public void resumeNetworkMaybe() { - native_resumeNetwork(true); - } - - public void updateDcSettings() { - native_updateDcSettings(); - } - - public long getPauseTime() { - return lastPauseTime; + //native_resumeNetwork(true); } public void setAppPaused(final boolean value, final boolean byScreenState) { @@ -250,7 +166,7 @@ public class ConnectionsManager { if (lastPauseTime == 0) { lastPauseTime = System.currentTimeMillis(); } - native_pauseNetwork(); + //native_pauseNetwork(); } else { if (appPaused) { return; @@ -260,135 +176,10 @@ public class ConnectionsManager { ContactsController.getInstance().checkContacts(); } lastPauseTime = 0; - native_resumeNetwork(false); + //native_resumeNetwork(false); } } - public static void onUnparsedMessageReceived(int address) { - try { - NativeByteBuffer buff = NativeByteBuffer.wrap(address); - buff.reused = true; - final TLObject message = TLClassStore.Instance().TLdeserialize(buff, buff.readInt32(true), true); - if (message instanceof TLRPC.Updates) { - FileLog.d("tmessages", "java received " + message); - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (getInstance().wakeLock.isHeld()) { - FileLog.d("tmessages", "release wakelock"); - getInstance().wakeLock.release(); - } - } - }); - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - MessagesController.getInstance().processUpdates((TLRPC.Updates) message, false); - } - }); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - - public static void onUpdate() { - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - MessagesController.getInstance().updateTimerProc(); - } - }); - } - - public static void onSessionCreated() { - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - MessagesController.getInstance().getDifference(); - } - }); - } - - public static void onConnectionStateChanged(final int state) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - getInstance().connectionState = state; - NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState); - } - }); - } - - public static void onLogout() { - /* - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (UserConfig.getClientUserId() != 0) { - UserConfig.clearConfig(); - MessagesController.getInstance().performLogout(false); - } - } - }); - */ - } - - public static void onUpdateConfig(int address) { - try { - NativeByteBuffer buff = NativeByteBuffer.wrap(address); - buff.reused = true; - final TLRPC.TL_config message = TLRPC.TL_config.TLdeserialize(buff, buff.readInt32(true), true); - if (message != null) { - Utilities.stageQueue.postRunnable(new Runnable() { - @Override - public void run() { - MessagesController.getInstance().updateConfig(message); - } - }); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - - public static void onInternalPushReceived() { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - try { - if (!getInstance().wakeLock.isHeld()) { - getInstance().wakeLock.acquire(10000); - FileLog.d("tmessages", "acquire wakelock"); - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - }); - } - - public static native void native_switchBackend(); - public static native void native_pauseNetwork(); - public static native void native_setUseIpv6(boolean value); - public static native void native_updateDcSettings(); - public static native void native_setNetworkAvailable(boolean value); - public static native void native_resumeNetwork(boolean partial); - public static native long native_getCurrentTimeMillis(); - public static native int native_getCurrentTime(); - public static native int native_getTimeDifference(); - public static native void native_sendRequest(int object, RequestDelegateInternal onComplete, QuickAckDelegate onQuickAck, int flags, int datacenterId, int connetionType, boolean immediate, int requestToken); - public static native void native_cancelRequest(int token, boolean notifyServer); - public static native void native_cleanUp(); - public static native void native_cancelRequestsForGuid(int guid); - public static native void native_bindRequestToGuid(int requestToken, int guid); - public static native void native_applyDatacenterAddress(int datacenterId, String ipAddress, int port); - public static native int native_getConnectionState(); - public static native void native_setUserId(int id); - public static native void native_init(int version, int layer, int apiId, String deviceModel, String systemVersion, String appVersion, String langCode, String configPath, String logPath, int userId, boolean enablePushConnection); - public static native void native_setJava(boolean useJavaByteBuffers); - public static native void native_setPushConnectionEnabled(boolean value); - public int generateClassGuid() { return lastClassGuid++; } @@ -419,25 +210,6 @@ public class ConnectionsManager { return false; } - public void applyCountryPortNumber(String number) { - - } - - public void setIsUpdating(final boolean value) { - AndroidUtilities.runOnUIThread(new Runnable() { - @Override - public void run() { - if (isUpdating == value) { - return; - } - isUpdating = value; - if (connectionState == ConnectionStateConnected) { - NotificationCenter.getInstance().postNotificationName(NotificationCenter.didUpdatedConnectionState); - } - } - }); - } - @SuppressLint("NewApi") protected static boolean useIpv6Address() { if (Build.VERSION.SDK_INT < 19) { diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/NativeByteBuffer.java b/TMessagesProj/src/main/java/org/telegram/tgnet/NativeByteBuffer.java deleted file mode 100644 index 91185ea06..000000000 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/NativeByteBuffer.java +++ /dev/null @@ -1,510 +0,0 @@ -package org.telegram.tgnet; - -import org.telegram.messenger.FileLog; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -public class NativeByteBuffer extends AbstractSerializedData { - - protected int address; - public ByteBuffer buffer; - private boolean justCalc; - private int len; - public boolean reused = true; - - private static final ThreadLocal addressWrapper = new ThreadLocal() { - @Override - protected NativeByteBuffer initialValue() { - return new NativeByteBuffer(0, true); - } - }; - - public static NativeByteBuffer wrap(int address) { - NativeByteBuffer result = addressWrapper.get(); - if (address != 0) { - if (!result.reused) { - FileLog.e("tmessages", "forgot to reuse?"); - } - result.address = address; - result.reused = false; - result.buffer = native_getJavaByteBuffer(address); - result.buffer.limit(native_limit(address)); - int position = native_position(address); - if (position <= result.buffer.limit()) { - result.buffer.position(position); - } - result.buffer.order(ByteOrder.LITTLE_ENDIAN); - } - return result; - } - - private NativeByteBuffer(int address, boolean wrap) { - - } - - public NativeByteBuffer(int size) throws Exception { - if (size >= 0) { - address = native_getFreeBuffer(size); - if (address != 0) { - buffer = native_getJavaByteBuffer(address); - buffer.position(0); - buffer.limit(size); - buffer.order(ByteOrder.LITTLE_ENDIAN); - } - } else { - throw new Exception("invalid NativeByteBuffer size"); - } - } - - public NativeByteBuffer(boolean calculate) { - justCalc = calculate; - } - - public int position() { - return buffer.position(); - } - - public void position(int position) { - buffer.position(position); - } - - public int capacity() { - return buffer.capacity(); - } - - public int limit() { - return buffer.limit(); - } - - public void limit(int limit) { - buffer.limit(limit); - } - - public void put(ByteBuffer buff) { - buffer.put(buff); - } - - public void rewind() { - if (justCalc) { - len = 0; - } else { - buffer.rewind(); - } - } - - public void compact() { - buffer.compact(); - } - - public boolean hasRemaining() { - return buffer.hasRemaining(); - } - - public void writeInt32(int x) { - try { - if (!justCalc) { - buffer.putInt(x); - } else { - len += 4; - } - } catch(Exception e) { - FileLog.e("tmessages", "write int32 error"); - } - } - - public void writeInt64(long x) { - try { - if (!justCalc) { - buffer.putLong(x); - } else { - len += 8; - } - } catch(Exception e) { - FileLog.e("tmessages", "write int64 error"); - } - } - - public void writeBool(boolean value) { - if (!justCalc) { - if (value) { - writeInt32(0x997275b5); - } else { - writeInt32(0xbc799737); - } - } else { - len += 4; - } - } - - public void writeBytes(byte[] b) { - try { - if (!justCalc) { - buffer.put(b); - } else { - len += b.length; - } - } catch (Exception e) { - FileLog.e("tmessages", "write raw error"); - } - } - - public void writeBytes(byte[] b, int offset, int count) { - try { - if (!justCalc) { - buffer.put(b, offset, count); - } else { - len += count; - } - } catch (Exception e) { - FileLog.e("tmessages", "write raw error"); - } - } - - public void writeByte(int i) { - writeByte((byte) i); - } - - public void writeByte(byte b) { - try { - if (!justCalc) { - buffer.put(b); - } else { - len += 1; - } - } catch (Exception e) { - FileLog.e("tmessages", "write byte error"); - } - } - - public void writeString(String s) { - try { - writeByteArray(s.getBytes("UTF-8")); - } catch(Exception e) { - FileLog.e("tmessages", "write string error"); - } - } - - public void writeByteArray(byte[] b, int offset, int count) { - try { - if(count <= 253) { - if (!justCalc) { - buffer.put((byte)count); - } else { - len += 1; - } - } else { - if (!justCalc) { - buffer.put((byte)254); - buffer.put((byte)count); - buffer.put((byte)(count >> 8)); - buffer.put((byte)(count >> 16)); - } else { - len += 4; - } - } - if (!justCalc) { - buffer.put(b, offset, count); - } else { - len += count; - } - int i = count <= 253 ? 1 : 4; - while ((count + i) % 4 != 0) { - if (!justCalc) { - buffer.put((byte)0); - } else { - len += 1; - } - i++; - } - } catch (Exception e) { - FileLog.e("tmessages", "write byte array error"); - } - } - - public void writeByteArray(byte[] b) { - try { - if (b.length <= 253) { - if (!justCalc) { - buffer.put((byte) b.length); - } else { - len += 1; - } - } else { - if (!justCalc) { - buffer.put((byte) 254); - buffer.put((byte) b.length); - buffer.put((byte) (b.length >> 8)); - buffer.put((byte) (b.length >> 16)); - } else { - len += 4; - } - } - if (!justCalc) { - buffer.put(b); - } else { - len += b.length; - } - int i = b.length <= 253 ? 1 : 4; - while((b.length + i) % 4 != 0) { - if (!justCalc) { - buffer.put((byte) 0); - } else { - len += 1; - } - i++; - } - } catch (Exception e) { - FileLog.e("tmessages", "write byte array error"); - } - } - - public void writeDouble(double d) { - try { - writeInt64(Double.doubleToRawLongBits(d)); - } catch(Exception e) { - FileLog.e("tmessages", "write double error"); - } - } - - public void writeByteBuffer(NativeByteBuffer b) { - try { - int l = b.limit(); - if (l <= 253) { - if (!justCalc) { - buffer.put((byte) l); - } else { - len += 1; - } - } else { - if (!justCalc) { - buffer.put((byte) 254); - buffer.put((byte) l); - buffer.put((byte) (l >> 8)); - buffer.put((byte) (l >> 16)); - } else { - len += 4; - } - } - if (!justCalc) { - b.rewind(); - buffer.put(b.buffer); - } else { - len += l; - } - int i = l <= 253 ? 1 : 4; - while((l + i) % 4 != 0) { - if (!justCalc) { - buffer.put((byte) 0); - } else { - len += 1; - } - i++; - } - } catch (Exception e) { - FileLog.e("tmessages", e); - } - } - - public void writeBytes(NativeByteBuffer b) { - if (justCalc) { - len += b.limit(); - } else { - b.rewind(); - buffer.put(b.buffer); - } - } - - public int getIntFromByte(byte b) { - return b >= 0 ? b : ((int)b) + 256; - } - - public int length() { - if (!justCalc) { - return buffer.position(); - } - return len; - } - - public void skip(int count) { - if (count == 0) { - return; - } - if (!justCalc) { - buffer.position(buffer.position() + count); - } else { - len += count; - } - } - - public int getPosition() { - return buffer.position(); - } - - public int readInt32(boolean exception) { - try { - return buffer.getInt(); - } catch (Exception e) { - if (exception) { - throw new RuntimeException("read int32 error", e); - } else { - FileLog.e("tmessages", "read int32 error"); - } - } - return 0; - } - - public boolean readBool(boolean exception) { - int consructor = readInt32(exception); - if (consructor == 0x997275b5) { - return true; - } else if (consructor == 0xbc799737) { - return false; - } - if (exception) { - throw new RuntimeException("Not bool value!"); - } else { - FileLog.e("tmessages", "Not bool value!"); - } - return false; - } - - public long readInt64(boolean exception) { - try { - return buffer.getLong(); - } catch (Exception e) { - if (exception) { - throw new RuntimeException("read int64 error", e); - } else { - FileLog.e("tmessages", "read int64 error"); - } - } - return 0; - } - - public void readBytes(byte[] b, boolean exception) { - try { - buffer.get(b); - } catch (Exception e) { - if (exception) { - throw new RuntimeException("read raw error", e); - } else { - FileLog.e("tmessages", "read raw error"); - } - } - } - - public byte[] readData(int count, boolean exception) { - byte[] arr = new byte[count]; - readBytes(arr, exception); - return arr; - } - - public String readString(boolean exception) { - try { - int sl = 1; - int l = getIntFromByte(buffer.get()); - if(l >= 254) { - l = getIntFromByte(buffer.get()) | (getIntFromByte(buffer.get()) << 8) | (getIntFromByte(buffer.get()) << 16); - sl = 4; - } - byte[] b = new byte[l]; - buffer.get(b); - int i = sl; - while((l + i) % 4 != 0) { - buffer.get(); - i++; - } - return new String(b, "UTF-8"); - } catch (Exception e) { - if (exception) { - throw new RuntimeException("read string error", e); - } else { - FileLog.e("tmessages", "read string error"); - } - } - return null; - } - - public byte[] readByteArray(boolean exception) { - try { - int sl = 1; - int l = getIntFromByte(buffer.get()); - if (l >= 254) { - l = getIntFromByte(buffer.get()) | (getIntFromByte(buffer.get()) << 8) | (getIntFromByte(buffer.get()) << 16); - sl = 4; - } - byte[] b = new byte[l]; - buffer.get(b); - int i = sl; - while((l + i) % 4 != 0) { - buffer.get(); - i++; - } - return b; - } catch (Exception e) { - if (exception) { - throw new RuntimeException("read byte array error", e); - } else { - FileLog.e("tmessages", "read byte array error"); - } - } - return null; - } - - public NativeByteBuffer readByteBuffer(boolean exception) { - try { - int sl = 1; - int l = getIntFromByte(buffer.get()); - if (l >= 254) { - l = getIntFromByte(buffer.get()) | (getIntFromByte(buffer.get()) << 8) | (getIntFromByte(buffer.get()) << 16); - sl = 4; - } - NativeByteBuffer b = new NativeByteBuffer(l); - int old = buffer.limit(); - buffer.limit(buffer.position() + l); - b.buffer.put(buffer); - buffer.limit(old); - b.buffer.position(0); - int i = sl; - while((l + i) % 4 != 0) { - buffer.get(); - i++; - } - return b; - } catch (Exception e) { - if (exception) { - throw new RuntimeException("read byte array error", e); - } else { - FileLog.e("tmessages", "read byte array error"); - } - } - return null; - } - - public double readDouble(boolean exception) { - try { - return Double.longBitsToDouble(readInt64(exception)); - } catch(Exception e) { - if (exception) { - throw new RuntimeException("read double error", e); - } else { - FileLog.e("tmessages", "read double error"); - } - } - return 0; - } - - public void reuse() { - if (address != 0) { - reused = true; - native_reuse(address); - } - } - - public static native int native_getFreeBuffer(int length); - public static native ByteBuffer native_getJavaByteBuffer(int address); - public static native int native_limit(int address); - public static native int native_position(int address); - public static native void native_reuse(int address); -} diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/SerializedData.java b/TMessagesProj/src/main/java/org/telegram/tgnet/SerializedData.java index 13f1ff2d4..507a10944 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/SerializedData.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/SerializedData.java @@ -464,14 +464,4 @@ public class SerializedData extends AbstractSerializedData { } return 0; } - - @Override - public void writeByteBuffer(NativeByteBuffer buffer) { - - } - - @Override - public NativeByteBuffer readByteBuffer(boolean exception) { - return null; - } } diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/TLClassStore.java b/TMessagesProj/src/main/java/org/telegram/tgnet/TLClassStore.java deleted file mode 100644 index 11e79f95e..000000000 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/TLClassStore.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This is the source code of Telegram for Android v. 3.x.x. - * It is licensed under GNU GPL v. 2 or later. - * You should have received a copy of the license in this archive (see LICENSE). - * - * Copyright Nikolai Kudashov, 2013-2016. - */ - -package org.telegram.tgnet; - -import org.telegram.messenger.FileLog; - -import java.util.HashMap; - -public class TLClassStore { - private HashMap classStore; - - public TLClassStore() { - classStore = new HashMap<>(); - - classStore.put(TLRPC.TL_error.constructor, TLRPC.TL_error.class); - classStore.put(TLRPC.TL_decryptedMessageService.constructor, TLRPC.TL_decryptedMessageService.class); - classStore.put(TLRPC.TL_decryptedMessage.constructor, TLRPC.TL_decryptedMessage.class); - classStore.put(TLRPC.TL_config.constructor, TLRPC.TL_config.class); - classStore.put(TLRPC.TL_decryptedMessageLayer.constructor, TLRPC.TL_decryptedMessageLayer.class); - classStore.put(TLRPC.TL_decryptedMessage_layer17.constructor, TLRPC.TL_decryptedMessage.class); - classStore.put(TLRPC.TL_decryptedMessageService_layer8.constructor, TLRPC.TL_decryptedMessageService_layer8.class); - classStore.put(TLRPC.TL_decryptedMessage_layer8.constructor, TLRPC.TL_decryptedMessage_layer8.class); - classStore.put(TLRPC.TL_message_secret.constructor, TLRPC.TL_message_secret.class); - classStore.put(TLRPC.TL_message_secret_old.constructor, TLRPC.TL_message_secret_old.class); - classStore.put(TLRPC.TL_messageEncryptedAction.constructor, TLRPC.TL_messageEncryptedAction.class); - classStore.put(TLRPC.TL_null.constructor, TLRPC.TL_null.class); - - classStore.put(TLRPC.TL_updateShortChatMessage.constructor, TLRPC.TL_updateShortChatMessage.class); - classStore.put(TLRPC.TL_updates.constructor, TLRPC.TL_updates.class); - classStore.put(TLRPC.TL_updateShortMessage.constructor, TLRPC.TL_updateShortMessage.class); - classStore.put(TLRPC.TL_updateShort.constructor, TLRPC.TL_updateShort.class); - classStore.put(TLRPC.TL_updatesCombined.constructor, TLRPC.TL_updatesCombined.class); - classStore.put(TLRPC.TL_updateShortSentMessage.constructor, TLRPC.TL_updateShortSentMessage.class); - classStore.put(TLRPC.TL_updatesTooLong.constructor, TLRPC.TL_updatesTooLong.class); - } - - static TLClassStore store = null; - - public static TLClassStore Instance() { - if (store == null) { - store = new TLClassStore(); - } - return store; - } - - public TLObject TLdeserialize(NativeByteBuffer stream, int constructor, boolean exception) { - Class objClass = classStore.get(constructor); - if (objClass != null) { - TLObject response; - try { - response = (TLObject) objClass.newInstance(); - } catch (Throwable e) { - FileLog.e("tmessages", e); - return null; - } - response.readParams(stream, exception); - return response; - } - return null; - } -} diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/TLObject.java b/TMessagesProj/src/main/java/org/telegram/tgnet/TLObject.java index 1f781b6d3..675d32e7d 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/TLObject.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/TLObject.java @@ -10,13 +10,15 @@ package org.telegram.tgnet; public class TLObject { - public boolean disableFree = false; + //public boolean disableFree = false; + /* private static final ThreadLocal sizeCalculator = new ThreadLocal() { @Override protected NativeByteBuffer initialValue() { return new NativeByteBuffer(true); } }; + */ public TLObject() { @@ -30,18 +32,7 @@ public class TLObject { } - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return null; - } - - public void freeResources() { - - } - public int getObjectSize() { - NativeByteBuffer byteBuffer = sizeCalculator.get(); - byteBuffer.rewind(); - serializeToStream(sizeCalculator.get()); - return byteBuffer.length(); + return 0; } } diff --git a/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java b/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java index 5c746bea4..9267c7ae6 100644 --- a/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java +++ b/TMessagesProj/src/main/java/org/telegram/tgnet/TLRPC.java @@ -17,11 +17,8 @@ public class TLRPC { public static final int CHAT_FLAG_IS_PUBLIC = 0x00000040; public static final int MESSAGE_FLAG_FWD = 0x00000004; public static final int MESSAGE_FLAG_REPLY = 0x00000008; - public static final int MESSAGE_FLAG_HAS_MARKUP = 0x00000040; - public static final int MESSAGE_FLAG_HAS_ENTITIES = 0x00000080; public static final int MESSAGE_FLAG_HAS_FROM_ID = 0x00000100; public static final int MESSAGE_FLAG_HAS_MEDIA = 0x00000200; - public static final int MESSAGE_FLAG_HAS_BOT_ID = 0x00000800; public static final int MESSAGE_FLAG_EDITED = 0x00008000; public static final int LAYER = 53; @@ -380,83 +377,6 @@ public class TLRPC { } } - public static class TL_messages_messagesSlice extends messages_Messages { - public static int constructor = 0xb446ae3; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - count = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Message object = Message.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - messages.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Chat object = Chat.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - chats.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - User object = User.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - users.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(count); - stream.writeInt32(0x1cb5c415); - int count = messages.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - messages.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = chats.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - chats.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - } - } - public static class Peer extends TLObject { public int channel_id; public int user_id; @@ -530,75 +450,6 @@ public class TLRPC { } } - public static class TL_account_privacyRules extends TLObject { - public static int constructor = 0x554abb6f; - - public ArrayList rules = new ArrayList<>(); - public ArrayList users = new ArrayList<>(); - - public static TL_account_privacyRules TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_account_privacyRules.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_account_privacyRules", constructor)); - } else { - return null; - } - } - TL_account_privacyRules result = new TL_account_privacyRules(); - result.readParams(stream, exception); - return result; - } - - public void readParams(AbstractSerializedData stream, boolean exception) { - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - PrivacyRule object = PrivacyRule.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - rules.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - User object = User.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - users.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = rules.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - rules.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - } - } - public static class ChatInvite extends TLObject { public int flags; public boolean channel; @@ -1188,15 +1039,6 @@ public class TLRPC { } } - public static class TL_contacts_contactsNotModified extends contacts_Contacts { - public static int constructor = 0xb74ba9d2; - - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - public static class InputPrivacyKey extends TLObject { public static InputPrivacyKey TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -1205,24 +1047,6 @@ public class TLRPC { } } - public static class TL_inputPrivacyKeyChatInvite extends InputPrivacyKey { - public static int constructor = 0xbdfb0426; - - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - - public static class TL_inputPrivacyKeyStatusTimestamp extends InputPrivacyKey { - public static int constructor = 0x4f96cb18; - - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - public static class photos_Photos extends TLObject { public ArrayList photos = new ArrayList<>(); public ArrayList users = new ArrayList<>(); @@ -1234,60 +1058,6 @@ public class TLRPC { } } - public static class TL_photos_photos extends photos_Photos { - public static int constructor = 0x8dca6aa5; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Photo object = Photo.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - photos.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - User object = User.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - users.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = photos.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - photos.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - } - } - public static class ChatFull extends TLObject { public int flags; public boolean can_view_participants; @@ -1610,22 +1380,6 @@ public class TLRPC { } } - public static class TL_webPagePending extends WebPage { - public static int constructor = 0xc586da1c; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - id = stream.readInt64(exception); - date = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(id); - stream.writeInt32(date); - } - } - public static class TL_webPageEmpty extends WebPage { public static int constructor = 0xeb1477e8; @@ -1640,20 +1394,6 @@ public class TLRPC { } } - public static class TL_webPageUrlPending extends WebPage { - public static int constructor = 0xd41a5167; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - url = stream.readString(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(url); - } - } - public static class TL_webPage extends WebPage { public static int constructor = 0xca820ed7; @@ -1746,34 +1486,6 @@ public class TLRPC { } } - public static class TL_auth_passwordRecovery extends TLObject { - public static int constructor = 0x137948a5; - - public String email_pattern; - - public static TL_auth_passwordRecovery TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_auth_passwordRecovery.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_auth_passwordRecovery", constructor)); - } else { - return null; - } - } - TL_auth_passwordRecovery result = new TL_auth_passwordRecovery(); - result.readParams(stream, exception); - return result; - } - - public void readParams(AbstractSerializedData stream, boolean exception) { - email_pattern = stream.readString(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(email_pattern); - } - } - public static class TL_botCommand extends TLObject { public static int constructor = 0xc27ac8c7; @@ -2475,24 +2187,6 @@ public class TLRPC { } } - public static class TL_topPeerCategoryCorrespondents extends TopPeerCategory { - public static int constructor = 0x637b7ed; - - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - - public static class TL_topPeerCategoryBotsInline extends TopPeerCategory { - public static int constructor = 0x148677e2; - - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - public static class TL_contactBlocked extends TLObject { public static int constructor = 0x561bc879; @@ -3105,170 +2799,6 @@ public class TLRPC { } } - public static class TL_updateReadHistoryInbox extends Update { - public static int constructor = 0x9961fd5c; - - public Peer peer; - - public void readParams(AbstractSerializedData stream, boolean exception) { - peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - max_id = stream.readInt32(exception); - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - peer.serializeToStream(stream); - stream.writeInt32(max_id); - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - - public static class TL_updateEditMessage extends Update { - public static int constructor = 0xe40370a3; - - public Message message; - - public void readParams(AbstractSerializedData stream, boolean exception) { - message = Message.TLdeserialize(stream, stream.readInt32(exception), exception); - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - message.serializeToStream(stream); - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - - public static class TL_updateWebPage extends Update { - public static int constructor = 0x7f891213; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - webpage = WebPage.TLdeserialize(stream, stream.readInt32(exception), exception); - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - webpage.serializeToStream(stream); - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - - public static class TL_updateNewMessage extends Update { - public static int constructor = 0x1f2b0afd; - - public Message message; - - public void readParams(AbstractSerializedData stream, boolean exception) { - message = Message.TLdeserialize(stream, stream.readInt32(exception), exception); - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - message.serializeToStream(stream); - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - - public static class TL_updateReadMessagesContents extends Update { - public static int constructor = 0x68c13933; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - messages.add(stream.readInt32(exception)); - } - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = messages.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stream.writeInt32(messages.get(a)); - } - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - - public static class TL_updateDeleteMessages extends Update { - public static int constructor = 0xa20db0e5; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - messages.add(stream.readInt32(exception)); - } - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = messages.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stream.writeInt32(messages.get(a)); - } - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - - public static class TL_updateReadHistoryOutbox extends Update { - public static int constructor = 0x2f2f21bf; - - public Peer peer; - - public void readParams(AbstractSerializedData stream, boolean exception) { - peer = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - max_id = stream.readInt32(exception); - pts = stream.readInt32(exception); - pts_count = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - peer.serializeToStream(stream); - stream.writeInt32(max_id); - stream.writeInt32(pts); - stream.writeInt32(pts_count); - } - } - public static class InputEncryptedFile extends TLObject { public long id; public long access_hash; @@ -3282,26 +2812,6 @@ public class TLRPC { } } - public static class TL_inputEncryptedFileUploaded extends InputEncryptedFile { - public static int constructor = 0x64bd0306; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - id = stream.readInt64(exception); - parts = stream.readInt32(exception); - md5_checksum = stream.readString(exception); - key_fingerprint = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(id); - stream.writeInt32(parts); - stream.writeString(md5_checksum); - stream.writeInt32(key_fingerprint); - } - } - public static class messages_AllStickers extends TLObject { public String hash; public ArrayList sets = new ArrayList<>(); @@ -3314,41 +2824,6 @@ public class TLRPC { } } - public static class TL_messages_allStickers extends messages_AllStickers { - public static int constructor = 0xedfd405f; - - public int hash; - - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - StickerSet object = StickerSet.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - sets.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - stream.writeInt32(0x1cb5c415); - int count = sets.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - sets.get(a).serializeToStream(stream); - } - } - } public static class DecryptedMessageAction extends TLObject { public int ttl_seconds; @@ -3418,28 +2893,6 @@ public class TLRPC { } } - public static class TL_account_password extends account_Password { - public static int constructor = 0x7c18141c; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - current_salt = stream.readByteArray(exception); - new_salt = stream.readByteArray(exception); - hint = stream.readString(exception); - has_recovery = stream.readBool(exception); - email_unconfirmed_pattern = stream.readString(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeByteArray(current_salt); - stream.writeByteArray(new_salt); - stream.writeString(hint); - stream.writeBool(has_recovery); - stream.writeString(email_unconfirmed_pattern); - } - } - public static class UserProfilePhoto extends TLObject { public long photo_id; public FileLocation photo_small; @@ -3460,23 +2913,6 @@ public class TLRPC { } } - public static class TL_userProfilePhoto extends UserProfilePhoto { - public static int constructor = 0xd559d8c8; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - photo_id = stream.readInt64(exception); - photo_small = FileLocation.TLdeserialize(stream, stream.readInt32(exception), exception); - photo_big = FileLocation.TLdeserialize(stream, stream.readInt32(exception), exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(photo_id); - photo_small.serializeToStream(stream); - photo_big.serializeToStream(stream); - } - } public static class MessageEntity extends TLObject { public int offset; @@ -3954,80 +3390,6 @@ public class TLRPC { } } - public static class TL_contacts_topPeers extends contacts_TopPeers { - public static int constructor = 0x70b772a8; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - TL_topPeerCategoryPeers object = TL_topPeerCategoryPeers.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - categories.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Chat object = Chat.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - chats.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - User object = User.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - users.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = categories.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - categories.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = chats.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - chats.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - } - } public static class InputChannel extends TLObject { public int channel_id; @@ -4136,97 +3498,6 @@ public class TLRPC { } } - public static class TL_contacts_found extends TLObject { - public static int constructor = 0x1aa1f784; - - public ArrayList results = new ArrayList<>(); - public ArrayList chats = new ArrayList<>(); - public ArrayList users = new ArrayList<>(); - - public static TL_contacts_found TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_contacts_found.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_contacts_found", constructor)); - } else { - return null; - } - } - TL_contacts_found result = new TL_contacts_found(); - result.readParams(stream, exception); - return result; - } - - public void readParams(AbstractSerializedData stream, boolean exception) { - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Peer object = Peer.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - results.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Chat object = Chat.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - chats.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - User object = User.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - users.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = results.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - results.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = chats.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - chats.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - } - } - public static class ChatParticipants extends TLObject { public int flags; public int chat_id; @@ -4596,14 +3867,6 @@ public class TLRPC { } } - public static class storage_FileType extends TLObject { - - public static storage_FileType TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - storage_FileType result = null; - return result; - } - } - public static class auth_CodeType extends TLObject { public static auth_CodeType TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { @@ -4820,41 +4083,6 @@ public class TLRPC { } } - public static class TL_messages_savedGifs extends messages_SavedGifs { - public static int constructor = 0x2e0709a5; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - hash = stream.readInt32(exception); - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Document object = Document.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - gifs.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - stream.writeInt32(0x1cb5c415); - int count = gifs.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - gifs.get(a).serializeToStream(stream); - } - } - } - public static class PhotoSize extends TLObject { public String type; public FileLocation location; @@ -4869,7 +4097,10 @@ public class TLRPC { } } - public static class TL_photoSize extends PhotoSize { + public static class TL_photoSizeEmpty extends PhotoSize { // used as an indicator via instanceof + } + + public static class TL_photoSize extends PhotoSize { public static int constructor = 0x77bfb61b; @@ -4891,33 +4122,6 @@ public class TLRPC { } } - public static class TL_photoSizeEmpty extends PhotoSize { - public static int constructor = 0xe17e23c; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - int startReadPosiition = stream.getPosition(); //TODO remove this hack after some time - try { - type = stream.readString(true); - if (type.length() > 1 || !type.equals("") && !type.equals("s") && !type.equals("x") && !type.equals("m") && !type.equals("y") && !type.equals("w")) { - type = "s"; - if (stream instanceof NativeByteBuffer) { - ((NativeByteBuffer) stream).position(startReadPosiition); - } - } - } catch (Exception e) { - type = "s"; - if (stream instanceof NativeByteBuffer) { - ((NativeByteBuffer) stream).position(startReadPosiition); - } - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(type); - } - } public static class TL_photoCachedSize extends PhotoSize { public static int constructor = 0xe9a734fa; @@ -4985,44 +4189,6 @@ public class TLRPC { } } - public static class TL_inputFileBig extends InputFile { - public static int constructor = 0xfa4f0bb5; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - id = stream.readInt64(exception); - parts = stream.readInt32(exception); - name = stream.readString(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(id); - stream.writeInt32(parts); - stream.writeString(name); - } - } - - public static class TL_inputFile extends InputFile { - public static int constructor = 0xf52ff27f; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - id = stream.readInt64(exception); - parts = stream.readInt32(exception); - name = stream.readString(exception); - md5_checksum = stream.readString(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(id); - stream.writeInt32(parts); - stream.writeString(name); - stream.writeString(md5_checksum); - } - } - public static class Updates extends TLObject { public ArrayList updates = new ArrayList<>(); public ArrayList users = new ArrayList<>(); @@ -5541,34 +4707,6 @@ public class TLRPC { } } - public static class TL_accountDaysTTL extends TLObject { - public static int constructor = 0xb8d0afdf; - - public int days; - - public static TL_accountDaysTTL TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_accountDaysTTL.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_accountDaysTTL", constructor)); - } else { - return null; - } - } - TL_accountDaysTTL result = new TL_accountDaysTTL(); - result.readParams(stream, exception); - return result; - } - - public void readParams(AbstractSerializedData stream, boolean exception) { - days = stream.readInt32(exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(days); - } - } - public static class InputPeer extends TLObject { public int user_id; public long access_hash; @@ -5786,129 +4924,6 @@ public class TLRPC { } } - public static class TL_messages_dialogs extends messages_Dialogs { - public static int constructor = 0x15ba6c40; - - - public void readParams(AbstractSerializedData stream, boolean exception) { - int magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - int count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - TL_dialog object = TL_dialog.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - dialogs.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Message object = Message.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - messages.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - Chat object = Chat.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - chats.add(object); - } - magic = stream.readInt32(exception); - if (magic != 0x1cb5c415) { - if (exception) { - throw new RuntimeException(String.format("wrong Vector magic, got %x", magic)); - } - return; - } - count = stream.readInt32(exception); - for (int a = 0; a < count; a++) { - User object = User.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return; - } - users.add(object); - } - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = dialogs.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - dialogs.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = messages.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - messages.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = chats.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - chats.get(a).serializeToStream(stream); - } - stream.writeInt32(0x1cb5c415); - count = users.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - users.get(a).serializeToStream(stream); - } - } - } - - public static class TL_auth_sendCode extends TLObject { - public static int constructor = 0x86aef0ec; - - public int flags; - public boolean allow_flashcall; - public String phone_number; - public boolean current_number; - public int api_id; - public String api_hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_auth_sentCode.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - flags = allow_flashcall ? (flags | 1) : (flags &~ 1); - stream.writeInt32(flags); - stream.writeString(phone_number); - if ((flags & 1) != 0) { - stream.writeBool(current_number); - } - stream.writeInt32(api_id); - stream.writeString(api_hash); - } - } - public static class TL_auth_signUp extends TLObject { public static int constructor = 0x1b067634; @@ -5932,38 +4947,6 @@ public class TLRPC { } } - public static class TL_auth_signIn extends TLObject { - public static int constructor = 0xbcd51581; - - public String phone_number; - public String phone_code_hash; - public String phone_code; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_auth_authorization.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(phone_number); - stream.writeString(phone_code_hash); - stream.writeString(phone_code); - } - } - - public static class TL_account_resetNotifySettings extends TLObject { - public static int constructor = 0xdb7e1747; - - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - public static class TL_account_updateStatus extends TLObject { public static int constructor = 0x6628562c; @@ -5979,43 +4962,6 @@ public class TLRPC { } } - public static class TL_contacts_getStatuses extends TLObject { - public static int constructor = 0xc4a353ee; - - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - Vector vector = new Vector(); - int size = stream.readInt32(exception); - for (int a = 0; a < size; a++) { - TL_contactStatus object = TL_contactStatus.TLdeserialize(stream, stream.readInt32(exception), exception); - if (object == null) { - return vector; - } - vector.objects.add(object); - } - return vector; - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - - public static class TL_contacts_getContacts extends TLObject { - public static int constructor = 0x22c6aa08; - - public String hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return contacts_Contacts.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(hash); - } - } - public static class TL_contacts_importContacts extends TLObject { public static int constructor = 0xda30b32d; @@ -6284,50 +5230,6 @@ public class TLRPC { } } - public static class TL_photos_deletePhotos extends TLObject { - public static int constructor = 0x87cf7f2f; - - public ArrayList id = new ArrayList<>(); - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - Vector vector = new Vector(); - int size = stream.readInt32(exception); - for (int a = 0; a < size; a++) { - vector.objects.add(stream.readInt64(exception)); - } - return vector; - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(0x1cb5c415); - int count = id.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - id.get(a).serializeToStream(stream); - } - } - } - - public static class TL_upload_getFile extends TLObject { - public static int constructor = 0xe3a6cfb5; - - public InputFileLocation location; - public int offset; - public int limit; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_upload_file.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - location.serializeToStream(stream); - stream.writeInt32(offset); - stream.writeInt32(limit); - } - } - public static class TL_photos_getUserPhotos extends TLObject { public static int constructor = 0x91cd32a8; @@ -6349,66 +5251,6 @@ public class TLRPC { } } - public static class TL_contacts_search extends TLObject { - public static int constructor = 0x11f812d8; - - public String q; - public int limit; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_contacts_found.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(q); - stream.writeInt32(limit); - } - } - - public static class TL_account_getPrivacy extends TLObject { - public static int constructor = 0xdadbc950; - - public InputPrivacyKey key; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_account_privacyRules.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - key.serializeToStream(stream); - } - } - - public static class TL_account_deleteAccount extends TLObject { - public static int constructor = 0x418d4e0b; - - public String reason; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(reason); - } - } - - public static class TL_account_getAccountTTL extends TLObject { - public static int constructor = 0x8fc711d; - - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_accountDaysTTL.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - public static class TL_contacts_resolveUsername extends TLObject { public static int constructor = 0xf93ccba3; @@ -6424,174 +5266,6 @@ public class TLRPC { } } - public static class TL_contacts_getTopPeers extends TLObject { - public static int constructor = 0xd4982db5; - - public int flags; - public boolean correspondents; - public boolean bots_pm; - public boolean bots_inline; - public boolean groups; - public boolean channels; - public int offset; - public int limit; - public int hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return contacts_TopPeers.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - flags = correspondents ? (flags | 1) : (flags &~ 1); - flags = bots_pm ? (flags | 2) : (flags &~ 2); - flags = bots_inline ? (flags | 4) : (flags &~ 4); - flags = groups ? (flags | 1024) : (flags &~ 1024); - flags = channels ? (flags | 32768) : (flags &~ 32768); - stream.writeInt32(flags); - stream.writeInt32(offset); - stream.writeInt32(limit); - stream.writeInt32(hash); - } - } - - public static class TL_contacts_resetTopPeerRating extends TLObject { - public static int constructor = 0x1ae373ac; - - public TopPeerCategory category; - public InputPeer peer; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - category.serializeToStream(stream); - peer.serializeToStream(stream); - } - } - - public static class TL_messages_getAllStickers extends TLObject { - public static int constructor = 0x1c9618b1; - - public int hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_AllStickers.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - } - } - - public static class TL_messages_getWebPagePreview extends TLObject { - public static int constructor = 0x25223e24; - - public String message; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return MessageMedia.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(message); - } - } - - public static class TL_account_getPassword extends TLObject { - public static int constructor = 0x548a30f5; - - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return account_Password.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - - public static class TL_auth_checkPassword extends TLObject { - public static int constructor = 0xa63011e; - - public byte[] password_hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_auth_authorization.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeByteArray(password_hash); - } - } - - public static class TL_auth_requestPasswordRecovery extends TLObject { - public static int constructor = 0xd897bc66; - - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_auth_passwordRecovery.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - } - } - - public static class TL_auth_recoverPassword extends TLObject { - public static int constructor = 0x4ea56e92; - - public String code; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_auth_authorization.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(code); - } - } - - public static class TL_auth_resendCode extends TLObject { - public static int constructor = 0x3ef1a9bf; - - public String phone_number; - public String phone_code_hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_auth_sentCode.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(phone_number); - stream.writeString(phone_code_hash); - } - } - - public static class TL_auth_cancelCode extends TLObject { - public static int constructor = 0x1f040578; - - public String phone_number; - public String phone_code_hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeString(phone_number); - stream.writeString(phone_code_hash); - } - } - public static class TL_messages_checkChatInvite extends TLObject { public static int constructor = 0x3eadb1bb; @@ -6622,117 +5296,6 @@ public class TLRPC { } } - public static class TL_messages_getStickerSet extends TLObject { - public static int constructor = 0x2619a90e; - - public InputStickerSet stickerset; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return TL_messages_stickerSet.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stickerset.serializeToStream(stream); - } - } - - public static class TL_messages_installStickerSet extends TLObject { - public static int constructor = 0x7b30c3a6; - - public InputStickerSet stickerset; - public boolean disabled; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stickerset.serializeToStream(stream); - stream.writeBool(disabled); - } - } - - public static class TL_messages_uninstallStickerSet extends TLObject { - public static int constructor = 0xf96e55de; - - public InputStickerSet stickerset; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stickerset.serializeToStream(stream); - } - } - - public static class TL_messages_getMessagesViews extends TLObject { - public static int constructor = 0xc4c8a55d; - - public InputPeer peer; - public ArrayList id = new ArrayList<>(); - public boolean increment; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - Vector vector = new Vector(); - int size = stream.readInt32(exception); - for (int a = 0; a < size; a++) { - vector.objects.add(stream.readInt32(exception)); - } - return vector; - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - peer.serializeToStream(stream); - stream.writeInt32(0x1cb5c415); - int count = id.size(); - stream.writeInt32(count); - for (int a = 0; a < count; a++) { - stream.writeInt32(id.get(a)); - } - stream.writeBool(increment); - } - } - - public static class TL_messages_getSavedGifs extends TLObject { - public static int constructor = 0x83bf3d52; - - public int hash; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return messages_SavedGifs.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt32(hash); - } - } - - public static class TL_messages_saveGif extends TLObject { - public static int constructor = 0x327a30cb; - - public InputDocument id; - public boolean unsave; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - id.serializeToStream(stream); - stream.writeBool(unsave); - } - } - - //manually created - - //MessageMedia start public static class MessageMedia extends TLObject { public byte[] bytes; public Audio audio_unused; @@ -7219,107 +5782,6 @@ public class TLRPC { } //Chat end - //functions memory optimize - public static class TL_upload_saveFilePart extends TLObject { - public static int constructor = 0xb304a621; - - public long file_id; - public int file_part; - public NativeByteBuffer bytes; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(file_id); - stream.writeInt32(file_part); - stream.writeByteBuffer(bytes); - } - - @Override - public void freeResources() { - if (disableFree) { - return; - } - if (bytes != null) { - bytes.reuse(); - bytes = null; - } - } - } - - public static class TL_upload_saveBigFilePart extends TLObject { - public static int constructor = 0xde7b673d; - - public long file_id; - public int file_part; - public int file_total_parts; - public NativeByteBuffer bytes; - - public TLObject deserializeResponse(AbstractSerializedData stream, int constructor, boolean exception) { - return Bool.TLdeserialize(stream, constructor, exception); - } - - public void serializeToStream(AbstractSerializedData stream) { - stream.writeInt32(constructor); - stream.writeInt64(file_id); - stream.writeInt32(file_part); - stream.writeInt32(file_total_parts); - stream.writeByteBuffer(bytes); - } - - @Override - public void freeResources() { - if (disableFree) { - return; - } - if (bytes != null) { - bytes.reuse(); - bytes = null; - } - } - } - - public static class TL_upload_file extends TLObject { - public static int constructor = 0x96a18d5; - - public storage_FileType type; - public int mtime; - public NativeByteBuffer bytes; - - public static TL_upload_file TLdeserialize(AbstractSerializedData stream, int constructor, boolean exception) { - if (TL_upload_file.constructor != constructor) { - if (exception) { - throw new RuntimeException(String.format("can't parse magic %x in TL_upload_file", constructor)); - } else { - return null; - } - } - TL_upload_file result = new TL_upload_file(); - result.readParams(stream, exception); - return result; - } - - public void readParams(AbstractSerializedData stream, boolean exception) { - type = storage_FileType.TLdeserialize(stream, stream.readInt32(exception), exception); - mtime = stream.readInt32(exception); - bytes = stream.readByteBuffer(exception); - } - - @Override - public void freeResources() { - if (disableFree) { - return; - } - if (bytes != null) { - bytes.reuse(); - bytes = null; - } - } - } - //functions public static class Vector extends TLObject { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseSearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseSearchAdapter.java index e11d5fd52..9e8542f49 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseSearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseSearchAdapter.java @@ -49,11 +49,12 @@ public class BaseSearchAdapter extends BaseFragmentAdapter { notifyDataSetChanged(); return; } - TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search(); + /*TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search(); req.q = query; - req.limit = 50; - final int currentReqId = ++lastReqId; - reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + req.limit = 50;*/ + /*final int currentReqId =*/ + ++lastReqId; + reqId = 0; /* ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -82,7 +83,7 @@ public class BaseSearchAdapter extends BaseFragmentAdapter { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors);*/ } /* diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseSearchAdapterRecycler.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseSearchAdapterRecycler.java index 45dad6c81..b3bde720f 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseSearchAdapterRecycler.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/BaseSearchAdapterRecycler.java @@ -50,11 +50,11 @@ public abstract class BaseSearchAdapterRecycler extends RecyclerView.Adapter { notifyDataSetChanged(); return; } - TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search(); + /*TLRPC.TL_contacts_search req = new TLRPC.TL_contacts_search(); req.q = query; - req.limit = 50; - final int currentReqId = ++lastReqId; - reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + req.limit = 50;*/ + /*final int currentReqId =*/ ++lastReqId; + reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -80,7 +80,7 @@ public abstract class BaseSearchAdapterRecycler extends RecyclerView.Adapter { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors);*/ } public void loadRecentHashtags() { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java index c4035bd23..026f5a6d0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Adapters/DialogsSearchAdapter.java @@ -9,13 +9,11 @@ package org.telegram.ui.Adapters; import android.content.Context; -import android.text.TextUtils; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import org.telegram.messenger.AndroidUtilities; -import org.telegram.messenger.ChatObject; import org.telegram.messenger.ContactsController; import org.telegram.messenger.LocaleController; import org.telegram.messenger.MessageObject; @@ -26,8 +24,6 @@ import org.telegram.messenger.support.widget.RecyclerView; import org.telegram.messenger.FileLog; import org.telegram.messenger.R; import org.telegram.tgnet.ConnectionsManager; -import org.telegram.tgnet.NativeByteBuffer; -import org.telegram.tgnet.RequestDelegate; import org.telegram.tgnet.TLObject; import org.telegram.tgnet.TLRPC; import org.telegram.ui.Cells.DialogCell; @@ -39,13 +35,9 @@ import org.telegram.ui.Cells.ProfileSearchCell; import org.telegram.ui.Components.RecyclerListView; import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; import java.util.HashMap; -import java.util.Locale; import java.util.Timer; import java.util.TimerTask; -import java.util.concurrent.ConcurrentHashMap; public class DialogsSearchAdapter extends BaseSearchAdapterRecycler { @@ -206,11 +198,11 @@ public class DialogsSearchAdapter extends BaseSearchAdapterRecycler { req.offset_peer = new TLRPC.TL_inputPeerEmpty(); } lastMessagesSearchString = query; - final int currentReqId = ++lastReqId; + /*final int currentReqId =*/ ++lastReqId; if (delegate != null) { delegate.searchStateChanged(true); } - reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + reqId = 0;/*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -248,7 +240,7 @@ public class DialogsSearchAdapter extends BaseSearchAdapterRecycler { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors);*/ } public boolean hasRecentRearch() { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java index 41cf0d4f5..4505af627 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/ChatActivity.java @@ -3122,13 +3122,15 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not textToCheck = charSequence; } + /* final TLRPC.TL_messages_getWebPagePreview req = new TLRPC.TL_messages_getWebPagePreview(); if (textToCheck instanceof String) { req.message = (String) textToCheck; } else { req.message = textToCheck.toString(); } - linkSearchRequestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + */ + linkSearchRequestId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -3156,7 +3158,7 @@ public class ChatActivity extends BaseFragment implements NotificationCenter.Not } }); } - }); + });*/ ConnectionsManager.getInstance().bindRequestToGuid(linkSearchRequestId, classGuid); } }); diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java index e0ca082f1..2849f5ca0 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/EmojiView.java @@ -710,7 +710,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific @Override public void onClick(DialogInterface dialogInterface, int i) { recentImages.remove(searchImage); - TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif(); + /*TLRPC.TL_messages_saveGif req = new TLRPC.TL_messages_saveGif(); req.id = new TLRPC.TL_inputDocument(); req.id.id = searchImage.document.id; req.id.access_hash = searchImage.document.access_hash; @@ -720,7 +720,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific public void run(TLObject response, TLRPC.TL_error error) { } - }); + });*/ //MessagesStorage.getInstance().removeWebRecent(searchImage); if (gifsAdapter != null) { gifsAdapter.notifyDataSetChanged(); @@ -1559,7 +1559,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific return; } loadingRecentGifs = true; - TLRPC.TL_messages_getSavedGifs req = new TLRPC.TL_messages_getSavedGifs(); + /*TLRPC.TL_messages_getSavedGifs req = new TLRPC.TL_messages_getSavedGifs(); req.hash = calcGifsHash(recentImages); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -1600,7 +1600,7 @@ public class EmojiView extends FrameLayout implements NotificationCenter.Notific } }); } - }); + });*/ } @SuppressWarnings("unchecked") diff --git a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickersAlert.java b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickersAlert.java index 0461ec5b4..6efbf7617 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/Components/StickersAlert.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/Components/StickersAlert.java @@ -367,7 +367,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not stickerSet = StickersQuery.getStickerSetById(inputStickerSet.id); } if (stickerSet == null) { - TLRPC.TL_messages_getStickerSet req = new TLRPC.TL_messages_getStickerSet(); + /*TLRPC.TL_messages_getStickerSet req = new TLRPC.TL_messages_getStickerSet(); req.stickerset = inputStickerSet; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -387,7 +387,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not } }); } - }); + });*/ } NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded); updateFields(); @@ -405,7 +405,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not @Override public void onClick(View v) { dismiss(); - TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet(); + /*TLRPC.TL_messages_installStickerSet req = new TLRPC.TL_messages_installStickerSet(); req.stickerset = inputStickerSet; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -430,7 +430,7 @@ public class StickersAlert extends BottomSheet implements NotificationCenter.Not } }); } - }); + });*/ } }, LocaleController.getString("AddStickers", R.string.AddStickers), Theme.STICKERS_SHEET_ADD_TEXT_COLOR, true); } else { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java index 78a595ab5..edb7c4ef8 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LaunchActivity.java @@ -1082,6 +1082,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa int requestId = 0; if (username != null) { + /* TLRPC.TL_contacts_resolveUsername req = new TLRPC.TL_contacts_resolveUsername(); req.username = username; requestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @@ -1102,7 +1103,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa MessagesController.getInstance().putChats(res.chats, false); //MessagesStorage.getInstance().putUsersAndChats(res.users, res.chats, false, true); - /*if (botChat != null) { + if (botChat != null) { final TLRPC.User user = !res.users.isEmpty() ? res.users.get(0) : null; if (user == null || user.bot && user.bot_nochats) { try { @@ -1131,7 +1132,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } }); presentFragment(fragment); - } else */ { + } else { long dialog_id; boolean isBot = false; Bundle args = new Bundle(); @@ -1161,24 +1162,22 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } } } else { - /* try { Toast.makeText(LaunchActivity.this, LocaleController.getString("NoUsernameFound", R.string.NoUsernameFound), Toast.LENGTH_SHORT).show(); } catch (Exception e) { FileLog.e("tmessages", e); } - */ } } } }); } - }); + }); */ } else if (group != null) { if (state == 0) { final TLRPC.TL_messages_checkChatInvite req = new TLRPC.TL_messages_checkChatInvite(); req.hash = group; - requestId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + requestId = 0; /* ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -1236,10 +1235,11 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors); */ } else if (state == 1) { TLRPC.TL_messages_importChatInvite req = new TLRPC.TL_messages_importChatInvite(); req.hash = group; + /* ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { @@ -1291,7 +1291,7 @@ public class LaunchActivity extends Activity implements ActionBarLayout.ActionBa } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors); */ } } else if (sticker != null) { if (!mainFragmentsStack.isEmpty()) { diff --git a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java index 817fe0005..66267f1cc 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/LoginActivity.java @@ -1223,7 +1223,7 @@ public class LoginActivity extends BaseFragment { wrongNumber.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { - TLRPC.TL_auth_cancelCode req = new TLRPC.TL_auth_cancelCode(); + /*TLRPC.TL_auth_cancelCode req = new TLRPC.TL_auth_cancelCode(); req.phone_number = requestPhone; req.phone_code_hash = phoneHash; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @@ -1231,7 +1231,7 @@ public class LoginActivity extends BaseFragment { public void run(TLObject response, TLRPC.TL_error error) { } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); + }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/ onBackPressed(); setPage(0, true, null, true); } @@ -1247,7 +1247,7 @@ public class LoginActivity extends BaseFragment { nextPressed = true; needShowProgress(); - TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode(); + /*TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode(); req.phone_number = requestPhone; req.phone_code_hash = phoneHash; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @@ -1280,7 +1280,7 @@ public class LoginActivity extends BaseFragment { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); + }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/ } @Override @@ -1463,7 +1463,7 @@ public class LoginActivity extends BaseFragment { if (nextType == 4) { timeText.setText(LocaleController.getString("Calling", R.string.Calling)); createCodeTimer(); - TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode(); + /*TLRPC.TL_auth_resendCode req = new TLRPC.TL_auth_resendCode(); req.phone_number = requestPhone; req.phone_code_hash = phoneHash; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @@ -1478,7 +1478,7 @@ public class LoginActivity extends BaseFragment { }); } } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); + }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/ } else if (nextType == 3) { AndroidUtilities.setWaitingForSms(false); NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveSmsCode); @@ -1521,13 +1521,13 @@ public class LoginActivity extends BaseFragment { NotificationCenter.getInstance().removeObserver(this, NotificationCenter.didReceiveCall); } waitingForEvent = false; - final TLRPC.TL_auth_signIn req = new TLRPC.TL_auth_signIn(); + /*final TLRPC.TL_auth_signIn req = new TLRPC.TL_auth_signIn(); req.phone_number = requestPhone; req.phone_code = codeField.getText().toString(); - req.phone_code_hash = phoneHash; + req.phone_code_hash = phoneHash;*/ destroyTimer(); needShowProgress(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -1626,7 +1626,7 @@ public class LoginActivity extends BaseFragment { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); + }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/ } @Override @@ -1874,7 +1874,7 @@ public class LoginActivity extends BaseFragment { @Override public void onClick(DialogInterface dialogInterface, int i) { needShowProgress(); - TLRPC.TL_account_deleteAccount req = new TLRPC.TL_account_deleteAccount(); + /*TLRPC.TL_account_deleteAccount req = new TLRPC.TL_account_deleteAccount(); req.reason = "Forgot password"; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -1895,7 +1895,7 @@ public class LoginActivity extends BaseFragment { } }); } - }, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors);*/ } }); builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null); @@ -1991,7 +1991,7 @@ public class LoginActivity extends BaseFragment { System.arraycopy(oldPasswordBytes, 0, hash, current_salt.length, oldPasswordBytes.length); System.arraycopy(current_salt, 0, hash, hash.length - current_salt.length, current_salt.length); - final TLRPC.TL_auth_checkPassword req = new TLRPC.TL_auth_checkPassword(); + /*final TLRPC.TL_auth_checkPassword req = new TLRPC.TL_auth_checkPassword(); req.password_hash = Utilities.computeSHA256(hash, 0, hash.length); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -2035,7 +2035,7 @@ public class LoginActivity extends BaseFragment { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); + }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/ } @Override @@ -2216,7 +2216,7 @@ public class LoginActivity extends BaseFragment { return; } needShowProgress(); - TLRPC.TL_auth_recoverPassword req = new TLRPC.TL_auth_recoverPassword(); + /*TLRPC.TL_auth_recoverPassword req = new TLRPC.TL_auth_recoverPassword(); req.code = code; ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override @@ -2260,7 +2260,7 @@ public class LoginActivity extends BaseFragment { } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin); + }, ConnectionsManager.RequestFlagFailOnServerErrors | ConnectionsManager.RequestFlagWithoutLogin);*/ } @Override @@ -2431,7 +2431,7 @@ public class LoginActivity extends BaseFragment { req.first_name = firstNameField.getText().toString(); req.last_name = lastNameField.getText().toString(); needShowProgress(); - ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(final TLObject response, final TLRPC.TL_error error) { AndroidUtilities.runOnUIThread(new Runnable() { @@ -2473,7 +2473,7 @@ public class LoginActivity extends BaseFragment { } }); } - }, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagWithoutLogin | ConnectionsManager.RequestFlagFailOnServerErrors);*/ } @Override diff --git a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java index c072266f1..2df95f54b 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/MediaActivity.java @@ -1563,7 +1563,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No return; } final int currentReqId = ++lastReqId; - reqId = ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { + reqId = 0; /*ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { final ArrayList messageObjects = new ArrayList<>(); @@ -1588,7 +1588,7 @@ public class MediaActivity extends BaseFragment implements NotificationCenter.No } }); } - }, ConnectionsManager.RequestFlagFailOnServerErrors); + }, ConnectionsManager.RequestFlagFailOnServerErrors);*/ ConnectionsManager.getInstance().bindRequestToGuid(reqId, classGuid); } diff --git a/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java b/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java index 0614884f1..002192f3d 100644 --- a/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java +++ b/TMessagesProj/src/main/java/org/telegram/ui/NotificationsSettingsActivity.java @@ -259,7 +259,7 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif return; } reseting = true; - TLRPC.TL_account_resetNotifySettings req = new TLRPC.TL_account_resetNotifySettings(); + /*TLRPC.TL_account_resetNotifySettings req = new TLRPC.TL_account_resetNotifySettings(); ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() { @Override public void run(TLObject response, TLRPC.TL_error error) { @@ -282,7 +282,7 @@ public class NotificationsSettingsActivity extends BaseFragment implements Notif } }); } - }); + });*/ } else if (i == inappSoundRow) { SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit();