| 6 |
| * Copyright Nikolai Kudashov, 2015. |
| 7 | */ |
| 8 |
| 9 | #ifndef CONNECTION_H |
| 10 | #define CONNECTION_H |
| 11 |
| 12 | #include <pthread.h> |
| 13 | #include <vector> |
| 14 | #include <string> |
| 15 | #include <openssl/aes.h> |
| 16 | #include "ConnectionSession.h" |
| 17 | #include "ConnectionSocket.h" |
| 18 | #include "Defines.h" |
| 19 |
| 20 | class Datacenter; |
| 21 | class Timer; |
| 22 | class ByteStream; |
| 23 |
| 24 | class Connection : public ConnectionSession, public ConnectionSocket { |
| 25 |
| 26 | public: |
| 27 |
| 28 | Connection(Datacenter *datacenter, ConnectionType type); |
| 29 | ~Connection(); |
| 30 |
| 31 | void connect(); |
| 32 | void suspendConnection(); |
| 33 | void sendData(NativeByteBuffer *buffer, bool reportAck); |
| 34 | uint32_t getConnectionToken(); |
| 35 | ConnectionType getConnectionType(); |
| 36 | Datacenter *getDatacenter(); |
| 37 |
| 38 | protected: |
| 39 |
| 40 | void onReceivedData(NativeByteBuffer *buffer) override; |
| 41 | void onDisconnected(int reason) override; |
| 42 | void onConnected() override; |
| 43 | void reconnect(); |
| 44 |
| 45 | private: |
| 46 |
| 47 | enum TcpConnectionState { |
| 48 | TcpConnectionStageIdle, |
| 49 | TcpConnectionStageConnecting, |
| 50 | TcpConnectionStageReconnecting, |
| 51 | TcpConnectionStageConnected, |
| 52 | TcpConnectionStageSuspended |
| 53 | }; |
| 54 |
| 55 | TcpConnectionState connectionState = TcpConnectionStageIdle; |
| 56 | uint32_t connectionToken = 0; |
| 57 | std::string hostAddress; |
| 58 | uint16_t hostPort; |
| 59 | uint16_t failedConnectionCount; |
| 60 | Datacenter *currentDatacenter; |
| 61 | uint32_t currentAddressFlags; |
| 62 | ConnectionType connectionType; |
| 63 | bool firstPacketSent = false; |
| 64 | NativeByteBuffer *restOfTheData = nullptr; |
| 65 | uint32_t lastPacketLength = 0; |
| 66 | bool hasSomeDataSinceLastConnect = false; |
| 67 | bool isTryingNextPort = false; |
| 68 | bool wasConnected = false; |
| 69 | uint32_t willRetryConnectCount = 5; |
| 70 | Timer *reconnectTimer; |
| 71 |
| 72 | AES_KEY encryptKey; |
| 73 | uint8_t encryptIv[16]; |
| 74 | uint32_t encryptNum; |
| 75 | uint8_t encryptCount[16]; |
| 76 |
| 77 | AES_KEY decryptKey; |
| 78 | uint8_t decryptIv[16]; |
| 79 | uint32_t decryptNum; |
| 80 | uint8_t decryptCount[16]; |
| 81 |
| 82 | friend class ConnectionsManager; |
| 83 | }; |
| 84 |
| 85 | #endif |
| 86 |