P2P 与分布式存储 / 系统课时

从 torrent 文件读取分块信息

从 torrent 文件读取分块信息

拿到一个 .torrent 文件后,可以直接解析其中的 Bencode 元数据,确定资源包含哪些文件、每个分块覆盖哪些字节,以及如何取得分块的 SHA-1 校验值。本课使用 Python 标准库编写解析器,并通过可复现的样例验证分块索引、文件偏移和哈希之间的对应关系。

学习目标

  • 识别 .torrent 文件中的 announce、info、piece length、pieces 和文件路径字段。
  • 使用 Python 解析 Bencode,提取文件列表、分块长度及 SHA-1 摘要。
  • 根据全局分块索引计算字节范围,并定位跨文件边界的分块。

理解 torrent 文件的元数据结构

传统 BitTorrent v1 的 .torrent 文件使用 Bencode 编码。它支持整数、字节串、列表和字典四种类型。解析后通常得到一个顶层字典,其中 info 描述资源本身,announce 则提供 Tracker 地址。

字段 所在位置 含义
announce 顶层 Tracker URL,可能不存在
announce-list 顶层 可选的多 Tracker 列表
info.name info 建议使用的资源名称或根目录名
info.piece length info 常规分块长度,单位为字节
info.pieces info 连续排列的 20 字节 SHA-1 摘要
info.length info 单文件模式的文件长度
info.files info 多文件模式的文件长度与相对路径

length 和 files 分别对应单文件与多文件模式,不能把它们当作同一层级的文件列表。多文件模式下,每个 files 元素包含 length 和 path,其中 path 是由多个路径组件组成的列表。

例如,资源名为 dataset,包含 a.bin(5 字节)和 sub/b.bin(7 字节),总长度为 12 字节。假设 piece length = 4,则资源需要 3 个 Piece,每个 Piece 的哈希摘要占 20 字节,因此 pieces 必须恰好包含 60 字节。

用 Python 解析 Bencode 和分块字段

Bencode 中的字典键和字符串值本质上都是字节串。pieces 更是原始二进制摘要,不能使用 UTF-8 文本方式读取或按字符切分。下面的完整脚本仅依赖 Python 3.9+ 标准库,支持读取真实 .torrent 文件,也支持生成内存样例进行验证。

python
import hashlib
import sys


def decode(data, pos=0):
    # 返回解析值和下一个未消费字节的位置
    if pos >= len(data):
        raise ValueError('数据意外结束')
    tag = data[pos:pos + 1]
    if tag == b'i':
        end = data.index(b'e', pos + 1)
        raw = data[pos + 1:end]
        if not raw or (raw.startswith(b'0') and len(raw) > 1):
            raise ValueError('整数格式错误')
        return int(raw), end + 1
    if tag in (b'l', b'd'):
        items = []
        cursor = pos + 1
        while cursor < len(data) and data[cursor:cursor + 1] != b'e':
            value, cursor = decode(data, cursor)
            items.append(value)
        if cursor >= len(data):
            raise ValueError('容器未闭合')
        if tag == b'l':
            return items, cursor + 1
        if len(items) % 2 or any(not isinstance(k, bytes) for k in items[::2]):
            raise ValueError('字典键格式错误')
        return dict(zip(items[::2], items[1::2])), cursor + 1
    if b'0' <= tag <= b'9':
        colon = data.index(b':', pos)
        raw_size = data[pos:colon]
        if len(raw_size) > 1 and raw_size.startswith(b'0'):
            raise ValueError('字节串长度格式错误')
        size = int(raw_size)
        start = colon + 1
        end = start + size
        if end > len(data):
            raise ValueError('字节串长度越界')
        return data[start:end], end
    raise ValueError('未知 Bencode 类型')


def encode(value):
    # 只用于生成可复现样例,不参与真实文件的哈希重算
    if isinstance(value, int):
        return b'i' + str(value).encode() + b'e'
    if isinstance(value, bytes):
        return str(len(value)).encode() + b':' + value
    if isinstance(value, list):
        return b'l' + b''.join(encode(v) for v in value) + b'e'
    if isinstance(value, dict):
        return b'd' + b''.join(
            encode(k) + encode(value[k]) for k in sorted(value)
        ) + b'e'
    raise TypeError(type(value))


def inspect_torrent(raw):
    meta, end = decode(raw)
    if end != len(raw) or not isinstance(meta, dict):
        raise ValueError('顶层结构无效')
    info = meta[b'info']
    if not isinstance(info, dict):
        raise ValueError('info 必须是字典')
    if b'meta version' in info:
        raise ValueError('本示例不支持 BitTorrent v2 或混合种子')
    piece_size = info[b'piece length']
    hashes = info[b'pieces']
    if not isinstance(piece_size, int) or piece_size <= 0:
        raise ValueError('分块长度无效')
    if not isinstance(hashes, bytes) or len(hashes) % 20:
        raise ValueError('pieces 长度必须是 20 的倍数')

    name = info[b'name'].decode('utf-8')
    if b'files' in info:
        files = [
            ('/'.join(part.decode('utf-8') for part in f[b'path']), f[b'length'])
            for f in info[b'files']
        ]
    else:
        files = [(name, info[b'length'])]
    if any(not isinstance(size, int) or size < 0 for _, size in files):
        raise ValueError('文件长度无效')

    total = sum(size for _, size in files)
    count = (total + piece_size - 1) // piece_size
    if len(hashes) != count * 20:
        raise ValueError('分块数量与资源长度不一致')

    print('资源:', name)
    print('文件:', files)
    print('总字节:', total)
    print('分块长度:', piece_size)
    print('分块数量:', count)
    for index in range(count):
        start = index * piece_size
        stop = min(start + piece_size, total)
        digest = hashes[index * 20:(index + 1) * 20].hex()
        print(f'Piece {index}: [{start}, {stop}) SHA1={digest}')


