aboutsummaryrefslogtreecommitdiff
path: root/cmd/mybittorrent/message.go
blob: 9439bd5fe9145ae3ccef659999a480513981307a (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
package main

import (
	"encoding/binary"
	"io"
)

type MessageType byte

type BlockPayload struct {
	Index uint32
	Begin uint32
	Block []byte
}

type IncomingMessage struct {
	Len         uint32
	MessageType MessageType
	Payload     []byte
}

type OutgoingMessage struct {
	MessageType MessageType
	Writer      io.Writer
}

type RequestPayload struct {
	Index  uint32
	Begin  uint32
	Length uint32
}

const (
	MessageTypeChoke MessageType = iota
	MessageTypeUnchoke
	MessageTypeInterested
	MessageTypeNotInterested
	MessageTypeHave
	MessageTypeBitfield
	MessageTypeRequest
	MessageTypePiece
	MessageTypeCancel
)

func (o *OutgoingMessage) Write(b []byte) (int, error) {
	msgLen := 1 + len(b)
	payloadBuff := make([]byte, msgLen+4)
	binary.BigEndian.PutUint32(payloadBuff[0:4], uint32(msgLen))
	payloadBuff[4] = byte(o.MessageType)

	if msgLen > 1 {
		copy(payloadBuff[5:], b)
	}

	return o.Writer.Write(payloadBuff)
}

func (r RequestPayload) Bytes() []byte {
	buf := make([]byte, 12)
	binary.BigEndian.PutUint32(buf[0:4], r.Index)
	binary.BigEndian.PutUint32(buf[4:8], r.Begin)
	binary.BigEndian.PutUint32(buf[8:12], r.Length)
	return buf
}

func (p *BlockPayload) Write(b []byte) (int, error) {
	p.Index = binary.BigEndian.Uint32(b[0:4])
	p.Begin = binary.BigEndian.Uint32(b[4:8])
	p.Block = b[8:]
	return len(b), nil
}

func (p *BlockPayload) WriteTo(w io.Writer) (int64, error) {
	n, err := w.Write(p.Block)
	return int64(n), err
}