def scanPorts(self): host = input() print("[+] Scanning Ports for other bots") ports = range(45454, 50000) for port in ports: try: if self.connectTo(Peer(host, port)): self.addNewPeer(Peer(host, port)) print("[+] Found a new bot at", host + ":" + str(port)) except: pass
async def download(): print( "Proceso de descarga inicializado. \n\nEs posible que se deba esperar un tiempo prologando para la obtencion de pieces para la descarga.\n" ) peer_addresses = await Tracker(torrent).begin_connection() # asignacion de la clase encargada de gestionar las piezas, como la descarga que sera utilizada por cada # valido para hacer la descarga pieces = Pieces(torrent, torrent_writer.get_received_pieces_queue()) # lista de peers intanciados con su parametro de torrent, puerto, host # y descarga previamente creada. peers = [] for host, port in peer_addresses: peers.append(Peer(torrent, host, port, pieces, torrent_writer)) # lista de ejecucion de la descarga realizada para cada peer, # con su espera hasta que el mismo responda. for peer in peers: peer.pieces.peerList = peers await peer.download()
def __init__(self): Thread.__init__(self) self.id = "1000-" + str(random.randint(0, 100)) self.peer = Peer(self.id, self.resource_loaded) self.playlist_uri = "http://cdn.bem.tv/stream/soccer2sec/soccer/playlist.m3u8" self.player_buffer = [] self.start()
def __init__(self, bootstrap, miner, difficulty): """Allocate the backend storage of the high level API, i.e., your blockchain. Depending whether or not the miner flag has been specified, you should allocate the mining process. """ self._peer = Peer(bootstrap) self._blockchain = Blockchain()
def __handle_peer(self, client_sock): """ handle_peer( new socket connection ) -> () Dispatches messages from the socket connection """ self.__debug('New child ' + str(threading.currentThread().getName())) self.__debug('Connected ' + str(client_sock.getpeername())) host, port = client_sock.getpeername() conn = Peer(port, client_sock) while True: try: msg_type, msg_data = conn.recv_data() if msg_type: msg_type = msg_type.upper() if msg_type not in self.handlers: self.__debug('Peer msg not handled') # : %s: %s' % (msg_type, msg_data)) break else: self.__debug('Handling peer msg') # : %s: %s' % (msg_type, msg_data)) disconnect = self.handlers[msg_type](conn, msg_data) if disconnect: break except KeyboardInterrupt: raise except: traceback.print_exc() self.__debug('Disconnecting ' + str(client_sock.getpeername())) conn.close()
def create_peers(self): peers = [] for p in self.tracker.parse_peer_address(): if p[0] == self.ip: continue peers.append(Peer(p[0], p[1], self)) return peers
def handle_commands(self, command): if (command in ['help', '?', '/?', 'h']): self.cli.log('\nAvailable commands:') self.cli.log(' peer add HOST:PORT') self.cli.log(' peer remove HOST:PORT') self.cli.log(' track list') self.cli.log(' track get SHORT_HASH') return elif (command == 'exit' or command == 'quit'): self.cli.log('Exiting...') # Do some work to notify neighboring nodes that you're going down? sys.exit() tokens = command.split() if (len(tokens) == 0): return if (tokens[0] == 'peer'): if (len(tokens) < 3 or tokens[1] not in ['add', 'remove']): self.cli.log('usage: peer add|remove HOST:PORT') else: host, port = tokens[2].split(':') peer = Peer(self.cli, host, port) self.peer_manipulate(peer, tokens[1]) elif (tokens[0] == 'track'): if (len(tokens) < 2 or tokens[1] not in ['list', 'get'] or (tokens[1] == 'get' and len(tokens) < 3)): self.cli.log('Usage:') self.cli.log(' track list') self.cli.log(' track get SHORT_HASH') elif (tokens[1] == 'list'): self.do_track_list_update() elif (tokens[1] == 'get'): short_hash = tokens[2] if (len(short_hash) != constant.HASH_LEN): self.cli.log( f'SHORT_HASH should be the {constant.HASH_LEN} character prefix to the left of the track' ) return track = self.all_tracks_sh[short_hash] track.download(self.cli) self.update_tracks() else: self.cli.log('Invalid command. Type "help" for available commands')
def create_peers(self): peers = [] for p in self.tracker.peer_list: if p[0] == self.torrent.ip: continue peers.append(Peer(p[0], p[1], self)) return peers
def run(self): while True: try: msg, addr = self.hQueue.get(False) newPeer = Peer(msg, addr[0], addr[1]) # Create a new peer based on the username, which is given by the text before a semicolon, and the address. exists = self.existInList(newPeer) # If the peer exists, an index is returned. Otherwise, -1 is returned and we need to add the peer. if exists == 0: continue elif exists < 0: self.peerlist.append(newPeer) print("\n" + newPeer.username + " has come online.") self.timers.append(Timer(15.0, self.delete_peer, [newPeer])) self.timers[-1].start() else: try: self.timers[exists - 1].cancel() # If the peer already exists, cancel the current timer self.timers[exists - 1] = Timer( 15.0, self.delete_peer, [newPeer]) # and start a new one self.timers[exists - 1].start() except IndexError as ie: print(ie) except Empty: continue
def __init__(self, data: dict): self.failure_reason = data.get('failure reason') self.warning_message = data.get('warning message') self.interval = data.get('interval') self.min_interval = data.get('min interval') self.tracker_id = data.get('tracker id') self.complete = data.get('complete') self.incomplete = data.get('incomplete') peers = data.get('peers') if isinstance(peers, list): self.peers = [Peer(peer) for peer in peers] elif isinstance(peers, bytes): peers = [peers[i:i + 6] for i in range(len(peers))] self.peers = [Peer(peer) for peer in peers] else: self.peers = None
def __init__(self): init_balances = {} for i in xrange(Parameters.num_peers): init_balances["P_" + str(i)] = Parameters.start_balance self.gen_block = Block("B_-1", 0, init_balances, {}, {}, "None") self.nodes = [Peer("P_" + str(i), self.get_delay, self.gen_block) for i in xrange(Parameters.num_peers)] self.node_is_slow = dict() self.network_graph = self.generate_graph() self.assign_neighbours() for i in xrange(Parameters.num_peers): pid = "P_" + str(i) self.node_is_slow[pid] = (random.random() < Parameters.z) # testing str of peers. t = threading.Timer(5, self.nodes[0].write_to_file) t.start() #for tree generation if _ete2_import: self.nst = [NodeStyle() for i in xrange(Parameters.num_peers)] self.fnst = [NodeStyle() for i in xrange(Parameters.num_peers)] for i in xrange(Parameters.num_peers): self.nst[i]["bgcolor"] = "#" + str(hex(random.randint(128,255)))[2:] + str(hex(random.randint(128,255)))[2:] + str(hex(random.randint(128,255)))[2:] for i in xrange(Parameters.num_peers): self.fnst[i]["size"] = 15 self.fnst[i]["fgcolor"] = self.nst[i]["bgcolor"] self.ts = TreeStyle() # self.ts.mode = "c" #circle self.ts.show_leaf_name = False def my_layout(node): F = TextFace(node.name, tight_text=True) add_face_to_node(F, node, column=0, position="branch-right") self.ts.layout_fn = my_layout
def start(self, response=None, mechanism=None, locale="en_US", tune_params=None, username=None, password=None, client_properties=None, connection_options=None, sasl_options = None, channel_options=None): if response is not None and (username is not None or password is not None): raise RuntimeError("client must not specify both response and (username, password).") if response is not None: self.response = response authzid, self.username, self.password = response.split("\0") else: self.username = username self.password = password self.mechanism = mechanism self.locale = locale self.tune_params = tune_params self.client_properties=get_client_properties_with_defaults(provided_client_properties=client_properties, version_property_key="version") self.sasl_options = sasl_options self.socket = connect(self.host, self.port, connection_options) self.conn = Connection(self.socket, self.spec) self.peer = Peer(self.conn, ClientDelegate(self), Session, channel_options) self.conn.init() self.peer.start() self.wait() self.channel(0).connection_open(self.vhost)
def handlePeerArrival(self, name, connection): request = connection.recv(1024) request = request.decode() print(F"Incoming Request: {request}") if (request[:3] == "NEW" ): # NEW command is for new peers connecting to the server peerID = (len(self.connectedPeers) + 1) connection.send(f"{peerID}".encode()) information = request[4:].split(":") # we save the information of the new peer and store a Peer object inside the dirctionary self.connectedPeers[peerID] = Peer(str(information[0]), portNumber=int(information[1])) elif (request[:3] == "REQ"): # REQ command is for requesting a file requestedFile = request[4:] if Server.fileExists(f"Server_files/{requestedFile}"): self.sendFile("", connection, f"./Server_files/{requestedFile}") elif Tracker.manifestExists(requestedFile): self.sendManifestFile(connection, requestedFile) else: connection.send("ERR".encode()) connection.close() for peer in self.connectedPeers: print( f"Name: {self.connectedPeers[peer].name} - Port: {self.connectedPeers[peer].portNo}" )
def start(self, response=None, mechanism=None, locale="en_US", tune_params=None, username=None, password=None, client_properties=None, connection_options=None, sasl_options=None): self.mechanism = mechanism self.response = response self.username = username self.password = password self.locale = locale self.tune_params = tune_params self.client_properties = get_client_properties_with_defaults( provided_client_properties=client_properties) self.sasl_options = sasl_options self.socket = connect(self.host, self.port, connection_options) self.conn = Connection(self.socket, self.spec) self.peer = Peer(self.conn, ClientDelegate(self), Session) self.conn.init() self.peer.start() self.wait() self.channel(0).connection_open(self.vhost)
def __init__(self): host_name = socket.gethostname() if os.path.isdir("sdfs/"): shutil.rmtree("sdfs/") os.system("mkdir sdfs") self.membership_manager = Peer(host_name) self.membership_manager.start() self.padding = "jyuan18?yixinz6" self.file_receive_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.file_receive_socket.bind(("0.0.0.0",2333)) self.file_dict = {"filename":[1,2,3,4,5]} self.file_dict_lock = threading.Lock() self.file_to_node = {"filename":["ip1","ip2","ip3"]} self.ip = socket.gethostname() self.file_receive_socket.listen(100) logging.basicConfig(filename='vm1.log', level=logging.INFO) threading.Thread(target=self.receive_file).start() if self.ip == "fa18-cs425-g26-01.cs.illinois.edu": Master = master(self.membership_manager) threading.Thread(target=Master.listen, args=(Master.op_listen_socket, False)).start() threading.Thread(target=Master.listen, args=(Master.ack_listen_socket, True)).start()
def get_peers(peer_val, elts, length): peers = [] if (isinstance(peer_val, basestring)): # Compact response (binary) i = 0 while (i < len(peer_val)): curr_peer = peer_val[i:i + 6] ip_addr = socket.inet_ntoa(curr_peer[0:4]) port = int(unpack("!H", curr_peer[4:6])[0]) peers.append(Peer(ip_addr, port, elts, length)) i += 6 return peers else: # Dictionary repsonse??? for peer in peer_val: peers.append(Peer(peer['ip'], peer['port'], elts, length)) return peers
def add_peer(self, ip, port): p = Peer((ip, port), active_torrent=self) self.peer_history[(p.ip, p.port)] = 'connected' self.peers.append(p) #TODO store result of peer connect in self.peer_history - maybe use peer_id too or instead # this probably has to happen later, because p.connect is async # probably should do this in peer.die() return weakref.proxy(p)
def managed_peer(name, env): p = Peer(name, env) p.services.append(ConnectionManager(p)) p.services.append(PeerRequestHandler()) p.services.append(PingHandler()) p.services.append(Downtime(env, p)) p.services.append(Slowdown(env, p)) return p
def __init__(self): super(PeerApplication, self).__init__() os.system("pyuic5 -x GUI/gui.ui -o GUI/gui.py") # compile the gui from GUI.gui import Ui_MainWindow # import the newly compiled gui self.ui = Ui_MainWindow() # create an instance of the GUI self.ui.setupUi(self) self.configure() self.peer = Peer() self.show()
def __init__(self, cli, addr, conn, tracks, local_tracks): threading.Thread.__init__(self) self.cli = cli self.conn = conn self.tracks = tracks self.local_tracks = local_tracks self.peer = Peer(cli, *addr) self.cli.log(f'Got connection from {self.peer}')
def run(self): """ Peer is now active. A new P2PSP Peer object is created. """ print("Starting " + self.name) self.peer_active = True self._peer = Peer() print("Exiting " + self.name)
def sendTo(self): message = input("Message: ") peerIP = input("Recievers Ip: ") peerPort = input("Recievers Port: ") peer = Peer(peerIP, peerPort) if peer in self.connections: client = self.connectTo(peer) client.send(message) client.disconnect()
def Main(): name = input("Enter your name please: ") newPeer = Peer(name, portNumber=5600, allowConnection=True) newPeer.connect(justGetID=False) print("You are now connected to the server!") print(f"Hello {newPeer.name}! Your ID is {newPeer.id}") filename = input("Please enter the filename: ") newPeer.requestFile(filename)
def __init__(self, dns_ip_addr): self.dns_ip_addr = dns_ip_addr external_ip, external_port = self._retrieve_public_ip_stun() self.ip_addr = external_ip self.external_port = external_port self.peer = Peer(self.ip_addr, self.external_port) self.chord = Chord(self.peer) self.dhash = Dhash(self.peer)
def main(): # Read options from command line opts = readOptions(sys.argv[1:]) # Init peer mypeer = Peer(opts.id, opts.maxpeers, opts.port, opts.ttl, opts.verbose) # Add list of known peers for p in opts.peers: pfull = p.split(':') mypeer.addpeer(pfull[0], pfull[1], int(pfull[2])) # Add handlers for m in messages: mypeer.addhandler(m, messages[m].handler) # Add router mypeer.addrouter(distancerouter) # Start peer server in a separate thread t = threading.Thread( target = mypeer.start, args = [opts.backlog, opts.timeout] ) t.daemon = True t.start() print(f'Peer {mypeer.host}:{mypeer.port} started') # Start client menu() try: for line in sys.stdin: line = line.rstrip().split(' ', 2) msgtype = line[0].upper() target = line[1] if msgtype not in messages or not messages[msgtype].iscallable: print('Wrong message type. Please try again.') continue data = '' if len(line) == 3: data = line[2] if messages[msgtype].isasync: # Need to add own info as sender for async messages, so receiver can respond data = json.dumps({'data': data, 'sender': mypeer.peerid}) res = mypeer.sendtopeer(target, msgtype, data, not messages[msgtype].isasync) for r in res: if r[0] == 'ERRO': print(f'{r[1]}') break if r[0] == 'RESP': print(f'[{target}] -> {r[1]}') continue print('Unable to process response.') continue menu() except KeyboardInterrupt: exit()
def main(): # make sure a file name is provided if len(sys.argv) < 2: error_quit("File name not provided") ## attempt to decode torrent torrent = None try: torrent = Torrent(sys.argv[1]) except OSError as e: error_quit(f"Could not open torrent file - {e}") except BEncodeDecodeError as e: error_quit(f"Could not decode torrent file - {e}") except Exception as e: error_quit(f"Unexpected error! - {e}") ## attempt to contact tracker tracker = Tracker(torrent, ID, PORT) try: response = tracker.request() except TrackerParseError as e: error_quit(f"Tracker Parsing error - {e}") except URLError as e: error_quit(f"Could not connect to tracker: {e}") except BEncodeDecodeError as e: error_quit(f"Malformed tracker response: {e}") except Exception as e: error_quit(f"Unexpected error! - {e}") # make sure the peers blob is correct if len(response["peers"]) % 6 != 0: error_quit("Malformed peers list") # list of raw peer IPs and port raw_peers = [ response["peers"][i:i + 6] for i in range(0, len(response["peers"]), 6) ] # peers we are attempting to request pieces from seed_peers = [] for peer_bytes in raw_peers: try: seed_peers.append(Peer(peer_bytes)) except ValueError as e: print(f"Could not parse {peer_bytes}'s ip: {e}") asyncio.run(do_connect(seed_peers, torrent))
def _start_peer(self, connection, address, remote_pubkey=None): # create peer peer = Peer(self, connection, remote_pubkey=remote_pubkey) log.debug('created new peer', peer=peer, fno=connection.fileno()) self.peers.append(peer) # loop peer.start() log.debug('peer started', peer=peer, fno=connection.fileno()) assert not connection.closed return peer
def _start_peer(self, connection, address, remote_pubkey=None): log.debug('new connect', connection=connection, incoming=bool(not remote_pubkey)) # create peer peer = Peer(self, connection, remote_pubkey=remote_pubkey) log.debug('created new peer', peer=peer) self.peers.append(peer) # loop peer.start() log.debug('peer started', peer=peer)
def parse_config(config_file): # loading config file config = json.load(open(config_file, 'r')) ''' Create RouteServer environment ... ''' # create XRS object xrs = XRS() peers_out = {} for participant_name in config: participant = config[participant_name] for peer in participant["Peers"]: if (peer not in peers_out): peers_out[peer] = [] peers_out[peer].append(int(participant_name)) for participant_name in config: participant = config[participant_name] # adding asn and mappings asn = participant["ASN"] xrs.asn_2_participant[participant["ASN"]] = int(participant_name) xrs.participant_2_asn[int(participant_name)] = participant["ASN"] # adding ports and mappings ports = [{"ID": participant["Ports"][i]['Id'], "MAC": participant["Ports"][i]['MAC'], "IP": participant["Ports"][i]['IP']} for i in range(0, len(participant["Ports"]))] xrs.participant_2_port[int(participant_name)] = [] xrs.participant_2_portip[int(participant_name)] = [] xrs.participant_2_portmac[int(participant_name)] = [] for i in range(0, len(participant["Ports"])): xrs.port_2_participant[participant["Ports"][i]['Id']] = int(participant_name) xrs.portip_2_participant[participant["Ports"][i]['IP']] = int(participant_name) xrs.portmac_2_participant[participant["Ports"][i]['MAC']] = int(participant_name) xrs.participant_2_port[int(participant_name)].append(participant["Ports"][i]['Id']) xrs.participant_2_portip[int(participant_name)].append(participant["Ports"][i]['IP']) xrs.participant_2_portmac[int(participant_name)].append(participant["Ports"][i]['MAC']) peers_in = participant["Peers"] # create peer and add it to the route server environment xrs.participants[int(participant_name)] = Peer(asn, ports, peers_in, peers_out[int(participant_name)]) return xrs
def main(): torrent = Torrent('data/ubuntu.torrent') td = deepcopy(torrent.torrent_file_dict) td[b'info'][b'pieces'] = '20 byte pieces hashes go here...' pp(td) print('Number of pieces in the file:', torrent.num_pieces) print('Size of download in bytes: ', torrent.get_download_length()) input() peers_info = PeersGetter(torrent).parse_peers() writers = [] readers = [] peers_connected_to_count = 0 # Build connected peers for peer_info in peers_info: if peers_connected_to_count > 3: break peers_connected_to_count += 1 peer = Peer(torrent, peer_info=peer_info) peer.connect() if peer.is_connected: writers.append(peer) readers.append(peer) while not torrent.is_download_finished(): # print( # 'Downloading... Writers: {} Readers: {}'.format( # len(readers), len(writers) # ) # ) to_read, to_write, errors = select.select(readers, writers, readers) for peer in to_read: peer.read() for peer in to_write: peer.write() for peer in errors: readers.remove(peer) writers.remove(peer)