| 6 |
| * Copyright Nikolai Kudashov, 2015-2018. |
| 7 | */ |
| 8 |
| 9 | #ifndef CONNECTIONSMANAGER_H |
| 10 | #define CONNECTIONSMANAGER_H |
| 11 |
| 12 | #include <pthread.h> |
| 13 | #include <queue> |
| 14 | #include <functional> |
| 15 | #include <sys/epoll.h> |
| 16 | #include <map> |
| 17 | #include <atomic> |
| 18 | #include <unordered_set> |
| 19 | #include "Defines.h" |
| 20 |
| 21 | #ifdef ANDROID |
| 22 | #include <jni.h> |
| 23 | #endif |
| 24 |
| 25 | class NativeByteBuffer; |
| 26 | class Connection; |
| 27 | class Datacenter; |
| 28 | class Request; |
| 29 | class DatacenterHandshake; |
| 30 | class TLObject; |
| 31 | class ConnectionSocket; |
| 32 | class TL_auth_exportedAuthorization; |
| 33 | class ByteArray; |
| 34 | class TL_config; |
| 35 | class EventObject; |
| 36 | class Config; |
| 37 | class ProxyCheckInfo; |
| 38 |
| 39 | class ConnectionsManager { |
| 40 |
| 41 | public: |
| 42 | ConnectionsManager(int32_t instance); |
| 43 | ~ConnectionsManager(); |
| 44 |
| 45 | static ConnectionsManager &getInstance(int32_t instanceNum); |
| 46 | int64_t getCurrentTimeMillis(); |
| 47 | int64_t getCurrentTimeMonotonicMillis(); |
| 48 | int32_t getCurrentTime(); |
| 49 | int32_t getCurrentPingTime(); |
| 50 | uint32_t getCurrentDatacenterId(); |
| 51 | int64_t getCurrentAuthKeyId(); |
| 52 | bool isTestBackend(); |
| 53 | int32_t getTimeDifference(); |
| 54 | int32_t sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate); |
| 55 | int32_t sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate, int32_t requestToken); |
| 56 | void cancelRequest(int32_t token, bool notifyServer, onRequestCancelDoneFunc onCancelled); |
| 57 | void cleanUp(bool resetKeys, int32_t datacenterId); |
| 58 | void cancelRequestsForGuid(int32_t guid); |
| 59 | void bindRequestToGuid(int32_t requestToken, int32_t guid); |
| 60 | void applyDatacenterAddress(uint32_t datacenterId, std::string ipAddress, uint32_t port); |
| 61 | void setDelegate(ConnectiosManagerDelegate *connectiosManagerDelegate); |
| 62 | ConnectionState getConnectionState(); |
| 63 | void setUserId(int64_t userId); |
| 64 | void setUserPremium(bool premium); |
| 65 | void switchBackend(bool restart); |
| 66 | void resumeNetwork(bool partial); |
| 67 | void pauseNetwork(); |
| 68 | void setNetworkAvailable(bool value, int32_t type, bool slow); |
| 69 | void setIpStrategy(uint8_t value); |
| 70 | 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 systemLangCode, std::string configPath, std::string logPath, std::string regId, std::string cFingerprint, std::string installerId, std::string packageId, int32_t timezoneOffset, int64_t userId, bool userPremium, bool isPaused, bool enablePushConnection, bool hasNetwork, int32_t networkType, int32_t performanceClass); |
| 71 | void setProxySettings(std::string address, uint16_t port, std::string username, std::string password, std::string secret); |
| 72 | void setLangCode(std::string langCode); |
| 73 | void setRegId(std::string regId); |
| 74 | void setSystemLangCode(std::string langCode); |
| 75 | void updateDcSettings(uint32_t datacenterId, bool workaround, bool ifLoadingTryAgain); |
| 76 | void setPushConnectionEnabled(bool value); |
| 77 | void applyDnsConfig(NativeByteBuffer *buffer, std::string phone, int32_t date); |
| 78 | int64_t checkProxy(std::string address, uint16_t port, std::string username, std::string password, std::string secret, onRequestTimeFunc requestTimeFunc, jobject ptr1); |
| 79 |
| 80 | #ifdef ANDROID |
| 81 | void sendRequest(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onWriteToSocketFunc onWriteToSocket, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connectionType, bool immediate, int32_t requestToken); |
| 82 | static void useJavaVM(JavaVM *vm, bool useJavaByteBuffers); |
| 83 | #endif |
| 84 |
| 85 | void reconnect(int32_t datacentrId, int32_t connectionType); |
| 86 | void failNotRunningRequest(int32_t token); |
| 87 | void receivedIntegrityCheckClassic(int32_t requestToken, std::string nonce, std::string token); |
| 88 | void receivedCaptchaResult(int32_t requestTokensCount, int32_t* requestTokens, std::string token); |
| 89 | void moveToDatacenter(uint32_t datacenterId); |
| 90 |
| 91 | private: |
| 92 | static void *ThreadProc(void *data); |
| 93 |
| 94 | void initDatacenters(); |
| 95 | void loadConfig(); |
| 96 | void saveConfig(); |
| 97 | void saveConfigInternal(NativeByteBuffer *buffer); |
| 98 | void select(); |
| 99 | void wakeup(); |
| 100 | void processServerResponse(TLObject *message, int64_t messageId, int32_t messageSeqNo, int64_t messageSalt, Connection *connection, int64_t innerMsgId, int64_t containerMessageId); |
| 101 | void sendPing(Datacenter *datacenter, bool usePushConnection); |
| 102 | void sendMessagesToConnection(std::vector<std::unique_ptr<NetworkMessage>> &messages, Connection *connection, bool reportAck); |
| 103 | void sendMessagesToConnectionWithConfirmation(std::vector<std::unique_ptr<NetworkMessage>> &messages, Connection *connection, bool reportAck); |
| 104 | void requestSaltsForDatacenter(Datacenter *datacenter, bool media, bool useTempConnection); |
| 105 | void clearRequestsForDatacenter(Datacenter *datacenter, HandshakeType type); |
| 106 | void registerForInternalPushUpdates(); |
| 107 | void processRequestQueue(uint32_t connectionType, uint32_t datacenterId); |
| 108 | void authorizeOnMovingDatacenter(); |
| 109 | void authorizedOnMovingDatacenter(); |
| 110 | Datacenter *getDatacenterWithId(uint32_t datacenterId); |
| 111 | std::unique_ptr<TLObject> wrapInLayer(TLObject *object, Datacenter *datacenter, Request *baseRequest); |
| 112 | void removeRequestFromGuid(int32_t requestToken); |
| 113 | bool cancelRequestInternal(int32_t token, int64_t messageId, bool notifyServer, bool removeFromClass, onRequestCancelDoneFunc onCancelled); |
| 114 | int callEvents(int64_t now); |
| 115 | int32_t sendRequestInternal(TLObject *object, onCompleteFunc onComplete, onQuickAckFunc onQuickAck, onRequestClearFunc onClear, uint32_t flags, uint32_t datacenterId, ConnectionType connetionType, bool immediate); |
| 116 |
| 117 | void checkPendingTasks(); |
| 118 | void scheduleTask(std::function<void()> task); |
| 119 | void scheduleEvent(EventObject *eventObject, uint32_t time); |
| 120 | void removeEvent(EventObject *eventObject); |
| 121 | void onConnectionClosed(Connection *connection, int reason); |
| 122 | void onConnectionConnected(Connection *connection); |
| 123 | void onConnectionQuickAckReceived(Connection *connection, int32_t ack); |
| 124 | void onConnectionDataReceived(Connection *connection, NativeByteBuffer *data, uint32_t length); |
| 125 | bool hasPendingRequestsForConnection(Connection *connection); |
| 126 | void attachConnection(ConnectionSocket *connection); |
| 127 | void detachConnection(ConnectionSocket *connection); |
| 128 | TLObject *TLdeserialize(TLObject *request, uint32_t bytes, NativeByteBuffer *data); |
| 129 | TLObject *getRequestWithMessageId(int64_t messageId); |
| 130 | void onDatacenterHandshakeComplete(Datacenter *datacenter, HandshakeType type, int32_t timeDiff); |
| 131 | void onDatacenterExportAuthorizationComplete(Datacenter *datacenter); |
| 132 | int64_t generateMessageId(); |
| 133 | uint8_t getIpStratagy(); |
| 134 | bool isNetworkAvailable(); |
| 135 |
| 136 | void scheduleCheckProxyInternal(ProxyCheckInfo *proxyCheckInfo); |
| 137 | void checkProxyInternal(ProxyCheckInfo *proxyCheckInfo); |
| 138 |
| 139 | int32_t instanceNum = 0; |
| 140 | uint32_t configVersion = 5; |
| 141 | Config *config = nullptr; |
| 142 |
| 143 | std::list<EventObject *> events; |
| 144 |
| 145 | std::map<uint32_t, Datacenter *> datacenters; |
| 146 | std::map<int32_t, std::vector<std::int32_t>> quickAckIdToRequestIds; |
| 147 | int32_t pingTime; |
| 148 | int64_t pingTimeMs; |
| 149 | bool testBackend = false; |
| 150 | bool clientBlocked = true; |
| 151 | std::string lastInitSystemLangcode = ""; |
| 152 | std::atomic<uint32_t> lastRequestToken{50000000}; |
| 153 | uint32_t currentDatacenterId = 0; |
| 154 | uint32_t movingToDatacenterId = DEFAULT_DATACENTER_ID; |
| 155 | int64_t pushSessionId = 0; |
| 156 | int32_t currentPingTime = 0; |
| 157 | int32_t currentPingTimeLive = 0; |
| 158 | bool registeringForPush = false; |
| 159 | int64_t lastPushPingTime = 0; |
| 160 | int32_t nextPingTimeOffset = 60000 * 3; |
| 161 | int64_t sendingPushPingTime = 0; |
| 162 | bool sendingPushPing = false; |
| 163 | bool sendingPing = false; |
| 164 | bool updatingDcSettings = false; |
| 165 | bool updatingDcSettingsAgain = false; |
| 166 | uint32_t updatingDcSettingsAgainDcNum = 0; |
| 167 | bool updatingDcSettingsWorkaround = false; |
| 168 | int32_t disconnectTimeoutAmount = 0; |
| 169 | bool requestingSecondAddressByTlsHashMismatch = false; |
| 170 | int32_t requestingSecondAddress = 0; |
| 171 | int32_t updatingDcStartTime = 0; |
| 172 | int32_t lastDcUpdateTime = 0; |
| 173 | int64_t lastPingTime = getCurrentTimeMonotonicMillis(); |
| 174 | bool networkPaused = false; |
| 175 | int32_t nextSleepTimeout = CONNECTION_BACKGROUND_KEEP_TIME; |
| 176 | int64_t lastPauseTime = 0; |
| 177 | int64_t lastMonotonicPauseTime = 0; |
| 178 | int32_t lastSystemPauseTime = 0; |
| 179 | ConnectionState connectionState = ConnectionStateConnecting; |
| 180 | std::unique_ptr<ByteArray> movingAuthorization; |
| 181 | std::vector<int64_t> sessionsToDestroy; |
| 182 | int32_t lastDestroySessionRequestTime; |
| 183 | std::map<int32_t, std::vector<int32_t>> requestsByGuids; |
| 184 | std::map<int32_t, int32_t> guidsByRequests; |
| 185 | std::map<int64_t, int64_t> resendRequests; |
| 186 | Datacenter *deserializingDatacenter; |
| 187 |
| 188 | std::string proxyUser = ""; |
| 189 | std::string proxyPassword = ""; |
| 190 | std::string proxyAddress = ""; |
| 191 | std::string proxySecret = ""; |
| 192 | uint16_t proxyPort = 1080; |
| 193 | int32_t lastPingProxyId = 2000000; |
| 194 | std::vector<std::unique_ptr<ProxyCheckInfo>> proxyCheckQueue; |
| 195 | std::vector<std::unique_ptr<ProxyCheckInfo>> proxyActiveChecks; |
| 196 |
| 197 | pthread_t networkThread; |
| 198 | pthread_mutex_t mutex; |
| 199 | std::queue<std::function<void()>> pendingTasks; |
| 200 | struct epoll_event *epollEvents; |
| 201 | timespec timeSpec; |
| 202 | timespec timeSpecMonotonic; |
| 203 | int32_t timeDifference = 0; |
| 204 | int64_t lastOutgoingMessageId = 0; |
| 205 | bool networkAvailable = true; |
| 206 | bool networkSlow = false; |
| 207 | uint8_t ipStrategy = USE_IPV4_ONLY; |
| 208 | bool lastProtocolIsIpv6 = false; |
| 209 | bool lastProtocolUsefullData = false; |
| 210 | std::vector<ConnectionSocket *> activeConnections; |
| 211 | std::vector<ConnectionSocket *> activeConnectionsCopy; |
| 212 | int epolFd; |
| 213 | int eventFd; |
| 214 | int *pipeFd = nullptr; |
| 215 | NativeByteBuffer *networkBuffer; |
| 216 |
| 217 | requestsList waitingLoginRequests; |
| 218 | requestsList requestsQueue; |
| 219 | requestsList runningRequests; |
| 220 | std::vector<uint32_t> requestingSaltsForDc; |
| 221 | std::unordered_set<int32_t> tokensToBeCancelled; |
| 222 | int32_t lastPingId = 0; |
| 223 | int64_t lastInvokeAfterMessageId = 0; |
| 224 |
| 225 | int32_t currentNetworkType = NETWORK_TYPE_WIFI; |
| 226 | uint32_t currentVersion = 1; |
| 227 | int32_t currentLayer = 34; |
| 228 | int32_t currentApiId = 6; |
| 229 | std::string currentDeviceModel; |
| 230 | std::string currentSystemVersion; |
| 231 | std::string currentAppVersion; |
| 232 | std::string currentLangCode; |
| 233 | std::string currentRegId; |
| 234 | std::string certFingerprint; |
| 235 | std::string installer; |
| 236 | std::string package; |
| 237 | int32_t currentDeviceTimezone = 0; |
| 238 | std::string currentSystemLangCode; |
| 239 | std::string currentConfigPath; |
| 240 | std::string currentLogPath; |
| 241 | int64_t currentUserId = 0; |
| 242 | bool currentUserPremium = false; |
| 243 | bool registeredForInternalPush = false; |
| 244 | bool pushConnectionEnabled = true; |
| 245 | int32_t currentPerformanceClass = -1; |
| 246 |
| 247 | std::map<uint32_t, std::vector<std::unique_ptr<NetworkMessage>>> genericMessagesToDatacenters; |
| 248 | std::map<uint32_t, std::vector<std::unique_ptr<NetworkMessage>>> genericMediaMessagesToDatacenters; |
| 249 | std::map<uint32_t, std::vector<std::unique_ptr<NetworkMessage>>> tempMessagesToDatacenters; |
| 250 | std::vector<uint32_t> unknownDatacenterIds; |
| 251 | std::vector<std::pair<Datacenter *, ConnectionType>> neededDatacenters; |
| 252 | std::map<uint32_t, uint32_t> downloadRunningRequestCount; |
| 253 | std::map<uint32_t, uint32_t> downloadCancelRunningRequestCount; |
| 254 | std::vector<Datacenter *> unauthorizedDatacenters; |
| 255 | NativeByteBuffer *sizeCalculator; |
| 256 |
| 257 | ConnectiosManagerDelegate *delegate; |
| 258 |
| 259 | friend class ConnectionSocket; |
| 260 | friend class ConnectionSession; |
| 261 | friend class Connection; |
| 262 | friend class Timer; |
| 263 | friend class Datacenter; |
| 264 | friend class TL_message; |
| 265 | friend class TL_rpc_result; |
| 266 | friend class Config; |
| 267 | friend class FileLog; |
| 268 | friend class Handshake; |
| 269 | }; |
| 270 |
| 271 | #ifdef ANDROID |
| 272 | extern JavaVM *javaVm; |
| 273 | extern JNIEnv *jniEnv[MAX_ACCOUNT_COUNT]; |
| 274 | extern jclass jclass_ByteBuffer; |
| 275 | extern jmethodID jclass_ByteBuffer_allocateDirect; |
| 276 | #endif |
| 277 |
| 278 | #endif |
| 279 |