Ejemplo n.º 1
0
    def setUp(self):
        """create test client, add sample data"""

        s = Stock(stock_symbol="AAPL", stock_name="Apple")
        p = Peer(lead_stock_symbol=s.stock_symbol, peer_stock_symbol='MSFT')
        p.id = 9876

        db.session.add_all([s, p])
        db.session.commit()
        self.p = p
Ejemplo n.º 2
0
def handle_started(values, user, peer):
  if peer is not None:
    return None, 'You are already on this torrent'
  
  new_peer = Peer(info_hash=values['info_hash'], peer_id=values['peer_id'], port=values['port'], user=user, key=values['key'])
  if values['amount_left'] == 0:
    new_peer.state = settings.MAGIC_VALUES['seed']
  else:
    new_peer.state = settings.MAGIC_VALUES['peer']
  
  new_peer.save()
  
  return new_peer, None
Ejemplo n.º 3
0
    def extract_peers(self):
        announce_list = []

        if 'announce-list' in self.torrent_tracker:
            announce_list = self.torrent_tracker['announce-list']
        else:
            announce_list.append([self.torrent_tracker['announce']])
        
        for announce in announce_list:
            announce = announce[0]

            if announce.startswith('http'):
                piece_length = str(self.torrent_tracker['info']['piece length'])
                response = self.scrape_http(announce, self.file_hash, self.id, piece_length)
            elif announce.startswith('udp'):
                response = self.scrape_udp(announce, self.file_hash, self.id)

            if response:
                break

        for data_chunk in self.chunk_to_six_bytes(response):
            ip = []
            port = None

            for index in range(0, 4):
                ip.append(str(data_chunk[index]))
            
            port = data_chunk[4] * 256 + data_chunk[5]
            socket8 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            socket8.setblocking(0)
            ip = '.'.join(ip)
            peer = Peer(ip, port, socket8, self.file_hash, self.id)
            self.peers.append(peer)
        print('Total of peers: ', len(self.peers))
Ejemplo n.º 4
0
def find_new_peers():
    urls = get_initial_peer_urls()
    for url in urls:
        peer = session.query(Peer).filter_by(url=url).one_or_none()
        if peer is None:
            peer = Peer(url=url)
            session.add(peer)
            session.commit()
            print('Added {}'.format(url))
Ejemplo n.º 5
0
    def get(self):
        ## remove any old peers
        plist = Peer.all().filter('datetime <',datetime.now() - timedelta(days=1))
        peercount = plist.count()
        for p in plist:
            p.delete()

        ## remove any empty trackers
        trackers = Tracker.all()
        trackercount = 0
        for tracker in trackers:
            p = Peer.all().filter('tracker =',tracker).order('-datetime').get()
            if p == None:
                tracker.delete()
                trackercount += 1

        ## some simple stats
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write("Cleaned %d trackers and %d peers"%(trackercount,peercount))
        if trackercount and peercount:
            logging.info("Cleaned %d trackers and %d peers"%(trackercount,peercount))
Ejemplo n.º 6
0
    def get(self,key):
        self.response.headers['Content-Type'] = 'text/plain'
        if re.match(r"\w{3,25}",key): ## check if a tracker is valid
            ## Check if the tracker exists, if not create it
            tracker = GetTracker(key)
            ## Check if the peer making the request is already in the DB, if not add them
            Tick(tracker,self.request.remote_addr)

            ## try getting a given tick if not set the default
            try:
                tick = int(self.request.get('tick'))
            except:
                tick = 60

            ## Get and echo the relevant peers
            plist = Peer.all().filter('tracker =',tracker).filter('datetime >',datetime.now() - timedelta(seconds=tick))
            for peer in plist:
                if peer.address != self.request.remote_addr:
                    self.response.out.write(peer.address+"\n")
        else:
            self.response.out.write('Tracker must contain only numbers, letters and the underscore, it must also be between 3 and 25 charachters')
Ejemplo n.º 7
0
    async def accept(self, reader, writer):
        addr = writer.get_extra_info('peername')
        peer = Peer(addr[0], addr[1])
        self.addr = addr

        client = PeerTCP(self.peer_id, peer)
        self.client = client

        try:
            info_hash = await client.accept(reader, writer)
            if info_hash not in self.torrent_managers:
                raise ValueError('Unknown info hash')
        except Exception as e:
            client.close()

            if isinstance(e, asyncio.CancelledError):
                raise
            else:
                print('{} was not accepted because of {}'.format(
                    peer, repr(e)))
        else:
            self.torrent_managers[info_hash].accept_client(peer, client)
Ejemplo n.º 8
0
def handle_started(values, user, peer):
    if peer is not None:
        return None, 'You are already on this torrent'

    new_peer = Peer(info_hash=values['info_hash'],
                    peer_id=values['peer_id'],
                    port=values['port'],
                    user=user,
                    key=values['key'])
    if values['amount_left'] == 0:
        new_peer.state = settings.MAGIC_VALUES['seed']
    else:
        new_peer.state = settings.MAGIC_VALUES['peer']

    new_peer.save()

    return new_peer, None
Ejemplo n.º 9
0
def Tick(tracker,address):
    p = Peer.all().filter('address =',address).filter('tracker =',tracker).get()
    if p != None:
        p.put()
    else:
        Peer(address=address,tracker=tracker).put()