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
|
package main
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"io"
"net"
"os"
)
type HandshakeMessage []byte
type Peer struct {
conn net.Conn
handshake HandshakeMessage
ct *ClientTorrent
msgCh chan *IncomingMessage
}
func (p *Peer) PeerIdHexString() string {
return hex.EncodeToString(p.handshake[48:])
}
func (p *Peer) InfoHash() []byte {
return p.handshake[28:48]
}
func (p *Peer) Close() error {
err := p.conn.Close()
if err != nil {
return errors.Join(fmt.Errorf("failed to close peer connection: %s", p.conn.RemoteAddr()), err)
}
return nil
}
func (p *Peer) DownloadPiece(outFile string, index int) error {
if index >= p.ct.Meta.PieceCount() {
return nil
}
var data = new(bytes.Buffer)
blockLens := p.ct.Meta.BlockLens(index)
var blockIndex = 0
requestFn := func() error {
if blockIndex == len(blockLens) {
return nil
}
r := RequestPayload{
Index: uint32(index),
Begin: uint32(blockIndex * BlockSize),
Length: blockLens[blockIndex],
}
return p.WriteMessage(MessageTypeRequest, r.Bytes())
}
for {
if blockIndex == len(blockLens) {
break
}
msg, err := p.ReadMessage()
if err != nil {
return err
}
switch msg.MessageType {
case MessageTypeBitfield:
if err != nil {
return err
}
err = p.WriteMessage(MessageTypeInterested, nil)
if err != nil {
return err
}
case MessageTypeUnchoke:
if err = requestFn(); err != nil {
return err
}
case MessageTypePiece:
var block BlockPayload
_, err = block.Write(msg.Payload)
if err != nil {
return err
}
_, err = data.Write(block.Block)
if err != nil {
return err
}
blockIndex++
if err = requestFn(); err != nil {
return err
}
default:
return fmt.Errorf("unimplemented message type: %d", msg.MessageType)
}
}
if !p.ct.Meta.CheckHash(index, data.Bytes()) {
return fmt.Errorf("invalid hash value")
}
out, err := os.Create(outFile)
if err != nil {
return errors.Join(fmt.Errorf("failed to create file"), err)
}
_, err = out.Write(data.Bytes())
if err != nil {
return errors.Join(fmt.Errorf("failed to write file"), err)
}
err = out.Close()
if err != nil {
return errors.Join(fmt.Errorf("failed to close file"), err)
}
return nil
}
func (p *Peer) ReadMessage() (*IncomingMessage, error) {
lenBuf := make([]byte, 4)
_, err := p.conn.Read(lenBuf)
if err != nil {
return nil, errors.Join(fmt.Errorf("failed to read message length"), err)
}
msgLen := binary.BigEndian.Uint32(lenBuf) - 1
typeBuf := make([]byte, 1)
_, err = p.conn.Read(typeBuf)
if err != nil {
return nil, errors.Join(fmt.Errorf("failed to read message type"), err)
}
msgType := MessageType(typeBuf[0])
if msgLen == 0 {
return &IncomingMessage{
Len: msgLen,
MessageType: msgType,
}, nil
}
payloadBuf := make([]byte, msgLen)
_, err = io.ReadFull(p.conn, payloadBuf)
if err != nil {
return nil, errors.Join(fmt.Errorf("failed to read message payload"), err)
}
return &IncomingMessage{
Len: msgLen,
MessageType: msgType,
Payload: payloadBuf,
}, nil
}
func (p *Peer) WriteMessage(t MessageType, payload []byte) error {
msg := &OutgoingMessage{
MessageType: t,
Writer: p.conn,
}
_, err := msg.Write(payload)
return err
}
|