| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652 |
- /* <!-- copyright */
- /*
- * aria2 - The high speed download utility
- *
- * Copyright (C) 2006 Tatsuhiro Tsujikawa
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * In addition, as a special exception, the copyright holders give
- * permission to link the code of portions of this program with the
- * OpenSSL library under certain conditions as described in each
- * individual source file, and distribute linked combinations
- * including the two.
- * You must obey the GNU General Public License in all respects
- * for all of the code used other than OpenSSL. If you modify
- * file(s) with this exception, you may extend this exception to your
- * version of the file(s), but you are not obligated to do so. If you
- * do not wish to do so, delete this exception statement from your
- * version. If you delete this exception statement from all source
- * files in the program, then also delete it here.
- */
- /* copyright --> */
- #include "SocketCore.h"
- #ifdef HAVE_IPHLPAPI_H
- # include <iphlpapi.h>
- #endif // HAVE_IPHLPAPI_H
- #include <unistd.h>
- #ifdef HAVE_IFADDRS_H
- # include <ifaddrs.h>
- #endif // HAVE_IFADDRS_H
- #include <cerrno>
- #include <cstring>
- #include <cassert>
- #include <sstream>
- #include "message.h"
- #include "DlRetryEx.h"
- #include "DlAbortEx.h"
- #include "fmt.h"
- #include "util.h"
- #include "TimeA2.h"
- #include "a2functional.h"
- #include "LogFactory.h"
- #include "A2STR.h"
- #ifdef ENABLE_SSL
- # include "TLSContext.h"
- # include "TLSSession.h"
- #endif // ENABLE_SSL
- #ifdef HAVE_LIBSSH2
- # include "SSHSession.h"
- #endif // HAVE_LIBSSH2
- namespace aria2 {
- #ifndef __MINGW32__
- # define SOCKET_ERRNO (errno)
- #else
- # define SOCKET_ERRNO (WSAGetLastError())
- #endif // __MINGW32__
- #ifdef __MINGW32__
- # define A2_EINPROGRESS WSAEWOULDBLOCK
- # define A2_EWOULDBLOCK WSAEWOULDBLOCK
- # define A2_EINTR WSAEINTR
- # define A2_WOULDBLOCK(e) (e == WSAEWOULDBLOCK)
- #else // !__MINGW32__
- # define A2_EINPROGRESS EINPROGRESS
- # ifndef EWOULDBLOCK
- # define EWOULDBLOCK EAGAIN
- # endif // EWOULDBLOCK
- # define A2_EWOULDBLOCK EWOULDBLOCK
- # define A2_EINTR EINTR
- # if EWOULDBLOCK == EAGAIN
- # define A2_WOULDBLOCK(e) (e == EWOULDBLOCK)
- # else // EWOULDBLOCK != EAGAIN
- # define A2_WOULDBLOCK(e) (e == EWOULDBLOCK || e == EAGAIN)
- # endif // EWOULDBLOCK != EAGAIN
- #endif // !__MINGW32__
- #ifdef __MINGW32__
- # define CLOSE(X) ::closesocket(X)
- #else
- # define CLOSE(X) close(X)
- #endif // __MINGW32__
- namespace {
- std::string errorMsg(int errNum)
- {
- #ifndef __MINGW32__
- return util::safeStrerror(errNum);
- #else
- static char buf[256];
- if (FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- nullptr,
- errNum,
- MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
- (LPTSTR) &buf,
- sizeof(buf),
- nullptr
- ) == 0) {
- snprintf(buf, sizeof(buf), EX_SOCKET_UNKNOWN_ERROR, errNum, errNum);
- }
- return buf;
- #endif // __MINGW32__
- }
- } // namespace
- namespace {
- enum TlsState {
- // TLS object is not initialized.
- A2_TLS_NONE = 0,
- // TLS object is now handshaking.
- A2_TLS_HANDSHAKING = 2,
- // TLS object is now connected.
- A2_TLS_CONNECTED = 3
- };
- } // namespace
- int SocketCore::protocolFamily_ = AF_UNSPEC;
- int SocketCore::ipDscp_ = 0;
- std::vector<std::pair<sockaddr_union, socklen_t> >
- SocketCore::bindAddrs_;
- std::vector<std::vector<std::pair<sockaddr_union, socklen_t> > >
- SocketCore::bindAddrsList_;
- std::vector<std::vector<std::pair<sockaddr_union, socklen_t> > >::iterator
- SocketCore::bindAddrsListIt_;
- #ifdef ENABLE_SSL
- std::shared_ptr<TLSContext> SocketCore::clTlsContext_;
- std::shared_ptr<TLSContext> SocketCore::svTlsContext_;
- void SocketCore::setClientTLSContext
- (const std::shared_ptr<TLSContext>& tlsContext)
- {
- clTlsContext_ = tlsContext;
- }
- void SocketCore::setServerTLSContext
- (const std::shared_ptr<TLSContext>& tlsContext)
- {
- svTlsContext_ = tlsContext;
- }
- #endif // ENABLE_SSL
- SocketCore::SocketCore(int sockType)
- : sockType_(sockType),
- sockfd_(-1)
- {
- init();
- }
- SocketCore::SocketCore(sock_t sockfd, int sockType)
- : sockType_(sockType),
- sockfd_(sockfd)
- {
- init();
- }
- void SocketCore::init()
- {
- blocking_ = true;
- secure_ = A2_TLS_NONE;
- wantRead_ = false;
- wantWrite_ = false;
- }
- SocketCore::~SocketCore() {
- closeConnection();
- }
- void SocketCore::create(int family, int protocol)
- {
- int errNum;
- closeConnection();
- sock_t fd = socket(family, sockType_, protocol);
- errNum = SOCKET_ERRNO;
- if(fd == (sock_t) -1) {
- throw DL_ABORT_EX
- (fmt("Failed to create socket. Cause:%s", errorMsg(errNum).c_str()));
- }
- int sockopt = 1;
- if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
- (a2_sockopt_t) &sockopt, sizeof(sockopt)) < 0) {
- errNum = SOCKET_ERRNO;
- CLOSE(fd);
- throw DL_ABORT_EX
- (fmt("Failed to create socket. Cause:%s", errorMsg(errNum).c_str()));
- }
- sockfd_ = fd;
- }
- static sock_t bindInternal
- (int family, int socktype, int protocol,
- const struct sockaddr* addr, socklen_t addrlen,
- std::string& error)
- {
- int errNum;
- sock_t fd = socket(family, socktype, protocol);
- errNum = SOCKET_ERRNO;
- if(fd == (sock_t) -1) {
- error = errorMsg(errNum);
- return -1;
- }
- int sockopt = 1;
- if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (a2_sockopt_t) &sockopt,
- sizeof(sockopt)) < 0) {
- errNum = SOCKET_ERRNO;
- error = errorMsg(errNum);
- CLOSE(fd);
- return -1;
- }
- #ifdef IPV6_V6ONLY
- if(family == AF_INET6) {
- int sockopt = 1;
- if(setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (a2_sockopt_t) &sockopt,
- sizeof(sockopt)) < 0) {
- errNum = SOCKET_ERRNO;
- error = errorMsg(errNum);
- CLOSE(fd);
- return -1;
- }
- }
- #endif // IPV6_V6ONLY
- if(::bind(fd, addr, addrlen) == -1) {
- errNum = SOCKET_ERRNO;
- error = errorMsg(errNum);
- CLOSE(fd);
- return -1;
- }
- return fd;
- }
- static sock_t bindTo
- (const char* host, uint16_t port, int family, int sockType,
- int getaddrinfoFlags, std::string& error)
- {
- struct addrinfo* res;
- int s = callGetaddrinfo(&res, host, util::uitos(port).c_str(),
- family, sockType, getaddrinfoFlags, 0);
- if(s) {
- error = gai_strerror(s);
- return -1;
- }
- std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
- (res, freeaddrinfo);
- struct addrinfo* rp;
- for(rp = res; rp; rp = rp->ai_next) {
- sock_t fd = bindInternal(rp->ai_family, rp->ai_socktype, rp->ai_protocol,
- rp->ai_addr, rp->ai_addrlen, error);
- if(fd != (sock_t)-1) {
- return fd;
- }
- }
- return -1;
- }
- void SocketCore::bindWithFamily(uint16_t port, int family, int flags)
- {
- closeConnection();
- std::string error;
- sock_t fd = bindTo(nullptr, port, family, sockType_, flags, error);
- if(fd == (sock_t) -1) {
- throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
- }
- sockfd_ = fd;
- }
- void SocketCore::bind
- (const char* addr, uint16_t port, int family, int flags)
- {
- closeConnection();
- std::string error;
- const char* addrp;
- if(addr && addr[0]) {
- addrp = addr;
- } else {
- addrp = nullptr;
- }
- if(!(flags&AI_PASSIVE) || bindAddrs_.empty()) {
- sock_t fd = bindTo(addrp, port, family, sockType_, flags, error);
- if(fd == (sock_t) -1) {
- throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
- }
- sockfd_ = fd;
- return;
- }
- for (const auto& a : bindAddrs_) {
- char host[NI_MAXHOST];
- int s;
- s = getnameinfo(&a.first.sa, a.second, host, NI_MAXHOST, nullptr, 0,
- NI_NUMERICHOST);
- if(s) {
- error = gai_strerror(s);
- continue;
- }
- if(addrp && strcmp(host, addrp) != 0) {
- error = "Given address and resolved address do not match.";
- continue;
- }
- sock_t fd = bindTo(host, port, family, sockType_, flags, error);
- if(fd != (sock_t)-1) {
- sockfd_ = fd;
- break;
- }
- }
- if(sockfd_ == (sock_t) -1) {
- throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
- }
- }
- void SocketCore::bind(uint16_t port, int flags)
- {
- bind(nullptr, port, protocolFamily_, flags);
- }
- void SocketCore::bind(const struct sockaddr* addr, socklen_t addrlen)
- {
- closeConnection();
- std::string error;
- sock_t fd = bindInternal(addr->sa_family, sockType_, 0, addr, addrlen, error);
- if(fd == (sock_t)-1) {
- throw DL_ABORT_EX(fmt(EX_SOCKET_BIND, error.c_str()));
- }
- sockfd_ = fd;
- }
- void SocketCore::beginListen()
- {
- if(listen(sockfd_, 1) == -1) {
- int errNum = SOCKET_ERRNO;
- throw DL_ABORT_EX(fmt(EX_SOCKET_LISTEN, errorMsg(errNum).c_str()));
- }
- setNonBlockingMode();
- }
- std::shared_ptr<SocketCore> SocketCore::acceptConnection() const
- {
- sockaddr_union sockaddr;
- socklen_t len = sizeof(sockaddr);
- sock_t fd;
- while((fd = accept(sockfd_, &sockaddr.sa, &len)) == (sock_t) -1 &&
- SOCKET_ERRNO == A2_EINTR);
- int errNum = SOCKET_ERRNO;
- if(fd == (sock_t) -1) {
- throw DL_ABORT_EX(fmt(EX_SOCKET_ACCEPT, errorMsg(errNum).c_str()));
- }
- auto sock = std::shared_ptr<SocketCore>(new SocketCore(fd, sockType_));
- sock->setNonBlockingMode();
- return sock;
- }
- int SocketCore::getAddrInfo(std::pair<std::string, uint16_t>& addrinfo) const
- {
- sockaddr_union sockaddr;
- socklen_t len = sizeof(sockaddr);
- getAddrInfo(sockaddr, len);
- addrinfo = util::getNumericNameInfo(&sockaddr.sa, len);
- return sockaddr.storage.ss_family;
- }
- void SocketCore::getAddrInfo(sockaddr_union& sockaddr, socklen_t& len) const
- {
- if(getsockname(sockfd_, &sockaddr.sa, &len) == -1) {
- int errNum = SOCKET_ERRNO;
- throw DL_ABORT_EX(fmt(EX_SOCKET_GET_NAME, errorMsg(errNum).c_str()));
- }
- }
- int SocketCore::getAddressFamily() const
- {
- sockaddr_union sockaddr;
- socklen_t len = sizeof(sockaddr);
- getAddrInfo(sockaddr, len);
- return sockaddr.storage.ss_family;
- }
- int SocketCore::getPeerInfo(std::pair<std::string, uint16_t>& peerinfo) const
- {
- sockaddr_union sockaddr;
- socklen_t len = sizeof(sockaddr);
- if(getpeername(sockfd_, &sockaddr.sa, &len) == -1) {
- int errNum = SOCKET_ERRNO;
- throw DL_ABORT_EX(fmt(EX_SOCKET_GET_NAME, errorMsg(errNum).c_str()));
- }
- peerinfo = util::getNumericNameInfo(&sockaddr.sa, len);
- return sockaddr.storage.ss_family;
- }
- void SocketCore::establishConnection(const std::string& host, uint16_t port,
- bool tcpNodelay)
- {
- closeConnection();
- std::string error;
- struct addrinfo* res;
- int s;
- s = callGetaddrinfo(&res, host.c_str(), util::uitos(port).c_str(),
- protocolFamily_, sockType_, 0, 0);
- if(s) {
- throw DL_ABORT_EX(fmt(EX_RESOLVE_HOSTNAME, host.c_str(), gai_strerror(s)));
- }
- std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
- (res, freeaddrinfo);
- struct addrinfo* rp;
- int errNum;
- for(rp = res; rp; rp = rp->ai_next) {
- sock_t fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
- errNum = SOCKET_ERRNO;
- if(fd == (sock_t) -1) {
- error = errorMsg(errNum);
- continue;
- }
- int sockopt = 1;
- if(setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (a2_sockopt_t) &sockopt,
- sizeof(sockopt)) < 0) {
- errNum = SOCKET_ERRNO;
- error = errorMsg(errNum);
- CLOSE(fd);
- continue;
- }
- if(!bindAddrs_.empty()) {
- bool bindSuccess = false;
- for(std::vector<std::pair<sockaddr_union, socklen_t> >::
- const_iterator i = bindAddrs_.begin(), eoi = bindAddrs_.end();
- i != eoi; ++i) {
- if(::bind(fd, &(*i).first.sa, (*i).second) == -1) {
- errNum = SOCKET_ERRNO;
- error = errorMsg(errNum);
- A2_LOG_DEBUG(fmt(EX_SOCKET_BIND, error.c_str()));
- } else {
- bindSuccess = true;
- break;
- }
- }
- if(!bindSuccess) {
- CLOSE(fd);
- continue;
- }
- }
- if(!bindAddrsList_.empty()) {
- ++bindAddrsListIt_;
- if (bindAddrsListIt_ == bindAddrsList_.end()) {
- bindAddrsListIt_ = bindAddrsList_.begin();
- }
- bindAddrs_ = *bindAddrsListIt_;
- }
- sockfd_ = fd;
- // make socket non-blocking mode
- setNonBlockingMode();
- if(tcpNodelay) {
- setTcpNodelay(true);
- }
- if(connect(fd, rp->ai_addr, rp->ai_addrlen) == -1 &&
- SOCKET_ERRNO != A2_EINPROGRESS) {
- errNum = SOCKET_ERRNO;
- error = errorMsg(errNum);
- CLOSE(sockfd_);
- sockfd_ = (sock_t) -1;
- continue;
- }
- // TODO at this point, connection may not be established and it may fail
- // later. In such case, next ai_addr should be tried.
- break;
- }
- if(sockfd_ == (sock_t) -1) {
- throw DL_ABORT_EX(fmt(EX_SOCKET_CONNECT, host.c_str(), error.c_str()));
- }
- }
- void SocketCore::setSockOpt
- (int level, int optname, void* optval, socklen_t optlen)
- {
- if(setsockopt(sockfd_, level, optname, (a2_sockopt_t)optval, optlen) < 0) {
- int errNum = SOCKET_ERRNO;
- throw DL_ABORT_EX(fmt(EX_SOCKET_SET_OPT, errorMsg(errNum).c_str()));
- }
- }
- void SocketCore::setMulticastInterface(const std::string& localAddr)
- {
- in_addr addr;
- if(localAddr.empty()) {
- addr.s_addr = htonl(INADDR_ANY);
- }
- else if(inetPton(AF_INET, localAddr.c_str(), &addr) != 0) {
- throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
- localAddr.c_str()));
- }
- setSockOpt(IPPROTO_IP, IP_MULTICAST_IF, &addr, sizeof(addr));
- }
- void SocketCore::setMulticastTtl(unsigned char ttl)
- {
- setSockOpt(IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
- }
- void SocketCore::setMulticastLoop(unsigned char loop)
- {
- setSockOpt(IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
- }
- void SocketCore::joinMulticastGroup
- (const std::string& multicastAddr, uint16_t multicastPort,
- const std::string& localAddr)
- {
- in_addr multiAddr;
- if(inetPton(AF_INET, multicastAddr.c_str(), &multiAddr) != 0) {
- throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
- multicastAddr.c_str()));
- }
- in_addr ifAddr;
- if(localAddr.empty()) {
- ifAddr.s_addr = htonl(INADDR_ANY);
- }
- else if(inetPton(AF_INET, localAddr.c_str(), &ifAddr) != 0) {
- throw DL_ABORT_EX(fmt("%s is not valid IPv4 numeric address",
- localAddr.c_str()));
- }
- struct ip_mreq mreq;
- memset(&mreq, 0, sizeof(mreq));
- mreq.imr_multiaddr = multiAddr;
- mreq.imr_interface = ifAddr;
- setSockOpt(IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
- }
- void SocketCore::setTcpNodelay(bool f)
- {
- int val = f;
- setSockOpt(IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
- }
- void SocketCore::applyIpDscp()
- {
- if(ipDscp_ == 0) {
- return;
- }
- try {
- int family = getAddressFamily();
- if(family == AF_INET) {
- setSockOpt(IPPROTO_IP, IP_TOS, &ipDscp_, sizeof(ipDscp_));
- }
- #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__)
- else if(family == AF_INET6) {
- setSockOpt(IPPROTO_IPV6, IPV6_TCLASS, &ipDscp_, sizeof(ipDscp_));
- }
- #endif
- } catch(RecoverableException& e) {
- A2_LOG_INFO_EX("Applying DSCP value failed", e);
- }
- }
- void SocketCore::setNonBlockingMode()
- {
- #ifdef __MINGW32__
- static u_long flag = 1;
- if (::ioctlsocket(sockfd_, FIONBIO, &flag) == -1) {
- int errNum = SOCKET_ERRNO;
- throw DL_ABORT_EX(fmt(EX_SOCKET_NONBLOCKING, errorMsg(errNum).c_str()));
- }
- #else
- int flags;
- while((flags = fcntl(sockfd_, F_GETFL, 0)) == -1 && errno == EINTR);
- // TODO add error handling
- while(fcntl(sockfd_, F_SETFL, flags|O_NONBLOCK) == -1 && errno == EINTR);
- #endif // __MINGW32__
- blocking_ = false;
- }
- void SocketCore::setBlockingMode()
- {
- #ifdef __MINGW32__
- static u_long flag = 0;
- if (::ioctlsocket(sockfd_, FIONBIO, &flag) == -1) {
- int errNum = SOCKET_ERRNO;
- throw DL_ABORT_EX(fmt(EX_SOCKET_BLOCKING, errorMsg(errNum).c_str()));
- }
- #else
- int flags;
- while((flags = fcntl(sockfd_, F_GETFL, 0)) == -1 && errno == EINTR);
- // TODO add error handling
- while(fcntl(sockfd_, F_SETFL, flags&(~O_NONBLOCK)) == -1 && errno == EINTR);
- #endif // __MINGW32__
- blocking_ = true;
- }
- void SocketCore::closeConnection()
- {
- #ifdef ENABLE_SSL
- if(tlsSession_) {
- tlsSession_->closeConnection();
- tlsSession_.reset();
- }
- #endif // ENABLE_SSL
- #ifdef HAVE_LIBSSH2
- if(sshSession_) {
- sshSession_->closeConnection();
- sshSession_.reset();
- }
- #endif // HAVE_LIBSSH2
- if(sockfd_ != (sock_t) -1) {
- shutdown(sockfd_, SHUT_WR);
- CLOSE(sockfd_);
- sockfd_ = -1;
- }
- }
- #ifndef __MINGW32__
- # define CHECK_FD(fd) \
- if(fd < 0 || FD_SETSIZE <= fd) { \
- logger_->warn("Detected file descriptor >= FD_SETSIZE or < 0. " \
- "Download may slow down or fail."); \
- return false; \
- }
- #endif // !__MINGW32__
- bool SocketCore::isWritable(time_t timeout)
- {
- #ifdef HAVE_POLL
- struct pollfd p;
- p.fd = sockfd_;
- p.events = POLLOUT;
- int r;
- while((r = poll(&p, 1, timeout*1000)) == -1 && errno == EINTR);
- int errNum = SOCKET_ERRNO;
- if(r > 0) {
- return p.revents&(POLLOUT|POLLHUP|POLLERR);
- }
- if(r == 0) {
- return false;
- }
- throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_WRITABLE, errorMsg(errNum).c_str()));
- #else // !HAVE_POLL
- # ifndef __MINGW32__
- CHECK_FD(sockfd_);
- # endif // !__MINGW32__
- fd_set fds;
- FD_ZERO(&fds);
- FD_SET(sockfd_, &fds);
- struct timeval tv;
- tv.tv_sec = timeout;
- tv.tv_usec = 0;
- int r = select(sockfd_+1, nullptr, &fds, nullptr, &tv);
- int errNum = SOCKET_ERRNO;
- if(r == 1) {
- return true;
- }
- if(r == 0) {
- // time out
- return false;
- }
- if(errNum == A2_EINPROGRESS || errNum == A2_EINTR) {
- return false;
- }
- throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_WRITABLE, errorMsg(errNum).c_str()));
- #endif // !HAVE_POLL
- }
- bool SocketCore::isReadable(time_t timeout)
- {
- #ifdef HAVE_POLL
- struct pollfd p;
- p.fd = sockfd_;
- p.events = POLLIN;
- int r;
- while((r = poll(&p, 1, timeout*1000)) == -1 && errno == EINTR);
- int errNum = SOCKET_ERRNO;
- if(r > 0) {
- return p.revents&(POLLIN|POLLHUP|POLLERR);
- }
- if(r == 0) {
- return false;
- }
- throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_READABLE, errorMsg(errNum).c_str()));
- #else // !HAVE_POLL
- # ifndef __MINGW32__
- CHECK_FD(sockfd_);
- # endif // !__MINGW32__
- fd_set fds;
- FD_ZERO(&fds);
- FD_SET(sockfd_, &fds);
- struct timeval tv;
- tv.tv_sec = timeout;
- tv.tv_usec = 0;
- int r = select(sockfd_+1, &fds, nullptr, nullptr, &tv);
- int errNum = SOCKET_ERRNO;
- if(r == 1) {
- return true;
- }
- if(r == 0) {
- // time out
- return false;
- }
- if(errNum == A2_EINPROGRESS || errNum == A2_EINTR) {
- return false;
- }
- throw DL_RETRY_EX(fmt(EX_SOCKET_CHECK_READABLE, errorMsg(errNum).c_str()));
- #endif // !HAVE_POLL
- }
- ssize_t SocketCore::writeVector(a2iovec *iov, size_t iovcnt)
- {
- ssize_t ret = 0;
- wantRead_ = false;
- wantWrite_ = false;
- if(!secure_) {
- #ifdef __MINGW32__
- DWORD nsent;
- int rv = WSASend(sockfd_, iov, iovcnt, &nsent, 0, 0, 0);
- if(rv == 0) {
- ret = nsent;
- } else {
- ret = -1;
- }
- #else // !__MINGW32__
- while((ret = writev(sockfd_, iov, iovcnt)) == -1 &&
- SOCKET_ERRNO == A2_EINTR);
- #endif // !__MINGW32__
- int errNum = SOCKET_ERRNO;
- if(ret == -1) {
- if(!A2_WOULDBLOCK(errNum)) {
- throw DL_RETRY_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
- }
- wantWrite_ = true;
- ret = 0;
- }
- } else {
- // For SSL/TLS, we could not use writev, so just iterate vector
- // and write the data in normal way.
- for(size_t i = 0; i < iovcnt; ++i) {
- ssize_t rv = writeData(iov[i].A2IOVEC_BASE, iov[i].A2IOVEC_LEN);
- if(rv == 0) {
- break;
- }
- ret += rv;
- }
- }
- return ret;
- }
- ssize_t SocketCore::writeData(const void* data, size_t len)
- {
- ssize_t ret = 0;
- wantRead_ = false;
- wantWrite_ = false;
- if(!secure_) {
- // Cast for Windows send()
- while((ret = send(sockfd_, reinterpret_cast<const char*>(data),
- len, 0)) == -1 && SOCKET_ERRNO == A2_EINTR);
- int errNum = SOCKET_ERRNO;
- if(ret == -1) {
- if(!A2_WOULDBLOCK(errNum)) {
- throw DL_RETRY_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
- }
- wantWrite_ = true;
- ret = 0;
- }
- } else {
- #ifdef ENABLE_SSL
- ret = tlsSession_->writeData(data, len);
- if(ret < 0) {
- if(ret != TLS_ERR_WOULDBLOCK) {
- throw DL_RETRY_EX(fmt(EX_SOCKET_SEND,
- tlsSession_->getLastErrorString().c_str()));
- }
- if(tlsSession_->checkDirection() == TLS_WANT_READ) {
- wantRead_ = true;
- } else {
- wantWrite_ = true;
- }
- ret = 0;
- }
- #endif // ENABLE_SSL
- }
- return ret;
- }
- void SocketCore::readData(void* data, size_t& len)
- {
- ssize_t ret = 0;
- wantRead_ = false;
- wantWrite_ = false;
- if(sshSession_) {
- #ifdef HAVE_LIBSSH2
- ret = sshSession_->readData(data, len);
- if(ret < 0) {
- if(ret != SSH_ERR_WOULDBLOCK) {
- throw DL_RETRY_EX(fmt(EX_SOCKET_RECV,
- sshSession_->getLastErrorString().c_str()));
- }
- if(sshSession_->checkDirection() == SSH_WANT_READ) {
- wantRead_ = true;
- } else {
- wantWrite_ = true;
- }
- ret = 0;
- }
- #endif // HAVE_LIBSSH2
- } else if(!secure_) {
- // Cast for Windows recv()
- while((ret = recv(sockfd_, reinterpret_cast<char*>(data), len, 0)) == -1 &&
- SOCKET_ERRNO == A2_EINTR);
- int errNum = SOCKET_ERRNO;
- if(ret == -1) {
- if(!A2_WOULDBLOCK(errNum)) {
- throw DL_RETRY_EX(fmt(EX_SOCKET_RECV, errorMsg(errNum).c_str()));
- }
- wantRead_ = true;
- ret = 0;
- }
- } else {
- #ifdef ENABLE_SSL
- ret = tlsSession_->readData(data, len);
- if(ret < 0) {
- if(ret != TLS_ERR_WOULDBLOCK) {
- throw DL_RETRY_EX(fmt(EX_SOCKET_RECV,
- tlsSession_->getLastErrorString().c_str()));
- }
- if(tlsSession_->checkDirection() == TLS_WANT_READ) {
- wantRead_ = true;
- } else {
- wantWrite_ = true;
- }
- ret = 0;
- }
- #endif // ENABLE_SSL
- }
- len = ret;
- }
- #ifdef ENABLE_SSL
- bool SocketCore::tlsAccept()
- {
- return tlsHandshake(svTlsContext_.get(), A2STR::NIL);
- }
- bool SocketCore::tlsConnect(const std::string& hostname)
- {
- return tlsHandshake(clTlsContext_.get(), hostname);
- }
- bool SocketCore::tlsHandshake(TLSContext* tlsctx, const std::string& hostname)
- {
- wantRead_ = false;
- wantWrite_ = false;
- if(secure_ == A2_TLS_CONNECTED) {
- // Already connected!
- return true;
- }
- if(secure_ == A2_TLS_NONE) {
- // Do some initial setup
- A2_LOG_DEBUG("Creating TLS session");
- tlsSession_.reset(TLSSession::make(tlsctx));
- auto rv = tlsSession_->init(sockfd_);
- if(rv != TLS_ERR_OK) {
- std::string error = tlsSession_->getLastErrorString();
- tlsSession_.reset();
- throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE, error.c_str()));
- }
- // Check hostname is not numeric and it includes ".". Setting
- // "localhost" will produce TLS alert with GNUTLS.
- if(tlsctx->getSide() == TLS_CLIENT &&
- !util::isNumericHost(hostname) &&
- hostname.find(".") != std::string::npos) {
- rv = tlsSession_->setSNIHostname(hostname);
- if(rv != TLS_ERR_OK) {
- throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE,
- tlsSession_->getLastErrorString().c_str()));
- }
- }
- // Done with the setup, now let handshaking begin immediately.
- secure_ = A2_TLS_HANDSHAKING;
- A2_LOG_DEBUG("TLS Handshaking");
- }
- if(secure_ == A2_TLS_HANDSHAKING) {
- // Starting handshake after initial setup or still handshaking.
- TLSVersion ver = TLS_PROTO_NONE;
- int rv = 0;
- std::string handshakeError;
- if(tlsctx->getSide() == TLS_CLIENT) {
- rv = tlsSession_->tlsConnect(hostname, ver, handshakeError);
- } else {
- rv = tlsSession_->tlsAccept(ver);
- }
- if(rv == TLS_ERR_OK) {
- // We're good, more or less.
- // 1. Construct peerinfo
- std::stringstream ss;
- if (!hostname.empty()) {
- ss << hostname << " (";
- }
- std::pair<std::string, uint16_t> peer;
- getPeerInfo(peer);
- ss << peer.first << ":" << peer.second;
- if (!hostname.empty()) {
- ss << ")";
- }
- auto peerInfo = ss.str();
- // 2. Issue any warnings
- switch(ver) {
- case TLS_PROTO_NONE:
- A2_LOG_WARN(fmt(MSG_WARN_UNKNOWN_TLS_CONNECTION, peerInfo.c_str()));
- break;
- case TLS_PROTO_SSL3:
- A2_LOG_WARN(fmt(MSG_WARN_OLD_TLS_CONNECTION,
- "SSLv3", peerInfo.c_str()));
- break;
- default:
- A2_LOG_DEBUG(fmt("Securely connected to %s", peerInfo.c_str()));
- break;
- }
- // 3. We're connected now!
- secure_ = A2_TLS_CONNECTED;
- return true;
- }
- if(rv == TLS_ERR_WOULDBLOCK) {
- // We're not done yet...
- if(tlsSession_->checkDirection() == TLS_WANT_READ) {
- // ... but read buffers are empty.
- wantRead_ = true;
- } else {
- // ... but write buffers are full.
- wantWrite_ = true;
- }
- // Returning false (instead of true==success or throwing) will cause this
- // function to be called again once buffering is dealt with
- return false;
- }
- if (rv == TLS_ERR_ERROR) {
- // Damn those error.
- throw DL_ABORT_EX(fmt("SSL/TLS handshake failure: %s",
- handshakeError.empty() ?
- tlsSession_->getLastErrorString().c_str() :
- handshakeError.c_str()));
- }
- // Some implementation passed back an invalid result.
- throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE,
- "Invalid connect state (this is a bug in the TLS "
- "backend!)"));
- }
- // We should never get here, i.e. all possible states should have been handled
- // and returned from a branch before! Getting here is a bug, of course!
- throw DL_ABORT_EX(fmt(EX_SSL_INIT_FAILURE, "Invalid state (this is a bug!)"));
- }
- #endif // ENABLE_SSL
- #ifdef HAVE_LIBSSH2
- bool SocketCore::sshHandshake()
- {
- wantRead_ = false;
- wantWrite_ = false;
- if (!sshSession_) {
- sshSession_ = make_unique<SSHSession>();
- if (sshSession_->init(sockfd_) == SSH_ERR_ERROR) {
- throw DL_ABORT_EX("Could not create SSH session");
- }
- }
- auto rv = sshSession_->handshake();
- if (rv == SSH_ERR_WOULDBLOCK) {
- sshCheckDirection();
- return false;
- }
- if (rv == SSH_ERR_ERROR) {
- throw DL_ABORT_EX(fmt("SSH handshake failure: %s",
- sshSession_->getLastErrorString().c_str()));
- }
- return true;
- }
- bool SocketCore::sshAuthPassword(const std::string& user,
- const std::string& password)
- {
- assert(sshSession_);
- wantRead_ = false;
- wantWrite_ = false;
- auto rv = sshSession_->authPassword(user, password);
- if (rv == SSH_ERR_WOULDBLOCK) {
- sshCheckDirection();
- return false;
- }
- if (rv == SSH_ERR_ERROR) {
- throw DL_ABORT_EX(fmt("SSH authentication failure: %s",
- sshSession_->getLastErrorString().c_str()));
- }
- return true;
- }
- bool SocketCore::sshSFTPOpen(const std::string& path)
- {
- assert(sshSession_);
- wantRead_ = false;
- wantWrite_ = false;
- auto rv = sshSession_->sftpOpen(path);
- if (rv == SSH_ERR_WOULDBLOCK) {
- sshCheckDirection();
- return false;
- }
- if (rv == SSH_ERR_ERROR) {
- throw DL_ABORT_EX(fmt("SSH opening SFTP path %s failed: %s",
- path.c_str(),
- sshSession_->getLastErrorString().c_str()));
- }
- return true;
- }
- bool SocketCore::sshSFTPClose()
- {
- assert(sshSession_);
- wantRead_ = false;
- wantWrite_ = false;
- auto rv = sshSession_->sftpClose();
- if (rv == SSH_ERR_WOULDBLOCK) {
- sshCheckDirection();
- return false;
- }
- if (rv == SSH_ERR_ERROR) {
- throw DL_ABORT_EX(fmt("SSH closing SFTP failed: %s",
- sshSession_->getLastErrorString().c_str()));
- }
- return true;
- }
- bool SocketCore::sshSFTPStat(int64_t& totalLength, time_t& mtime,
- const std::string& path)
- {
- assert(sshSession_);
- wantRead_ = false;
- wantWrite_ = false;
- auto rv = sshSession_->sftpStat(totalLength, mtime);
- if (rv == SSH_ERR_WOULDBLOCK) {
- sshCheckDirection();
- return false;
- }
- if (rv == SSH_ERR_ERROR) {
- throw DL_ABORT_EX(fmt("SSH stat SFTP path %s filed: %s",
- path.c_str(),
- sshSession_->getLastErrorString().c_str()));
- }
- return true;
- }
- void SocketCore::sshSFTPSeek(int64_t pos)
- {
- assert(sshSession_);
- sshSession_->sftpSeek(pos);
- }
- bool SocketCore::sshGracefulShutdown()
- {
- assert(sshSession_);
- auto rv = sshSession_->gracefulShutdown();
- if (rv == SSH_ERR_WOULDBLOCK) {
- sshCheckDirection();
- return false;
- }
- if (rv == SSH_ERR_ERROR) {
- throw DL_ABORT_EX(fmt("SSH graceful shutdown failed: %s",
- sshSession_->getLastErrorString().c_str()));
- }
- return true;
- }
- void SocketCore::sshCheckDirection()
- {
- if (sshSession_->checkDirection() == SSH_WANT_READ) {
- wantRead_ = true;
- } else {
- wantWrite_ = true;
- }
- }
- #endif // HAVE_LIBSSH2
- ssize_t SocketCore::writeData(const void* data, size_t len,
- const std::string& host, uint16_t port)
- {
- wantRead_ = false;
- wantWrite_ = false;
- struct addrinfo* res;
- int s;
- s = callGetaddrinfo(&res, host.c_str(), util::uitos(port).c_str(),
- protocolFamily_, sockType_, 0, 0);
- if(s) {
- throw DL_ABORT_EX(fmt(EX_SOCKET_SEND, gai_strerror(s)));
- }
- std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
- (res, freeaddrinfo);
- struct addrinfo* rp;
- ssize_t r = -1;
- int errNum = 0;
- for(rp = res; rp; rp = rp->ai_next) {
- // Cast for Windows sendto()
- while((r = sendto(sockfd_, reinterpret_cast<const char*>(data), len, 0,
- rp->ai_addr, rp->ai_addrlen)) == -1
- && A2_EINTR == SOCKET_ERRNO);
- errNum = SOCKET_ERRNO;
- if(r == static_cast<ssize_t>(len)) {
- break;
- }
- if(r == -1 && A2_WOULDBLOCK(errNum)) {
- wantWrite_ = true;
- r = 0;
- break;
- }
- }
- if(r == -1) {
- throw DL_ABORT_EX(fmt(EX_SOCKET_SEND, errorMsg(errNum).c_str()));
- }
- return r;
- }
- ssize_t SocketCore::readDataFrom(void* data, size_t len,
- std::pair<std::string /* numerichost */,
- uint16_t /* port */>& sender)
- {
- wantRead_ = false;
- wantWrite_ = false;
- sockaddr_union sockaddr;
- socklen_t sockaddrlen = sizeof(sockaddr);
- ssize_t r;
- // Cast for Windows recvfrom()
- while((r = recvfrom(sockfd_, reinterpret_cast<char*>(data), len, 0,
- &sockaddr.sa, &sockaddrlen)) == -1
- && A2_EINTR == SOCKET_ERRNO);
- int errNum = SOCKET_ERRNO;
- if(r == -1) {
- if(!A2_WOULDBLOCK(errNum)) {
- throw DL_RETRY_EX(fmt(EX_SOCKET_RECV, errorMsg(errNum).c_str()));
- }
- wantRead_ = true;
- r = 0;
- } else {
- sender = util::getNumericNameInfo(&sockaddr.sa, sockaddrlen);
- }
- return r;
- }
- std::string SocketCore::getSocketError() const
- {
- int error;
- socklen_t optlen = sizeof(error);
- if(getsockopt(sockfd_, SOL_SOCKET, SO_ERROR,
- (a2_sockopt_t) &error, &optlen) == -1) {
- int errNum = SOCKET_ERRNO;
- throw DL_ABORT_EX
- (fmt("Failed to get socket error: %s", errorMsg(errNum).c_str()));
- }
- if(error != 0) {
- return errorMsg(error);
- }
- return "";
- }
- bool SocketCore::wantRead() const
- {
- return wantRead_;
- }
- bool SocketCore::wantWrite() const
- {
- return wantWrite_;
- }
- void SocketCore::bindAddress(const std::string& iface)
- {
- std::vector<std::pair<sockaddr_union, socklen_t> > bindAddrs;
- getInterfaceAddress(bindAddrs, iface, protocolFamily_);
- if(bindAddrs.empty()) {
- throw DL_ABORT_EX(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(),
- "not available"));
- }
- bindAddrs_.swap(bindAddrs);
- for (const auto& a: bindAddrs_) {
- char host[NI_MAXHOST];
- int s;
- s = getnameinfo(&a.first.sa, a.second, host, NI_MAXHOST, nullptr, 0,
- NI_NUMERICHOST);
- if(s == 0) {
- A2_LOG_DEBUG(fmt("Sockets will bind to %s", host));
- }
- }
- }
- void SocketCore::bindAllAddress(const std::string& ifaces)
- {
- std::vector<std::vector<std::pair<sockaddr_union, socklen_t> > > bindAddrsList;
- std::vector<std::string> ifaceList;
- util::split(ifaces.begin(), ifaces.end(), std::back_inserter(ifaceList), ',', true);
- if (ifaceList.empty()) {
- throw DL_ABORT_EX("List of interfaces is empty, one or more interfaces is required");
- }
- for (auto& iface: ifaceList) {
- std::vector<std::pair<sockaddr_union, socklen_t> > bindAddrs;
- getInterfaceAddress(bindAddrs, iface, protocolFamily_);
- if(bindAddrs.empty()) {
- throw DL_ABORT_EX(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(),
- "not available"));
- }
- bindAddrsList.push_back(bindAddrs);
- for (const auto& a: bindAddrs) {
- char host[NI_MAXHOST];
- int s;
- s = getnameinfo(&a.first.sa, a.second, host, NI_MAXHOST, nullptr, 0,
- NI_NUMERICHOST);
- if(s == 0) {
- A2_LOG_DEBUG(fmt("Sockets will bind to %s", host));
- }
- }
- }
- bindAddrsList_.swap(bindAddrsList);
- bindAddrsListIt_ = bindAddrsList_.begin();
- bindAddrs_ = *bindAddrsListIt_;
- }
- void getInterfaceAddress
- (std::vector<std::pair<sockaddr_union, socklen_t> >& ifAddrs,
- const std::string& iface, int family, int aiFlags)
- {
- A2_LOG_DEBUG(fmt("Finding interface %s", iface.c_str()));
- #ifdef HAVE_GETIFADDRS
- // First find interface in interface addresses
- struct ifaddrs* ifaddr = nullptr;
- if(getifaddrs(&ifaddr) == -1) {
- int errNum = SOCKET_ERRNO;
- A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND,
- iface.c_str(), errorMsg(errNum).c_str()));
- } else {
- std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> ifaddrDeleter
- (ifaddr, freeifaddrs);
- for(ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
- if(!ifa->ifa_addr) {
- continue;
- }
- int iffamily = ifa->ifa_addr->sa_family;
- if(family == AF_UNSPEC) {
- if(iffamily != AF_INET && iffamily != AF_INET6) {
- continue;
- }
- } else if(family == AF_INET) {
- if(iffamily != AF_INET) {
- continue;
- }
- } else if(family == AF_INET6) {
- if(iffamily != AF_INET6) {
- continue;
- }
- } else {
- continue;
- }
- if(strcmp(iface.c_str(), ifa->ifa_name) == 0) {
- socklen_t bindAddrLen =
- iffamily == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6);
- sockaddr_union bindAddr;
- memset(&bindAddr, 0, sizeof(bindAddr));
- memcpy(&bindAddr.storage, ifa->ifa_addr, bindAddrLen);
- ifAddrs.push_back(std::make_pair(bindAddr, bindAddrLen));
- }
- }
- }
- #endif // HAVE_GETIFADDRS
- if(ifAddrs.empty()) {
- addrinfo* res;
- int s;
- s = callGetaddrinfo(&res, iface.c_str(), nullptr, family, SOCK_STREAM, aiFlags,0);
- if(s) {
- A2_LOG_INFO(fmt(MSG_INTERFACE_NOT_FOUND, iface.c_str(), gai_strerror(s)));
- } else {
- std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
- (res, freeaddrinfo);
- addrinfo* rp;
- for(rp = res; rp; rp = rp->ai_next) {
- // Try to bind socket with this address. If it fails, the
- // address is not for this machine.
- try {
- SocketCore socket;
- socket.bind(rp->ai_addr, rp->ai_addrlen);
- sockaddr_union bindAddr;
- memset(&bindAddr, 0, sizeof(bindAddr));
- memcpy(&bindAddr.storage, rp->ai_addr, rp->ai_addrlen);
- ifAddrs.push_back(std::make_pair(bindAddr, rp->ai_addrlen));
- } catch(RecoverableException& e) {
- continue;
- }
- }
- }
- }
- }
- namespace {
- int defaultAIFlags = DEFAULT_AI_FLAGS;
- int getDefaultAIFlags()
- {
- return defaultAIFlags;
- }
- } // namespace
- void setDefaultAIFlags(int flags)
- {
- defaultAIFlags = flags;
- }
- int callGetaddrinfo
- (struct addrinfo** resPtr, const char* host, const char* service, int family,
- int sockType, int flags, int protocol)
- {
- struct addrinfo hints;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = family;
- hints.ai_socktype = sockType;
- hints.ai_flags = getDefaultAIFlags();
- hints.ai_flags |= flags;
- hints.ai_protocol = protocol;
- return getaddrinfo(host, service, &hints, resPtr);
- }
- int inetNtop(int af, const void* src, char* dst, socklen_t size)
- {
- sockaddr_union su;
- memset(&su, 0, sizeof(su));
- if(af == AF_INET) {
- su.in.sin_family = AF_INET;
- #ifdef HAVE_SOCKADDR_IN_SIN_LEN
- su.in.sin_len = sizeof(su.in);
- #endif // HAVE_SOCKADDR_IN_SIN_LEN
- memcpy(&su.in.sin_addr, src, sizeof(su.in.sin_addr));
- return getnameinfo(&su.sa, sizeof(su.in), dst, size, nullptr, 0,
- NI_NUMERICHOST);
- }
- if(af == AF_INET6) {
- su.in6.sin6_family = AF_INET6;
- #ifdef HAVE_SOCKADDR_IN6_SIN6_LEN
- su.in6.sin6_len = sizeof(su.in6);
- #endif // HAVE_SOCKADDR_IN6_SIN6_LEN
- memcpy(&su.in6.sin6_addr, src, sizeof(su.in6.sin6_addr));
- return getnameinfo(&su.sa, sizeof(su.in6), dst, size, nullptr, 0,
- NI_NUMERICHOST);
- }
- return EAI_FAMILY;
- }
- int inetPton(int af, const char* src, void* dst)
- {
- union {
- uint32_t ipv4_addr;
- unsigned char ipv6_addr[16];
- } binaddr;
- size_t len = net::getBinAddr(binaddr.ipv6_addr, src);
- if(af == AF_INET) {
- if(len != 4) {
- return -1;
- }
- in_addr* addr = reinterpret_cast<in_addr*>(dst);
- addr->s_addr = binaddr.ipv4_addr;
- return 0;
- }
- if(af == AF_INET6) {
- if(len != 16) {
- return -1;
- }
- in6_addr* addr = reinterpret_cast<in6_addr*>(dst);
- memcpy(addr->s6_addr, binaddr.ipv6_addr, sizeof(addr->s6_addr));
- return 0;
- }
- return -1;
- }
- namespace net {
- size_t getBinAddr(void* dest, const std::string& ip)
- {
- size_t len = 0;
- addrinfo* res;
- if(callGetaddrinfo(&res, ip.c_str(), nullptr, AF_UNSPEC,
- 0, AI_NUMERICHOST, 0) != 0) {
- return len;
- }
- std::unique_ptr<addrinfo, decltype(&freeaddrinfo)> resDeleter
- (res, freeaddrinfo);
- for(addrinfo* rp = res; rp; rp = rp->ai_next) {
- sockaddr_union su;
- memcpy(&su, rp->ai_addr, rp->ai_addrlen);
- if(rp->ai_family == AF_INET) {
- len = sizeof(in_addr);
- memcpy(dest, &(su.in.sin_addr), len);
- break;
- } else if(rp->ai_family == AF_INET6) {
- len = sizeof(in6_addr);
- memcpy(dest, &(su.in6.sin6_addr), len);
- break;
- }
- }
- return len;
- }
- bool verifyHostname(const std::string& hostname,
- const std::vector<std::string>& dnsNames,
- const std::vector<std::string>& ipAddrs,
- const std::string& commonName)
- {
- if(util::isNumericHost(hostname)) {
- if(ipAddrs.empty()) {
- return commonName == hostname;
- }
- // We need max 16 bytes to store IPv6 address.
- unsigned char binAddr[16];
- size_t addrLen = getBinAddr(binAddr, hostname);
- if(addrLen == 0) {
- return false;
- }
- for(auto& ipAddr : ipAddrs) {
- if(addrLen == ipAddr.size() &&
- memcmp(binAddr, ipAddr.c_str(), addrLen) == 0) {
- return true;
- }
- }
- return false;
- }
- if(dnsNames.empty()) {
- return util::tlsHostnameMatch(commonName, hostname);
- }
- for(auto& dnsName : dnsNames) {
- if(util::tlsHostnameMatch(dnsName, hostname)) {
- return true;
- }
- }
- return false;
- }
- namespace {
- bool ipv4AddrConfigured = true;
- bool ipv6AddrConfigured = true;
- } // namespace
- #ifdef __MINGW32__
- namespace {
- const uint32_t APIPA_IPV4_BEGIN = 2851995649u; // 169.254.0.1
- const uint32_t APIPA_IPV4_END = 2852061183u; // 169.254.255.255
- } // namespace
- #endif // __MINGW32__
- void checkAddrconfig()
- {
- #ifdef HAVE_IPHLPAPI_H
- A2_LOG_INFO("Checking configured addresses");
- ULONG bufsize = 15*1024;
- ULONG retval = 0;
- IP_ADAPTER_ADDRESSES* buf = 0;
- int numTry = 0;
- const int MAX_TRY = 3;
- do {
- buf = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(malloc(bufsize));
- retval = GetAdaptersAddresses(AF_UNSPEC, 0, 0, buf, &bufsize);
- if(retval != ERROR_BUFFER_OVERFLOW) {
- break;
- }
- free(buf);
- buf = 0;
- } while(retval == ERROR_BUFFER_OVERFLOW && numTry < MAX_TRY);
- if(retval != NO_ERROR) {
- A2_LOG_INFO("GetAdaptersAddresses failed. Assume both IPv4 and IPv6 "
- " addresses are configured.");
- return;
- }
- ipv4AddrConfigured = false;
- ipv6AddrConfigured = false;
- char host[NI_MAXHOST];
- sockaddr_union ad;
- int rv;
- for(IP_ADAPTER_ADDRESSES* p = buf; p; p = p->Next) {
- if(p->IfType == IF_TYPE_TUNNEL) {
- // Skip tunnel interface because Windows7 automatically setup
- // this for IPv6.
- continue;
- }
- PIP_ADAPTER_UNICAST_ADDRESS ucaddr = p->FirstUnicastAddress;
- if(!ucaddr) {
- continue;
- }
- for(PIP_ADAPTER_UNICAST_ADDRESS i = ucaddr; i; i = i->Next) {
- bool found = false;
- switch(i->Address.iSockaddrLength) {
- case sizeof(sockaddr_in): {
- memcpy(&ad.storage, i->Address.lpSockaddr,
- i->Address.iSockaddrLength);
- uint32_t haddr = ntohl(ad.in.sin_addr.s_addr);
- if(haddr != INADDR_LOOPBACK &&
- (haddr < APIPA_IPV4_BEGIN || APIPA_IPV4_END <= haddr)) {
- ipv4AddrConfigured = true;
- found = true;
- }
- break;
- }
- case sizeof(sockaddr_in6):
- memcpy(&ad.storage, i->Address.lpSockaddr,
- i->Address.iSockaddrLength);
- if(!IN6_IS_ADDR_LOOPBACK(&ad.in6.sin6_addr) &&
- !IN6_IS_ADDR_LINKLOCAL(&ad.in6.sin6_addr)) {
- ipv6AddrConfigured = true;
- found = true;
- }
- break;
- }
- rv = getnameinfo(i->Address.lpSockaddr, i->Address.iSockaddrLength,
- host, NI_MAXHOST, 0, 0, NI_NUMERICHOST);
- if(rv == 0) {
- if(found) {
- A2_LOG_INFO(fmt("Found configured address: %s", host));
- } else {
- A2_LOG_INFO(fmt("Not considered: %s", host));
- }
- }
- }
- }
- free(buf);
- A2_LOG_INFO(fmt("IPv4 configured=%d, IPv6 configured=%d",
- ipv4AddrConfigured, ipv6AddrConfigured));
- #elif defined(HAVE_GETIFADDRS)
- A2_LOG_INFO("Checking configured addresses");
- ipv4AddrConfigured = false;
- ipv6AddrConfigured = false;
- ifaddrs* ifaddr = nullptr;
- int rv;
- rv = getifaddrs(&ifaddr);
- if(rv == -1) {
- int errNum = SOCKET_ERRNO;
- A2_LOG_INFO(fmt("getifaddrs failed. Cause: %s", errorMsg(errNum).c_str()));
- return;
- }
- std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> ifaddrDeleter
- (ifaddr, freeifaddrs);
- char host[NI_MAXHOST];
- sockaddr_union ad;
- for(ifaddrs* ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
- if(!ifa->ifa_addr) {
- continue;
- }
- bool found = false;
- size_t addrlen = 0;
- switch(ifa->ifa_addr->sa_family) {
- case AF_INET: {
- addrlen = sizeof(sockaddr_in);
- memcpy(&ad.storage, ifa->ifa_addr, addrlen);
- if(ad.in.sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
- ipv4AddrConfigured = true;
- found = true;
- }
- break;
- }
- case AF_INET6: {
- addrlen = sizeof(sockaddr_in6);
- memcpy(&ad.storage, ifa->ifa_addr, addrlen);
- if(!IN6_IS_ADDR_LOOPBACK(&ad.in6.sin6_addr) &&
- !IN6_IS_ADDR_LINKLOCAL(&ad.in6.sin6_addr)) {
- ipv6AddrConfigured = true;
- found = true;
- }
- break;
- }
- default:
- continue;
- }
- rv = getnameinfo(ifa->ifa_addr, addrlen, host, NI_MAXHOST, nullptr, 0,
- NI_NUMERICHOST);
- if(rv == 0) {
- if(found) {
- A2_LOG_INFO(fmt("Found configured address: %s", host));
- } else {
- A2_LOG_INFO(fmt("Not considered: %s", host));
- }
- }
- }
- A2_LOG_INFO(fmt("IPv4 configured=%d, IPv6 configured=%d",
- ipv4AddrConfigured, ipv6AddrConfigured));
- #else // !HAVE_GETIFADDRS
- A2_LOG_INFO("getifaddrs is not available. Assume IPv4 and IPv6 addresses"
- " are configured.");
- #endif // !HAVE_GETIFADDRS
- }
- bool getIPv4AddrConfigured()
- {
- return ipv4AddrConfigured;
- }
- bool getIPv6AddrConfigured()
- {
- return ipv6AddrConfigured;
- }
- } // namespace net
- } // namespace aria2
|