/* */ #include "PeerListenCommand.h" #include "DownloadEngine.h" #include "Peer.h" #include "RequestGroupMan.h" #include "RecoverableException.h" #include "CUIDCounter.h" #include "message.h" #include "ReceiverMSEHandshakeCommand.h" #include "Logger.h" #include "Socket.h" #include namespace aria2 { int32_t PeerListenCommand::__numInstance = 0; PeerListenCommand* PeerListenCommand::__instance = 0; PeerListenCommand::PeerListenCommand(int32_t cuid, DownloadEngine* e): Command(cuid), e(e), _lowestSpeedLimit(20*1024) { ++__numInstance; } PeerListenCommand::~PeerListenCommand() { --__numInstance; } int32_t PeerListenCommand::bindPort(IntSequence& seq) { while(seq.hasNext()) { int32_t port = seq.next(); try { socket->bind(port); socket->beginListen(); socket->setNonBlockingMode(); logger->info(MSG_LISTENING_PORT, cuid, port); return port; } catch(RecoverableException* ex) { logger->error(MSG_BIND_FAILURE, ex, cuid, port); socket->closeConnection(); delete ex; } } return -1; } bool PeerListenCommand::execute() { if(e->isHaltRequested() || e->_requestGroupMan->downloadFinished()) { return true; } for(int32_t i = 0; i < 3 && socket->isReadable(0); i++) { SocketHandle peerSocket; try { peerSocket = socket->acceptConnection(); std::pair peerInfo; peerSocket->getPeerInfo(peerInfo); std::pair localInfo; peerSocket->getAddrInfo(localInfo); if(peerInfo.first == localInfo.first) { continue; } // Since peerSocket may be in non-blocking mode, make it blocking mode // here. peerSocket->setBlockingMode(); PeerHandle peer = new Peer(peerInfo.first, 0); int32_t cuid = CUIDCounterSingletonHolder::instance()->newID(); Command* command = new ReceiverMSEHandshakeCommand(cuid, peer, e, peerSocket); e->commands.push_back(command); logger->debug("Accepted the connection from %s:%u.", peer->ipaddr.c_str(), peer->port); logger->debug("Added CUID#%d to receive BitTorrent/MSE handshake.", cuid); } catch(RecoverableException* ex) { logger->debug(MSG_ACCEPT_FAILURE, ex, cuid); delete ex; } } e->commands.push_back(this); return false; } PeerListenCommand* PeerListenCommand::getInstance(DownloadEngine* e) { if(__numInstance == 0) { __instance = new PeerListenCommand(CUIDCounterSingletonHolder::instance()->newID(), e); } return __instance; } } // namespace aria2