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

import (
	"encoding/json"
	"fmt"
	"os"
	"strconv"
	"strings"

	bencode "github.com/jackpal/bencode-go" // Available if you need it!
)

func createClient(fn string) *Client {
	c := NewClient("00112233445566778899", 6881)

	if err := c.AddTorrentFile(fn); err != nil {
		panic(err)
	}

	return c
}

func main() {
	command := os.Args[1]

	switch command {
	case "decode":
		bencodedValue := os.Args[2]
		decoded, err := bencode.Decode(strings.NewReader(bencodedValue))
		if err != nil {
			fmt.Println(err)
			return
		}

		jsonOutput, _ := json.Marshal(decoded)
		fmt.Println(string(jsonOutput))

	case "info":
		fn := os.Args[2]
		c := createClient(fn)
		meta := c.Torrents[fn].Meta
		fmt.Printf("Tracker URL: %s\n", meta.Announce)
		fmt.Printf("Length: %d\n", meta.Info.Length)

		infoHash, err := meta.InfoHash()
		if err != nil {
			panic(err)
		}

		fmt.Printf("Info Hash: %x", infoHash)

		fmt.Printf("Piece Length: %d\n", meta.Info.PieceLength)
		fmt.Println("Piece Hashes:")

		for _, h := range meta.PieceHashes() {
			fmt.Printf("%x\n", h)
		}

	case "peers":
		fn := os.Args[2]
		c := createClient(fn)

		pr, err := c.GetPeers(fn)
		if err != nil {
			panic(err)
		}

		for _, peer := range pr.Peers {
			fmt.Println(peer)
		}

	case "handshake":
		fn := os.Args[2]
		c := createClient(fn)
		peerAddr := os.Args[3]

		peer, err := c.Handshake(fn, peerAddr)
		if err != nil {
			panic(err)
		}

		fmt.Printf("Peer ID: %s\n", peer.PeerIdHexString())

	case "download_piece":
		out := os.Args[3]
		fn := os.Args[4]

		index, err := strconv.Atoi(os.Args[5])
		if err != nil {
			panic(err)
		}

		c := createClient(fn)
		pr, err := c.GetPeers(fn)
		if err != nil {
			panic(err)
		}

		var peer *Peer

		for _, peerAddr := range pr.Peers {
			peer, err = c.Handshake(fn, peerAddr)
			if err != nil {
				continue
			}
		}

		if peer == nil {
			panic(fmt.Errorf("no peers found for file: %s", out))
		}

		defer peer.Close()

		err = peer.DownloadPiece(out, index)
		if err != nil {
			panic(err)
		}

		fmt.Printf("Piece %d downloaded to %s.", index, out)

	default:
		fmt.Println("Unknown command: " + command)
		os.Exit(1)
	}
}