SocketCore.cc 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  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. #ifdef HAVE_IPHLPAPI_H
  37. # include <iphlpapi.h>
  38. #endif // HAVE_IPHLPAPI_H
  39. #include <unistd.h>
  40. #ifdef HAVE_IFADDRS_H
  41. # include <ifaddrs.h>
  42. #endif // HAVE_IFADDRS_H
  43. #include <cerrno>
  44. #include <cstring>
  45. #include <cassert>
  46. #include <sstream>
  47. #include "message.h"
  48. #include "DlRetryEx.h"
  49. #include "DlAbortEx.h"
  50. #include "fmt.h"
  51. #include "util.h"
  52. #include "TimeA2.h"
  53. #include "a2functional.h"
  54. #include "LogFactory.h"
  55. #include "A2STR.h"
  56. #ifdef ENABLE_SSL
  57. # include "TLSContext.h"
  58. # include "TLSSession.h"
  59. #endif // ENABLE_SSL
  60. #ifdef HAVE_LIBSSH2
  61. # include "SSHSession.h"
  62. #endif // HAVE_LIBSSH2
  63. namespace aria2 {
  64. #ifndef __MINGW32__
  65. # define SOCKET_ERRNO (errno)
  66. #else
  67. # define SOCKET_ERRNO (WSAGetLastError())
  68. #endif // __MINGW32__
  69. #ifdef __MINGW32__
  70. # define A2_EINPROGRESS WSAEWOULDBLOCK
  71. # define A2_EWOULDBLOCK WSAEWOULDBLOCK
  72. # define A2_EINTR WSAEINTR
  73. # define A2_WOULDBLOCK(e) (e == WSAEWOULDBLOCK)
  74. #else // !__MINGW32__
  75. # define A2_EINPROGRESS EINPROGRESS
  76. # ifndef EWOULDBLOCK
  77. # define EWOULDBLOCK EAGAIN
  78. # endif // EWOULDBLOCK
  79. # define A2_EWOULDBLOCK EWOULDBLOCK
  80. # define A2_EINTR EINTR
  81. # if EWOULDBLOCK == EAGAIN
  82. # define A2_WOULDBLOCK(e) (e == EWOULDBLOCK)
  83. # else // EWOULDBLOCK != EAGAIN
  84. # define A2_WOULDBLOCK(e) (e == EWOULDBLOCK || e == EAGAIN)
  85. # endif // EWOULDBLOCK != EAGAIN
  86. #endif // !__MINGW32__
  87. #ifdef __MINGW32__
  88. # define CLOSE(X) ::closesocket(X)
  89. #else
  90. # define CLOSE(X) close(X)
  91. #endif // __MINGW32__
  92. namespace {
  93. std::string errorMsg(int errNum)
  94. {
  95. #ifndef __MINGW32__
  96. return util::safeStrerror(errNum);
  97. #else
  98. static char buf[256];
  99. if (FormatMessage(
  100. FORMAT_MESSAGE_FROM_SYSTEM |
  101. FORMAT_MESSAGE_IGNORE_INSERTS,
  102. nullptr,
  103. errNum,
  104. MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  105. (LPTSTR) &buf,
  106. sizeof(buf),
  107. nullptr
  108. ) == 0) {
  109. snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, errNum, errNum);
  110. }
  111. return buf;
  112. #endif // __MINGW32__
  113. }
  114. } // namespace
  115. namespace {
  116. enum TlsState {
  117. // TLS object is not initialized.
  118. A2_TLS_NONE = 0,
  119. // TLS object is now handshaking.
  120. A2_TLS_HANDSHAKING = 2,
  121. // TLS object is now connected.
  122. A2_TLS_CONNECTED = 3
  123. };
  124. } // namespace
  125. int SocketCore::protocolFamily_ = AF_UNSPEC;
  126. int SocketCore::ipDscp_ = 0;
  127. std::vector<std::pair<sockaddr_union, socklen_t> >
  128. SocketCore::bindAddrs_;
  129. std::vector<std::vector<std::pair<sockaddr_union, socklen_t> > >
  130. SocketCore::bindAddrsList_;
  131. std::vector<std::vector<std::pair<sockaddr_union, socklen_t> > >::iterator
  132. SocketCore::bindAddrsListIt_;
  133. int SocketCore::socketRecvBufferSize_ = 0;
  134. #ifdef ENABLE_SSL
  135. std::shared_ptr<TLSContext> SocketCore::clTlsContext_;
  136. std::shared_ptr<TLSContext> SocketCore::svTlsContext_;
  137. void SocketCore::setClientTLSContext
  138. (const std::shared_ptr<TLSContext>& tlsContext)
  139. {
  140. clTlsContext_ = tlsContext;
  141. }
  142. void SocketCore::setServerTLSContext
  143. (const std::shared_ptr<TLSContext>& tlsContext)
  144. {
  145. svTlsContext_ = tlsContext;
  146. }
  147. #endif // ENABLE_SSL
  148. SocketCore::SocketCore(int sockType)
  149. : sockType_(sockType),
  150. sockfd_(-1)
  151. {
  152. init();
  153. }
  154. SocketCore::SocketCore(sock_t sockfd, int sockType)
  155. : sockType_(sockType),
  156. sockfd_(sockfd)
  157. {
  158. init();
  159. }
  160. void SocketCore::init()
  161. {
  162. blocking_ = true;
  163. secure_ = A2_TLS_NONE;
  164. wantRead_ = false;
  165. wantWrite_ = false;
  166. }
  167. SocketCore::~SocketCore() {
  168. closeConnection();
  169. }
  170. namespace {
  171. void applySocketBufferSize(sock_t fd)
  172. {
  173. auto recvBufSize = SocketCore::getSocketRecvBufferSize();
  174. if (recvBufSize == 0) {
  175. return;
  176. }
  177. if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (a2_sockopt_t)&recvBufSize,
  178. sizeof(recvBufSize)) < 0) {
  179. auto errNum = SOCKET_ERRNO;
  180. A2_LOG_WARN(fmt("Failed to set socket buffer size. Cause: %s",
  181. errorMsg(errNum).c_str()));
  182. }
  183. }
  184. } // namespace
  185. void SocketCore::create(int family, int protocol)
  186. {
  187. int errNum;
  188. closeConnection();
  189. sock_t fd = socket(family, sockType_, protocol);
  190. errNum = SOCKET_ERRNO;
  191. if(fd == (sock_t) -1) {
  192. throw DL_ABORT_EX
  193. (fmt("Failed to create socket. Cause:%s", errorMsg(errNum).c_str()));
  194. }
  195. int sockopt = 1;
  196. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
  197. (a2_sockopt_t) &sockopt, sizeof(sockopt)) < 0) {
  198. errNum = SOCKET_ERRNO;
  199. CLOSE(fd);
  200. throw DL_ABORT_EX
  201. (fmt("Failed to create socket. Cause:%s", errorMsg(errNum).c_str()));
  202. }
  203. applySocketBufferSize(fd);
  204. sockfd_ = fd;
  205. }
  206. static sock_t bindInternal
  207. (int family, int socktype, int protocol,
  208. const struct sockaddr* addr, socklen_t addrlen,
  209. std::string& error)
  210. {
  211. int errNum;
  212. sock_t fd = socket(family, socktype, protocol);
  213. errNum = SOCKET_ERRNO;
  214. if(fd == (sock_t) -1) {
  215. error = errorMsg(errNum);
  216. return -1;
  217. }
  218. int sockopt = 1;
  219. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (a2_sockopt_t) &sockopt,
  220. sizeof(sockopt)) < 0) {
  221. errNum = SOCKET_ERRNO;
  222. error = errorMsg(errNum);
  223. CLOSE(fd);
  224. return -1;
  225. }
  226. #ifdef IPV6_V6ONLY
  227. if(family == AF_INET6) {
  228. int sockopt = 1;
  229. if(setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (a2_sockopt_t) &sockopt,
  230. sizeof(sockopt)) < 0) {
  231. errNum = SOCKET_ERRNO;
  232. error = errorMsg(errNum);
  233. CLOSE(fd);
  234. return -1;
  235. }
  236. }
  237. #endif // IPV6_V6ONLY
  238. applySocketBufferSize(fd);
  239. if(::bind(fd, addr, addrlen) == -1) {
  240. errNum = SOCKET_ERRNO;
  241. error = errorMsg(errNum);
  242. CLOSE(fd);
  243. return -1;
  244. }
  245. return fd;
  246. }
  247. static sock_t bindTo
  248. (const char* host, uint16_t port, int family, int sockType,
  249. int getaddrinfoFlags, std::string& error)
  250. {
  251. struct addrinfo* res;
  252. int s = callGetaddrinfo(&res, host, util::uitos(port).c_str(),
  253. family, sockType, getaddrinfoFlags, 0);
  254. if(s) {
  255. error = gai_strerror(s);
  256. return -1;
  257. }
  258. std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
  259. (res, freeaddrinfo);
  260. struct addrinfo* rp;
  261. for(rp = res; rp; rp = rp->ai_next) {
  262. sock_t fd = bindInternal(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
  263. rp->ai_addr, rp->ai_addrlen, error);
  264. if(fd != (sock_t)-1) {
  265. return fd;
  266. }
  267. }
  268. return -1;
  269. }
  270. void SocketCore::bindWithFamily(uint16_t port, int family, int flags)
  271. {
  272. closeConnection();
  273. std::string error;
  274. sock_t fd = bindTo(nullptr, port, family, sockType_, flags, error);
  275. if(fd == (sock_t) -1) {
  276. throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
  277. }
  278. sockfd_ = fd;
  279. }
  280. void SocketCore::bind
  281. (const char* addr, uint16_t port, int family, int flags)
  282. {
  283. closeConnection();
  284. std::string error;
  285. const char* addrp;
  286. if(addr && addr[0]) {
  287. addrp = addr;
  288. } else {
  289. addrp = nullptr;
  290. }
  291. if(!(flags&AI_PASSIVE) || bindAddrs_.empty()) {
  292. sock_t fd = bindTo(addrp, port, family, sockType_, flags, error);
  293. if(fd == (sock_t) -1) {
  294. throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
  295. }
  296. sockfd_ = fd;
  297. return;
  298. }
  299. for (const auto& a : bindAddrs_) {
  300. char host[NI_MAXHOST];
  301. int s;
  302. s = getnameinfo(&a.first.sa, a.second, host, NI_MAXHOST, nullptr, 0,
  303. NI_NUMERICHOST);
  304. if(s) {
  305. error = gai_strerror(s);
  306. continue;
  307. }
  308. if(addrp && strcmp(host, addrp) != 0) {
  309. error = "Given address and resolved address do not match.";
  310. continue;
  311. }
  312. sock_t fd = bindTo(host, port, family, sockType_, flags, error);
  313. if(fd != (sock_t)-1) {
  314. sockfd_ = fd;
  315. break;
  316. }
  317. }
  318. if(sockfd_ == (sock_t) -1) {
  319. throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
  320. }
  321. }
  322. void SocketCore::bind(uint16_t port, int flags)
  323. {
  324. bind(nullptr, port, protocolFamily_, flags);
  325. }
  326. void SocketCore::bind(const struct sockaddr* addr, socklen_t addrlen)
  327. {
  328. closeConnection();
  329. std::string error;
  330. sock_t fd = bindInternal(addr->sa_family, sockType_, 0, addr, addrlen, error);
  331. if(fd == (sock_t)-1) {
  332. throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
  333. }
  334. sockfd_ = fd;
  335. }
  336. void SocketCore::beginListen()
  337. {
  338. if(listen(sockfd_, 1) == -1) {
  339. int errNum = SOCKET_ERRNO;
  340. throw DL_ABORT_EX(fmt(EX_SOCKET_LISTEN, errorMsg(errNum).c_str()));
  341. }
  342. setNonBlockingMode();
  343. }
  344. std::shared_ptr<SocketCore> SocketCore::acceptConnection() const
  345. {
  346. sockaddr_union sockaddr;
  347. socklen_t len = sizeof(sockaddr);
  348. sock_t fd;
  349. while((fd = accept(sockfd_, &sockaddr.sa, &len)) == (sock_t) -1 &&
  350. SOCKET_ERRNO == A2_EINTR);
  351. int errNum = SOCKET_ERRNO;
  352. if(fd == (sock_t) -1) {
  353. throw DL_ABORT_EX(fmt(EX_SOCKET_ACCEPT, errorMsg(errNum).c_str()));
  354. }
  355. applySocketBufferSize(fd);
  356. auto sock = std::make_shared<SocketCore>(fd, sockType_);
  357. sock->setNonBlockingMode();
  358. return sock;
  359. }
  360. int SocketCore::getAddrInfo(std::pair<std::string, uint16_t>& addrinfo) const
  361. {
  362. sockaddr_union sockaddr;
  363. socklen_t len = sizeof(sockaddr);
  364. getAddrInfo(sockaddr, len);
  365. addrinfo = util::getNumericNameInfo(&sockaddr.sa, len);
  366. return sockaddr.storage.ss_family;
  367. }
  368. void SocketCore::getAddrInfo(sockaddr_union& sockaddr, socklen_t& len) const
  369. {
  370. if(getsockname(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. }
  375. int SocketCore::getAddressFamily() const
  376. {
  377. sockaddr_union sockaddr;
  378. socklen_t len = sizeof(sockaddr);
  379. getAddrInfo(sockaddr, len);
  380. return sockaddr.storage.ss_family;
  381. }
  382. int SocketCore::getPeerInfo(std::pair<std::string, uint16_t>& peerinfo) const
  383. {
  384. sockaddr_union sockaddr;
  385. socklen_t len = sizeof(sockaddr);
  386. if(getpeername(sockfd_, &sockaddr.sa, &len) == -1) {
  387. int errNum = SOCKET_ERRNO;
  388. throw DL_ABORT_EX(fmt(EX_SOCKET_GET_NAME, errorMsg(errNum).c_str()));
  389. }
  390. peerinfo = util::getNumericNameInfo(&sockaddr.sa, len);
  391. return sockaddr.storage.ss_family;
  392. }
  393. void SocketCore::establishConnection(const std::string& host, uint16_t port,
  394. bool tcpNodelay)
  395. {
  396. closeConnection();
  397. std::string error;
  398. struct addrinfo* res;
  399. int s;
  400. s = callGetaddrinfo(&res, host.c_str(), util::uitos(port).c_str(),
  401. protocolFamily_, sockType_, 0, 0);
  402. if(s) {
  403. throw DL_ABORT_EX(fmt(EX_RESOLVE_HOSTNAME, host.c_str(), gai_strerror(s)));
  404. }
  405. std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
  406. (res, freeaddrinfo);
  407. struct addrinfo* rp;
  408. int errNum;
  409. for(rp = res; rp; rp = rp->ai_next) {
  410. sock_t fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
  411. errNum = SOCKET_ERRNO;
  412. if(fd == (sock_t) -1) {
  413. error = errorMsg(errNum);
  414. continue;
  415. }
  416. int sockopt = 1;
  417. if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (a2_sockopt_t) &sockopt,
  418. sizeof(sockopt)) < 0) {
  419. errNum = SOCKET_ERRNO;
  420. error = errorMsg(errNum);
  421. CLOSE(fd);
  422. continue;
  423. }
  424. applySocketBufferSize(fd);
  425. if(!bindAddrs_.empty()) {
  426. bool bindSuccess = false;
  427. for(std::vector<std::pair<sockaddr_union, socklen_t> >::
  428. const_iterator i = bindAddrs_.begin(), eoi = bindAddrs_.end();
  429. i != eoi; ++i) {
  430. if(::bind(fd, &(*i).first.sa, (*i).second) == -1) {
  431. errNum = SOCKET_ERRNO;
  432. error = errorMsg(errNum);
  433. A2_LOG_DEBUG(fmt(EX_SOCKET_BIND, error.c_str()));
  434. } else {
  435. bindSuccess = true;
  436. break;
  437. }
  438. }
  439. if(!bindSuccess) {
  440. CLOSE(fd);
  441. continue;
  442. }
  443. }
  444. if(!bindAddrsList_.empty()) {
  445. ++bindAddrsListIt_;
  446. if (bindAddrsListIt_ == bindAddrsList_.end()) {
  447. bindAddrsListIt_ = bindAddrsList_.begin();
  448. }
  449. bindAddrs_ = *bindAddrsListIt_;
  450. }
  451. sockfd_ = fd;
  452. // make socket non-blocking mode
  453. setNonBlockingMode();
  454. if(tcpNodelay) {
  455. setTcpNodelay(true);
  456. }
  457. if(connect(fd, rp->ai_addr, rp->ai_addrlen) == -1 &&
  458. SOCKET_ERRNO != A2_EINPROGRESS) {
  459. errNum = SOCKET_ERRNO;
  460. error = errorMsg(errNum);
  461. CLOSE(sockfd_);
  462. sockfd_ = (sock_t) -1;
  463. continue;
  464. }
  465. // TODO at this point, connection may not be established and it may fail
  466. // later. In such case, next ai_addr should be tried.
  467. break;
  468. }
  469. if(sockfd_ == (sock_t) -1) {
  470. throw DL_ABORT_EX(fmt(EX_SOCKET_CONNECT, host.c_str(), error.c_str()));
  471. }
  472. }
  473. void SocketCore::setSockOpt
  474. (int level, int optname, void* optval, socklen_t optlen)
  475. {
  476. if(setsockopt(sockfd_, level, optname, (a2_sockopt_t)optval, optlen) < 0) {
  477. int errNum = SOCKET_ERRNO;
  478. throw DL_ABORT_EX(fmt(EX_SOCKET_SET_OPT, errorMsg(errNum).c_str()));
  479. }
  480. }
  481. void SocketCore::setMulticastInterface(const std::string& localAddr)
  482. {
  483. in_addr addr;
  484. if(localAddr.empty()) {
  485. addr.s_addr = htonl(INADDR_ANY);
  486. }
  487. else if(inetPton(AF_INET, localAddr.c_str(), &addr) != 0) {
  488. throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
  489. localAddr.c_str()));
  490. }
  491. setSockOpt(IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr));
  492. }
  493. void SocketCore::setMulticastTtl(unsigned char ttl)
  494. {
  495. setSockOpt(IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
  496. }
  497. void SocketCore::setMulticastLoop(unsigned char loop)
  498. {
  499. setSockOpt(IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
  500. }
  501. void SocketCore::joinMulticastGroup
  502. (const std::string& multicastAddr, uint16_t multicastPort,
  503. const std::string& localAddr)
  504. {
  505. in_addr multiAddr;
  506. if(inetPton(AF_INET, multicastAddr.c_str(), &multiAddr) != 0) {
  507. throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
  508. multicastAddr.c_str()));
  509. }
  510. in_addr ifAddr;
  511. if(localAddr.empty()) {
  512. ifAddr.s_addr = htonl(INADDR_ANY);
  513. }
  514. else if(inetPton(AF_INET, localAddr.c_str(), &ifAddr) != 0) {
  515. throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
  516. localAddr.c_str()));
  517. }
  518. struct ip_mreq mreq;
  519. memset(&mreq, 0, sizeof(mreq));
  520. mreq.imr_multiaddr = multiAddr;
  521. mreq.imr_interface = ifAddr;
  522. setSockOpt(IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
  523. }
  524. void SocketCore::setTcpNodelay(bool f)
  525. {
  526. int val = f;
  527. setSockOpt(IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
  528. }
  529. void SocketCore::applyIpDscp()
  530. {
  531. if(ipDscp_ == 0) {
  532. return;
  533. }
  534. try {
  535. int family = getAddressFamily();
  536. if(family == AF_INET) {
  537. setSockOpt(IPPROTO_IP, IP_TOS, &ipDscp_, sizeof(ipDscp_));
  538. }
  539. #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
  540. else if(family == AF_INET6) {
  541. setSockOpt(IPPROTO_IPV6, IPV6_TCLASS, &ipDscp_, sizeof(ipDscp_));
  542. }
  543. #endif
  544. } catch(RecoverableException& e) {
  545. A2_LOG_INFO_EX("Applying DSCP value failed", e);
  546. }
  547. }
  548. void SocketCore::setNonBlockingMode()
  549. {
  550. #ifdef __MINGW32__
  551. static u_long flag = 1;
  552. if (::ioctlsocket(sockfd_, FIONBIO, &flag) == -1) {
  553. int errNum = SOCKET_ERRNO;
  554. throw DL_ABORT_EX(fmt(EX_SOCKET_NONBLOCKING, errorMsg(errNum).c_str()));
  555. }
  556. #else
  557. int flags;
  558. while((flags = fcntl(sockfd_, F_GETFL, 0)) == -1 && errno == EINTR);
  559. // TODO add error handling
  560. while(fcntl(sockfd_, F_SETFL, flags|O_NONBLOCK) == -1 && errno == EINTR);
  561. #endif // __MINGW32__
  562. blocking_ = false;
  563. }
  564. void SocketCore::setBlockingMode()
  565. {
  566. #ifdef __MINGW32__
  567. static u_long flag = 0;
  568. if (::ioctlsocket(sockfd_, FIONBIO, &flag) == -1) {
  569. int errNum = SOCKET_ERRNO;
  570. throw DL_ABORT_EX(fmt(EX_SOCKET_BLOCKING, errorMsg(errNum).c_str()));
  571. }
  572. #else
  573. int flags;
  574. while((flags = fcntl(sockfd_, F_GETFL, 0)) == -1 && errno == EINTR);
  575. // TODO add error handling
  576. while(fcntl(sockfd_, F_SETFL, flags&(~O_NONBLOCK)) == -1 && errno == EINTR);
  577. #endif // __MINGW32__
  578. blocking_ = true;
  579. }
  580. void SocketCore::closeConnection()
  581. {
  582. #ifdef ENABLE_SSL
  583. if(tlsSession_) {
  584. tlsSession_->closeConnection();
  585. tlsSession_.reset();
  586. }
  587. #endif // ENABLE_SSL
  588. #ifdef HAVE_LIBSSH2
  589. if(sshSession_) {
  590. sshSession_->closeConnection();
  591. sshSession_.reset();
  592. }
  593. #endif // HAVE_LIBSSH2
  594. if(sockfd_ != (sock_t) -1) {
  595. shutdown(sockfd_, SHUT_WR);
  596. CLOSE(sockfd_);
  597. sockfd_ = -1;
  598. }
  599. }
  600. #ifndef __MINGW32__
  601. # define CHECK_FD(fd) \
  602. if(fd < 0 || FD_SETSIZE <= fd) { \
  603. logger_->warn("Detected file descriptor >= FD_SETSIZE or < 0. " \
  604. "Download may slow down or fail."); \
  605. return false; \
  606. }
  607. #endif // !__MINGW32__
  608. bool SocketCore::isWritable(time_t timeout)
  609. {
  610. #ifdef HAVE_POLL
  611. struct pollfd p;
  612. p.fd = sockfd_;
  613. p.events = POLLOUT;
  614. int r;
  615. while((r = poll(&p, 1, timeout*1000)) == -1 && errno == EINTR);
  616. int errNum = SOCKET_ERRNO;
  617. if(r > 0) {
  618. return p.revents&(POLLOUT|POLLHUP|POLLERR);
  619. }
  620. if(r == 0) {
  621. return false;
  622. }
  623. throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_WRITABLE, errorMsg(errNum).c_str()));
  624. #else // !HAVE_POLL
  625. # ifndef __MINGW32__
  626. CHECK_FD(sockfd_);
  627. # endif // !__MINGW32__
  628. fd_set fds;
  629. FD_ZERO(&fds);
  630. FD_SET(sockfd_, &fds);
  631. struct timeval tv;
  632. tv.tv_sec = timeout;
  633. tv.tv_usec = 0;
  634. int r = select(sockfd_+1, nullptr, &fds, nullptr, &tv);
  635. int errNum = SOCKET_ERRNO;
  636. if(r == 1) {
  637. return true;
  638. }
  639. if(r == 0) {
  640. // time out
  641. return false;
  642. }
  643. if(errNum == A2_EINPROGRESS || errNum == A2_EINTR) {
  644. return false;
  645. }
  646. throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_WRITABLE, errorMsg(errNum).c_str()));
  647. #endif // !HAVE_POLL
  648. }
  649. bool SocketCore::isReadable(time_t timeout)
  650. {
  651. #ifdef HAVE_POLL
  652. struct pollfd p;
  653. p.fd = sockfd_;
  654. p.events = POLLIN;
  655. int r;
  656. while((r = poll(&p, 1, timeout*1000)) == -1 && errno == EINTR);
  657. int errNum = SOCKET_ERRNO;
  658. if(r > 0) {
  659. return p.revents&(POLLIN|POLLHUP|POLLERR);
  660. }
  661. if(r == 0) {
  662. return false;
  663. }
  664. throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_READABLE, errorMsg(errNum).c_str()));
  665. #else // !HAVE_POLL
  666. # ifndef __MINGW32__
  667. CHECK_FD(sockfd_);
  668. # endif // !__MINGW32__
  669. fd_set fds;
  670. FD_ZERO(&fds);
  671. FD_SET(sockfd_, &fds);
  672. struct timeval tv;
  673. tv.tv_sec = timeout;
  674. tv.tv_usec = 0;
  675. int r = select(sockfd_+1, &fds, nullptr, nullptr, &tv);
  676. int errNum = SOCKET_ERRNO;
  677. if(r == 1) {
  678. return true;
  679. }
  680. if(r == 0) {
  681. // time out
  682. return false;
  683. }
  684. if(errNum == A2_EINPROGRESS || errNum == A2_EINTR) {
  685. return false;
  686. }
  687. throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_READABLE, errorMsg(errNum).c_str()));
  688. #endif // !HAVE_POLL
  689. }
  690. ssize_t SocketCore::writeVector(a2iovec *iov, size_t iovcnt)
  691. {
  692. ssize_t ret = 0;
  693. wantRead_ = false;
  694. wantWrite_ = false;
  695. if(!secure_) {
  696. #ifdef __MINGW32__
  697. DWORD nsent;
  698. int rv = WSASend(sockfd_, iov, iovcnt, &nsent, 0, 0, 0);
  699. if(rv == 0) {
  700. ret = nsent;
  701. } else {
  702. ret = -1;
  703. }
  704. #else // !__MINGW32__
  705. while((ret = writev(sockfd_, iov, iovcnt)) == -1 &&
  706. SOCKET_ERRNO == A2_EINTR);
  707. #endif // !__MINGW32__
  708. int errNum = SOCKET_ERRNO;
  709. if(ret == -1) {
  710. if(!A2_WOULDBLOCK(errNum)) {
  711. throw DL_RETRY_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
  712. }
  713. wantWrite_ = true;
  714. ret = 0;
  715. }
  716. } else {
  717. // For SSL/TLS, we could not use writev, so just iterate vector
  718. // and write the data in normal way.
  719. for(size_t i = 0; i < iovcnt; ++i) {
  720. ssize_t rv = writeData(iov[i].A2IOVEC_BASE, iov[i].A2IOVEC_LEN);
  721. if(rv == 0) {
  722. break;
  723. }
  724. ret += rv;
  725. }
  726. }
  727. return ret;
  728. }
  729. ssize_t SocketCore::writeData(const void* data, size_t len)
  730. {
  731. ssize_t ret = 0;
  732. wantRead_ = false;
  733. wantWrite_ = false;
  734. if(!secure_) {
  735. // Cast for Windows send()
  736. while((ret = send(sockfd_, reinterpret_cast<const char*>(data),
  737. len, 0)) == -1 && SOCKET_ERRNO == A2_EINTR);
  738. int errNum = SOCKET_ERRNO;
  739. if(ret == -1) {
  740. if(!A2_WOULDBLOCK(errNum)) {
  741. throw DL_RETRY_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
  742. }
  743. wantWrite_ = true;
  744. ret = 0;
  745. }
  746. } else {
  747. #ifdef ENABLE_SSL
  748. ret = tlsSession_->writeData(data, len);
  749. if(ret < 0) {
  750. if(ret != TLS_ERR_WOULDBLOCK) {
  751. throw DL_RETRY_EX(fmt(EX_SOCKET_SEND,
  752. tlsSession_->getLastErrorString().c_str()));
  753. }
  754. if(tlsSession_->checkDirection() == TLS_WANT_READ) {
  755. wantRead_ = true;
  756. } else {
  757. wantWrite_ = true;
  758. }
  759. ret = 0;
  760. }
  761. #endif // ENABLE_SSL
  762. }
  763. return ret;
  764. }
  765. void SocketCore::readData(void* data, size_t& len)
  766. {
  767. ssize_t ret = 0;
  768. wantRead_ = false;
  769. wantWrite_ = false;
  770. #ifdef HAVE_LIBSSH2
  771. if(sshSession_) {
  772. ret = sshSession_->readData(data, len);
  773. if(ret < 0) {
  774. if(ret != SSH_ERR_WOULDBLOCK) {
  775. throw DL_RETRY_EX(fmt(EX_SOCKET_RECV,
  776. sshSession_->getLastErrorString().c_str()));
  777. }
  778. if(sshSession_->checkDirection() == SSH_WANT_READ) {
  779. wantRead_ = true;
  780. } else {
  781. wantWrite_ = true;
  782. }
  783. ret = 0;
  784. }
  785. } else
  786. #endif // HAVE_LIBSSH2
  787. if(!secure_) {
  788. // Cast for Windows recv()
  789. while((ret = recv(sockfd_,
  790. reinterpret_cast<char*>(data), len, 0)) == -1 &&
  791. SOCKET_ERRNO == A2_EINTR);
  792. int errNum = SOCKET_ERRNO;
  793. if(ret == -1) {
  794. if(!A2_WOULDBLOCK(errNum)) {
  795. throw DL_RETRY_EX(fmt(EX_SOCKET_RECV, errorMsg(errNum).c_str()));
  796. }
  797. wantRead_ = true;
  798. ret = 0;
  799. }
  800. } else {
  801. #ifdef ENABLE_SSL
  802. ret = tlsSession_->readData(data, len);
  803. if(ret < 0) {
  804. if(ret != TLS_ERR_WOULDBLOCK) {
  805. throw DL_RETRY_EX(fmt(EX_SOCKET_RECV,
  806. tlsSession_->getLastErrorString().c_str()));
  807. }
  808. if(tlsSession_->checkDirection() == TLS_WANT_READ) {
  809. wantRead_ = true;
  810. } else {
  811. wantWrite_ = true;
  812. }
  813. ret = 0;
  814. }
  815. #endif // ENABLE_SSL
  816. }
  817. len = ret;
  818. }
  819. #ifdef ENABLE_SSL
  820. bool SocketCore::tlsAccept()
  821. {
  822. return tlsHandshake(svTlsContext_.get(), A2STR::NIL);
  823. }
  824. bool SocketCore::tlsConnect(const std::string& hostname)
  825. {
  826. return tlsHandshake(clTlsContext_.get(), hostname);
  827. }
  828. bool SocketCore::tlsHandshake(TLSContext* tlsctx, const std::string& hostname)
  829. {
  830. wantRead_ = false;
  831. wantWrite_ = false;
  832. if(secure_ == A2_TLS_CONNECTED) {
  833. // Already connected!
  834. return true;
  835. }
  836. if(secure_ == A2_TLS_NONE) {
  837. // Do some initial setup
  838. A2_LOG_DEBUG("Creating TLS session");
  839. tlsSession_.reset(TLSSession::make(tlsctx));
  840. auto rv = tlsSession_->init(sockfd_);
  841. if(rv != TLS_ERR_OK) {
  842. std::string error = tlsSession_->getLastErrorString();
  843. tlsSession_.reset();
  844. throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE, error.c_str()));
  845. }
  846. // Check hostname is not numeric and it includes ".". Setting
  847. // "localhost" will produce TLS alert with GNUTLS.
  848. if(tlsctx->getSide() == TLS_CLIENT &&
  849. !util::isNumericHost(hostname) &&
  850. hostname.find(".") != std::string::npos) {
  851. rv = tlsSession_->setSNIHostname(hostname);
  852. if(rv != TLS_ERR_OK) {
  853. throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE,
  854. tlsSession_->getLastErrorString().c_str()));
  855. }
  856. }
  857. // Done with the setup, now let handshaking begin immediately.
  858. secure_ = A2_TLS_HANDSHAKING;
  859. A2_LOG_DEBUG("TLS Handshaking");
  860. }
  861. if(secure_ == A2_TLS_HANDSHAKING) {
  862. // Starting handshake after initial setup or still handshaking.
  863. TLSVersion ver = TLS_PROTO_NONE;
  864. int rv = 0;
  865. std::string handshakeError;
  866. if(tlsctx->getSide() == TLS_CLIENT) {
  867. rv = tlsSession_->tlsConnect(hostname, ver, handshakeError);
  868. } else {
  869. rv = tlsSession_->tlsAccept(ver);
  870. }
  871. if(rv == TLS_ERR_OK) {
  872. // We're good, more or less.
  873. // 1. Construct peerinfo
  874. std::stringstream ss;
  875. if (!hostname.empty()) {
  876. ss << hostname << " (";
  877. }
  878. std::pair<std::string, uint16_t> peer;
  879. getPeerInfo(peer);
  880. ss << peer.first << ":" << peer.second;
  881. if (!hostname.empty()) {
  882. ss << ")";
  883. }
  884. auto peerInfo = ss.str();
  885. // 2. Issue any warnings
  886. switch(ver) {
  887. case TLS_PROTO_NONE:
  888. A2_LOG_WARN(fmt(MSG_WARN_UNKNOWN_TLS_CONNECTION, peerInfo.c_str()));
  889. break;
  890. case TLS_PROTO_SSL3:
  891. A2_LOG_WARN(fmt(MSG_WARN_OLD_TLS_CONNECTION,
  892. "SSLv3", peerInfo.c_str()));
  893. break;
  894. default:
  895. A2_LOG_DEBUG(fmt("Securely connected to %s", peerInfo.c_str()));
  896. break;
  897. }
  898. // 3. We're connected now!
  899. secure_ = A2_TLS_CONNECTED;
  900. return true;
  901. }
  902. if(rv == TLS_ERR_WOULDBLOCK) {
  903. // We're not done yet...
  904. if(tlsSession_->checkDirection() == TLS_WANT_READ) {
  905. // ... but read buffers are empty.
  906. wantRead_ = true;
  907. } else {
  908. // ... but write buffers are full.
  909. wantWrite_ = true;
  910. }
  911. // Returning false (instead of true==success or throwing) will cause this
  912. // function to be called again once buffering is dealt with
  913. return false;
  914. }
  915. if (rv == TLS_ERR_ERROR) {
  916. // Damn those error.
  917. throw DL_ABORT_EX(fmt("SSL/TLS handshake failure: %s",
  918. handshakeError.empty() ?
  919. tlsSession_->getLastErrorString().c_str() :
  920. handshakeError.c_str()));
  921. }
  922. // Some implementation passed back an invalid result.
  923. throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE,
  924. "Invalid connect state (this is a bug in the TLS "
  925. "backend!)"));
  926. }
  927. // We should never get here, i.e. all possible states should have been handled
  928. // and returned from a branch before! Getting here is a bug, of course!
  929. throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE, "Invalid state (this is a bug!)"));
  930. }
  931. #endif // ENABLE_SSL
  932. #ifdef HAVE_LIBSSH2
  933. bool SocketCore::sshHandshake(const std::string& hashType,
  934. const std::string& digest)
  935. {
  936. wantRead_ = false;
  937. wantWrite_ = false;
  938. if (!sshSession_) {
  939. sshSession_ = make_unique<SSHSession>();
  940. if (sshSession_->init(sockfd_) == SSH_ERR_ERROR) {
  941. throw DL_ABORT_EX("Could not create SSH session");
  942. }
  943. }
  944. auto rv = sshSession_->handshake();
  945. if (rv == SSH_ERR_WOULDBLOCK) {
  946. sshCheckDirection();
  947. return false;
  948. }
  949. if (rv == SSH_ERR_ERROR) {
  950. throw DL_ABORT_EX(fmt("SSH handshake failure: %s",
  951. sshSession_->getLastErrorString().c_str()));
  952. }
  953. if (!hashType.empty()) {
  954. auto actualDigest = sshSession_->hostkeyMessageDigest(hashType);
  955. if (actualDigest.empty()) {
  956. throw DL_ABORT_EX(fmt("Empty host key fingerprint from SSH layer: "
  957. "perhaps hash type %s is not supported?",
  958. hashType.c_str()));
  959. }
  960. if (digest != actualDigest) {
  961. throw DL_ABORT_EX(fmt("Unexpected SSH host key: expected %s, actual %s",
  962. util::toHex(digest).c_str(),
  963. util::toHex(actualDigest).c_str()));
  964. }
  965. }
  966. return true;
  967. }
  968. bool SocketCore::sshAuthPassword(const std::string& user,
  969. const std::string& password)
  970. {
  971. assert(sshSession_);
  972. wantRead_ = false;
  973. wantWrite_ = false;
  974. auto rv = sshSession_->authPassword(user, password);
  975. if (rv == SSH_ERR_WOULDBLOCK) {
  976. sshCheckDirection();
  977. return false;
  978. }
  979. if (rv == SSH_ERR_ERROR) {
  980. throw DL_ABORT_EX(fmt("SSH authentication failure: %s",
  981. sshSession_->getLastErrorString().c_str()));
  982. }
  983. return true;
  984. }
  985. bool SocketCore::sshSFTPOpen(const std::string& path)
  986. {
  987. assert(sshSession_);
  988. wantRead_ = false;
  989. wantWrite_ = false;
  990. auto rv = sshSession_->sftpOpen(path);
  991. if (rv == SSH_ERR_WOULDBLOCK) {
  992. sshCheckDirection();
  993. return false;
  994. }
  995. if (rv == SSH_ERR_ERROR) {
  996. throw DL_ABORT_EX(fmt("SSH opening SFTP path %s failed: %s",
  997. path.c_str(),
  998. sshSession_->getLastErrorString().c_str()));
  999. }
  1000. return true;
  1001. }
  1002. bool SocketCore::sshSFTPClose()
  1003. {
  1004. assert(sshSession_);
  1005. wantRead_ = false;
  1006. wantWrite_ = false;
  1007. auto rv = sshSession_->sftpClose();
  1008. if (rv == SSH_ERR_WOULDBLOCK) {
  1009. sshCheckDirection();
  1010. return false;
  1011. }
  1012. if (rv == SSH_ERR_ERROR) {
  1013. throw DL_ABORT_EX(fmt("SSH closing SFTP failed: %s",
  1014. sshSession_->getLastErrorString().c_str()));
  1015. }
  1016. return true;
  1017. }
  1018. bool SocketCore::sshSFTPStat(int64_t& totalLength, time_t& mtime,
  1019. const std::string& path)
  1020. {
  1021. assert(sshSession_);
  1022. wantRead_ = false;
  1023. wantWrite_ = false;
  1024. auto rv = sshSession_->sftpStat(totalLength, mtime);
  1025. if (rv == SSH_ERR_WOULDBLOCK) {
  1026. sshCheckDirection();
  1027. return false;
  1028. }
  1029. if (rv == SSH_ERR_ERROR) {
  1030. throw DL_ABORT_EX(fmt("SSH stat SFTP path %s filed: %s",
  1031. path.c_str(),
  1032. sshSession_->getLastErrorString().c_str()));
  1033. }
  1034. return true;
  1035. }
  1036. void SocketCore::sshSFTPSeek(int64_t pos)
  1037. {
  1038. assert(sshSession_);
  1039. sshSession_->sftpSeek(pos);
  1040. }
  1041. bool SocketCore::sshGracefulShutdown()
  1042. {
  1043. assert(sshSession_);
  1044. auto rv = sshSession_->gracefulShutdown();
  1045. if (rv == SSH_ERR_WOULDBLOCK) {
  1046. sshCheckDirection();
  1047. return false;
  1048. }
  1049. if (rv == SSH_ERR_ERROR) {
  1050. throw DL_ABORT_EX(fmt("SSH graceful shutdown failed: %s",
  1051. sshSession_->getLastErrorString().c_str()));
  1052. }
  1053. return true;
  1054. }
  1055. void SocketCore::sshCheckDirection()
  1056. {
  1057. if (sshSession_->checkDirection() == SSH_WANT_READ) {
  1058. wantRead_ = true;
  1059. } else {
  1060. wantWrite_ = true;
  1061. }
  1062. }
  1063. #endif // HAVE_LIBSSH2
  1064. ssize_t SocketCore::writeData(const void* data, size_t len,
  1065. const std::string& host, uint16_t port)
  1066. {
  1067. wantRead_ = false;
  1068. wantWrite_ = false;
  1069. struct addrinfo* res;
  1070. int s;
  1071. s = callGetaddrinfo(&res, host.c_str(), util::uitos(port).c_str(),
  1072. protocolFamily_, sockType_, 0, 0);
  1073. if(s) {
  1074. throw DL_ABORT_EX(fmt(EX_SOCKET_SEND, gai_strerror(s)));
  1075. }
  1076. std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
  1077. (res, freeaddrinfo);
  1078. struct addrinfo* rp;
  1079. ssize_t r = -1;
  1080. int errNum = 0;
  1081. for(rp = res; rp; rp = rp->ai_next) {
  1082. // Cast for Windows sendto()
  1083. while((r = sendto(sockfd_, reinterpret_cast<const char*>(data), len, 0,
  1084. rp->ai_addr, rp->ai_addrlen)) == -1
  1085. && A2_EINTR == SOCKET_ERRNO);
  1086. errNum = SOCKET_ERRNO;
  1087. if(r == static_cast<ssize_t>(len)) {
  1088. break;
  1089. }
  1090. if(r == -1 && A2_WOULDBLOCK(errNum)) {
  1091. wantWrite_ = true;
  1092. r = 0;
  1093. break;
  1094. }
  1095. }
  1096. if(r == -1) {
  1097. throw DL_ABORT_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
  1098. }
  1099. return r;
  1100. }
  1101. ssize_t SocketCore::readDataFrom(void* data, size_t len,
  1102. std::pair<std::string /* numerichost */,
  1103. uint16_t /* port */>& sender)
  1104. {
  1105. wantRead_ = false;
  1106. wantWrite_ = false;
  1107. sockaddr_union sockaddr;
  1108. socklen_t sockaddrlen = sizeof(sockaddr);
  1109. ssize_t r;
  1110. // Cast for Windows recvfrom()
  1111. while((r = recvfrom(sockfd_, reinterpret_cast<char*>(data), len, 0,
  1112. &sockaddr.sa, &sockaddrlen)) == -1
  1113. && A2_EINTR == SOCKET_ERRNO);
  1114. int errNum = SOCKET_ERRNO;
  1115. if(r == -1) {
  1116. if(!A2_WOULDBLOCK(errNum)) {
  1117. throw DL_RETRY_EX(fmt(EX_SOCKET_RECV, errorMsg(errNum).c_str()));
  1118. }
  1119. wantRead_ = true;
  1120. r = 0;
  1121. } else {
  1122. sender = util::getNumericNameInfo(&sockaddr.sa, sockaddrlen);
  1123. }
  1124. return r;
  1125. }
  1126. std::string SocketCore::getSocketError() const
  1127. {
  1128. int error;
  1129. socklen_t optlen = sizeof(error);
  1130. if(getsockopt(sockfd_, SOL_SOCKET, SO_ERROR,
  1131. (a2_sockopt_t) &error, &optlen) == -1) {
  1132. int errNum = SOCKET_ERRNO;
  1133. throw DL_ABORT_EX
  1134. (fmt("Failed to get socket error: %s", errorMsg(errNum).c_str()));
  1135. }
  1136. if(error != 0) {
  1137. return errorMsg(error);
  1138. }
  1139. return "";
  1140. }
  1141. bool SocketCore::wantRead() const
  1142. {
  1143. return wantRead_;
  1144. }
  1145. bool SocketCore::wantWrite() const
  1146. {
  1147. return wantWrite_;
  1148. }
  1149. void SocketCore::bindAddress(const std::string& iface)
  1150. {
  1151. std::vector<std::pair<sockaddr_union, socklen_t> > bindAddrs;
  1152. getInterfaceAddress(bindAddrs, iface, protocolFamily_);
  1153. if(bindAddrs.empty()) {
  1154. throw DL_ABORT_EX(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(),
  1155. "not available"));
  1156. }
  1157. bindAddrs_.swap(bindAddrs);
  1158. for (const auto& a: bindAddrs_) {
  1159. char host[NI_MAXHOST];
  1160. int s;
  1161. s = getnameinfo(&a.first.sa, a.second, host, NI_MAXHOST, nullptr, 0,
  1162. NI_NUMERICHOST);
  1163. if(s == 0) {
  1164. A2_LOG_DEBUG(fmt("Sockets will bind to %s", host));
  1165. }
  1166. }
  1167. }
  1168. void SocketCore::bindAllAddress(const std::string& ifaces)
  1169. {
  1170. std::vector<std::vector<std::pair<sockaddr_union, socklen_t> > > bindAddrsList;
  1171. std::vector<std::string> ifaceList;
  1172. util::split(ifaces.begin(), ifaces.end(), std::back_inserter(ifaceList), ',', true);
  1173. if (ifaceList.empty()) {
  1174. throw DL_ABORT_EX("List of interfaces is empty, one or more interfaces is required");
  1175. }
  1176. for (auto& iface: ifaceList) {
  1177. std::vector<std::pair<sockaddr_union, socklen_t> > bindAddrs;
  1178. getInterfaceAddress(bindAddrs, iface, protocolFamily_);
  1179. if(bindAddrs.empty()) {
  1180. throw DL_ABORT_EX(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(),
  1181. "not available"));
  1182. }
  1183. bindAddrsList.push_back(bindAddrs);
  1184. for (const auto& a: bindAddrs) {
  1185. char host[NI_MAXHOST];
  1186. int s;
  1187. s = getnameinfo(&a.first.sa, a.second, host, NI_MAXHOST, nullptr, 0,
  1188. NI_NUMERICHOST);
  1189. if(s == 0) {
  1190. A2_LOG_DEBUG(fmt("Sockets will bind to %s", host));
  1191. }
  1192. }
  1193. }
  1194. bindAddrsList_.swap(bindAddrsList);
  1195. bindAddrsListIt_ = bindAddrsList_.begin();
  1196. bindAddrs_ = *bindAddrsListIt_;
  1197. }
  1198. void SocketCore::setSocketRecvBufferSize(int size)
  1199. {
  1200. socketRecvBufferSize_ = size;
  1201. }
  1202. int SocketCore::getSocketRecvBufferSize()
  1203. {
  1204. return socketRecvBufferSize_;
  1205. }
  1206. void getInterfaceAddress
  1207. (std::vector<std::pair<sockaddr_union, socklen_t> >& ifAddrs,
  1208. const std::string& iface, int family, int aiFlags)
  1209. {
  1210. A2_LOG_DEBUG(fmt("Finding interface %s", iface.c_str()));
  1211. #ifdef HAVE_GETIFADDRS
  1212. // First find interface in interface addresses
  1213. struct ifaddrs* ifaddr = nullptr;
  1214. if(getifaddrs(&ifaddr) == -1) {
  1215. int errNum = SOCKET_ERRNO;
  1216. A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND,
  1217. iface.c_str(), errorMsg(errNum).c_str()));
  1218. } else {
  1219. std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> ifaddrDeleter
  1220. (ifaddr, freeifaddrs);
  1221. for(ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
  1222. if(!ifa->ifa_addr) {
  1223. continue;
  1224. }
  1225. int iffamily = ifa->ifa_addr->sa_family;
  1226. if(family == AF_UNSPEC) {
  1227. if(iffamily != AF_INET && iffamily != AF_INET6) {
  1228. continue;
  1229. }
  1230. } else if(family == AF_INET) {
  1231. if(iffamily != AF_INET) {
  1232. continue;
  1233. }
  1234. } else if(family == AF_INET6) {
  1235. if(iffamily != AF_INET6) {
  1236. continue;
  1237. }
  1238. } else {
  1239. continue;
  1240. }
  1241. if(strcmp(iface.c_str(), ifa->ifa_name) == 0) {
  1242. socklen_t bindAddrLen =
  1243. iffamily == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6);
  1244. sockaddr_union bindAddr;
  1245. memset(&bindAddr, 0, sizeof(bindAddr));
  1246. memcpy(&bindAddr.storage, ifa->ifa_addr, bindAddrLen);
  1247. ifAddrs.push_back(std::make_pair(bindAddr, bindAddrLen));
  1248. }
  1249. }
  1250. }
  1251. #endif // HAVE_GETIFADDRS
  1252. if(ifAddrs.empty()) {
  1253. addrinfo* res;
  1254. int s;
  1255. s = callGetaddrinfo(&res, iface.c_str(), nullptr, family, SOCK_STREAM, aiFlags,0);
  1256. if(s) {
  1257. A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), gai_strerror(s)));
  1258. } else {
  1259. std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
  1260. (res, freeaddrinfo);
  1261. addrinfo* rp;
  1262. for(rp = res; rp; rp = rp->ai_next) {
  1263. // Try to bind socket with this address. If it fails, the
  1264. // address is not for this machine.
  1265. try {
  1266. SocketCore socket;
  1267. socket.bind(rp->ai_addr, rp->ai_addrlen);
  1268. sockaddr_union bindAddr;
  1269. memset(&bindAddr, 0, sizeof(bindAddr));
  1270. memcpy(&bindAddr.storage, rp->ai_addr, rp->ai_addrlen);
  1271. ifAddrs.push_back(std::make_pair(bindAddr, rp->ai_addrlen));
  1272. } catch(RecoverableException& e) {
  1273. continue;
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. namespace {
  1280. int defaultAIFlags = DEFAULT_AI_FLAGS;
  1281. int getDefaultAIFlags()
  1282. {
  1283. return defaultAIFlags;
  1284. }
  1285. } // namespace
  1286. void setDefaultAIFlags(int flags)
  1287. {
  1288. defaultAIFlags = flags;
  1289. }
  1290. int callGetaddrinfo
  1291. (struct addrinfo** resPtr, const char* host, const char* service, int family,
  1292. int sockType, int flags, int protocol)
  1293. {
  1294. struct addrinfo hints;
  1295. memset(&hints, 0, sizeof(hints));
  1296. hints.ai_family = family;
  1297. hints.ai_socktype = sockType;
  1298. hints.ai_flags = getDefaultAIFlags();
  1299. hints.ai_flags |= flags;
  1300. hints.ai_protocol = protocol;
  1301. return getaddrinfo(host, service, &hints, resPtr);
  1302. }
  1303. int inetNtop(int af, const void* src, char* dst, socklen_t size)
  1304. {
  1305. sockaddr_union su;
  1306. memset(&su, 0, sizeof(su));
  1307. if(af == AF_INET) {
  1308. su.in.sin_family = AF_INET;
  1309. #ifdef HAVE_SOCKADDR_IN_SIN_LEN
  1310. su.in.sin_len = sizeof(su.in);
  1311. #endif // HAVE_SOCKADDR_IN_SIN_LEN
  1312. memcpy(&su.in.sin_addr, src, sizeof(su.in.sin_addr));
  1313. return getnameinfo(&su.sa, sizeof(su.in), dst, size, nullptr, 0,
  1314. NI_NUMERICHOST);
  1315. }
  1316. if(af == AF_INET6) {
  1317. su.in6.sin6_family = AF_INET6;
  1318. #ifdef HAVE_SOCKADDR_IN6_SIN6_LEN
  1319. su.in6.sin6_len = sizeof(su.in6);
  1320. #endif // HAVE_SOCKADDR_IN6_SIN6_LEN
  1321. memcpy(&su.in6.sin6_addr, src, sizeof(su.in6.sin6_addr));
  1322. return getnameinfo(&su.sa, sizeof(su.in6), dst, size, nullptr, 0,
  1323. NI_NUMERICHOST);
  1324. }
  1325. return EAI_FAMILY;
  1326. }
  1327. int inetPton(int af, const char* src, void* dst)
  1328. {
  1329. union {
  1330. uint32_t ipv4_addr;
  1331. unsigned char ipv6_addr[16];
  1332. } binaddr;
  1333. size_t len = net::getBinAddr(binaddr.ipv6_addr, src);
  1334. if(af == AF_INET) {
  1335. if(len != 4) {
  1336. return -1;
  1337. }
  1338. in_addr* addr = reinterpret_cast<in_addr*>(dst);
  1339. addr->s_addr = binaddr.ipv4_addr;
  1340. return 0;
  1341. }
  1342. if(af == AF_INET6) {
  1343. if(len != 16) {
  1344. return -1;
  1345. }
  1346. in6_addr* addr = reinterpret_cast<in6_addr*>(dst);
  1347. memcpy(addr->s6_addr, binaddr.ipv6_addr, sizeof(addr->s6_addr));
  1348. return 0;
  1349. }
  1350. return -1;
  1351. }
  1352. namespace net {
  1353. size_t getBinAddr(void* dest, const std::string& ip)
  1354. {
  1355. size_t len = 0;
  1356. addrinfo* res;
  1357. if(callGetaddrinfo(&res, ip.c_str(), nullptr, AF_UNSPEC,
  1358. 0, AI_NUMERICHOST, 0) != 0) {
  1359. return len;
  1360. }
  1361. std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
  1362. (res, freeaddrinfo);
  1363. for(addrinfo* rp = res; rp; rp = rp->ai_next) {
  1364. sockaddr_union su;
  1365. memcpy(&su, rp->ai_addr, rp->ai_addrlen);
  1366. if(rp->ai_family == AF_INET) {
  1367. len = sizeof(in_addr);
  1368. memcpy(dest, &(su.in.sin_addr), len);
  1369. break;
  1370. } else if(rp->ai_family == AF_INET6) {
  1371. len = sizeof(in6_addr);
  1372. memcpy(dest, &(su.in6.sin6_addr), len);
  1373. break;
  1374. }
  1375. }
  1376. return len;
  1377. }
  1378. bool verifyHostname(const std::string& hostname,
  1379. const std::vector<std::string>& dnsNames,
  1380. const std::vector<std::string>& ipAddrs,
  1381. const std::string& commonName)
  1382. {
  1383. if(util::isNumericHost(hostname)) {
  1384. if(ipAddrs.empty()) {
  1385. return commonName == hostname;
  1386. }
  1387. // We need max 16 bytes to store IPv6 address.
  1388. unsigned char binAddr[16];
  1389. size_t addrLen = getBinAddr(binAddr, hostname);
  1390. if(addrLen == 0) {
  1391. return false;
  1392. }
  1393. for(auto& ipAddr : ipAddrs) {
  1394. if(addrLen == ipAddr.size() &&
  1395. memcmp(binAddr, ipAddr.c_str(), addrLen) == 0) {
  1396. return true;
  1397. }
  1398. }
  1399. return false;
  1400. }
  1401. if(dnsNames.empty()) {
  1402. return util::tlsHostnameMatch(commonName, hostname);
  1403. }
  1404. for(auto& dnsName : dnsNames) {
  1405. if(util::tlsHostnameMatch(dnsName, hostname)) {
  1406. return true;
  1407. }
  1408. }
  1409. return false;
  1410. }
  1411. namespace {
  1412. bool ipv4AddrConfigured = true;
  1413. bool ipv6AddrConfigured = true;
  1414. } // namespace
  1415. #ifdef __MINGW32__
  1416. namespace {
  1417. const uint32_t APIPA_IPV4_BEGIN = 2851995649u; // 169.254.0.1
  1418. const uint32_t APIPA_IPV4_END = 2852061183u; // 169.254.255.255
  1419. } // namespace
  1420. #endif // __MINGW32__
  1421. void checkAddrconfig()
  1422. {
  1423. #ifdef HAVE_IPHLPAPI_H
  1424. A2_LOG_INFO("Checking configured addresses");
  1425. ULONG bufsize = 15_k;
  1426. ULONG retval = 0;
  1427. IP_ADAPTER_ADDRESSES* buf = 0;
  1428. int numTry = 0;
  1429. const int MAX_TRY = 3;
  1430. do {
  1431. buf = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(malloc(bufsize));
  1432. retval = GetAdaptersAddresses(AF_UNSPEC, 0, 0, buf, &bufsize);
  1433. if(retval != ERROR_BUFFER_OVERFLOW) {
  1434. break;
  1435. }
  1436. free(buf);
  1437. buf = 0;
  1438. } while(retval == ERROR_BUFFER_OVERFLOW && numTry < MAX_TRY);
  1439. if(retval != NO_ERROR) {
  1440. A2_LOG_INFO("GetAdaptersAddresses failed. Assume both IPv4 and IPv6 "
  1441. " addresses are configured.");
  1442. return;
  1443. }
  1444. ipv4AddrConfigured = false;
  1445. ipv6AddrConfigured = false;
  1446. char host[NI_MAXHOST];
  1447. sockaddr_union ad;
  1448. int rv;
  1449. for(IP_ADAPTER_ADDRESSES* p = buf; p; p = p->Next) {
  1450. if(p->IfType == IF_TYPE_TUNNEL) {
  1451. // Skip tunnel interface because Windows7 automatically setup
  1452. // this for IPv6.
  1453. continue;
  1454. }
  1455. PIP_ADAPTER_UNICAST_ADDRESS ucaddr = p->FirstUnicastAddress;
  1456. if(!ucaddr) {
  1457. continue;
  1458. }
  1459. for(PIP_ADAPTER_UNICAST_ADDRESS i = ucaddr; i; i = i->Next) {
  1460. bool found = false;
  1461. switch(i->Address.iSockaddrLength) {
  1462. case sizeof(sockaddr_in): {
  1463. memcpy(&ad.storage, i->Address.lpSockaddr,
  1464. i->Address.iSockaddrLength);
  1465. uint32_t haddr = ntohl(ad.in.sin_addr.s_addr);
  1466. if(haddr != INADDR_LOOPBACK &&
  1467. (haddr < APIPA_IPV4_BEGIN || APIPA_IPV4_END <= haddr)) {
  1468. ipv4AddrConfigured = true;
  1469. found = true;
  1470. }
  1471. break;
  1472. }
  1473. case sizeof(sockaddr_in6):
  1474. memcpy(&ad.storage, i->Address.lpSockaddr,
  1475. i->Address.iSockaddrLength);
  1476. if(!IN6_IS_ADDR_LOOPBACK(&ad.in6.sin6_addr) &&
  1477. !IN6_IS_ADDR_LINKLOCAL(&ad.in6.sin6_addr)) {
  1478. ipv6AddrConfigured = true;
  1479. found = true;
  1480. }
  1481. break;
  1482. }
  1483. rv = getnameinfo(i->Address.lpSockaddr, i->Address.iSockaddrLength,
  1484. host, NI_MAXHOST, 0, 0, NI_NUMERICHOST);
  1485. if(rv == 0) {
  1486. if(found) {
  1487. A2_LOG_INFO(fmt("Found configured address: %s", host));
  1488. } else {
  1489. A2_LOG_INFO(fmt("Not considered: %s", host));
  1490. }
  1491. }
  1492. }
  1493. }
  1494. free(buf);
  1495. A2_LOG_INFO(fmt("IPv4 configured=%d, IPv6 configured=%d",
  1496. ipv4AddrConfigured, ipv6AddrConfigured));
  1497. #elif defined(HAVE_GETIFADDRS)
  1498. A2_LOG_INFO("Checking configured addresses");
  1499. ipv4AddrConfigured = false;
  1500. ipv6AddrConfigured = false;
  1501. ifaddrs* ifaddr = nullptr;
  1502. int rv;
  1503. rv = getifaddrs(&ifaddr);
  1504. if(rv == -1) {
  1505. int errNum = SOCKET_ERRNO;
  1506. A2_LOG_INFO(fmt("getifaddrs failed. Cause: %s", errorMsg(errNum).c_str()));
  1507. return;
  1508. }
  1509. std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> ifaddrDeleter
  1510. (ifaddr, freeifaddrs);
  1511. char host[NI_MAXHOST];
  1512. sockaddr_union ad;
  1513. for(ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
  1514. if(!ifa->ifa_addr) {
  1515. continue;
  1516. }
  1517. bool found = false;
  1518. size_t addrlen = 0;
  1519. switch(ifa->ifa_addr->sa_family) {
  1520. case AF_INET: {
  1521. addrlen = sizeof(sockaddr_in);
  1522. memcpy(&ad.storage, ifa->ifa_addr, addrlen);
  1523. if(ad.in.sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
  1524. ipv4AddrConfigured = true;
  1525. found = true;
  1526. }
  1527. break;
  1528. }
  1529. case AF_INET6: {
  1530. addrlen = sizeof(sockaddr_in6);
  1531. memcpy(&ad.storage, ifa->ifa_addr, addrlen);
  1532. if(!IN6_IS_ADDR_LOOPBACK(&ad.in6.sin6_addr) &&
  1533. !IN6_IS_ADDR_LINKLOCAL(&ad.in6.sin6_addr)) {
  1534. ipv6AddrConfigured = true;
  1535. found = true;
  1536. }
  1537. break;
  1538. }
  1539. default:
  1540. continue;
  1541. }
  1542. rv = getnameinfo(ifa->ifa_addr, addrlen, host, NI_MAXHOST, nullptr, 0,
  1543. NI_NUMERICHOST);
  1544. if(rv == 0) {
  1545. if(found) {
  1546. A2_LOG_INFO(fmt("Found configured address: %s", host));
  1547. } else {
  1548. A2_LOG_INFO(fmt("Not considered: %s", host));
  1549. }
  1550. }
  1551. }
  1552. A2_LOG_INFO(fmt("IPv4 configured=%d, IPv6 configured=%d",
  1553. ipv4AddrConfigured, ipv6AddrConfigured));
  1554. #else // !HAVE_GETIFADDRS
  1555. A2_LOG_INFO("getifaddrs is not available. Assume IPv4 and IPv6 addresses"
  1556. " are configured.");
  1557. #endif // !HAVE_GETIFADDRS
  1558. }
  1559. bool getIPv4AddrConfigured()
  1560. {
  1561. return ipv4AddrConfigured;
  1562. }
  1563. bool getIPv6AddrConfigured()
  1564. {
  1565. return ipv6AddrConfigured;
  1566. }
  1567. } // namespace net
  1568. } // namespace aria2