1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main

// A bencode decoder, and the torrent-file model built on top of it.
//
// Bencode has four types:
//
//	i<int>e                     integer
//	<len>:<bytes>               byte string (NOT necessarily UTF-8)
//	l<value>*e                  list
//	d(<string><value>)*e        dictionary, keys sorted
//
// We only ever decode; the torrent files come from the tracker and are stored
// verbatim in the database, so re-encoding is never needed.
//
// Strings stay []byte because a torrent's `pieces` field is a concatenation of
// binary SHA-1 hashes and is not text at all. Fields that are text are converted
// leniently at the point of use, as the Haskell version did: a torrent with a
// mis-encoded filename should still be usable.

import (
	"errors"
	"fmt"
	"strconv"
	"time"
	"unicode/utf8"
)

// bencodeValue is a decoded bencode value: exactly one field is set.
type bencodeValue struct {
	Str  []byte
	Int  *int64
	List []bencodeValue
	Dict map[string]bencodeValue
}

func (v bencodeValue) kind() string {
	switch {
	case v.Str != nil:
		return "byte-string"
	case v.Int != nil:
		return "integer"
	case v.List != nil:
		return "list"
	case v.Dict != nil:
		return "dict"
	default:
		return "empty"
	}
}

// parseBencode decodes one value, which must span the whole input.
func parseBencode(data []byte) (bencodeValue, error) {
	v, rest, err := decodeValue(data)
	if err != nil {
		return bencodeValue{}, err
	}
	if len(rest) != 0 {
		// Trailing data usually means we mis-parsed a length somewhere.
		return bencodeValue{}, fmt.Errorf("%d trailing bytes after the top-level value", len(rest))
	}
	return v, nil
}

func decodeValue(data []byte) (bencodeValue, []byte, error) {
	if len(data) == 0 {
		return bencodeValue{}, nil, errors.New("unexpected end of input")
	}
	switch c := data[0]; {
	case c == 'i':
		return decodeInt(data)
	case c == 'l':
		return decodeList(data)
	case c == 'd':
		return decodeDict(data)
	case c >= '0' && c <= '9':
		return decodeString(data)
	default:
		return bencodeValue{}, nil, fmt.Errorf("unexpected byte %q at start of value", c)
	}
}

func decodeInt(data []byte) (bencodeValue, []byte, error) {
	end := indexByte(data, 'e')
	if end < 0 {
		return bencodeValue{}, nil, errors.New("unterminated integer")
	}
	n, err := strconv.ParseInt(string(data[1:end]), 10, 64)
	if err != nil {
		return bencodeValue{}, nil, fmt.Errorf("bad integer: %w", err)
	}
	return bencodeValue{Int: &n}, data[end+1:], nil
}

func decodeString(data []byte) (bencodeValue, []byte, error) {
	colon := indexByte(data, ':')
	if colon < 0 {
		return bencodeValue{}, nil, errors.New("byte-string without a length separator")
	}
	length, err := strconv.Atoi(string(data[:colon]))
	if err != nil {
		return bencodeValue{}, nil, fmt.Errorf("bad byte-string length: %w", err)
	}
	if length < 0 {
		return bencodeValue{}, nil, errors.New("negative byte-string length")
	}
	start := colon + 1
	if start+length > len(data) {
		return bencodeValue{}, nil, fmt.Errorf("byte-string of length %d exceeds the remaining input", length)
	}
	// Non-nil even when empty, so kind() can distinguish it from a missing value.
	s := data[start : start+length]
	if s == nil {
		s = []byte{}
	}
	return bencodeValue{Str: s}, data[start+length:], nil
}

func decodeList(data []byte) (bencodeValue, []byte, error) {
	rest := data[1:]
	list := []bencodeValue{}
	for {
		if len(rest) == 0 {
			return bencodeValue{}, nil, errors.New("unterminated list")
		}
		if rest[0] == 'e' {
			return bencodeValue{List: list}, rest[1:], nil
		}
		var v bencodeValue
		var err error
		v, rest, err = decodeValue(rest)
		if err != nil {
			return bencodeValue{}, nil, err
		}
		list = append(list, v)
	}
}

func decodeDict(data []byte) (bencodeValue, []byte, error) {
	rest := data[1:]
	dict := map[string]bencodeValue{}
	for {
		if len(rest) == 0 {
			return bencodeValue{}, nil, errors.New("unterminated dict")
		}
		if rest[0] == 'e' {
			return bencodeValue{Dict: dict}, rest[1:], nil
		}
		var key bencodeValue
		var err error
		key, rest, err = decodeValue(rest)
		if err != nil {
			return bencodeValue{}, nil, err
		}
		if key.Str == nil {
			return bencodeValue{}, nil, fmt.Errorf("dict key is a %s, not a byte-string", key.kind())
		}
		var val bencodeValue
		val, rest, err = decodeValue(rest)
		if err != nil {
			return bencodeValue{}, nil, err
		}
		dict[string(key.Str)] = val
	}
}

