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