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