Example #1
0
def _callFunc(session, funcName, password, args):
    """Call custom cjdns admin function"""

    txid = _randomString()
    sock = session.socket
    sock.send('d1:q6:cookie4:txid10:' + txid + 'e')
    msg = _getMessage(session, txid)
    cookie = msg['cookie']
    txid = _randomString()
    req = {
        'q': funcName,
        'hash': hashlib.sha256(password + cookie).hexdigest(),
        'cookie': cookie,
        'args': args,
        'txid': txid
    }

    if password:
        req['aq'] = req['q']
        req['q'] = 'auth'
        reqBenc = bencode(req)
        req['hash'] = hashlib.sha256(reqBenc).hexdigest()

    reqBenc = bencode(req)
    sock.send(reqBenc)
    return _getMessage(session, txid)
Example #2
0
def callfunc(cjdns, funcName, password, args):
    sock = cjdns.socket;

    # empty the socket if there's anything on it.
    try:
        sock.recv(BUFFER_SIZE, socket.MSG_DONTWAIT);
    except:
        pass;

    sock.send('d1:q6:cookiee');
    data = sock.recv(BUFFER_SIZE);
    benc = bdecode(data);
    cookie = benc['cookie'];
    req = {
        'q': 'auth',
        'aq': funcName,
        'hash': hashlib.sha256(password + cookie).hexdigest(),
        'cookie' : cookie,
        'args': args
    };
    reqBenc = bencode(req);
    req['hash'] = hashlib.sha256(reqBenc).hexdigest();
    reqBenc = bencode(req);
    sock.send(reqBenc);
    data = sock.recv(BUFFER_SIZE);
    try:
        return bdecode(data);
    except ValueError:
        print("Failed to parse:\n" + data);
        print("Length: " + str(len(data)));
        raise;
Example #3
0
def _callFunc(session, funcName, password, args):
    """Call custom cjdns admin function"""

    txid = _randomString()
    sock = session.socket
    sock.send('d1:q6:cookie4:txid10:' + txid + 'e')
    msg = _getMessage(session, txid)
    cookie = msg['cookie']
    txid = _randomString()
    req = {
        'q': funcName,
        'hash': hashlib.sha256(password + cookie).hexdigest(),
        'cookie': cookie,
        'args': args,
        'txid': txid
    }

    if password:
        req['aq'] = req['q']
        req['q'] = 'auth'
        reqBenc = bencode(req)
        req['hash'] = hashlib.sha256(reqBenc).hexdigest()

    reqBenc = bencode(req)
    sock.send(reqBenc)
    return _getMessage(session, txid)
Example #4
0
File: cjdns.py Project: zorun/cjdns
def callfunc(cjdns, funcName, password, args):
    sock = cjdns.socket

    # empty the socket if there's anything on it.
    try:
        sock.recv(BUFFER_SIZE, socket.MSG_DONTWAIT)
    except:
        pass

    sock.send('d1:q6:cookiee')
    data = sock.recv(BUFFER_SIZE)
    benc = bdecode(data)
    cookie = benc['cookie']
    req = {
        'q': 'auth',
        'aq': funcName,
        'hash': hashlib.sha256(password + cookie).hexdigest(),
        'cookie': cookie,
        'args': args
    }
    reqBenc = bencode(req)
    req['hash'] = hashlib.sha256(reqBenc).hexdigest()
    reqBenc = bencode(req)
    sock.send(reqBenc)
    data = sock.recv(BUFFER_SIZE)
    try:
        return bdecode(data)
    except ValueError:
        print("Failed to parse:\n" + data)
        print("Length: " + str(len(data)))
        raise
Example #5
0
def getInfoHash():

    f = open("abc.torrent")
    buf = f.read()
    obj = bdecode(buf)
    obj2 = obj

    info = obj["info"]
    info = bencode(info)

    del obj2["info"]["pieces"]
    #print obj2

    sha = hashlib.sha1()
    sha.update(info)
    info_hash = sha.digest()
    hex = sha.hexdigest()

    info_hash = urllib.quote(info_hash)
    #print(info_hash)
    #print(hex)

    f.close()

    #print(peer)``

    return info_hash
