SocketCore.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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 "message.h"
  37. #include "a2netcompat.h"
  38. #include "DlRetryEx.h"
  39. #include "DlAbortEx.h"
  40. #include "StringFormat.h"
  41. #include "Util.h"
  42. #include <unistd.h>
  43. #include <cerrno>
  44. #include <cstring>
  45. #ifndef __MINGW32__
  46. # define SOCKET_ERRNO (errno)
  47. #else
  48. # define SOCKET_ERRNO (WSAGetLastError())
  49. #endif // __MINGW32__
  50. #ifdef __MINGW32__
  51. # define A2_EINPROGRESS WSAEWOULDBLOCK
  52. #else
  53. # define A2_EINPROGRESS EINPROGRESS
  54. #endif // __MINGW32__
  55. #ifdef __MINGW32__
  56. # define CLOSE(X) ::closesocket(sockfd)
  57. #else
  58. # define CLOSE(X) while(close(X) == -1 && errno == EINTR)
  59. #endif // __MINGW32__
  60. namespace aria2 {
  61. SocketCore::SocketCore(int sockType):_sockType(sockType), sockfd(-1) {
  62. init();
  63. }
  64. SocketCore::SocketCore(int sockfd, int sockType):_sockType(sockType), sockfd(sockfd) {
  65. init();
  66. }
  67. void SocketCore::init()
  68. {
  69. blocking = true;
  70. secure = false;
  71. #ifdef HAVE_LIBSSL
  72. // for SSL
  73. sslCtx = NULL;
  74. ssl = NULL;
  75. #endif // HAVE_LIBSSL
  76. #ifdef HAVE_LIBGNUTLS
  77. sslSession = NULL;
  78. sslXcred = NULL;
  79. peekBufMax = 4096;
  80. peekBuf = 0;
  81. peekBufLength = 0;
  82. #endif //HAVE_LIBGNUTLS
  83. }
  84. SocketCore::~SocketCore() {
  85. closeConnection();
  86. #ifdef HAVE_LIBGNUTLS
  87. delete [] peekBuf;
  88. #endif // HAVE_LIBGNUTLS
  89. }
  90. template<typename T>
  91. std::string uitos(T value)
  92. {
  93. std::string str;
  94. if(value == 0) {
  95. str = "0";
  96. return str;
  97. }
  98. while(value) {
  99. char digit = value%10+'0';
  100. str.insert(str.begin(), digit);
  101. value /= 10;
  102. }
  103. return str;
  104. }
  105. void SocketCore::bind(uint16_t port)
  106. {
  107. closeConnection();
  108. struct addrinfo hints;
  109. struct addrinfo* res;
  110. memset(&hints, 0, sizeof(hints));
  111. hints.ai_family = AF_UNSPEC;
  112. hints.ai_socktype = _sockType;
  113. hints.ai_flags = AI_PASSIVE;
  114. hints.ai_protocol = 0;
  115. int s;
  116. s = getaddrinfo(0, uitos(port).c_str(), &hints, &res);
  117. if(s) {
  118. throw DlAbortEx(StringFormat(EX_SOCKET_BIND, gai_strerror(s)).str());
  119. }
  120. struct addrinfo* rp;
  121. for(rp = res; rp; rp = rp->ai_next) {
  122. int fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  123. if(fd == -1) {
  124. continue;
  125. }
  126. SOCKOPT_T sockopt = 1;
  127. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(socklen_t)) < 0) {
  128. CLOSE(fd);
  129. continue;
  130. }
  131. if(::bind(fd, rp->ai_addr, rp->ai_addrlen) == -1) {
  132. CLOSE(fd);
  133. continue;
  134. }
  135. sockfd = fd;
  136. break;
  137. }
  138. freeaddrinfo(res);
  139. if(sockfd == -1) {
  140. throw DlAbortEx(StringFormat(EX_SOCKET_BIND, "all addresses failed").str());
  141. }
  142. }
  143. void SocketCore::beginListen()
  144. {
  145. if(listen(sockfd, 1) == -1) {
  146. throw DlAbortEx(StringFormat(EX_SOCKET_LISTEN, errorMsg()).str());
  147. }
  148. }
  149. SocketCore* SocketCore::acceptConnection() const
  150. {
  151. struct sockaddr_storage sockaddr;
  152. socklen_t len = sizeof(sockaddr);
  153. int fd;
  154. while((fd = accept(sockfd, reinterpret_cast<struct sockaddr*>(&sockaddr), &len)) == -1 && errno == EINTR);
  155. if(fd == -1) {
  156. throw DlAbortEx(StringFormat(EX_SOCKET_ACCEPT, errorMsg()).str());
  157. }
  158. return new SocketCore(fd, _sockType);
  159. }
  160. void SocketCore::getAddrInfo(std::pair<std::string, uint16_t>& addrinfo) const
  161. {
  162. struct sockaddr_storage sockaddr;
  163. socklen_t len = sizeof(sockaddr);
  164. struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr);
  165. if(getsockname(sockfd, addrp, &len) == -1) {
  166. throw DlAbortEx(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str());
  167. }
  168. addrinfo = Util::getNumericNameInfo(addrp, len);
  169. }
  170. void SocketCore::getPeerInfo(std::pair<std::string, uint16_t>& peerinfo) const
  171. {
  172. struct sockaddr_storage sockaddr;
  173. socklen_t len = sizeof(sockaddr);
  174. struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr);
  175. if(getpeername(sockfd, addrp, &len) == -1) {
  176. throw DlAbortEx(StringFormat(EX_SOCKET_GET_NAME, errorMsg()).str());
  177. }
  178. peerinfo = Util::getNumericNameInfo(addrp, len);
  179. }
  180. void SocketCore::establishConnection(const std::string& host, uint16_t port)
  181. {
  182. closeConnection();
  183. struct addrinfo hints;
  184. struct addrinfo* res;
  185. memset(&hints, 0, sizeof(hints));
  186. hints.ai_family = AF_UNSPEC;
  187. hints.ai_socktype = _sockType;
  188. hints.ai_flags = 0;
  189. hints.ai_protocol = 0;
  190. int s;
  191. s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res);
  192. if(s) {
  193. throw DlAbortEx(StringFormat(EX_RESOLVE_HOSTNAME,
  194. host.c_str(), gai_strerror(s)).str());
  195. }
  196. struct addrinfo* rp;
  197. for(rp = res; rp; rp = rp->ai_next) {
  198. int fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  199. if(fd == -1) {
  200. continue;
  201. }
  202. SOCKOPT_T sockopt = 1;
  203. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(socklen_t)) < 0) {
  204. CLOSE(fd);
  205. continue;
  206. }
  207. sockfd = fd;
  208. // make socket non-blocking mode
  209. setNonBlockingMode();
  210. if(connect(fd, rp->ai_addr, rp->ai_addrlen) == -1 &&
  211. SOCKET_ERRNO != A2_EINPROGRESS) {
  212. CLOSE(sockfd);
  213. sockfd = -1;
  214. continue;
  215. }
  216. // TODO at this point, connection may not be established and it may fail
  217. // later. In such case, next ai_addr should be tried.
  218. break;
  219. }
  220. freeaddrinfo(res);
  221. if(sockfd == -1) {
  222. throw DlAbortEx(StringFormat(EX_SOCKET_CONNECT, host.c_str(),
  223. "all addresses failed").str());
  224. }
  225. }
  226. void SocketCore::setNonBlockingMode()
  227. {
  228. #ifdef __MINGW32__
  229. static u_long flag = 1;
  230. if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) {
  231. throw DlAbortEx(StringFormat(EX_SOCKET_NONBLOCKING, errorMsg()).str());
  232. }
  233. #else
  234. int flags;
  235. while((flags = fcntl(sockfd, F_GETFL, 0)) == -1 && errno == EINTR);
  236. // TODO add error handling
  237. while(fcntl(sockfd, F_SETFL, flags|O_NONBLOCK) == -1 && errno == EINTR);
  238. #endif // __MINGW32__
  239. blocking = false;
  240. }
  241. void SocketCore::setBlockingMode()
  242. {
  243. #ifdef __MINGW32__
  244. static u_long flag = 0;
  245. if (::ioctlsocket(sockfd, FIONBIO, &flag) == -1) {
  246. throw DlAbortEx(StringFormat(EX_SOCKET_BLOCKING, errorMsg()).str());
  247. }
  248. #else
  249. int flags;
  250. while((flags = fcntl(sockfd, F_GETFL, 0)) == -1 && errno == EINTR);
  251. // TODO add error handling
  252. while(fcntl(sockfd, F_SETFL, flags&(~O_NONBLOCK)) == -1 && errno == EINTR);
  253. #endif // __MINGW32__
  254. blocking = true;
  255. }
  256. void SocketCore::closeConnection()
  257. {
  258. #ifdef HAVE_LIBSSL
  259. // for SSL
  260. if(secure) {
  261. SSL_shutdown(ssl);
  262. }
  263. #endif // HAVE_LIBSSL
  264. #ifdef HAVE_LIBGNUTLS
  265. if(secure) {
  266. gnutls_bye(sslSession, GNUTLS_SHUT_RDWR);
  267. }
  268. #endif // HAVE_LIBGNUTLS
  269. if(sockfd != -1) {
  270. CLOSE(sockfd);
  271. sockfd = -1;
  272. }
  273. #ifdef HAVE_LIBSSL
  274. // for SSL
  275. if(secure) {
  276. SSL_free(ssl);
  277. SSL_CTX_free(sslCtx);
  278. }
  279. #endif // HAVE_LIBSSL
  280. #ifdef HAVE_LIBGNUTLS
  281. if(secure) {
  282. gnutls_deinit(sslSession);
  283. gnutls_certificate_free_credentials(sslXcred);
  284. }
  285. #endif // HAVE_LIBGNUTLS
  286. }
  287. bool SocketCore::isWritable(time_t timeout) const
  288. {
  289. fd_set fds;
  290. FD_ZERO(&fds);
  291. FD_SET(sockfd, &fds);
  292. struct timeval tv;
  293. tv.tv_sec = timeout;
  294. tv.tv_usec = 0;
  295. int r = select(sockfd+1, NULL, &fds, NULL, &tv);
  296. if(r == 1) {
  297. return true;
  298. } else if(r == 0) {
  299. // time out
  300. return false;
  301. } else {
  302. if(SOCKET_ERRNO == EINPROGRESS || SOCKET_ERRNO == EINTR) {
  303. return false;
  304. } else {
  305. throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_WRITABLE, errorMsg()).str());
  306. }
  307. }
  308. }
  309. bool SocketCore::isReadable(time_t timeout) const
  310. {
  311. #ifdef HAVE_LIBGNUTLS
  312. if(secure && peekBufLength > 0) {
  313. return true;
  314. }
  315. #endif // HAVE_LIBGNUTLS
  316. fd_set fds;
  317. FD_ZERO(&fds);
  318. FD_SET(sockfd, &fds);
  319. struct timeval tv;
  320. tv.tv_sec = timeout;
  321. tv.tv_usec = 0;
  322. int r = select(sockfd+1, &fds, NULL, NULL, &tv);
  323. if(r == 1) {
  324. return true;
  325. } else if(r == 0) {
  326. // time out
  327. return false;
  328. } else {
  329. if(SOCKET_ERRNO == EINPROGRESS || SOCKET_ERRNO == EINTR) {
  330. return false;
  331. } else {
  332. throw DlRetryEx(StringFormat(EX_SOCKET_CHECK_READABLE, errorMsg()).str());
  333. }
  334. }
  335. }
  336. void SocketCore::writeData(const char* data, size_t len)
  337. {
  338. ssize_t ret = 0;
  339. if(!secure) {
  340. while((ret = send(sockfd, data, len, 0)) == -1 && errno == EINTR);
  341. // TODO assuming Blocking mode.
  342. if(ret == -1 || (size_t)ret != len) {
  343. throw DlRetryEx(StringFormat(EX_SOCKET_SEND, errorMsg()).str());
  344. }
  345. } else {
  346. #ifdef HAVE_LIBSSL
  347. // for SSL
  348. // TODO handling len == 0 case required
  349. ret = SSL_write(ssl, data, len);
  350. if(ret <= 0 || (size_t)ret != len) {
  351. throw DlRetryEx(StringFormat(EX_SOCKET_SEND, ERR_error_string(ERR_get_error(), NULL)).str());
  352. }
  353. #endif // HAVE_LIBSSL
  354. #ifdef HAVE_LIBGNUTLS
  355. ret = gnutls_record_send(sslSession, data, len);
  356. if(ret < 0 || (size_t)ret != len) {
  357. throw DlRetryEx(StringFormat(EX_SOCKET_SEND, gnutls_strerror(ret)).str());
  358. }
  359. #endif // HAVE_LIBGNUTLS
  360. }
  361. }
  362. void SocketCore::readData(char* data, size_t& len)
  363. {
  364. ssize_t ret = 0;
  365. if(!secure) {
  366. while((ret = recv(sockfd, data, len, 0)) == -1 && errno == EINTR);
  367. if(ret == -1) {
  368. throw DlRetryEx(StringFormat(EX_SOCKET_RECV, errorMsg()).str());
  369. }
  370. } else {
  371. #ifdef HAVE_LIBSSL
  372. // for SSL
  373. // TODO handling len == 0 case required
  374. if ((ret = SSL_read(ssl, data, len)) <= 0) {
  375. throw DlRetryEx
  376. (StringFormat(EX_SOCKET_RECV,
  377. ERR_error_string(ERR_get_error(), 0)).str());
  378. }
  379. #endif // HAVE_LIBSSL
  380. #ifdef HAVE_LIBGNUTLS
  381. if ((ret = gnutlsRecv(data, len)) < 0) {
  382. throw DlRetryEx
  383. (StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str());
  384. }
  385. #endif // HAVE_LIBGNUTLS
  386. }
  387. len = ret;
  388. }
  389. void SocketCore::peekData(char* data, size_t& len)
  390. {
  391. ssize_t ret = 0;
  392. if(!secure) {
  393. while((ret = recv(sockfd, data, len, MSG_PEEK)) == -1 && errno == EINTR);
  394. if(ret == -1) {
  395. throw DlRetryEx(StringFormat(EX_SOCKET_PEEK, errorMsg()).str());
  396. }
  397. } else {
  398. #ifdef HAVE_LIBSSL
  399. // for SSL
  400. // TODO handling len == 0 case required
  401. if ((ret = SSL_peek(ssl, data, len)) < 0) {
  402. throw DlRetryEx
  403. (StringFormat(EX_SOCKET_PEEK,
  404. ERR_error_string(ERR_get_error(), 0)).str());
  405. }
  406. #endif // HAVE_LIBSSL
  407. #ifdef HAVE_LIBGNUTLS
  408. if ((ret = gnutlsPeek(data, len)) < 0) {
  409. throw DlRetryEx(StringFormat(EX_SOCKET_PEEK,
  410. gnutls_strerror(ret)).str());
  411. }
  412. #endif // HAVE_LIBGNUTLS
  413. }
  414. len = ret;
  415. }
  416. #ifdef HAVE_LIBGNUTLS
  417. size_t SocketCore::shiftPeekData(char* data, size_t len)
  418. {
  419. if(peekBufLength <= len) {
  420. memcpy(data, peekBuf, peekBufLength);
  421. size_t ret = peekBufLength;
  422. peekBufLength = 0;
  423. return ret;
  424. } else {
  425. memcpy(data, peekBuf, len);
  426. char* temp = new char[peekBufMax];
  427. memcpy(temp, peekBuf+len, peekBufLength-len);
  428. delete [] peekBuf;
  429. peekBuf = temp;
  430. peekBufLength -= len;
  431. return len;
  432. }
  433. }
  434. void SocketCore::addPeekData(char* data, size_t len)
  435. {
  436. if(peekBufLength+len > peekBufMax) {
  437. char* temp = new char[peekBufMax+len];
  438. memcpy(temp, peekBuf, peekBufLength);
  439. delete [] peekBuf;
  440. peekBuf = temp;
  441. peekBufMax = peekBufLength+len;
  442. }
  443. memcpy(peekBuf+peekBufLength, data, len);
  444. peekBufLength += len;
  445. }
  446. ssize_t SocketCore::gnutlsRecv(char* data, size_t len)
  447. {
  448. size_t plen = shiftPeekData(data, len);
  449. if(plen < len) {
  450. ssize_t ret = gnutls_record_recv(sslSession, data+plen, len-plen);
  451. if(ret < 0) {
  452. throw DlRetryEx(StringFormat(EX_SOCKET_RECV, gnutls_strerror(ret)).str());
  453. }
  454. return plen+ret;
  455. } else {
  456. return plen;
  457. }
  458. }
  459. ssize_t SocketCore::gnutlsPeek(char* data, size_t len)
  460. {
  461. if(peekBufLength >= len) {
  462. memcpy(data, peekBuf, len);
  463. return len;
  464. } else {
  465. memcpy(data, peekBuf, peekBufLength);
  466. ssize_t ret = gnutls_record_recv(sslSession, data+peekBufLength, len-peekBufLength);
  467. if(ret < 0) {
  468. throw DlRetryEx(StringFormat(EX_SOCKET_PEEK, gnutls_strerror(ret)).str());
  469. }
  470. addPeekData(data+peekBufLength, ret);
  471. return peekBufLength;
  472. }
  473. }
  474. #endif // HAVE_LIBGNUTLS
  475. void SocketCore::initiateSecureConnection()
  476. {
  477. #ifdef HAVE_LIBSSL
  478. // for SSL
  479. if(!secure) {
  480. sslCtx = SSL_CTX_new(SSLv23_client_method());
  481. if(sslCtx == NULL) {
  482. throw DlAbortEx
  483. (StringFormat(EX_SSL_INIT_FAILURE,
  484. ERR_error_string(ERR_get_error(), 0)).str());
  485. }
  486. SSL_CTX_set_mode(sslCtx, SSL_MODE_AUTO_RETRY);
  487. ssl = SSL_new(sslCtx);
  488. if(ssl == NULL) {
  489. throw DlAbortEx
  490. (StringFormat(EX_SSL_INIT_FAILURE,
  491. ERR_error_string(ERR_get_error(), 0)).str());
  492. }
  493. if(SSL_set_fd(ssl, sockfd) == 0) {
  494. throw DlAbortEx
  495. (StringFormat(EX_SSL_INIT_FAILURE,
  496. ERR_error_string(ERR_get_error(), 0)).str());
  497. }
  498. // TODO handling return value == 0 case required
  499. int e = SSL_connect(ssl);
  500. if (e <= 0) {
  501. int ssl_error = SSL_get_error(ssl, e);
  502. switch(ssl_error) {
  503. case SSL_ERROR_NONE:
  504. break;
  505. case SSL_ERROR_WANT_READ:
  506. case SSL_ERROR_WANT_WRITE:
  507. case SSL_ERROR_WANT_X509_LOOKUP:
  508. case SSL_ERROR_ZERO_RETURN:
  509. if (blocking) {
  510. throw DlAbortEx
  511. (StringFormat(EX_SSL_CONNECT_ERROR, ssl_error).str());
  512. }
  513. break;
  514. case SSL_ERROR_SYSCALL:
  515. throw DlAbortEx(EX_SSL_IO_ERROR);
  516. case SSL_ERROR_SSL:
  517. throw DlAbortEx(EX_SSL_PROTOCOL_ERROR);
  518. default:
  519. throw DlAbortEx
  520. (StringFormat(EX_SSL_UNKNOWN_ERROR, ssl_error).str());
  521. }
  522. }
  523. }
  524. #endif // HAVE_LIBSSL
  525. #ifdef HAVE_LIBGNUTLS
  526. if(!secure) {
  527. const int cert_type_priority[3] = { GNUTLS_CRT_X509,
  528. GNUTLS_CRT_OPENPGP, 0
  529. };
  530. // while we do not support X509 certificate, most web servers require
  531. // X509 stuff.
  532. gnutls_certificate_allocate_credentials (&sslXcred);
  533. gnutls_init(&sslSession, GNUTLS_CLIENT);
  534. gnutls_set_default_priority(sslSession);
  535. gnutls_kx_set_priority(sslSession, cert_type_priority);
  536. // put the x509 credentials to the current session
  537. gnutls_credentials_set(sslSession, GNUTLS_CRD_CERTIFICATE, sslXcred);
  538. gnutls_transport_set_ptr(sslSession, (gnutls_transport_ptr_t)sockfd);
  539. int ret = gnutls_handshake(sslSession);
  540. if(ret < 0) {
  541. throw DlAbortEx
  542. (StringFormat(EX_SSL_INIT_FAILURE, gnutls_strerror(ret)).str());
  543. }
  544. peekBuf = new char[peekBufMax];
  545. }
  546. #endif // HAVE_LIBGNUTLS
  547. secure = true;
  548. }
  549. /* static */ int SocketCore::error()
  550. {
  551. return SOCKET_ERRNO;
  552. }
  553. /* static */ const char *SocketCore::errorMsg()
  554. {
  555. return errorMsg(SOCKET_ERRNO);
  556. }
  557. /* static */ const char *SocketCore::errorMsg(const int err)
  558. {
  559. #ifndef __MINGW32__
  560. return strerror(err);
  561. #else
  562. static char buf[256];
  563. if (FormatMessage(
  564. FORMAT_MESSAGE_FROM_SYSTEM |
  565. FORMAT_MESSAGE_IGNORE_INSERTS,
  566. NULL,
  567. err,
  568. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  569. (LPTSTR) &buf,
  570. sizeof(buf),
  571. NULL
  572. ) == 0) {
  573. snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, err, err);
  574. }
  575. return buf;
  576. #endif // __MINGW32__
  577. }
  578. void SocketCore::writeData(const char* data, size_t len, const std::string& host, uint16_t port)
  579. {
  580. struct addrinfo hints;
  581. struct addrinfo* res;
  582. memset(&hints, 0, sizeof(hints));
  583. hints.ai_family = AF_UNSPEC;
  584. hints.ai_socktype = _sockType;
  585. hints.ai_flags = 0;
  586. hints.ai_protocol = 0;
  587. int s;
  588. s = getaddrinfo(host.c_str(), uitos(port).c_str(), &hints, &res);
  589. if(s) {
  590. throw DlAbortEx(StringFormat(EX_SOCKET_SEND, gai_strerror(s)).str());
  591. }
  592. struct addrinfo* rp;
  593. ssize_t r = -1;
  594. for(rp = res; rp; rp = rp->ai_next) {
  595. while((r = sendto(sockfd, data, len, 0, rp->ai_addr, rp->ai_addrlen)) == -1 && EINTR == errno);
  596. if(r == static_cast<ssize_t>(len)) {
  597. break;
  598. }
  599. }
  600. freeaddrinfo(res);
  601. if(r == -1) {
  602. throw DlAbortEx(StringFormat(EX_SOCKET_SEND, errorMsg()).str());
  603. }
  604. }
  605. ssize_t SocketCore::readDataFrom(char* data, size_t len,
  606. std::pair<std::string /* numerichost */,
  607. uint16_t /* port */>& sender)
  608. {
  609. struct sockaddr_storage sockaddr;
  610. socklen_t sockaddrlen = sizeof(struct sockaddr_storage);
  611. struct sockaddr* addrp = reinterpret_cast<struct sockaddr*>(&sockaddr);
  612. ssize_t r;
  613. while((r = recvfrom(sockfd, data, len, 0, addrp, &sockaddrlen)) == -1 &&
  614. EINTR == errno);
  615. if(r == -1) {
  616. throw DlAbortEx(StringFormat(EX_SOCKET_RECV, errorMsg()).str());
  617. }
  618. sender = Util::getNumericNameInfo(addrp, sockaddrlen);
  619. return r;
  620. }
  621. } // namespace aria2