/* */ #include "PeerListenCommand.h" #include "PeerInteractionCommand.h" #include "RecoverableException.h" #include "CUIDCounter.h" PeerListenCommand::PeerListenCommand(int cuid, TorrentDownloadEngine* e, const BtContextHandle& btContext) :BtContextAwareCommand(cuid, btContext), e(e), _lowestSpeedLimit(20*1024) {} PeerListenCommand::~PeerListenCommand() {} int PeerListenCommand::bindPort(int portRangeStart, int portRangeEnd) { if(portRangeStart > portRangeEnd) { return -1; } for(int port = portRangeStart; port <= portRangeEnd; port++) { try { socket->beginListen(port); logger->info("CUID#%d - using port %d for accepting new connections", cuid, port); return port; } catch(RecoverableException* ex) { logger->error("CUID#%d - an error occurred while binding port=%d", ex, cuid, port); socket->closeConnection(); delete ex; } } return -1; } bool PeerListenCommand::execute() { if(btRuntime->isHalt()) { return true; } for(int i = 0; i < 3 && socket->isReadable(0); i++) { SocketHandle peerSocket; try { peerSocket = socket->acceptConnection(); pair peerInfo; peerSocket->getPeerInfo(peerInfo); pair localInfo; peerSocket->getAddrInfo(localInfo); TransferStat tstat = peerStorage->calculateStat(); if(peerInfo.first != localInfo.first && (!pieceStorage->downloadFinished() && tstat.getDownloadSpeed() < _lowestSpeedLimit || btRuntime->getConnections() < MAX_PEERS)) { PeerHandle peer = PeerHandle(new Peer(peerInfo.first, peerInfo.second, btContext->getPieceLength(), btContext->getTotalLength())); if(peerStorage->addIncomingPeer(peer)) { peer->cuid = CUIDCounterSingletonHolder::instance()->newID(); PeerInteractionCommand* command = new PeerInteractionCommand(peer->cuid, peer, e, btContext, peerSocket, PeerInteractionCommand::RECEIVER_WAIT_HANDSHAKE); e->commands.push_back(command); logger->debug("CUID#%d - incoming connection, adding new command CUID#%d", cuid, peer->cuid); } } } catch(RecoverableException* ex) { logger->debug("CUID#%d - error in accepting connection", ex, cuid); delete ex; } } e->commands.push_back(this); return false; }