Class: Rbkb::Cli::Bgrep

Inherits:
Executable show all
Defined in:
lib/rbkb/cli/bgrep.rb

Overview

Copyright 2009 emonti at matasano.com See README.rdoc for license information

searches for a binary string in input. string can be provided ‘hexified’

Instance Attribute Summary

Attributes inherited from Executable

#argv, #exit_status, #oparse, #opts, #stderr, #stdin, #stdout

Instance Method Summary collapse

Methods inherited from Executable

#bail, #bail_args, #exit, run

Constructor Details

#initialize(*args) ⇒ Bgrep

Returns a new instance of Bgrep.



8
9
10
11
12
13
14
# File 'lib/rbkb/cli/bgrep.rb', line 8

def initialize(*args)
  super(*args) do |this|
    this.opts[:start_off] ||= 0
    this.opts[:end_off] ||= -1
    this.opts[:include_fname] ||= true
  end
end

Instance Method Details

#go(*args) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/rbkb/cli/bgrep.rb', line 53

def go(*args)
  super(*args)

  if @opts[:hex]
    bail "you specified -x for hex and the subject isn't" unless @find.ishex?
    @find = @find.unhexify
  elsif @opts[:rx]
    @find = Regexp.new(@find, Regexp::MULTILINE)
  end

  if fname = @argv.shift
    dat = do_file_read(fname)
    fname = nil unless @argv[0] # only print filenames for multiple files
  else
    dat = @stdin.read
  end

  loop do 
    dat.bgrep(@find, @opts[:align]) do |hit_start, hit_end, match|
      @stdout.write "#{fname}:" if fname and @opts[:include_fname]

      @stdout.write(
        "#{(hit_start).to_hex.rjust(8,"0")}:"+
        "#{(hit_end).to_hex.rjust(8,"0")}:b:"+
        "#{match.inspect}\n")
    end

    break unless fname=@argv.shift
    dat = do_file_read(fname)
  end
  self.exit(0)
end

#make_parserObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/rbkb/cli/bgrep.rb', line 16

def make_parser
  arg = super()
  arg.banner += " <search> <file | blank for stdin>"

  arg.on("-x", "--[no-]hex", "Search for hex (default: false)") do |x|
    @opts[:hex] = x
  end

  arg.on("-r", "--[no-]regex", "Search for regex (default: false)") do |r|
    @opts[:rx] = r
  end

  arg.on("-a", "--align=BYTES", Numeric, 
         "Only match on alignment boundary") do |a|
    @opts[:align] = a
  end

  arg.on("-n", "--[no-]filename", 
         "Toggle filenames. (Default: #{@opts[:include_fname]})") do |n|
    @opts[:include_fname] = n
  end
  return arg
end

#parse(*args) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rbkb/cli/bgrep.rb', line 41

def parse(*args)
  super(*args)

  bail "need search argument" unless @find = @argv.shift

  if @opts[:hex] and @opts[:rx]
    bail "-r and -x are mutually exclusive"
  end

  # ... filenames vs. stdin will be parsed in 'go'
end