#!/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 = [] @str = String.new 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 @str end private def str(str) @str += "#{str.length}:#{str}" end def int(i) @str += "i#{i}e" end def list(l) @str += "l" l.each {|x| add x} @str += "e" end def dict(h) @str += "d" h.each do |k,v| add k add v end @str += "e" end def add(x) if x.kind_of? Symbol str(x.to_s) elsif x.kind_of? String str(x) 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 def initialize(stream, opts = {}) @opts = opts @stream = stream @hash = parse end def parse ret = nil loop do c = next_char(false) break if c.nil? case c when 'd': ret = BEncHash.new k = nil loop do break if (x = parse) == :end unless k.nil? ret[k] = x k = nil else k = x.intern end end when 'l': ret = [] loop do break if (x = parse) == :end ret << x end when 'i': ret = '' loop do c = next_char break if c == 'e' ret << c end ret = ret.to_i when /[0-9]/ len = c ret = '' loop do c = next_char break if c == ':' len << c end 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 next_char(err = true) n = @stream.getc raise "Unexpected EOF" if err and n.nil? return nil if n.nil? return n.chr end end end if $0 == __FILE__ if ARGV.length == 0 parser = Torrent::Parser.new(ARGF) puts parser.hash[:announce] else ARGV.each do |arg| File.open(arg, 'r') {|f| parser = Torrent::Parser.new(f) } puts parser.hash[:announce] end end end