| 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 "TLSHello.h" |
| 34 | #include <random> |
| 35 |
| 36 | #ifndef EPOLLRDHUP |
| 37 | #define EPOLLRDHUP 0x2000 |
| 38 | #endif |
| 39 |
| 40 | #define MAX_GREASE 8 |
| 41 |
| 42 | ConnectionSocket::ConnectionSocket(int32_t instance) { |
| 43 | instanceNum = instance; |
| 44 | outgoingByteStream = new ByteStream(); |
| 45 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 46 | eventObject = new EventObject(this, EventObjectTypeConnection); |
| 47 | } |
| 48 |
| 49 | ConnectionSocket::~ConnectionSocket() { |
| 50 | if (outgoingByteStream != nullptr) { |
| 51 | delete outgoingByteStream; |
| 52 | outgoingByteStream = nullptr; |
| 53 | } |
| 54 | if (eventObject != nullptr) { |
| 55 | delete eventObject; |
| 56 | eventObject = nullptr; |
| 57 | } |
| 58 | if (tempBuffer != nullptr) { |
| 59 | delete tempBuffer; |
| 60 | tempBuffer = nullptr; |
| 61 | } |
| 62 | if (tlsBuffer != nullptr) { |
| 63 | tlsBuffer->reuse(); |
| 64 | tlsBuffer = nullptr; |
| 65 | } |
| 66 | } |
| 67 |
| 68 | void ConnectionSocket::openConnection(std::string address, uint16_t port, std::string secret, bool ipv6, int32_t networkType) { |
| 69 | currentNetworkType = networkType; |
| 70 | isIpv6 = ipv6; |
| 71 | currentAddress = address; |
| 72 | currentPort = port; |
| 73 | waitingForHostResolve = ""; |
| 74 | adjustWriteOpAfterResolve = false; |
| 75 | tlsState = 0; |
| 76 | ConnectionsManager::getInstance(instanceNum).attachConnection(this); |
| 77 |
| 78 | memset(&socketAddress, 0, sizeof(sockaddr_in)); |
| 79 | memset(&socketAddress6, 0, sizeof(sockaddr_in6)); |
| 80 |
| 81 | std::string *proxyAddress = &overrideProxyAddress; |
| 82 | std::string *proxySecret = &overrideProxySecret; |
| 83 | uint16_t proxyPort = overrideProxyPort; |
| 84 | if (proxyAddress->empty()) { |
| 85 | proxyAddress = &ConnectionsManager::getInstance(instanceNum).proxyAddress; |
| 86 | proxyPort = ConnectionsManager::getInstance(instanceNum).proxyPort; |
| 87 | proxySecret = &ConnectionsManager::getInstance(instanceNum).proxySecret; |
| 88 | } |
| 89 |
| 90 | // NekoX: Check whether proxyAddress is an ipv6 addr |
| 91 | struct sockaddr_in6 addr; |
| 92 | bool isProxyIpv6 = inet_pton(AF_INET6, proxyAddress->c_str(), &(addr.sin6_addr)) != 0; |
| 93 |
| 94 | if (!proxyAddress->empty()) { |
| 95 | 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); |
| 96 | if ((socketFd = socket(isProxyIpv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0)) < 0) { |
| 97 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't create proxy socket", this); |
| 98 | closeSocket(1, -1); |
| 99 | return; |
| 100 | } |
| 101 | uint32_t tempBuffLength; |
| 102 | if (proxySecret->empty()) { |
| 103 | proxyAuthState = 1; |
| 104 | tempBuffLength = 1024; |
| 105 | } else if (proxySecret->size() > 17 && (*proxySecret)[0] == '\xee') { |
| 106 | proxyAuthState = 10; |
| 107 | currentSecret = proxySecret->substr(1, 16); |
| 108 | currentSecretDomain = proxySecret->substr(17); |
| 109 | tempBuffLength = 65 * 1024; |
| 110 | } else { |
| 111 | proxyAuthState = 0; |
| 112 | tempBuffLength = 0; |
| 113 | } |
| 114 | if (tempBuffLength > 0) { |
| 115 | if (tempBuffer == nullptr || tempBuffer->length < tempBuffLength) { |
| 116 | if (tempBuffer != nullptr) { |
| 117 | delete tempBuffer; |
| 118 | } |
| 119 | tempBuffer = new ByteArray(tempBuffLength); |
| 120 | } |
| 121 | } |
| 122 | socketAddress.sin_family = AF_INET; |
| 123 | socketAddress.sin_port = htons(proxyPort); |
| 124 | socketAddress6.sin6_family = AF_INET6; |
| 125 | socketAddress6.sin6_port = htons(proxyPort); |
| 126 | bool continueCheckAddress; |
| 127 | if (inet_pton(AF_INET, proxyAddress->c_str(), &socketAddress.sin_addr.s_addr) != 1) { |
| 128 | continueCheckAddress = true; |
| 129 | if (LOGS_ENABLED) DEBUG_D("connection(%p) not ipv4 address %s", this, proxyAddress->c_str()); |
| 130 | } else { |
| 131 | ipv6 = false; |
| 132 | continueCheckAddress = false; |
| 133 | } |
| 134 | if (continueCheckAddress) { |
| 135 | if (inet_pton(AF_INET6, proxyAddress->c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) { |
| 136 | continueCheckAddress = true; |
| 137 | if (LOGS_ENABLED) DEBUG_D("connection(%p) not ipv6 address %s", this, proxyAddress->c_str()); |
| 138 | } else { |
| 139 | ipv6 = true; |
| 140 | continueCheckAddress = false; |
| 141 | } |
| 142 | if (continueCheckAddress) { |
| 143 | #ifdef USE_DELEGATE_HOST_RESOLVE |
| 144 | waitingForHostResolve = *proxyAddress; |
| 145 | ConnectionsManager::getInstance(instanceNum).delegate->getHostByName(*proxyAddress, instanceNum, this); |
| 146 | return; |
| 147 | #else |
| 148 | struct hostent *he; |
| 149 | if ((he = gethostbyname(proxyAddress->c_str())) == nullptr) { |
| 150 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address", this, proxyAddress->c_str()); |
| 151 | closeSocket(1, -1); |
| 152 | return; |
| 153 | } |
| 154 | struct in_addr **addr_list = (struct in_addr **) he->h_addr_list; |
| 155 | if (addr_list[0] != nullptr) { |
| 156 | socketAddress.sin_addr.s_addr = addr_list[0]->s_addr; |
| 157 | if (LOGS_ENABLED) DEBUG_D("connection(%p) resolved host %s address %x", this, proxyAddress->c_str(), addr_list[0]->s_addr); |
| 158 | ipv6 = false; |
| 159 | } else { |
| 160 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address", this, proxyAddress->c_str()); |
| 161 | closeSocket(1, -1); |
| 162 | return; |
| 163 | } |
| 164 | #endif |
| 165 | } |
| 166 | } |
| 167 | } else { |
| 168 | proxyAuthState = 0; |
| 169 | if ((socketFd = socket(ipv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0)) < 0) { |
| 170 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't create socket", this); |
| 171 | closeSocket(1, -1); |
| 172 | return; |
| 173 | } |
| 174 | if (ipv6) { |
| 175 | socketAddress6.sin6_family = AF_INET6; |
| 176 | socketAddress6.sin6_port = htons(port); |
| 177 | if (inet_pton(AF_INET6, address.c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) { |
| 178 | if (LOGS_ENABLED) DEBUG_E("connection(%p) bad ipv6 %s", this, address.c_str()); |
| 179 | closeSocket(1, -1); |
| 180 | return; |
| 181 | } |
| 182 | } else { |
| 183 | socketAddress.sin_family = AF_INET; |
| 184 | socketAddress.sin_port = htons(port); |
| 185 | if (inet_pton(AF_INET, address.c_str(), &socketAddress.sin_addr.s_addr) != 1) { |
| 186 | if (LOGS_ENABLED) DEBUG_E("connection(%p) bad ipv4 %s", this, address.c_str()); |
| 187 | closeSocket(1, -1); |
| 188 | return; |
| 189 | } |
| 190 | } |
| 191 | uint32_t tempBuffLength; |
| 192 | if (secret.size() > 17 && secret[0] == '\xee') { |
| 193 | proxyAuthState = 10; |
| 194 | currentSecret = secret.substr(1, 16); |
| 195 | currentSecretDomain = secret.substr(17); |
| 196 | tempBuffLength = 65 * 1024; |
| 197 | } else { |
| 198 | proxyAuthState = 0; |
| 199 | tempBuffLength = 0; |
| 200 | } |
| 201 | if (tempBuffLength > 0) { |
| 202 | if (tempBuffer == nullptr || tempBuffer->length < tempBuffLength) { |
| 203 | if (tempBuffer != nullptr) { |
| 204 | delete tempBuffer; |
| 205 | } |
| 206 | tempBuffer = new ByteArray(tempBuffLength); |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 |
| 211 | openConnectionInternal(ipv6); |
| 212 | } |
| 213 |
| 214 | void ConnectionSocket::openConnectionInternal(bool ipv6) { |
| 215 | int epolFd = ConnectionsManager::getInstance(instanceNum).epolFd; |
| 216 | int yes = 1; |
| 217 | if (setsockopt(socketFd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int))) { |
| 218 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set TCP_NODELAY failed", this); |
| 219 | } |
| 220 | #ifdef DEBUG_VERSION |
| 221 | int size = 4 * 1024 * 1024; |
| 222 | if (setsockopt(socketFd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int))) { |
| 223 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set SO_SNDBUF failed", this); |
| 224 | } |
| 225 | if (setsockopt(socketFd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(int))) { |
| 226 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set SO_RCVBUF failed", this); |
| 227 | } |
| 228 | #endif |
| 229 |
| 230 | if (fcntl(socketFd, F_SETFL, O_NONBLOCK) == -1) { |
| 231 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set O_NONBLOCK failed", this); |
| 232 | closeSocket(1, -1); |
| 233 | return; |
| 234 | } |
| 235 |
| 236 | if(LOGS_ENABLED) DEBUG_D("connection(%p) socketAddress6, port: %d, family:%d", this, socketAddress6.sin6_port, socketAddress6.sin6_family); |
| 237 |
| 238 | if (connect(socketFd, (ipv6 ? (sockaddr *) &socketAddress6 : (sockaddr *) &socketAddress), (socklen_t) (ipv6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) == -1 && errno != EINPROGRESS) { |
| 239 | closeSocket(1, -1); |
| 240 | } else { |
| 241 | eventMask.events = EPOLLOUT | EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; |
| 242 | eventMask.data.ptr = eventObject; |
| 243 | if (epoll_ctl(epolFd, EPOLL_CTL_ADD, socketFd, &eventMask) != 0) { |
| 244 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll_ctl, adding socket failed", this); |
| 245 | closeSocket(1, -1); |
| 246 | } |
| 247 | } |
| 248 | if (adjustWriteOpAfterResolve) { |
| 249 | adjustWriteOp(); |
| 250 | } |
| 251 | } |
| 252 |
| 253 | int32_t ConnectionSocket::checkSocketError(int32_t *error) { |
| 254 | if (socketFd < 0) { |
| 255 | return true; |
| 256 | } |
| 257 | int ret; |
| 258 | int code; |
| 259 | socklen_t len = sizeof(int); |
| 260 | ret = getsockopt(socketFd, SOL_SOCKET, SO_ERROR, &code, &len); |
| 261 | if (ret != 0 || code != 0) { |
| 262 | if (LOGS_ENABLED) DEBUG_E("socket error 0x%x code 0x%x", ret, code); |
| 263 | } |
| 264 | *error = code; |
| 265 | return (ret || code) != 0; |
| 266 | } |
| 267 |
| 268 | void ConnectionSocket::closeSocket(int32_t reason, int32_t error) { |
| 269 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 270 | ConnectionsManager::getInstance(instanceNum).detachConnection(this); |
| 271 | if (socketFd >= 0) { |
| 272 | epoll_ctl(ConnectionsManager::getInstance(instanceNum).epolFd, EPOLL_CTL_DEL, socketFd, nullptr); |
| 273 | if (close(socketFd) != 0) { |
| 274 | if (LOGS_ENABLED) DEBUG_E("connection(%p) unable to close socket", this); |
| 275 | } |
| 276 | socketFd = -1; |
| 277 | } |
| 278 | waitingForHostResolve = ""; |
| 279 | adjustWriteOpAfterResolve = false; |
| 280 | proxyAuthState = 0; |
| 281 | tlsState = 0; |
| 282 | onConnectedSent = false; |
| 283 | outgoingByteStream->clean(); |
| 284 | if (tlsBuffer != nullptr) { |
| 285 | tlsBuffer->reuse(); |
| 286 | tlsBuffer = nullptr; |
| 287 | } |
| 288 | onDisconnected(reason, error); |
| 289 | } |
| 290 |
| 291 | void ConnectionSocket::onEvent(uint32_t events) { |
| 292 | if (events & EPOLLIN) { |
| 293 | int32_t error; |
| 294 | if (checkSocketError(&error) != 0) { |
| 295 | closeSocket(1, error); |
| 296 | return; |
| 297 | } else { |
| 298 | ssize_t readCount; |
| 299 | NativeByteBuffer *buffer = ConnectionsManager::getInstance(instanceNum).networkBuffer; |
| 300 | while (true) { |
| 301 | buffer->rewind(); |
| 302 | readCount = recv(socketFd, buffer->bytes(), READ_BUFFER_SIZE, 0); |
| 303 | int err = errno; |
| 304 | // if (LOGS_ENABLED) DEBUG_D("connection(%p) recv resulted with %d, errno=%d", this, readCount, err); |
| 305 | if (readCount < 0) { |
| 306 | if (err == EAGAIN) { |
| 307 | break; |
| 308 | } |
| 309 | closeSocket(1, -1); |
| 310 | if (LOGS_ENABLED) DEBUG_E("connection(%p) recv failed", this); |
| 311 | return; |
| 312 | } |
| 313 | if (readCount > 0) { |
| 314 | buffer->limit((uint32_t) readCount); |
| 315 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 316 | if (proxyAuthState == 11) { |
| 317 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS received %d", this, (int) readCount); |
| 318 | size_t newBytesRead = bytesRead + readCount; |
| 319 | if (newBytesRead > 64 * 1024) { |
| 320 | closeSocket(1, -1); |
| 321 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS client hello too much data", this); |
| 322 | return; |
| 323 | } |
| 324 | if (newBytesRead >= 16) { |
| 325 | std::memcpy(tempBuffer->bytes + bytesRead, buffer->bytes(), (size_t) readCount); |
| 326 |
| 327 | static std::string hello1 = std::string("\x16\x03\x03", 3); |
| 328 | if (std::memcmp(hello1.data(), tempBuffer->bytes, hello1.size()) != 0) { |
| 329 | closeSocket(1, -1); |
| 330 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hello1 mismatch", this); |
| 331 | return; |
| 332 | } |
| 333 | size_t len1 = (tempBuffer->bytes[3] << 8) + tempBuffer->bytes[4]; |
| 334 | if (len1 > 64 * 1024 - 5) { |
| 335 | closeSocket(1, -1); |
| 336 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS len1 invalid", this); |
| 337 | return; |
| 338 | } else if (newBytesRead < len1 + 5) { |
| 339 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS client hello wait for more data", this); |
| 340 | bytesRead = newBytesRead; |
| 341 | return; |
| 342 | } |
| 343 |
| 344 | static std::string hello2 = std::string("\x14\x03\x03\x00\x01\x01\x17\x03\x03", 9); |
| 345 | if (std::memcmp(hello2.data(), tempBuffer->bytes + 5 + len1, hello2.size()) != 0) { |
| 346 | closeSocket(1, -1); |
| 347 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hello2 mismatch", this); |
| 348 | return; |
| 349 | } |
| 350 | size_t len2 = (tempBuffer->bytes[5 + 9 + len1] << 8) + tempBuffer->bytes[5 + 9 + len1 + 1]; |
| 351 | if (len2 > 64 * 1024 - len1 - 5 - 11) { |
| 352 | closeSocket(1, -1); |
| 353 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS len2 invalid", this); |
| 354 | return; |
| 355 | } else if (newBytesRead < len2 + len1 + 5 + 11) { |
| 356 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS client hello wait for more data", this); |
| 357 | bytesRead = newBytesRead; |
| 358 | return; |
| 359 | } |
| 360 | std::memcpy(tempBuffer->bytes + 64 * 1024 + 32, tempBuffer->bytes + 11, 32); |
| 361 | std::memset(tempBuffer->bytes + 11, 0, 32); |
| 362 |
| 363 | uint8_t *temp = new uint8_t[32 + newBytesRead]; |
| 364 | memcpy(temp, tempBuffer->bytes + 64 * 1024, 32); |
| 365 | memcpy(temp + 32, tempBuffer->bytes, newBytesRead); |
| 366 | uint32_t outLength; |
| 367 | HMAC(EVP_sha256(), currentSecret.data(), currentSecret.size(), temp, 32 + newBytesRead, tempBuffer->bytes + 64 * 1024, &outLength); |
| 368 | delete[] temp; |
| 369 | if (std::memcmp(tempBuffer->bytes + 64 * 1024, tempBuffer->bytes + 64 * 1024 + 32, 32) != 0) { |
| 370 | tlsHashMismatch = true; |
| 371 | closeSocket(1, -1); |
| 372 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS hash mismatch", this); |
| 373 | return; |
| 374 | } |
| 375 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS hello complete", this); |
| 376 | tlsState = 1; |
| 377 | proxyAuthState = 0; |
| 378 | bytesRead = 0; |
| 379 | adjustWriteOp(); |
| 380 | } else { |
| 381 | std::memcpy(tempBuffer->bytes + bytesRead, buffer->bytes(), (size_t) readCount); |
| 382 | bytesRead = newBytesRead; |
| 383 | } |
| 384 | } else if (proxyAuthState == 2) { |
| 385 | if (readCount == 2) { |
| 386 | uint8_t auth_method = buffer->bytes()[1]; |
| 387 | if (auth_method == 0xff) { |
| 388 | closeSocket(1, -1); |
| 389 | if (LOGS_ENABLED) DEBUG_E("connection(%p) unsupported proxy auth method", this); |
| 390 | } else if (auth_method == 0x02) { |
| 391 | if (LOGS_ENABLED) DEBUG_D("connection(%p) proxy auth required", this); |
| 392 | proxyAuthState = 3; |
| 393 | } else if (auth_method == 0x00) { |
| 394 | proxyAuthState = 5; |
| 395 | } |
| 396 | adjustWriteOp(); |
| 397 | } else { |
| 398 | closeSocket(1, -1); |
| 399 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 2", this); |
| 400 | } |
| 401 | } else if (proxyAuthState == 4) { |
| 402 | if (readCount == 2) { |
| 403 | uint8_t auth_method = buffer->bytes()[1]; |
| 404 | if (auth_method != 0x00) { |
| 405 | closeSocket(1, -1); |
| 406 | if (LOGS_ENABLED) DEBUG_E("connection(%p) auth invalid", this); |
| 407 | } else { |
| 408 | proxyAuthState = 5; |
| 409 | } |
| 410 | adjustWriteOp(); |
| 411 | } else { |
| 412 | closeSocket(1, -1); |
| 413 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 4", this); |
| 414 | } |
| 415 | } else if (proxyAuthState == 6) { |
| 416 | if (readCount > 2) { |
| 417 | uint8_t status = buffer->bytes()[1]; |
| 418 | if (status == 0x00) { |
| 419 | if (LOGS_ENABLED) DEBUG_D("connection(%p) connected via proxy", this); |
| 420 | proxyAuthState = 0; |
| 421 | adjustWriteOp(); |
| 422 | } else { |
| 423 | closeSocket(1, -1); |
| 424 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy status on state 6, 0x%x", this, status); |
| 425 | } |
| 426 | } else { |
| 427 | closeSocket(1, -1); |
| 428 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 6", this); |
| 429 | } |
| 430 | } else if (proxyAuthState == 0) { |
| 431 | if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) { |
| 432 | ConnectionsManager::getInstance(instanceNum).delegate->onBytesReceived((int32_t) readCount, currentNetworkType, instanceNum); |
| 433 | } |
| 434 | if (tlsState != 0) { |
| 435 | while (buffer->hasRemaining()) { |
| 436 | size_t newBytesRead = buffer->remaining(); |
| 437 | if (tlsBuffer != nullptr) { |
| 438 | newBytesRead += tlsBuffer->position(); |
| 439 | if (tlsBufferSized) { |
| 440 | newBytesRead += 5; |
| 441 | } |
| 442 | } |
| 443 | if (newBytesRead >= 5) { |
| 444 | if (tlsBuffer == nullptr || !tlsBufferSized) { |
| 445 | uint32_t pos = buffer->position(); |
| 446 |
| 447 | uint8_t offset = 0; |
| 448 | uint8_t header[5]; |
| 449 | if (tlsBuffer != nullptr) { |
| 450 | offset = (uint8_t) tlsBuffer->position(); |
| 451 | memcpy(header, tlsBuffer->bytes(), offset); |
| 452 | tlsBuffer->reuse(); |
| 453 | tlsBuffer = nullptr; |
| 454 | } |
| 455 | memcpy(header + offset, buffer->bytes() + pos, (uint8_t) (5 - offset)); |
| 456 |
| 457 | static std::string header1 = std::string("\x17\x03\x03", 3); |
| 458 | if (std::memcmp(header1.data(), header, header1.size()) != 0) { |
| 459 | closeSocket(1, -1); |
| 460 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS response header1 mismatch", this); |
| 461 | return; |
| 462 | } |
| 463 | uint32_t len1 = (header[3] << 8) + header[4]; |
| 464 | if (len1 > 64 * 1024) { |
| 465 | closeSocket(1, -1); |
| 466 | if (LOGS_ENABLED) DEBUG_E("connection(%p) TLS response len1 invalid", this); |
| 467 | return; |
| 468 | } else { |
| 469 | tlsBuffer = BuffersStorage::getInstance().getFreeBuffer(len1); |
| 470 | tlsBufferSized = true; |
| 471 | buffer->position(pos + (5 - offset)); |
| 472 | } |
| 473 | } else { |
| 474 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response new data %d", this, buffer->remaining()); |
| 475 | } |
| 476 | buffer->limit(std::min(buffer->position() + tlsBuffer->remaining(), buffer->limit())); |
| 477 | tlsBuffer->writeBytes(buffer); |
| 478 | buffer->limit((uint32_t) readCount); |
| 479 | if (tlsBuffer->remaining() == 0) { |
| 480 | tlsBuffer->rewind(); |
| 481 | onReceivedData(tlsBuffer); |
| 482 | if (tlsBuffer == nullptr) { |
| 483 | return; |
| 484 | } |
| 485 | tlsBuffer->reuse(); |
| 486 | tlsBuffer = nullptr; |
| 487 | } else { |
| 488 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response wait for more data, total size %d, left %d", this, tlsBuffer->limit(), tlsBuffer->remaining()); |
| 489 | } |
| 490 | } else { |
| 491 | if (tlsBuffer == nullptr) { |
| 492 | tlsBuffer = BuffersStorage::getInstance().getFreeBuffer(4); |
| 493 | tlsBufferSized = false; |
| 494 | } |
| 495 | tlsBuffer->writeBytes(buffer); |
| 496 | if (LOGS_ENABLED) DEBUG_D("connection(%p) TLS response wait for more data, not enough bytes for header, total = %d", this, (int) tlsBuffer->position()); |
| 497 | } |
| 498 | } |
| 499 | } else { |
| 500 | onReceivedData(buffer); |
| 501 | } |
| 502 | } |
| 503 | } else if (readCount == 0) { |
| 504 | break; |
| 505 | } |
| 506 | // if (readCount != READ_BUFFER_SIZE) { |
| 507 | // break; |
| 508 | // } |
| 509 | } |
| 510 | } |
| 511 | } |
| 512 | if (events & EPOLLOUT) { |
| 513 | int32_t error; |
| 514 | if (checkSocketError(&error) != 0) { |
| 515 | closeSocket(1, error); |
| 516 | return; |
| 517 | } else { |
| 518 | if (proxyAuthState != 0) { |
| 519 | if (proxyAuthState >= 10) { |
| 520 | if (proxyAuthState == 10) { |
| 521 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 522 | tlsHashMismatch = false; |
| 523 | proxyAuthState = 11; |
| 524 | TLSHello hello = TLSHello::getDefault(); |
| 525 | hello.setDomain(currentSecretDomain); |
| 526 | uint32_t size = hello.writeToBuffer(tempBuffer->bytes); |
| 527 | uint32_t outLength; |
| 528 | HMAC(EVP_sha256(), currentSecret.data(), currentSecret.size(), tempBuffer->bytes, size, tempBuffer->bytes + 64 * 1024, &outLength); |
| 529 |
| 530 | int32_t currentTime = ConnectionsManager::getInstance(instanceNum).getCurrentTime(); |
| 531 | int32_t old = ((int32_t *) (tempBuffer->bytes + 64 * 1024 + 28))[0]; |
| 532 | ((int32_t *) (tempBuffer->bytes + 64 * 1024 + 28))[0] = old ^ currentTime; |
| 533 |
| 534 | memcpy(tempBuffer->bytes + 11, tempBuffer->bytes + 64 * 1024, 32); |
| 535 | bytesRead = 0; |
| 536 |
| 537 | if (send(socketFd, tempBuffer->bytes, size, 0) < 0) { |
| 538 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 539 | closeSocket(1, -1); |
| 540 | return; |
| 541 | } |
| 542 | adjustWriteOp(); |
| 543 | } |
| 544 | } else { |
| 545 | if (proxyAuthState == 1) { |
| 546 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 547 | proxyAuthState = 2; |
| 548 | tempBuffer->bytes[0] = 0x05; |
| 549 | tempBuffer->bytes[1] = 0x02; |
| 550 | tempBuffer->bytes[2] = 0x00; |
| 551 | tempBuffer->bytes[3] = 0x02; |
| 552 | if (send(socketFd, tempBuffer->bytes, 4, 0) < 0) { |
| 553 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 554 | closeSocket(1, -1); |
| 555 | return; |
| 556 | } |
| 557 | adjustWriteOp(); |
| 558 | } else if (proxyAuthState == 3) { |
| 559 | tempBuffer->bytes[0] = 0x01; |
| 560 | std::string *proxyUser; |
| 561 | std::string *proxyPassword; |
| 562 | if (!overrideProxyAddress.empty()) { |
| 563 | proxyUser = &overrideProxyUser; |
| 564 | proxyPassword = &overrideProxyPassword; |
| 565 | } else { |
| 566 | proxyUser = &ConnectionsManager::getInstance(instanceNum).proxyUser; |
| 567 | proxyPassword = &ConnectionsManager::getInstance(instanceNum).proxyPassword; |
| 568 | } |
| 569 | uint8_t len1 = (uint8_t) proxyUser->length(); |
| 570 | uint8_t len2 = (uint8_t) proxyPassword->length(); |
| 571 | tempBuffer->bytes[1] = len1; |
| 572 | memcpy(tempBuffer->bytes + 2, proxyUser->c_str(), len1); |
| 573 | tempBuffer->bytes[2 + len1] = len2; |
| 574 | memcpy(tempBuffer->bytes + 3 + len1, proxyPassword->c_str(), len2); |
| 575 | proxyAuthState = 4; |
| 576 | if (send(socketFd, tempBuffer->bytes, 3 + len1 + len2, 0) < 0) { |
| 577 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 578 | closeSocket(1, -1); |
| 579 | return; |
| 580 | } |
| 581 | adjustWriteOp(); |
| 582 | } else if (proxyAuthState == 5) { |
| 583 | tempBuffer->bytes[0] = 0x05; |
| 584 | tempBuffer->bytes[1] = 0x01; |
| 585 | tempBuffer->bytes[2] = 0x00; |
| 586 | tempBuffer->bytes[3] = (uint8_t) (isIpv6 ? 0x04 : 0x01); |
| 587 | uint16_t networkPort = ntohs(currentPort); |
| 588 | inet_pton(isIpv6 ? AF_INET6 : AF_INET, currentAddress.c_str(), tempBuffer->bytes + 4); |
| 589 | memcpy(tempBuffer->bytes + 4 + (isIpv6 ? 16 : 4), &networkPort, sizeof(uint16_t)); |
| 590 | proxyAuthState = 6; |
| 591 | if (send(socketFd, tempBuffer->bytes, 4 + (isIpv6 ? 16 : 4) + 2, 0) < 0) { |
| 592 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 593 | closeSocket(1, -1); |
| 594 | return; |
| 595 | } |
| 596 | adjustWriteOp(); |
| 597 | } |
| 598 | } |
| 599 | } else { |
| 600 | if (!onConnectedSent) { |
| 601 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 602 | if (LOGS_ENABLED) DEBUG_D("connection(%p) reset last event time, on connect", this); |
| 603 | onConnected(); |
| 604 | onConnectedSent = true; |
| 605 | } |
| 606 | NativeByteBuffer *buffer = ConnectionsManager::getInstance(instanceNum).networkBuffer; |
| 607 | buffer->clear(); |
| 608 | outgoingByteStream->get(buffer); |
| 609 | buffer->flip(); |
| 610 |
| 611 | uint32_t remaining = buffer->remaining(); |
| 612 | if (remaining) { |
| 613 | ssize_t sentLength; |
| 614 | if (tlsState != 0) { |
| 615 | if (remaining > 2878) { |
| 616 | remaining = 2878; |
| 617 | } |
| 618 | size_t headersSize = 0; |
| 619 | if (tlsState == 1) { |
| 620 | static std::string header1 = std::string("\x14\x03\x03\x00\x01\x01", 6); |
| 621 | std::memcpy(tempBuffer->bytes, header1.data(), header1.size()); |
| 622 | headersSize += header1.size(); |
| 623 | tlsState = 2; |
| 624 | } |
| 625 | static std::string header2 = std::string("\x17\x03\x03", 3); |
| 626 | std::memcpy(tempBuffer->bytes + headersSize, header2.data(), header2.size()); |
| 627 | headersSize += header2.size(); |
| 628 |
| 629 | tempBuffer->bytes[headersSize] = static_cast<uint8_t>((remaining >> 8) & 0xff); |
| 630 | tempBuffer->bytes[headersSize + 1] = static_cast<uint8_t>(remaining & 0xff); |
| 631 | headersSize += 2; |
| 632 |
| 633 | std::memcpy(tempBuffer->bytes + headersSize, buffer->bytes(), remaining); |
| 634 |
| 635 | if ((sentLength = send(socketFd, tempBuffer->bytes, headersSize + remaining, 0)) < headersSize) { |
| 636 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 637 | closeSocket(1, -1); |
| 638 | return; |
| 639 | } else { |
| 640 | if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) { |
| 641 | ConnectionsManager::getInstance(instanceNum).delegate->onBytesSent((int32_t) sentLength, currentNetworkType, instanceNum); |
| 642 | } |
| 643 | outgoingByteStream->discard((uint32_t) (sentLength - headersSize)); |
| 644 | adjustWriteOp(); |
| 645 | } |
| 646 | } else { |
| 647 | if ((sentLength = send(socketFd, buffer->bytes(), remaining, 0)) < 0) { |
| 648 | if (LOGS_ENABLED) DEBUG_D("connection(%p) send failed", this); |
| 649 | closeSocket(1, -1); |
| 650 | return; |
| 651 | } else { |
| 652 | if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) { |
| 653 | ConnectionsManager::getInstance(instanceNum).delegate->onBytesSent((int32_t) sentLength, currentNetworkType, instanceNum); |
| 654 | } |
| 655 | outgoingByteStream->discard((uint32_t) sentLength); |
| 656 | adjustWriteOp(); |
| 657 | } |
| 658 | } |
| 659 | } |
| 660 | } |
| 661 | } |
| 662 | } |
| 663 | if (events & EPOLLHUP) { |
| 664 | if (LOGS_ENABLED) DEBUG_E("socket event has EPOLLHUP"); |
| 665 | closeSocket(1, -1); |
| 666 | return; |
| 667 | } else if (events & EPOLLRDHUP) { |
| 668 | if (LOGS_ENABLED) DEBUG_E("socket event has EPOLLRDHUP"); |
| 669 | closeSocket(1, -1); |
| 670 | return; |
| 671 | } |
| 672 | if (events & EPOLLERR) { |
| 673 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll error", this); |
| 674 | return; |
| 675 | } |
| 676 | } |
| 677 |
| 678 | void ConnectionSocket::writeBuffer(uint8_t *data, uint32_t size) { |
| 679 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(size); |
| 680 | buffer->writeBytes(data, size); |
| 681 | outgoingByteStream->append(buffer); |
| 682 | adjustWriteOp(); |
| 683 | } |
| 684 |
| 685 | void ConnectionSocket::writeBuffer(NativeByteBuffer *buffer) { |
| 686 | outgoingByteStream->append(buffer); |
| 687 | adjustWriteOp(); |
| 688 | } |
| 689 |
| 690 | void ConnectionSocket::adjustWriteOp() { |
| 691 | if (!waitingForHostResolve.empty()) { |
| 692 | adjustWriteOpAfterResolve = true; |
| 693 | return; |
| 694 | } |
| 695 | eventMask.events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; |
| 696 | if (proxyAuthState == 0 && (outgoingByteStream->hasData() || !onConnectedSent) || proxyAuthState == 1 || proxyAuthState == 3 || proxyAuthState == 5 || proxyAuthState == 10) { |
| 697 | eventMask.events |= EPOLLOUT; |
| 698 | } |
| 699 | eventMask.data.ptr = eventObject; |
| 700 | if (epoll_ctl(ConnectionsManager::getInstance(instanceNum).epolFd, EPOLL_CTL_MOD, socketFd, &eventMask) != 0) { |
| 701 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll_ctl, modify socket failed", this); |
| 702 | closeSocket(1, -1); |
| 703 | } |
| 704 | } |
| 705 |
| 706 | void ConnectionSocket::setTimeout(time_t time) { |
| 707 | timeout = time; |
| 708 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 709 | if (LOGS_ENABLED) DEBUG_D("connection(%p) set current timeout = %lld", this, (long long) timeout); |
| 710 | } |
| 711 |
| 712 | time_t ConnectionSocket::getTimeout() { |
| 713 | return timeout; |
| 714 | } |
| 715 |
| 716 | bool ConnectionSocket::checkTimeout(int64_t now) { |
| 717 | if (timeout != 0 && (now - lastEventTime) > (int64_t) timeout * 1000) { |
| 718 | if (!onConnectedSent || hasPendingRequests()) { |
| 719 | closeSocket(2, 0); |
| 720 | return true; |
| 721 | } else { |
| 722 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 723 | if (LOGS_ENABLED) DEBUG_D("connection(%p) reset last event time, no requests", this); |
| 724 | } |
| 725 | } |
| 726 | return false; |
| 727 | } |
| 728 |
| 729 | bool ConnectionSocket::hasTlsHashMismatch() { |
| 730 | return tlsHashMismatch; |
| 731 | } |
| 732 |
| 733 | void ConnectionSocket::resetLastEventTime() { |
| 734 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 735 | } |
| 736 |
| 737 | bool ConnectionSocket::isDisconnected() { |
| 738 | return socketFd < 0; |
| 739 | } |
| 740 |
| 741 | void ConnectionSocket::dropConnection() { |
| 742 | closeSocket(0, 0); |
| 743 | } |
| 744 |
| 745 | void ConnectionSocket::setOverrideProxy(std::string address, uint16_t port, std::string username, std::string password, std::string secret) { |
| 746 | overrideProxyAddress = address; |
| 747 | overrideProxyPort = port; |
| 748 | overrideProxyUser = username; |
| 749 | overrideProxyPassword = password; |
| 750 | overrideProxySecret = secret; |
| 751 | } |
| 752 |
| 753 | void ConnectionSocket::onHostNameResolved(std::string host, std::string ip, bool ipv6) { |
| 754 | ConnectionsManager::getInstance(instanceNum).scheduleTask([&, host, ip, ipv6] { |
| 755 | if (waitingForHostResolve == host) { |
| 756 | waitingForHostResolve = ""; |
| 757 | 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)) { |
| 758 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address via delegate", this, host.c_str()); |
| 759 | closeSocket(1, -1); |
| 760 | return; |
| 761 | } |
| 762 | if (LOGS_ENABLED) DEBUG_D("connection(%p) resolved host %s address %s via delegate ipv6:%d", this, host.c_str(), ip.c_str(), ipv6); |
| 763 | // NekoX: ipv6 Proxy with domain resolved, fix socket |
| 764 | // Since default socket type is IPv4 (isProxyIPv6 == false) |
| 765 | if (!ConnectionsManager::getInstance(instanceNum).proxyAddress.empty() && ipv6) { |
| 766 | 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); |
| 767 | // recreate socket |
| 768 | close(socketFd); |
| 769 | if ((socketFd = socket(AF_INET6 , SOCK_STREAM, 0)) < 0) { |
| 770 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't recreate proxy socket when use resolved ipv6 address", this); |
| 771 | closeSocket(1, -1); |
| 772 | return; |
| 773 | } |
| 774 | socketAddress6.sin6_port = htons(ConnectionsManager::getInstance(instanceNum).proxyPort); |
| 775 | socketAddress6.sin6_family = AF_INET6; |
| 776 | } |
| 777 | openConnectionInternal(ipv6); |
| 778 | } |
| 779 | }); |
| 780 | } |
| 781 |