Example #6
0
def get_torrent_file(target_name, announce_list=None, comment=None,
                     no_creation_date=False, piece_length=17,
                     torrent_name=None, private=False, num_threads=2,
                     web_seed_list=None, metainfo_file_path=None):
    if target_name == None:
        raise TgetException('Must specify the contents.')

    if not isinstance(target_name, str):
        raise TgetException('Must specify a valid file or directory name.')
    else:
        target = target_name.strip()
        if torrent_name == None:
            torrent_name = os.path.basename(target)
            
    if not metainfo_file_path:
        metainfo_file_path = os.getcwd() + '/' + torrent_name  + '.torrent'
    elif not os.path.isabs(metainfo_file_path):
        metainfo_file_path = os.getcwd() + '/' + metainfo_file_path
    
    if piece_length < 15 or piece_length > 28:
        raise TgetException('The piece length must be a number between 15 and 28.')
    
    piece_length = 1 << piece_length
    
    #if announce_list == None:
    #    raise TgetException('Must specify an announce URL.')
    
    if num_threads < 1 or num_threads > 20:
        raise TgetException('The number of threads must be a number between 1 and 20.')
    
 
    if os.path.isdir(target_name):
        dirname = os.path.abspath(target_name)
        target_is_directory = True
        file_list = []
        for sub_dir in os.walk(dirname):
            dirpath = sub_dir[0]
            for short_name in sub_dir[2]:
                file_path = dirpath + '/' + short_name
                if os.path.isfile(file_path):
                    file_list.append(file_path)
        file_list = sorted(file_list)
        
    elif os.path.isfile(target_name):
        dirname = ""
        target_is_directory = False
        file_list = [target_name]
    
    metadata = generate_metainfo(dirname + '/', announce_list, file_list,
                      target_is_directory, torrent_name,
                      piece_length, private,
                      comment, no_creation_date,
                      web_seed_list)
    
    with open(metainfo_file_path, 'wb') as f:
        f.write(bencode(metadata))
Example #7
0
 def query_find_node(self, address, nid):
     nid = get_neighbor(nid,self.nid) if nid else self.nid
     msg={
         "t":entropy(TID_LENGTH),
         "y":"q",
         "q":"find_node",
         "a":{"id":nid,
              "target":random_nid()
         },
     }
     self.send_krpc(bencode(msg), address)
Example #8
0
def callfunc(cjdns, funcName, password, args):
    txid = randStr();
    sock = cjdns.socket;
    sock.send('d1:q6:cookie4:txid10:'+ txid +'e');
    msg = _getMessage(cjdns, txid);
    cookie = msg['cookie'];
    txid = randStr();
    req = {
        'q': 'auth',
        'aq': funcName,
        'hash': hashlib.sha256(password + cookie).hexdigest(),
        'cookie' : cookie,
        'args': args,
        'txid': txid
    };
    reqBenc = bencode(req);
    req['hash'] = hashlib.sha256(reqBenc).hexdigest();
    reqBenc = bencode(req);
    sock.send(reqBenc);
    return _getMessage(cjdns, txid);
Example #9
0
def callfunc(cjdns, funcName, password, args):
    txid = randStr()
    sock = cjdns.socket
    sock.send('d1:q6:cookie4:txid10:' + txid + 'e')
    msg = _getMessage(cjdns, txid)
    cookie = msg['cookie']
    txid = randStr()
    req = {
        'q': 'auth',
        'aq': funcName,
        'hash': hashlib.sha256(password + cookie).hexdigest(),
        'cookie': cookie,
        'args': args,
        'txid': txid
    }
    reqBenc = bencode(req)
    req['hash'] = hashlib.sha256(reqBenc).hexdigest()
    reqBenc = bencode(req)
    sock.send(reqBenc)
    return _getMessage(cjdns, txid)
Example #10
0
	def encode(self,t,y,q=None,r=None,e=None,a=None):
		if not t or not y:
			return None
		msg = {'t': t,'y': y}
		if q:
			msg['q'] = q
			if a:
				msg['a'] = a
		elif r:
			msg['r'] = r
		else:
			return None

		if r:
			logging.debug(msg)
		return bencode(msg)
