SocketCore.cc 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  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 <unistd.h>
  37. #include <cerrno>
  38. #include <cstring>
  39. #ifdef HAVE_LIBGNUTLS
  40. # include <gnutls/x509.h>
  41. #endif // HAVE_LIBGNUTLS
  42. #include "message.h"
  43. #include "a2netcompat.h"
  44. #include "DlRetryEx.h"
  45. #include "DlAbortEx.h"
  46. #include "StringFormat.h"
  47. #include "Util.h"
  48. #include "TimeA2.h"
  49. #include "a2functional.h"
  50. #ifdef ENABLE_SSL
  51. # include "TLSContext.h"
  52. #endif // ENABLE_SSL
  53. #ifndef __MINGW32__
  54. # define SOCKET_ERRNO (errno)
  55. #else
  56. # define SOCKET_ERRNO (WSAGetLastError())
  57. #endif // __MINGW32__
  58. #ifdef __MINGW32__
  59. # define A2_EINPROGRESS WSAEWOULDBLOCK
  60. #else
  61. # define A2_EINPROGRESS EINPROGRESS
  62. #endif // __MINGW32__
  63. #ifdef __MINGW32__
  64. # define CLOSE(X) ::closesocket(X)
  65. #else
  66. # define CLOSE(X) while(close(X) == -1 && errno == EINTR)
  67. #endif // __MINGW32__
  68. namespace aria2 {
  69. #ifdef HAVE_EPOLL
  70. SocketCore::PollMethod SocketCore::_pollMethod = SocketCore::POLL_METHOD_EPOLL;
  71. #else // !HAVE_EPOLL
  72. SocketCore::PollMethod SocketCore::_pollMethod = SocketCore::POLL_METHOD_SELECT;
  73. #endif // !HAVE_EPOLL
  74. int SocketCore::_protocolFamily = AF_UNSPEC;
  75. #ifdef ENABLE_SSL
  76. SharedHandle<TLSContext> SocketCore::_tlsContext;
  77. void SocketCore::setTLSContext(const SharedHandle<TLSContext>& tlsContext)
  78. {
  79. _tlsContext = tlsContext;
  80. }
  81. #endif // ENABLE_SSL
  82. SocketCore::SocketCore(int sockType):_sockType(sockType), sockfd(-1) {
  83. init();
  84. }
  85. SocketCore::SocketCore(sock_t sockfd, int sockType):_sockType(sockType), sockfd(sockfd) {
  86. init();
  87. }
  88. void SocketCore::init()
  89. {
  90. #ifdef HAVE_EPOLL
  91. _epfd = -1;
  92. #endif // HAVE_EPOLL
  93. blocking = true;
  94. secure = 0;
  95. _wantRead = false;
  96. _wantWrite = false;
  97. #ifdef HAVE_LIBSSL
  98. // for SSL
  99. ssl = NULL;
  100. #endif // HAVE_LIBSSL
  101. #ifdef HAVE_LIBGNUTLS
  102. sslSession = NULL;
  103. peekBufMax = 4096;
  104. peekBuf = 0;
  105. peekBufLength = 0;
  106. #endif //HAVE_LIBGNUTLS
  107. }
  108. SocketCore::~SocketCore() {
  109. closeConnection();
  110. #ifdef HAVE_EPOLL
  111. if(_epfd != -1) {
  112. CLOSE(_epfd);
  113. }
  114. #endif // HAVE_EPOLL
  115. #ifdef HAVE_LIBGNUTLS
  116. delete [] peekBuf;
  117. #endif // HAVE_LIBGNUTLS
  118. }
  119. template<typename T>
  120. std::string uitos(T value)
  121. {
  122. std::string str;
  123. if(value == 0) {
  124. str = "0";
  125. return str;
  126. }
  127. while(value) {
  128. char digit = value%10+'0';
  129. str.insert(str.begin(), digit);
  130. value /= 10;
  131. }
  132. return str;
  133. }
  134. void SocketCore::bind(uint16_t port)
  135. {
  136. closeConnection();
  137. struct addrinfo hints;
  138. struct addrinfo* res;
  139. memset(&hints, 0, sizeof(hints));
  140. hints.ai_family = _protocolFamily;
  141. hints.ai_socktype = _sockType;
  142. hints.ai_flags = AI_PASSIVE;
  143. hints.ai_protocol = 0;
  144. int s;
  145. s = getaddrinfo(0, uitos(port).c_str(), &hints, &res);
  146. if(s) {
  147. throw DlAbortEx(StringFormat(EX_SOCKET_BIND, gai_strerror(s)).str());
  148. }
  149. struct addrinfo* rp;
  150. for(rp = res; rp; rp = rp->ai_next) {
  151. sock_t fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  152. if(fd == -1) {
  153. continue;
  154. }
  155. int sockopt = 1;
  156. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (a2_sockopt_t) &sockopt, sizeof(sockopt)) < 0) {
  157. CLOSE(fd);
  158. continue;
  159. }
  160. if(::bind(fd, rp->ai_addr, rp->ai_addrlen) == -1) {
  161. CLOSE(fd);
  162. continue;
  163. }
  164. sockfd = fd;
  165. break;
  166. }
  167. freeaddrinfo(res);
  168. if(sockfd == -1) {
  169. throw DlAbortEx(StringFormat(EX_SOCKET_BIND, "all addresses failed").str());
  170. }
  171. }
  172. void SocketCore::beginListen()
  173. {
  174. if(listen(sockfd, 1) == -1) {
  175. throw DlAbortEx(StringFormat(EX_SOCKET_LISTEN, errorMsg()).str());
  176. }
  177. }
  178. SocketCore* SocketCore::acceptConnection() const
  179. {
  180. struct sockaddr_storage sockaddr;
  181. socklen_t len = sizeof(sockaddr);
  182. sock_t fd;
  183. while((fd = accept(sockfd, reinterpret_cast<struct sockaddr*>(&sockaddr), &len)) == -1 && SOCKET_ERRNO == EINTR);
  184. if(fd == -1) {
  185. throw DlAbortEx(StringFormat(EX_SOCKET_ACCEPT, errorMsg()).str());
  186. }
  187. return new SocketCore(fd, _sockType);
  188. }
  189. void SocketCore::getAddrInfo(std::pair<std::string, uint16_t>& addrinfo) const
  190. {
  191. struct sockaddr_storage sockaddr;
  192. socklen_t len = sizeof(sockaddr);
  193. struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr);
  194. if(getsockname(sockfd, addrp, &len) == -1) {
  195. throw DlAbortEx(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str());
  196. }
  197. addrinfo = Util::getNumericNameInfo(addrp, len);
  198. }
  199. void SocketCore::getPeerInfo(std::pair<std::string, uint16_t>& peerinfo) const
  200. {
  201. struct sockaddr_storage sockaddr;
  202. socklen_t len = sizeof(sockaddr);
  203. struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr);
  204. if(getpeername(sockfd, addrp, &len) == -1) {
  205. throw DlAbortEx(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str());
  206. }
  207. peerinfo = Util::getNumericNameInfo(addrp, len);
  208. }
  209. void SocketCore::establishConnection(const std::string& host, uint16_t port)
  210. {
  211. closeConnection();
  212. struct addrinfo hints;
  213. struct addrinfo* res;
  214. memset(&hints, 0, sizeof(hints));
  215. hints.ai_family = _protocolFamily;
  216. hints.ai_socktype = _sockType;
  217. hints.ai_flags = 0;
  218. hints.ai_protocol = 0;
  219. int s;
  220. s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res);
  221. if(s) {
  222. throw DlAbortEx(StringFormat(EX_RESOLVE_HOSTNAME,
  223. host.c_str(), gai_strerror(s)).str());
  224. }
  225. struct addrinfo* rp;
  226. for(rp = res; rp; rp = rp->ai_next) {
  227. sock_t fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  228. if(fd == -1) {
  229. continue;
  230. }
  231. int sockopt = 1;
  232. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (a2_sockopt_t) &sockopt, sizeof(sockopt)) < 0) {
  233. CLOSE(fd);
  234. continue;
  235. }
  236. sockfd = fd;
  237. // make socket non-blocking mode
  238. setNonBlockingMode();
  239. if(connect(fd, rp->ai_addr, rp->ai_addrlen) == -1 &&
  240. SOCKET_ERRNO != A2_EINPROGRESS) {
  241. CLOSE(sockfd);
  242. sockfd = -1;
  243. continue;
  244. }
  245. // TODO at this point, connection may not be established and it may fail
  246. // later. In such case, next ai_addr should be tried.
  247. break;
  248. }
  249. freeaddrinfo(res);
  250. if(sockfd == -1) {
  251. throw DlAbortEx(StringFormat(EX_SOCKET_CONNECT, host.c_str(),
  252. "all addresses failed").str());
  253. }
  254. }
  255. void SocketCore::setNonBlockingMode()
  256. {
  257. #ifdef __MINGW32__
  258. static u_long flag = 1;
  259. if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) {
  260. throw DlAbortEx(StringFormat(EX_SOCKET_NONBLOCKING, errorMsg()).str());
  261. }
  262. #else
  263. int flags;
  264. while((flags = fcntl(sockfd, F_GETFL, 0)) == -1 && errno == EINTR);
  265. // TODO add error handling
  266. while(fcntl(sockfd, F_SETFL, flags|O_NONBLOCK) == -1 && errno == EINTR);
  267. #endif // __MINGW32__
  268. blocking = false;
  269. }
  270. void SocketCore::setBlockingMode()
  271. {
  272. #ifdef __MINGW32__
  273. static u_long flag = 0;
  274. if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) {
  275. throw DlAbortEx(StringFormat(EX_SOCKET_BLOCKING, errorMsg()).str());
  276. }
  277. #else
  278. int flags;
  279. while((flags = fcntl(sockfd, F_GETFL, 0)) == -1 && errno == EINTR);
  280. // TODO add error handling
  281. while(fcntl(sockfd, F_SETFL, flags&(~O_NONBLOCK)) == -1 && errno == EINTR);
  282. #endif // __MINGW32__
  283. blocking = true;
  284. }
  285. void SocketCore::closeConnection()
  286. {
  287. #ifdef HAVE_LIBSSL
  288. // for SSL
  289. if(secure) {
  290. SSL_shutdown(ssl);
  291. }
  292. #endif // HAVE_LIBSSL
  293. #ifdef HAVE_LIBGNUTLS
  294. if(secure) {
  295. gnutls_bye(sslSession, GNUTLS_SHUT_RDWR);
  296. }
  297. #endif // HAVE_LIBGNUTLS
  298. if(sockfd != -1) {
  299. CLOSE(sockfd);
  300. sockfd = -1;
  301. }
  302. #ifdef HAVE_LIBSSL
  303. // for SSL
  304. if(secure) {
  305. SSL_free(ssl);
  306. }
  307. #endif // HAVE_LIBSSL
  308. #ifdef HAVE_LIBGNUTLS
  309. if(secure) {
  310. gnutls_deinit(sslSession);
  311. }
  312. #endif // HAVE_LIBGNUTLS
  313. }
  314. #ifdef HAVE_EPOLL
  315. void SocketCore::initEPOLL()
  316. {
  317. if((_epfd = epoll_create(1)) == -1) {
  318. throw DlRetryEx(StringFormat("epoll_create failed:%s", errorMsg()).str());
  319. }
  320. memset(&_epEvent, 0, sizeof(struct epoll_event));
  321. _epEvent.events = EPOLLIN|EPOLLOUT;
  322. _epEvent.data.fd = sockfd;
  323. if(epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &_epEvent) == -1) {
  324. throw DlRetryEx(StringFormat("epoll_ctl failed:%s", errorMsg()).str());
  325. }
  326. }
  327. #endif // HAVE_EPOLL
  328. bool SocketCore::isWritable(time_t timeout)
  329. {
  330. #ifdef HAVE_EPOLL
  331. if(_pollMethod == SocketCore::POLL_METHOD_EPOLL) {
  332. if(_epfd == -1) {
  333. initEPOLL();
  334. }
  335. struct epoll_event epEvents[1];
  336. int r;
  337. while((r = epoll_wait(_epfd, epEvents, 1, 0)) == -1 && errno == EINTR);
  338. if(r > 0) {
  339. return epEvents[0].events&(EPOLLOUT|EPOLLHUP|EPOLLERR);
  340. } else if(r == 0) {
  341. return false;
  342. } else {
  343. throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_WRITABLE, errorMsg()).str());
  344. }
  345. } else
  346. #endif // HAVE_EPOLL
  347. if(_pollMethod == SocketCore::POLL_METHOD_SELECT) {
  348. fd_set fds;
  349. FD_ZERO(&fds);
  350. FD_SET(sockfd, &fds);
  351. struct timeval tv;
  352. tv.tv_sec = timeout;
  353. tv.tv_usec = 0;
  354. int r = select(sockfd+1, NULL, &fds, NULL, &tv);
  355. if(r == 1) {
  356. return true;
  357. } else if(r == 0) {
  358. // time out
  359. return false;
  360. } else {
  361. if(SOCKET_ERRNO == A2_EINPROGRESS || SOCKET_ERRNO == EINTR) {
  362. return false;
  363. } else {
  364. throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_WRITABLE, errorMsg()).str());
  365. }
  366. }
  367. } else {
  368. abort();
  369. }
  370. }
  371. bool SocketCore::isReadable(time_t timeout)
  372. {
  373. #ifdef HAVE_LIBGNUTLS
  374. if(secure && peekBufLength > 0) {
  375. return true;
  376. }
  377. #endif // HAVE_LIBGNUTLS
  378. #ifdef HAVE_EPOLL
  379. if(_pollMethod == SocketCore::POLL_METHOD_EPOLL) {
  380. if(_epfd == -1) {
  381. initEPOLL();
  382. }
  383. struct epoll_event epEvents[1];
  384. int r;
  385. while((r = epoll_wait(_epfd, epEvents, 1, 0)) == -1 && errno == EINTR);
  386. if(r > 0) {
  387. return epEvents[0].events&(EPOLLIN|EPOLLHUP|EPOLLERR);
  388. } else if(r == 0) {
  389. return false;
  390. } else {
  391. throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_READABLE, errorMsg()).str());
  392. }
  393. } else
  394. #endif // HAVE_EPOLL
  395. if(_pollMethod == SocketCore::POLL_METHOD_SELECT) {
  396. fd_set fds;
  397. FD_ZERO(&fds);
  398. FD_SET(sockfd, &fds);
  399. struct timeval tv;
  400. tv.tv_sec = timeout;
  401. tv.tv_usec = 0;
  402. int r = select(sockfd+1, &fds, NULL, NULL, &tv);
  403. if(r == 1) {
  404. return true;
  405. } else if(r == 0) {
  406. // time out
  407. return false;
  408. } else {
  409. if(SOCKET_ERRNO == A2_EINPROGRESS || SOCKET_ERRNO == EINTR) {
  410. return false;
  411. } else {
  412. throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_READABLE, errorMsg()).str());
  413. }
  414. }
  415. } else {
  416. abort();
  417. }
  418. }
  419. #ifdef HAVE_LIBSSL
  420. int SocketCore::sslHandleEAGAIN(int ret)
  421. {
  422. int error = SSL_get_error(ssl, ret);
  423. if(error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
  424. ret = 0;
  425. if(error == SSL_ERROR_WANT_READ) {
  426. _wantRead = true;
  427. } else {
  428. _wantWrite = true;
  429. }
  430. }
  431. return ret;
  432. }
  433. #endif // HAVE_LIBSSL
  434. #ifdef HAVE_LIBGNUTLS
  435. void SocketCore::gnutlsRecordCheckDirection()
  436. {
  437. int direction = gnutls_record_get_direction(sslSession);
  438. if(direction == 0) {
  439. _wantRead = true;
  440. } else { // if(direction == 1) {
  441. _wantWrite = true;
  442. }
  443. }
  444. #endif // HAVE_LIBGNUTLS
  445. ssize_t SocketCore::writeData(const char* data, size_t len)
  446. {
  447. ssize_t ret = 0;
  448. _wantRead = false;
  449. _wantWrite = false;
  450. if(!secure) {
  451. while((ret = send(sockfd, data, len, 0)) == -1 && SOCKET_ERRNO == EINTR);
  452. if(ret == -1) {
  453. if(SOCKET_ERRNO == EAGAIN) {
  454. _wantWrite = true;
  455. ret = 0;
  456. } else {
  457. throw DlRetryEx(StringFormat(EX_SOCKET_SEND, errorMsg()).str());
  458. }
  459. }
  460. } else {
  461. #ifdef HAVE_LIBSSL
  462. ret = SSL_write(ssl, data, len);
  463. if(ret == 0) {
  464. throw DlRetryEx
  465. (StringFormat
  466. (EX_SOCKET_SEND, ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
  467. }
  468. if(ret < 0) {
  469. ret = sslHandleEAGAIN(ret);
  470. }
  471. if(ret < 0) {
  472. throw DlRetryEx
  473. (StringFormat
  474. (EX_SOCKET_SEND, ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
  475. }
  476. #endif // HAVE_LIBSSL
  477. #ifdef HAVE_LIBGNUTLS
  478. while((ret = gnutls_record_send(sslSession, data, len)) ==
  479. GNUTLS_E_INTERRUPTED);
  480. if(ret == GNUTLS_E_AGAIN) {
  481. gnutlsRecordCheckDirection();
  482. ret = 0;
  483. } else if(ret < 0) {
  484. throw DlRetryEx(StringFormat(EX_SOCKET_SEND, gnutls_strerror(ret)).str());
  485. }
  486. #endif // HAVE_LIBGNUTLS
  487. }
  488. return ret;
  489. }
  490. void SocketCore::readData(char* data, size_t& len)
  491. {
  492. ssize_t ret = 0;
  493. _wantRead = false;
  494. _wantWrite = false;
  495. if(!secure) {
  496. while((ret = recv(sockfd, data, len, 0)) == -1 && SOCKET_ERRNO == EINTR);
  497. if(ret == -1) {
  498. if(SOCKET_ERRNO == EAGAIN) {
  499. _wantRead = true;
  500. ret = 0;
  501. } else {
  502. throw DlRetryEx(StringFormat(EX_SOCKET_RECV, errorMsg()).str());
  503. }
  504. }
  505. } else {
  506. #ifdef HAVE_LIBSSL
  507. // for SSL
  508. // TODO handling len == 0 case required
  509. ret = SSL_read(ssl, data, len);
  510. if(ret == 0) {
  511. throw DlRetryEx
  512. (StringFormat
  513. (EX_SOCKET_RECV, ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
  514. }
  515. if(ret < 0) {
  516. ret = sslHandleEAGAIN(ret);
  517. }
  518. if(ret < 0) {
  519. throw DlRetryEx
  520. (StringFormat
  521. (EX_SOCKET_RECV, ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
  522. }
  523. #endif // HAVE_LIBSSL
  524. #ifdef HAVE_LIBGNUTLS
  525. ret = gnutlsRecv(data, len);
  526. if(ret == GNUTLS_E_AGAIN) {
  527. gnutlsRecordCheckDirection();
  528. ret = 0;
  529. } else if(ret < 0) {
  530. throw DlRetryEx
  531. (StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str());
  532. }
  533. #endif // HAVE_LIBGNUTLS
  534. }
  535. len = ret;
  536. }
  537. void SocketCore::peekData(char* data, size_t& len)
  538. {
  539. ssize_t ret = 0;
  540. _wantRead = false;
  541. _wantWrite = false;
  542. if(!secure) {
  543. while((ret = recv(sockfd, data, len, MSG_PEEK)) == -1 && SOCKET_ERRNO == EINTR);
  544. if(ret == -1) {
  545. if(SOCKET_ERRNO == EAGAIN) {
  546. _wantRead = true;
  547. ret = 0;
  548. } else {
  549. throw DlRetryEx(StringFormat(EX_SOCKET_PEEK, errorMsg()).str());
  550. }
  551. }
  552. } else {
  553. #ifdef HAVE_LIBSSL
  554. // for SSL
  555. // TODO handling len == 0 case required
  556. ret = SSL_peek(ssl, data, len);
  557. if(ret == 0) {
  558. throw DlRetryEx
  559. (StringFormat(EX_SOCKET_PEEK,
  560. ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
  561. }
  562. if(ret < 0) {
  563. ret = sslHandleEAGAIN(ret);
  564. }
  565. if(ret < 0) {
  566. throw DlRetryEx
  567. (StringFormat(EX_SOCKET_PEEK,
  568. ERR_error_string(SSL_get_error(ssl, ret), 0)).str());
  569. }
  570. #endif // HAVE_LIBSSL
  571. #ifdef HAVE_LIBGNUTLS
  572. ret = gnutlsPeek(data, len);
  573. if(ret == GNUTLS_E_AGAIN) {
  574. gnutlsRecordCheckDirection();
  575. ret = 0;
  576. } else if(ret < 0) {
  577. throw DlRetryEx(StringFormat(EX_SOCKET_PEEK,
  578. gnutls_strerror(ret)).str());
  579. }
  580. #endif // HAVE_LIBGNUTLS
  581. }
  582. len = ret;
  583. }
  584. #ifdef HAVE_LIBGNUTLS
  585. size_t SocketCore::shiftPeekData(char* data, size_t len)
  586. {
  587. if(peekBufLength <= len) {
  588. memcpy(data, peekBuf, peekBufLength);
  589. size_t ret = peekBufLength;
  590. peekBufLength = 0;
  591. return ret;
  592. } else {
  593. memcpy(data, peekBuf, len);
  594. char* temp = new char[peekBufMax];
  595. memcpy(temp, peekBuf+len, peekBufLength-len);
  596. delete [] peekBuf;
  597. peekBuf = temp;
  598. peekBufLength -= len;
  599. return len;
  600. }
  601. }
  602. void SocketCore::addPeekData(char* data, size_t len)
  603. {
  604. if(peekBufLength+len > peekBufMax) {
  605. char* temp = new char[peekBufMax+len];
  606. memcpy(temp, peekBuf, peekBufLength);
  607. delete [] peekBuf;
  608. peekBuf = temp;
  609. peekBufMax = peekBufLength+len;
  610. }
  611. memcpy(peekBuf+peekBufLength, data, len);
  612. peekBufLength += len;
  613. }
  614. static ssize_t GNUTLS_RECORD_RECV_NO_INTERRUPT
  615. (gnutls_session_t sslSession, char* data, size_t len)
  616. {
  617. int ret;
  618. while((ret = gnutls_record_recv(sslSession, data, len)) ==
  619. GNUTLS_E_INTERRUPTED);
  620. if(ret < 0 && ret != GNUTLS_E_AGAIN) {
  621. throw DlRetryEx
  622. (StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str());
  623. }
  624. return ret;
  625. }
  626. ssize_t SocketCore::gnutlsRecv(char* data, size_t len)
  627. {
  628. size_t plen = shiftPeekData(data, len);
  629. if(plen < len) {
  630. ssize_t ret = GNUTLS_RECORD_RECV_NO_INTERRUPT
  631. (sslSession, data+plen, len-plen);
  632. if(ret == GNUTLS_E_AGAIN) {
  633. return GNUTLS_E_AGAIN;
  634. }
  635. return plen+ret;
  636. } else {
  637. return plen;
  638. }
  639. }
  640. ssize_t SocketCore::gnutlsPeek(char* data, size_t len)
  641. {
  642. if(peekBufLength >= len) {
  643. memcpy(data, peekBuf, len);
  644. return len;
  645. } else {
  646. memcpy(data, peekBuf, peekBufLength);
  647. ssize_t ret = GNUTLS_RECORD_RECV_NO_INTERRUPT
  648. (sslSession, data+peekBufLength, len-peekBufLength);
  649. if(ret == GNUTLS_E_AGAIN) {
  650. return GNUTLS_E_AGAIN;
  651. }
  652. addPeekData(data+peekBufLength, ret);
  653. return peekBufLength;
  654. }
  655. }
  656. #endif // HAVE_LIBGNUTLS
  657. void SocketCore::prepareSecureConnection()
  658. {
  659. if(!secure) {
  660. #ifdef HAVE_LIBSSL
  661. // for SSL
  662. ssl = SSL_new(_tlsContext->getSSLCtx());
  663. if(!ssl) {
  664. throw DlAbortEx
  665. (StringFormat(EX_SSL_INIT_FAILURE,
  666. ERR_error_string(ERR_get_error(), 0)).str());
  667. }
  668. if(SSL_set_fd(ssl, sockfd) == 0) {
  669. throw DlAbortEx
  670. (StringFormat(EX_SSL_INIT_FAILURE,
  671. ERR_error_string(ERR_get_error(), 0)).str());
  672. }
  673. #endif // HAVE_LIBSSL
  674. #ifdef HAVE_LIBGNUTLS
  675. const int cert_type_priority[3] = { GNUTLS_CRT_X509,
  676. GNUTLS_CRT_OPENPGP, 0
  677. };
  678. // while we do not support X509 certificate, most web servers require
  679. // X509 stuff.
  680. gnutls_init(&sslSession, GNUTLS_CLIENT);
  681. gnutls_set_default_priority(sslSession);
  682. gnutls_kx_set_priority(sslSession, cert_type_priority);
  683. // put the x509 credentials to the current session
  684. gnutls_credentials_set(sslSession, GNUTLS_CRD_CERTIFICATE,
  685. _tlsContext->getCertCred());
  686. gnutls_transport_set_ptr(sslSession, (gnutls_transport_ptr_t)sockfd);
  687. #endif // HAVE_LIBGNUTLS
  688. secure = 1;
  689. }
  690. }
  691. bool SocketCore::initiateSecureConnection(const std::string& hostname)
  692. {
  693. if(secure == 1) {
  694. _wantRead = false;
  695. _wantWrite = false;
  696. #ifdef HAVE_LIBSSL
  697. int e = SSL_connect(ssl);
  698. if (e <= 0) {
  699. int ssl_error = SSL_get_error(ssl, e);
  700. switch(ssl_error) {
  701. case SSL_ERROR_NONE:
  702. break;
  703. case SSL_ERROR_WANT_READ:
  704. _wantRead = true;
  705. return false;
  706. case SSL_ERROR_WANT_WRITE:
  707. _wantWrite = true;
  708. return false;
  709. case SSL_ERROR_WANT_X509_LOOKUP:
  710. case SSL_ERROR_ZERO_RETURN:
  711. if (blocking) {
  712. throw DlAbortEx
  713. (StringFormat(EX_SSL_CONNECT_ERROR, ssl_error).str());
  714. }
  715. break;
  716. case SSL_ERROR_SYSCALL:
  717. throw DlAbortEx(EX_SSL_IO_ERROR);
  718. case SSL_ERROR_SSL:
  719. throw DlAbortEx(EX_SSL_PROTOCOL_ERROR);
  720. default:
  721. throw DlAbortEx
  722. (StringFormat(EX_SSL_UNKNOWN_ERROR, ssl_error).str());
  723. }
  724. }
  725. if(_tlsContext->peerVerificationEnabled()) {
  726. // verify peer
  727. X509* peerCert = SSL_get_peer_certificate(ssl);
  728. if(!peerCert) {
  729. throw DlAbortEx(MSG_NO_CERT_FOUND);
  730. }
  731. auto_delete<X509*> certDeleter(peerCert, X509_free);
  732. long verifyResult = SSL_get_verify_result(ssl);
  733. if(verifyResult != X509_V_OK) {
  734. throw DlAbortEx
  735. (StringFormat(MSG_CERT_VERIFICATION_FAILED,
  736. X509_verify_cert_error_string(verifyResult)).str());
  737. }
  738. X509_NAME* name = X509_get_subject_name(peerCert);
  739. if(!name) {
  740. throw DlAbortEx("Could not get X509 name object from the certificate.");
  741. }
  742. bool hostnameOK = false;
  743. int lastpos = -1;
  744. while(true) {
  745. lastpos = X509_NAME_get_index_by_NID(name, NID_commonName, lastpos);
  746. if(lastpos == -1) {
  747. break;
  748. }
  749. X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, lastpos);
  750. unsigned char* out;
  751. int outlen = ASN1_STRING_to_UTF8(&out, X509_NAME_ENTRY_get_data(entry));
  752. if(outlen < 0) {
  753. continue;
  754. }
  755. std::string commonName(&out[0], &out[outlen]);
  756. OPENSSL_free(out);
  757. if(commonName == hostname) {
  758. hostnameOK = true;
  759. break;
  760. }
  761. }
  762. if(!hostnameOK) {
  763. throw DlAbortEx(MSG_HOSTNAME_NOT_MATCH);
  764. }
  765. }
  766. #endif // HAVE_LIBSSL
  767. #ifdef HAVE_LIBGNUTLS
  768. int ret = gnutls_handshake(sslSession);
  769. if(ret == GNUTLS_E_AGAIN) {
  770. gnutlsRecordCheckDirection();
  771. return false;
  772. } else if(ret < 0) {
  773. throw DlAbortEx
  774. (StringFormat(EX_SSL_INIT_FAILURE, gnutls_strerror(ret)).str());
  775. }
  776. if(_tlsContext->peerVerificationEnabled()) {
  777. // verify peer
  778. unsigned int status;
  779. ret = gnutls_certificate_verify_peers2(sslSession, &status);
  780. if(ret < 0) {
  781. throw DlAbortEx
  782. (StringFormat("gnutls_certificate_verify_peer2() failed. Cause: %s",
  783. gnutls_strerror(ret)).str());
  784. }
  785. if(status) {
  786. std::string errors;
  787. if(status & GNUTLS_CERT_INVALID) {
  788. errors += " `not signed by known authorities or invalid'";
  789. }
  790. if(status & GNUTLS_CERT_REVOKED) {
  791. errors += " `revoked by its CA'";
  792. }
  793. if(status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
  794. errors += " `issuer is not known'";
  795. }
  796. if(!errors.empty()) {
  797. throw DlAbortEx
  798. (StringFormat(MSG_CERT_VERIFICATION_FAILED, errors.c_str()).str());
  799. }
  800. }
  801. // certificate type: only X509 is allowed.
  802. if(gnutls_certificate_type_get(sslSession) != GNUTLS_CRT_X509) {
  803. throw DlAbortEx("Certificate type is not X509.");
  804. }
  805. unsigned int peerCertsLength;
  806. const gnutls_datum_t* peerCerts = gnutls_certificate_get_peers
  807. (sslSession, &peerCertsLength);
  808. if(!peerCerts) {
  809. throw DlAbortEx(MSG_NO_CERT_FOUND);
  810. }
  811. Time now;
  812. for(unsigned int i = 0; i < peerCertsLength; ++i) {
  813. gnutls_x509_crt_t cert;
  814. ret = gnutls_x509_crt_init(&cert);
  815. if(ret < 0) {
  816. throw DlAbortEx
  817. (StringFormat("gnutls_x509_crt_init() failed. Cause: %s",
  818. gnutls_strerror(ret)).str());
  819. }
  820. auto_delete<gnutls_x509_crt_t> certDeleter
  821. (cert, gnutls_x509_crt_deinit);
  822. ret = gnutls_x509_crt_import(cert, &peerCerts[i], GNUTLS_X509_FMT_DER);
  823. if(ret < 0) {
  824. throw DlAbortEx
  825. (StringFormat("gnutls_x509_crt_import() failed. Cause: %s",
  826. gnutls_strerror(ret)).str());
  827. }
  828. if(i == 0) {
  829. if(!gnutls_x509_crt_check_hostname(cert, hostname.c_str())) {
  830. throw DlAbortEx(MSG_HOSTNAME_NOT_MATCH);
  831. }
  832. }
  833. time_t activationTime = gnutls_x509_crt_get_activation_time(cert);
  834. if(activationTime == -1) {
  835. throw DlAbortEx("Could not get activation time from certificate.");
  836. }
  837. if(now.getTime() < activationTime) {
  838. throw DlAbortEx("Certificate is not activated yet.");
  839. }
  840. time_t expirationTime = gnutls_x509_crt_get_expiration_time(cert);
  841. if(expirationTime == -1) {
  842. throw DlAbortEx("Could not get expiration time from certificate.");
  843. }
  844. if(expirationTime < now.getTime()) {
  845. throw DlAbortEx("Certificate has expired.");
  846. }
  847. }
  848. }
  849. peekBuf = new char[peekBufMax];
  850. #endif // HAVE_LIBGNUTLS
  851. secure = 2;
  852. return true;
  853. } else {
  854. return true;
  855. }
  856. }
  857. /* static */ int SocketCore::error()
  858. {
  859. return SOCKET_ERRNO;
  860. }
  861. /* static */ const char *SocketCore::errorMsg()
  862. {
  863. return errorMsg(SOCKET_ERRNO);
  864. }
  865. /* static */ const char *SocketCore::errorMsg(const int err)
  866. {
  867. #ifndef __MINGW32__
  868. return strerror(err);
  869. #else
  870. static char buf[256];
  871. if (FormatMessage(
  872. FORMAT_MESSAGE_FROM_SYSTEM |
  873. FORMAT_MESSAGE_IGNORE_INSERTS,
  874. NULL,
  875. err,
  876. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  877. (LPTSTR) &buf,
  878. sizeof(buf),
  879. NULL
  880. ) == 0) {
  881. snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, err, err);
  882. }
  883. return buf;
  884. #endif // __MINGW32__
  885. }
  886. ssize_t SocketCore::writeData(const char* data, size_t len,
  887. const std::string& host, uint16_t port)
  888. {
  889. _wantRead = false;
  890. _wantWrite = false;
  891. struct addrinfo hints;
  892. struct addrinfo* res;
  893. memset(&hints, 0, sizeof(hints));
  894. hints.ai_family = _protocolFamily;
  895. hints.ai_socktype = _sockType;
  896. hints.ai_flags = 0;
  897. hints.ai_protocol = 0;
  898. int s;
  899. s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res);
  900. if(s) {
  901. throw DlAbortEx(StringFormat(EX_SOCKET_SEND, gai_strerror(s)).str());
  902. }
  903. struct addrinfo* rp;
  904. ssize_t r = -1;
  905. for(rp = res; rp; rp = rp->ai_next) {
  906. while((r = sendto(sockfd, data, len, 0, rp->ai_addr, rp->ai_addrlen)) == -1 && EINTR == SOCKET_ERRNO);
  907. if(r == static_cast<ssize_t>(len)) {
  908. break;
  909. }
  910. if(r == -1 && SOCKET_ERRNO == EAGAIN) {
  911. _wantWrite = true;
  912. r = 0;
  913. break;
  914. }
  915. }
  916. freeaddrinfo(res);
  917. if(r == -1) {
  918. throw DlAbortEx(StringFormat(EX_SOCKET_SEND, errorMsg()).str());
  919. }
  920. return r;
  921. }
  922. ssize_t SocketCore::readDataFrom(char* data, size_t len,
  923. std::pair<std::string /* numerichost */,
  924. uint16_t /* port */>& sender)
  925. {
  926. _wantRead = false;
  927. _wantWrite = false;
  928. struct sockaddr_storage sockaddr;
  929. socklen_t sockaddrlen = sizeof(struct sockaddr_storage);
  930. struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr);
  931. ssize_t r;
  932. while((r = recvfrom(sockfd, data, len, 0, addrp, &sockaddrlen)) == -1 &&
  933. EINTR == SOCKET_ERRNO);
  934. if(r == -1) {
  935. if(SOCKET_ERRNO == EAGAIN) {
  936. _wantRead = true;
  937. r = 0;
  938. } else {
  939. throw DlRetryEx(StringFormat(EX_SOCKET_RECV, errorMsg()).str());
  940. }
  941. } else {
  942. sender = Util::getNumericNameInfo(addrp, sockaddrlen);
  943. }
  944. return r;
  945. }
  946. std::string SocketCore::getSocketError() const
  947. {
  948. int error;
  949. socklen_t optlen = sizeof(error);
  950. if(getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (a2_sockopt_t) &error, &optlen) == -1) {
  951. throw DlAbortEx(StringFormat("Failed to get socket error: %s",
  952. errorMsg()).str());
  953. }
  954. if(error != 0) {
  955. return errorMsg(error);
  956. } else {
  957. return "";
  958. }
  959. }
  960. bool SocketCore::wantRead() const
  961. {
  962. return _wantRead;
  963. }
  964. bool SocketCore::wantWrite() const
  965. {
  966. return _wantWrite;
  967. }
  968. #ifdef HAVE_EPOLL
  969. void SocketCore::useEpoll()
  970. {
  971. _pollMethod = SocketCore::POLL_METHOD_EPOLL;
  972. }
  973. #endif // HAVE_EPOLL
  974. void SocketCore::useSelect()
  975. {
  976. _pollMethod = SocketCore::POLL_METHOD_SELECT;
  977. }
  978. } // namespace aria2