-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
391 lines (354 loc) · 9.67 KB
/
main.go
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package main
import (
"bytes"
"encoding/hex"
"flag"
"fmt"
"log"
"os"
"os/signal"
"os/user"
"path/filepath"
"runtime/pprof"
"strings"
"time"
"github.com/rakoo/rakoshare/pkg/id"
"github.com/rakoo/rakoshare/pkg/sharesession"
"github.com/zeebo/bencode"
"github.com/codegangsta/cli"
)
var (
cpuprofile = flag.String("cpuprofile", "", "If not empty, collects CPU profile samples and writes the profile to the given file before the program exits")
memprofile = flag.String("memprofile", "", "If not empty, writes memory heap allocations to the given file before the program exits")
generate = flag.Bool("gen", false, "If true, generate a 3-tuple of ids")
)
var torrent string
func main() {
flag.Parse()
if *cpuprofile != "" {
cpuf, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(cpuf)
defer pprof.StopCPUProfile()
}
if *memprofile != "" {
defer func(file string) {
memf, err := os.Create(file)
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(memf)
}(*memprofile)
}
// Working directory, where all transient stuff happens
u, err := user.Current()
if err != nil {
log.Fatal("Couldn't watch dir: ", err)
}
pathArgs := []string{u.HomeDir, ".local", "share", "rakoshare"}
workDir := filepath.Join(pathArgs...)
app := cli.NewApp()
app.Name = "rakoshare"
app.Usage = "Share content with everyone"
app.Commands = []cli.Command{
{
Name: "gen",
Usage: "Generate a share with a given target directory. Outputs the 3-tuple of id",
Flags: []cli.Flag{
cli.StringFlag{
Name: "dir",
Value: "",
Usage: "The directory to share",
},
},
Action: func(c *cli.Context) {
if c.String("dir") == "" {
fmt.Println("Need a valid directory!")
fmt.Println("Use the -dir flag")
return
}
err := Generate(c.String("dir"), workDir)
if err != nil {
fmt.Println(err)
}
},
},
{
Name: "share",
Usage: "Share the given id",
Flags: []cli.Flag{
cli.StringFlag{
Name: "id",
Value: "",
Usage: "The id to share",
},
cli.StringFlag{
Name: "dir",
Value: "",
Usage: "If not empty, the dir to share",
},
cli.StringSliceFlag{
Name: "tracker",
Value: &cli.StringSlice{},
Usage: "A tracker to connect to",
},
cli.BoolTFlag{
Name: "useLPD",
Usage: "Use Local Peer Discovery",
},
cli.StringSliceFlag{
Name: "peer",
Value: &cli.StringSlice{},
Usage: "A peer to connect to",
},
},
Action: func(c *cli.Context) {
if c.String("id") == "" {
fmt.Println("Need an id!")
return
}
Share(c.String("id"), workDir, c.String("dir"),
c.StringSlice("tracker"), c.Bool("useLPD"),
c.StringSlice("peer"))
},
},
{
Name: "list",
Usage: "List availables shares",
Action: func(c *cli.Context) {
shares := List(workDir)
for _, s := range shares {
fmt.Printf("Sharing %s in %s: \n", s.folder, s.sessionFile)
fmt.Printf("\tWriteReadStore:\t%s\n\t ReadStore:\t%s\n\t Store:\t%s\n",
s.wrs, s.rs, s.s)
fmt.Println()
}
},
},
}
app.Run(os.Args)
}
type share struct {
sessionFile string
folder string
wrs string
rs string
s string
}
func List(workDir string) []share {
dir, err := os.Open(workDir)
if err != nil {
log.Fatal(err)
}
names, err := dir.Readdirnames(-1)
if err != nil {
log.Fatal(err)
}
shares := make([]share, 0, len(names))
for _, n := range names {
if !strings.HasSuffix(n, ".sql") {
continue
}
session, err := sharesession.New(filepath.Join(workDir, n))
if err != nil {
continue
}
id := session.GetShareId()
shares = append(shares, share{
sessionFile: filepath.Join(workDir, n),
folder: session.GetTarget(),
wrs: id.WRS(),
rs: id.RS(),
s: id.S(),
})
}
return shares
}
func Share(cliId string, workDir string, cliTarget string, trackers []string, useLPD bool, manualPeers []string) {
shareID, err := id.NewFromString(cliId)
if err != nil {
fmt.Printf("Couldn't generate shareId: %s\n", err)
return
}
sessionName := hex.EncodeToString(shareID.Infohash) + ".sql"
session, err := sharesession.New(filepath.Join(workDir, sessionName))
if err != nil {
log.Fatal("Couldn't open session file: ", err)
}
fmt.Printf("WriteReadStore:\t%s\n ReadStore:\t%s\n Store:\t%s\n",
shareID.WRS(), shareID.RS(), shareID.S())
target := session.GetTarget()
if target == "" {
if cliTarget == "" {
fmt.Println("Need a folder to share!")
return
}
target = cliTarget
session.SaveSession(target, shareID)
} else if cliTarget != "" {
fmt.Printf("Can't override folder already set to %s\n", target)
}
_, err = os.Stat(target)
if err != nil {
if os.IsNotExist(err) {
os.MkdirAll(target, 0744)
} else {
fmt.Printf("%s is an invalid dir: %s\n", target, err)
os.Exit(1)
}
}
// Watcher
watcher := &Watcher{
PingNewTorrent: make(chan string),
}
if shareID.CanWrite() {
watcher, err = NewWatcher(session, filepath.Clean(target))
if err != nil {
log.Fatal("Couldn't start watcher: ", err)
}
} else {
watcher.PingNewTorrent = make(chan string, 1)
watcher.PingNewTorrent <- session.GetCurrentInfohash()
}
// External listener
conChan, listenPort, err := listenForPeerConnections([]byte(shareID.Psk[:]))
if err != nil {
log.Fatal("Couldn't listen for peers connection: ", err)
}
var currentSession TorrentSessionI = EmptyTorrent{}
// quitChan
quitChan := listenSigInt()
// LPD
lpd := &Announcer{announces: make(chan *Announce)}
if useLPD {
lpd, err = NewAnnouncer(listenPort)
if err != nil {
log.Fatal("Couldn't listen for Local Peer Discoveries: ", err)
}
}
// Control session
controlSession, err := NewControlSession(shareID, listenPort, session, trackers)
if err != nil {
log.Fatal(err)
}
if useLPD {
lpd.Announce(string(shareID.Infohash))
}
for _, peer := range manualPeers {
controlSession.backoffHintNewPeer(peer)
}
peers := session.GetPeers()
for _, p := range peers {
log.Printf("Feeding with known peer: %s\n", p)
controlSession.backoffHintNewPeer(p)
}
log.Println("Starting.")
mainLoop:
for {
select {
case <-quitChan:
err := currentSession.Quit()
if err != nil {
log.Println("Failed: ", err)
} else {
log.Println("Done")
}
break mainLoop
case c := <-conChan:
if currentSession.Matches(c.infohash) {
currentSession.AcceptNewPeer(c)
} else if controlSession.Matches(c.infohash) {
controlSession.AcceptNewPeer(c)
}
case announce := <-lpd.announces:
hexhash, err := hex.DecodeString(announce.infohash)
if err != nil {
log.Println("Err with hex-decoding:", err)
break
}
if controlSession.Matches(string(hexhash)) {
controlSession.backoffHintNewPeer(announce.peer)
}
case ih := <-watcher.PingNewTorrent:
if ih == controlSession.currentIH && !currentSession.IsEmpty() {
break
}
err := controlSession.SetCurrent(ih)
if err != nil {
log.Fatal("Error setting new current infohash:", err)
}
currentSession.Quit()
torrentFile := session.GetCurrentTorrent()
tentativeSession, err := NewTorrentSession(shareID, target, torrentFile, listenPort)
if err != nil {
if !os.IsNotExist(err) {
log.Println("Couldn't start new session from watched dir: ", err)
}
// Fallback to an emptytorrent, because the previous one is
// invalid; hope it will be ok next time !
currentSession = EmptyTorrent{}
break
}
currentSession = tentativeSession
go currentSession.DoTorrent()
for _, peer := range controlSession.peers.All() {
currentSession.hintNewPeer(peer.address)
}
case announce := <-controlSession.Torrents:
if controlSession.currentIH == announce.infohash && !currentSession.IsEmpty() {
break
}
err := controlSession.SetCurrent(announce.infohash)
if err != nil {
log.Fatal("Error setting new current infohash:", err)
}
currentSession.Quit()
log.Println("Opening new torrent session")
magnet := fmt.Sprintf("magnet:?xt=urn:btih:%x", announce.infohash)
tentativeSession, err := NewTorrentSession(shareID, target, magnet, listenPort)
if err != nil {
log.Println("Couldn't start new session from announce: ", err)
currentSession = EmptyTorrent{}
break
}
currentSession = tentativeSession
go currentSession.DoTorrent()
currentSession.hintNewPeer(announce.peer)
case peer := <-controlSession.NewPeers:
if currentSession.IsEmpty() {
magnet := fmt.Sprintf("magnet:?xt=urn:btih:%x", controlSession.currentIH)
tentativeSession, err := NewTorrentSession(shareID, target, magnet, listenPort)
if err != nil {
log.Printf("Couldn't start new session with new peer: %s\n", err)
break
}
currentSession = tentativeSession
go currentSession.DoTorrent()
}
currentSession.hintNewPeer(peer)
case meta := <-currentSession.NewMetaInfo():
var buf bytes.Buffer
err := bencode.NewEncoder(&buf).Encode(meta)
if err != nil {
log.Println(err)
break
}
session.SaveTorrent(buf.Bytes(), meta.InfoHash, time.Now().Format(time.RFC3339))
}
}
}
type EmptyTorrent struct{}
func (et EmptyTorrent) Quit() error { return nil }
func (et EmptyTorrent) Matches(ih string) bool { return false }
func (et EmptyTorrent) AcceptNewPeer(btc *btConn) {}
func (et EmptyTorrent) DoTorrent() {}
func (et EmptyTorrent) hintNewPeer(peer string) bool { return true }
func (et EmptyTorrent) IsEmpty() bool { return true }
func (et EmptyTorrent) NewMetaInfo() chan *MetaInfo { return nil }
func listenSigInt() chan os.Signal {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, os.Kill)
return c
}