Example #11
0
    def encode(self, t, y, q=None, r=None, e=None, a=None):
        if not t or not y:
            return None
        msg = {'t': t, 'y': y}
        if q:
            msg['q'] = q
            if a:
                msg['a'] = a
        elif r:
            msg['r'] = r
        else:
            return None

        if r:
            logging.debug(msg)
        return bencode(msg)
Example #12
0
 def handle_request_announce_peers(self, decoded_msg,address):
     '''
     处理其他节点的announce_peers请求
     :return:
     '''
     print "handle_request_announce_peers"
     info_hash = decoded_msg["a"]["info_hash"]
     print "handle_request_announce_peers:",info_hash
     response={
         "t":decoded_msg["t"],
         "y":"r",
         "r":{
             "id":self.nid,
         }
     }
     self.send_krpc(bencode(response),address)
     pass
Example #13
0
    def __init__(self, url, fileName = None):  
        
        if fileName is None:
            handle = urllib2.urlopen(url) 

            # download the torrent into a temp dir
            self.tempFileName = "/tmp" + "/" + os.path.basename(url)
                
            tempFileHandle = file(self.tempFileName, 'w')
            tempFileHandle.write(handle.read())            
            tempFileHandle.close()
            
        else:
            self.tempFileName = fileName

        tempFileHandle = file(self.tempFileName, 'r')
                        
        torrentInfo = bdecode(tempFileHandle.read())
        self.torrentHashString = sha1(bencode(torrentInfo['info'])).hexdigest()
Example #14
0
 def handle_request_get_peers(self, decoded_msg,address):
     '''
     处理其他节点的get_peers请求
     :return:
     '''
     print "handle_request_get_peers"
     info_hash = decoded_msg["a"]["info_hash"]
     print "get_peers_info_hash:",info_hash
     response={
         "t":decoded_msg["t"],
         "y":"r",
         "r":{
             "id":self.nid,
             "token":info_hash[:TOKEN_LENGTH],
             "nodes":"",
         }
     }
     self.send_krpc(bencode(response),address)
     pass
Example #15
0
 def start_req_metainfo(self, MsgID):
     Dict = bencode({'msg_type': 0, 'piece': 0})
     msg = self.encode_ext_msg(MsgID, Dict)
     logging.info('start_req_metainfo:%r' % msg)
     return msg
def bencode_info(info):
    encodedInfo = bencode(info)
    return encodedInfo
Example #17
0
File: views.py Project: usic/dlms
def index(request):
    
    errorFlag = False
    user = request.user
    username = user.username
    
    tc = transmissionrpc.Client(settings.TRANSMISSION_SETTINGS['host'],
                                port=settings.TRANSMISSION_SETTINGS['port'],
                                user=settings.TRANSMISSION_SETTINGS['user'],
                                password=settings.TRANSMISSION_SETTINGS['password'])
    
    url = ''
    magicString = ''
    
    if request.method == 'POST':
        url = request.POST['url']
        
        try:
            # read the first 11 bytes to determine whether this is a torrent fileList
            handle = urllib2.urlopen(url) 
            magicString = handle.read(11)
        except ValueError, e:
            errorFlag = True
        
        if magicString == "d8:announce":
            # download the torrent into a temp dir
            tempFileName = "/tmp" + "/" + os.path.basename(url)
            
            tempFileHandle = file(tempFileName, 'w')
            tempFileHandle.write(magicString)
            tempFileHandle.write(handle.read())            
            tempFileHandle.close()

            tempFileHandle = file(tempFileName, 'r')
            
            #torrentInfo = libtorrent.torrent_info(libtorrent.bdecode(tempFileHandle.read()))
            #torrentHashString = str(torrentInfo.info_hash())
            
            torrentInfo = bdecode(tempFileHandle.read())
            torrentHashString = sha1(bencode(torrentInfo['info'])).hexdigest()
            
            
            torrentListForHash = Torrent.objects.filter(transmission_hash_string=torrentHashString)
            
            # if the hashstring of the torrent is already in the db, 
            # just add it to the db without adding to transmission
            if len(torrentListForHash) == 0:
        
                # add the torrent to transmission
                #globalDownloadDir = "/var/www/dlms_downloads/"
                globalDownloadDir = settings.GLOBAL_DOWNLOAD_DIR
                userDir = globalDownloadDir + torrentHashString
        
                try:
                    addedTorrent = tc.add_uri(tempFileName, download_dir = userDir)
                except TransmissionError, e:
                    errorFlag = True
    
            # save the record to the db
            torrent = Torrent(url=url, user=user, transmission_hash_string=torrentHashString)
            torrent.save()
       
            # delete the temp torrent file
            os.remove(tempFileName)
