forked from bizzehdee/bzTorrent
/
PeerWireClient.cs
689 lines (545 loc) · 20.4 KB
/
PeerWireClient.cs
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
/*
Copyright (c) 2013, Darren Horrocks
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of Darren Horrocks nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
using System.Net.Torrent.IO;
using System.Net.Torrent.Misc;
using System.Text;
using System.Threading;
namespace System.Net.Torrent
{
public class PeerWireClient : IPeerWireClient
{
private readonly Object _locker = new Object();
private bool _asyncContinue = true;
private readonly byte[] _bitTorrentProtocolHeader = { 0x42, 0x69, 0x74, 0x54, 0x6F, 0x72, 0x72, 0x65, 0x6E, 0x74, 0x20, 0x70, 0x72, 0x6F, 0x74, 0x6F, 0x63, 0x6F, 0x6C };
internal readonly IWireIO Socket;
private byte[] _internalBuffer; //async internal buffer
private readonly List<IProtocolExtension> _btProtocolExtensions;
private bool _handshakeSent;
private bool _handshakeComplete;
private bool _receiving;
private IAsyncResult _async;
private const int MinBufferSize = 1024;
private const int MaxBufferSize = 1024 * 256;
private int _dynamicBufferSize = 1024*16;
public Int32 Timeout { get { return Socket.Timeout; } }
public bool[] PeerBitField { get; set; }
public bool KeepConnectionAlive { get; set; }
public bool RemoteUsesDHT { get; private set; }
public string LocalPeerID { get; set; }
public string RemotePeerID { get; private set; }
public string Hash { get; set; }
public event Action<IPeerWireClient> DroppedConnection;
public event Action<IPeerWireClient> NoData;
public event Action<IPeerWireClient> HandshakeComplete;
public event Action<IPeerWireClient> KeepAlive;
public event Action<IPeerWireClient> Choke;
public event Action<IPeerWireClient> UnChoke;
public event Action<IPeerWireClient> Interested;
public event Action<IPeerWireClient> NotInterested;
public event Action<IPeerWireClient, Int32> Have;
public event Action<IPeerWireClient, Int32, bool[]> BitField;
public event Action<IPeerWireClient, Int32, Int32, Int32> Request;
public event Action<IPeerWireClient, Int32, Int32, byte[]> Piece;
public event Action<IPeerWireClient, Int32, Int32, Int32> Cancel;
public PeerWireClient(IWireIO io)
{
Socket = io;
_btProtocolExtensions = new List<IProtocolExtension>();
_internalBuffer = new byte[0];
}
public void Connect(IPEndPoint endPoint)
{
Socket.Connect(endPoint);
}
public void Connect(string ipHost, Int32 port)
{
Socket.Connect(new IPEndPoint(IPAddress.Parse(ipHost), port));
}
public void Disconnect()
{
if(_async != null)
{
Socket.EndReceive(_async);
}
Socket.Disconnect();
}
public bool Handshake()
{
return Handshake(Pack.Hex(Hash), Encoding.ASCII.GetBytes(LocalPeerID));
}
public bool Handshake(string hash, string peerId)
{
LocalPeerID = peerId;
Hash = hash;
return Handshake();
}
public bool Handshake(byte[] hash, byte[] peerId)
{
if (hash == null) throw new ArgumentNullException(nameof(hash), "Hash cannot be null");
if (peerId == null) throw new ArgumentNullException(nameof(peerId), "Peer ID cannot be null");
if (hash.Length != 20) throw new ArgumentOutOfRangeException(nameof(hash), "hash must be 20 bytes exactly");
if (peerId.Length != 20) throw new ArgumentOutOfRangeException(nameof(peerId), "Peer ID must be 20 bytes exactly");
byte[] reservedBytes = {0, 0, 0, 0, 0, 0, 0, 0};
foreach (var extension in _btProtocolExtensions)
{
for (var x = 0; x < 8; x++)
{
reservedBytes[x] |= extension.ByteMask[x];
}
}
var sendBuf = (new[] { (byte)_bitTorrentProtocolHeader.Length }).Cat(_bitTorrentProtocolHeader).Cat(reservedBytes).Cat(hash).Cat(peerId);
try
{
var len = Socket.Send(sendBuf);
if (len != sendBuf.Length)
{
throw new Exception("Didnt sent entire handshake");
}
}
catch (SocketException ex)
{
Trace.TraceInformation(ex.Message);
return false;
}
foreach (IProtocolExtension extension in _btProtocolExtensions)
{
extension.OnHandshake(this);
}
_handshakeSent = true;
return true;
}
public void ProcessAsync()
{
_asyncContinue = true;
(new Thread(o =>
{
var client = (PeerWireClient) o;
while (client.Process() && _asyncContinue)
{
Thread.Sleep(10);
}
})).Start(this);
}
public void StopProcessAsync()
{
_asyncContinue = false;
}
public bool Process()
{
var returnVal = _process();
if (returnVal) return true;
if (Socket.Connected)
{
Socket.Disconnect();
}
DroppedConnection?.Invoke(this);
return false;
}
private bool _process()
{
if (!_receiving)
{
var recBuffer = new byte[_dynamicBufferSize];
try
{
_async = Socket.BeginReceive(recBuffer, 0, _dynamicBufferSize, OnReceived, recBuffer);
}
catch(Exception ex)
{
Trace.TraceInformation(ex.Message);
return false;
}
_receiving = true;
}
if (_internalBuffer.Length < 4)
{
OnNoData();
return Socket.Connected;
}
if (!_handshakeComplete)
{
Int32 resLen = _internalBuffer[0];
if (resLen != 19)
{
if (resLen == 0)
{
// keep alive?
Thread.Sleep(100);
Disconnect();
return false;
}
}
_handshakeComplete = true;
var recReserved = _internalBuffer.GetBytes(20, 8);
RemoteUsesDHT = (recReserved[7] & 0x1) == 0x1;
var remoteHashBytes = _internalBuffer.GetBytes(28, 20);
if (string.IsNullOrEmpty(Hash))
{
var remoteHash = Unpack.Hex(remoteHashBytes);
Hash = remoteHash;
}
var remoteIdbytes = _internalBuffer.GetBytes(48, 20);
RemotePeerID = Encoding.ASCII.GetString(remoteIdbytes);
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(68);
}
OnHandshake();
if (_handshakeSent) return true;
Handshake();
SendBitField(PeerBitField);
return true;
}
var commandLength = Unpack.Int32(_internalBuffer, 0, Unpack.Endianness.Big);
if (commandLength > (_internalBuffer.Length - 4))
{
//need more data first
return true;
}
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(4);
}
if (commandLength == 0)
{
if (!KeepConnectionAlive) return true;
SendKeepAlive();
OnKeepAlive();
return true;
}
Int32 commandId = _internalBuffer[0];
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(1);
}
switch (commandId)
{
case 0:
//choke
OnChoke();
break;
case 1:
//unchoke
OnUnChoke();
break;
case 2:
//interested
OnInterested();
break;
case 3:
//not interested
OnNotInterested();
break;
case 4:
//have
ProcessHave();
break;
case 5:
//bitfield
ProcessBitfield(commandLength - 1);
break;
case 6:
//request
ProcessRequest(false);
break;
case 7:
//piece
ProcessPiece(commandLength - 1);
break;
case 8:
//cancel
ProcessRequest(true);
break;
default:
{
foreach (var extension in _btProtocolExtensions)
{
if (!extension.CommandIDs.Contains(b => b == commandId))
{
continue;
}
if (extension.OnCommand(this, commandLength, (byte)commandId, _internalBuffer))
{
break;
}
}
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(commandLength - 1);
}
}
break;
}
return true;
}
private void OnReceived(IAsyncResult ar)
{
if (Socket == null) return;
var data = (byte[])ar.AsyncState;
var len = Socket.EndReceive(ar);
_async = null;
lock (_locker)
{
_internalBuffer = _internalBuffer == null ? data : _internalBuffer.Cat(data.GetBytes(0, len));
}
#region Automatically alter the buffer size
if (_internalBuffer.Length > _dynamicBufferSize && (_dynamicBufferSize - 1024) >= MinBufferSize)
{
_dynamicBufferSize -= 1024;
}
if (_internalBuffer.Length < _dynamicBufferSize && (_dynamicBufferSize + 1024) <= MaxBufferSize)
{
_dynamicBufferSize += 1024;
}
_receiving = false;
#endregion
}
public bool SendKeepAlive()
{
var sent = Socket.Send(Pack.Int32(0));
return sent == 4;
}
public bool SendChoke()
{
var sent = Socket.Send(new PeerMessageBuilder(0).Message());
return sent == 5;
}
public bool SendUnChoke()
{
var sent = Socket.Send(new PeerMessageBuilder(1).Message());
return sent == 5;
}
public bool SendInterested()
{
var sent = Socket.Send(new PeerMessageBuilder(2).Message());
return sent == 5;
}
public bool SendNotInterested()
{
var sent = Socket.Send(new PeerMessageBuilder(3).Message());
return sent == 5;
}
public bool SendHave(UInt32 index)
{
var sent = Socket.Send(new PeerMessageBuilder(4).Add(index).Message());
return sent == 9;
}
public void SendBitField(bool[] bitField)
{
SendBitField(bitField, false);
}
public bool SendBitField(bool[] bitField, bool obsf)
{
var obsfIDs = new UInt32[0];
if (obsf && bitField.Length > 32)
{
var rand = new Random();
var obsfCount = (UInt32)Math.Min(16, bitField.Length / 16);
UInt32 distObsf = 0;
obsfIDs = new UInt32[obsfCount];
while (distObsf < obsfCount)
{
var piece = (UInt32)rand.Next(0, bitField.Length);
if (obsfIDs.Contains(piece)) continue;
obsfIDs[distObsf] = piece;
distObsf++;
}
}
var bytes = new byte[bitField.Length / 8];
for (UInt32 i = 0; i < bitField.Length; i++)
{
if (obsfIDs.Contains(i)) continue;
var x = (int)Math.Floor((double)i/8);
var p = (ushort) (i%8);
if (bitField[i])
{
bytes[x] = bytes[x].SetBit(p);
}
}
var sent = Socket.Send(new PeerMessageBuilder(5).Add(bytes).Message());
if (obsfIDs.Length > 0)
{
foreach (var obsfID in obsfIDs)
{
SendHave(obsfID);
}
}
return sent == (5 + bitField.Length);
}
public bool SendRequest(UInt32 index, UInt32 start, UInt32 length)
{
var sent = Socket.Send(new PeerMessageBuilder(6).Add(index).Add(start).Add(length).Message());
return sent == 17;
}
public bool SendPiece(UInt32 index, UInt32 start, byte[] data)
{
var sent = Socket.Send(new PeerMessageBuilder(7).Add(index).Add(start).Add(data).Message());
return (sent == 13 + data.Length);
}
public bool SendCancel(UInt32 index, UInt32 start, UInt32 length)
{
var sent = Socket.Send(new PeerMessageBuilder(8).Add(index).Add(start).Add(length).Message());
return sent == 13;
}
public bool SendBytes(byte[] bytes)
{
var sent = Socket.Send(bytes);
return sent == bytes.Length;
}
#region Processors
private void ProcessHave()
{
var pieceIndex = Unpack.Int32(_internalBuffer, 0, Unpack.Endianness.Big);
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(4);
}
PeerBitField[pieceIndex] = true;
OnHave(pieceIndex);
}
private void ProcessBitfield(Int32 length)
{
if (_internalBuffer.Length < length)
{
//not sent entire bitfield, kill the connection
Disconnect();
return;
}
PeerBitField = new bool[length * 8];
for (var i = 0; i < length; i++)
{
var b = _internalBuffer[0];
PeerBitField[(i * 8) + 0] = b.GetBit(0);
PeerBitField[(i * 8) + 1] = b.GetBit(1);
PeerBitField[(i * 8) + 2] = b.GetBit(2);
PeerBitField[(i * 8) + 3] = b.GetBit(3);
PeerBitField[(i * 8) + 4] = b.GetBit(4);
PeerBitField[(i * 8) + 5] = b.GetBit(5);
PeerBitField[(i * 8) + 6] = b.GetBit(6);
PeerBitField[(i * 8) + 7] = b.GetBit(7);
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(1);
}
}
OnBitField(length*8, PeerBitField);
}
private void ProcessRequest(bool cancel)
{
var index = Unpack.Int32(_internalBuffer, 0, Unpack.Endianness.Big);
var begin = Unpack.Int32(_internalBuffer, 4, Unpack.Endianness.Big);
var length = Unpack.Int32(_internalBuffer, 8, Unpack.Endianness.Big);
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(12);
}
if (!cancel)
{
OnRequest(index, begin, length);
}
else
{
OnCancel(index, begin, length);
}
}
private void ProcessPiece(Int32 length)
{
var index = Unpack.Int32(_internalBuffer, 0, Unpack.Endianness.Big);
var begin = Unpack.Int32(_internalBuffer, 4, Unpack.Endianness.Big);
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(8);
}
byte[] buffer = _internalBuffer.GetBytes(0, length - 8);
lock (_locker)
{
_internalBuffer = _internalBuffer.GetBytes(length - 8);
}
OnPiece(index, begin, buffer);
}
#endregion
#region Event Dispatchers
private void OnNoData()
{
NoData?.Invoke(this);
}
private void OnHandshake()
{
HandshakeComplete?.Invoke(this);
}
private void OnKeepAlive()
{
KeepAlive?.Invoke(this);
}
private void OnChoke()
{
Choke?.Invoke(this);
}
private void OnUnChoke()
{
UnChoke?.Invoke(this);
}
private void OnInterested()
{
Interested?.Invoke(this);
}
private void OnNotInterested()
{
NotInterested?.Invoke(this);
}
private void OnHave(Int32 pieceIndex)
{
Have?.Invoke(this, pieceIndex);
}
private void OnBitField(Int32 size, bool[] bitField)
{
BitField?.Invoke(this, size, bitField);
}
private void OnRequest(Int32 index, Int32 begin, Int32 length)
{
Request?.Invoke(this, index, begin, length);
}
private void OnPiece(Int32 index, Int32 begin, byte[] bytes)
{
Piece?.Invoke(this, index, begin, bytes);
}
private void OnCancel(Int32 index, Int32 begin, Int32 length)
{
Cancel?.Invoke(this, index, begin, length);
}
#endregion
public void RegisterBTExtension(IProtocolExtension extension)
{
_btProtocolExtensions.Add(extension);
}
public void UnregisterBTExtension(IProtocolExtension extension)
{
_btProtocolExtensions.Remove(extension);
}
}
}