if __name__ == '__main__':
    if len(sys.argv) == 2:
        with open(sys.argv[1], 'rb') as file:
            raw = file.read()
    else:
        payload = b'abcdefghijkl'
        info = {
            b'name': b'dataset',
            b'piece length': 4,
            b'files': [
                {b'length': 5, b'path': [b'a.bin']},
                {b'length': 7, b'path': [b'sub', b'b.bin']},
            ],
            b'pieces': b''.join(
                hashlib.sha1(payload[i:i + 4]).digest()
                for i in range(0, len(payload), 4)
            ),
        }
        raw = encode({b'announce': b'http://tracker.example/announce', b'info': info})
    inspect_torrent(raw)

保存为 inspect_torrent.py,执行以下命令运行内存样例:

bash
python inspect_torrent.py

预期输出:

text
资源: dataset
文件: [('a.bin', 5), ('sub/b.bin', 7)]
总字节: 12
分块长度: 4
分块数量: 3
Piece 0: [0, 4) SHA1=81fe8bfe87576c3ecb22426f8e57847382917acf
Piece 1: [4, 8) SHA1=2c0e7e6c8a0bb8c5ed8f2f36e5c9bde8c7c3c1b2
Piece 2: [8, 12) SHA1=604ebdeb8d3be5303c0fc891773f69fc3a3720fa

其中 SHA-1 值应以程序实际计算结果为准;第一块 abcd 的 SHA-1 为 81fe8bfe87576c3ecb22426f8e57847382917acf。其余摘要可以通过 Python 的 hashlib.sha1 独立核对,不能把示例中的十六进制文本作为固定协议字段。

读取实际种子时,将命令改为 python inspect_torrent.py sample.torrent。sample.torrent 是用户自己提供的文件名,实际路径可能不同。真实种子还可能使用非 UTF-8 名称、扩展字段或不规范编码;生产解析器需要增加编码兼容、Bencode 严格校验与资源上限。

建立 Piece 与文件字节范围的映射

BitTorrent v1 将全部文件按 info.files 中的顺序逻辑拼接,再按固定 piece length 切分。因此,Piece 索引针对整个资源,不会因为进入下一个文件而重新从零开始。

对于索引 i、分块长度 L 和资源总长度 T,采用左闭右开区间:

starti=i×Lstart_i=i\times L
endi=min⁡((i+1)×L,T)end_i=\min((i+1)\times L,T)

在上述样例中,文件与 Piece 的关系如下:

对象 全局字节区间 对应内容
a.bin [0,5) abcde
sub/b.bin [5,12) fghijkl
Piece 0 [0,4) abcd
Piece 1 [4,8) efgh
Piece 2 [8,12) ijkl

Piece 1 跨越文件边界:全局偏移 4 对应 a.bin 的第 5 个字节 e,全局偏移 5~7 对应 sub/b.bin 的前三个字节 fgh。客户端验证 Piece 1 时,必须按顺序拼接 efgh 后计算 SHA-1,不能分别对两个文件片段计算摘要。

BitTorrent 多文件资源与 Piece 全局字节区间映射图

在真实下载器中,可以先计算每个文件的全局起点,再求 Piece 区间与文件区间的交集。只有交集非空的文件才需要参与该 Piece 的磁盘读取或写入。最后一个 Piece 可能短于 piece length,但其哈希仍占完整的 20 字节。

校验分块哈希并处理解析边界

pieces 不是文件内容,也不是一个 SHA-1 字符串,而是按 Piece 顺序连续排列的原始摘要。第 i 块的摘要取自 pieces[i*20:(i+1)*20]。客户端下载分块后,使用完整分块数据计算 SHA-1,并与对应的 20 字节摘要比较。

下面的片段示例依赖前面脚本生成的 info 字典和 payload 字节串,用于验证第二个 Piece:

python
# 片段示例:接在样例 info 与 payload 创建完成之后运行
index = 1
piece_size = info[b'piece length']
start = index * piece_size
chunk = payload[start:start + piece_size]
expected = info[b'pieces'][index * 20:(index + 1) * 20]
print('分块数据:', chunk.decode('ascii'))
print('校验通过:', hashlib.sha1(chunk).digest() == expected)

预期输出:

text
分块数据: efgh
校验通过: True

验证真实 .torrent 时还需要区分三类问题:

  • 元数据格式错误:Bencode 不完整、piece length 非正数、pieces 长度不是 20 的倍数,应直接拒绝解析。
  • 资源布局错误:文件长度之和与摘要数量不匹配,或路径包含 ..、绝对路径等危险组件,应拒绝用于下载写盘。真实客户端还必须检查符号链接、路径规范化和目标目录边界。
  • 内容校验失败:Piece 字节数正确但 SHA-1 不匹配,应丢弃或重新获取该分块,不能将其标记为已验证。

完成验证后,应能从任意 v1 种子得到文件顺序、总长度、Piece 数量和每块的全局字节范围,并准确识别跨文件分块。分块摘要只能证明下载数据与种子声明一致;SHA-1 不提供现代意义上的抗恶意篡改安全保证,资源来源的可信性仍需另行验证。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

从 torrent 文件读取分块信息

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通