SocketCore.cc 46 KB

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