ConnectionSocket.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  1. /*
  2. * This is the source code of tgnet library v. 1.1
  3. * It is licensed under GNU GPL v. 2 or later.
  4. * You should have received a copy of the license in this archive (see LICENSE).
  5. *
  6. * Copyright Nikolai Kudashov, 2015-2018.
  7. */
  8. #include <cassert>
  9. #include <unistd.h>
  10. #include <fcntl.h>
  11. #include <cerrno>
  12. #include <sys/socket.h>
  13. #include <memory.h>
  14. #include <netinet/tcp.h>
  15. #include <arpa/inet.h>
  16. #include <netdb.h>
  17. #include <openssl/rand.h>
  18. #include <openssl/hmac.h>
  19. #include <algorithm>
  20. #include <openssl/bn.h>
  21. #include "ByteStream.h"
  22. #include "ConnectionSocket.h"
  23. #include "FileLog.h"
  24. #include "Defines.h"
  25. #include "ConnectionsManager.h"
  26. #include "EventObject.h"
  27. #include "Timer.h"
  28. #include "NativeByteBuffer.h"
  29. #include "BuffersStorage.h"
  30. #include "Connection.h"
  31. #ifndef EPOLLRDHUP
  32. #define EPOLLRDHUP 0x2000
  33. #endif
  34. #define MAX_GREASE 8
  35. static BIGNUM *get_y2(BIGNUM *x, const BIGNUM *mod, BN_CTX *big_num_context) {
  36. // returns y^2 = x^3 + 486662 * x^2 + x
  37. BIGNUM *y = BN_dup(x);
  38. assert(y != NULL);
  39. BIGNUM *coef = BN_new();
  40. BN_set_word(coef, 486662);
  41. BN_mod_add(y, y, coef, mod, big_num_context);
  42. BN_mod_mul(y, y, x, mod, big_num_context);
  43. BN_one(coef);
  44. BN_mod_add(y, y, coef, mod, big_num_context);
  45. BN_mod_mul(y, y, x, mod, big_num_context);
  46. BN_clear_free(coef);
  47. return y;
  48. }
  49. static BIGNUM *get_double_x(BIGNUM *x, const BIGNUM *mod, BN_CTX *big_num_context) {
  50. // returns x_2 =(x^2 - 1)^2/(4*y^2)
  51. BIGNUM *denominator = get_y2(x, mod, big_num_context);
  52. assert(denominator != NULL);
  53. BIGNUM *coef = BN_new();
  54. BN_set_word(coef, 4);
  55. BN_mod_mul(denominator, denominator, coef, mod, big_num_context);
  56. BIGNUM *numerator = BN_new();
  57. assert(numerator != NULL);
  58. BN_mod_mul(numerator, x, x, mod, big_num_context);
  59. BN_one(coef);
  60. BN_mod_sub(numerator, numerator, coef, mod, big_num_context);
  61. BN_mod_mul(numerator, numerator, numerator, mod, big_num_context);
  62. BN_mod_inverse(denominator, denominator, mod, big_num_context);
  63. BN_mod_mul(numerator, numerator, denominator, mod, big_num_context);
  64. BN_clear_free(coef);
  65. BN_clear_free(denominator);
  66. return numerator;
  67. }
  68. static void generate_public_key(unsigned char *key) {
  69. BIGNUM *mod = NULL;
  70. BN_hex2bn(&mod, "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
  71. BIGNUM *pow = NULL;
  72. BN_hex2bn(&pow, "3ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6");
  73. BN_CTX *big_num_context = BN_CTX_new();
  74. assert(big_num_context != NULL);
  75. BIGNUM *x = BN_new();
  76. while (1) {
  77. RAND_bytes(key, 32);
  78. key[31] &= 127;
  79. BN_bin2bn(key, 32, x);
  80. assert(x != NULL);
  81. BN_mod_mul(x, x, x, mod, big_num_context);
  82. BIGNUM *y = get_y2(x, mod, big_num_context);
  83. BIGNUM *r = BN_new();
  84. BN_mod_exp(r, y, pow, mod, big_num_context);
  85. BN_clear_free(y);
  86. if (BN_is_one(r)) {
  87. BN_clear_free(r);
  88. break;
  89. }
  90. BN_clear_free(r);
  91. }
  92. int i;
  93. for (i = 0; i < 3; i++) {
  94. BIGNUM *x2 = get_double_x(x, mod, big_num_context);
  95. BN_clear_free(x);
  96. x = x2;
  97. }
  98. int num_size = BN_num_bytes(x);
  99. assert(num_size <= 32);
  100. memset(key, '\0', 32 - num_size);
  101. BN_bn2bin(x, key + (32 - num_size));
  102. for (i = 0; i < 16; i++) {
  103. unsigned char t = key[i];
  104. key[i] = key[31 - i];
  105. key[31 - i] = t;
  106. }
  107. BN_clear_free(x);
  108. BN_CTX_free(big_num_context);
  109. BN_clear_free(pow);
  110. BN_clear_free(mod);
  111. }
  112. class TlsHello {
  113. public:
  114. TlsHello() {
  115. RAND_bytes(grease, MAX_GREASE);
  116. for (int a = 0; a < MAX_GREASE; a++) {
  117. grease[a] = (uint8_t) ((grease[a] & 0xf0) + 0x0A);
  118. }
  119. for (size_t i = 1; i < MAX_GREASE; i += 2) {
  120. if (grease[i] == grease[i - 1]) {
  121. grease[i] ^= 0x10;
  122. }
  123. }
  124. }
  125. struct Op {
  126. enum class Type {
  127. String, Random, K, Zero, Domain, Grease, BeginScope, EndScope
  128. };
  129. Type type;
  130. size_t length;
  131. int seed;
  132. std::string data;
  133. static Op string(const char str[], size_t len) {
  134. Op res;
  135. res.type = Type::String;
  136. res.data = std::string(str, len);
  137. return res;
  138. }
  139. static Op random(size_t length) {
  140. Op res;
  141. res.type = Type::Random;
  142. res.length = length;
  143. return res;
  144. }
  145. static Op K() {
  146. Op res;
  147. res.type = Type::K;
  148. res.length = 32;
  149. return res;
  150. }
  151. static Op zero(size_t length) {
  152. Op res;
  153. res.type = Type::Zero;
  154. res.length = length;
  155. return res;
  156. }
  157. static Op domain() {
  158. Op res;
  159. res.type = Type::Domain;
  160. return res;
  161. }
  162. static Op grease(int seed) {
  163. Op res;
  164. res.type = Type::Grease;
  165. res.seed = seed;
  166. return res;
  167. }
  168. static Op begin_scope() {
  169. Op res;
  170. res.type = Type::BeginScope;
  171. return res;
  172. }
  173. static Op end_scope() {
  174. Op res;
  175. res.type = Type::EndScope;
  176. return res;
  177. }
  178. };
  179. static const TlsHello &getDefault() {
  180. static TlsHello result = [] {
  181. TlsHello res;
  182. res.ops = {
  183. Op::string("\x16\x03\x01\x02\x00\x01\x00\x01\xfc\x03\x03", 11),
  184. Op::zero(32),
  185. Op::string("\x20", 1),
  186. Op::random(32),
  187. Op::string("\x00\x20", 2),
  188. Op::grease(0),
  189. Op::string("\x13\x01\x13\x02\x13\x03\xc0\x2b\xc0\x2f\xc0\x2c\xc0\x30\xcc\xa9\xcc\xa8\xc0\x13\xc0\x14\x00\x9c"
  190. "\x00\x9d\x00\x2f\x00\x35\x01\x00\x01\x93", 34),
  191. Op::grease(2),
  192. Op::string("\x00\x00\x00\x00", 4),
  193. Op::begin_scope(),
  194. Op::begin_scope(),
  195. Op::string("\x00", 1),
  196. Op::begin_scope(),
  197. Op::domain(),
  198. Op::end_scope(),
  199. Op::end_scope(),
  200. Op::end_scope(),
  201. Op::string("\x00\x17\x00\x00\xff\x01\x00\x01\x00\x00\x0a\x00\x0a\x00\x08", 15),
  202. Op::grease(4),
  203. Op::string(
  204. "\x00\x1d\x00\x17\x00\x18\x00\x0b\x00\x02\x01\x00\x00\x23\x00\x00\x00\x10\x00\x0e\x00\x0c\x02\x68\x32\x08"
  205. "\x68\x74\x74\x70\x2f\x31\x2e\x31\x00\x05\x00\x05\x01\x00\x00\x00\x00\x00\x0d\x00\x12\x00\x10\x04\x03\x08"
  206. "\x04\x04\x01\x05\x03\x08\x05\x05\x01\x08\x06\x06\x01\x00\x12\x00\x00\x00\x33\x00\x2b\x00\x29", 75),
  207. Op::grease(4),
  208. Op::string("\x00\x01\x00\x00\x1d\x00\x20", 7),
  209. Op::K(),
  210. Op::string("\x00\x2d\x00\x02\x01\x01\x00\x2b\x00\x0b\x0a", 11),
  211. Op::grease(6),
  212. Op::string("\x03\x04\x03\x03\x03\x02\x03\x01\x00\x1b\x00\x03\x02\x00\x02", 15),
  213. Op::grease(3),
  214. Op::string("\x00\x01\x00\x00\x15", 5)};
  215. return res;
  216. }();
  217. return result;
  218. }
  219. uint32_t writeToBuffer(uint8_t *data) {
  220. uint32_t offset = 0;
  221. for (auto op : ops) {
  222. writeOp(op, data, offset);
  223. }
  224. return offset;
  225. }
  226. uint32_t writePadding(uint8_t *data, uint32_t length) {
  227. if (length > 515) {
  228. return 0;
  229. }
  230. uint32_t size = 515 - length;
  231. memset(data + length + 2, 0, size);
  232. data[length] = static_cast<uint8_t>((size >> 8) & 0xff);
  233. data[length + 1] = static_cast<uint8_t>(size & 0xff);
  234. return length + size + 2;
  235. }
  236. void setDomain(std::string value) {
  237. domain = std::move(value);
  238. }
  239. private:
  240. std::vector<Op> ops;
  241. uint8_t grease[MAX_GREASE];
  242. std::vector<size_t> scopeOffset;
  243. std::string domain;
  244. void writeOp(const TlsHello::Op &op, uint8_t *data, uint32_t &offset) {
  245. using Type = TlsHello::Op::Type;
  246. switch (op.type) {
  247. case Type::String:
  248. memcpy(data + offset, op.data.data(), op.data.size());
  249. offset += op.data.size();
  250. break;
  251. case Type::Random:
  252. RAND_bytes(data + offset, (size_t) op.length);
  253. offset += op.length;
  254. break;
  255. case Type::K:
  256. generate_public_key(data + offset);
  257. offset += op.length;
  258. break;
  259. case Type::Zero:
  260. std::memset(data + offset, 0, op.length);
  261. offset += op.length;
  262. break;
  263. case Type::Domain: {
  264. size_t size = domain.size();
  265. if (size > 253) {
  266. size = 253;
  267. }
  268. memcpy(data + offset, domain.data(), size);
  269. offset += size;
  270. break;
  271. }
  272. case Type::Grease: {
  273. data[offset] = grease[op.seed];
  274. data[offset + 1] = grease[op.seed];
  275. offset += 2;
  276. break;
  277. }
  278. case Type::BeginScope:
  279. scopeOffset.push_back(offset);
  280. offset += 2;
  281. break;
  282. case Type::EndScope: {
  283. auto begin_offset = scopeOffset.back();
  284. scopeOffset.pop_back();
  285. size_t size = offset - begin_offset - 2;
  286. data[begin_offset] = static_cast<uint8_t>((size >> 8) & 0xff);
  287. data[begin_offset + 1] = static_cast<uint8_t>(size & 0xff);
  288. break;
  289. }
  290. }
  291. }
  292. };
  293. ConnectionSocket::ConnectionSocket(int32_t instance) {
  294. instanceNum = instance;
  295. outgoingByteStream = new ByteStream();
  296. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  297. eventObject = new EventObject(this, EventObjectTypeConnection);
  298. }
  299. ConnectionSocket::~ConnectionSocket() {
  300. if (outgoingByteStream != nullptr) {
  301. delete outgoingByteStream;
  302. outgoingByteStream = nullptr;
  303. }
  304. if (eventObject != nullptr) {
  305. delete eventObject;
  306. eventObject = nullptr;
  307. }
  308. if (tempBuffer != nullptr) {
  309. delete tempBuffer;
  310. tempBuffer = nullptr;
  311. }
  312. if (tlsBuffer != nullptr) {
  313. tlsBuffer->reuse();
  314. tlsBuffer = nullptr;
  315. }
  316. }
  317. void ConnectionSocket::openConnection(std::string address, uint16_t port, std::string secret, bool ipv6, int32_t networkType) {
  318. currentNetworkType = networkType;
  319. isIpv6 = ipv6;
  320. currentAddress = address;
  321. currentPort = port;
  322. waitingForHostResolve = "";
  323. adjustWriteOpAfterResolve = false;
  324. tlsState = 0;
  325. ConnectionsManager::getInstance(instanceNum).attachConnection(this);
  326. memset(&socketAddress, 0, sizeof(sockaddr_in));
  327. memset(&socketAddress6, 0, sizeof(sockaddr_in6));
  328. std::string *proxyAddress = &overrideProxyAddress;
  329. std::string *proxySecret = &overrideProxySecret;
  330. uint16_t proxyPort = overrideProxyPort;
  331. if (proxyAddress->empty()) {
  332. proxyAddress = &ConnectionsManager::getInstance(instanceNum).proxyAddress;
  333. proxyPort = ConnectionsManager::getInstance(instanceNum).proxyPort;
  334. proxySecret = &ConnectionsManager::getInstance(instanceNum).proxySecret;
  335. }
  336. if (!proxyAddress->empty()) {
  337. if (LOGS_ENABLED) DEBUG_D("connection(%p) connecting via proxy %s:%d secret[%d]", this, proxyAddress->c_str(), proxyPort, (int) proxySecret->size());
  338. if ((socketFd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  339. if (LOGS_ENABLED) DEBUG_E("connection(%p) can't create proxy socket", this);
  340. closeSocket(1, -1);
  341. return;
  342. }
  343. uint32_t tempBuffLength;
  344. if (proxySecret->empty()) {
  345. proxyAuthState = 1;
  346. tempBuffLength = 1024;
  347. } else if (proxySecret->size() > 17 && (*proxySecret)[0] == '\xee') {
  348. proxyAuthState = 10;
  349. currentSecret = proxySecret->substr(1, 16);
  350. currentSecretDomain = proxySecret->substr(17);
  351. tempBuffLength = 65 * 1024;
  352. } else {
  353. proxyAuthState = 0;
  354. tempBuffLength = 0;
  355. }
  356. if (tempBuffLength > 0) {
  357. if (tempBuffer == nullptr || tempBuffer->length < tempBuffLength) {
  358. if (tempBuffer != nullptr) {
  359. delete tempBuffer;
  360. }
  361. tempBuffer = new ByteArray(tempBuffLength);
  362. }
  363. }
  364. socketAddress.sin_family = AF_INET;
  365. socketAddress.sin_port = htons(proxyPort);
  366. bool continueCheckAddress;
  367. if (inet_pton(AF_INET, proxyAddress->c_str(), &socketAddress.sin_addr.s_addr) != 1) {
  368. continueCheckAddress = true;
  369. if (LOGS_ENABLED) DEBUG_D("connection(%p) not ipv4 address %s", this, proxyAddress->c_str());
  370. } else {
  371. ipv6 = false;
  372. continueCheckAddress = false;
  373. }
  374. if (continueCheckAddress) {
  375. if (inet_pton(AF_INET6, proxyAddress->c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) {
  376. continueCheckAddress = true;
  377. if (LOGS_ENABLED) DEBUG_D("connection(%p) not ipv6 address %s", this, proxyAddress->c_str());
  378. } else {
  379. ipv6 = true;
  380. continueCheckAddress = false;
  381. }
  382. if (continueCheckAddress) {
  383. #ifdef USE_DELEGATE_HOST_RESOLVE
  384. waitingForHostResolve = *proxyAddress;
  385. ConnectionsManager::getInstance(instanceNum).delegate->getHostByName(*proxyAddress, instanceNum, this);
  386. return;
  387. #else
  388. struct hostent *he;
  389. if ((he = gethostbyname(proxyAddress->c_str())) == nullptr) {
  390. if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address", this, proxyAddress->c_str());
  391. closeSocket(1, -1);
  392. return;
  393. }
  394. struct in_addr **addr_list = (struct in_addr **) he->h_addr_list;
  395. if (addr_list[0] != nullptr) {
  396. socketAddress.sin_addr.s_addr = addr_list[0]->s_addr;
  397. if (LOGS_ENABLED) DEBUG_D("connection(%p) resolved host %s address %x", this, proxyAddress->c_str(), addr_list[0]->s_addr);
  398. ipv6 = false;
  399. } else {
  400. if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address", this, proxyAddress->c_str());
  401. closeSocket(1, -1);
  402. return;
  403. }
  404. #endif
  405. }
  406. }
  407. } else {
  408. proxyAuthState = 0;
  409. if ((socketFd = socket(ipv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0)) < 0) {
  410. if (LOGS_ENABLED) DEBUG_E("connection(%p) can't create socket", this);
  411. closeSocket(1, -1);
  412. return;
  413. }
  414. if (ipv6) {
  415. socketAddress6.sin6_family = AF_INET6;
  416. socketAddress6.sin6_port = htons(port);
  417. if (inet_pton(AF_INET6, address.c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) {
  418. if (LOGS_ENABLED) DEBUG_E("connection(%p) bad ipv6 %s", this, address.c_str());
  419. closeSocket(1, -1);
  420. return;
  421. }
  422. } else {
  423. socketAddress.sin_family = AF_INET;
  424. socketAddress.sin_port = htons(port);
  425. if (inet_pton(AF_INET, address.c_str(), &socketAddress.sin_addr.s_addr) != 1) {
  426. if (LOGS_ENABLED) DEBUG_E("connection(%p) bad ipv4 %s", this, address.c_str());
  427. closeSocket(1, -1);
  428. return;
  429. }
  430. }
  431. uint32_t tempBuffLength;
  432. if (secret.size() > 17 && secret[0] == '\xee') {
  433. proxyAuthState = 10;
  434. currentSecret = secret.substr(1, 16);
  435. currentSecretDomain = secret.substr(17);
  436. tempBuffLength = 65 * 1024;
  437. } else {
  438. proxyAuthState = 0;
  439. tempBuffLength = 0;
  440. }
  441. if (tempBuffLength > 0) {
  442. if (tempBuffer == nullptr || tempBuffer->length < tempBuffLength) {
  443. if (tempBuffer != nullptr) {
  444. delete tempBuffer;
  445. }
  446. tempBuffer = new ByteArray(tempBuffLength);
  447. }
  448. }
  449. }
  450. openConnectionInternal(ipv6);
  451. }
  452. void ConnectionSocket::openConnectionInternal(bool ipv6) {
  453. int epolFd = ConnectionsManager::getInstance(instanceNum).epolFd;
  454. int yes = 1;
  455. if (setsockopt(socketFd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int))) {
  456. if (LOGS_ENABLED) DEBUG_E("connection(%p) set TCP_NODELAY failed", this);
  457. }
  458. #ifdef DEBUG_VERSION
  459. int size = 4 * 1024 * 1024;
  460. if (setsockopt(socketFd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int))) {
  461. if (LOGS_ENABLED) DEBUG_E("connection(%p) set SO_SNDBUF failed", this);
  462. }
  463. if (setsockopt(socketFd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(int))) {
  464. if (LOGS_ENABLED) DEBUG_E("connection(%p) set SO_RCVBUF failed", this);
  465. }
  466. #endif
  467. if (fcntl(socketFd, F_SETFL, O_NONBLOCK) == -1) {
  468. if (LOGS_ENABLED) DEBUG_E("connection(%p) set O_NONBLOCK failed", this);
  469. closeSocket(1, -1);
  470. return;
  471. }
  472. if (connect(socketFd, (ipv6 ? (sockaddr *) &socketAddress6 : (sockaddr *) &socketAddress), (socklen_t) (ipv6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) == -1 && errno != EINPROGRESS) {
  473. closeSocket(1, -1);
  474. } else {
  475. eventMask.events = EPOLLOUT | EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET;
  476. eventMask.data.ptr = eventObject;
  477. if (epoll_ctl(epolFd, EPOLL_CTL_ADD, socketFd, &eventMask) != 0) {
  478. if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll_ctl, adding socket failed", this);
  479. closeSocket(1, -1);
  480. }
  481. }
  482. if (adjustWriteOpAfterResolve) {
  483. adjustWriteOp();
  484. }
  485. }
  486. int32_t ConnectionSocket::checkSocketError(int32_t *error) {
  487. if (socketFd < 0) {
  488. return true;
  489. }
  490. int ret;
  491. int code;
  492. socklen_t len = sizeof(int);
  493. ret = getsockopt(socketFd, SOL_SOCKET, SO_ERROR, &code, &len);
  494. if (ret != 0 || code != 0) {
  495. if (LOGS_ENABLED) DEBUG_E("socket error 0x%x code 0x%x", ret, code);
  496. }
  497. *error = code;
  498. return (ret || code) != 0;
  499. }
  500. void ConnectionSocket::closeSocket(int32_t reason, int32_t error) {
  501. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  502. ConnectionsManager::getInstance(instanceNum).detachConnection(this);
  503. if (socketFd >= 0) {
  504. epoll_ctl(ConnectionsManager::getInstance(instanceNum).epolFd, EPOLL_CTL_DEL, socketFd, nullptr);
  505. if (close(socketFd) != 0) {
  506. if (LOGS_ENABLED) DEBUG_E("connection(%p) unable to close socket", this);
  507. }
  508. socketFd = -1;
  509. }
  510. waitingForHostResolve = "";
  511. adjustWriteOpAfterResolve = false;
  512. proxyAuthState = 0;
  513. tlsState = 0;
  514. onConnectedSent = false;
  515. outgoingByteStream->clean();
  516. if (tlsBuffer != nullptr) {
  517. tlsBuffer->reuse();
  518. tlsBuffer = nullptr;
  519. }
  520. onDisconnected(reason, error);
  521. }
  522. void ConnectionSocket::onEvent(uint32_t events) {
  523. if (events & EPOLLIN) {
  524. int32_t error;
  525. if (checkSocketError(&error) != 0) {
  526. closeSocket(1, error);
  527. return;
  528. } else {
  529. ssize_t readCount;
  530. NativeByteBuffer *buffer = ConnectionsManager::getInstance(instanceNum).networkBuffer;
  531. while (true) {
  532. buffer->rewind();
  533. readCount = recv(socketFd, buffer->bytes(), READ_BUFFER_SIZE, 0);
  534. if (readCount < 0) {
  535. closeSocket(1, -1);
  536. if (LOGS_ENABLED) DEBUG_E("connection(%p) recv failed", this);
  537. return;
  538. }
  539. if (readCount > 0) {
  540. buffer->limit((uint32_t) readCount);
  541. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  542. if (proxyAuthState == 11) {
  543. if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS received %d", this, (int) readCount);
  544. size_t newBytesRead = bytesRead + readCount;
  545. if (newBytesRead > 64 * 1024) {
  546. closeSocket(1, -1);
  547. if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS client hello too much data", this);
  548. return;
  549. }
  550. if (newBytesRead >= 16) {
  551. std::memcpy(tempBuffer->bytes + bytesRead, buffer->bytes(), (size_t) readCount);
  552. static std::string hello1 = std::string("\x16\x03\x03", 3);
  553. if (std::memcmp(hello1.data(), tempBuffer->bytes, hello1.size()) != 0) {
  554. closeSocket(1, -1);
  555. if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hello1 mismatch", this);
  556. return;
  557. }
  558. size_t len1 = (tempBuffer->bytes[3] << 8) + tempBuffer->bytes[4];
  559. if (len1 > 64 * 1024 - 5) {
  560. closeSocket(1, -1);
  561. if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS len1 invalid", this);
  562. return;
  563. } else if (newBytesRead < len1 + 5) {
  564. if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS client hello wait for more data", this);
  565. bytesRead = newBytesRead;
  566. return;
  567. }
  568. static std::string hello2 = std::string("\x14\x03\x03\x00\x01\x01\x17\x03\x03", 9);
  569. if (std::memcmp(hello2.data(), tempBuffer->bytes + 5 + len1, hello2.size()) != 0) {
  570. closeSocket(1, -1);
  571. if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hello2 mismatch", this);
  572. return;
  573. }
  574. size_t len2 = (tempBuffer->bytes[5 + 9 + len1] << 8) + tempBuffer->bytes[5 + 9 + len1 + 1];
  575. if (len2 > 64 * 1024 - len1 - 5 - 11) {
  576. closeSocket(1, -1);
  577. if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS len2 invalid", this);
  578. return;
  579. } else if (newBytesRead < len2 + len1 + 5 + 11) {
  580. if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS client hello wait for more data", this);
  581. bytesRead = newBytesRead;
  582. return;
  583. }
  584. std::memcpy(tempBuffer->bytes + 64 * 1024 + 32, tempBuffer->bytes + 11, 32);
  585. std::memset(tempBuffer->bytes + 11, 0, 32);
  586. uint8_t *temp = new uint8_t[32 + newBytesRead];
  587. memcpy(temp, tempBuffer->bytes + 64 * 1024, 32);
  588. memcpy(temp + 32, tempBuffer->bytes, newBytesRead);
  589. uint32_t outLength;
  590. HMAC(EVP_sha256(), currentSecret.data(), currentSecret.size(), temp, 32 + newBytesRead, tempBuffer->bytes + 64 * 1024, &outLength);
  591. delete[] temp;
  592. if (std::memcmp(tempBuffer->bytes + 64 * 1024, tempBuffer->bytes + 64 * 1024 + 32, 32) != 0) {
  593. tlsHashMismatch = true;
  594. closeSocket(1, -1);
  595. if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hash mismatch", this);
  596. return;
  597. }
  598. if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS hello complete", this);
  599. tlsState = 1;
  600. proxyAuthState = 0;
  601. bytesRead = 0;
  602. adjustWriteOp();
  603. } else {
  604. std::memcpy(tempBuffer->bytes + bytesRead, buffer->bytes(), (size_t) readCount);
  605. bytesRead = newBytesRead;
  606. }
  607. } else if (proxyAuthState == 2) {
  608. if (readCount == 2) {
  609. uint8_t auth_method = buffer->bytes()[1];
  610. if (auth_method == 0xff) {
  611. closeSocket(1, -1);
  612. if (LOGS_ENABLED) DEBUG_E("connection(%p) unsupported proxy auth method", this);
  613. } else if (auth_method == 0x02) {
  614. if (LOGS_ENABLED) DEBUG_D("connection(%p) proxy auth required", this);
  615. proxyAuthState = 3;
  616. } else if (auth_method == 0x00) {
  617. proxyAuthState = 5;
  618. }
  619. adjustWriteOp();
  620. } else {
  621. closeSocket(1, -1);
  622. if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 2", this);
  623. }
  624. } else if (proxyAuthState == 4) {
  625. if (readCount == 2) {
  626. uint8_t auth_method = buffer->bytes()[1];
  627. if (auth_method != 0x00) {
  628. closeSocket(1, -1);
  629. if (LOGS_ENABLED) DEBUG_E("connection(%p) auth invalid", this);
  630. } else {
  631. proxyAuthState = 5;
  632. }
  633. adjustWriteOp();
  634. } else {
  635. closeSocket(1, -1);
  636. if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 4", this);
  637. }
  638. } else if (proxyAuthState == 6) {
  639. if (readCount > 2) {
  640. uint8_t status = buffer->bytes()[1];
  641. if (status == 0x00) {
  642. if (LOGS_ENABLED) DEBUG_D("connection(%p) connected via proxy", this);
  643. proxyAuthState = 0;
  644. adjustWriteOp();
  645. } else {
  646. closeSocket(1, -1);
  647. if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy status on state 6, 0x%x", this, status);
  648. }
  649. } else {
  650. closeSocket(1, -1);
  651. if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 6", this);
  652. }
  653. } else if (proxyAuthState == 0) {
  654. if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) {
  655. ConnectionsManager::getInstance(instanceNum).delegate->onBytesReceived((int32_t) readCount, currentNetworkType, instanceNum);
  656. }
  657. if (tlsState != 0) {
  658. while (buffer->hasRemaining()) {
  659. size_t newBytesRead = buffer->remaining();
  660. if (tlsBuffer != nullptr) {
  661. newBytesRead += tlsBuffer->position();
  662. if (tlsBufferSized) {
  663. newBytesRead += 5;
  664. }
  665. }
  666. if (newBytesRead >= 5) {
  667. if (tlsBuffer == nullptr || !tlsBufferSized) {
  668. uint32_t pos = buffer->position();
  669. uint8_t offset = 0;
  670. uint8_t header[5];
  671. if (tlsBuffer != nullptr) {
  672. offset = (uint8_t) tlsBuffer->position();
  673. memcpy(header, tlsBuffer->bytes(), offset);
  674. tlsBuffer->reuse();
  675. tlsBuffer = nullptr;
  676. }
  677. memcpy(header + offset, buffer->bytes() + pos, (uint8_t) (5 - offset));
  678. static std::string header1 = std::string("\x17\x03\x03", 3);
  679. if (std::memcmp(header1.data(), header, header1.size()) != 0) {
  680. closeSocket(1, -1);
  681. if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS response header1 mismatch", this);
  682. return;
  683. }
  684. uint32_t len1 = (header[3] << 8) + header[4];
  685. if (len1 > 64 * 1024) {
  686. closeSocket(1, -1);
  687. if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS response len1 invalid", this);
  688. return;
  689. } else {
  690. tlsBuffer = BuffersStorage::getInstance().getFreeBuffer(len1);
  691. tlsBufferSized = true;
  692. buffer->position(pos + (5 - offset));
  693. }
  694. } else {
  695. if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response new data %d", this, buffer->remaining());
  696. }
  697. buffer->limit(std::min(buffer->position() + tlsBuffer->remaining(), buffer->limit()));
  698. tlsBuffer->writeBytes(buffer);
  699. buffer->limit((uint32_t) readCount);
  700. if (tlsBuffer->remaining() == 0) {
  701. tlsBuffer->rewind();
  702. onReceivedData(tlsBuffer);
  703. if (tlsBuffer == nullptr) {
  704. return;
  705. }
  706. tlsBuffer->reuse();
  707. tlsBuffer = nullptr;
  708. } else {
  709. if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response wait for more data, total size %d, left %d", this, tlsBuffer->limit(), tlsBuffer->remaining());
  710. }
  711. } else {
  712. if (tlsBuffer == nullptr) {
  713. tlsBuffer = BuffersStorage::getInstance().getFreeBuffer(4);
  714. tlsBufferSized = false;
  715. }
  716. tlsBuffer->writeBytes(buffer);
  717. if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response wait for more data, not enough bytes for header, total = %d", this, (int) tlsBuffer->position());
  718. }
  719. }
  720. } else {
  721. onReceivedData(buffer);
  722. }
  723. }
  724. }
  725. if (readCount != READ_BUFFER_SIZE) {
  726. break;
  727. }
  728. }
  729. }
  730. }
  731. if (events & EPOLLOUT) {
  732. int32_t error;
  733. if (checkSocketError(&error) != 0) {
  734. closeSocket(1, error);
  735. return;
  736. } else {
  737. if (proxyAuthState != 0) {
  738. if (proxyAuthState >= 10) {
  739. if (proxyAuthState == 10) {
  740. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  741. tlsHashMismatch = false;
  742. proxyAuthState = 11;
  743. TlsHello hello = TlsHello::getDefault();
  744. hello.setDomain(currentSecretDomain);
  745. uint32_t size = hello.writeToBuffer(tempBuffer->bytes);
  746. if (!(size = hello.writePadding(tempBuffer->bytes, size))) {
  747. if (LOGS_ENABLED) DEBUG_E("connection(%p) too much data for padding", this);
  748. closeSocket(1, -1);
  749. return;
  750. }
  751. uint32_t outLength;
  752. HMAC(EVP_sha256(), currentSecret.data(), currentSecret.size(), tempBuffer->bytes, size, tempBuffer->bytes + 64 * 1024, &outLength);
  753. int32_t currentTime = ConnectionsManager::getInstance(instanceNum).getCurrentTime();
  754. int32_t old = ((int32_t *) (tempBuffer->bytes + 64 * 1024 + 28))[0];
  755. ((int32_t *) (tempBuffer->bytes + 64 * 1024 + 28))[0] = old ^ currentTime;
  756. memcpy(tempBuffer->bytes + 11, tempBuffer->bytes + 64 * 1024, 32);
  757. bytesRead = 0;
  758. if (send(socketFd, tempBuffer->bytes, size, 0) < 0) {
  759. if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this);
  760. closeSocket(1, -1);
  761. return;
  762. }
  763. adjustWriteOp();
  764. }
  765. } else {
  766. if (proxyAuthState == 1) {
  767. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  768. proxyAuthState = 2;
  769. tempBuffer->bytes[0] = 0x05;
  770. tempBuffer->bytes[1] = 0x02;
  771. tempBuffer->bytes[2] = 0x00;
  772. tempBuffer->bytes[3] = 0x02;
  773. if (send(socketFd, tempBuffer->bytes, 4, 0) < 0) {
  774. if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this);
  775. closeSocket(1, -1);
  776. return;
  777. }
  778. adjustWriteOp();
  779. } else if (proxyAuthState == 3) {
  780. tempBuffer->bytes[0] = 0x01;
  781. std::string *proxyUser;
  782. std::string *proxyPassword;
  783. if (!overrideProxyAddress.empty()) {
  784. proxyUser = &overrideProxyUser;
  785. proxyPassword = &overrideProxyPassword;
  786. } else {
  787. proxyUser = &ConnectionsManager::getInstance(instanceNum).proxyUser;
  788. proxyPassword = &ConnectionsManager::getInstance(instanceNum).proxyPassword;
  789. }
  790. uint8_t len1 = (uint8_t) proxyUser->length();
  791. uint8_t len2 = (uint8_t) proxyPassword->length();
  792. tempBuffer->bytes[1] = len1;
  793. memcpy(tempBuffer->bytes + 2, proxyUser->c_str(), len1);
  794. tempBuffer->bytes[2 + len1] = len2;
  795. memcpy(tempBuffer->bytes + 3 + len1, proxyPassword->c_str(), len2);
  796. proxyAuthState = 4;
  797. if (send(socketFd, tempBuffer->bytes, 3 + len1 + len2, 0) < 0) {
  798. if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this);
  799. closeSocket(1, -1);
  800. return;
  801. }
  802. adjustWriteOp();
  803. } else if (proxyAuthState == 5) {
  804. tempBuffer->bytes[0] = 0x05;
  805. tempBuffer->bytes[1] = 0x01;
  806. tempBuffer->bytes[2] = 0x00;
  807. tempBuffer->bytes[3] = (uint8_t) (isIpv6 ? 0x04 : 0x01);
  808. uint16_t networkPort = ntohs(currentPort);
  809. inet_pton(isIpv6 ? AF_INET6 : AF_INET, currentAddress.c_str(), tempBuffer->bytes + 4);
  810. memcpy(tempBuffer->bytes + 4 + (isIpv6 ? 16 : 4), &networkPort, sizeof(uint16_t));
  811. proxyAuthState = 6;
  812. if (send(socketFd, tempBuffer->bytes, 4 + (isIpv6 ? 16 : 4) + 2, 0) < 0) {
  813. if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this);
  814. closeSocket(1, -1);
  815. return;
  816. }
  817. adjustWriteOp();
  818. }
  819. }
  820. } else {
  821. if (!onConnectedSent) {
  822. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  823. if (LOGS_ENABLED) DEBUG_D("connection(%p) reset last event time, on connect", this);
  824. onConnected();
  825. onConnectedSent = true;
  826. }
  827. NativeByteBuffer *buffer = ConnectionsManager::getInstance(instanceNum).networkBuffer;
  828. buffer->clear();
  829. outgoingByteStream->get(buffer);
  830. buffer->flip();
  831. uint32_t remaining = buffer->remaining();
  832. if (remaining) {
  833. ssize_t sentLength;
  834. if (tlsState != 0) {
  835. if (remaining > 2878) {
  836. remaining = 2878;
  837. }
  838. size_t headersSize = 0;
  839. if (tlsState == 1) {
  840. static std::string header1 = std::string("\x14\x03\x03\x00\x01\x01", 6);
  841. std::memcpy(tempBuffer->bytes, header1.data(), header1.size());
  842. headersSize += header1.size();
  843. tlsState = 2;
  844. }
  845. static std::string header2 = std::string("\x17\x03\x03", 3);
  846. std::memcpy(tempBuffer->bytes + headersSize, header2.data(), header2.size());
  847. headersSize += header2.size();
  848. tempBuffer->bytes[headersSize] = static_cast<uint8_t>((remaining >> 8) & 0xff);
  849. tempBuffer->bytes[headersSize + 1] = static_cast<uint8_t>(remaining & 0xff);
  850. headersSize += 2;
  851. std::memcpy(tempBuffer->bytes + headersSize, buffer->bytes(), remaining);
  852. if ((sentLength = send(socketFd, tempBuffer->bytes, headersSize + remaining, 0)) < headersSize) {
  853. if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this);
  854. closeSocket(1, -1);
  855. return;
  856. } else {
  857. if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) {
  858. ConnectionsManager::getInstance(instanceNum).delegate->onBytesSent((int32_t) sentLength, currentNetworkType, instanceNum);
  859. }
  860. outgoingByteStream->discard((uint32_t) (sentLength - headersSize));
  861. adjustWriteOp();
  862. }
  863. } else {
  864. if ((sentLength = send(socketFd, buffer->bytes(), remaining, 0)) < 0) {
  865. if (LOGS_ENABLED) DEBUG_D("connection(%p) send failed", this);
  866. closeSocket(1, -1);
  867. return;
  868. } else {
  869. if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) {
  870. ConnectionsManager::getInstance(instanceNum).delegate->onBytesSent((int32_t) sentLength, currentNetworkType, instanceNum);
  871. }
  872. outgoingByteStream->discard((uint32_t) sentLength);
  873. adjustWriteOp();
  874. }
  875. }
  876. }
  877. }
  878. }
  879. }
  880. if (events & EPOLLHUP) {
  881. if (LOGS_ENABLED) DEBUG_E("socket event has EPOLLHUP");
  882. closeSocket(1, -1);
  883. return;
  884. } else if (events & EPOLLRDHUP) {
  885. if (LOGS_ENABLED) DEBUG_E("socket event has EPOLLRDHUP");
  886. closeSocket(1, -1);
  887. return;
  888. }
  889. if (events & EPOLLERR) {
  890. if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll error", this);
  891. return;
  892. }
  893. }
  894. void ConnectionSocket::writeBuffer(uint8_t *data, uint32_t size) {
  895. NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(size);
  896. buffer->writeBytes(data, size);
  897. outgoingByteStream->append(buffer);
  898. adjustWriteOp();
  899. }
  900. void ConnectionSocket::writeBuffer(NativeByteBuffer *buffer) {
  901. outgoingByteStream->append(buffer);
  902. adjustWriteOp();
  903. }
  904. void ConnectionSocket::adjustWriteOp() {
  905. if (!waitingForHostResolve.empty()) {
  906. adjustWriteOpAfterResolve = true;
  907. return;
  908. }
  909. eventMask.events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET;
  910. if (proxyAuthState == 0 && (outgoingByteStream->hasData() || !onConnectedSent) || proxyAuthState == 1 || proxyAuthState == 3 || proxyAuthState == 5 || proxyAuthState == 10) {
  911. eventMask.events |= EPOLLOUT;
  912. }
  913. eventMask.data.ptr = eventObject;
  914. if (epoll_ctl(ConnectionsManager::getInstance(instanceNum).epolFd, EPOLL_CTL_MOD, socketFd, &eventMask) != 0) {
  915. if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll_ctl, modify socket failed", this);
  916. closeSocket(1, -1);
  917. }
  918. }
  919. void ConnectionSocket::setTimeout(time_t time) {
  920. timeout = time;
  921. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  922. if (LOGS_ENABLED) DEBUG_D("connection(%p) set current timeout = %lld", this, (long long) timeout);
  923. }
  924. time_t ConnectionSocket::getTimeout() {
  925. return timeout;
  926. }
  927. bool ConnectionSocket::checkTimeout(int64_t now) {
  928. if (timeout != 0 && (now - lastEventTime) > (int64_t) timeout * 1000) {
  929. if (!onConnectedSent || hasPendingRequests()) {
  930. closeSocket(2, 0);
  931. return true;
  932. } else {
  933. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  934. if (LOGS_ENABLED) DEBUG_D("connection(%p) reset last event time, no requests", this);
  935. }
  936. }
  937. return false;
  938. }
  939. bool ConnectionSocket::hasTlsHashMismatch() {
  940. return tlsHashMismatch;
  941. }
  942. void ConnectionSocket::resetLastEventTime() {
  943. lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis();
  944. }
  945. bool ConnectionSocket::isDisconnected() {
  946. return socketFd < 0;
  947. }
  948. void ConnectionSocket::dropConnection() {
  949. closeSocket(0, 0);
  950. }
  951. void ConnectionSocket::setOverrideProxy(std::string address, uint16_t port, std::string username, std::string password, std::string secret) {
  952. overrideProxyAddress = address;
  953. overrideProxyPort = port;
  954. overrideProxyUser = username;
  955. overrideProxyPassword = password;
  956. overrideProxySecret = secret;
  957. }
  958. void ConnectionSocket::onHostNameResolved(std::string host, std::string ip, bool ipv6) {
  959. ConnectionsManager::getInstance(instanceNum).scheduleTask([&, host, ip, ipv6] {
  960. if (waitingForHostResolve == host) {
  961. waitingForHostResolve = "";
  962. if (ip.empty() || inet_pton(AF_INET, ip.c_str(), &socketAddress.sin_addr.s_addr) != 1) {
  963. if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address via delegate", this, host.c_str());
  964. closeSocket(1, -1);
  965. return;
  966. }
  967. if (LOGS_ENABLED) DEBUG_D("connection(%p) resolved host %s address %s via delegate", this, host.c_str(), ip.c_str());
  968. openConnectionInternal(ipv6);
  969. }
  970. });
  971. }