| 6 |
| * Copyright Nikolai Kudashov, 2015-2018. |
| 7 | */ |
| 8 |
| 9 | #include <unistd.h> |
| 10 | #include <fcntl.h> |
| 11 | #include <errno.h> |
| 12 | #include <sys/socket.h> |
| 13 | #include <memory.h> |
| 14 | #include <netinet/tcp.h> |
| 15 | #include <arpa/inet.h> |
| 16 | #include <netdb.h> |
| 17 | #include "ByteStream.h" |
| 18 | #include "ConnectionSocket.h" |
| 19 | #include "FileLog.h" |
| 20 | #include "Defines.h" |
| 21 | #include "ConnectionsManager.h" |
| 22 | #include "EventObject.h" |
| 23 | #include "Timer.h" |
| 24 | #include "NativeByteBuffer.h" |
| 25 | #include "BuffersStorage.h" |
| 26 |
| 27 | #ifndef EPOLLRDHUP |
| 28 | #define EPOLLRDHUP 0x2000 |
| 29 | #endif |
| 30 |
| 31 | ConnectionSocket::ConnectionSocket(int32_t instance) { |
| 32 | instanceNum = instance; |
| 33 | outgoingByteStream = new ByteStream(); |
| 34 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 35 | eventObject = new EventObject(this, EventObjectTypeConnection); |
| 36 | } |
| 37 |
| 38 | ConnectionSocket::~ConnectionSocket() { |
| 39 | if (outgoingByteStream != nullptr) { |
| 40 | delete outgoingByteStream; |
| 41 | outgoingByteStream = nullptr; |
| 42 | } |
| 43 | if (eventObject != nullptr) { |
| 44 | delete eventObject; |
| 45 | eventObject = nullptr; |
| 46 | } |
| 47 | } |
| 48 |
| 49 | void ConnectionSocket::openConnection(std::string address, uint16_t port, bool ipv6, int32_t networkType) { |
| 50 | currentNetworkType = networkType; |
| 51 | isIpv6 = ipv6; |
| 52 | currentAddress = address; |
| 53 | currentPort = port; |
| 54 | int epolFd = ConnectionsManager::getInstance(instanceNum).epolFd; |
| 55 | ConnectionsManager::getInstance(instanceNum).attachConnection(this); |
| 56 |
| 57 | memset(&socketAddress, 0, sizeof(sockaddr_in)); |
| 58 | memset(&socketAddress6, 0, sizeof(sockaddr_in6)); |
| 59 |
| 60 | std::string *proxyAddress = &overrideProxyAddress; |
| 61 | std::string *proxySecret = &overrideProxySecret; |
| 62 | uint16_t proxyPort = overrideProxyPort; |
| 63 | if (proxyAddress->empty()) { |
| 64 | proxyAddress = &ConnectionsManager::getInstance(instanceNum).proxyAddress; |
| 65 | proxyPort = ConnectionsManager::getInstance(instanceNum).proxyPort; |
| 66 | proxySecret = &ConnectionsManager::getInstance(instanceNum).proxySecret; |
| 67 | } |
| 68 |
| 69 | if (proxyAddress != nullptr && !proxyAddress->empty()) { |
| 70 | if ((socketFd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { |
| 71 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't create proxy socket", this); |
| 72 | closeSocket(1, -1); |
| 73 | return; |
| 74 | } |
| 75 | if (proxySecret->empty()) { |
| 76 | proxyAuthState = 1; |
| 77 | } else { |
| 78 | proxyAuthState = 0; |
| 79 | } |
| 80 | socketAddress.sin_family = AF_INET; |
| 81 | socketAddress.sin_port = htons(proxyPort); |
| 82 | bool continueCheckAddress; |
| 83 | if (inet_pton(AF_INET, proxyAddress->c_str(), &socketAddress.sin_addr.s_addr) != 1) { |
| 84 | continueCheckAddress = true; |
| 85 | if (LOGS_ENABLED) DEBUG_D("connection(%p) not ipv4 address %s", this, proxyAddress->c_str()); |
| 86 | } else { |
| 87 | ipv6 = false; |
| 88 | continueCheckAddress = false; |
| 89 | } |
| 90 | if (continueCheckAddress) { |
| 91 | if (inet_pton(AF_INET6, proxyAddress->c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) { |
| 92 | continueCheckAddress = true; |
| 93 | if (LOGS_ENABLED) DEBUG_D("connection(%p) not ipv6 address %s", this, proxyAddress->c_str()); |
| 94 | } else { |
| 95 | ipv6 = true; |
| 96 | continueCheckAddress = false; |
| 97 | } |
| 98 | if (continueCheckAddress) { |
| 99 | std::string host = ConnectionsManager::getInstance(instanceNum).delegate->getHostByName(*proxyAddress, instanceNum); |
| 100 | if (host.empty() || inet_pton(AF_INET, host.c_str(), &socketAddress.sin_addr.s_addr) != 1) { |
| 101 | continueCheckAddress = true; |
| 102 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address via delegate", this, proxyAddress->c_str()); |
| 103 | } else { |
| 104 | continueCheckAddress = false; |
| 105 | if (LOGS_ENABLED) DEBUG_D("connection(%p) resolved host %s address %x via delegate", this, proxyAddress->c_str(), socketAddress.sin_addr.s_addr); |
| 106 | } |
| 107 | if (continueCheckAddress) { |
| 108 | struct hostent *he; |
| 109 | if ((he = gethostbyname(proxyAddress->c_str())) == nullptr) { |
| 110 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address", this, proxyAddress->c_str()); |
| 111 | closeSocket(1, -1); |
| 112 | return; |
| 113 | } |
| 114 | struct in_addr **addr_list = (struct in_addr **) he->h_addr_list; |
| 115 | if (addr_list[0] != nullptr) { |
| 116 | socketAddress.sin_addr.s_addr = addr_list[0]->s_addr; |
| 117 | if (LOGS_ENABLED) DEBUG_D("connection(%p) resolved host %s address %x", this, proxyAddress->c_str(), addr_list[0]->s_addr); |
| 118 | ipv6 = false; |
| 119 | } else { |
| 120 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't resolve host %s address", this, proxyAddress->c_str()); |
| 121 | closeSocket(1, -1); |
| 122 | return; |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | } else { |
| 128 | proxyAuthState = 0; |
| 129 | if ((socketFd = socket(ipv6 ? AF_INET6 : AF_INET, SOCK_STREAM, 0)) < 0) { |
| 130 | if (LOGS_ENABLED) DEBUG_E("connection(%p) can't create socket", this); |
| 131 | closeSocket(1, -1); |
| 132 | return; |
| 133 | } |
| 134 | if (ipv6) { |
| 135 | socketAddress6.sin6_family = AF_INET6; |
| 136 | socketAddress6.sin6_port = htons(port); |
| 137 | if (inet_pton(AF_INET6, address.c_str(), &socketAddress6.sin6_addr.s6_addr) != 1) { |
| 138 | if (LOGS_ENABLED) DEBUG_E("connection(%p) bad ipv6 %s", this, address.c_str()); |
| 139 | closeSocket(1, -1); |
| 140 | return; |
| 141 | } |
| 142 | } else { |
| 143 | socketAddress.sin_family = AF_INET; |
| 144 | socketAddress.sin_port = htons(port); |
| 145 | if (inet_pton(AF_INET, address.c_str(), &socketAddress.sin_addr.s_addr) != 1) { |
| 146 | if (LOGS_ENABLED) DEBUG_E("connection(%p) bad ipv4 %s", this, address.c_str()); |
| 147 | closeSocket(1, -1); |
| 148 | return; |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 |
| 153 | int yes = 1; |
| 154 | if (setsockopt(socketFd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(int))) { |
| 155 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set TCP_NODELAY failed", this); |
| 156 | } |
| 157 |
| 158 | if (fcntl(socketFd, F_SETFL, O_NONBLOCK) == -1) { |
| 159 | if (LOGS_ENABLED) DEBUG_E("connection(%p) set O_NONBLOCK failed", this); |
| 160 | closeSocket(1, -1); |
| 161 | return; |
| 162 | } |
| 163 |
| 164 | if (connect(socketFd, (ipv6 ? (sockaddr *) &socketAddress6 : (sockaddr *) &socketAddress), (socklen_t) (ipv6 ? sizeof(sockaddr_in6) : sizeof(sockaddr_in))) == -1 && errno != EINPROGRESS) { |
| 165 | closeSocket(1, -1); |
| 166 | } else { |
| 167 | eventMask.events = EPOLLOUT | EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; |
| 168 | eventMask.data.ptr = eventObject; |
| 169 | if (epoll_ctl(epolFd, EPOLL_CTL_ADD, socketFd, &eventMask) != 0) { |
| 170 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll_ctl, adding socket failed", this); |
| 171 | closeSocket(1, -1); |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 |
| 176 | int32_t ConnectionSocket::checkSocketError(int32_t *error) { |
| 177 | if (socketFd < 0) { |
| 178 | return true; |
| 179 | } |
| 180 | int ret; |
| 181 | int code; |
| 182 | socklen_t len = sizeof(int); |
| 183 | ret = getsockopt(socketFd, SOL_SOCKET, SO_ERROR, &code, &len); |
| 184 | if (ret != 0 || code != 0) { |
| 185 | if (LOGS_ENABLED) DEBUG_E("socket error 0x%x code 0x%x", ret, code); |
| 186 | } |
| 187 | *error = code; |
| 188 | return (ret || code) != 0; |
| 189 | } |
| 190 |
| 191 | void ConnectionSocket::closeSocket(int32_t reason, int32_t error) { |
| 192 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 193 | ConnectionsManager::getInstance(instanceNum).detachConnection(this); |
| 194 | if (socketFd >= 0) { |
| 195 | epoll_ctl(ConnectionsManager::getInstance(instanceNum).epolFd, EPOLL_CTL_DEL, socketFd, NULL); |
| 196 | if (close(socketFd) != 0) { |
| 197 | if (LOGS_ENABLED) DEBUG_E("connection(%p) unable to close socket", this); |
| 198 | } |
| 199 | socketFd = -1; |
| 200 | } |
| 201 | proxyAuthState = 0; |
| 202 | onConnectedSent = false; |
| 203 | outgoingByteStream->clean(); |
| 204 | onDisconnected(reason, error); |
| 205 | } |
| 206 |
| 207 | void ConnectionSocket::onEvent(uint32_t events) { |
| 208 | if (events & EPOLLIN) { |
| 209 | int32_t error; |
| 210 | if (checkSocketError(&error) != 0) { |
| 211 | closeSocket(1, error); |
| 212 | return; |
| 213 | } else { |
| 214 | ssize_t readCount; |
| 215 | NativeByteBuffer *buffer = ConnectionsManager::getInstance(instanceNum).networkBuffer; |
| 216 | while (true) { |
| 217 | buffer->rewind(); |
| 218 | readCount = recv(socketFd, buffer->bytes(), READ_BUFFER_SIZE, 0); |
| 219 | if (readCount < 0) { |
| 220 | closeSocket(1, -1); |
| 221 | if (LOGS_ENABLED) DEBUG_E("connection(%p) recv failed", this); |
| 222 | return; |
| 223 | } |
| 224 | if (readCount > 0) { |
| 225 | buffer->limit((uint32_t) readCount); |
| 226 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 227 | if (proxyAuthState == 2) { |
| 228 | if (readCount == 2) { |
| 229 | uint8_t auth_method = buffer->bytes()[1]; |
| 230 | if (auth_method == 0xff) { |
| 231 | closeSocket(1, -1); |
| 232 | if (LOGS_ENABLED) DEBUG_E("connection(%p) unsupported proxy auth method", this); |
| 233 | } else if (auth_method == 0x02) { |
| 234 | if (LOGS_ENABLED) DEBUG_D("connection(%p) proxy auth required", this); |
| 235 | proxyAuthState = 3; |
| 236 | } else if (auth_method == 0x00) { |
| 237 | proxyAuthState = 5; |
| 238 | } |
| 239 | adjustWriteOp(); |
| 240 | } else { |
| 241 | closeSocket(1, -1); |
| 242 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 2", this); |
| 243 | } |
| 244 | } else if (proxyAuthState == 4) { |
| 245 | if (readCount == 2) { |
| 246 | uint8_t auth_method = buffer->bytes()[1]; |
| 247 | if (auth_method != 0x00) { |
| 248 | closeSocket(1, -1); |
| 249 | if (LOGS_ENABLED) DEBUG_E("connection(%p) auth invalid", this); |
| 250 | } else { |
| 251 | proxyAuthState = 5; |
| 252 | } |
| 253 | adjustWriteOp(); |
| 254 | } else { |
| 255 | closeSocket(1, -1); |
| 256 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 4", this); |
| 257 | } |
| 258 | } else if (proxyAuthState == 6) { |
| 259 | if (readCount > 2) { |
| 260 | uint8_t status = buffer->bytes()[1]; |
| 261 | if (status == 0x00) { |
| 262 | if (LOGS_ENABLED) DEBUG_D("connection(%p) connected via proxy", this); |
| 263 | proxyAuthState = 0; |
| 264 | adjustWriteOp(); |
| 265 | } else { |
| 266 | closeSocket(1, -1); |
| 267 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy status on state 6, 0x%x", this, status); |
| 268 | } |
| 269 | } else { |
| 270 | closeSocket(1, -1); |
| 271 | if (LOGS_ENABLED) DEBUG_E("connection(%p) invalid proxy response on state 6", this); |
| 272 | } |
| 273 | } else if (proxyAuthState == 0) { |
| 274 | if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) { |
| 275 | ConnectionsManager::getInstance(instanceNum).delegate->onBytesReceived((int32_t) readCount, currentNetworkType, instanceNum); |
| 276 | } |
| 277 | onReceivedData(buffer); |
| 278 | } |
| 279 | } |
| 280 | if (readCount != READ_BUFFER_SIZE) { |
| 281 | break; |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | } |
| 286 | if (events & EPOLLOUT) { |
| 287 | int32_t error; |
| 288 | if (checkSocketError(&error) != 0) { |
| 289 | closeSocket(1, error); |
| 290 | return; |
| 291 | } else { |
| 292 | if (proxyAuthState != 0) { |
| 293 | if (proxyAuthState == 1) { |
| 294 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 295 | proxyAuthState = 2; |
| 296 | buffer[0] = 0x05; |
| 297 | buffer[1] = 0x02; |
| 298 | buffer[2] = 0x00; |
| 299 | buffer[3] = 0x02; |
| 300 | if (send(socketFd, buffer, 4, 0) < 0) { |
| 301 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 302 | closeSocket(1, -1); |
| 303 | return; |
| 304 | } |
| 305 | adjustWriteOp(); |
| 306 | } else if (proxyAuthState == 3) { |
| 307 | buffer[0] = 0x01; |
| 308 | std::string *proxyUser; |
| 309 | std::string *proxyPassword; |
| 310 | if (!overrideProxyAddress.empty()) { |
| 311 | proxyUser = &overrideProxyUser; |
| 312 | proxyPassword = &overrideProxyPassword; |
| 313 | } else { |
| 314 | proxyUser = &ConnectionsManager::getInstance(instanceNum).proxyUser; |
| 315 | proxyPassword = &ConnectionsManager::getInstance(instanceNum).proxyPassword; |
| 316 | } |
| 317 | uint8_t len1 = (uint8_t) proxyUser->length(); |
| 318 | uint8_t len2 = (uint8_t) proxyPassword->length(); |
| 319 | buffer[1] = len1; |
| 320 | memcpy(&buffer[2], proxyUser->c_str(), len1); |
| 321 | buffer[2 + len1] = len2; |
| 322 | memcpy(&buffer[3 + len1], proxyPassword->c_str(), len2); |
| 323 | proxyAuthState = 4; |
| 324 | if (send(socketFd, buffer, 3 + len1 + len2, 0) < 0) { |
| 325 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 326 | closeSocket(1, -1); |
| 327 | return; |
| 328 | } |
| 329 | adjustWriteOp(); |
| 330 | } else if (proxyAuthState == 5) { |
| 331 | buffer[0] = 0x05; |
| 332 | buffer[1] = 0x01; |
| 333 | buffer[2] = 0x00; |
| 334 | buffer[3] = (uint8_t) (isIpv6 ? 0x04 : 0x01); |
| 335 | uint16_t networkPort = ntohs(currentPort); |
| 336 | inet_pton(isIpv6 ? AF_INET6 : AF_INET, currentAddress.c_str(), &buffer[4]); |
| 337 | memcpy(&buffer[4 + (isIpv6 ? 16 : 4)], &networkPort, sizeof(uint16_t)); |
| 338 | proxyAuthState = 6; |
| 339 | if (send(socketFd, buffer, 4 + (isIpv6 ? 16 : 4) + 2, 0) < 0) { |
| 340 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 341 | closeSocket(1, -1); |
| 342 | return; |
| 343 | } |
| 344 | adjustWriteOp(); |
| 345 | } |
| 346 | } else { |
| 347 | if (!onConnectedSent) { |
| 348 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 349 | if (LOGS_ENABLED) DEBUG_D("connection(%p) reset last event time, on connect", this); |
| 350 | onConnected(); |
| 351 | onConnectedSent = true; |
| 352 | } |
| 353 | NativeByteBuffer *buffer = ConnectionsManager::getInstance(instanceNum).networkBuffer; |
| 354 | buffer->clear(); |
| 355 | outgoingByteStream->get(buffer); |
| 356 | buffer->flip(); |
| 357 |
| 358 | uint32_t remaining = buffer->remaining(); |
| 359 | if (remaining) { |
| 360 | ssize_t sentLength; |
| 361 | if ((sentLength = send(socketFd, buffer->bytes(), remaining, 0)) < 0) { |
| 362 | if (LOGS_ENABLED) DEBUG_E("connection(%p) send failed", this); |
| 363 | closeSocket(1, -1); |
| 364 | return; |
| 365 | } else { |
| 366 | if (ConnectionsManager::getInstance(instanceNum).delegate != nullptr) { |
| 367 | ConnectionsManager::getInstance(instanceNum).delegate->onBytesSent((int32_t) sentLength, currentNetworkType, instanceNum); |
| 368 | } |
| 369 | outgoingByteStream->discard((uint32_t) sentLength); |
| 370 | adjustWriteOp(); |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | } |
| 375 | } |
| 376 | if (events & EPOLLHUP) { |
| 377 | if (LOGS_ENABLED) DEBUG_E("socket event has EPOLLHUP"); |
| 378 | closeSocket(1, -1); |
| 379 | return; |
| 380 | } else if (events & EPOLLRDHUP) { |
| 381 | if (LOGS_ENABLED) DEBUG_E("socket event has EPOLLRDHUP"); |
| 382 | closeSocket(1, -1); |
| 383 | return; |
| 384 | } |
| 385 | if (events & EPOLLERR) { |
| 386 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll error", this); |
| 387 | return; |
| 388 | } |
| 389 | } |
| 390 |
| 391 | void ConnectionSocket::writeBuffer(uint8_t *data, uint32_t size) { |
| 392 | NativeByteBuffer *buffer = BuffersStorage::getInstance().getFreeBuffer(size); |
| 393 | buffer->writeBytes(data, size); |
| 394 | outgoingByteStream->append(buffer); |
| 395 | adjustWriteOp(); |
| 396 | } |
| 397 |
| 398 | void ConnectionSocket::writeBuffer(NativeByteBuffer *buffer) { |
| 399 | outgoingByteStream->append(buffer); |
| 400 | adjustWriteOp(); |
| 401 | } |
| 402 |
| 403 | void ConnectionSocket::adjustWriteOp() { |
| 404 | eventMask.events = EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; |
| 405 | if (proxyAuthState == 0 && (outgoingByteStream->hasData() || !onConnectedSent) || proxyAuthState == 1 || proxyAuthState == 3 || proxyAuthState == 5) { |
| 406 | eventMask.events |= EPOLLOUT; |
| 407 | } |
| 408 | eventMask.data.ptr = eventObject; |
| 409 | if (epoll_ctl(ConnectionsManager::getInstance(instanceNum).epolFd, EPOLL_CTL_MOD, socketFd, &eventMask) != 0) { |
| 410 | if (LOGS_ENABLED) DEBUG_E("connection(%p) epoll_ctl, modify socket failed", this); |
| 411 | closeSocket(1, -1); |
| 412 | } |
| 413 | } |
| 414 |
| 415 | void ConnectionSocket::setTimeout(time_t time) { |
| 416 | timeout = time; |
| 417 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 418 | if (LOGS_ENABLED) DEBUG_D("connection(%p) set current timeout = %lld", this, (long long) timeout); |
| 419 | } |
| 420 |
| 421 | time_t ConnectionSocket::getTimeout() { |
| 422 | return timeout; |
| 423 | } |
| 424 |
| 425 | void ConnectionSocket::checkTimeout(int64_t now) { |
| 426 | if (timeout != 0 && (now - lastEventTime) > (int64_t) timeout * 1000) { |
| 427 | if (!onConnectedSent || hasPendingRequests()) { |
| 428 | closeSocket(2, 0); |
| 429 | } else { |
| 430 | lastEventTime = ConnectionsManager::getInstance(instanceNum).getCurrentTimeMonotonicMillis(); |
| 431 | if (LOGS_ENABLED) DEBUG_D("connection(%p) reset last event time, no requests", this); |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 |
| 436 | bool ConnectionSocket::isDisconnected() { |
| 437 | return socketFd < 0; |
| 438 | } |
| 439 |
| 440 | void ConnectionSocket::dropConnection() { |
| 441 | closeSocket(0, 0); |
| 442 | } |
| 443 |
| 444 | void ConnectionSocket::setOverrideProxy(std::string address, uint16_t port, std::string username, std::string password, std::string secret) { |
| 445 | overrideProxyAddress = address; |
| 446 | overrideProxyPort = port; |
| 447 | overrideProxyUser = username; |
| 448 | overrideProxyPassword = password; |
| 449 | overrideProxySecret = secret; |
| 450 | } |