#!/usr/bin/env ruby # Author Eric Monti (emonti at matasano) # # len prepends a binary length number in front of its input and writes it # raw on STDOUT # # Usage: len [options] # -h, --help Show this message # -v, --version Show version and exit # -f, --file FILENAME Input from FILENAME # -n, --nudge INT Add integer to length # -s, --size=SIZE Size of length field in bytes # -x, --[no-]swap Swap endianness. Default=big # -t, --[no-]total Include size word in size # -l, --length=LEN Ignore all else and use LEN # require 'rbkb' require 'rbkb/command_line' include RBkB::CommandLine #------------------------------------------------------------------------------- # Init options and arg parsing # endianness pair. index 0 is always the default endpair = [:big, :little] OPTS = {:nudge => 0, :size => 4, :endian => endpair[0]} arg = bkb_stdargs(nil, OPTS) arg = bkb_inputargs(arg, OPTS) arg.banner += " " #------------------------------------------------------------------------------ # Add local options arg.on("-n", "--nudge INT", Numeric, "Add integer to length") do |n| OPTS[:nudge] += n end arg.on("-s", "--size=SIZE", Numeric, "Size of length field in bytes") do |s| bail("Size must be greater than 0") unless (OPTS[:size] = s) > 0 end arg.on("-x", "--[no-]swap", "Swap endianness. Default=#{OPTS[:endian]}") do |x| OPTS[:endian] = endpair[(x)? 1 : 0] end arg.on("-t", "--[no-]total", "Include size word in size") do |t| OPTS[:tot]=t end arg.on("-l", "--length=LEN", Numeric, "Ignore all else and use LEN") do |l| OPTS[:static]=l end #------------------------------------------------------------------------------ # Parse arguments arg.parse!(ARGV) rescue bail "Error: #{$!}\n#{arg}" OPTS[:indat] ||= ARGV.shift OPTS[:indat] ||= STDIN.read bail "Error: Too many arguments\n##{arg}" if ARGV.shift unless len=OPTS[:static] len = OPTS[:indat].size len += OPTS[:size] if OPTS[:tot] len += OPTS[:nudge] end STDOUT.write len.to_bytes(OPTS[:endian], OPTS[:size]) << OPTS[:indat]