views:

78

answers:

2

Hello,

I'm currently developing a torrent metainfo management library for Ruby.

I'm having trouble reading the pieces from the files. I just don't understand how I'm supposed to go about it. I know I'm supposed to SHA1 digest piece length bytes of a file once (or read piece length bytes multiple times, or what?)

I'm counting on your help. Pseudo / Python / Ruby / PHP code preferred.

Thanks in advance.

+1  A: 

C#

// Open the file
using (var file = File.Open(...))
{
    // Move to the relevant place in the file where the piece begins
    file.Seek(piece * pieceLength, SeekOrigin.Begin);

    // Attempt to read up to pieceLength bytes from the file into a buffer
    byte[] buffer = new byte[pieceLength];
    int totalRead = 0;
    while (totalRead < pieceLength)
    {
        var read = stream.Read(buffer, totalRead, pieceLength-totalRead);
        if (read == 0)
        {
            // the piece is smaller than the pieceLength,
            // because it’s the last in the file
            Array.Resize(ref buffer, totalRead);
            break;
        }
        totalRead += read;
    }

    // If you want the raw data for the piece:
    return buffer;

    // If you want the SHA1 hashsum:
    return SHA1.Create().ComputeHash(buffer);
}
Timwi
That's just a function to read a single piece, from a single file, right? if so, should I just read x pieces of each file with that function and concatenate them to a string which I will then bencode? (x pieces being ceil(file size / piece length))
mkroman
@mkroman: Your question only stated “I'm having trouble reading the pieces from the files”. My answer answers this. If not this, what exactly do you need help with?
Timwi
I need help with the whole process of reading each piece in each file, hashing it and then concatenating the right amount of bytes etc. Do you think you could give me an example on how to do exactly that?
mkroman
A: 

Please taker a look at this distribution here:

http://prdownload.berlios.de/torrentparse/TorrentParse.GTK.0.21.zip

Written in PHP, it contains an Encoder and Decoder and the in's and out I believe!

RobertPitt
Thanks for your comment, but that's not what I was looking for. I'm not having trouble with bencoding.
mkroman