#!/usr/bin/env ruby =begin Copyright 2008 Ben Clarke Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =end module Torrent class BEncHash < Hash alias_method :store, :[]= alias_method :each_pair, :each def initialize @keys = [] end def []=(key, val) @keys << key super end def delete(key) @keys.delete(key) super end def each @keys.each { |k| yield k, self[k] } end def each_key @keys.each { |k| yield k } end def each_value @keys.each { |k| yield self[k] } end def to_s dict self end private def str(str) "#{str.length}:#{str}" end def int(i) "i#{i}e" end def list(l) "l" << l.collect{|x| add(x)}.join << "e" end def dict(h) ret = "" h.each {|k,v| ret << add(k) << add(v) } "d#{ret}e" end def add(x) if x.kind_of? Symbol or x.kind_of? String str(x.to_s) elsif x.kind_of? Fixnum or x.kind_of? Bignum int(x) elsif x.kind_of? Array list(x) elsif x.kind_of? Hash dict(x) end end end class Parser attr_accessor :hash BufSize = 1024 def initialize(stream) @buf_size = BufSize @buf = String.new @buf_ptr = 0 @stream = stream @hash = parse end def parse ret = nil until (c = next_char(false)) == nil case c when 'd': ret = BEncHash.new k = nil until (x = parse) == :end unless k.nil? ret[k] = x k = nil else k = x.intern end end when 'l': ret = [] until (x = parse) == :end ret << x end when 'i': ret = read_to('e').to_i when /[0-9]/ len = c << read_to(':') ret = '' len.to_i.times {|i| ret << next_char } when 'e': ret = :end else raise "Invalid torrent file: " + "encountered unexpected character '#{c}'" end return ret end end def read_to(x) ret = "" until (c = next_char) == x ret << c end ret end def next_char(err = true) if @buf_ptr >= @buf.length @stream.read(@buf_size, @buf) @buf_ptr = 0 end c = @buf[@buf_ptr].chr @buf_ptr += 1 raise "Unexpected EOF" if err and c.nil? return c end end end if $0 == __FILE__ if ARGV.length == 0 parser = Torrent::Parser.new(ARGF) puts parser.hash else ARGV.each do |arg| File.open(arg, 'r') {|f| parser = Torrent::Parser.new(f) } puts parser.hash end end end