| 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(bool useLegacy) { |
| 255 | if (!useLegacy) { |
| 256 | static TlsHello result = [] { |
| 257 | TlsHello res; |
| 258 | res.ops = { |
| 259 | Op::string("\x16\x03\x01", 3), |
| 260 | Op::begin_scope(), |
| 261 | Op::string("\x01\x00", 2), |
| 262 | Op::begin_scope(), |
| 263 | Op::string("\x03\x03", 2), |
| 264 | Op::zero(32), |
| 265 | Op::string("\x20", 1), |
| 266 | Op::random(32), |
| 267 | Op::string("\x00\x20", 2), |
| 268 | Op::grease(0), |
| 269 | 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), |
| 270 | Op::begin_scope(), |
| 271 | Op::grease(2), |
| 272 | Op::string("\x00\x00", 2), |
| 273 | Op::permutation({ |
| 274 | { |
| 275 | Op::string("\x00\x00", 2), |
| 276 | Op::begin_scope(), |
| 277 | Op::begin_scope(), |
| 278 | Op::string("\x00", 1), |
| 279 | Op::begin_scope(), |
| 280 | Op::domain(), |
| 281 | Op::end_scope(), |
| 282 | Op::end_scope(), |
| 283 | Op::end_scope() |
| 284 | }, |
| 285 | { Op::string("\x00\x05\x00\x05\x01\x00\x00\x00\x00",9) }, |
| 286 | { |
| 287 | Op::string("\x00\x0a\x00\x0c\x00\x0a", 6), |
| 288 | Op::grease(4), |
| 289 | Op::string("\x11\xec\x00\x1d\x00\x17\x00\x18", 8) |
| 290 | }, |
| 291 | { Op::string("\x00\x0b\x00\x02\x01\x00", 6) }, |
| 292 | { 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) }, |
| 293 | { Op::string("\x00\x10\x00\x0e\x00\x0c\x02\x68\x32\x08\x68\x74\x74\x70\x2f\x31\x2e\x31", 18) }, |
| 294 | { Op::string("\x00\x12\x00\x00", 4) }, |
| 295 | { Op::string("\x00\x17\x00\x00", 4) }, |
| 296 | { Op::string("\x00\x1b\x00\x03\x02\x00\x02", 7) }, |
| 297 | { Op::string("\x00\x23\x00\x00", 4) }, |
| 298 | { |
| 299 | Op::string("\x00\x2b\x00\x07\x06", 5), |
| 300 | Op::grease(6), |
| 301 | Op::string("\x03\x04\x03\x03", 4) |
| 302 | }, |
| 303 | { Op::string("\x00\x2d\x00\x02\x01\x01", 6) }, |
| 304 | { |
| 305 | Op::string("\x00\x33\x04\xef\x04\xed", 6), |
| 306 | Op::grease(4), |
| 307 | Op::string("\x00\x01\x00\x11\xec\x04\xc0", 7), |
| 308 | Op::M(), |
| 309 | Op::K(), |
| 310 | Op::string("\x00\x1d\x00\x20", 4), |
| 311 | Op::K(), |
| 312 | }, |
| 313 | { Op::string("\x44\xcd\x00\x05\x00\x03\x02\x68\x32", 9) }, |
| 314 | { |
| 315 | Op::string("\xfe\x02", 2), |
| 316 | Op::begin_scope(), |
| 317 | Op::string("\x00\x00\x01\x00\x01", 5), |
| 318 | Op::random(1), |
| 319 | Op::string("\x00\x20", 2), |
| 320 | Op::random(20), |
| 321 | Op::begin_scope(), |
| 322 | Op::E(), |
| 323 | Op::end_scope(), |
| 324 | Op::end_scope() |
| 325 | }, |
| 326 | { Op::string("\xff\x01\x00\x01\x00", 5) } |
| 327 | }), |
| 328 | Op::grease(3), |
| 329 | Op::string("\x00\x01\x00", 3), |
| 330 | Op::P(), |
| 331 | Op::end_scope(), |
| 332 | Op::end_scope(), |
| 333 | Op::end_scope() |
| 334 | }; |
| 335 | return res; |
| 336 | }(); |
| 337 | return result; |
| 338 | } |
| 339 |
| 340 | static TlsHello result = [] { |
| 341 | TlsHello res; |
| 342 | res.ops = { |
| 343 | Op::string("\x16\x03\x01\x02\x00\x01\x00\x01\xfc\x03\x03", 11), |
| 344 | Op::zero(32), |
| 345 | Op::string("\x20", 1), |
| 346 | Op::random(32), |
| 347 | Op::string("\x00\x20", 2), |
| 348 | Op::grease(0), |
| 349 | 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\x01\x93", 34), |
| 350 | Op::grease(2), |
| 351 | Op::string("\x00\x00", 2), |
| 352 | Op::permutation({ |
| 353 | { |
| 354 | Op::string("\x00\x00", 2), |
| 355 | Op::begin_scope(), |
| 356 | Op::begin_scope(), |
| 357 | Op::string("\x00", 1), |
| 358 | Op::begin_scope(), |
| 359 | Op::domain(), |
| 360 | Op::end_scope(), |
| 361 | Op::end_scope(), |
| 362 | Op::end_scope() |
| 363 | }, |
| 364 | { |
| 365 | Op::string( |
| 366 | "\x00\x05\x00\x05\x01\x00\x00\x00\x00", |
| 367 | 9) |
| 368 | }, |
| 369 | { |
| 370 | Op::string("\x00\x0a\x00\x0a\x00\x08", 6), |
| 371 | Op::grease(4), |
| 372 | Op::string("\x00\x1d\x00\x17\x00\x18", 6) |
| 373 | }, |
| 374 | { |
| 375 | Op::string("\x00\x0b\x00\x02\x01\x00", 6), |
| 376 | }, |
| 377 | { |
| 378 | Op::string( |
| 379 | "\x00\x0d\x00\x12\x00\x10\x04\x03\x08\x04\x04\x01\x05\x03\x08\x05\x05\x01\x08\x06\x06\x01", |
| 380 | 22), |
| 381 | }, |
| 382 | { |
| 383 | Op::string( |
| 384 | "\x00\x10\x00\x0e\x00\x0c\x02\x68\x32\x08\x68\x74\x74\x70\x2f\x31\x2e\x31", |
| 385 | 18), |
| 386 | }, |
| 387 | { |
| 388 | Op::string("\x00\x12\x00\x00", 4) |
| 389 | }, |
| 390 | { |
| 391 | Op::string("\x00\x17\x00\x00", 4) |
| 392 | }, |
| 393 | { |
| 394 | Op::string("\x00\x1b\x00\x03\x02\x00\x02", 7) |
| 395 | }, |
| 396 | { |
| 397 | Op::string("\x00\x23\x00\x00", 4) |
| 398 | }, |
| 399 | { |
| 400 | Op::string("\x00\x2b\x00\x07\x06", 5), |
| 401 | Op::grease(6), |
| 402 | Op::string("\x03\x04\x03\x03", 4) |
| 403 | }, |
| 404 | { |
| 405 | Op::string("\x00\x2d\x00\x02\x01\x01", 6) |
| 406 | }, |
| 407 | { |
| 408 | Op::string("\x00\x33\x00\x2b\x00\x29", 6), |
| 409 | Op::grease(4), |
| 410 | Op::string("\x00\x01\x00\x00\x1d\x00\x20", 7), |
| 411 | Op::K() |
| 412 | }, |
| 413 | { |
| 414 | Op::string("\x44\x69\x00\x05\x00\x03\x02\x68\x32",9), |
| 415 | }, |
| 416 | { |
| 417 | Op::string("\xff\x01\x00\x01\x00", 5), |
| 418 | } |
| 419 | }), |
| 420 |
| 421 | Op::grease(3), |
| 422 | Op::string("\x00\x01\x00", 3), |
| 423 | Op::P() |
| 424 | }; |
| 425 | return res; |
| 426 | }(); |
| 427 | return result; |
| 428 | } |
| 429 |
| 430 | uint32_t writeToBuffer(uint8_t *data) { |
| 431 | uint32_t offset = 0; |
| 432 | for (auto op : ops) { |
| 433 | writeOp(op, data, offset); |
| 434 | } |
| 435 | return offset; |
| 436 | } |
| 437 |
| 438 | void setDomain(std::string value) { |
| 439 | domain = std::move(value); |
| 440 | } |
| 441 |
| 442 | private: |
| 443 | std::vector<Op> ops; |
| 444 | uint8_t grease[MAX_GREASE]; |
| 445 | std::vector<size_t> scopeOffset; |
| 446 | std::string domain; |
| 447 |
| 448 | void writeOp(const TlsHello::Op &op, uint8_t *data, uint32_t &offset) { |
| 449 | using Type = TlsHello::Op::Type; |
| 450 | switch (op.type) { |
| 451 | case Type::String: |
| 452 | memcpy(data + offset, op.data.data(), op.data.size()); |
| 453 | offset += op.data.size(); |
| 454 | break; |
| 455 | case Type::Random: |
| 456 | RAND_bytes(data + offset, (size_t) op.length); |
| 457 | offset += op.length; |
| 458 | break; |
| 459 | case Type::K: |
| 460 | generate_public_key(data + offset); |
| 461 | offset += op.length; |
| 462 | break; |
| 463 | case Type::M: |
| 464 | generate_key_ml_kem_768(data + offset); |
| 465 | offset += 1184; |
| 466 | break; |
| 467 | case Type::Zero: |
| 468 | std::memset(data + offset, 0, op.length); |
| 469 | offset += op.length; |
| 470 | break; |
| 471 | case Type::Domain: { |
| 472 | size_t size = domain.size(); |
| 473 | if (size > 253) { |
| 474 | size = 253; |
| 475 | } |
| 476 | memcpy(data + offset, domain.data(), size); |
| 477 | offset += size; |
| 478 | break; |
| 479 | } |
| 480 | case Type::Grease: { |
| 481 | data[offset] = grease[op.seed]; |
| 482 | data[offset + 1] = grease[op.seed]; |
| 483 | offset += 2; |
| 484 | break; |
| 485 | } |
| 486 | case Type::BeginScope: |
| 487 | scopeOffset.push_back(offset); |
| 488 | offset += 2; |
| 489 | break; |
| 490 | case Type::EndScope: { |
| 491 | auto begin_offset = scopeOffset.back(); |
| 492 | scopeOffset.pop_back(); |
| 493 | size_t size = offset - begin_offset - 2; |
| 494 | data[begin_offset] = static_cast<uint8_t>((size >> 8) & 0xff); |
| 495 | data[begin_offset + 1] = static_cast<uint8_t>(size & 0xff); |
| 496 | break; |
| 497 | } |
| 498 | case Type::E: { |
| 499 | size_t r = rand() % 4; |
| 500 | size_t length = (r == 0 ? 144 : |
| 501 | (r == 1 ? 176 : |
| 502 | (r == 2 ? 208 : 240))); |
| 503 | RAND_bytes(data + offset, (size_t) length); |
| 504 | offset += length; |
| 505 | break; |
| 506 | } |
| 507 | case Type::P: { |
| 508 | auto length = offset; |
| 509 | if (length <= 513) { |
| 510 | writeOp(Op::string("\x00\x15", 2), data, offset); |
| 511 | writeOp(Op::begin_scope(), data, offset); |
| 512 | writeOp(Op::zero(513 - length), data, offset); |
| 513 | writeOp(Op::end_scope(), data, offset); |
| 514 | } |
| 515 | break; |
| 516 | } |
| 517 | case Type::Permutation: { |
| 518 | std::vector<std::vector<Op>> list = {}; |
| 519 | for (const auto &part : op.entities) { |
| 520 | list.push_back(part); |
| 521 | } |
| 522 | size_t size = list.size(); |
| 523 | for (int i = 0; i < size - 1; i++) { |
| 524 | int j = i + rand() % (size - i); |
| 525 | if (i != j) { |
| 526 | std::swap(list[i], list[j]); |
| 527 | } |
| 528 | } |
| 529 | for (const auto &part : list) { |
| 530 | for (const auto &op_local: part) { |
| 531 | writeOp(op_local, data, offset); |
| 532 | } |
| 533 | } |
| 534 | break; |
| 535 | } |
| 536 | } |
| 537 | } |
| 538 | }; |
| 539 |
| 540 | ConnectionSocket::ConnectionSocket(int32_t instance) { |
| 541 | instanceNum = instance; |
| 542 | outgoingByteStream = new ByteStream(); |
| 543 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 544 | eventObject = new EventObject(this, EventObjectTypeConnection); |
| 545 | } |
| 546 |
| 547 | ConnectionSocket::~ConnectionSocket() { |
| 548 | if (outgoingByteStream != nullptr) { |
| 549 | delete outgoingByteStream; |
| 550 | outgoingByteStream = nullptr; |
| 551 | } |
| 552 | if (eventObject != nullptr) { |
| 553 | delete eventObject; |
| 554 | eventObject = nullptr; |
| 555 | } |
| 556 | if (tempBuffer != nullptr) { |
| 557 | delete tempBuffer; |
| 558 | tempBuffer = nullptr; |
| 559 | } |
| 560 | if (tlsBuffer != nullptr) { |
| 561 | tlsBuffer->reuse(); |
| 562 | tlsBuffer = nullptr; |
| 563 | } |
| 564 | } |
| 565 |
| 566 | void ConnectionSocket::openConnection(std::string address, uint16_t port, std::string secret, bool ipv6, int32_t networkType) { |
| 567 | currentNetworkType = networkType; |
| 568 | isIpv6 = ipv6; |
| 569 | currentAddress = address; |
| 570 | currentPort = port; |
| 571 | waitingForHostResolve = ""; |
| 572 | adjustWriteOpAfterResolve = false; |
| 573 | tlsState = 0; |
| 574 | ConnectionsManager::getInstance(instanceNum).attachConnection(this); |
| 575 |
| 576 | memset(&socketAddress, 0, sizeof(sockaddr_in)); |
| 577 | memset(&socketAddress6, 0, sizeof(sockaddr_in6)); |
| 578 |
| 579 | std::string *proxyAddress = &overrideProxyAddress; |
| 580 | std::string *proxySecret = &overrideProxySecret; |
| 581 | uint16_t proxyPort = overrideProxyPort; |
| 582 | bool isProxyIpv6 = false; |
| 583 | if (proxyAddress->empty()) { |
| 584 | proxyAddress = &ConnectionsManager::getInstance(instanceNum).proxyAddress; |
| 585 | proxyPort = ConnectionsManager::getInstance(instanceNum).proxyPort; |
| 586 | proxySecret = &ConnectionsManager::getInstance(instanceNum).proxySecret; |
| 587 |
| 588 | // NekoX: Check whether proxyAddress is an ipv6 addr |
| 589 | struct sockaddr_in6 addr; |
| 590 | isProxyIpv6 = inet_pton(AF_INET6, proxyAddress->c_str(), &(addr.sin6_addr)) != 0; |
| 591 | } |
| 592 |
| 593 | if (!proxyAddress->empty()) { |
| 594 | if (LOGS_ENABLED) DEBUG_D("connection(%p) connecting via proxy %s:%d secret[%d] ipv6:%d", this, proxyAddress->c_str(), proxyPort, (int) proxySecret->size(), isProxyIpv6); |
| 595 | if ((socketFd = socket(isProxyIpv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0)) < 0) { |
| 596 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't create proxy socket", this); |
| 597 | closeSocket(1, -1); |
| 598 | return; |
| 599 | } |
| 600 | uint32_t tempBuffLength; |
| 601 | if (proxySecret->empty()) { |
| 602 | proxyAuthState = 1; |
| 603 | tempBuffLength = 1024; |
| 604 | } else if (proxySecret->size() > 17 && (*proxySecret)[0] == '\xee') { |
| 605 | proxyAuthState = 10; |
| 606 | currentSecret = proxySecret->substr(1, 16); |
| 607 | currentSecretDomain = proxySecret->substr(17); |
| 608 | tempBuffLength = 65 * 1024; |
| 609 | } else { |
| 610 | proxyAuthState = 0; |
| 611 | tempBuffLength = 0; |
| 612 | } |
| 613 | if (tempBuffLength > 0) { |
| 614 | if (tempBuffer == nullptr || tempBuffer->length < tempBuffLength) { |
| 615 | if (tempBuffer != nullptr) { |
| 616 | delete tempBuffer; |
| 617 | } |
| 618 | tempBuffer = new ByteArray(tempBuffLength); |
| 619 | } |
| 620 | } |
| 621 | socketAddress.sin_family = AF_INET; |
| 622 | socketAddress.sin_port = htons(proxyPort); |
| 623 | socketAddress6.sin6_family = AF_INET6; |
| 624 | socketAddress6.sin6_port = htons(proxyPort); |
| 625 | bool continueCheckAddress; |
| 626 | if (inet_pton(AF_INET, proxyAddress->c_str(), &socketAddress.sin_addr.s_addr) != 1) { |
| 627 | continueCheckAddress = true; |
| 628 | if (LOGS_ENABLED) DEBUG_D("connection(%p) not ipv4 address %s", this, proxyAddress->c_str()); |
| 629 | } else { |
| 630 | ipv6 = false; |
| 631 | continueCheckAddress = false; |
| 632 | } |
| 633 | if (continueCheckAddress) { |
| 634 | if (inet_pton(AF_INET6, proxyAddress->c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) { |
| 635 | continueCheckAddress = true; |
| 636 | if (LOGS_ENABLED) DEBUG_D("connection(%p) not ipv6 address %s", this, proxyAddress->c_str()); |
| 637 | } else { |
| 638 | ipv6 = true; |
| 639 | continueCheckAddress = false; |
| 640 | } |
| 641 | if (continueCheckAddress) { |
| 642 | #ifdef USE_DELEGATE_HOST_RESOLVE |
| 643 | waitingForHostResolve = *proxyAddress; |
| 644 | ConnectionsManager::getInstance(instanceNum).delegate->getHostByName(*proxyAddress, instanceNum, this); |
| 645 | return; |
| 646 | #else |
| 647 | struct hostent *he; |
| 648 | if ((he = gethostbyname(proxyAddress->c_str())) == nullptr) { |
| 649 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address", this, proxyAddress->c_str()); |
| 650 | closeSocket(1, -1); |
| 651 | return; |
| 652 | } |
| 653 | struct in_addr **addr_list = (struct in_addr **) he->h_addr_list; |
| 654 | if (addr_list[0] != nullptr) { |
| 655 | socketAddress.sin_addr.s_addr = addr_list[0]->s_addr; |
| 656 | if (LOGS_ENABLED) DEBUG_D("connection(%p) resolved host %s address %x", this, proxyAddress->c_str(), addr_list[0]->s_addr); |
| 657 | ipv6 = false; |
| 658 | } else { |
| 659 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address", this, proxyAddress->c_str()); |
| 660 | closeSocket(1, -1); |
| 661 | return; |
| 662 | } |
| 663 | #endif |
| 664 | } |
| 665 | } |
| 666 | } else { |
| 667 | proxyAuthState = 0; |
| 668 | if ((socketFd = socket(ipv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0)) < 0) { |
| 669 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't create socket", this); |
| 670 | closeSocket(1, -1); |
| 671 | return; |
| 672 | } |
| 673 | if (ipv6) { |
| 674 | socketAddress6.sin6_family = AF_INET6; |
| 675 | socketAddress6.sin6_port = htons(port); |
| 676 | if (inet_pton(AF_INET6, address.c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) { |
| 677 | if (LOGS_ENABLED) DEBUG_E("connection(%p) bad ipv6 %s", this, address.c_str()); |
| 678 | closeSocket(1, -1); |
| 679 | return; |
| 680 | } |
| 681 | } else { |
| 682 | socketAddress.sin_family = AF_INET; |
| 683 | socketAddress.sin_port = htons(port); |
| 684 | if (inet_pton(AF_INET, address.c_str(), &socketAddress.sin_addr.s_addr) != 1) { |
| 685 | if (LOGS_ENABLED) DEBUG_E("connection(%p) bad ipv4 %s", this, address.c_str()); |
| 686 | closeSocket(1, -1); |
| 687 | return; |
| 688 | } |
| 689 | } |
| 690 | uint32_t tempBuffLength; |
| 691 | if (secret.size() > 17 && secret[0] == '\xee') { |
| 692 | proxyAuthState = 10; |
| 693 | currentSecret = secret.substr(1, 16); |
| 694 | currentSecretDomain = secret.substr(17); |
| 695 | tempBuffLength = 65 * 1024; |
| 696 | } else { |
| 697 | proxyAuthState = 0; |
| 698 | tempBuffLength = 0; |
| 699 | } |
| 700 | if (tempBuffLength > 0) { |
| 701 | if (tempBuffer == nullptr || tempBuffer->length < tempBuffLength) { |
| 702 | if (tempBuffer != nullptr) { |
| 703 | delete tempBuffer; |
| 704 | } |
| 705 | tempBuffer = new ByteArray(tempBuffLength); |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 |
| 710 | openConnectionInternal(ipv6); |
| 711 | } |
| 712 |
| 713 | void ConnectionSocket::openConnectionInternal(bool ipv6) { |
| 714 | int epolFd = ConnectionsManager::getInstance(instanceNum).epolFd; |
| 715 | int yes = 1; |
| 716 | if (setsockopt(socketFd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int))) { |
| 717 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set TCP_NODELAY failed", this); |
| 718 | } |
| 719 | #ifdef DEBUG_VERSION |
| 720 | int size = 4 * 1024 * 1024; |
| 721 | if (setsockopt(socketFd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int))) { |
| 722 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set SO_SNDBUF failed", this); |
| 723 | } |
| 724 | if (setsockopt(socketFd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(int))) { |
| 725 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set SO_RCVBUF failed", this); |
| 726 | } |
| 727 | #endif |
| 728 |
| 729 | if (fcntl(socketFd, F_SETFL, O_NONBLOCK) == -1) { |
| 730 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set O_NONBLOCK failed", this); |
| 731 | closeSocket(1, -1); |
| 732 | return; |
| 733 | } |
| 734 |
| 735 | if(LOGS_ENABLED) DEBUG_D("connection(%p) socketAddress6, port: %d, family:%d", this, socketAddress6.sin6_port, socketAddress6.sin6_family); |
| 736 |
| 737 | if (connect(socketFd, (ipv6 ? (sockaddr *) &socketAddress6 : (sockaddr *) &socketAddress), (socklen_t) (ipv6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) == -1 && errno != EINPROGRESS) { |
| 738 | closeSocket(1, -1); |
| 739 | } else { |
| 740 | eventMask.events = EPOLLOUT | EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; |
| 741 | eventMask.data.ptr = eventObject; |
| 742 | if (epoll_ctl(epolFd, EPOLL_CTL_ADD, socketFd, &eventMask) != 0) { |
| 743 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll_ctl, adding socket failed", this); |
| 744 | closeSocket(1, -1); |
| 745 | } |
| 746 | } |
| 747 | if (adjustWriteOpAfterResolve) { |
| 748 | adjustWriteOp(); |
| 749 | } |
| 750 | } |
| 751 |
| 752 | int32_t ConnectionSocket::checkSocketError(int32_t *error) { |
| 753 | if (socketFd < 0) { |
| 754 | return true; |
| 755 | } |
| 756 | int ret; |
| 757 | int code; |
| 758 | socklen_t len = sizeof(int); |
| 759 | ret = getsockopt(socketFd, SOL_SOCKET, SO_ERROR, &code, &len); |
| 760 | if (ret != 0 || code != 0) { |
| 761 | if (LOGS_ENABLED) DEBUG_E("socket error 0x%x code 0x%x", ret, code); |
| 762 | } |
| 763 | *error = code; |
| 764 | return (ret || code) != 0; |
| 765 | } |
| 766 |
| 767 | void ConnectionSocket::closeSocket(int32_t reason, int32_t error) { |
| 768 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 769 | ConnectionsManager::getInstance(instanceNum).detachConnection(this); |
| 770 | if (socketFd >= 0) { |
| 771 | epoll_ctl(ConnectionsManager::getInstance(instanceNum).epolFd, EPOLL_CTL_DEL, socketFd, nullptr); |
| 772 | if (close(socketFd) != 0) { |
| 773 | if (LOGS_ENABLED) DEBUG_E("connection(%p) unable to close socket", this); |
| 774 | } |
| 775 | socketFd = -1; |
| 776 | } |
| 777 | waitingForHostResolve = ""; |
| 778 | adjustWriteOpAfterResolve = false; |
| 779 | proxyAuthState = 0; |
| 780 | tlsState = 0; |
| 781 | onConnectedSent = false; |
| 782 | outgoingByteStream->clean(); |
| 783 | if (tlsBuffer != nullptr) { |
| 784 | tlsBuffer->reuse(); |
| 785 | tlsBuffer = nullptr; |
| 786 | } |
| 787 | onDisconnected(reason, error); |
| 788 | } |
| 789 |
| 790 | void ConnectionSocket::onEvent(uint32_t events) { |
| 791 | if (events & EPOLLIN) { |
| 792 | int32_t error; |
| 793 | if (checkSocketError(&error) != 0) { |
| 794 | closeSocket(1, error); |
| 795 | return; |
| 796 | } else { |
| 797 | ssize_t readCount; |
| 798 | NativeByteBuffer *buffer = ConnectionsManager::getInstance(instanceNum).networkBuffer; |
| 799 | while (true) { |
| 800 | buffer->rewind(); |
| 801 | readCount = recv(socketFd, buffer->bytes(), READ_BUFFER_SIZE, 0); |
| 802 | int err = errno; |
| 803 | // if (LOGS_ENABLED) DEBUG_D("connection(%p) recv resulted with %d, errno=%d", this, readCount, err); |
| 804 | if (readCount < 0) { |
| 805 | if (err == EAGAIN) { |
| 806 | break; |
| 807 | } |
| 808 | closeSocket(1, -1); |
| 809 | if (LOGS_ENABLED) DEBUG_E("connection(%p) recv failed", this); |
| 810 | return; |
| 811 | } |
| 812 | if (readCount > 0) { |
| 813 | buffer->limit((uint32_t) readCount); |
| 814 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 815 | if (proxyAuthState == 11) { |
| 816 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS received %d", this, (int) readCount); |
| 817 | size_t newBytesRead = bytesRead + readCount; |
| 818 | if (newBytesRead > 64 * 1024) { |
| 819 | closeSocket(1, -1); |
| 820 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS client hello too much data", this); |
| 821 | return; |
| 822 | } |
| 823 | if (newBytesRead >= 16) { |
| 824 | std::memcpy(tempBuffer->bytes + bytesRead, buffer->bytes(), (size_t) readCount); |
| 825 |
| 826 | static std::string hello1 = std::string("\x16\x03\x03", 3); |
| 827 | if (std::memcmp(hello1.data(), tempBuffer->bytes, hello1.size()) != 0) { |
| 828 | closeSocket(1, -1); |
| 829 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hello1 mismatch", this); |
| 830 | return; |
| 831 | } |
| 832 | size_t len1 = (tempBuffer->bytes[3] << 8) + tempBuffer->bytes[4]; |
| 833 | if (len1 > 64 * 1024 - 5) { |
| 834 | closeSocket(1, -1); |
| 835 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS len1 invalid", this); |
| 836 | return; |
| 837 | } else if (newBytesRead < len1 + 5) { |
| 838 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS client hello wait for more data", this); |
| 839 | bytesRead = newBytesRead; |
| 840 | return; |
| 841 | } |
| 842 |
| 843 | static std::string hello2 = std::string("\x14\x03\x03\x00\x01\x01\x17\x03\x03", 9); |
| 844 | if (std::memcmp(hello2.data(), tempBuffer->bytes + 5 + len1, hello2.size()) != 0) { |
| 845 | closeSocket(1, -1); |
| 846 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hello2 mismatch", this); |
| 847 | return; |
| 848 | } |
| 849 | size_t len2 = (tempBuffer->bytes[5 + 9 + len1] << 8) + tempBuffer->bytes[5 + 9 + len1 + 1]; |
| 850 | if (len2 > 64 * 1024 - len1 - 5 - 11) { |
| 851 | closeSocket(1, -1); |
| 852 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS len2 invalid", this); |
| 853 | return; |
| 854 | } else if (newBytesRead < len2 + len1 + 5 + 11) { |
| 855 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS client hello wait for more data", this); |
| 856 | bytesRead = newBytesRead; |
| 857 | return; |
| 858 | } |
| 859 | std::memcpy(tempBuffer->bytes + 64 * 1024 + 32, tempBuffer->bytes + 11, 32); |
| 860 | std::memset(tempBuffer->bytes + 11, 0, 32); |
| 861 |
| 862 | uint8_t *temp = new uint8_t[32 + newBytesRead]; |
| 863 | memcpy(temp, tempBuffer->bytes + 64 * 1024, 32); |
| 864 | memcpy(temp + 32, tempBuffer->bytes, newBytesRead); |
| 865 | uint32_t outLength; |
| 866 | HMAC(EVP_sha256(), currentSecret.data(), currentSecret.size(), temp, 32 + newBytesRead, tempBuffer->bytes + 64 * 1024, &outLength); |
| 867 | delete[] temp; |
| 868 | if (std::memcmp(tempBuffer->bytes + 64 * 1024, tempBuffer->bytes + 64 * 1024 + 32, 32) != 0) { |
| 869 | tlsHashMismatch = true; |
| 870 | tlsUseLegacy = true; |
| 871 | closeSocket(1, -1); |
| 872 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hash mismatch", this); |
| 873 | return; |
| 874 | } |
| 875 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS hello complete", this); |
| 876 | tlsState = 1; |
| 877 | proxyAuthState = 0; |
| 878 | bytesRead = 0; |
| 879 | adjustWriteOp(); |
| 880 | } else { |
| 881 | std::memcpy(tempBuffer->bytes + bytesRead, buffer->bytes(), (size_t) readCount); |
| 882 | bytesRead = newBytesRead; |
| 883 | } |
| 884 | } else if (proxyAuthState == 2) { |
| 885 | if (readCount == 2) { |
| 886 | uint8_t auth_method = buffer->bytes()[1]; |
| 887 | if (auth_method == 0xff) { |
| 888 | closeSocket(1, -1); |
| 889 | if (LOGS_ENABLED) DEBUG_E("connection(%p) unsupported proxy auth method", this); |
| 890 | } else if (auth_method == 0x02) { |
| 891 | if (LOGS_ENABLED) DEBUG_D("connection(%p) proxy auth required", this); |
| 892 | proxyAuthState = 3; |
| 893 | } else if (auth_method == 0x00) { |
| 894 | proxyAuthState = 5; |
| 895 | } |
| 896 | adjustWriteOp(); |
| 897 | } else { |
| 898 | closeSocket(1, -1); |
| 899 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 2", this); |
| 900 | } |
| 901 | } else if (proxyAuthState == 4) { |
| 902 | if (readCount == 2) { |
| 903 | uint8_t auth_method = buffer->bytes()[1]; |
| 904 | if (auth_method != 0x00) { |
| 905 | closeSocket(1, -1); |
| 906 | if (LOGS_ENABLED) DEBUG_E("connection(%p) auth invalid", this); |
| 907 | } else { |
| 908 | proxyAuthState = 5; |
| 909 | } |
| 910 | adjustWriteOp(); |
| 911 | } else { |
| 912 | closeSocket(1, -1); |
| 913 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 4", this); |
| 914 | } |
| 915 | } else if (proxyAuthState == 6) { |
| 916 | if (readCount > 2) { |
| 917 | uint8_t status = buffer->bytes()[1]; |
| 918 | if (status == 0x00) { |
| 919 | if (LOGS_ENABLED) DEBUG_D("connection(%p) connected via proxy", this); |
| 920 | proxyAuthState = 0; |
| 921 | adjustWriteOp(); |
| 922 | } else { |
| 923 | closeSocket(1, -1); |
| 924 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy status on state 6, 0x%x", this, status); |
| 925 | } |
| 926 | } else { |
| 927 | closeSocket(1, -1); |
| 928 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 6", this); |
| 929 | } |
| 930 | } else if (proxyAuthState == 0) { |
| 931 | if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) { |
| 932 | ConnectionsManager::getInstance(instanceNum).delegate->onBytesReceived((int32_t) readCount, currentNetworkType, instanceNum); |
| 933 | } |
| 934 | if (tlsState != 0) { |
| 935 | while (buffer->hasRemaining()) { |
| 936 | size_t newBytesRead = buffer->remaining(); |
| 937 | if (tlsBuffer != nullptr) { |
| 938 | newBytesRead += tlsBuffer->position(); |
| 939 | if (tlsBufferSized) { |
| 940 | newBytesRead += 5; |
| 941 | } |
| 942 | } |
| 943 | if (newBytesRead >= 5) { |
| 944 | if (tlsBuffer == nullptr || !tlsBufferSized) { |
| 945 | uint32_t pos = buffer->position(); |
| 946 |
| 947 | uint8_t offset = 0; |
| 948 | uint8_t header[5]; |
| 949 | if (tlsBuffer != nullptr) { |
| 950 | offset = (uint8_t) tlsBuffer->position(); |
| 951 | memcpy(header, tlsBuffer->bytes(), offset); |
| 952 | tlsBuffer->reuse(); |
| 953 | tlsBuffer = nullptr; |
| 954 | } |
| 955 | memcpy(header + offset, buffer->bytes() + pos, (uint8_t) (5 - offset)); |
| 956 |
| 957 | static std::string header1 = std::string("\x17\x03\x03", 3); |
| 958 | if (std::memcmp(header1.data(), header, header1.size()) != 0) { |
| 959 | closeSocket(1, -1); |
| 960 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS response header1 mismatch", this); |
| 961 | return; |
| 962 | } |
| 963 | uint32_t len1 = (header[3] << 8) + header[4]; |
| 964 | if (len1 > 64 * 1024) { |
| 965 | closeSocket(1, -1); |
| 966 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS response len1 invalid", this); |
| 967 | return; |
| 968 | } else { |
| 969 | tlsBuffer = BuffersStorage::getInstance().getFreeBuffer(len1); |
| 970 | tlsBufferSized = true; |
| 971 | buffer->position(pos + (5 - offset)); |
| 972 | } |
| 973 | } else { |
| 974 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response new data %d", this, buffer->remaining()); |
| 975 | } |
| 976 | buffer->limit(std::min(buffer->position() + tlsBuffer->remaining(), buffer->limit())); |
| 977 | tlsBuffer->writeBytes(buffer); |
| 978 | buffer->limit((uint32_t) readCount); |
| 979 | if (tlsBuffer->remaining() == 0) { |
| 980 | tlsBuffer->rewind(); |
| 981 | onReceivedData(tlsBuffer); |
| 982 | if (tlsBuffer == nullptr) { |
| 983 | return; |
| 984 | } |
| 985 | tlsBuffer->reuse(); |
| 986 | tlsBuffer = nullptr; |
| 987 | } else { |
| 988 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response wait for more data, total size %d, left %d", this, tlsBuffer->limit(), tlsBuffer->remaining()); |
| 989 | } |
| 990 | } else { |
| 991 | if (tlsBuffer == nullptr) { |
| 992 | tlsBuffer = BuffersStorage::getInstance().getFreeBuffer(4); |
| 993 | tlsBufferSized = false; |
| 994 | } |
| 995 | tlsBuffer->writeBytes(buffer); |
| 996 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response wait for more data, not enough bytes for header, total = %d", this, (int) tlsBuffer->position()); |
| 997 | } |
| 998 | } |
| 999 | } else { |
| 1000 | onReceivedData(buffer); |
| 1001 | } |
| 1002 | } |
| 1003 | } else if (readCount == 0) { |
| 1004 | break; |
| 1005 | } |
| 1006 | // if (readCount != READ_BUFFER_SIZE) { |
| 1007 | // break; |
| 1008 | // } |
| 1009 | } |
| 1010 | } |
| 1011 | } |
| 1012 | if (events & EPOLLOUT) { |
| 1013 | int32_t error; |
| 1014 | if (checkSocketError(&error) != 0) { |
| 1015 | closeSocket(1, error); |
| 1016 | return; |
| 1017 | } else { |
| 1018 | if (proxyAuthState != 0) { |
| 1019 | if (proxyAuthState >= 10) { |
| 1020 | if (proxyAuthState == 10) { |
| 1021 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 1022 | tlsHashMismatch = false; |
| 1023 | proxyAuthState = 11; |
| 1024 | TlsHello hello = TlsHello::getDefault(tlsUseLegacy); |
| 1025 | hello.setDomain(currentSecretDomain); |
| 1026 | uint32_t size = hello.writeToBuffer(tempBuffer->bytes); |
| 1027 | uint32_t outLength; |
| 1028 | HMAC(EVP_sha256(), currentSecret.data(), currentSecret.size(), tempBuffer->bytes, size, tempBuffer->bytes + 64 * 1024, &outLength); |
| 1029 |
| 1030 | int32_t currentTime = ConnectionsManager::getInstance(instanceNum).getCurrentTime(); |
| 1031 | int32_t old = ((int32_t *) (tempBuffer->bytes + 64 * 1024 + 28))[0]; |
| 1032 | ((int32_t *) (tempBuffer->bytes + 64 * 1024 + 28))[0] = old ^ currentTime; |
| 1033 |
| 1034 | memcpy(tempBuffer->bytes + 11, tempBuffer->bytes + 64 * 1024, 32); |
| 1035 | bytesRead = 0; |
| 1036 |
| 1037 | if (send(socketFd, tempBuffer->bytes, size, 0) < 0) { |
| 1038 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 1039 | closeSocket(1, -1); |
| 1040 | return; |
| 1041 | } |
| 1042 | adjustWriteOp(); |
| 1043 | } |
| 1044 | } else { |
| 1045 | if (proxyAuthState == 1) { |
| 1046 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 1047 | proxyAuthState = 2; |
| 1048 | tempBuffer->bytes[0] = 0x05; |
| 1049 | tempBuffer->bytes[1] = 0x02; |
| 1050 | tempBuffer->bytes[2] = 0x00; |
| 1051 | tempBuffer->bytes[3] = 0x02; |
| 1052 | if (send(socketFd, tempBuffer->bytes, 4, 0) < 0) { |
| 1053 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 1054 | closeSocket(1, -1); |
| 1055 | return; |
| 1056 | } |
| 1057 | adjustWriteOp(); |
| 1058 | } else if (proxyAuthState == 3) { |
| 1059 | tempBuffer->bytes[0] = 0x01; |
| 1060 | std::string *proxyUser; |
| 1061 | std::string *proxyPassword; |
| 1062 | if (!overrideProxyAddress.empty()) { |
| 1063 | proxyUser = &overrideProxyUser; |
| 1064 | proxyPassword = &overrideProxyPassword; |
| 1065 | } else { |
| 1066 | proxyUser = &ConnectionsManager::getInstance(instanceNum).proxyUser; |
| 1067 | proxyPassword = &ConnectionsManager::getInstance(instanceNum).proxyPassword; |
| 1068 | } |
| 1069 | uint8_t len1 = (uint8_t) proxyUser->length(); |
| 1070 | uint8_t len2 = (uint8_t) proxyPassword->length(); |
| 1071 | tempBuffer->bytes[1] = len1; |
| 1072 | memcpy(tempBuffer->bytes + 2, proxyUser->c_str(), len1); |
| 1073 | tempBuffer->bytes[2 + len1] = len2; |
| 1074 | memcpy(tempBuffer->bytes + 3 + len1, proxyPassword->c_str(), len2); |
| 1075 | proxyAuthState = 4; |
| 1076 | if (send(socketFd, tempBuffer->bytes, 3 + len1 + len2, 0) < 0) { |
| 1077 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 1078 | closeSocket(1, -1); |
| 1079 | return; |
| 1080 | } |
| 1081 | adjustWriteOp(); |
| 1082 | } else if (proxyAuthState == 5) { |
| 1083 | tempBuffer->bytes[0] = 0x05; |
| 1084 | tempBuffer->bytes[1] = 0x01; |
| 1085 | tempBuffer->bytes[2] = 0x00; |
| 1086 | tempBuffer->bytes[3] = (uint8_t) (isIpv6 ? 0x04 : 0x01); |
| 1087 | uint16_t networkPort = ntohs(currentPort); |
| 1088 | inet_pton(isIpv6 ? AF_INET6 : AF_INET, currentAddress.c_str(), tempBuffer->bytes + 4); |
| 1089 | memcpy(tempBuffer->bytes + 4 + (isIpv6 ? 16 : 4), &networkPort, sizeof(uint16_t)); |
| 1090 | proxyAuthState = 6; |
| 1091 | if (send(socketFd, tempBuffer->bytes, 4 + (isIpv6 ? 16 : 4) + 2, 0) < 0) { |
| 1092 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 1093 | closeSocket(1, -1); |
| 1094 | return; |
| 1095 | } |
| 1096 | adjustWriteOp(); |
| 1097 | } |
| 1098 | } |
| 1099 | } else { |
| 1100 | if (!onConnectedSent) { |
| 1101 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 1102 | if (LOGS_ENABLED) DEBUG_D("connection(%p) reset last event time, on connect", this); |
| 1103 | onConnected(); |
| 1104 | onConnectedSent = true; |
| 1105 | } |
| 1106 | NativeByteBuffer *buffer = ConnectionsManager::getInstance(instanceNum).networkBuffer; |
| 1107 | buffer->clear(); |
| 1108 | outgoingByteStream->get(buffer); |
| 1109 | buffer->flip(); |
| 1110 |
| 1111 | uint32_t remaining = buffer->remaining(); |
| 1112 | if (remaining) { |
| 1113 | ssize_t sentLength; |
| 1114 | if (tlsState != 0) { |
| 1115 | if (remaining > 2878) { |
| 1116 | remaining = 2878; |
| 1117 | } |
| 1118 | size_t headersSize = 0; |
| 1119 | if (tlsState == 1) { |
| 1120 | static std::string header1 = std::string("\x14\x03\x03\x00\x01\x01", 6); |
| 1121 | std::memcpy(tempBuffer->bytes, header1.data(), header1.size()); |
| 1122 | headersSize += header1.size(); |
| 1123 | tlsState = 2; |
| 1124 | } |
| 1125 | static std::string header2 = std::string("\x17\x03\x03", 3); |
| 1126 | std::memcpy(tempBuffer->bytes + headersSize, header2.data(), header2.size()); |
| 1127 | headersSize += header2.size(); |
| 1128 |
| 1129 | tempBuffer->bytes[headersSize] = static_cast<uint8_t>((remaining >> 8) & 0xff); |
| 1130 | tempBuffer->bytes[headersSize + 1] = static_cast<uint8_t>(remaining & 0xff); |
| 1131 | headersSize += 2; |
| 1132 |
| 1133 | std::memcpy(tempBuffer->bytes + headersSize, buffer->bytes(), remaining); |
| 1134 |
| 1135 | if ((sentLength = send(socketFd, tempBuffer->bytes, headersSize + remaining, 0)) < headersSize) { |
| 1136 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 1137 | closeSocket(1, -1); |
| 1138 | return; |
| 1139 | } else { |
| 1140 | if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) { |
| 1141 | ConnectionsManager::getInstance(instanceNum).delegate->onBytesSent((int32_t) sentLength, currentNetworkType, instanceNum); |
| 1142 | } |
| 1143 | outgoingByteStream->discard((uint32_t) (sentLength - headersSize)); |
| 1144 | adjustWriteOp(); |
| 1145 | } |
| 1146 | } else { |
| 1147 | if ((sentLength = send(socketFd, buffer->bytes(), remaining, 0)) < 0) { |
| 1148 | if (LOGS_ENABLED) DEBUG_D("connection(%p) send failed", this); |
| 1149 | closeSocket(1, -1); |
| 1150 | return; |
| 1151 | } else { |
| 1152 | if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) { |
| 1153 | ConnectionsManager::getInstance(instanceNum).delegate->onBytesSent((int32_t) sentLength, currentNetworkType, instanceNum); |
| 1154 | } |
| 1155 | outgoingByteStream->discard((uint32_t) sentLength); |
| 1156 | adjustWriteOp(); |
| 1157 | } |
| 1158 | } |
| 1159 | } |
| 1160 | } |
| 1161 | } |
| 1162 | } |
| 1163 | if (events & EPOLLHUP) { |
| 1164 | if (LOGS_ENABLED) DEBUG_E("socket event has EPOLLHUP"); |
| 1165 | closeSocket(1, -1); |
| 1166 | return; |
| 1167 | } else if (events & EPOLLRDHUP) { |
| 1168 | if (LOGS_ENABLED) DEBUG_E("socket event has EPOLLRDHUP"); |
| 1169 | closeSocket(1, -1); |
| 1170 | return; |
| 1171 | } |
| 1172 | if (events & EPOLLERR) { |
| 1173 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll error", this); |
| 1174 | return; |
| 1175 | } |
| 1176 | } |
| 1177 |
| 1178 | void ConnectionSocket::writeBuffer(uint8_t *data, uint32_t size) { |
| 1179 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(size); |
| 1180 | buffer->writeBytes(data, size); |
| 1181 | outgoingByteStream->append(buffer); |
| 1182 | adjustWriteOp(); |
| 1183 | } |
| 1184 |
| 1185 | void ConnectionSocket::writeBuffer(NativeByteBuffer *buffer) { |
| 1186 | outgoingByteStream->append(buffer); |
| 1187 | adjustWriteOp(); |
| 1188 | } |
| 1189 |
| 1190 | void ConnectionSocket::adjustWriteOp() { |
| 1191 | if (!waitingForHostResolve.empty()) { |
| 1192 | adjustWriteOpAfterResolve = true; |
| 1193 | return; |
| 1194 | } |
| 1195 | eventMask.events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; |
| 1196 | if (proxyAuthState == 0 && (outgoingByteStream->hasData() || !onConnectedSent) || proxyAuthState == 1 || proxyAuthState == 3 || proxyAuthState == 5 || proxyAuthState == 10) { |
| 1197 | eventMask.events |= EPOLLOUT; |
| 1198 | } |
| 1199 | eventMask.data.ptr = eventObject; |
| 1200 | if (epoll_ctl(ConnectionsManager::getInstance(instanceNum).epolFd, EPOLL_CTL_MOD, socketFd, &eventMask) != 0) { |
| 1201 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll_ctl, modify socket failed", this); |
| 1202 | closeSocket(1, -1); |
| 1203 | } |
| 1204 | } |
| 1205 |
| 1206 | void ConnectionSocket::setTimeout(time_t time) { |
| 1207 | timeout = time; |
| 1208 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 1209 | if (LOGS_ENABLED) DEBUG_D("connection(%p) set current timeout = %lld", this, (long long) timeout); |
| 1210 | } |
| 1211 |
| 1212 | time_t ConnectionSocket::getTimeout() { |
| 1213 | return timeout; |
| 1214 | } |
| 1215 |
| 1216 | bool ConnectionSocket::checkTimeout(int64_t now) { |
| 1217 | if (timeout != 0 && (now - lastEventTime) > (int64_t) timeout * 1000) { |
| 1218 | if (!onConnectedSent || hasPendingRequests()) { |
| 1219 | closeSocket(2, 0); |
| 1220 | return true; |
| 1221 | } else { |
| 1222 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 1223 | if (LOGS_ENABLED) DEBUG_D("connection(%p) reset last event time, no requests", this); |
| 1224 | } |
| 1225 | } |
| 1226 | return false; |
| 1227 | } |
| 1228 |
| 1229 | bool ConnectionSocket::hasTlsHashMismatch() { |
| 1230 | return tlsHashMismatch; |
| 1231 | } |
| 1232 |
| 1233 | void ConnectionSocket::resetLastEventTime() { |
| 1234 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 1235 | } |
| 1236 |
| 1237 | bool ConnectionSocket::isDisconnected() { |
| 1238 | return socketFd < 0; |
| 1239 | } |
| 1240 |
| 1241 | void ConnectionSocket::dropConnection() { |
| 1242 | closeSocket(0, 0); |
| 1243 | } |
| 1244 |
| 1245 | void ConnectionSocket::setOverrideProxy(std::string address, uint16_t port, std::string username, std::string password, std::string secret) { |
| 1246 | overrideProxyAddress = address; |
| 1247 | overrideProxyPort = port; |
| 1248 | overrideProxyUser = username; |
| 1249 | overrideProxyPassword = password; |
| 1250 | overrideProxySecret = secret; |
| 1251 | } |
| 1252 |
| 1253 | void ConnectionSocket::onHostNameResolved(std::string host, std::string ip, bool ipv6) { |
| 1254 | ConnectionsManager::getInstance(instanceNum).scheduleTask([&, host, ip, ipv6] { |
| 1255 | if (waitingForHostResolve == host) { |
| 1256 | waitingForHostResolve = ""; |
| 1257 | if (ip.empty() || (inet_pton(AF_INET, ip.c_str(), &socketAddress.sin_addr.s_addr) != 1 && inet_pton(AF_INET6, ip.c_str(), &socketAddress6.sin6_addr.s6_addr) != 1)) { |
| 1258 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address via delegate", this, host.c_str()); |
| 1259 | closeSocket(1, -1); |
| 1260 | return; |
| 1261 | } |
| 1262 | if (LOGS_ENABLED) DEBUG_D("connection(%p) resolved host %s address %s via delegate ipv6:%d", this, host.c_str(), ip.c_str(), ipv6); |
| 1263 | // NekoX: ipv6 Proxy with domain resolved, fix socket |
| 1264 | // Since default socket type is IPv4 (isProxyIPv6 == false) |
| 1265 | if (!ConnectionsManager::getInstance(instanceNum).proxyAddress.empty() && ipv6) { |
| 1266 | if (LOGS_ENABLED) DEBUG_D("connection(%p) recreate proxy socket when use resolved ipv6 address, host:%s, ip:%s, port:%d isIPv6: %d", this, host.c_str(), ip.c_str(), ConnectionsManager::getInstance(instanceNum).proxyPort, ipv6); |
| 1267 | // recreate socket |
| 1268 | close(socketFd); |
| 1269 | if ((socketFd = socket(AF_INET6 , SOCK_STREAM, 0)) < 0) { |
| 1270 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't recreate proxy socket when use resolved ipv6 address", this); |
| 1271 | closeSocket(1, -1); |
| 1272 | return; |
| 1273 | } |
| 1274 | socketAddress6.sin6_port = htons(ConnectionsManager::getInstance(instanceNum).proxyPort); |
| 1275 | socketAddress6.sin6_family = AF_INET6; |
| 1276 | } |
| 1277 | openConnectionInternal(ipv6); |
| 1278 | } |
| 1279 | }); |
| 1280 | } |
| 1281 |