SocketCore.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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 <unistd.h>
  40. #include <fcntl.h>
  41. #include <netdb.h>
  42. #include <sys/types.h>
  43. #include <sys/socket.h>
  44. #include <netinet/in.h>
  45. #include <arpa/inet.h>
  46. #include <sys/time.h>
  47. #include <netdb.h>
  48. #include <errno.h>
  49. SocketCore::SocketCore():sockfd(-1) {
  50. init();
  51. }
  52. SocketCore::SocketCore(int sockfd):sockfd(sockfd) {
  53. init();
  54. }
  55. void SocketCore::init() {
  56. use = 1;
  57. secure = false;
  58. #ifdef HAVE_LIBSSL
  59. // for SSL
  60. sslCtx = NULL;
  61. ssl = NULL;
  62. #endif // HAVE_LIBSSL
  63. #ifdef HAVE_LIBGNUTLS
  64. sslSession = NULL;
  65. sslXcred = NULL;
  66. peekBufMax = 4096;
  67. peekBuf = new char[peekBufMax];
  68. peekBufLength = 0;
  69. #endif //HAVE_LIBGNUTLS
  70. }
  71. SocketCore::~SocketCore() {
  72. closeConnection();
  73. #ifdef HAVE_LIBGNUTLS
  74. delete [] peekBuf;
  75. #endif // HAVE_LIBGNUTLS
  76. }
  77. void SocketCore::beginListen(int port) {
  78. closeConnection();
  79. //sockfd = socket(AF_UNSPEC, SOCK_STREAM, PF_UNSPEC);
  80. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  81. if(sockfd == -1) {
  82. throw new DlAbortEx(EX_SOCKET_OPEN, strerror(errno));
  83. }
  84. socklen_t sockopt = 1;
  85. if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(socklen_t)) < 0) {
  86. close(sockfd);
  87. sockfd = -1;
  88. throw new DlAbortEx(EX_SOCKET_SET_OPT, strerror(errno));
  89. }
  90. struct sockaddr_in sockaddr;
  91. memset((char*)&sockaddr, 0, sizeof(sockaddr));
  92. sockaddr.sin_family = AF_INET;
  93. sockaddr.sin_addr.s_addr = INADDR_ANY;
  94. sockaddr.sin_port = htons(port);
  95. if(bind(sockfd, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == -1) {
  96. throw new DlAbortEx(EX_SOCKET_BIND, strerror(errno));
  97. }
  98. if(listen(sockfd, 1) == -1) {
  99. throw new DlAbortEx(EX_SOCKET_LISTEN, strerror(errno));
  100. }
  101. setNonBlockingMode();
  102. }
  103. SocketCore* SocketCore::acceptConnection() const {
  104. struct sockaddr_in sockaddr;
  105. socklen_t len = sizeof(sockaddr);
  106. memset((char*)&sockaddr, 0, sizeof(sockaddr));
  107. int fd;
  108. if((fd = accept(sockfd, (struct sockaddr*)&sockaddr, &len)) == -1) {
  109. throw new DlAbortEx(EX_SOCKET_ACCEPT, strerror(errno));
  110. }
  111. SocketCore* s = new SocketCore(fd);
  112. return s;
  113. }
  114. void SocketCore::getAddrInfo(pair<string, int>& addrinfo) const {
  115. struct sockaddr_in listenaddr;
  116. memset((char*)&listenaddr, 0, sizeof(listenaddr));
  117. socklen_t len = sizeof(listenaddr);
  118. if(getsockname(sockfd, (struct sockaddr*)&listenaddr, &len) == -1) {
  119. throw new DlAbortEx(EX_SOCKET_GET_NAME, strerror(errno));
  120. }
  121. addrinfo.first = inet_ntoa(listenaddr.sin_addr);
  122. addrinfo.second = ntohs(listenaddr.sin_port);
  123. }
  124. void SocketCore::getPeerInfo(pair<string, int>& peerinfo) const {
  125. struct sockaddr_in peerin;
  126. memset(&peerin, 0, sizeof(peerin));
  127. int len = sizeof(peerin);
  128. if(getpeername(sockfd, (struct sockaddr*)&peerin, (socklen_t*)&len) < 0) {
  129. throw new DlAbortEx(EX_SOCKET_GET_PEER, strerror(errno));
  130. }
  131. peerinfo.first = inet_ntoa(peerin.sin_addr);
  132. peerinfo.second = ntohs(peerin.sin_port);
  133. }
  134. void SocketCore::establishConnection(const string& host, int port) {
  135. closeConnection();
  136. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  137. if(sockfd == -1) {
  138. throw new DlAbortEx(EX_SOCKET_OPEN, strerror(errno));
  139. }
  140. socklen_t sockopt = 1;
  141. if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &sockopt, sizeof(socklen_t)) < 0) {
  142. close(sockfd);
  143. sockfd = -1;
  144. throw new DlAbortEx(EX_SOCKET_SET_OPT, strerror(errno));
  145. }
  146. struct sockaddr_in sockaddr;
  147. memset((char*)&sockaddr, 0, sizeof(sockaddr));
  148. sockaddr.sin_family = AF_INET;
  149. sockaddr.sin_port = htons(port);
  150. if(inet_aton(host.c_str(), &sockaddr.sin_addr)) {
  151. // ok
  152. } else {
  153. struct addrinfo ai;
  154. memset((char*)&ai, 0, sizeof(ai));
  155. ai.ai_flags = 0;
  156. ai.ai_family = PF_INET;
  157. ai.ai_socktype = SOCK_STREAM;
  158. ai.ai_protocol = 0;
  159. struct addrinfo* res;
  160. int ec;
  161. if((ec = getaddrinfo(host.c_str(), NULL, &ai, &res)) != 0) {
  162. throw new DlAbortEx(EX_RESOLVE_HOSTNAME,
  163. host.c_str(), gai_strerror(ec));
  164. }
  165. sockaddr.sin_addr = ((struct sockaddr_in*)res->ai_addr)->sin_addr;
  166. freeaddrinfo(res);
  167. }
  168. // make socket non-blocking mode
  169. setNonBlockingMode();
  170. if(connect(sockfd, (struct sockaddr*)&sockaddr, (socklen_t)sizeof(sockaddr)) == -1 && errno != EINPROGRESS) {
  171. throw new DlAbortEx(EX_SOCKET_CONNECT, host.c_str(), strerror(errno));
  172. }
  173. }
  174. void SocketCore::setNonBlockingMode() const {
  175. int flags = fcntl(sockfd, F_GETFL, 0);
  176. // TODO add error handling
  177. fcntl(sockfd, F_SETFL, flags|O_NONBLOCK);
  178. }
  179. void SocketCore::setBlockingMode() const {
  180. int flags = fcntl(sockfd, F_GETFL, 0);
  181. // TODO add error handling
  182. fcntl(sockfd, F_SETFL, flags&(~O_NONBLOCK));
  183. }
  184. void SocketCore::closeConnection() {
  185. #ifdef HAVE_LIBSSL
  186. // for SSL
  187. if(secure) {
  188. SSL_shutdown(ssl);
  189. }
  190. #endif // HAVE_LIBSSL
  191. #ifdef HAVE_LIBGNUTLS
  192. if(secure) {
  193. gnutls_bye(sslSession, GNUTLS_SHUT_RDWR);
  194. }
  195. #endif // HAVE_LIBGNUTLS
  196. if(sockfd != -1) {
  197. close(sockfd);
  198. sockfd = -1;
  199. }
  200. #ifdef HAVE_LIBSSL
  201. // for SSL
  202. if(secure) {
  203. SSL_free(ssl);
  204. SSL_CTX_free(sslCtx);
  205. }
  206. #endif // HAVE_LIBSSL
  207. #ifdef HAVE_LIBGNUTLS
  208. if(secure) {
  209. gnutls_deinit(sslSession);
  210. gnutls_certificate_free_credentials(sslXcred);
  211. }
  212. #endif // HAVE_LIBGNUTLS
  213. }
  214. bool SocketCore::isWritable(int timeout) const {
  215. fd_set fds;
  216. FD_ZERO(&fds);
  217. FD_SET(sockfd, &fds);
  218. struct timeval tv;
  219. tv.tv_sec = timeout;
  220. tv.tv_usec = 0;
  221. int r = select(sockfd+1, NULL, &fds, NULL, &tv);
  222. if(r == 1) {
  223. return true;
  224. } else if(r == 0) {
  225. // time out
  226. return false;
  227. } else {
  228. if(errno == EINPROGRESS || errno == EINTR) {
  229. return false;
  230. } else {
  231. throw new DlRetryEx(EX_SOCKET_CHECK_WRITABLE, strerror(errno));
  232. }
  233. }
  234. }
  235. bool SocketCore::isReadable(int timeout) const {
  236. #ifdef HAVE_LIBGNUTLS
  237. if(secure && peekBufLength > 0) {
  238. return true;
  239. }
  240. #endif // HAVE_LIBGNUTLS
  241. fd_set fds;
  242. FD_ZERO(&fds);
  243. FD_SET(sockfd, &fds);
  244. struct timeval tv;
  245. tv.tv_sec = timeout;
  246. tv.tv_usec = 0;
  247. int r = select(sockfd+1, &fds, NULL, NULL, &tv);
  248. if(r == 1) {
  249. return true;
  250. } else if(r == 0) {
  251. // time out
  252. return false;
  253. } else {
  254. if(errno == EINPROGRESS || errno == EINTR) {
  255. return false;
  256. } else {
  257. throw new DlRetryEx(EX_SOCKET_CHECK_READABLE, strerror(errno));
  258. }
  259. }
  260. }
  261. void SocketCore::writeData(const char* data, int len) {
  262. int ret = 0;
  263. if(!secure && (ret = send(sockfd, data, (size_t)len, 0)) != len
  264. #ifdef HAVE_LIBSSL
  265. // for SSL
  266. // TODO handling len == 0 case required
  267. || secure && (ret = SSL_write(ssl, data, len)) != len
  268. #endif // HAVE_LIBSSL
  269. #ifdef HAVE_LIBGNUTLS
  270. || secure && (ret = gnutls_record_send(sslSession, data, len)) != len
  271. #endif // HAVE_LIBGNUTLS
  272. ) {
  273. const char* errorMsg;
  274. #ifdef HAVE_LIBGNUTLS
  275. if(secure) {
  276. errorMsg = gnutls_strerror(ret);
  277. } else {
  278. errorMsg = strerror(errno);
  279. }
  280. #else // HAVE_LIBGNUTLS
  281. errorMsg = strerror(errno);
  282. #endif
  283. throw new DlRetryEx(EX_SOCKET_SEND, errorMsg);
  284. }
  285. }
  286. void SocketCore::readData(char* data, int& len) {
  287. int ret = 0;
  288. if(!secure && (ret = recv(sockfd, data, (size_t)len, 0)) < 0
  289. #ifdef HAVE_LIBSSL
  290. // for SSL
  291. // TODO handling len == 0 case required
  292. || secure && (ret = SSL_read(ssl, data, len)) < 0
  293. #endif // HAVE_LIBSSL
  294. #ifdef HAVE_LIBGNUTLS
  295. || secure && (ret = gnutlsRecv(data, len)) < 0
  296. #endif // HAVE_LIBGNUTLS
  297. ) {
  298. const char* errorMsg;
  299. #ifdef HAVE_LIBGNUTLS
  300. if(secure) {
  301. errorMsg = gnutls_strerror(ret);
  302. } else {
  303. errorMsg = strerror(errno);
  304. }
  305. #else // HAVE_LIBGNUTLS
  306. errorMsg = strerror(errno);
  307. #endif
  308. throw new DlRetryEx(EX_SOCKET_RECV, errorMsg);
  309. }
  310. len = ret;
  311. }
  312. void SocketCore::peekData(char* data, int& len) {
  313. int ret = 0;
  314. if(!secure && (ret = recv(sockfd, data, (size_t)len, MSG_PEEK)) < 0
  315. #ifdef HAVE_LIBSSL
  316. // for SSL
  317. // TODO handling len == 0 case required
  318. || secure && (ret = SSL_peek(ssl, data, len)) < 0
  319. #endif // HAVE_LIBSSL
  320. #ifdef HAVE_LIBGNUTLS
  321. || secure && (ret = gnutlsPeek(data, len)) < 0
  322. #endif // HAVE_LIBGNUTLS
  323. ) {
  324. const char* errorMsg;
  325. #ifdef HAVE_LIBGNUTLS
  326. if(secure) {
  327. errorMsg = gnutls_strerror(ret);
  328. } else {
  329. errorMsg = strerror(errno);
  330. }
  331. #else // HAVE_LIBGNUTLS
  332. errorMsg = strerror(errno);
  333. #endif
  334. throw new DlRetryEx(EX_SOCKET_PEEK, errorMsg);
  335. }
  336. len = ret;
  337. }
  338. #ifdef HAVE_LIBGNUTLS
  339. int SocketCore::shiftPeekData(char* data, int len) {
  340. if(peekBufLength <= len) {
  341. memcpy(data, peekBuf, peekBufLength);
  342. int ret = peekBufLength;
  343. peekBufLength = 0;
  344. return ret;
  345. } else {
  346. memcpy(data, peekBuf, len);
  347. char* temp = new char[peekBufMax];
  348. memcpy(temp, peekBuf+len, peekBufLength-len);
  349. delete [] peekBuf;
  350. peekBuf = temp;
  351. peekBufLength -= len;
  352. return len;
  353. }
  354. }
  355. void SocketCore::addPeekData(char* data, int len) {
  356. if(peekBufLength+len > peekBufMax) {
  357. char* temp = new char[peekBufMax+len];
  358. memcpy(temp, peekBuf, peekBufLength);
  359. delete [] peekBuf;
  360. peekBuf = temp;
  361. peekBufMax = peekBufLength+len;
  362. }
  363. memcpy(peekBuf+peekBufLength, data, len);
  364. peekBufLength += len;
  365. }
  366. int SocketCore::gnutlsRecv(char* data, int len) {
  367. int plen = shiftPeekData(data, len);
  368. if(plen < len) {
  369. int ret = gnutls_record_recv(sslSession, data+plen, len-plen);
  370. if(ret < 0) {
  371. throw new DlRetryEx(EX_SOCKET_RECV, gnutls_strerror(ret));
  372. }
  373. return plen+ret;
  374. } else {
  375. return plen;
  376. }
  377. }
  378. int SocketCore::gnutlsPeek(char* data, int len) {
  379. if(peekBufLength >= len) {
  380. memcpy(data, peekBuf, len);
  381. return len;
  382. } else {
  383. memcpy(data, peekBuf, peekBufLength);
  384. int ret = gnutls_record_recv(sslSession, data+peekBufLength, len-peekBufLength);
  385. if(ret < 0) {
  386. throw new DlRetryEx(EX_SOCKET_PEEK, gnutls_strerror(ret));
  387. }
  388. addPeekData(data+peekBufLength, ret);
  389. return peekBufLength;
  390. }
  391. }
  392. #endif // HAVE_LIBGNUTLS
  393. void SocketCore::initiateSecureConnection() {
  394. #ifdef HAVE_LIBSSL
  395. // for SSL
  396. if(!secure) {
  397. sslCtx = SSL_CTX_new(SSLv23_client_method());
  398. if(sslCtx == NULL) {
  399. throw new DlAbortEx(EX_SSL_INIT_FAILURE);
  400. }
  401. SSL_CTX_set_mode(sslCtx, SSL_MODE_AUTO_RETRY);
  402. ssl = SSL_new(sslCtx);
  403. if(ssl == NULL) {
  404. throw new DlAbortEx(EX_SSL_INIT_FAILURE);
  405. }
  406. if(SSL_set_fd(ssl, sockfd) == 0) {
  407. throw new DlAbortEx(EX_SSL_INIT_FAILURE);
  408. }
  409. // TODO handling return value == 0 case required
  410. if(SSL_connect(ssl) <= 0) {
  411. throw new DlAbortEx(EX_SSL_INIT_FAILURE);
  412. }
  413. secure = true;
  414. }
  415. #endif // HAVE_LIBSSL
  416. #ifdef HAVE_LIBGNUTLS
  417. if(!secure) {
  418. const int cert_type_priority[3] = { GNUTLS_CRT_X509,
  419. GNUTLS_CRT_OPENPGP, 0
  420. };
  421. // while we do not support X509 certificate, most web servers require
  422. // X509 stuff.
  423. gnutls_certificate_allocate_credentials (&sslXcred);
  424. gnutls_init(&sslSession, GNUTLS_CLIENT);
  425. gnutls_set_default_priority(sslSession);
  426. gnutls_kx_set_priority(sslSession, cert_type_priority);
  427. // put the x509 credentials to the current session
  428. gnutls_credentials_set(sslSession, GNUTLS_CRD_CERTIFICATE, sslXcred);
  429. gnutls_transport_set_ptr(sslSession, (gnutls_transport_ptr_t)sockfd);
  430. int ret = gnutls_handshake(sslSession);
  431. if(ret < 0) {
  432. throw new DlAbortEx(gnutls_strerror(ret));
  433. }
  434. secure = true;
  435. }
  436. #endif // HAVE_LIBGNUTLS
  437. }