Repository navigation
Expand file tree
/
Copy pathbittorrent.go
More file actions
763 lines (652 loc) · 20.8 KB
/
Copy pathbittorrent.go
File metadata and controls
763 lines (652 loc) · 20.8 KB
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
// Scalability
//
// TODO. We avoid polling that is O(torrents) by using events. E.g. instead of inspecting each torrent for its state or statistics, we'll emit events only for those torrents that had activity.
//
// Callbacks, events, and blocking calls
//
// We use three different mechanisms for communicating with users of this package.
//
// Callbacks
//
// Callbacks are used when we need to request data from the user.
// For example, in order to implement peer whitelists or blacklists, we'll ask the user to make a decision whenever a new incoming connection is made.
//
// Callbacks are executed synchronously as we cannot proceed until we get their results.
// In some cases, this means that callbacks should finish as quickly as possible, so that good performance can be maintained.
// In other cases, deliberate delays can be used to implement rate control, for example to throttle the rate of incoming connections.
//
// Events
//
// Events are used when we need to send data to the user but don't require a response.
// For example, periodic per-peer traffic statistics are reported as events.
// Events have to be polled periodically by the user.
// Not doing so will cause events to accumulate and grow memory usage without bounds.
//
// Some events may overlap with callbacks.
// For example, there is both a callback and an event for new peer connections.
// While callbacks can make decisions and block execution, events can do neither.
//
// Blocking calls
//
// Requests and actions originating from the user are handled by blocking calls.
// For example, verifying a torrent's data is done via a function call that will not return until verification has completed.
// If the user wishes to run actions in parallel with their other code, they have to set up concurrency themselves, by using goroutines.
package bittorrent
// XXX look at all integer types and decide on their width
// XXX support removing torrents
// XXX handle clients that don't support the Fast extension; don't send them messages they won't understand
// TODO learn about socket options, send/receive buffers, corking, …
// TODO corking and/or nagle might make sense. blocks are obviously
// too large to benefit from it, but HAVE messages are small enough to
// be batched together. should we relegate this caching to the kernel,
// or should we cache in user space instead?
// TODO can we write to sockets without having to copy data from user space to kernel space?
// XXX handle read/write timeouts, both on disk i/o and network i/o
// XXX set user agent for HTTP requests
import (
"bytes"
"crypto/sha1"
"fmt"
"io"
"log"
"math/big"
"math/bits"
"math/rand"
"os"
"sort"
"sync"
"time"
"honnef.co/go/bittorrent/channel"
"honnef.co/go/bittorrent/mymath"
"honnef.co/go/bittorrent/oursync"
"honnef.co/go/bittorrent/protocol"
)
type lockedRand struct {
mu sync.Mutex
rng *rand.Rand
}
func (rng *lockedRand) Intn(n int) int {
rng.mu.Lock()
defer rng.mu.Unlock()
return rng.rng.Intn(n)
}
// The maximum number of peers per torrent the code supports.
const maxPeersPerTorrent = 65535
// How often each peer updates the global and per-torrent traffic statistics.
const peerStatisticsInterval = 500 * time.Millisecond
func verifyBlock(data []byte, checksum []byte) bool {
h := sha1.Sum(data)
return bytes.Equal(h[:], checksum)
}
type trackerSession struct {
PeerID [20]byte
nextAnnounce time.Time
up oursync.Uint64
down oursync.Uint64
}
type Announce struct {
InfoHash protocol.InfoHash
Tracker string
PeerID [20]byte
Event string
Up uint64
Down uint64
// XXX left
Created time.Time
Fails []struct {
When time.Time
Err error
}
NextTry time.Time
}
type Bitset struct {
count oursync.Uint32
// OPT: don't use big.Int. use our own representation that matches
// the wire protocol, so that we don't have to convert between the
// two all the time
bits big.Int
}
func (set Bitset) Copy() Bitset {
nset := Bitset{
count: set.count,
}
nset.bits.Set(&set.bits)
return nset
}
func (set Bitset) Get(bit uint32) bool {
return set.bits.Bit(int(bit)) == 1
}
func (set *Bitset) Set(bit uint32) {
if set.bits.Bit(int(bit)) == 1 {
return
}
set.count.Add(1)
set.bits.SetBit(&set.bits, int(bit), 1)
}
func (set *Bitset) Unset(bit uint32) {
if set.bits.Bit(int(bit)) == 0 {
return
}
set.count.Add(^uint32(0))
set.bits.SetBit(&set.bits, int(bit), 0)
}
// SetBitfield populates set from a bittorrent bitfield.
// The first byte of the bitfield corresponds to indices 0 - 7 from high bit to low bit, respectively. The next one 8-15, etc.
func (set *Bitset) SetBitfield(buf []byte) {
// OPT optimize this, probably by writing our own bitset type instead of using big.Int.
// Note that we cannot use big.Int.SetBytes, because the byte layout doesn't match that of the bitfield.
bit := 0
for _, b := range buf {
for n := 7; n >= 0; n-- {
bit++
if b&1<<n != 0 {
set.count.Add(1)
set.bits.SetBit(&set.bits, bit, 1)
} else {
set.bits.SetBit(&set.bits, bit, 0)
}
}
}
}
func (set Bitset) Intersect(other Bitset) Bitset {
out := Bitset{}
if set.count.Load() == 0 || other.count.Load() == 0 {
return out
}
out.bits.And(&set.bits, &other.bits)
// OPT: we'll call Intersect a lot, and Bytes allocates, so this is no good.
// We could use FillBytes, but the loop is still O(n).
for _, b := range out.bits.Bytes() {
out.count.Add(uint32(bits.OnesCount8(b)))
}
return out
}
func (set *Bitset) String() string {
return fmt.Sprintf("%d bits set", set.Count())
}
func (set *Bitset) Count() int { return int(set.count.Load()) }
// OPT track HaveAll separately
// OPT don't spread requests for the same piece among many peers, it
// wastes their disk caches. "The logic in libtorrent switches into
// the request-whole-pieces mode when a peer sends blocks fast enough
// to send an entire piece in 30 seconds."
//
// At an 8 MB piece piece, 30 seconds means 267 kB/s. We might be able
// to always default to requesting entire pieces, based on modern
// internet speeds. However, 8 MB pieces have 500 blocks, so we can't
// truly request them all at once without risking overflowing the
// peer's request queue.
// OPT: this data structure is fine for keeping a priority-sorted list
// of pieces, but finding a peer-piece combination requires looping
// over each piece and checking with the peer until we find one. IOW,
// it's O(n) worst case.
//
// TODO: prioritize pieces we've already downloading
type Pieces struct {
// mapping from piece to entry in sorted_pieces
pieceIndices []uint32
// pieces sorted by availability, in ascending order, indexed into by piece_indices
sortedPieces []uint32
// mapping from piece to availability
availabilities []uint16 // supports at most 65536 peers
// mapping from priority to one past the last item in sorted_pieces that is part of that priority
buckets []uint32
// Mapping from piece to requested or downloaded blocks. This map
// only contains entries for partially downloaded pieces.
requestedBlocks map[uint32]*Bitset
// Mapping from piece to downloaded blocks. This map only contains
// entries for partially downloaded pieces.
downloadedBlocks map[uint32]*Bitset
// Pieces we have. These have been hashed and written to disk.
have Bitset
// The size of a single piece, in blocks
blocksPerNormalPiece int
// The index of the final piece
lastPieceIndex int
// The index of the final block
lastBlockIndex int
// The size of the final piece, in blocks
blocksPerLastPiece int
// The size of the final block, in bytes
bytesPerLastBlock int
bytesPerLastPiece int
bytesPerNormalPiece int
}
func NewPieces(torr *Torrent) Pieces {
pieceSize := torr.Metainfo.Info.PieceLength
lastPieceBytes := torr.NumBytes() - ((int64(torr.NumPieces()) - 1) * pieceSize)
lastPieceBlocks := mymath.DivUp(lastPieceBytes, protocol.MaxBlockSize)
lastBlockBytes := lastPieceBytes - (lastPieceBlocks-1)*protocol.MaxBlockSize
n := uint32(torr.NumPieces())
out := Pieces{
pieceIndices: make([]uint32, n),
sortedPieces: make([]uint32, n),
availabilities: make([]uint16, n),
buckets: []uint32{n},
requestedBlocks: map[uint32]*Bitset{},
downloadedBlocks: map[uint32]*Bitset{},
blocksPerNormalPiece: mymath.DivUp(int(pieceSize), protocol.MaxBlockSize),
lastPieceIndex: torr.NumPieces() - 1,
lastBlockIndex: int(lastPieceBlocks - 1),
blocksPerLastPiece: int(lastPieceBlocks),
bytesPerLastBlock: int(lastBlockBytes),
bytesPerLastPiece: int(lastPieceBytes),
bytesPerNormalPiece: int(pieceSize),
}
for i := uint32(0); i < n; i++ {
out.pieceIndices[i] = i
out.sortedPieces[i] = i
}
return out
}
type Block struct {
Piece uint32
Block uint32
}
func (t *Pieces) RequestToBlock(req Request) Block {
if req.Begin%protocol.MaxBlockSize != 0 {
panic(fmt.Sprintf("request %v isn't block-aligned", req))
}
return Block{
Piece: req.Piece,
Block: req.Begin / protocol.MaxBlockSize,
}
}
func (t *Pieces) BlockToRequest(b Block) Request {
return Request{
Piece: b.Piece,
Begin: b.Block * protocol.MaxBlockSize,
Length: uint32(t.BytesInBlock(b)),
}
}
func (t *Pieces) BytesInBlock(b Block) int {
if b.Piece == uint32(t.lastPieceIndex) && b.Block == uint32(t.lastBlockIndex) {
return t.bytesPerLastBlock
} else {
return protocol.MaxBlockSize
}
}
func (t *Pieces) BytesInPiece(piece uint32) int {
if piece == uint32(t.lastPieceIndex) {
return t.bytesPerLastPiece
} else {
return t.bytesPerNormalPiece
}
}
func (t *Pieces) BlocksInPiece(piece uint32) int {
if piece == uint32(t.lastPieceIndex) {
return t.blocksPerLastPiece
} else {
return t.blocksPerNormalPiece
}
}
// Half-open interval [start, end) of blocks to request for piece.
//
// TODO(dh): give this type a better name
type blockRange struct {
piece uint32
start, end int
}
// HavePiece records that we have a piece.
func (t *Pieces) HavePiece(piece uint32) {
t.have.Set(piece)
delete(t.requestedBlocks, piece)
delete(t.downloadedBlocks, piece)
}
// NeedPiece records that we need a piece. This needs to be called if a downloaded piece failed verification, so that we request it again.
// This shouldn't be used on a piece that has already been marked as completed by Have.
func (t *Pieces) NeedPiece(piece uint32) {
// TODO(dh): record which peers we got the piece from, try to find out which peer is to blame
delete(t.requestedBlocks, piece)
delete(t.downloadedBlocks, piece)
}
func (t *Pieces) NeedBlock(b Block) {
req, ok := t.requestedBlocks[b.Piece]
if !ok {
panic(fmt.Sprintf("called NeedBlock(%v), but piece %d doesn't have any currently requested blocks", b, b.Piece))
}
if req.bits.Bit(int(b.Block)) == 0 {
panic(fmt.Sprintf("called NeedBlock(%v), but block %d wasn't requested", b, b.Block))
}
req.Unset(b.Block)
}
func (t *Pieces) HaveBlock(piece uint32, block uint32) (complete bool) {
req, ok := t.downloadedBlocks[piece]
if !ok {
req = new(Bitset)
t.downloadedBlocks[piece] = req
}
req.Set(block)
return int(req.count.Load()) == t.BlocksInPiece(piece)
}
// TODO(dh): this API cannot support end-game mode
func (t *Pieces) Pick(peer *Peer, numBlocks int) (ranges []blockRange, ok bool) {
// Based on commonly used piece sizes, large torrents have between
// 4096 and 24320 pieces. However, every once in a while, someone
// uses the default piece size of 128 KiB even for very large
// torrents, leading to hundreds of thousands of pieces. The
// current implementation of the piece picker is technically
// O(pieces) for picking a single piece, and O(pieces²) for
// pic
8000
king all pieces. However, in practice, only a small fraction
// of all pieces get looked at.
if !peer.AmInterested() {
panic(fmt.Sprintf("trying to pick piece for peer %s we're not interested in", peer))
}
if peer.have.count.Load() == 0 {
panic(fmt.Sprintf("interested in peer %s with no pieces", peer))
}
if t.availabilities[t.sortedPieces[len(t.sortedPieces)-1]] == 0 {
panic(fmt.Sprintf("peer %s has pieces but we think nobody has any pieces", peer))
}
// OPT(dh): when the peer has much fewer pieces than the rest of
// the swarm, then it should be faster to loop over the peer's
// pieces and return the one with the highest priority. It's the
// same O(pieces) because we have to look at each piece to know if
// the peer has it, but since that's stored in a bitmap we can
// check 64 pieces at a time.
blocksForPiece := func(piece uint32, max int) (ranges []blockRange, n int) {
if max > t.BlocksInPiece(piece) {
max = t.BlocksInPiece(piece)
}
reqBlocks, ok := t.requestedBlocks[piece]
if !ok {
reqBlocks = new(Bitset)
t.requestedBlocks[piece] = reqBlocks
}
if reqBlocks.count.Load() == 0 {
// We haven't requested any blocks of this piece, so we can request from 0 to max
ranges = append(ranges, blockRange{piece: piece, start: 0, end: max})
} else if int(reqBlocks.count.Load()) == t.BlocksInPiece(piece) {
// We have already requested all blocks in this piece
} else {
// Find contiguous ranges of blocks to request
start := -1
for bit := 0; bit < t.BlocksInPiece(piece); bit++ {
if max < 0 {
panic("max became negative")
}
if max == 0 {
break
}
if reqBlocks.Get(uint32(bit)) {
if start != -1 {
// End range
ranges = append(ranges, blockRange{piece: piece, start: start, end: bit})
max -= bit - start
start = -1
}
} else {
if start == -1 {
// Start range
start = bit
} else if bit-start == max {
// End range early, we've gotten enough blocks
ranges = append(ranges, blockRange{piece: piece, start: start, end: bit})
start = -1
max = 0
break
}
}
}
if start != -1 {
// We ran out of blocks, end range
ranges = append(ranges, blockRange{piece: piece, start: start, end: t.BlocksInPiece(piece)})
max -= t.BlocksInPiece(piece) - start
}
}
n = 0
for _, r := range ranges {
n += r.end - r.start
for bit := r.start; bit < r.end; bit++ {
// OPT surely there's a better way than setting each bit individually
reqBlocks.Set(uint32(bit))
}
}
if len(ranges) > 0 && n == 0 {
panic("have ranges but n == 0")
}
return ranges, n
}
// XXX prefer partial pieces
for _, piece := range t.sortedPieces {
if numBlocks < 0 {
panic("numBlocks became negative")
}
if numBlocks == 0 {
break
}
// TODO(dh): can we ever reach a piece with zero availability?
// I don't think so; we only request from peers that we're
// interested in, and we shouldn't be interested in peers that
// have no pieces we don't also have.
// OPT(dh): can we deprioritize pieces that we already have,
// by giving them the smallest priority possible? That way
// we'll have to iterate over much fewer total pieces. Or can
// we just remove them altogether?
if t.have.Get(piece) {
// Don't pick a piece we already have
continue
}
if !peer.have.Get(piece) {
// Don't pick a piece the peer doesn't have
continue
}
pranges, n := blocksForPiece(piece, numBlocks)
ranges = append(ranges, pranges...)
numBlocks -= n
}
return ranges, len(ranges) != 0
}
func (t *Pieces) incAvailability(piece uint32) {
avail := t.availabilities[piece]
t.buckets[avail]--
t.availabilities[piece]++
index := t.pieceIndices[piece]
other_index := t.buckets[avail]
other_piece := t.sortedPieces[other_index]
t.sortedPieces[other_index], t.sortedPieces[index] = t.sortedPieces[index], t.sortedPieces[other_index]
t.pieceIndices[other_piece], t.pieceIndices[piece] = t.pieceIndices[piece], t.pieceIndices[other_piece]
if uint32(avail+1) >= uint32(len(t.buckets)) {
t.buckets = append(t.buckets, other_index+1)
}
}
func (t *Pieces) decAvailability(piece uint32) {
log.Println("dec", piece)
t.availabilities[piece]--
avail := t.availabilities[piece]
index := t.pieceIndices[piece]
other_index := t.buckets[avail]
other_piece := t.sortedPieces[other_index]
t.buckets[avail]++
log.Println(other_index)
t.sortedPieces[other_index], t.sortedPieces[index] = t.sortedPieces[index], t.sortedPieces[other_index]
t.pieceIndices[other_piece], t.pieceIndices[piece] = t.pieceIndices[piece], t.pieceIndices[other_piece]
}
type Action interface {
Run() (result interface{}, stopped bool, err error)
Pause()
Stop()
}
type BaseAction struct {
Torrent *Torrent
PauseCh chan struct{}
StopCh chan struct{}
UnpauseCh chan struct{}
}
func (l *BaseAction) Pause() { channel.TrySend(l.PauseCh, struct{}{}) }
func (l *BaseAction) Unpause() { channel.TrySend(l.UnpauseCh, struct{}{}) }
func (l *BaseAction) Stop() { channel.TrySend(l.StopCh, struct{}{}) }
type Verify struct {
BaseAction
}
func (l *Verify) Run() (result interface{}, stopped bool, err error) {
log.Println("started verifying", l.Torrent)
defer func() {
if stopped {
log.Println("stopped verifying", l.Torrent)
} else {
log.Println("finished verifying", l.Torrent)
}
}()
// OPT use more than one goroutine to verify in parallel; we get about 1 GB/s on one core
pieceSize := l.Torrent.Metainfo.Info.PieceLength
numPieces := l.Torrent.NumPieces()
res := Bitset{}
// OPT use a normal MultiReader to avoid the unnecessary cost of
// mapping from piece to file. We just want to read everything
// sequentially.
buf := make([]byte, pieceSize)
piece := uint32(0)
for {
select {
case <-l.PauseCh:
<-l.UnpauseCh
case <-l.StopCh:
return res, true, nil
default:
}
n, err := l.Torrent.Data.ReadAt(buf, int64(piece)*int64(pieceSize))
if err != nil {
if err == io.ErrUnexpectedEOF {
if piece+1 != uint32(numPieces) {
break
} else {
buf = buf[:n]
}
} else if err == io.EOF {
break
} else {
// XXX report the error
return res, false, err
}
}
off := piece * 20
if verifyBlock(buf, l.Torrent.Metainfo.Info.Pieces[off:off+20]) {
res.Set(piece)
}
piece++
}
return res, false, nil
}
func NewVerify(torr *Torrent) Action {
return &Verify{
BaseAction: BaseAction{
Torrent: torr,
PauseCh: make(chan struct{}, 1),
StopCh: make(chan struct{}, 1),
UnpauseCh: make(chan struct{}, 1),
},
}
}
// TODO(dh): add necessary interfaces so that we don't depend on the file system. something that can open paths and return io.ReaderAts.
// OPT cache open files
type DataStorage struct {
Files []DataStorageFile
Length int64
}
type DataStorageFile struct {
Path string
Offset int64
Size int64
}
func (ds *DataStorage) add(path string, length int64) {
ds.Files = append(ds.Files, DataStorageFile{path, ds.Length, length})
ds.Length += length
}
func (ds *DataStorage) relevantFiles(n int, off int64) []DataStorageFile {
// Skip past the requested offset.
skipFiles := sort.Search(len(ds.Files), func(i int) bool {
// This function returns whether Files[i] will
// contribute any bytes to our output.
8FDB
file := ds.Files[i]
return file.Offset+file.Size > off
})
return ds.Files[skipFiles:]
}
func (ds *DataStorage) ReadAt(p []byte, off int64) (int, error) {
wantN := len(p)
files := ds.relevantFiles(len(p), off)
// How far to skip in the first file.
needSkip := off
if len(files) > 0 {
needSkip -= files[0].Offset
}
n := 0
for len(files) > 0 && len(p) > 0 {
readP := p
fileSize := files[0].Size
if int64(len(readP)) > fileSize-needSkip {
readP = readP[:fileSize-needSkip]
}
f, err := os.Open(files[0].Path)
if err == nil {
rn, err := f.ReadAt(readP, needSkip)
f.Close()
if err != nil {
if err == io.EOF {
// file is shorter than it should be. pad with zeroes
for i := range readP[rn:] {
readP[i+rn] = 0
}
} else {
return n, err
}
}
} else {
// if the file is missing we pad with zeros
for i := range readP {
readP[i] = 0
}
}
// The return value of ReadAt doesn't matter. Either it read exactly len(readP) bytes, or it returned a non-nil error and we padded with zeroes.
pn := len(readP)
n += pn
p = p[pn:]
if int64(pn)+needSkip == fileSize {
files = files[1:]
}
needSkip = 0
}
if n != wantN {
return n, io.ErrUnexpectedEOF
}
return n, nil
}
func (ds *DataStorage) WriteAt(p []byte, off int64) (int, error) {
files := ds.relevantFiles(len(p), off)
// How far to skip in the first file.
needSkip := off
if len(files) > 0 {
needSkip -= files[0].Offset
}
n := 0
for len(files) > 0 && len(p) > 0 {
writeP := p
fileSize := files[0].Size
if int64(len(writeP)) > fileSize-needSkip {
writeP = writeP[:fileSize-needSkip]
}
// OPT(dh): support preallocating files
f, err := os.OpenFile(files[0].Path, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return n, err
}
rn, err := f.WriteAt(writeP, needSkip)
n += rn
f.Close()
if err != nil {
return n, err
}
pn := len(writeP)
p = p[pn:]
if int64(pn)+needSkip == fileSize {
files = files[1:]
}
needSkip = 0
}
return n, nil
}
// OPT(dh): replace (*big.Int).AndNot with function that returns true or false
// XXX switch torrent into seeding state once we've downloaded the last piece
// XXX time out block requests
// XXX kill stalled peers