Class: LogStash::Filters::Referer

Inherits:
Base
  • Object
show all
Defined in:
lib/logstash/filters/referer.rb

Overview

Referer plugin get information from the referer field in http logs. This plugin can tell if a website is “social” or “search engine”. For Search engine, the query is extracted.

Patterns came from the Piwik project : see <github.com/piwik/searchengine-and-social-list>

Instance Method Summary collapse

Instance Method Details

#filter(event) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# File 'lib/logstash/filters/referer.rb', line 81

def filter(event)
  ref = event[@source]
  event[@target] = {"raw" => ref }
  if ref != "-"
    ref = URI(ref)
    host = ref.host
    host = host.slice(4..-1) if host.start_with? 'www.'
    if soc = @social[host]
      event[@target]["social"] = {"raw" => soc}
    else
      if s = index(host)
        name, index = s
        event[@target]["searchengine"] = {"name" => {"raw" => name}}
        engine = @searchEngines[name][index - 1]
        query = Hash[URI::decode_www_form(ref.query)] if ref.query
        engine["params"].each do |param|
          if param.start_with? '/'
            m = Regexp.new(param.slice(1..-2)).match(ref.path)
            p = m[1] if m
          else
            p = query[param] if query
          end
          if p
            event[@target]["searchengine"]["query"] = {"raw" => p}
            break
          end
        end
      end
    end
  end
  # filter_matched should go in the last line of our successful code
  filter_matched(event)
end

#registerObject



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
# File 'lib/logstash/filters/referer.rb', line 33

def register
  path = ::File.expand_path('../../../vendor/Socials.yml', ::File.dirname(__FILE__))
  @social = Hash.new
  YAML.load(File.open(path, 'r').read).each do |key, values|
    values.each do |value|
      @social[value] = key
    end
  end
  path = ::File.expand_path('../../../vendor/SearchEngines.yml', ::File.dirname(__FILE__))
  @searchEnginesIndex = Hash.new
  @searchEnginesIndexPrefix = Hash.new
  @searchEnginesIndexSufix = Hash.new
  @searchEngines = YAML.load(File.open(path, 'r').read)
  @searchEngines.each do |key, engines|
    engines.each do |engine|
      if urls = engine['urls']
        urls.each_with_index do |url, index|
          if url.end_with? '.{}'
            @searchEnginesIndexPrefix[url.slice 0..-4] = [key, index]
            next
          end
          if url.start_with? '{}.'
            @searchEnginesIndexSufix[url.slice 3..-1] = [key, index]
            next
          end
          @searchEnginesIndex[url] = [key, index]
        end
      end
    end
  end

end