func indexByte(data []byte, b byte) int {
	for i, c := range data {
		if c == b {
			return i
		}
	}
	return -1
}

// ---------------------------------------------------------------------------
// Torrent files
// ---------------------------------------------------------------------------

// torrentFile is the subset of a .torrent we care about.
//
// From the BitTorrent spec:
//   - announce — the URL of the tracker
//   - info.name — suggested file name (single file) or directory name (multi)
//   - info.files — one entry per file, each with a length and a path split into
//     path components; only present for multi-file torrents
//   - info.piece length / pieces — piece hashes, not used here
type torrentFile struct {
	Announce     string
	Comment      string
	CreatedBy    string
	CreationDate *time.Time
	Encoding     string
	Info         torrentInfo
}

type torrentInfo struct {
	Name        string
	Files       []torrentFileEntry
	PieceLength uint64
	Pieces      []byte
	Private     *bool
	Source      string
}

type torrentFileEntry struct {
	Length uint64
	// Path is the file path split into components; join with "/" to get the
	// path relative to Info.Name.
	Path []string
}

// parseTorrentFile decodes a .torrent.
func parseTorrentFile(data []byte) (torrentFile, error) {
	root, err := parseBencode(data)
	if err != nil {
		return torrentFile{}, fmt.Errorf("cannot parse bencode: %w", err)
	}
	if root.Dict == nil {
		return torrentFile{}, fmt.Errorf("expected a bencode dict, but got %s", root.kind())
	}

	var tf torrentFile
	tf.Announce = lenientText(root.Dict["announce"].Str)
	tf.Comment = lenientText(root.Dict["comment"].Str)
	tf.CreatedBy = lenientText(root.Dict["created by"].Str)
	tf.Encoding = lenientText(root.Dict["encoding"].Str)
	if v, ok := root.Dict["creation date"]; ok && v.Int != nil {
		t := time.Unix(*v.Int, 0).UTC()
		tf.CreationDate = &t
	}

	infoVal, ok := root.Dict["info"]
	if !ok || infoVal.Dict == nil {
		return torrentFile{}, errors.New(`torrent has no "info" dict`)
	}
	info := infoVal.Dict

	tf.Info.Name = lenientText(info["name"].Str)
	tf.Info.Pieces = info["pieces"].Str
	tf.Info.Source = lenientText(info["source"].Str)
	if v, ok := info["piece length"]; ok && v.Int != nil && *v.Int >= 0 {
		tf.Info.PieceLength = uint64(*v.Int)
	}
	if v, ok := info["private"]; ok && v.Int != nil {
		b := *v.Int != 0
		tf.Info.Private = &b
	}

	// Multi-file torrents have `files`; single-file ones have `length` and use
	// `name` as the file name. Redacted only ever produces multi-file torrents,
	// but handling both costs little and avoids a confusing failure.
	if filesVal, ok := info["files"]; ok {
		if filesVal.List == nil {
			return torrentFile{}, fmt.Errorf(`"files" is a %s, not a list`, filesVal.kind())
		}
		for i, f := range filesVal.List {
			if f.Dict == nil {
				return torrentFile{}, fmt.Errorf("file %d is a %s, not a dict", i, f.kind())
			}
			var entry torrentFileEntry
			if v, ok := f.Dict["length"]; ok && v.Int != nil && *v.Int >= 0 {
				entry.Length = uint64(*v.Int)
			} else {
				return torrentFile{}, fmt.Errorf("file %d has no valid length", i)
			}
			pathVal, ok := f.Dict["path"]
			if !ok || pathVal.List == nil {
				return torrentFile{}, fmt.Errorf("file %d has no path list", i)
			}
			for _, comp := range pathVal.List {
				if comp.Str == nil {
					return torrentFile{}, fmt.Errorf("file %d has a non-string path component", i)
				}
				entry.Path = append(entry.Path, lenientText(comp.Str))
			}
			tf.Info.Files = append(tf.Info.Files, entry)
		}
	} else if v, ok := info["length"]; ok && v.Int != nil && *v.Int >= 0 {
		tf.Info.Files = []torrentFileEntry{{
			Length: uint64(*v.Int),
			Path:   []string{tf.Info.Name},
		}}
	}

	return tf, nil
}

// lenientText converts bytes to a string, replacing invalid UTF-8 rather than
// failing: torrent file names are frequently in some legacy encoding, and a
// mangled name is far better than an unusable torrent.
func lenientText(b []byte) string {
	if b == nil {
		return ""
	}
	if utf8.Valid(b) {
		return string(b)
	}
	runes := make([]rune, 0, len(b))
	for len(b) > 0 {
		r, size := utf8.DecodeRune(b)
		runes = append(runes, r) // RuneError for invalid sequences
		b = b[size:]
	}
	return string(runes)
}