Example #18
0
#Cristina Chu
#Samarth Paliwal

#----------Parse Torrent file to output metainfo {} ----------#
from bencode import *
from hashlib import sha1
import struct
import socket

torrentFile = "alibaba.torrent"
metainfo_file = open(str(torrentFile), 'rb')
metainfo = bdecode(metainfo_file.read())
info = metainfo['info']
torrentDir = info['name']
metainfo_file.close()
info_hash=sha1(bencode(metainfo['info'])).digest()

#Get IP address of Peers/Seeders from File (ideally Tracker)

#If there is a text file with lines: peer IP, peer port
def getPeers(filename):
	f = open(filename, 'r')
	peers = []
	for x in f.readlines():
		x = x.split(",")
		peers.append(x[0],x[1])

	f.close()
	return peers

#using only 1 peer
Example #19
0
	def start_req_metainfo(self,MsgID):
		Dict = bencode({'msg_type': 0, 'piece': 0})
		msg = self.encode_ext_msg(MsgID,Dict)
		logging.info('start_req_metainfo:%r' % msg)
		return msg
Example #20
0
 def encode_ext_msg(self, MsgID, Dict):
     Body = bencode(Dict)
     Len = len(Body) + 2
     msg = struct.pack('!LBB', Len, 0x20, MsgID)
     msg += Body
     return msg
Example #21
0
# from BitTornado.bencode import *
from bencode import *

VERSION = '20030621'

if len(argv) == 1:
    print argv[0], 'torrent-files ...' 
    print
    exit(2) # common exit code for syntax error

for metainfo_name in argv[1:]:
    metainfo_file = open(metainfo_name, 'rb')
    metainfo = bdecode(metainfo_file.read())
    #print metainfo
    info = metainfo['info']
    info_hash = sha(bencode(info))

    print 'metafile:\t', basename(metainfo_name)
    piece_length = info['piece length']
    if info.has_key('length'):
        # let's assume we just have a fil3
        print 'file name\t', info['name']
        file_length = info['length']
        name ='file size      '
    else:
        # let's assume we have a directory structure
        print 'directory name: %s' % info['name']
        print 'files:'
        file_length = 0;
        for file in info['files']:
            path = '/'.join( file['path'])
Example #22
0
 def getInfoHash(self):
     return sha1(bencode(self.bDict["info"])).digest()
Example #23
0
#!/usr/bin/env python
import libtorrent as lt
import sys
from bencode import *
from hashlib import *
import random


with open(sys.argv[1],'rb') as FileHandle,\
    open('sha1EncodeRename.torrent','wb') as reWrite:
        decodeFileHandle=bdecode(FileHandle.read())
        arrayPoint=['path.utf-8','path']
        for i in decodeFileHandle['info']['files']:
           for j in arrayPoint:
               try:
                   i[j][0]=sha1(i[j][0].split('.')[0]).hexdigest()+'.'+i[j][0].split('.')[-1]
               except:
                   continue
           print i['path'][0]

        reWrite.write(bencode(decodeFileHandle))


Example #24
0
	def encode_ext_msg(self,MsgID,Dict):
		Body = bencode(Dict)
		Len = len(Body) + 2
		msg =  struct.pack('!LBB',Len,0x20,MsgID)
		msg += Body
		return msg