Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/lib/rex/proto/kademlia/message.rb
Views: 11703
# -*- coding: binary -*-12module Rex3module Proto4##5#6# Minimal support for the newer Kademlia protocol, referred to here and often7# elsewhere as Kademlia2. It is unclear how this differs from the old protocol.8#9# Protocol details are hard to come by because most documentation is academic10# in nature and glosses over the low-level network details. The best11# documents I found on the protocol are:12#13# http://gbmaster.wordpress.com/2013/05/05/botnets-surrounding-us-an-initial-focus-on-kad/14# http://gbmaster.wordpress.com/2013/06/16/botnets-surrounding-us-sending-kademlia2_bootstrap_req-kademlia2_hello_req-and-their-strict-cousins/15# http://gbmaster.wordpress.com/2013/11/23/botnets-surrounding-us-performing-requests-sending-out-kademlia2_req-and-asking-contact-where-art-thou/16#17##18module Kademlia19# A simple Kademlia message20class Message21# The header that non-compressed Kad messages use22STANDARD_PACKET = 0xE423# The header that compressed Kad messages use, which is currently unsupported24COMPRESSED_PACKET = 0xE52526# @return [Integer] the message type27attr_reader :type28# @return [String] the message body29attr_reader :body3031# Construct a new Message from the provided type and body32#33# @param type [String] the message type34# @param body [String] the message body35def initialize(type, body = '')36@type = type37@body = body38end3940# Construct a new Message from the provided data41#42# @param data [String] the data to interpret as a Kademlia message43# @return [Message] the message if valid, nil otherwise44def self.from_data(data)45return if data.length < 246header, type = data.unpack('CC')47if header == COMPRESSED_PACKET48fail NotImplementedError, "Unable to handle #{data.length}-byte compressed Kademlia message"49end50return if header != STANDARD_PACKET51Message.new(type, data[2, data.length])52end5354# Get this Message as a String55#56# @return [String] the string representation of this Message57def to_str58[STANDARD_PACKET, @type].pack('CC') + @body59end6061# Compares this Message and another Message for equality62#63# @param other [Message] the Message to compare64# @return [Boolean] true iff the two messages have equal types and bodies, false otherwise65def ==(other)66type == other.type && body == other.body67end68end69end70end71end727374