SocketCore.cc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "SocketCore.h"
  36. #include "DlRetryEx.h"
  37. #include "DlAbortEx.h"
  38. #include "message.h"
  39. #include "a2netcompat.h"
  40. #include "a2time.h"
  41. #include <unistd.h>
  42. #include <fcntl.h>
  43. #include <errno.h>
  44. #ifndef __MINGW32__
  45. # define SOCKET_ERRNO (errno)
  46. #else
  47. # define SOCKET_ERRNO (WSAGetLastError())
  48. #endif // __MINGW32__
  49. SocketCore::SocketCore():sockfd(-1) {
  50. init();
  51. }
  52. SocketCore::SocketCore(int32_t sockfd):sockfd(sockfd) {
  53. init();
  54. }
  55. void SocketCore::init() {
  56. use = 1;
  57. blocking = true;
  58. secure = false;
  59. #ifdef HAVE_LIBSSL
  60. // for SSL
  61. sslCtx = NULL;
  62. ssl = NULL;
  63. #endif // HAVE_LIBSSL
  64. #ifdef HAVE_LIBGNUTLS
  65. sslSession = NULL;
  66. sslXcred = NULL;
  67. peekBufMax = 4096;
  68. peekBuf = new char[peekBufMax];
  69. peekBufLength = 0;
  70. #endif //HAVE_LIBGNUTLS
  71. }
  72. SocketCore::~SocketCore() {
  73. closeConnection();
  74. #ifdef HAVE_LIBGNUTLS
  75. delete [] peekBuf;
  76. #endif // HAVE_LIBGNUTLS
  77. }
  78. void SocketCore::beginListen(int32_t port) {
  79. closeConnection();
  80. //sockfd = socket(AF_UNSPEC, SOCK_STREAM, PF_UNSPEC);
  81. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  82. if(sockfd == -1) {
  83. throw new DlAbortEx(EX_SOCKET_OPEN, errorMsg());
  84. }
  85. SOCKOPT_T sockopt = 1;
  86. if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(socklen_t)) < 0) {
  87. #ifdef __MINGW32__
  88. ::closesocket(sockfd);
  89. #else
  90. close(sockfd);
  91. #endif // __MINGW32__
  92. sockfd = -1;
  93. throw new DlAbortEx(EX_SOCKET_SET_OPT, errorMsg());
  94. }
  95. struct sockaddr_in sockaddr;
  96. memset((char*)&sockaddr, 0, sizeof(sockaddr));
  97. sockaddr.sin_family = AF_INET;
  98. sockaddr.sin_addr.s_addr = INADDR_ANY;
  99. sockaddr.sin_port = htons(port);
  100. if(bind(sockfd, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == -1) {
  101. throw new DlAbortEx(EX_SOCKET_BIND, errorMsg());
  102. }
  103. if(listen(sockfd, 1) == -1) {
  104. throw new DlAbortEx(EX_SOCKET_LISTEN, errorMsg());
  105. }
  106. setNonBlockingMode();
  107. }
  108. SocketCore* SocketCore::acceptConnection() const {
  109. struct sockaddr_in sockaddr;
  110. socklen_t len = sizeof(sockaddr);
  111. memset((char*)&sockaddr, 0, sizeof(sockaddr));
  112. int32_t fd;
  113. if((fd = accept(sockfd, (struct sockaddr*)&sockaddr, &len)) == -1) {
  114. throw new DlAbortEx(EX_SOCKET_ACCEPT, errorMsg());
  115. }
  116. SocketCore* s = new SocketCore(fd);
  117. return s;
  118. }
  119. void SocketCore::getAddrInfo(pair<string, int32_t>& addrinfo) const {
  120. struct sockaddr_in listenaddr;
  121. memset((char*)&listenaddr, 0, sizeof(listenaddr));
  122. socklen_t len = sizeof(listenaddr);
  123. if(getsockname(sockfd, (struct sockaddr*)&listenaddr, &len) == -1) {
  124. throw new DlAbortEx(EX_SOCKET_GET_NAME, errorMsg());
  125. }
  126. addrinfo.first = inet_ntoa(listenaddr.sin_addr);
  127. addrinfo.second = ntohs(listenaddr.sin_port);
  128. }
  129. void SocketCore::getPeerInfo(pair<string, int32_t>& peerinfo) const {
  130. struct sockaddr_in peerin;
  131. memset(&peerin, 0, sizeof(peerin));
  132. int32_t len = sizeof(peerin);
  133. if(getpeername(sockfd, (struct sockaddr*)&peerin, (socklen_t*)&len) < 0) {
  134. throw new DlAbortEx(EX_SOCKET_GET_PEER, errorMsg());
  135. }
  136. peerinfo.first = inet_ntoa(peerin.sin_addr);
  137. peerinfo.second = ntohs(peerin.sin_port);
  138. }
  139. void SocketCore::establishConnection(const string& host, int32_t port) {
  140. closeConnection();
  141. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  142. if(sockfd == -1) {
  143. throw new DlAbortEx(EX_SOCKET_OPEN, errorMsg());
  144. }
  145. SOCKOPT_T sockopt = 1;
  146. if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(socklen_t)) < 0) {
  147. close(sockfd);
  148. sockfd = -1;
  149. throw new DlAbortEx(EX_SOCKET_SET_OPT, errorMsg());
  150. }
  151. struct sockaddr_in sockaddr;
  152. memset((char*)&sockaddr, 0, sizeof(sockaddr));
  153. sockaddr.sin_family = AF_INET;
  154. sockaddr.sin_port = htons(port);
  155. if(inet_aton(host.c_str(), &sockaddr.sin_addr)) {
  156. // ok
  157. } else {
  158. struct addrinfo ai;
  159. memset((char*)&ai, 0, sizeof(ai));
  160. ai.ai_flags = 0;
  161. ai.ai_family = PF_INET;
  162. ai.ai_socktype = SOCK_STREAM;
  163. ai.ai_protocol = 0;
  164. struct addrinfo* res;
  165. int32_t ec;
  166. if((ec = getaddrinfo(host.c_str(), NULL, &ai, &res)) != 0) {
  167. throw new DlAbortEx(EX_RESOLVE_HOSTNAME,
  168. host.c_str(), gai_strerror(ec));
  169. }
  170. sockaddr.sin_addr = ((struct sockaddr_in*)res->ai_addr)->sin_addr;
  171. freeaddrinfo(res);
  172. }
  173. // make socket non-blocking mode
  174. setNonBlockingMode();
  175. if(connect(sockfd, (struct sockaddr*)&sockaddr, (socklen_t)sizeof(sockaddr)) == -1 && SOCKET_ERRNO !=
  176. #ifndef __MINGW32__
  177. EINPROGRESS
  178. #else
  179. WSAEWOULDBLOCK
  180. #endif // __MINGW32__
  181. ) {
  182. throw new DlAbortEx(EX_SOCKET_CONNECT, host.c_str(), errorMsg());
  183. }
  184. }
  185. void SocketCore::setNonBlockingMode() {
  186. #ifdef __MINGW32__
  187. static u_long flag = 1;
  188. if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) {
  189. throw new DlAbortEx(EX_SOCKET_NONBLOCKING, errorMsg());
  190. }
  191. #else
  192. int32_t flags = fcntl(sockfd, F_GETFL, 0);
  193. // TODO add error handling
  194. fcntl(sockfd, F_SETFL, flags|O_NONBLOCK);
  195. #endif // __MINGW32__
  196. blocking = false;
  197. }
  198. void SocketCore::setBlockingMode() {
  199. #ifdef __MINGW32__
  200. static u_long flag = 0;
  201. if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) {
  202. throw new DlAbortEx(EX_SOCKET_BLOCKING, errorMsg());
  203. }
  204. #else
  205. int32_t flags = fcntl(sockfd, F_GETFL, 0);
  206. // TODO add error handling
  207. fcntl(sockfd, F_SETFL, flags&(~O_NONBLOCK));
  208. #endif // __MINGW32__
  209. blocking = true;
  210. }
  211. void SocketCore::closeConnection() {
  212. #ifdef HAVE_LIBSSL
  213. // for SSL
  214. if(secure) {
  215. SSL_shutdown(ssl);
  216. }
  217. #endif // HAVE_LIBSSL
  218. #ifdef HAVE_LIBGNUTLS
  219. if(secure) {
  220. gnutls_bye(sslSession, GNUTLS_SHUT_RDWR);
  221. }
  222. #endif // HAVE_LIBGNUTLS
  223. if(sockfd != -1) {
  224. #ifdef __MINGW32__
  225. ::closesocket(sockfd);
  226. #else
  227. close(sockfd);
  228. #endif // __MINGW32__
  229. sockfd = -1;
  230. }
  231. #ifdef HAVE_LIBSSL
  232. // for SSL
  233. if(secure) {
  234. SSL_free(ssl);
  235. SSL_CTX_free(sslCtx);
  236. }
  237. #endif // HAVE_LIBSSL
  238. #ifdef HAVE_LIBGNUTLS
  239. if(secure) {
  240. gnutls_deinit(sslSession);
  241. gnutls_certificate_free_credentials(sslXcred);
  242. }
  243. #endif // HAVE_LIBGNUTLS
  244. }
  245. bool SocketCore::isWritable(int32_t timeout) const {
  246. fd_set fds;
  247. FD_ZERO(&fds);
  248. FD_SET(sockfd, &fds);
  249. struct timeval tv;
  250. tv.tv_sec = timeout;
  251. tv.tv_usec = 0;
  252. int32_t r = select(sockfd+1, NULL, &fds, NULL, &tv);
  253. if(r == 1) {
  254. return true;
  255. } else if(r == 0) {
  256. // time out
  257. return false;
  258. } else {
  259. if(SOCKET_ERRNO == EINPROGRESS || SOCKET_ERRNO == EINTR) {
  260. return false;
  261. } else {
  262. throw new DlRetryEx(EX_SOCKET_CHECK_WRITABLE, errorMsg());
  263. }
  264. }
  265. }
  266. bool SocketCore::isReadable(int32_t timeout) const {
  267. #ifdef HAVE_LIBGNUTLS
  268. if(secure && peekBufLength > 0) {
  269. return true;
  270. }
  271. #endif // HAVE_LIBGNUTLS
  272. fd_set fds;
  273. FD_ZERO(&fds);
  274. FD_SET(sockfd, &fds);
  275. struct timeval tv;
  276. tv.tv_sec = timeout;
  277. tv.tv_usec = 0;
  278. int32_t r = select(sockfd+1, &fds, NULL, NULL, &tv);
  279. if(r == 1) {
  280. return true;
  281. } else if(r == 0) {
  282. // time out
  283. return false;
  284. } else {
  285. if(SOCKET_ERRNO == EINPROGRESS || SOCKET_ERRNO == EINTR) {
  286. return false;
  287. } else {
  288. throw new DlRetryEx(EX_SOCKET_CHECK_READABLE, errorMsg());
  289. }
  290. }
  291. }
  292. void SocketCore::writeData(const char* data, int32_t len) {
  293. int32_t ret = 0;
  294. if(!secure) {
  295. if((ret = send(sockfd, data, (size_t)len, 0)) != len) {
  296. throw new DlRetryEx(EX_SOCKET_SEND, errorMsg());
  297. }
  298. } else {
  299. #ifdef HAVE_LIBSSL
  300. // for SSL
  301. // TODO handling len == 0 case required
  302. if((ret = SSL_write(ssl, data, len)) != len) {
  303. throw new DlRetryEx(EX_SOCKET_SEND, ERR_error_string(ERR_get_error(), NULL));
  304. }
  305. #endif // HAVE_LIBSSL
  306. #ifdef HAVE_LIBGNUTLS
  307. if((ret = gnutls_record_send(sslSession, data, len)) == len) {
  308. throw new DlRetryEx(EX_SOCKET_SEND, gnutls_strerror(ret));
  309. }
  310. #endif // HAVE_LIBGNUTLS
  311. }
  312. }
  313. void SocketCore::readData(char* data, int32_t& len) {
  314. int32_t ret = 0;
  315. if(!secure) {
  316. if ((ret = recv(sockfd, data, (size_t)len, 0)) < 0) {
  317. throw new DlRetryEx(EX_SOCKET_RECV, errorMsg());
  318. }
  319. } else {
  320. #ifdef HAVE_LIBSSL
  321. // for SSL
  322. // TODO handling len == 0 case required
  323. if ((ret = SSL_read(ssl, data, len)) < 0) {
  324. throw new DlRetryEx(EX_SOCKET_RECV, ERR_error_string(ERR_get_error(), NULL));
  325. }
  326. #endif // HAVE_LIBSSL
  327. #ifdef HAVE_LIBGNUTLS
  328. if ((ret = gnutlsRecv(data, len)) < 0) {
  329. throw new DlRetryEx(EX_SOCKET_RECV, gnutls_strerror(ret));
  330. }
  331. #endif // HAVE_LIBGNUTLS
  332. }
  333. len = ret;
  334. }
  335. void SocketCore::peekData(char* data, int32_t& len) {
  336. int32_t ret = 0;
  337. if(!secure) {
  338. if ((ret = recv(sockfd, data, (size_t)len, MSG_PEEK)) < 0) {
  339. throw new DlRetryEx(EX_SOCKET_PEEK, errorMsg());
  340. }
  341. } else {
  342. #ifdef HAVE_LIBSSL
  343. // for SSL
  344. // TODO handling len == 0 case required
  345. if ((ret = SSL_peek(ssl, data, len)) < 0) {
  346. throw new DlRetryEx(EX_SOCKET_PEEK, ERR_error_string(ERR_get_error(), NULL));
  347. }
  348. #endif // HAVE_LIBSSL
  349. #ifdef HAVE_LIBGNUTLS
  350. if ((ret = gnutlsPeek(data, len)) < 0) {
  351. throw new DlRetryEx(EX_SOCKET_PEEK, gnutls_strerror(ret));
  352. }
  353. #endif // HAVE_LIBGNUTLS
  354. }
  355. len = ret;
  356. }
  357. #ifdef HAVE_LIBGNUTLS
  358. int32_t SocketCore::shiftPeekData(char* data, int32_t len) {
  359. if(peekBufLength <= len) {
  360. memcpy(data, peekBuf, peekBufLength);
  361. int32_t ret = peekBufLength;
  362. peekBufLength = 0;
  363. return ret;
  364. } else {
  365. memcpy(data, peekBuf, len);
  366. char* temp = new char[peekBufMax];
  367. memcpy(temp, peekBuf+len, peekBufLength-len);
  368. delete [] peekBuf;
  369. peekBuf = temp;
  370. peekBufLength -= len;
  371. return len;
  372. }
  373. }
  374. void SocketCore::addPeekData(char* data, int32_t len) {
  375. if(peekBufLength+len > peekBufMax) {
  376. char* temp = new char[peekBufMax+len];
  377. memcpy(temp, peekBuf, peekBufLength);
  378. delete [] peekBuf;
  379. peekBuf = temp;
  380. peekBufMax = peekBufLength+len;
  381. }
  382. memcpy(peekBuf+peekBufLength, data, len);
  383. peekBufLength += len;
  384. }
  385. int32_t SocketCore::gnutlsRecv(char* data, int32_t len) {
  386. int32_t plen = shiftPeekData(data, len);
  387. if(plen < len) {
  388. int32_t ret = gnutls_record_recv(sslSession, data+plen, len-plen);
  389. if(ret < 0) {
  390. throw new DlRetryEx(EX_SOCKET_RECV, gnutls_strerror(ret));
  391. }
  392. return plen+ret;
  393. } else {
  394. return plen;
  395. }
  396. }
  397. int32_t SocketCore::gnutlsPeek(char* data, int32_t len) {
  398. if(peekBufLength >= len) {
  399. memcpy(data, peekBuf, len);
  400. return len;
  401. } else {
  402. memcpy(data, peekBuf, peekBufLength);
  403. int32_t ret = gnutls_record_recv(sslSession, data+peekBufLength, len-peekBufLength);
  404. if(ret < 0) {
  405. throw new DlRetryEx(EX_SOCKET_PEEK, gnutls_strerror(ret));
  406. }
  407. addPeekData(data+peekBufLength, ret);
  408. return peekBufLength;
  409. }
  410. }
  411. #endif // HAVE_LIBGNUTLS
  412. void SocketCore::initiateSecureConnection() {
  413. #ifdef HAVE_LIBSSL
  414. // for SSL
  415. if(!secure) {
  416. sslCtx = SSL_CTX_new(SSLv23_client_method());
  417. if(sslCtx == NULL) {
  418. throw new DlAbortEx(EX_SSL_INIT_FAILURE, ERR_error_string(ERR_get_error(), NULL));
  419. }
  420. SSL_CTX_set_mode(sslCtx, SSL_MODE_AUTO_RETRY);
  421. ssl = SSL_new(sslCtx);
  422. if(ssl == NULL) {
  423. throw new DlAbortEx(EX_SSL_INIT_FAILURE, ERR_error_string(ERR_get_error(), NULL));
  424. }
  425. if(SSL_set_fd(ssl, sockfd) == 0) {
  426. throw new DlAbortEx(EX_SSL_INIT_FAILURE, ERR_error_string(ERR_get_error(), NULL));
  427. }
  428. // TODO handling return value == 0 case required
  429. int e = SSL_connect(ssl);
  430. if (e <= 0) {
  431. int ssl_error = SSL_get_error(ssl, e);
  432. switch(ssl_error) {
  433. case SSL_ERROR_NONE:
  434. break;
  435. case SSL_ERROR_WANT_READ:
  436. case SSL_ERROR_WANT_WRITE:
  437. case SSL_ERROR_WANT_X509_LOOKUP:
  438. case SSL_ERROR_ZERO_RETURN:
  439. if (blocking) {
  440. throw new DlAbortEx(EX_SSL_CONNECT_ERROR, ssl_error);
  441. }
  442. break;
  443. case SSL_ERROR_SYSCALL:
  444. throw new DlAbortEx(EX_SSL_IO_ERROR);
  445. case SSL_ERROR_SSL:
  446. throw new DlAbortEx(EX_SSL_PROTOCOL_ERROR);
  447. default:
  448. throw new DlAbortEx(EX_SSL_UNKNOWN_ERROR, ssl_error);
  449. }
  450. }
  451. }
  452. #endif // HAVE_LIBSSL
  453. #ifdef HAVE_LIBGNUTLS
  454. if(!secure) {
  455. const int32_t cert_type_priority[3] = { GNUTLS_CRT_X509,
  456. GNUTLS_CRT_OPENPGP, 0
  457. };
  458. // while we do not support X509 certificate, most web servers require
  459. // X509 stuff.
  460. gnutls_certificate_allocate_credentials (&sslXcred);
  461. gnutls_init(&sslSession, GNUTLS_CLIENT);
  462. gnutls_set_default_priority(sslSession);
  463. gnutls_kx_set_priority(sslSession, cert_type_priority);
  464. // put the x509 credentials to the current session
  465. gnutls_credentials_set(sslSession, GNUTLS_CRD_CERTIFICATE, sslXcred);
  466. gnutls_transport_set_ptr(sslSession, (gnutls_transport_ptr_t)sockfd);
  467. int32_t ret = gnutls_handshake(sslSession);
  468. if(ret < 0) {
  469. throw new DlAbortEx(EX_SSL_INIT_FAILURE, gnutls_strerror(ret));
  470. }
  471. }
  472. #endif // HAVE_LIBGNUTLS
  473. secure = true;
  474. }
  475. /* static */ int SocketCore::error() {
  476. return SOCKET_ERRNO;
  477. }
  478. /* static */ const char *SocketCore::errorMsg() {
  479. return errorMsg(SOCKET_ERRNO);
  480. }
  481. /* static */ const char *SocketCore::errorMsg(const int err) {
  482. #ifndef __MINGW32__
  483. return strerror(err);
  484. #else
  485. static char buf[256];
  486. if (FormatMessage(
  487. FORMAT_MESSAGE_FROM_SYSTEM |
  488. FORMAT_MESSAGE_IGNORE_INSERTS,
  489. NULL,
  490. err,
  491. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  492. (LPTSTR) &buf,
  493. sizeof(buf),
  494. NULL
  495. ) == 0) {
  496. snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, err, err);
  497. }
  498. return buf;
  499. #endif // __MINGW32__
  500. }