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