aboutsummaryrefslogtreecommitdiff
path: root/meta/torrent.go
blob: 20496bec7672cd935adb432b16d9c2c9fed997ca (plain)
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
package meta

import (
	"crypto/sha1"
	"errors"
	"fmt"
	"os"
	"path"
	"time"
)

var ErrNotImplemented = errors.New("not implemented")

type File struct {
	Length int      `bencode:"length"`
	MD5Sum []byte   `bencode:"md5sum,optional"`
	Path   []string `bencode:"path"`
}

func (f File) Name() string {
	return path.Join(f.Path...)
}

type Info struct {
	Files       []File `bencode:"files"`
	Length      int    `bencode:"length"`
	MD5Sum      []byte `bencode:"md5sum,optional"`
	Name        string `bencode:"name"`
	PieceLength int    `bencode:"piece length"`
	Pieces      []byte `bencode:"pieces"`
	Private     bool   `bencode:"private"`
}

func (i Info) TotalLength() int {
	if i.Length > 0 {
		return i.Length
	}
	var l int
	for _, f := range i.Files {
		l += f.Length
	}
	return l
}

func (i Info) GetPieces() []Piece {
	length := i.TotalLength()
	n := length / i.PieceLength
	last := length % i.PieceLength
	if last > 0 {
		n++
	}
	p := make([]Piece, n)
	for k := 0; k < n; k++ {
		p[k].Length = i.PieceLength
		if k+1 == n {
			p[k].Length = length
		}
		off := k * sha1.Size
		copy(p[k].Sum[:], i.Pieces[off:off+sha1.Size])
		p[k].Offset = k * i.PieceLength
	}
	return p
}

func (i Info) FullPath(n int) (string, error) {
	if i.isSingleFile() {
		return i.Name, nil
	}
	if n >= len(i.Files) || n < 0 {
		return "", errors.New("out of range")
	}
	return path.Join(i.Name, i.Files[n].Name()), nil
}

func (i Info) Offset(piece int) int {
	return i.PieceLength * piece
}

func (i Info) FindFile(off int) (int, int) {
	for n, l := range i.Files {
		if l.Length > off {
			return n, off
		}
		off -= l.Length
	}
	return 0, off
}

/*
 *  0    1    2    3    4    5    6    7   #piece
 * |----|----|----|----|----|----|----|--| pieces
 * |-|----|--|----|----------|-|----|----| files
 *  0 1    2  3    4          5 6    7     #file
 */

// FIXME WriteAt ...
func (i Info) WriteAt(b []byte, off int64) (n int, err error) {
	return 0, ErrNotImplemented
}

// FIXME ReadAt ...
func (i Info) ReadAt(b []byte, off int64) (n int, err error) {
	if i.isSingleFile() {
		fd, err := os.OpenFile(i.Name, os.O_RDWR|os.O_CREATE, 0644)
		if err != nil {
			return 0, err
		}
		defer fd.Close()
		return fd.ReadAt(b, int64(i.PieceLength)*off)
	} else {
		n, off := i.FindFile(int(off))
		start := off
		end := i.PieceLength
		for k := n; k < len(i.Files); k++ {
			f := i.Files[n]
			p, err := i.FullPath(k)
			if err != nil {
				return 0, err
			}
			fd, err := os.OpenFile(p, os.O_RDWR|os.O_CREATE, 0644)
			if err != nil {
				return 0, err
			}
			defer fd.Close()
			if end > f.Length {
				end = f.Length
			}
			fd.ReadAt(b[start:end], int64(off))
			start = end
			end = i.PieceLength
			off += f.Length
			if start == end {
				return cap(b), nil
			}
		}
	}
	return 0, ErrNotImplemented
}

func (i Info) isSingleFile() bool {
	return len(i.Files) == 0
}

// Last returns size of last truncated piece
func (i Info) Last() int {
	return i.TotalLength() % i.PieceLength
}

// Full returns count of full pieces
func (i Info) Full() int {
	return i.TotalLength() / i.PieceLength
}

func (i Info) String() string {
	var s string
	for n, f := range i.Files {
		p, err := i.FullPath(n)
		if err != nil {
			panic(err)
		}
		s += fmt.Sprintf("    %s (%d)\n", p, f.Length)
	}
	s += fmt.Sprintf("%s (%d) ", i.Name, i.TotalLength())
	s += fmt.Sprintf("%d × %d + %d\n", i.Full(), i.PieceLength, i.Last())
	return s
}

type Torrent struct {
	Announce     string     `bencode:"announce"`
	AnnounceList [][]string `bencode:"announce-list,optional"`
	Comment      string     `bencode:"comment,optional"`
	CreatedBy    string     `bencode:"created by,optional"`
	CreationDate time.Time  `bencode:"creation date,optional"`
	Encoding     string     `bencode:"encoding,optional"`
	HTTPSeeds    []string   `bencode:"httpseeds,optional"`
	Info         Info       `bencode:"info"`
	URLList      string     `bencode:"url-list,optional"`
	InfoHash     []byte     `bencode:"-"`
}

func (t Torrent) String() string {
	s := fmt.Sprintf("announce: %s\n", t.Announce)
	s += fmt.Sprintf("comment: %s\n", t.Comment)
	s += fmt.Sprintf("date: %s\n", t.CreationDate)
	s += fmt.Sprintf("%v", t.Info)
	s += fmt.Sprintf("info hash: % x", t.InfoHash)
	return s
}