summaryrefslogtreecommitdiff
path: root/lib/rbot/core/utils/wordlist.rb
blob: 339a3219383a934bf0db5003a26947d3893705c9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#-- vim:sw=2:et
#++
#
# :title: rbot wordlist provider
#
# Author:: Raine Virta <rane@kapsi.fi>

require "find"

module ::Irc
class Bot
class Wordlist
  def self.get(bot, where, options={})
    wordlist_base = bot.path('wordlists')
    opts = { :spaces => false }.merge(options)

    wordlist_path = File.join(wordlist_base, where)
    raise "wordlist not found: #{wordlist_path}" unless File.exist?(wordlist_path)

    # Location is a directory -> combine all lists beneath it
    wordlist = if File.directory?(wordlist_path)
      wordlists = []
      Find.find(wordlist_path) do |path|
        next if path == wordlist_path
        wordlists << path unless File.directory?(path)
      end

      wordlists.map { |list| File.readlines(list) }.flatten
    else
      File.readlines(wordlist_path)
    end

    # wordlists are assumed to be UTF-8, but we need to strip the BOM, if present
    wordlist.map! { |l| l.sub("\xef\xbb\xbf",'').strip }
    wordlist.reject do |word|
      word =~ /\s/ && !opts[:spaces] ||
      word.empty?
    end
  end

  # Return an array with the list of available wordlists.
  # Available options:
  # pattern:: pattern that should be matched by the wordlist filename
  def self.list(bot, options={})
    wordlist_base = bot.path('wordlists')
    pattern = options[:pattern] || "**"
    # refuse patterns that contain ../
    return [] if pattern =~ /\.\.\//
    striplen = wordlist_base.length+1
    Dir.glob(File.join(wordlist_base, pattern)).map { |name|
      name[striplen..-1]
    }
  end

  def self.exist?(bot, path)
    wordlist_base = bot.path('wordlists')
    fn = path.to_s
    # refuse to check outside of the wordlist base directory
    return false if fn =~ /\.\.\//
    File.exist?(File.join(wordlist_base, fn))
  end

end
end
end