SocketCore.cc 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  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_, 1) == -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(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || \
  529. 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. auto peerInfo = ss.str();
  892. // 2. Issue any warnings
  893. switch (ver) {
  894. case TLS_PROTO_NONE:
  895. A2_LOG_WARN(fmt(MSG_WARN_UNKNOWN_TLS_CONNECTION, peerInfo.c_str()));
  896. break;
  897. case TLS_PROTO_SSL3:
  898. A2_LOG_WARN(
  899. fmt(MSG_WARN_OLD_TLS_CONNECTION, "SSLv3", peerInfo.c_str()));
  900. break;
  901. default:
  902. A2_LOG_DEBUG(fmt("Securely connected to %s", peerInfo.c_str()));
  903. break;
  904. }
  905. // 3. We're connected now!
  906. secure_ = A2_TLS_CONNECTED;
  907. return true;
  908. }
  909. if (rv == TLS_ERR_WOULDBLOCK) {
  910. // We're not done yet...
  911. if (tlsSession_->checkDirection() == TLS_WANT_READ) {
  912. // ... but read buffers are empty.
  913. wantRead_ = true;
  914. }
  915. else {
  916. // ... but write buffers are full.
  917. wantWrite_ = true;
  918. }
  919. // Returning false (instead of true==success or throwing) will cause this
  920. // function to be called again once buffering is dealt with
  921. return false;
  922. }
  923. if (rv == TLS_ERR_ERROR) {
  924. // Damn those error.
  925. throw DL_ABORT_EX(fmt("SSL/TLS handshake failure: %s",
  926. handshakeError.empty()
  927. ? tlsSession_->getLastErrorString().c_str()
  928. : handshakeError.c_str()));
  929. }
  930. // Some implementation passed back an invalid result.
  931. throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE,
  932. "Invalid connect state (this is a bug in the TLS "
  933. "backend!)"));
  934. }
  935. // We should never get here, i.e. all possible states should have been handled
  936. // and returned from a branch before! Getting here is a bug, of course!
  937. throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE, "Invalid state (this is a bug!)"));
  938. }
  939. #endif // ENABLE_SSL
  940. #ifdef HAVE_LIBSSH2
  941. bool SocketCore::sshHandshake(const std::string& hashType,
  942. const std::string& digest)
  943. {
  944. wantRead_ = false;
  945. wantWrite_ = false;
  946. if (!sshSession_) {
  947. sshSession_ = make_unique<SSHSession>();
  948. if (sshSession_->init(sockfd_) == SSH_ERR_ERROR) {
  949. throw DL_ABORT_EX("Could not create SSH session");
  950. }
  951. }
  952. auto rv = sshSession_->handshake();
  953. if (rv == SSH_ERR_WOULDBLOCK) {
  954. sshCheckDirection();
  955. return false;
  956. }
  957. if (rv == SSH_ERR_ERROR) {
  958. throw DL_ABORT_EX(fmt("SSH handshake failure: %s",
  959. sshSession_->getLastErrorString().c_str()));
  960. }
  961. if (!hashType.empty()) {
  962. auto actualDigest = sshSession_->hostkeyMessageDigest(hashType);
  963. if (actualDigest.empty()) {
  964. throw DL_ABORT_EX(fmt("Empty host key fingerprint from SSH layer: "
  965. "perhaps hash type %s is not supported?",
  966. hashType.c_str()));
  967. }
  968. if (digest != actualDigest) {
  969. throw DL_ABORT_EX(fmt("Unexpected SSH host key: expected %s, actual %s",
  970. util::toHex(digest).c_str(),
  971. util::toHex(actualDigest).c_str()));
  972. }
  973. }
  974. return true;
  975. }
  976. bool SocketCore::sshAuthPassword(const std::string& user,
  977. const std::string& password)
  978. {
  979. assert(sshSession_);
  980. wantRead_ = false;
  981. wantWrite_ = false;
  982. auto rv = sshSession_->authPassword(user, password);
  983. if (rv == SSH_ERR_WOULDBLOCK) {
  984. sshCheckDirection();
  985. return false;
  986. }
  987. if (rv == SSH_ERR_ERROR) {
  988. throw DL_ABORT_EX(fmt("SSH authentication failure: %s",
  989. sshSession_->getLastErrorString().c_str()));
  990. }
  991. return true;
  992. }
  993. bool SocketCore::sshSFTPOpen(const std::string& path)
  994. {
  995. assert(sshSession_);
  996. wantRead_ = false;
  997. wantWrite_ = false;
  998. auto rv = sshSession_->sftpOpen(path);
  999. if (rv == SSH_ERR_WOULDBLOCK) {
  1000. sshCheckDirection();
  1001. return false;
  1002. }
  1003. if (rv == SSH_ERR_ERROR) {
  1004. throw DL_ABORT_EX(fmt("SSH opening SFTP path %s failed: %s", path.c_str(),
  1005. sshSession_->getLastErrorString().c_str()));
  1006. }
  1007. return true;
  1008. }
  1009. bool SocketCore::sshSFTPClose()
  1010. {
  1011. assert(sshSession_);
  1012. wantRead_ = false;
  1013. wantWrite_ = false;
  1014. auto rv = sshSession_->sftpClose();
  1015. if (rv == SSH_ERR_WOULDBLOCK) {
  1016. sshCheckDirection();
  1017. return false;
  1018. }
  1019. if (rv == SSH_ERR_ERROR) {
  1020. throw DL_ABORT_EX(fmt("SSH closing SFTP failed: %s",
  1021. sshSession_->getLastErrorString().c_str()));
  1022. }
  1023. return true;
  1024. }
  1025. bool SocketCore::sshSFTPStat(int64_t& totalLength, time_t& mtime,
  1026. const std::string& path)
  1027. {
  1028. assert(sshSession_);
  1029. wantRead_ = false;
  1030. wantWrite_ = false;
  1031. auto rv = sshSession_->sftpStat(totalLength, mtime);
  1032. if (rv == SSH_ERR_WOULDBLOCK) {
  1033. sshCheckDirection();
  1034. return false;
  1035. }
  1036. if (rv == SSH_ERR_ERROR) {
  1037. throw DL_ABORT_EX(fmt("SSH stat SFTP path %s filed: %s", path.c_str(),
  1038. sshSession_->getLastErrorString().c_str()));
  1039. }
  1040. return true;
  1041. }
  1042. void SocketCore::sshSFTPSeek(int64_t pos)
  1043. {
  1044. assert(sshSession_);
  1045. sshSession_->sftpSeek(pos);
  1046. }
  1047. bool SocketCore::sshGracefulShutdown()
  1048. {
  1049. assert(sshSession_);
  1050. auto rv = sshSession_->gracefulShutdown();
  1051. if (rv == SSH_ERR_WOULDBLOCK) {
  1052. sshCheckDirection();
  1053. return false;
  1054. }
  1055. if (rv == SSH_ERR_ERROR) {
  1056. throw DL_ABORT_EX(fmt("SSH graceful shutdown failed: %s",
  1057. sshSession_->getLastErrorString().c_str()));
  1058. }
  1059. return true;
  1060. }
  1061. void SocketCore::sshCheckDirection()
  1062. {
  1063. if (sshSession_->checkDirection() == SSH_WANT_READ) {
  1064. wantRead_ = true;
  1065. }
  1066. else {
  1067. wantWrite_ = true;
  1068. }
  1069. }
  1070. #endif // HAVE_LIBSSH2
  1071. ssize_t SocketCore::writeData(const void* data, size_t len,
  1072. const std::string& host, uint16_t port)
  1073. {
  1074. wantRead_ = false;
  1075. wantWrite_ = false;
  1076. struct addrinfo* res;
  1077. int s;
  1078. s = callGetaddrinfo(&res, host.c_str(), util::uitos(port).c_str(),
  1079. protocolFamily_, sockType_, 0, 0);
  1080. if (s) {
  1081. throw DL_ABORT_EX(fmt(EX_SOCKET_SEND, gai_strerror(s)));
  1082. }
  1083. std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter(res,
  1084. freeaddrinfo);
  1085. struct addrinfo* rp;
  1086. ssize_t r = -1;
  1087. int errNum = 0;
  1088. for (rp = res; rp; rp = rp->ai_next) {
  1089. // Cast for Windows sendto()
  1090. while ((r = sendto(sockfd_, reinterpret_cast<const char*>(data), len, 0,
  1091. rp->ai_addr, rp->ai_addrlen)) == -1 &&
  1092. A2_EINTR == SOCKET_ERRNO)
  1093. ;
  1094. errNum = SOCKET_ERRNO;
  1095. if (r == static_cast<ssize_t>(len)) {
  1096. break;
  1097. }
  1098. if (r == -1 && A2_WOULDBLOCK(errNum)) {
  1099. wantWrite_ = true;
  1100. r = 0;
  1101. break;
  1102. }
  1103. }
  1104. if (r == -1) {
  1105. throw DL_ABORT_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
  1106. }
  1107. return r;
  1108. }
  1109. ssize_t SocketCore::readDataFrom(void* data, size_t len, Endpoint& sender)
  1110. {
  1111. wantRead_ = false;
  1112. wantWrite_ = false;
  1113. sockaddr_union sockaddr;
  1114. socklen_t sockaddrlen = sizeof(sockaddr);
  1115. ssize_t r;
  1116. // Cast for Windows recvfrom()
  1117. while ((r = recvfrom(sockfd_, reinterpret_cast<char*>(data), len, 0,
  1118. &sockaddr.sa, &sockaddrlen)) == -1 &&
  1119. A2_EINTR == SOCKET_ERRNO)
  1120. ;
  1121. int errNum = SOCKET_ERRNO;
  1122. if (r == -1) {
  1123. if (!A2_WOULDBLOCK(errNum)) {
  1124. throw DL_RETRY_EX(fmt(EX_SOCKET_RECV, errorMsg(errNum).c_str()));
  1125. }
  1126. wantRead_ = true;
  1127. r = 0;
  1128. }
  1129. else {
  1130. sender = util::getNumericNameInfo(&sockaddr.sa, sockaddrlen);
  1131. }
  1132. return r;
  1133. }
  1134. std::string SocketCore::getSocketError() const
  1135. {
  1136. int error;
  1137. socklen_t optlen = sizeof(error);
  1138. if (getsockopt(sockfd_, SOL_SOCKET, SO_ERROR, (a2_sockopt_t)&error,
  1139. &optlen) == -1) {
  1140. int errNum = SOCKET_ERRNO;
  1141. throw DL_ABORT_EX(
  1142. fmt("Failed to get socket error: %s", errorMsg(errNum).c_str()));
  1143. }
  1144. if (error != 0) {
  1145. return errorMsg(error);
  1146. }
  1147. return "";
  1148. }
  1149. bool SocketCore::wantRead() const { return wantRead_; }
  1150. bool SocketCore::wantWrite() const { return wantWrite_; }
  1151. void SocketCore::bindAddress(const std::string& iface)
  1152. {
  1153. auto bindAddrs = getInterfaceAddress(iface, protocolFamily_);
  1154. if (bindAddrs.empty()) {
  1155. throw DL_ABORT_EX(
  1156. fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), "not available"));
  1157. }
  1158. bindAddrs_.swap(bindAddrs);
  1159. for (const auto& a : bindAddrs_) {
  1160. char host[NI_MAXHOST];
  1161. int s;
  1162. s = getnameinfo(&a.su.sa, a.suLength, host, NI_MAXHOST, nullptr, 0,
  1163. NI_NUMERICHOST);
  1164. if (s == 0) {
  1165. A2_LOG_DEBUG(fmt("Sockets will bind to %s", host));
  1166. }
  1167. }
  1168. bindAddrsList_.push_back(bindAddrs_);
  1169. bindAddrsListIt_ = std::begin(bindAddrsList_);
  1170. }
  1171. void SocketCore::bindAllAddress(const std::string& ifaces)
  1172. {
  1173. std::vector<std::vector<SockAddr>> bindAddrsList;
  1174. std::vector<std::string> ifaceList;
  1175. util::split(ifaces.begin(), ifaces.end(), std::back_inserter(ifaceList), ',',
  1176. true);
  1177. if (ifaceList.empty()) {
  1178. throw DL_ABORT_EX(
  1179. "List of interfaces is empty, one or more interfaces is required");
  1180. }
  1181. for (auto& iface : ifaceList) {
  1182. auto bindAddrs = getInterfaceAddress(iface, protocolFamily_);
  1183. if (bindAddrs.empty()) {
  1184. throw DL_ABORT_EX(
  1185. fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), "not available"));
  1186. }
  1187. bindAddrsList.push_back(bindAddrs);
  1188. for (const auto& a : bindAddrs) {
  1189. char host[NI_MAXHOST];
  1190. int s;
  1191. s = getnameinfo(&a.su.sa, a.suLength, host, NI_MAXHOST, nullptr, 0,
  1192. NI_NUMERICHOST);
  1193. if (s == 0) {
  1194. A2_LOG_DEBUG(fmt("Sockets will bind to %s", host));
  1195. }
  1196. }
  1197. }
  1198. bindAddrsList_.swap(bindAddrsList);
  1199. bindAddrsListIt_ = bindAddrsList_.begin();
  1200. bindAddrs_ = *bindAddrsListIt_;
  1201. }
  1202. void SocketCore::setSocketRecvBufferSize(int size)
  1203. {
  1204. socketRecvBufferSize_ = size;
  1205. }
  1206. int SocketCore::getSocketRecvBufferSize() { return socketRecvBufferSize_; }
  1207. size_t SocketCore::getRecvBufferedLength() const
  1208. {
  1209. if (!tlsSession_) {
  1210. return 0;
  1211. }
  1212. return tlsSession_->getRecvBufferedLength();
  1213. }
  1214. std::vector<SockAddr> SocketCore::getInterfaceAddress(const std::string& iface,
  1215. int family, int aiFlags)
  1216. {
  1217. A2_LOG_DEBUG(fmt("Finding interface %s", iface.c_str()));
  1218. std::vector<SockAddr> ifAddrs;
  1219. #ifdef HAVE_GETIFADDRS
  1220. // First find interface in interface addresses
  1221. struct ifaddrs* ifaddr = nullptr;
  1222. if (getifaddrs(&ifaddr) == -1) {
  1223. int errNum = SOCKET_ERRNO;
  1224. A2_LOG_INFO(
  1225. fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), errorMsg(errNum).c_str()));
  1226. }
  1227. else {
  1228. std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> ifaddrDeleter(ifaddr,
  1229. freeifaddrs);
  1230. for (ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
  1231. if (!ifa->ifa_addr) {
  1232. continue;
  1233. }
  1234. int iffamily = ifa->ifa_addr->sa_family;
  1235. if (family == AF_UNSPEC) {
  1236. if (iffamily != AF_INET && iffamily != AF_INET6) {
  1237. continue;
  1238. }
  1239. }
  1240. else if (family == AF_INET) {
  1241. if (iffamily != AF_INET) {
  1242. continue;
  1243. }
  1244. }
  1245. else if (family == AF_INET6) {
  1246. if (iffamily != AF_INET6) {
  1247. continue;
  1248. }
  1249. }
  1250. else {
  1251. continue;
  1252. }
  1253. if (strcmp(iface.c_str(), ifa->ifa_name) == 0) {
  1254. SockAddr soaddr;
  1255. soaddr.suLength =
  1256. iffamily == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6);
  1257. memcpy(&soaddr.su, ifa->ifa_addr, soaddr.suLength);
  1258. ifAddrs.push_back(soaddr);
  1259. }
  1260. }
  1261. }
  1262. #endif // HAVE_GETIFADDRS
  1263. if (ifAddrs.empty()) {
  1264. addrinfo* res;
  1265. int s;
  1266. s = callGetaddrinfo(&res, iface.c_str(), nullptr, family, SOCK_STREAM,
  1267. aiFlags, 0);
  1268. if (s) {
  1269. A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), gai_strerror(s)));
  1270. }
  1271. else {
  1272. std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter(
  1273. res, freeaddrinfo);
  1274. addrinfo* rp;
  1275. for (rp = res; rp; rp = rp->ai_next) {
  1276. // Try to bind socket with this address. If it fails, the
  1277. // address is not for this machine.
  1278. try {
  1279. SocketCore socket;
  1280. socket.bind(rp->ai_addr, rp->ai_addrlen);
  1281. SockAddr soaddr;
  1282. memcpy(&soaddr.su, rp->ai_addr, rp->ai_addrlen);
  1283. soaddr.suLength = rp->ai_addrlen;
  1284. ifAddrs.push_back(soaddr);
  1285. }
  1286. catch (RecoverableException& e) {
  1287. continue;
  1288. }
  1289. }
  1290. }
  1291. }
  1292. return ifAddrs;
  1293. }
  1294. namespace {
  1295. int defaultAIFlags = DEFAULT_AI_FLAGS;
  1296. int getDefaultAIFlags() { return defaultAIFlags; }
  1297. } // namespace
  1298. void setDefaultAIFlags(int flags) { defaultAIFlags = flags; }
  1299. int callGetaddrinfo(struct addrinfo** resPtr, const char* host,
  1300. const char* service, int family, int sockType, int flags,
  1301. int protocol)
  1302. {
  1303. struct addrinfo hints;
  1304. memset(&hints, 0, sizeof(hints));
  1305. hints.ai_family = family;
  1306. hints.ai_socktype = sockType;
  1307. hints.ai_flags = getDefaultAIFlags();
  1308. hints.ai_flags |= flags;
  1309. hints.ai_protocol = protocol;
  1310. return getaddrinfo(host, service, &hints, resPtr);
  1311. }
  1312. int inetNtop(int af, const void* src, char* dst, socklen_t size)
  1313. {
  1314. sockaddr_union su;
  1315. memset(&su, 0, sizeof(su));
  1316. if (af == AF_INET) {
  1317. su.in.sin_family = AF_INET;
  1318. #ifdef HAVE_SOCKADDR_IN_SIN_LEN
  1319. su.in.sin_len = sizeof(su.in);
  1320. #endif // HAVE_SOCKADDR_IN_SIN_LEN
  1321. memcpy(&su.in.sin_addr, src, sizeof(su.in.sin_addr));
  1322. return getnameinfo(&su.sa, sizeof(su.in), dst, size, nullptr, 0,
  1323. NI_NUMERICHOST);
  1324. }
  1325. if (af == AF_INET6) {
  1326. su.in6.sin6_family = AF_INET6;
  1327. #ifdef HAVE_SOCKADDR_IN6_SIN6_LEN
  1328. su.in6.sin6_len = sizeof(su.in6);
  1329. #endif // HAVE_SOCKADDR_IN6_SIN6_LEN
  1330. memcpy(&su.in6.sin6_addr, src, sizeof(su.in6.sin6_addr));
  1331. return getnameinfo(&su.sa, sizeof(su.in6), dst, size, nullptr, 0,
  1332. NI_NUMERICHOST);
  1333. }
  1334. return EAI_FAMILY;
  1335. }
  1336. int inetPton(int af, const char* src, void* dst)
  1337. {
  1338. union {
  1339. uint32_t ipv4_addr;
  1340. unsigned char ipv6_addr[16];
  1341. } binaddr;
  1342. size_t len = net::getBinAddr(binaddr.ipv6_addr, src);
  1343. if (af == AF_INET) {
  1344. if (len != 4) {
  1345. return -1;
  1346. }
  1347. in_addr* addr = reinterpret_cast<in_addr*>(dst);
  1348. addr->s_addr = binaddr.ipv4_addr;
  1349. return 0;
  1350. }
  1351. if (af == AF_INET6) {
  1352. if (len != 16) {
  1353. return -1;
  1354. }
  1355. in6_addr* addr = reinterpret_cast<in6_addr*>(dst);
  1356. memcpy(addr->s6_addr, binaddr.ipv6_addr, sizeof(addr->s6_addr));
  1357. return 0;
  1358. }
  1359. return -1;
  1360. }
  1361. namespace net {
  1362. size_t getBinAddr(void* dest, const std::string& ip)
  1363. {
  1364. size_t len = 0;
  1365. addrinfo* res;
  1366. if (callGetaddrinfo(&res, ip.c_str(), nullptr, AF_UNSPEC, 0, AI_NUMERICHOST,
  1367. 0) != 0) {
  1368. return len;
  1369. }
  1370. std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter(res,
  1371. freeaddrinfo);
  1372. for (addrinfo* rp = res; rp; rp = rp->ai_next) {
  1373. sockaddr_union su;
  1374. memcpy(&su, rp->ai_addr, rp->ai_addrlen);
  1375. if (rp->ai_family == AF_INET) {
  1376. len = sizeof(in_addr);
  1377. memcpy(dest, &(su.in.sin_addr), len);
  1378. break;
  1379. }
  1380. else if (rp->ai_family == AF_INET6) {
  1381. len = sizeof(in6_addr);
  1382. memcpy(dest, &(su.in6.sin6_addr), len);
  1383. break;
  1384. }
  1385. }
  1386. return len;
  1387. }
  1388. bool verifyHostname(const std::string& hostname,
  1389. const std::vector<std::string>& dnsNames,
  1390. const std::vector<std::string>& ipAddrs,
  1391. const std::string& commonName)
  1392. {
  1393. if (util::isNumericHost(hostname)) {
  1394. if (ipAddrs.empty()) {
  1395. return commonName == hostname;
  1396. }
  1397. // We need max 16 bytes to store IPv6 address.
  1398. unsigned char binAddr[16];
  1399. size_t addrLen = getBinAddr(binAddr, hostname);
  1400. if (addrLen == 0) {
  1401. return false;
  1402. }
  1403. for (auto& ipAddr : ipAddrs) {
  1404. if (addrLen == ipAddr.size() &&
  1405. memcmp(binAddr, ipAddr.c_str(), addrLen) == 0) {
  1406. return true;
  1407. }
  1408. }
  1409. return false;
  1410. }
  1411. if (dnsNames.empty()) {
  1412. return util::tlsHostnameMatch(commonName, hostname);
  1413. }
  1414. for (auto& dnsName : dnsNames) {
  1415. if (util::tlsHostnameMatch(dnsName, hostname)) {
  1416. return true;
  1417. }
  1418. }
  1419. return false;
  1420. }
  1421. namespace {
  1422. bool ipv4AddrConfigured = true;
  1423. bool ipv6AddrConfigured = true;
  1424. } // namespace
  1425. #ifdef __MINGW32__
  1426. namespace {
  1427. const uint32_t APIPA_IPV4_BEGIN = 2851995649u; // 169.254.0.1
  1428. const uint32_t APIPA_IPV4_END = 2852061183u; // 169.254.255.255
  1429. } // namespace
  1430. #endif // __MINGW32__
  1431. void checkAddrconfig()
  1432. {
  1433. #ifdef HAVE_IPHLPAPI_H
  1434. A2_LOG_INFO("Checking configured addresses");
  1435. ULONG bufsize = 15_k;
  1436. ULONG retval = 0;
  1437. IP_ADAPTER_ADDRESSES* buf = 0;
  1438. int numTry = 0;
  1439. const int MAX_TRY = 3;
  1440. do {
  1441. buf = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(malloc(bufsize));
  1442. retval = GetAdaptersAddresses(AF_UNSPEC, 0, 0, buf, &bufsize);
  1443. if (retval != ERROR_BUFFER_OVERFLOW) {
  1444. break;
  1445. }
  1446. free(buf);
  1447. buf = 0;
  1448. } while (retval == ERROR_BUFFER_OVERFLOW && numTry < MAX_TRY);
  1449. if (retval != NO_ERROR) {
  1450. A2_LOG_INFO("GetAdaptersAddresses failed. Assume both IPv4 and IPv6 "
  1451. " addresses are configured.");
  1452. return;
  1453. }
  1454. ipv4AddrConfigured = false;
  1455. ipv6AddrConfigured = false;
  1456. char host[NI_MAXHOST];
  1457. sockaddr_union ad;
  1458. int rv;
  1459. for (IP_ADAPTER_ADDRESSES* p = buf; p; p = p->Next) {
  1460. if (p->IfType == IF_TYPE_TUNNEL) {
  1461. // Skip tunnel interface because Windows7 automatically setup
  1462. // this for IPv6.
  1463. continue;
  1464. }
  1465. PIP_ADAPTER_UNICAST_ADDRESS ucaddr = p->FirstUnicastAddress;
  1466. if (!ucaddr) {
  1467. continue;
  1468. }
  1469. for (PIP_ADAPTER_UNICAST_ADDRESS i = ucaddr; i; i = i->Next) {
  1470. bool found = false;
  1471. switch (i->Address.iSockaddrLength) {
  1472. case sizeof(sockaddr_in): {
  1473. memcpy(&ad.storage, i->Address.lpSockaddr, i->Address.iSockaddrLength);
  1474. uint32_t haddr = ntohl(ad.in.sin_addr.s_addr);
  1475. if (haddr != INADDR_LOOPBACK &&
  1476. (haddr < APIPA_IPV4_BEGIN || APIPA_IPV4_END <= haddr)) {
  1477. ipv4AddrConfigured = true;
  1478. found = true;
  1479. }
  1480. break;
  1481. }
  1482. case sizeof(sockaddr_in6):
  1483. memcpy(&ad.storage, i->Address.lpSockaddr, i->Address.iSockaddrLength);
  1484. if (!IN6_IS_ADDR_LOOPBACK(&ad.in6.sin6_addr) &&
  1485. !IN6_IS_ADDR_LINKLOCAL(&ad.in6.sin6_addr)) {
  1486. ipv6AddrConfigured = true;
  1487. found = true;
  1488. }
  1489. break;
  1490. }
  1491. rv = getnameinfo(i->Address.lpSockaddr, i->Address.iSockaddrLength, host,
  1492. NI_MAXHOST, 0, 0, NI_NUMERICHOST);
  1493. if (rv == 0) {
  1494. if (found) {
  1495. A2_LOG_INFO(fmt("Found configured address: %s", host));
  1496. }
  1497. else {
  1498. A2_LOG_INFO(fmt("Not considered: %s", host));
  1499. }
  1500. }
  1501. }
  1502. }
  1503. free(buf);
  1504. A2_LOG_INFO(fmt("IPv4 configured=%d, IPv6 configured=%d", ipv4AddrConfigured,
  1505. ipv6AddrConfigured));
  1506. #elif defined(HAVE_GETIFADDRS)
  1507. A2_LOG_INFO("Checking configured addresses");
  1508. ipv4AddrConfigured = false;
  1509. ipv6AddrConfigured = false;
  1510. ifaddrs* ifaddr = nullptr;
  1511. int rv;
  1512. rv = getifaddrs(&ifaddr);
  1513. if (rv == -1) {
  1514. int errNum = SOCKET_ERRNO;
  1515. A2_LOG_INFO(fmt("getifaddrs failed. Cause: %s", errorMsg(errNum).c_str()));
  1516. return;
  1517. }
  1518. std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> ifaddrDeleter(ifaddr,
  1519. freeifaddrs);
  1520. char host[NI_MAXHOST];
  1521. sockaddr_union ad;
  1522. for (ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
  1523. if (!ifa->ifa_addr) {
  1524. continue;
  1525. }
  1526. bool found = false;
  1527. size_t addrlen = 0;
  1528. switch (ifa->ifa_addr->sa_family) {
  1529. case AF_INET: {
  1530. addrlen = sizeof(sockaddr_in);
  1531. memcpy(&ad.storage, ifa->ifa_addr, addrlen);
  1532. if (ad.in.sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
  1533. ipv4AddrConfigured = true;
  1534. found = true;
  1535. }
  1536. break;
  1537. }
  1538. case AF_INET6: {
  1539. addrlen = sizeof(sockaddr_in6);
  1540. memcpy(&ad.storage, ifa->ifa_addr, addrlen);
  1541. if (!IN6_IS_ADDR_LOOPBACK(&ad.in6.sin6_addr) &&
  1542. !IN6_IS_ADDR_LINKLOCAL(&ad.in6.sin6_addr)) {
  1543. ipv6AddrConfigured = true;
  1544. found = true;
  1545. }
  1546. break;
  1547. }
  1548. default:
  1549. continue;
  1550. }
  1551. rv = getnameinfo(ifa->ifa_addr, addrlen, host, NI_MAXHOST, nullptr, 0,
  1552. NI_NUMERICHOST);
  1553. if (rv == 0) {
  1554. if (found) {
  1555. A2_LOG_INFO(fmt("Found configured address: %s", host));
  1556. }
  1557. else {
  1558. A2_LOG_INFO(fmt("Not considered: %s", host));
  1559. }
  1560. }
  1561. }
  1562. A2_LOG_INFO(fmt("IPv4 configured=%d, IPv6 configured=%d", ipv4AddrConfigured,
  1563. ipv6AddrConfigured));
  1564. #else // !HAVE_GETIFADDRS
  1565. A2_LOG_INFO("getifaddrs is not available. Assume IPv4 and IPv6 addresses"
  1566. " are configured.");
  1567. #endif // !HAVE_GETIFADDRS
  1568. }
  1569. bool getIPv4AddrConfigured() { return ipv4AddrConfigured; }
  1570. bool getIPv6AddrConfigured() { return ipv6AddrConfigured; }
  1571. } // namespace net
  1572. } // namespace aria2