]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/httputil.rb
Minor tweaks to httputil: make last response available in @last_resp for get and...
[user/henk/code/ruby/rbot.git] / lib / rbot / httputil.rb
1 module Irc
2 module Utils
3
4 require 'resolv'
5 require 'net/http'
6 require 'net/https'
7 Net::HTTP.version_1_2
8
9 # class for making http requests easier (mainly for plugins to use)
10 # this class can check the bot proxy configuration to determine if a proxy
11 # needs to be used, which includes support for per-url proxy configuration.
12 class HttpUtil
13     BotConfig.register BotConfigBooleanValue.new('http.use_proxy',
14       :default => false, :desc => "should a proxy be used for HTTP requests?")
15     BotConfig.register BotConfigStringValue.new('http.proxy_uri', :default => false,
16       :desc => "Proxy server to use for HTTP requests (URI, e.g http://proxy.host:port)")
17     BotConfig.register BotConfigStringValue.new('http.proxy_user',
18       :default => nil,
19       :desc => "User for authenticating with the http proxy (if required)")
20     BotConfig.register BotConfigStringValue.new('http.proxy_pass',
21       :default => nil,
22       :desc => "Password for authenticating with the http proxy (if required)")
23     BotConfig.register BotConfigArrayValue.new('http.proxy_include',
24       :default => [],
25       :desc => "List of regexps to check against a URI's hostname/ip to see if we should use the proxy to access this URI. All URIs are proxied by default if the proxy is set, so this is only required to re-include URIs that might have been excluded by the exclude list. e.g. exclude /.*\.foo\.com/, include bar\.foo\.com")
26     BotConfig.register BotConfigArrayValue.new('http.proxy_exclude',
27       :default => [],
28       :desc => "List of regexps to check against a URI's hostname/ip to see if we should use avoid the proxy to access this URI and access it directly")
29     BotConfig.register BotConfigIntegerValue.new('http.max_redir',
30       :default => 5,
31       :desc => "Maximum number of redirections to be used when getting a document")
32     BotConfig.register BotConfigIntegerValue.new('http.expire_time',
33       :default => 60,
34       :desc => "After how many minutes since last use a cached document is considered to be expired")
35     BotConfig.register BotConfigIntegerValue.new('http.max_cache_time',
36       :default => 60*24,
37       :desc => "After how many minutes since first use a cached document is considered to be expired")
38     BotConfig.register BotConfigIntegerValue.new('http.no_expire_cache',
39       :default => false,
40       :desc => "Set this to true if you want the bot to never expire the cached pages")
41
42   def initialize(bot)
43     @bot = bot
44     @cache = Hash.new
45     @headers = {
46       'User-Agent' => "rbot http util #{$version} (http://linuxbrit.co.uk/rbot/)",
47     }
48     @last_response = nil
49   end
50   attr_reader :last_response
51
52   # if http_proxy_include or http_proxy_exclude are set, then examine the
53   # uri to see if this is a proxied uri
54   # the in/excludes are a list of regexps, and each regexp is checked against
55   # the server name, and its IP addresses
56   def proxy_required(uri)
57     use_proxy = true
58     if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
59       return use_proxy
60     end
61
62     list = [uri.host]
63     begin
64       list.concat Resolv.getaddresses(uri.host)
65     rescue StandardError => err
66       warning "couldn't resolve host uri.host"
67     end
68
69     unless @bot.config["http.proxy_exclude"].empty?
70       re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
71       re.each do |r|
72         list.each do |item|
73           if r.match(item)
74             use_proxy = false
75             break
76           end
77         end
78       end
79     end
80     unless @bot.config["http.proxy_include"].empty?
81       re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
82       re.each do |r|
83         list.each do |item|
84           if r.match(item)
85             use_proxy = true
86             break
87           end
88         end
89       end
90     end
91     debug "using proxy for uri #{uri}?: #{use_proxy}"
92     return use_proxy
93   end
94
95   # uri:: Uri to create a proxy for
96   #
97   # return a net/http Proxy object, which is configured correctly for
98   # proxying based on the bot's proxy configuration.
99   # This will include per-url proxy configuration based on the bot config
100   # +http_proxy_include/exclude+ options.
101   def get_proxy(uri)
102     proxy = nil
103     proxy_host = nil
104     proxy_port = nil
105     proxy_user = nil
106     proxy_pass = nil
107
108     if @bot.config["http.use_proxy"]
109       if (ENV['http_proxy'])
110         proxy = URI.parse ENV['http_proxy'] rescue nil
111       end
112       if (@bot.config["http.proxy_uri"])
113         proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
114       end
115       if proxy
116         debug "proxy is set to #{proxy.host} port #{proxy.port}"
117         if proxy_required(uri)
118           proxy_host = proxy.host
119           proxy_port = proxy.port
120           proxy_user = @bot.config["http.proxy_user"]
121           proxy_pass = @bot.config["http.proxy_pass"]
122         end
123       end
124     end
125
126     h = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, proxy_user, proxy_port)
127     h.use_ssl = true if uri.scheme == "https"
128     return h
129   end
130
131   # uri::         uri to query (Uri object)
132   # readtimeout:: timeout for reading the response
133   # opentimeout:: timeout for opening the connection
134   #
135   # simple get request, returns (if possible) response body following redirs
136   # and caching if requested
137   # if a block is given, it yields the urls it gets redirected to
138   # TODO we really need something to implement proper caching
139   def get(uri_or_str, readtimeout=10, opentimeout=5, max_redir=@bot.config["http.max_redir"], cache=false)
140     if uri_or_str.kind_of?(URI)
141       uri = uri_or_str
142     else
143       uri = URI.parse(uri_or_str.to_s)
144     end
145
146     proxy = get_proxy(uri)
147     proxy.open_timeout = opentimeout
148     proxy.read_timeout = readtimeout
149
150     begin
151       proxy.start() {|http|
152         yield uri.request_uri() if block_given?
153         resp = http.get(uri.request_uri(), @headers)
154         case resp
155         when Net::HTTPSuccess
156           if cache && !(resp.key?('cache-control') && resp['cache-control']=='must-revalidate')
157             k = uri.to_s
158             @cache[k] = Hash.new
159             @cache[k][:body] = resp.body
160             @cache[k][:last_mod] = Time.httpdate(resp['last-modified']) if resp.key?('last-modified')
161             if resp.key?('date')
162               @cache[k][:first_use] = Time.httpdate(resp['date'])
163               @cache[k][:last_use] = Time.httpdate(resp['date'])
164             else
165               now = Time.new
166               @cache[k][:first_use] = now
167               @cache[k][:last_use] = now
168             end
169             @cache[k][:count] = 1
170           end
171           return resp.body
172         when Net::HTTPRedirection
173           debug "Redirecting #{uri} to #{resp['location']}"
174           yield resp['location'] if block_given?
175           if max_redir > 0
176             return get( URI.parse(resp['location']), readtimeout, opentimeout, max_redir-1, cache)
177           else
178             warning "Max redirection reached, not going to #{resp['location']}"
179           end
180         else
181           debug "HttpUtil.get return code #{resp.code} #{resp.body}"
182         end
183         @last_response = resp
184         return nil
185       }
186     rescue StandardError, Timeout::Error => e
187       error "HttpUtil.get exception: #{e.inspect}, while trying to get #{uri}"
188       debug e.backtrace.join("\n")
189     end
190     @last_response = nil
191     return nil
192   end
193
194   # just like the above, but only gets the head
195   def head(uri_or_str, readtimeout=10, opentimeout=5, max_redir=@bot.config["http.max_redir"])
196     if uri_or_str.kind_of?(URI)
197       uri = uri_or_str
198     else
199       uri = URI.parse(uri_or_str.to_s)
200     end
201
202     proxy = get_proxy(uri)
203     proxy.open_timeout = opentimeout
204     proxy.read_timeout = readtimeout
205
206     begin
207       proxy.start() {|http|
208         yield uri.request_uri() if block_given?
209         resp = http.request_head(uri.request_uri(), @headers)
210         case resp
211         when Net::HTTPSuccess
212           return resp
213         when Net::HTTPRedirection
214           debug "Redirecting #{uri} to #{resp['location']}"
215           yield resp['location'] if block_given?
216           if max_redir > 0
217             return head( URI.parse(resp['location']), readtimeout, opentimeout, max_redir-1)
218           else
219             warning "Max redirection reached, not going to #{resp['location']}"
220           end
221         else
222           debug "HttpUtil.head return code #{resp.code}"
223         end
224         @last_response = resp
225         return nil
226       }
227     rescue StandardError, Timeout::Error => e
228       error "HttpUtil.head exception: #{e.inspect}, while trying to get #{uri}"
229       debug e.backtrace.join("\n")
230     end
231     @last_response = nil
232     return nil
233   end
234
235   # gets a page from the cache if it's still (assumed to be) valid
236   # TODO remove stale cached pages, except when called with noexpire=true
237   def get_cached(uri_or_str, readtimeout=10, opentimeout=5,
238                  max_redir=@bot.config['http.max_redir'],
239                  noexpire=@bot.config['http.no_expire_cache'])
240     if uri_or_str.kind_of?(URI)
241       uri = uri_or_str
242     else
243       uri = URI.parse(uri_or_str.to_s)
244     end
245
246     k = uri.to_s
247     if !@cache.key?(k)
248       remove_stale_cache unless noexpire
249       return get(uri, readtimeout, opentimeout, max_redir, true)
250     end
251     now = Time.new
252     begin
253       # See if the last-modified header can be used
254       # Assumption: the page was not modified if both the header
255       # and the cached copy have the last-modified value, and it's the same time
256       # If only one of the cached copy and the header have the value, or if the
257       # value is different, we assume that the cached copyis invalid and therefore
258       # get a new one.
259       # On our first try, we tested for last-modified in the webpage first,
260       # and then on the local cache. however, this is stupid (in general),
261       # so we only test for the remote page if the local copy had the header
262       # in the first place.
263       if @cache[k].key?(:last_mod)
264         h = head(uri, readtimeout, opentimeout, max_redir)
265         if h.key?('last-modified')
266           if Time.httpdate(h['last-modified']) == @cache[k][:last_mod]
267             if h.key?('date')
268               @cache[k][:last_use] = Time.httpdate(h['date'])
269             else
270               @cache[k][:last_use] = now
271             end
272             @cache[k][:count] += 1
273             return @cache[k][:body]
274           end
275           remove_stale_cache unless noexpire
276           return get(uri, readtimeout, opentimeout, max_redir, true)
277         end
278         remove_stale_cache unless noexpire
279         return get(uri, readtimeout, opentimeout, max_redir, true)
280       end
281     rescue => e
282       warning "Error #{e.inspect} getting the page #{uri}, using cache"
283       debug e.backtrace.join("\n")
284       return @cache[k][:body]
285     end
286     # If we still haven't returned, we are dealing with a non-redirected document
287     # that doesn't have the last-modified attribute
288     debug "Could not use last-modified attribute for URL #{uri}, guessing cache validity"
289     if noexpire or !expired?(@cache[k], now)
290       @cache[k][:count] += 1
291       @cache[k][:last_use] = now
292       debug "Using cache"
293       return @cache[k][:body]
294     end
295     debug "Cache expired, getting anew"
296     @cache.delete(k)
297     remove_stale_cache unless noexpire
298     return get(uri, readtimeout, opentimeout, max_redir, true)
299   end
300
301   def expired?(hash, time)
302     (time - hash[:last_use] > @bot.config['http.expire_time']*60) or
303     (time - hash[:first_use] > @bot.config['http.max_cache_time']*60)
304   end
305
306   def remove_stale_cache
307     now = Time.new
308     @cache.reject! { |k, val|
309       !val.key?(:last_modified) && expired?(val, now)
310     }
311   end
312
313 end
314 end
315 end