SocketCore.cc 44 KB

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