Class: QuartzTorrent::PeerHandshake

Inherits:
Object
  • Object
show all
Defined in:
lib/quartz_torrent/peermsg.rb

Overview

Represents a bittorrent peer protocol handshake message.

Constant Summary collapse

ProtocolName =
"BitTorrent protocol"
InfoHashLen =
20
PeerIdLen =
20

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePeerHandshake

Returns a new instance of PeerHandshake.



15
16
17
18
19
# File 'lib/quartz_torrent/peermsg.rb', line 15

def initialize
  @infoHash = nil
  @peerId = nil
  @reserved = nil
end

Instance Attribute Details

#infoHashObject

Returns the value of attribute infoHash.



32
33
34
# File 'lib/quartz_torrent/peermsg.rb', line 32

def infoHash
  @infoHash
end

#peerIdObject

Returns the value of attribute peerId.



31
32
33
# File 'lib/quartz_torrent/peermsg.rb', line 31

def peerId
  @peerId
end

#reservedObject

Returns the value of attribute reserved.



33
34
35
# File 'lib/quartz_torrent/peermsg.rb', line 33

def reserved
  @reserved
end

Class Method Details

.unserializeExceptPeerIdFrom(io) ⇒ Object

Unserialize the first part of a PeerHandshake message from the passed io object up to but not including the peer id. This is needed when handling a handshake from the tracker which doesn’t have a peer id.



64
65
66
67
68
69
70
71
72
# File 'lib/quartz_torrent/peermsg.rb', line 64

def self.unserializeExceptPeerIdFrom(io)
  result = PeerHandshake.new
  len = io.read(1).unpack("C")[0]
  proto = io.read(len)
  raise "Unrecognized peer protocol name '#{proto}'" if proto != ProtocolName
  result.reserved = io.read(8) # reserved
  result.infoHash = io.read(InfoHashLen)
  result
end

.unserializeFrom(io) ⇒ Object

Unserialize a PeerHandshake message from the passed io object and return it. Throws exceptions on failure.



50
51
52
53
54
55
56
57
58
59
# File 'lib/quartz_torrent/peermsg.rb', line 50

def self.unserializeFrom(io)
  result = PeerHandshake.new
  len = io.read(1).unpack("C")[0]
  proto = io.read(len)
  raise "Unrecognized peer protocol name '#{proto}'" if proto != ProtocolName
  result.reserved = io.read(8) # reserved
  result.infoHash = io.read(InfoHashLen)
  result.peerId = io.read(PeerIdLen)
  result
end

Instance Method Details

#serializeTo(io) ⇒ Object

Serialize this PeerHandshake message to the passed io object. Throws exceptions on failure.



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/quartz_torrent/peermsg.rb', line 36

def serializeTo(io)
  raise "PeerId is not set" if ! @peerId
  raise "InfoHash is not set" if ! @infoHash
  result = [ProtocolName.length].pack("C")
  result << ProtocolName
  result << [0,0,0,0,0,0x10,0,0].pack("C8") # Reserved. 0x10 means we support extensions (BEP 10).
  result << @infoHash
  result << @peerId
  
  io.write result
end