]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/httputil.rb
Initial implementation of proper caching based on last-modified and etag HTTP headers
[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   attr_reader :headers
52
53   # if http_proxy_include or http_proxy_exclude are set, then examine the
54   # uri to see if this is a proxied uri
55   # the in/excludes are a list of regexps, and each regexp is checked against
56   # the server name, and its IP addresses
57   def proxy_required(uri)
58     use_proxy = true
59     if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
60       return use_proxy
61     end
62
63     list = [uri.host]
64     begin
65       list.concat Resolv.getaddresses(uri.host)
66     rescue StandardError => err
67       warning "couldn't resolve host uri.host"
68     end
69
70     unless @bot.config["http.proxy_exclude"].empty?
71       re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
72       re.each do |r|
73         list.each do |item|
74           if r.match(item)
75             use_proxy = false
76             break
77           end
78         end
79       end
80     end
81     unless @bot.config["http.proxy_include"].empty?
82       re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
83       re.each do |r|
84         list.each do |item|
85           if r.match(item)
86             use_proxy = true
87             break
88           end
89         end
90       end
91     end
92     debug "using proxy for uri #{uri}?: #{use_proxy}"
93     return use_proxy
94   end
95
96   # uri:: Uri to create a proxy for
97   #
98   # return a net/http Proxy object, which is configured correctly for
99   # proxying based on the bot's proxy configuration.
100   # This will include per-url proxy configuration based on the bot config
101   # +http_proxy_include/exclude+ options.
102   def get_proxy(uri)
103     proxy = nil
104     proxy_host = nil
105     proxy_port = nil
106     proxy_user = nil
107     proxy_pass = nil
108
109     if @bot.config["http.use_proxy"]
110       if (ENV['http_proxy'])
111         proxy = URI.parse ENV['http_proxy'] rescue nil
112       end
113       if (@bot.config["http.proxy_uri"])
114         proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
115       end
116       if proxy
117         debug "proxy is set to #{proxy.host} port #{proxy.port}"
118         if proxy_required(uri)
119           proxy_host = proxy.host
120           proxy_port = proxy.port
121           proxy_user = @bot.config["http.proxy_user"]
122           proxy_pass = @bot.config["http.proxy_pass"]
123         end
124       end
125     end
126
127     h = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, proxy_user, proxy_port)
128     h.use_ssl = true if uri.scheme == "https"
129     return h
130   end
131
132   # uri::         uri to query (Uri object)
133   # readtimeout:: timeout for reading the response
134   # opentimeout:: timeout for opening the connection
135   #
136   # simple get request, returns (if possible) response body following redirs
137   # and caching if requested
138   # if a block is given, it yields the urls it gets redirected to
139   # TODO we really need something to implement proper caching
140   def get(uri_or_str, readtimeout=10, opentimeout=5, max_redir=@bot.config["http.max_redir"], cache=false)
141     if uri_or_str.kind_of?(URI)
142       uri = uri_or_str
143     else
144       uri = URI.parse(uri_or_str.to_s)
145     end
146     debug "Getting #{uri}"
147
148     proxy = get_proxy(uri)
149     proxy.open_timeout = opentimeout
150     proxy.read_timeout = readtimeout
151
152     begin
153       proxy.start() {|http|
154         yield uri.request_uri() if block_given?
155         req = Net::HTTP::Get.new(uri.request_uri(), @headers)
156         if uri.user and uri.password
157           req.basic_auth(uri.user, uri.password)
158         end
159         resp = http.request(req)
160         case resp
161         when Net::HTTPSuccess
162           if cache
163             debug "Caching #{uri.to_s}"
164             cache_response(uri.to_s, resp)
165           end
166           return resp.body
167         when Net::HTTPRedirection
168           debug "Redirecting #{uri} to #{resp['location']}"
169           yield resp['location'] if block_given?
170           if max_redir > 0
171             # If cache is an Array, we assume get was called by get_cached
172             # because of a cache miss and that the first value of the Array
173             # was the noexpire value. Since the cache miss might have been
174             # caused by a redirection, we want to try get_cached again
175             # TODO FIXME look at Python's httplib2 for a most likely
176             # better way to handle all this mess
177             if cache.kind_of?(Array)
178               return get_cached( URI.join(uri.to_s, resp['location']), readtimeout, opentimeout, max_redir-1, cache[0])
179             else
180               return get( URI.join(uri.to_s, resp['location']), readtimeout, opentimeout, max_redir-1, cache)
181             end
182           else
183             warning "Max redirection reached, not going to #{resp['location']}"
184           end
185         else
186           debug "HttpUtil.get return code #{resp.code} #{resp.body}"
187         end
188         @last_response = resp
189         return nil
190       }
191     rescue StandardError, Timeout::Error => e
192       error "HttpUtil.get exception: #{e.inspect}, while trying to get #{uri}"
193       debug e.backtrace.join("\n")
194     end
195     @last_response = nil
196     return nil
197   end
198
199   # just like the above, but only gets the head
200   def head(uri_or_str, readtimeout=10, opentimeout=5, max_redir=@bot.config["http.max_redir"])
201     if uri_or_str.kind_of?(URI)
202       uri = uri_or_str
203     else
204       uri = URI.parse(uri_or_str.to_s)
205     end
206
207     proxy = get_proxy(uri)
208     proxy.open_timeout = opentimeout
209     proxy.read_timeout = readtimeout
210
211     begin
212       proxy.start() {|http|
213         yield uri.request_uri() if block_given?
214         req = Net::HTTP::Head.new(uri.request_uri(), @headers)
215         if uri.user and uri.password
216           req.basic_auth(uri.user, uri.password)
217         end
218         resp = http.request(req)
219         case resp
220         when Net::HTTPSuccess
221           return resp
222         when Net::HTTPRedirection
223           debug "Redirecting #{uri} to #{resp['location']}"
224           yield resp['location'] if block_given?
225           if max_redir > 0
226             return head( URI.parse(resp['location']), readtimeout, opentimeout, max_redir-1)
227           else
228             warning "Max redirection reached, not going to #{resp['location']}"
229           end
230         else
231           debug "HttpUtil.head return code #{resp.code}"
232         end
233         @last_response = resp
234         return nil
235       }
236     rescue StandardError, Timeout::Error => e
237       error "HttpUtil.head exception: #{e.inspect}, while trying to get #{uri}"
238       debug e.backtrace.join("\n")
239     end
240     @last_response = nil
241     return nil
242   end
243
244   def cache_response(k, resp)
245     begin
246       if resp.key?('pragma') and resp['pragma'] == 'no-cache'
247         debug "Not caching #{k}, it has Pragma: no-cache"
248         return
249       end
250       # TODO should we skip caching if neither last-modified nor etag are present?
251       now = Time.new
252       u = Hash.new
253       u = Hash.new
254       u[:body] = resp.body
255       u[:last_modified] = nil
256       u[:last_modified] = Time.httpdate(resp['date']) if resp.key?('date')
257       u[:last_modified] = Time.httpdate(resp['last-modified']) if resp.key?('last-modified')
258       u[:expires] = Time.now
259       u[:expires] = Time.httpdate(resp['expires']) if resp.key?('expires')
260       u[:revalidate] = false
261       if resp.key?('cache-control')
262         # TODO max-age
263         case resp['cache-control']
264         when /no-cache|must-revalidate/
265           u[:revalidate] = true
266         end
267       end
268       u[:etag] = ""
269       u[:etag] = resp['etag'] if resp.key?('etag')
270       u[:count] = 1
271       u[:first_use] = now
272       u[:last_use] = now
273     rescue => e
274       error "Failed to cache #{k}/#{resp.to_hash.inspect}: #{e.inspect}"
275       return
276     end
277     # @cache[k] = u
278     # For debugging purposes
279     @cache[k] = u.dup
280     u.delete(:body)
281     debug "Cached #{k}/#{resp.to_hash.inspect}: #{u.inspect}"
282     debug "#{@cache.size} pages (#{@cache.keys.join(', ')}) cached up to now"
283   end
284
285   def expired?(uri, readtimeout, opentimeout)
286     k = uri.to_s
287     debug "Checking cache validity for #{k}"
288     begin
289       return true unless @cache.key?(k)
290       u = @cache[k]
291
292       # TODO we always revalidate for the time being
293
294       if u[:etag].empty? and u[:last_modified].nil?
295         # TODO max-age
296         return true
297       end
298
299       proxy = get_proxy(uri)
300       proxy.open_timeout = opentimeout
301       proxy.read_timeout = readtimeout
302
303       proxy.start() {|http|
304         yield uri.request_uri() if block_given?
305         headers = @headers
306         headers['If-None-Match'] = u[:etag] unless u[:etag].empty?
307         headers['If-Modified-Since'] = u[:last_modified].rfc2822 if u[:last_modified]
308         # FIXME TODO We might want to use a Get here
309         # because if a 200 OK is returned we would get the new body
310         # with one connection less ...
311         req = Net::HTTP::Head.new(uri.request_uri(), headers)
312         if uri.user and uri.password
313           req.basic_auth(uri.user, uri.password)
314         end
315         resp = http.request(req)
316         debug "Checking cache validity of #{u.inspect} against #{resp.to_hash.inspect}"
317         case resp
318         when Net::HTTPNotModified
319           return false
320         else
321           return true
322         end
323       }
324     rescue => e
325       error "Failed to check cache validity for #{uri}: #{e.inspect}"
326       return true
327     end
328   end
329
330   # gets a page from the cache if it's still (assumed to be) valid
331   # TODO remove stale cached pages, except when called with noexpire=true
332   def get_cached(uri_or_str, readtimeout=10, opentimeout=5,
333                  max_redir=@bot.config['http.max_redir'],
334                  noexpire=@bot.config['http.no_expire_cache'])
335     if uri_or_str.kind_of?(URI)
336       uri = uri_or_str
337     else
338       uri = URI.parse(uri_or_str.to_s)
339     end
340     debug "Getting cached #{uri}"
341
342     if expired?(uri, readtimeout, opentimeout)
343       debug "Cache expired"
344       bod = get(uri, readtimeout, opentimeout, max_redir, [noexpire])
345     else
346       debug "Using cache"
347       @cache[k][:count] += 1
348       @cache[k][:last_use] = now
349       bod = @cache[k][:body]
350     end
351     unless noexpire
352       remove_stale_cache
353     end
354     return bod
355   end
356
357   # We consider a page to be manually expired if it has no
358   # etag and no last-modified and if any of the expiration
359   # conditions are met (expire_time, max_cache_time, Expires)
360   def manually_expired?(hash, time)
361     auto = hash[:etag].empty? and hash[:last_modified].nil?
362     # TODO max-age
363     manual = (time - hash[:last_use] > @bot.config['http.expire_time']*60) or
364              (time - hash[:first_use] > @bot.config['http.max_cache_time']*60) or
365              (hash[:expires] < time)
366     return (auto and manual)
367   end
368
369   def remove_stale_cache
370     debug "Removing stale cache"
371     debug "#{@cache.size} pages before"
372     begin
373     now = Time.new
374     @cache.reject! { |k, val|
375        manually_expired?(val, now)
376     }
377     rescue => e
378       error "Failed to remove stale cache: #{e.inspect}"
379     end
380     debug "#{@cache.size} pages after"
381   end
382 end
383 end
384 end