SocketCore.cc 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  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. #ifdef HAVE_IFADDRS_H
  38. # include <ifaddrs.h>
  39. #endif // HAVE_IFADDRS_H
  40. #include <cerrno>
  41. #include <cstring>
  42. #ifdef HAVE_OPENSSL
  43. # include <openssl/x509.h>
  44. # include <openssl/x509v3.h>
  45. #endif // HAVE_OPENSSL
  46. #ifdef HAVE_LIBGNUTLS
  47. # include <gnutls/x509.h>
  48. #endif // HAVE_LIBGNUTLS
  49. #include "message.h"
  50. #include "DlRetryEx.h"
  51. #include "DlAbortEx.h"
  52. #include "fmt.h"
  53. #include "util.h"
  54. #include "TimeA2.h"
  55. #include "a2functional.h"
  56. #include "LogFactory.h"
  57. #include "A2STR.h"
  58. #ifdef ENABLE_SSL
  59. # include "TLSContext.h"
  60. #endif // ENABLE_SSL
  61. namespace aria2 {
  62. #ifndef __MINGW32__
  63. # define SOCKET_ERRNO (errno)
  64. #else
  65. # define SOCKET_ERRNO (WSAGetLastError())
  66. #endif // __MINGW32__
  67. #ifdef __MINGW32__
  68. # define A2_EINPROGRESS WSAEWOULDBLOCK
  69. # define A2_EWOULDBLOCK WSAEWOULDBLOCK
  70. # define A2_EINTR WSAEINTR
  71. # define A2_WOULDBLOCK(e) (e == WSAEWOULDBLOCK)
  72. #else // !__MINGW32__
  73. # define A2_EINPROGRESS EINPROGRESS
  74. # ifndef EWOULDBLOCK
  75. # define EWOULDBLOCK EAGAIN
  76. # endif // EWOULDBLOCK
  77. # define A2_EWOULDBLOCK EWOULDBLOCK
  78. # define A2_EINTR EINTR
  79. # if EWOULDBLOCK == EAGAIN
  80. # define A2_WOULDBLOCK(e) (e == EWOULDBLOCK)
  81. # else // EWOULDBLOCK != EAGAIN
  82. # define A2_WOULDBLOCK(e) (e == EWOULDBLOCK || e == EAGAIN)
  83. # endif // EWOULDBLOCK != EAGAIN
  84. #endif // !__MINGW32__
  85. #ifdef __MINGW32__
  86. # define CLOSE(X) ::closesocket(X)
  87. #else
  88. # define CLOSE(X) close(X)
  89. #endif // __MINGW32__
  90. namespace {
  91. std::string errorMsg(int errNum)
  92. {
  93. #ifndef __MINGW32__
  94. return util::safeStrerror(errNum);
  95. #else
  96. static char buf[256];
  97. if (FormatMessage(
  98. FORMAT_MESSAGE_FROM_SYSTEM |
  99. FORMAT_MESSAGE_IGNORE_INSERTS,
  100. NULL,
  101. errNum,
  102. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
  103. (LPTSTR) &buf,
  104. sizeof(buf),
  105. NULL
  106. ) == 0) {
  107. snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, errNum, errNum);
  108. }
  109. return buf;
  110. #endif // __MINGW32__
  111. }
  112. } // namespace
  113. namespace {
  114. enum TlsState {
  115. // TLS object is not initialized.
  116. A2_TLS_NONE = 0,
  117. // TLS object is now handshaking.
  118. A2_TLS_HANDSHAKING = 2,
  119. // TLS object is now connected.
  120. A2_TLS_CONNECTED = 3
  121. };
  122. } // namespace
  123. int SocketCore::protocolFamily_ = AF_UNSPEC;
  124. std::vector<std::pair<sockaddr_union, socklen_t> >
  125. SocketCore::bindAddrs_;
  126. #ifdef ENABLE_SSL
  127. SharedHandle<TLSContext> SocketCore::clTlsContext_;
  128. SharedHandle<TLSContext> SocketCore::svTlsContext_;
  129. void SocketCore::setClientTLSContext
  130. (const SharedHandle<TLSContext>& tlsContext)
  131. {
  132. clTlsContext_ = tlsContext;
  133. }
  134. void SocketCore::setServerTLSContext
  135. (const SharedHandle<TLSContext>& tlsContext)
  136. {
  137. svTlsContext_ = tlsContext;
  138. }
  139. #endif // ENABLE_SSL
  140. SocketCore::SocketCore(int sockType)
  141. : sockType_(sockType),
  142. sockfd_(-1)
  143. {
  144. init();
  145. }
  146. SocketCore::SocketCore(sock_t sockfd, int sockType)
  147. : sockType_(sockType),
  148. sockfd_(sockfd)
  149. {
  150. init();
  151. }
  152. void SocketCore::init()
  153. {
  154. blocking_ = true;
  155. secure_ = A2_TLS_NONE;
  156. wantRead_ = false;
  157. wantWrite_ = false;
  158. #ifdef HAVE_OPENSSL
  159. // for SSL
  160. ssl = NULL;
  161. #endif // HAVE_OPENSSL
  162. #ifdef HAVE_LIBGNUTLS
  163. sslSession_ = 0;
  164. #endif //HAVE_LIBGNUTLS
  165. }
  166. SocketCore::~SocketCore() {
  167. closeConnection();
  168. }
  169. void SocketCore::create(int family, int protocol)
  170. {
  171. int errNum;
  172. closeConnection();
  173. sock_t fd = socket(family, sockType_, protocol);
  174. errNum = SOCKET_ERRNO;
  175. if(fd == (sock_t) -1) {
  176. throw DL_ABORT_EX
  177. (fmt("Failed to create socket. Cause:%s", errorMsg(errNum).c_str()));
  178. }
  179. int sockopt = 1;
  180. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
  181. (a2_sockopt_t) &sockopt, sizeof(sockopt)) < 0) {
  182. errNum = SOCKET_ERRNO;
  183. CLOSE(fd);
  184. throw DL_ABORT_EX
  185. (fmt("Failed to create socket. Cause:%s", errorMsg(errNum).c_str()));
  186. }
  187. sockfd_ = fd;
  188. }
  189. static sock_t bindInternal
  190. (int family, int socktype, int protocol,
  191. const struct sockaddr* addr, socklen_t addrlen,
  192. std::string& error)
  193. {
  194. int errNum;
  195. sock_t fd = socket(family, socktype, protocol);
  196. errNum = SOCKET_ERRNO;
  197. if(fd == (sock_t) -1) {
  198. error = errorMsg(errNum);
  199. return -1;
  200. }
  201. int sockopt = 1;
  202. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (a2_sockopt_t) &sockopt,
  203. sizeof(sockopt)) < 0) {
  204. errNum = SOCKET_ERRNO;
  205. error = errorMsg(errNum);
  206. CLOSE(fd);
  207. return -1;
  208. }
  209. #ifdef IPV6_V6ONLY
  210. if(family == AF_INET6) {
  211. int sockopt = 1;
  212. if(setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (a2_sockopt_t) &sockopt,
  213. sizeof(sockopt)) < 0) {
  214. errNum = SOCKET_ERRNO;
  215. error = errorMsg(errNum);
  216. CLOSE(fd);
  217. return -1;
  218. }
  219. }
  220. #endif // IPV6_V6ONLY
  221. if(::bind(fd, addr, addrlen) == -1) {
  222. errNum = SOCKET_ERRNO;
  223. error = errorMsg(errNum);
  224. CLOSE(fd);
  225. return -1;
  226. }
  227. return fd;
  228. }
  229. static sock_t bindTo
  230. (const char* host, uint16_t port, int family, int sockType,
  231. int getaddrinfoFlags, std::string& error)
  232. {
  233. struct addrinfo* res;
  234. int s = callGetaddrinfo(&res, host, util::uitos(port).c_str(),
  235. family, sockType, getaddrinfoFlags, 0);
  236. if(s) {
  237. error = gai_strerror(s);
  238. return -1;
  239. }
  240. WSAAPI_AUTO_DELETE<struct addrinfo*> resDeleter(res, freeaddrinfo);
  241. struct addrinfo* rp;
  242. for(rp = res; rp; rp = rp->ai_next) {
  243. sock_t fd = bindInternal(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
  244. rp->ai_addr, rp->ai_addrlen, error);
  245. if(fd != (sock_t)-1) {
  246. return fd;
  247. }
  248. }
  249. return -1;
  250. }
  251. void SocketCore::bindWithFamily(uint16_t port, int family, int flags)
  252. {
  253. closeConnection();
  254. std::string error;
  255. sock_t fd = bindTo(0, port, family, sockType_, flags, error);
  256. if(fd == (sock_t) -1) {
  257. throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
  258. } else {
  259. sockfd_ = fd;
  260. }
  261. }
  262. void SocketCore::bind
  263. (const char* addr, uint16_t port, int family, int flags)
  264. {
  265. closeConnection();
  266. std::string error;
  267. const char* addrp;
  268. if(addr && addr[0]) {
  269. addrp = addr;
  270. } else {
  271. addrp = 0;
  272. }
  273. if(!(flags&AI_PASSIVE) || bindAddrs_.empty()) {
  274. sock_t fd = bindTo(addrp, port, family, sockType_, flags, error);
  275. if(fd != (sock_t) -1) {
  276. sockfd_ = fd;
  277. }
  278. } else {
  279. for(std::vector<std::pair<sockaddr_union, socklen_t> >::
  280. const_iterator i = bindAddrs_.begin(), eoi = bindAddrs_.end();
  281. i != eoi; ++i) {
  282. char host[NI_MAXHOST];
  283. int s;
  284. s = getnameinfo(&(*i).first.sa, (*i).second, host, NI_MAXHOST, 0, 0,
  285. NI_NUMERICHOST);
  286. if(s) {
  287. error = gai_strerror(s);
  288. continue;
  289. }
  290. if(addrp && strcmp(host, addrp) != 0) {
  291. error = "Given address and resolved address do not match.";
  292. continue;
  293. }
  294. sock_t fd = bindTo(host, port, family, sockType_, flags, error);
  295. if(fd != (sock_t)-1) {
  296. sockfd_ = fd;
  297. break;
  298. }
  299. }
  300. }
  301. if(sockfd_ == (sock_t) -1) {
  302. throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
  303. }
  304. }
  305. void SocketCore::bind(uint16_t port, int flags)
  306. {
  307. bind(0, port, protocolFamily_, flags);
  308. }
  309. void SocketCore::bind(const struct sockaddr* addr, socklen_t addrlen)
  310. {
  311. closeConnection();
  312. std::string error;
  313. sock_t fd = bindInternal(addr->sa_family, sockType_, 0, addr, addrlen, error);
  314. if(fd != (sock_t)-1) {
  315. sockfd_ = fd;
  316. } else {
  317. throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
  318. }
  319. }
  320. void SocketCore::beginListen()
  321. {
  322. if(listen(sockfd_, 1) == -1) {
  323. int errNum = SOCKET_ERRNO;
  324. throw DL_ABORT_EX(fmt(EX_SOCKET_LISTEN, errorMsg(errNum).c_str()));
  325. }
  326. setNonBlockingMode();
  327. }
  328. SharedHandle<SocketCore> SocketCore::acceptConnection() const
  329. {
  330. sockaddr_union sockaddr;
  331. socklen_t len = sizeof(sockaddr);
  332. sock_t fd;
  333. while((fd = accept(sockfd_, &sockaddr.sa, &len)) == (sock_t) -1 &&
  334. SOCKET_ERRNO == A2_EINTR);
  335. int errNum = SOCKET_ERRNO;
  336. if(fd == (sock_t) -1) {
  337. throw DL_ABORT_EX(fmt(EX_SOCKET_ACCEPT, errorMsg(errNum).c_str()));
  338. }
  339. SharedHandle<SocketCore> sock(new SocketCore(fd, sockType_));
  340. sock->setNonBlockingMode();
  341. sock->setTcpNodelay(true);
  342. return sock;
  343. }
  344. int SocketCore::getAddrInfo(std::pair<std::string, uint16_t>& addrinfo) const
  345. {
  346. sockaddr_union sockaddr;
  347. socklen_t len = sizeof(sockaddr);
  348. getAddrInfo(sockaddr, len);
  349. addrinfo = util::getNumericNameInfo(&sockaddr.sa, len);
  350. return sockaddr.storage.ss_family;
  351. }
  352. void SocketCore::getAddrInfo(sockaddr_union& sockaddr, socklen_t& len) const
  353. {
  354. if(getsockname(sockfd_, &sockaddr.sa, &len) == -1) {
  355. int errNum = SOCKET_ERRNO;
  356. throw DL_ABORT_EX(fmt(EX_SOCKET_GET_NAME, errorMsg(errNum).c_str()));
  357. }
  358. }
  359. int SocketCore::getAddressFamily() const
  360. {
  361. sockaddr_union sockaddr;
  362. socklen_t len = sizeof(sockaddr);
  363. getAddrInfo(sockaddr, len);
  364. return sockaddr.storage.ss_family;
  365. }
  366. int SocketCore::getPeerInfo(std::pair<std::string, uint16_t>& peerinfo) const
  367. {
  368. sockaddr_union sockaddr;
  369. socklen_t len = sizeof(sockaddr);
  370. if(getpeername(sockfd_, &sockaddr.sa, &len) == -1) {
  371. int errNum = SOCKET_ERRNO;
  372. throw DL_ABORT_EX(fmt(EX_SOCKET_GET_NAME, errorMsg(errNum).c_str()));
  373. }
  374. peerinfo = util::getNumericNameInfo(&sockaddr.sa, len);
  375. return sockaddr.storage.ss_family;
  376. }
  377. void SocketCore::establishConnection(const std::string& host, uint16_t port)
  378. {
  379. closeConnection();
  380. std::string error;
  381. struct addrinfo* res;
  382. int s;
  383. s = callGetaddrinfo(&res, host.c_str(), util::uitos(port).c_str(),
  384. protocolFamily_, sockType_, 0, 0);
  385. if(s) {
  386. throw DL_ABORT_EX(fmt(EX_RESOLVE_HOSTNAME, host.c_str(), gai_strerror(s)));
  387. }
  388. WSAAPI_AUTO_DELETE<struct addrinfo*> resDeleter(res, freeaddrinfo);
  389. struct addrinfo* rp;
  390. int errNum;
  391. for(rp = res; rp; rp = rp->ai_next) {
  392. sock_t fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  393. errNum = SOCKET_ERRNO;
  394. if(fd == (sock_t) -1) {
  395. error = errorMsg(errNum);
  396. continue;
  397. }
  398. int sockopt = 1;
  399. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (a2_sockopt_t) &sockopt,
  400. sizeof(sockopt)) < 0) {
  401. errNum = SOCKET_ERRNO;
  402. error = errorMsg(errNum);
  403. CLOSE(fd);
  404. continue;
  405. }
  406. if(!bindAddrs_.empty()) {
  407. bool bindSuccess = false;
  408. for(std::vector<std::pair<sockaddr_union, socklen_t> >::
  409. const_iterator i = bindAddrs_.begin(), eoi = bindAddrs_.end();
  410. i != eoi; ++i) {
  411. if(::bind(fd, &(*i).first.sa, (*i).second) == -1) {
  412. errNum = SOCKET_ERRNO;
  413. error = errorMsg(errNum);
  414. A2_LOG_DEBUG(fmt(EX_SOCKET_BIND, error.c_str()));
  415. } else {
  416. bindSuccess = true;
  417. break;
  418. }
  419. }
  420. if(!bindSuccess) {
  421. CLOSE(fd);
  422. continue;
  423. }
  424. }
  425. sockfd_ = fd;
  426. // make socket non-blocking mode
  427. setNonBlockingMode();
  428. setTcpNodelay(true);
  429. if(connect(fd, rp->ai_addr, rp->ai_addrlen) == -1 &&
  430. SOCKET_ERRNO != A2_EINPROGRESS) {
  431. errNum = SOCKET_ERRNO;
  432. error = errorMsg(errNum);
  433. CLOSE(sockfd_);
  434. sockfd_ = (sock_t) -1;
  435. continue;
  436. }
  437. // TODO at this point, connection may not be established and it may fail
  438. // later. In such case, next ai_addr should be tried.
  439. break;
  440. }
  441. if(sockfd_ == (sock_t) -1) {
  442. throw DL_ABORT_EX(fmt(EX_SOCKET_CONNECT, host.c_str(), error.c_str()));
  443. }
  444. }
  445. void SocketCore::setSockOpt
  446. (int level, int optname, void* optval, socklen_t optlen)
  447. {
  448. if(setsockopt(sockfd_, level, optname, (a2_sockopt_t)optval, optlen) < 0) {
  449. int errNum = SOCKET_ERRNO;
  450. throw DL_ABORT_EX(fmt(EX_SOCKET_SET_OPT, errorMsg(errNum).c_str()));
  451. }
  452. }
  453. void SocketCore::setMulticastInterface(const std::string& localAddr)
  454. {
  455. in_addr addr;
  456. if(localAddr.empty()) {
  457. addr.s_addr = htonl(INADDR_ANY);
  458. } else {
  459. if(inetPton(AF_INET, localAddr.c_str(), &addr) != 0) {
  460. throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
  461. localAddr.c_str()));
  462. }
  463. }
  464. setSockOpt(IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr));
  465. }
  466. void SocketCore::setMulticastTtl(unsigned char ttl)
  467. {
  468. setSockOpt(IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
  469. }
  470. void SocketCore::setMulticastLoop(unsigned char loop)
  471. {
  472. setSockOpt(IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
  473. }
  474. void SocketCore::joinMulticastGroup
  475. (const std::string& multicastAddr, uint16_t multicastPort,
  476. const std::string& localAddr)
  477. {
  478. in_addr multiAddr;
  479. if(inetPton(AF_INET, multicastAddr.c_str(), &multiAddr) != 0) {
  480. throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
  481. multicastAddr.c_str()));
  482. }
  483. in_addr ifAddr;
  484. if(localAddr.empty()) {
  485. ifAddr.s_addr = htonl(INADDR_ANY);
  486. } else {
  487. if(inetPton(AF_INET, localAddr.c_str(), &ifAddr) != 0) {
  488. throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
  489. localAddr.c_str()));
  490. }
  491. }
  492. struct ip_mreq mreq;
  493. memset(&mreq, 0, sizeof(mreq));
  494. mreq.imr_multiaddr = multiAddr;
  495. mreq.imr_interface = ifAddr;
  496. setSockOpt(IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
  497. }
  498. void SocketCore::setTcpNodelay(bool f)
  499. {
  500. int val = f;
  501. setSockOpt(IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
  502. }
  503. void SocketCore::setNonBlockingMode()
  504. {
  505. #ifdef __MINGW32__
  506. static u_long flag = 1;
  507. if (::ioctlsocket(sockfd_, FIONBIO, &flag) == -1) {
  508. int errNum = SOCKET_ERRNO;
  509. throw DL_ABORT_EX(fmt(EX_SOCKET_NONBLOCKING, errorMsg(errNum).c_str()));
  510. }
  511. #else
  512. int flags;
  513. while((flags = fcntl(sockfd_, F_GETFL, 0)) == -1 && errno == EINTR);
  514. // TODO add error handling
  515. while(fcntl(sockfd_, F_SETFL, flags|O_NONBLOCK) == -1 && errno == EINTR);
  516. #endif // __MINGW32__
  517. blocking_ = false;
  518. }
  519. void SocketCore::setBlockingMode()
  520. {
  521. #ifdef __MINGW32__
  522. static u_long flag = 0;
  523. if (::ioctlsocket(sockfd_, FIONBIO, &flag) == -1) {
  524. int errNum = SOCKET_ERRNO;
  525. throw DL_ABORT_EX(fmt(EX_SOCKET_BLOCKING, errorMsg(errNum).c_str()));
  526. }
  527. #else
  528. int flags;
  529. while((flags = fcntl(sockfd_, F_GETFL, 0)) == -1 && errno == EINTR);
  530. // TODO add error handling
  531. while(fcntl(sockfd_, F_SETFL, flags&(~O_NONBLOCK)) == -1 && errno == EINTR);
  532. #endif // __MINGW32__
  533. blocking_ = true;
  534. }
  535. void SocketCore::closeConnection()
  536. {
  537. #ifdef HAVE_OPENSSL
  538. // for SSL
  539. if(secure_) {
  540. SSL_shutdown(ssl);
  541. }
  542. #endif // HAVE_OPENSSL
  543. #ifdef HAVE_LIBGNUTLS
  544. if(secure_) {
  545. gnutls_bye(sslSession_, GNUTLS_SHUT_WR);
  546. }
  547. #endif // HAVE_LIBGNUTLS
  548. if(sockfd_ != (sock_t) -1) {
  549. shutdown(sockfd_, SHUT_WR);
  550. CLOSE(sockfd_);
  551. sockfd_ = -1;
  552. }
  553. #ifdef HAVE_OPENSSL
  554. // for SSL
  555. if(secure_) {
  556. SSL_free(ssl);
  557. }
  558. #endif // HAVE_OPENSSL
  559. #ifdef HAVE_LIBGNUTLS
  560. if(secure_) {
  561. gnutls_deinit(sslSession_);
  562. }
  563. #endif // HAVE_LIBGNUTLS
  564. }
  565. #ifndef __MINGW32__
  566. # define CHECK_FD(fd) \
  567. if(fd < 0 || FD_SETSIZE <= fd) { \
  568. logger_->warn("Detected file descriptor >= FD_SETSIZE or < 0. " \
  569. "Download may slow down or fail."); \
  570. return false; \
  571. }
  572. #endif // !__MINGW32__
  573. bool SocketCore::isWritable(time_t timeout)
  574. {
  575. #ifdef HAVE_POLL
  576. struct pollfd p;
  577. p.fd = sockfd_;
  578. p.events = POLLOUT;
  579. int r;
  580. while((r = poll(&p, 1, timeout*1000)) == -1 && errno == EINTR);
  581. int errNum = SOCKET_ERRNO;
  582. if(r > 0) {
  583. return p.revents&(POLLOUT|POLLHUP|POLLERR);
  584. } else if(r == 0) {
  585. return false;
  586. } else {
  587. throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_WRITABLE, errorMsg(errNum).c_str()));
  588. }
  589. #else // !HAVE_POLL
  590. # ifndef __MINGW32__
  591. CHECK_FD(sockfd_);
  592. # endif // !__MINGW32__
  593. fd_set fds;
  594. FD_ZERO(&fds);
  595. FD_SET(sockfd_, &fds);
  596. struct timeval tv;
  597. tv.tv_sec = timeout;
  598. tv.tv_usec = 0;
  599. int r = select(sockfd_+1, NULL, &fds, NULL, &tv);
  600. int errNum = SOCKET_ERRNO;
  601. if(r == 1) {
  602. return true;
  603. } else if(r == 0) {
  604. // time out
  605. return false;
  606. } else {
  607. if(errNum == A2_EINPROGRESS || errNum == A2_EINTR) {
  608. return false;
  609. } else {
  610. throw DL_RETRY_EX
  611. (fmt(EX_SOCKET_CHECK_WRITABLE, errorMsg(errNum).c_str()));
  612. }
  613. }
  614. #endif // !HAVE_POLL
  615. }
  616. bool SocketCore::isReadable(time_t timeout)
  617. {
  618. #ifdef HAVE_POLL
  619. struct pollfd p;
  620. p.fd = sockfd_;
  621. p.events = POLLIN;
  622. int r;
  623. while((r = poll(&p, 1, timeout*1000)) == -1 && errno == EINTR);
  624. int errNum = SOCKET_ERRNO;
  625. if(r > 0) {
  626. return p.revents&(POLLIN|POLLHUP|POLLERR);
  627. } else if(r == 0) {
  628. return false;
  629. } else {
  630. throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_READABLE, errorMsg(errNum).c_str()));
  631. }
  632. #else // !HAVE_POLL
  633. # ifndef __MINGW32__
  634. CHECK_FD(sockfd_);
  635. # endif // !__MINGW32__
  636. fd_set fds;
  637. FD_ZERO(&fds);
  638. FD_SET(sockfd_, &fds);
  639. struct timeval tv;
  640. tv.tv_sec = timeout;
  641. tv.tv_usec = 0;
  642. int r = select(sockfd_+1, &fds, NULL, NULL, &tv);
  643. int errNum = SOCKET_ERRNO;
  644. if(r == 1) {
  645. return true;
  646. } else if(r == 0) {
  647. // time out
  648. return false;
  649. } else {
  650. if(errNum == A2_EINPROGRESS || errNum == A2_EINTR) {
  651. return false;
  652. } else {
  653. throw DL_RETRY_EX
  654. (fmt(EX_SOCKET_CHECK_READABLE, errorMsg(errNum).c_str()));
  655. }
  656. }
  657. #endif // !HAVE_POLL
  658. }
  659. #ifdef HAVE_OPENSSL
  660. int SocketCore::sslHandleEAGAIN(int ret)
  661. {
  662. int error = SSL_get_error(ssl, ret);
  663. if(error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE) {
  664. ret = 0;
  665. if(error == SSL_ERROR_WANT_READ) {
  666. wantRead_ = true;
  667. } else {
  668. wantWrite_ = true;
  669. }
  670. }
  671. return ret;
  672. }
  673. #endif // HAVE_OPENSSL
  674. #ifdef HAVE_LIBGNUTLS
  675. void SocketCore::gnutlsRecordCheckDirection()
  676. {
  677. int direction = gnutls_record_get_direction(sslSession_);
  678. if(direction == 0) {
  679. wantRead_ = true;
  680. } else { // if(direction == 1) {
  681. wantWrite_ = true;
  682. }
  683. }
  684. #endif // HAVE_LIBGNUTLS
  685. ssize_t SocketCore::writeData(const char* data, size_t len)
  686. {
  687. ssize_t ret = 0;
  688. wantRead_ = false;
  689. wantWrite_ = false;
  690. if(!secure_) {
  691. while((ret = send(sockfd_, data, len, 0)) == -1 && SOCKET_ERRNO == A2_EINTR);
  692. int errNum = SOCKET_ERRNO;
  693. if(ret == -1) {
  694. if(A2_WOULDBLOCK(errNum)) {
  695. wantWrite_ = true;
  696. ret = 0;
  697. } else {
  698. throw DL_RETRY_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
  699. }
  700. }
  701. } else {
  702. #ifdef HAVE_OPENSSL
  703. ERR_clear_error();
  704. ret = SSL_write(ssl, data, len);
  705. if(ret < 0) {
  706. ret = sslHandleEAGAIN(ret);
  707. }
  708. if(ret < 0) {
  709. throw DL_RETRY_EX
  710. (fmt(EX_SOCKET_SEND, ERR_error_string(ERR_get_error(), 0)));
  711. }
  712. #endif // HAVE_OPENSSL
  713. #ifdef HAVE_LIBGNUTLS
  714. while((ret = gnutls_record_send(sslSession_, data, len)) ==
  715. GNUTLS_E_INTERRUPTED);
  716. if(ret == GNUTLS_E_AGAIN) {
  717. gnutlsRecordCheckDirection();
  718. ret = 0;
  719. } else if(ret < 0) {
  720. throw DL_RETRY_EX(fmt(EX_SOCKET_SEND, gnutls_strerror(ret)));
  721. }
  722. #endif // HAVE_LIBGNUTLS
  723. }
  724. return ret;
  725. }
  726. void SocketCore::readData(char* data, size_t& len)
  727. {
  728. ssize_t ret = 0;
  729. wantRead_ = false;
  730. wantWrite_ = false;
  731. if(!secure_) {
  732. while((ret = recv(sockfd_, data, len, 0)) == -1 &&
  733. SOCKET_ERRNO == A2_EINTR);
  734. int errNum = SOCKET_ERRNO;
  735. if(ret == -1) {
  736. if(A2_WOULDBLOCK(errNum)) {
  737. wantRead_ = true;
  738. ret = 0;
  739. } else {
  740. throw DL_RETRY_EX(fmt(EX_SOCKET_RECV, errorMsg(errNum).c_str()));
  741. }
  742. }
  743. } else {
  744. #ifdef HAVE_OPENSSL
  745. // for SSL
  746. // TODO handling len == 0 case required
  747. ERR_clear_error();
  748. ret = SSL_read(ssl, data, len);
  749. if(ret < 0) {
  750. ret = sslHandleEAGAIN(ret);
  751. }
  752. if(ret < 0) {
  753. throw DL_RETRY_EX
  754. (fmt(EX_SOCKET_RECV, ERR_error_string(ERR_get_error(), 0)));
  755. }
  756. #endif // HAVE_OPENSSL
  757. #ifdef HAVE_LIBGNUTLS
  758. while((ret = gnutls_record_recv(sslSession_, data, len)) ==
  759. GNUTLS_E_INTERRUPTED);
  760. if(ret == GNUTLS_E_AGAIN) {
  761. gnutlsRecordCheckDirection();
  762. ret = 0;
  763. } else if(ret < 0) {
  764. throw DL_RETRY_EX(fmt(EX_SOCKET_RECV, gnutls_strerror(ret)));
  765. }
  766. #endif // HAVE_LIBGNUTLS
  767. }
  768. len = ret;
  769. }
  770. bool SocketCore::tlsAccept()
  771. {
  772. return tlsHandshake(svTlsContext_.get(), A2STR::NIL);
  773. }
  774. bool SocketCore::tlsConnect(const std::string& hostname)
  775. {
  776. return tlsHandshake(clTlsContext_.get(), hostname);
  777. }
  778. bool SocketCore::tlsHandshake(TLSContext* tlsctx, const std::string& hostname)
  779. {
  780. wantRead_ = false;
  781. wantWrite_ = false;
  782. #ifdef HAVE_OPENSSL
  783. switch(secure_) {
  784. case A2_TLS_NONE:
  785. ssl = SSL_new(tlsctx->getSSLCtx());
  786. if(!ssl) {
  787. throw DL_ABORT_EX
  788. (fmt(EX_SSL_INIT_FAILURE, ERR_error_string(ERR_get_error(), 0)));
  789. }
  790. if(SSL_set_fd(ssl, sockfd_) == 0) {
  791. throw DL_ABORT_EX
  792. (fmt(EX_SSL_INIT_FAILURE, ERR_error_string(ERR_get_error(), 0)));
  793. }
  794. // Fall through
  795. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  796. if(tlsctx->getSide() == TLS_CLIENT && !util::isNumericHost(hostname)) {
  797. // TLS extensions: SNI. There is not documentation about the
  798. // return code for this function (actually this is macro
  799. // wrapping SSL_ctrl at the time of this writing).
  800. SSL_set_tlsext_host_name(ssl, hostname.c_str());
  801. }
  802. #endif // SSL_CTRL_SET_TLSEXT_HOSTNAME
  803. secure_ = A2_TLS_HANDSHAKING;
  804. // Fall through
  805. case A2_TLS_HANDSHAKING: {
  806. ERR_clear_error();
  807. int e;
  808. if(tlsctx->getSide() == TLS_CLIENT) {
  809. e = SSL_connect(ssl);
  810. } else {
  811. e = SSL_accept(ssl);
  812. }
  813. if (e <= 0) {
  814. int ssl_error = SSL_get_error(ssl, e);
  815. switch(ssl_error) {
  816. case SSL_ERROR_NONE:
  817. break;
  818. case SSL_ERROR_WANT_READ:
  819. wantRead_ = true;
  820. return false;
  821. case SSL_ERROR_WANT_WRITE:
  822. wantWrite_ = true;
  823. return false;
  824. case SSL_ERROR_WANT_X509_LOOKUP:
  825. case SSL_ERROR_ZERO_RETURN:
  826. if (blocking_) {
  827. throw DL_ABORT_EX(fmt(EX_SSL_CONNECT_ERROR, ssl_error));
  828. }
  829. break;
  830. case SSL_ERROR_SYSCALL: {
  831. int sslErr = ERR_get_error();
  832. if(sslErr == 0) {
  833. if(e == 0) {
  834. throw DL_ABORT_EX("Got EOF in SSL handshake");
  835. } else if(e == -1) {
  836. throw DL_ABORT_EX(fmt("SSL I/O error: %s", strerror(errno)));
  837. } else {
  838. throw DL_ABORT_EX(EX_SSL_IO_ERROR);
  839. }
  840. } else {
  841. throw DL_ABORT_EX(fmt("SSL I/O error: %s",
  842. ERR_error_string(sslErr, 0)));
  843. }
  844. }
  845. case SSL_ERROR_SSL:
  846. throw DL_ABORT_EX(EX_SSL_PROTOCOL_ERROR);
  847. default:
  848. throw DL_ABORT_EX(fmt(EX_SSL_UNKNOWN_ERROR, ssl_error));
  849. }
  850. }
  851. if(tlsctx->getSide() == TLS_CLIENT &&
  852. tlsctx->peerVerificationEnabled()) {
  853. // verify peer
  854. X509* peerCert = SSL_get_peer_certificate(ssl);
  855. if(!peerCert) {
  856. throw DL_ABORT_EX(MSG_NO_CERT_FOUND);
  857. }
  858. auto_delete<X509*> certDeleter(peerCert, X509_free);
  859. long verifyResult = SSL_get_verify_result(ssl);
  860. if(verifyResult != X509_V_OK) {
  861. throw DL_ABORT_EX
  862. (fmt(MSG_CERT_VERIFICATION_FAILED,
  863. X509_verify_cert_error_string(verifyResult)));
  864. }
  865. std::string commonName;
  866. std::vector<std::string> dnsNames;
  867. std::vector<std::string> ipAddrs;
  868. GENERAL_NAMES* altNames;
  869. altNames = reinterpret_cast<GENERAL_NAMES*>
  870. (X509_get_ext_d2i(peerCert, NID_subject_alt_name, NULL, NULL));
  871. if(altNames) {
  872. auto_delete<GENERAL_NAMES*> altNamesDeleter
  873. (altNames, GENERAL_NAMES_free);
  874. size_t n = sk_GENERAL_NAME_num(altNames);
  875. for(size_t i = 0; i < n; ++i) {
  876. const GENERAL_NAME* altName = sk_GENERAL_NAME_value(altNames, i);
  877. if(altName->type == GEN_DNS) {
  878. const char* name =
  879. reinterpret_cast<char*>(ASN1_STRING_data(altName->d.ia5));
  880. if(!name) {
  881. continue;
  882. }
  883. size_t len = ASN1_STRING_length(altName->d.ia5);
  884. dnsNames.push_back(std::string(name, len));
  885. } else if(altName->type == GEN_IPADD) {
  886. const unsigned char* ipAddr = altName->d.iPAddress->data;
  887. if(!ipAddr) {
  888. continue;
  889. }
  890. size_t len = altName->d.iPAddress->length;
  891. ipAddrs.push_back(std::string(reinterpret_cast<const char*>(ipAddr),
  892. len));
  893. }
  894. }
  895. }
  896. X509_NAME* subjectName = X509_get_subject_name(peerCert);
  897. if(!subjectName) {
  898. throw DL_ABORT_EX
  899. ("Could not get X509 name object from the certificate.");
  900. }
  901. int lastpos = -1;
  902. while(1) {
  903. lastpos = X509_NAME_get_index_by_NID(subjectName, NID_commonName,
  904. lastpos);
  905. if(lastpos == -1) {
  906. break;
  907. }
  908. X509_NAME_ENTRY* entry = X509_NAME_get_entry(subjectName, lastpos);
  909. unsigned char* out;
  910. int outlen = ASN1_STRING_to_UTF8(&out,
  911. X509_NAME_ENTRY_get_data(entry));
  912. if(outlen < 0) {
  913. continue;
  914. }
  915. commonName.assign(&out[0], &out[outlen]);
  916. OPENSSL_free(out);
  917. break;
  918. }
  919. if(!net::verifyHostname(hostname, dnsNames, ipAddrs, commonName)) {
  920. throw DL_ABORT_EX(MSG_HOSTNAME_NOT_MATCH);
  921. }
  922. }
  923. secure_ = A2_TLS_CONNECTED;
  924. break;
  925. }
  926. default:
  927. break;
  928. }
  929. #endif // HAVE_OPENSSL
  930. #ifdef HAVE_LIBGNUTLS
  931. switch(secure_) {
  932. case A2_TLS_NONE:
  933. int r;
  934. gnutls_init(&sslSession_,
  935. tlsctx->getSide() == TLS_CLIENT ?
  936. GNUTLS_CLIENT : GNUTLS_SERVER);
  937. // It seems err is not error message, but the argument string
  938. // which causes syntax error.
  939. const char* err;
  940. // For client side, disables TLS1.1 here because there are servers
  941. // that don't understand TLS1.1. TODO Is this still necessary?
  942. r = gnutls_priority_set_direct(sslSession_,
  943. tlsctx->getSide() == TLS_CLIENT ?
  944. "NORMAL:-VERS-TLS1.1" :
  945. "NORMAL",
  946. &err);
  947. if(r != GNUTLS_E_SUCCESS) {
  948. throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE, gnutls_strerror(r)));
  949. }
  950. // put the x509 credentials to the current session
  951. gnutls_credentials_set(sslSession_, GNUTLS_CRD_CERTIFICATE,
  952. tlsctx->getCertCred());
  953. gnutls_transport_set_ptr(sslSession_, (gnutls_transport_ptr_t)sockfd_);
  954. if(tlsctx->getSide() == TLS_CLIENT) {
  955. // Check hostname is not numeric and it includes ".". Setting
  956. // "localhost" will produce TLS alert.
  957. if(!util::isNumericHost(hostname) &&
  958. hostname.find(".") != std::string::npos) {
  959. // TLS extensions: SNI
  960. int ret = gnutls_server_name_set(sslSession_, GNUTLS_NAME_DNS,
  961. hostname.c_str(), hostname.size());
  962. if(ret < 0) {
  963. A2_LOG_WARN(fmt
  964. ("Setting hostname in SNI extension failed. Cause: %s",
  965. gnutls_strerror(ret)));
  966. }
  967. }
  968. }
  969. secure_ = A2_TLS_HANDSHAKING;
  970. // Fall through
  971. case A2_TLS_HANDSHAKING: {
  972. int ret = gnutls_handshake(sslSession_);
  973. if(ret == GNUTLS_E_AGAIN) {
  974. gnutlsRecordCheckDirection();
  975. return false;
  976. } else if(ret < 0) {
  977. throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE, gnutls_strerror(ret)));
  978. }
  979. if(tlsctx->getSide() == TLS_CLIENT && tlsctx->peerVerificationEnabled()) {
  980. // verify peer
  981. unsigned int status;
  982. ret = gnutls_certificate_verify_peers2(sslSession_, &status);
  983. if(ret < 0) {
  984. throw DL_ABORT_EX
  985. (fmt("gnutls_certificate_verify_peer2() failed. Cause: %s",
  986. gnutls_strerror(ret)));
  987. }
  988. if(status) {
  989. std::string errors;
  990. if(status & GNUTLS_CERT_INVALID) {
  991. errors += " `not signed by known authorities or invalid'";
  992. }
  993. if(status & GNUTLS_CERT_REVOKED) {
  994. errors += " `revoked by its CA'";
  995. }
  996. if(status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
  997. errors += " `issuer is not known'";
  998. }
  999. // TODO should check GNUTLS_CERT_SIGNER_NOT_CA ?
  1000. if(status & GNUTLS_CERT_INSECURE_ALGORITHM) {
  1001. errors += " `insecure algorithm'";
  1002. }
  1003. if(status & GNUTLS_CERT_NOT_ACTIVATED) {
  1004. errors += " `not activated yet'";
  1005. }
  1006. if(status & GNUTLS_CERT_EXPIRED) {
  1007. errors += " `expired'";
  1008. }
  1009. // TODO Add GNUTLS_CERT_SIGNATURE_FAILURE here
  1010. if(!errors.empty()) {
  1011. throw DL_ABORT_EX(fmt(MSG_CERT_VERIFICATION_FAILED, errors.c_str()));
  1012. }
  1013. }
  1014. // certificate type: only X509 is allowed.
  1015. if(gnutls_certificate_type_get(sslSession_) != GNUTLS_CRT_X509) {
  1016. throw DL_ABORT_EX("Certificate type is not X509.");
  1017. }
  1018. unsigned int peerCertsLength;
  1019. const gnutls_datum_t* peerCerts = gnutls_certificate_get_peers
  1020. (sslSession_, &peerCertsLength);
  1021. if(!peerCerts || peerCertsLength == 0 ) {
  1022. throw DL_ABORT_EX(MSG_NO_CERT_FOUND);
  1023. }
  1024. Time now;
  1025. for(unsigned int i = 0; i < peerCertsLength; ++i) {
  1026. gnutls_x509_crt_t cert;
  1027. ret = gnutls_x509_crt_init(&cert);
  1028. if(ret < 0) {
  1029. throw DL_ABORT_EX
  1030. (fmt("gnutls_x509_crt_init() failed. Cause: %s",
  1031. gnutls_strerror(ret)));
  1032. }
  1033. auto_delete<gnutls_x509_crt_t> certDeleter
  1034. (cert, gnutls_x509_crt_deinit);
  1035. ret = gnutls_x509_crt_import(cert, &peerCerts[i], GNUTLS_X509_FMT_DER);
  1036. if(ret < 0) {
  1037. throw DL_ABORT_EX
  1038. (fmt("gnutls_x509_crt_import() failed. Cause: %s",
  1039. gnutls_strerror(ret)));
  1040. }
  1041. if(i == 0) {
  1042. std::string commonName;
  1043. std::vector<std::string> dnsNames;
  1044. std::vector<std::string> ipAddrs;
  1045. int ret = 0;
  1046. char altName[256];
  1047. size_t altNameLen;
  1048. for(int j = 0; !(ret < 0); ++j) {
  1049. altNameLen = sizeof(altName);
  1050. ret = gnutls_x509_crt_get_subject_alt_name(cert, j, altName,
  1051. &altNameLen, 0);
  1052. if(ret == GNUTLS_SAN_DNSNAME) {
  1053. dnsNames.push_back(std::string(altName, altNameLen));
  1054. } else if(ret == GNUTLS_SAN_IPADDRESS) {
  1055. ipAddrs.push_back(std::string(altName, altNameLen));
  1056. }
  1057. }
  1058. altNameLen = sizeof(altName);
  1059. ret = gnutls_x509_crt_get_dn_by_oid(cert,
  1060. GNUTLS_OID_X520_COMMON_NAME, 0, 0,
  1061. altName, &altNameLen);
  1062. if(ret == 0) {
  1063. commonName.assign(altName, altNameLen);
  1064. }
  1065. if(!net::verifyHostname(hostname, dnsNames, ipAddrs, commonName)) {
  1066. throw DL_ABORT_EX(MSG_HOSTNAME_NOT_MATCH);
  1067. }
  1068. }
  1069. time_t activationTime = gnutls_x509_crt_get_activation_time(cert);
  1070. if(activationTime == -1) {
  1071. throw DL_ABORT_EX("Could not get activation time from certificate.");
  1072. }
  1073. if(now.getTime() < activationTime) {
  1074. throw DL_ABORT_EX("Certificate is not activated yet.");
  1075. }
  1076. time_t expirationTime = gnutls_x509_crt_get_expiration_time(cert);
  1077. if(expirationTime == -1) {
  1078. throw DL_ABORT_EX("Could not get expiration time from certificate.");
  1079. }
  1080. if(expirationTime < now.getTime()) {
  1081. throw DL_ABORT_EX("Certificate has expired.");
  1082. }
  1083. }
  1084. }
  1085. secure_ = A2_TLS_CONNECTED;
  1086. break;
  1087. }
  1088. default:
  1089. break;
  1090. }
  1091. #endif // HAVE_LIBGNUTLS
  1092. return true;
  1093. }
  1094. ssize_t SocketCore::writeData(const char* data, size_t len,
  1095. const std::string& host, uint16_t port)
  1096. {
  1097. wantRead_ = false;
  1098. wantWrite_ = false;
  1099. struct addrinfo* res;
  1100. int s;
  1101. s = callGetaddrinfo(&res, host.c_str(), util::uitos(port).c_str(),
  1102. protocolFamily_, sockType_, 0, 0);
  1103. if(s) {
  1104. throw DL_ABORT_EX(fmt(EX_SOCKET_SEND, gai_strerror(s)));
  1105. }
  1106. WSAAPI_AUTO_DELETE<struct addrinfo*> resDeleter(res, freeaddrinfo);
  1107. struct addrinfo* rp;
  1108. ssize_t r = -1;
  1109. int errNum = 0;
  1110. for(rp = res; rp; rp = rp->ai_next) {
  1111. while((r = sendto(sockfd_, data, len, 0, rp->ai_addr, rp->ai_addrlen)) == -1
  1112. && A2_EINTR == SOCKET_ERRNO);
  1113. errNum = SOCKET_ERRNO;
  1114. if(r == static_cast<ssize_t>(len)) {
  1115. break;
  1116. }
  1117. if(r == -1 && A2_WOULDBLOCK(errNum)) {
  1118. wantWrite_ = true;
  1119. r = 0;
  1120. break;
  1121. }
  1122. }
  1123. if(r == -1) {
  1124. throw DL_ABORT_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
  1125. }
  1126. return r;
  1127. }
  1128. ssize_t SocketCore::readDataFrom(char* data, size_t len,
  1129. std::pair<std::string /* numerichost */,
  1130. uint16_t /* port */>& sender)
  1131. {
  1132. wantRead_ = false;
  1133. wantWrite_ = false;
  1134. sockaddr_union sockaddr;
  1135. socklen_t sockaddrlen = sizeof(sockaddr);
  1136. ssize_t r;
  1137. while((r = recvfrom(sockfd_, data, len, 0, &sockaddr.sa, &sockaddrlen)) == -1
  1138. && A2_EINTR == SOCKET_ERRNO);
  1139. int errNum = SOCKET_ERRNO;
  1140. if(r == -1) {
  1141. if(A2_WOULDBLOCK(errNum)) {
  1142. wantRead_ = true;
  1143. r = 0;
  1144. } else {
  1145. throw DL_RETRY_EX(fmt(EX_SOCKET_RECV, errorMsg(errNum).c_str()));
  1146. }
  1147. } else {
  1148. sender = util::getNumericNameInfo(&sockaddr.sa, sockaddrlen);
  1149. }
  1150. return r;
  1151. }
  1152. std::string SocketCore::getSocketError() const
  1153. {
  1154. int error;
  1155. socklen_t optlen = sizeof(error);
  1156. if(getsockopt(sockfd_, SOL_SOCKET, SO_ERROR,
  1157. (a2_sockopt_t) &error, &optlen) == -1) {
  1158. int errNum = SOCKET_ERRNO;
  1159. throw DL_ABORT_EX
  1160. (fmt("Failed to get socket error: %s", errorMsg(errNum).c_str()));
  1161. }
  1162. if(error != 0) {
  1163. return errorMsg(error);
  1164. } else {
  1165. return "";
  1166. }
  1167. }
  1168. bool SocketCore::wantRead() const
  1169. {
  1170. return wantRead_;
  1171. }
  1172. bool SocketCore::wantWrite() const
  1173. {
  1174. return wantWrite_;
  1175. }
  1176. void SocketCore::bindAddress(const std::string& iface)
  1177. {
  1178. std::vector<std::pair<sockaddr_union, socklen_t> > bindAddrs;
  1179. getInterfaceAddress(bindAddrs, iface, protocolFamily_);
  1180. if(bindAddrs.empty()) {
  1181. throw DL_ABORT_EX
  1182. (fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), "not available"));
  1183. } else {
  1184. bindAddrs_.swap(bindAddrs);
  1185. for(std::vector<std::pair<sockaddr_union, socklen_t> >::
  1186. const_iterator i = bindAddrs_.begin(), eoi = bindAddrs_.end();
  1187. i != eoi; ++i) {
  1188. char host[NI_MAXHOST];
  1189. int s;
  1190. s = getnameinfo(&(*i).first.sa, (*i).second, host, NI_MAXHOST, 0, 0,
  1191. NI_NUMERICHOST);
  1192. if(s == 0) {
  1193. A2_LOG_DEBUG(fmt("Sockets will bind to %s", host));
  1194. }
  1195. }
  1196. }
  1197. }
  1198. void getInterfaceAddress
  1199. (std::vector<std::pair<sockaddr_union, socklen_t> >& ifAddrs,
  1200. const std::string& iface, int family, int aiFlags)
  1201. {
  1202. A2_LOG_DEBUG(fmt("Finding interface %s", iface.c_str()));
  1203. #ifdef HAVE_GETIFADDRS
  1204. // First find interface in interface addresses
  1205. struct ifaddrs* ifaddr = 0;
  1206. if(getifaddrs(&ifaddr) == -1) {
  1207. int errNum = SOCKET_ERRNO;
  1208. A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND,
  1209. iface.c_str(), errorMsg(errNum).c_str()));
  1210. } else {
  1211. auto_delete<ifaddrs*> ifaddrDeleter(ifaddr, freeifaddrs);
  1212. for(ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
  1213. if(!ifa->ifa_addr) {
  1214. continue;
  1215. }
  1216. int iffamily = ifa->ifa_addr->sa_family;
  1217. if(family == AF_UNSPEC) {
  1218. if(iffamily != AF_INET && iffamily != AF_INET6) {
  1219. continue;
  1220. }
  1221. } else if(family == AF_INET) {
  1222. if(iffamily != AF_INET) {
  1223. continue;
  1224. }
  1225. } else if(family == AF_INET6) {
  1226. if(iffamily != AF_INET6) {
  1227. continue;
  1228. }
  1229. } else {
  1230. continue;
  1231. }
  1232. if(strcmp(iface.c_str(), ifa->ifa_name) == 0) {
  1233. socklen_t bindAddrLen =
  1234. iffamily == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6);
  1235. sockaddr_union bindAddr;
  1236. memset(&bindAddr, 0, sizeof(bindAddr));
  1237. memcpy(&bindAddr.storage, ifa->ifa_addr, bindAddrLen);
  1238. ifAddrs.push_back(std::make_pair(bindAddr, bindAddrLen));
  1239. }
  1240. }
  1241. }
  1242. #endif // HAVE_GETIFADDRS
  1243. if(ifAddrs.empty()) {
  1244. addrinfo* res;
  1245. int s;
  1246. s = callGetaddrinfo(&res, iface.c_str(), 0, family, SOCK_STREAM, aiFlags,0);
  1247. if(s) {
  1248. A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), gai_strerror(s)));
  1249. } else {
  1250. WSAAPI_AUTO_DELETE<addrinfo*> resDeleter(res, freeaddrinfo);
  1251. addrinfo* rp;
  1252. for(rp = res; rp; rp = rp->ai_next) {
  1253. // Try to bind socket with this address. If it fails, the
  1254. // address is not for this machine.
  1255. try {
  1256. SocketCore socket;
  1257. socket.bind(rp->ai_addr, rp->ai_addrlen);
  1258. sockaddr_union bindAddr;
  1259. memset(&bindAddr, 0, sizeof(bindAddr));
  1260. memcpy(&bindAddr.storage, rp->ai_addr, rp->ai_addrlen);
  1261. ifAddrs.push_back(std::make_pair(bindAddr, rp->ai_addrlen));
  1262. } catch(RecoverableException& e) {
  1263. continue;
  1264. }
  1265. }
  1266. }
  1267. }
  1268. }
  1269. namespace {
  1270. int defaultAIFlags = DEFAULT_AI_FLAGS;
  1271. int getDefaultAIFlags()
  1272. {
  1273. return defaultAIFlags;
  1274. }
  1275. } // namespace
  1276. void setDefaultAIFlags(int flags)
  1277. {
  1278. defaultAIFlags = flags;
  1279. }
  1280. int callGetaddrinfo
  1281. (struct addrinfo** resPtr, const char* host, const char* service, int family,
  1282. int sockType, int flags, int protocol)
  1283. {
  1284. struct addrinfo hints;
  1285. memset(&hints, 0, sizeof(hints));
  1286. hints.ai_family = family;
  1287. hints.ai_socktype = sockType;
  1288. hints.ai_flags = getDefaultAIFlags();
  1289. hints.ai_flags |= flags;
  1290. hints.ai_protocol = protocol;
  1291. return getaddrinfo(host, service, &hints, resPtr);
  1292. }
  1293. int inetNtop(int af, const void* src, char* dst, socklen_t size)
  1294. {
  1295. int s;
  1296. sockaddr_union su;
  1297. memset(&su, 0, sizeof(su));
  1298. if(af == AF_INET) {
  1299. su.in.sin_family = AF_INET;
  1300. #ifdef HAVE_SOCKADDR_IN_SIN_LEN
  1301. su.in.sin_len = sizeof(su.in);
  1302. #endif // HAVE_SOCKADDR_IN_SIN_LEN
  1303. memcpy(&su.in.sin_addr, src, sizeof(su.in.sin_addr));
  1304. s = getnameinfo(&su.sa, sizeof(su.in),
  1305. dst, size, 0, 0, NI_NUMERICHOST);
  1306. } else if(af == AF_INET6) {
  1307. su.in6.sin6_family = AF_INET6;
  1308. #ifdef HAVE_SOCKADDR_IN6_SIN6_LEN
  1309. su.in6.sin6_len = sizeof(su.in6);
  1310. #endif // HAVE_SOCKADDR_IN6_SIN6_LEN
  1311. memcpy(&su.in6.sin6_addr, src, sizeof(su.in6.sin6_addr));
  1312. s = getnameinfo(&su.sa, sizeof(su.in6),
  1313. dst, size, 0, 0, NI_NUMERICHOST);
  1314. } else {
  1315. s = EAI_FAMILY;
  1316. }
  1317. return s;
  1318. }
  1319. int inetPton(int af, const char* src, void* dst)
  1320. {
  1321. union {
  1322. uint32_t ipv4_addr;
  1323. unsigned char ipv6_addr[16];
  1324. } binaddr;
  1325. size_t len = net::getBinAddr(binaddr.ipv6_addr, src);
  1326. if(af == AF_INET) {
  1327. if(len != 4) {
  1328. return -1;
  1329. }
  1330. in_addr* addr = reinterpret_cast<in_addr*>(dst);
  1331. addr->s_addr = binaddr.ipv4_addr;
  1332. } else if(af == AF_INET6) {
  1333. if(len != 16) {
  1334. return -1;
  1335. }
  1336. in6_addr* addr = reinterpret_cast<in6_addr*>(dst);
  1337. memcpy(addr->s6_addr, binaddr.ipv6_addr, sizeof(addr->s6_addr));
  1338. } else {
  1339. return -1;
  1340. }
  1341. return 0;
  1342. }
  1343. namespace net {
  1344. size_t getBinAddr(void* dest, const std::string& ip)
  1345. {
  1346. size_t len = 0;
  1347. addrinfo* res;
  1348. if(callGetaddrinfo(&res, ip.c_str(), 0, AF_UNSPEC,
  1349. 0, AI_NUMERICHOST, 0) != 0) {
  1350. return len;
  1351. }
  1352. WSAAPI_AUTO_DELETE<addrinfo*> resDeleter(res, freeaddrinfo);
  1353. for(addrinfo* rp = res; rp; rp = rp->ai_next) {
  1354. sockaddr_union su;
  1355. memcpy(&su, rp->ai_addr, rp->ai_addrlen);
  1356. if(rp->ai_family == AF_INET) {
  1357. len = sizeof(in_addr);
  1358. memcpy(dest, &(su.in.sin_addr), len);
  1359. break;
  1360. } else if(rp->ai_family == AF_INET6) {
  1361. len = sizeof(in6_addr);
  1362. memcpy(dest, &(su.in6.sin6_addr), len);
  1363. break;
  1364. }
  1365. }
  1366. return len;
  1367. }
  1368. bool verifyHostname(const std::string& hostname,
  1369. const std::vector<std::string>& dnsNames,
  1370. const std::vector<std::string>& ipAddrs,
  1371. const std::string& commonName)
  1372. {
  1373. if(util::isNumericHost(hostname)) {
  1374. if(ipAddrs.empty()) {
  1375. return commonName == hostname;
  1376. }
  1377. // We need max 16 bytes to store IPv6 address.
  1378. unsigned char binAddr[16];
  1379. size_t addrLen = getBinAddr(binAddr, hostname);
  1380. if(addrLen == 0) {
  1381. return false;
  1382. }
  1383. for(std::vector<std::string>::const_iterator i = ipAddrs.begin(),
  1384. eoi = ipAddrs.end(); i != eoi; ++i) {
  1385. if(addrLen == (*i).size() &&
  1386. memcmp(binAddr, (*i).c_str(), addrLen) == 0) {
  1387. return true;
  1388. }
  1389. }
  1390. } else {
  1391. if(dnsNames.empty()) {
  1392. return util::tlsHostnameMatch(commonName, hostname);
  1393. }
  1394. for(std::vector<std::string>::const_iterator i = dnsNames.begin(),
  1395. eoi = dnsNames.end(); i != eoi; ++i) {
  1396. if(util::tlsHostnameMatch(*i, hostname)) {
  1397. return true;
  1398. }
  1399. }
  1400. }
  1401. return false;
  1402. }
  1403. } // namespace net
  1404. } // namespace aria2