/* */ #include "PeerListenCommand.h" #include "PeerInteractionCommand.h" PeerListenCommand::PeerListenCommand(int cuid, TorrentDownloadEngine* e, const BtContextHandle& btContext) :BtContextAwareCommand(cuid, btContext), e(e) {} 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); if(peerInfo.first != localInfo.first && btRuntime->getConnections() < MAX_PEERS) { PeerHandle peer = PeerHandle(new Peer(peerInfo.first, peerInfo.second, btContext->getPieceLength(), btContext->getTotalLength())); if(peerStorage->addPeer(peer)) { int newCuid = btRuntime->getNewCuid(); peer->cuid = newCuid; PeerInteractionCommand* command = new PeerInteractionCommand(newCuid, 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, newCuid); } } } catch(RecoverableException* ex) { logger->error("CUID#%d - error in accepting connection", ex, cuid); delete ex; } } e->commands.push_back(this); return false; }