Class: DeadFinder::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/deadfinder/runner.rb

Overview

Runner class for executing the main logic

Instance Method Summary collapse

Instance Method Details

#default_optionsObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/deadfinder/runner.rb', line 15

def default_options
  {
    'concurrency' => 50,
    'timeout' => 10,
    'output' => '',
    'output_format' => 'json',
    'headers' => [],
    'worker_headers' => [],
    'silent' => true,
    'verbose' => false,
    'include30x' => false,
    'proxy' => '',
    'proxy_auth' => '',
    'match' => '',
    'ignore' => '',
  }
end

#run(target, options) ⇒ Object



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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/deadfinder/runner.rb', line 33

def run(target, options)
  DeadFinder::Logger.apply_options(options)
  headers = options['headers'].each_with_object({}) do |header, hash|
    kv = header.split(': ')
    hash[kv[0]] = kv[1]
  rescue StandardError
  end
  page = Nokogiri::HTML(URI.open(target, headers))
  links = extract_links(page)

  DeadFinder::Logger.debug "#{CACHE_QUE.size} URLs in queue, #{CACHE_SET.size} URLs in cache"

  if options['match'] != ''
    begin
      links.each do |type, urls|
    links[type] = urls.select { |url| DeadFinder::UrlPatternMatcher.match?(url, options['match']) }
      end
    rescue RegexpError => e
      DeadFinder::Logger.error "Invalid match pattern: #{e.message}"
    end
  end

  if options['ignore'] != ''
    begin
      links.each do |type, urls|
        links[type] = urls.reject { |url| DeadFinder::UrlPatternMatcher.ignore?(url, options['ignore']) }
      end
    rescue RegexpError => e
      DeadFinder::Logger.error "Invalid match pattern: #{e.message}"
    end
  end

  total_links_count = links.values.flatten.length
  link_info = links.map { |type, urls| "#{type}:#{urls.length}" if urls.length.positive? }
                   .compact.join(' / ')
  DeadFinder::Logger.sub_info "Discovered #{total_links_count} URLs, currently checking them. [#{link_info}]" unless link_info.empty?

  jobs = Channel.new(buffer: :buffered, capacity: 1000)
  results = Channel.new(buffer: :buffered, capacity: 1000)

  (1..options['concurrency']).each do |w|
    Channel.go { worker(w, jobs, results, target, options) }
  end

  links.values.flatten.uniq.each do |node|
    result = generate_url(node, target)
    jobs << result unless result.nil?
  end

  jobs_size = jobs.size
  jobs.close

  (1..jobs_size).each { ~results }

  # Log coverage summary if tracking was enabled
  if options['coverage'] && DeadFinder.coverage_data[target] && DeadFinder.coverage_data[target][:total] > 0
    total = DeadFinder.coverage_data[target][:total]
    dead = DeadFinder.coverage_data[target][:dead]
    percentage = ((dead.to_f / total) * 100).round(2)
    DeadFinder::Logger.sub_info "Coverage: #{dead}/#{total} URLs are dead links (#{percentage}%)"
  end

  DeadFinder::Logger.sub_complete 'Task completed'
rescue StandardError => e
  DeadFinder::Logger.error "[#{e}] #{target}"
end

#worker(_id, jobs, results, target, options) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/deadfinder/runner.rb', line 100

def worker(_id, jobs, results, target, options)
  jobs.each do |j|
    if CACHE_SET[j]
      # Skip if already cached
    else
      CACHE_SET[j] = true
      # Track total URLs tested for coverage calculation (only if coverage flag is enabled)
      if options['coverage']
        DeadFinder.coverage_data[target] ||= { total: 0, dead: 0, status_counts: Hash.new(0) }
        DeadFinder.coverage_data[target][:total] += 1
      end

      begin
        CACHE_QUE[j] = true
        uri = URI.parse(j)
        http = HttpClient.create(uri, options)

        request = Net::HTTP::Get.new(uri.request_uri)
        request['User-Agent'] = options['user_agent']
        options['worker_headers']&.each do |header|
          key, value = header.split(':', 2)
          request[key.strip] = value.strip
        end

        response = http.request(request)
        status_code = response.code.to_i

        if status_code >= 400 || (status_code >= 300 && options['include30x'])
          DeadFinder::Logger.found "[#{status_code}] #{j}"
          CACHE_QUE[j] = false
          DeadFinder.output[target] ||= []
          DeadFinder.output[target] << j
          # Track dead URLs for coverage calculation (only if coverage flag is enabled)
          if options['coverage']
            DeadFinder.coverage_data[target][:dead] += 1
            DeadFinder.coverage_data[target][:status_counts][status_code] += 1
          end
        else
          DeadFinder::Logger.verbose_ok "[#{status_code}] #{j}" if options['verbose']
          # Track status for successful URLs
          DeadFinder.coverage_data[target][:status_counts][status_code] += 1 if options['coverage']
        end
      rescue StandardError => e
        DeadFinder::Logger.verbose "[#{e}] #{j}" if options['verbose']
        # Consider errored URLs as dead for coverage calculation (only if coverage flag is enabled)
        if options['coverage']
          DeadFinder.coverage_data[target][:dead] += 1
          DeadFinder.coverage_data[target][:status_counts]['error'] += 1
        end
      end
    end
    results << j
  end
end