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