SocketCore.cc 39 KB

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