/* */ #include "PeerListenCommand.h" #include "PeerInteractionCommand.h" PeerListenCommand::PeerListenCommand(int cuid, TorrentDownloadEngine* e) :Command(cuid), e(e), socket(NULL) { } PeerListenCommand::~PeerListenCommand() { if(socket != NULL) { delete socket; } } int PeerListenCommand::bindPort(int portRangeStart, int portRangeEnd) { if(portRangeStart > portRangeEnd) { return -1; } for(int port = portRangeStart; port <= portRangeEnd; port++) { try { socket = new Socket(); socket->beginListen(port); e->logger->info("CUID#%d - using port %d for accepting new connections", cuid, port); return port; } catch(Exception* ex) { e->logger->error("CUID#%d - an error occurred while binding port=%d", ex, cuid, port); delete ex; delete socket; socket = NULL; } } return -1; } bool PeerListenCommand::execute() { for(int i = 0; i < 3 && socket->isReadable(0); i++) { Socket* peerSocket = NULL; try { peerSocket = socket->acceptConnection(); if(e->torrentMan->connections < MAX_PEERS) { pair peerInfo; peerSocket->getPeerInfo(peerInfo); Peer* peer = new Peer(peerInfo.first, peerInfo.second, e->torrentMan->pieceLength, e->torrentMan->totalSize); if(e->torrentMan->addPeer(peer, true)) { int newCuid = e->torrentMan->getNewCuid(); peer->cuid = newCuid; PeerInteractionCommand* command = new PeerInteractionCommand(newCuid, peer, e, peerSocket, PeerInteractionCommand::RECEIVER_WAIT_HANDSHAKE); e->commands.push(command); e->logger->debug("CUID#%d - incoming connection, adding new command CUID#%d", cuid, newCuid); } else { delete peer; } } delete peerSocket; } catch(Exception* ex) { e->logger->error("CUID#%d - error in accepting connection", ex, cuid); delete ex; if(peerSocket != NULL) { delete peerSocket; } } } e->commands.push(this); return false; }