Whitespace cleanup
[rbot] / 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   end
49
50   # if http_proxy_include or http_proxy_exclude are set, then examine the
51   # uri to see if this is a proxied uri
52   # the in/excludes are a list of regexps, and each regexp is checked against
53   # the server name, and its IP addresses
54   def proxy_required(uri)
55     use_proxy = true
56     if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
57       return use_proxy
58     end
59
60     list = [uri.host]
61     begin
62       list.concat Resolv.getaddresses(uri.host)
63     rescue StandardError => err
64       warning "couldn't resolve host uri.host"
65     end
66
67     unless @bot.config["http.proxy_exclude"].empty?
68       re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
69       re.each do |r|
70         list.each do |item|
71           if r.match(item)
72             use_proxy = false
73             break
74           end
75         end
76       end
77     end
78     unless @bot.config["http.proxy_include"].empty?
79       re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
80       re.each do |r|
81         list.each do |item|
82           if r.match(item)
83             use_proxy = true
84             break
85           end
86         end
87       end
88     end
89     debug "using proxy for uri #{uri}?: #{use_proxy}"
90     return use_proxy
91   end
92
93   # uri:: Uri to create a proxy for
94   #
95   # return a net/http Proxy object, which is configured correctly for
96   # proxying based on the bot's proxy configuration.
97   # This will include per-url proxy configuration based on the bot config
98   # +http_proxy_include/exclude+ options.
99   def get_proxy(uri)
100     proxy = nil
101     proxy_host = nil
102     proxy_port = nil
103     proxy_user = nil
104     proxy_pass = nil
105
106     if @bot.config["http.use_proxy"]
107       if (ENV['http_proxy'])
108         proxy = URI.parse ENV['http_proxy'] rescue nil
109       end
110       if (@bot.config["http.proxy_uri"])
111         proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
112       end
113       if proxy
114         debug "proxy is set to #{proxy.host} port #{proxy.port}"
115         if proxy_required(uri)
116           proxy_host = proxy.host
117           proxy_port = proxy.port
118           proxy_user = @bot.config["http.proxy_user"]
119           proxy_pass = @bot.config["http.proxy_pass"]
120         end
121       end
122     end
123
124     h = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, proxy_user, proxy_port)
125     h.use_ssl = true if uri.scheme == "https"
126     return h
127   end
128
129   # uri::         uri to query (Uri object)
130   # readtimeout:: timeout for reading the response
131   # opentimeout:: timeout for opening the connection
132   #
133   # simple get request, returns (if possible) response body following redirs
134   # and caching if requested
135   # if a block is given, it yields the urls it gets redirected to
136   # TODO we really need something to implement proper caching
137   def get(uri_or_str, readtimeout=10, opentimeout=5, max_redir=@bot.config["http.max_redir"], cache=false)
138     if uri_or_str.class <= URI
139       uri = uri_or_str
140     else
141       uri = URI.parse(uri_or_str.to_s)
142     end
143
144     proxy = get_proxy(uri)
145     proxy.open_timeout = opentimeout
146     proxy.read_timeout = readtimeout
147
148     begin
149       proxy.start() {|http|
150         yield uri.request_uri() if block_given?
151         resp = http.get(uri.request_uri(), @headers)
152         case resp
153         when Net::HTTPSuccess
154           if cache && !(resp.key?('cache-control') && resp['cache-control']=='must-revalidate')
155             k = uri.to_s
156             @cache[k] = Hash.new
157             @cache[k][:body] = resp.body
158             @cache[k][:last_mod] = Time.httpdate(resp['last-modified']) if resp.key?('last-modified')
159             if resp.key?('date')
160               @cache[k][:first_use] = Time.httpdate(resp['date'])
161               @cache[k][:last_use] = Time.httpdate(resp['date'])
162             else
163               now = Time.new
164               @cache[k][:first_use] = now
165               @cache[k][:last_use] = now
166             end
167             @cache[k][:count] = 1
168           end
169           return resp.body
170         when Net::HTTPRedirection
171           debug "Redirecting #{uri} to #{resp['location']}"
172           yield resp['location'] if block_given?
173           if max_redir > 0
174             return get( URI.parse(resp['location']), readtimeout, opentimeout, max_redir-1, cache)
175           else
176             warning "Max redirection reached, not going to #{resp['location']}"
177           end
178         else
179           debug "HttpUtil.get return code #{resp.code} #{resp.body}"
180         end
181         return nil
182       }
183     rescue StandardError, Timeout::Error => e
184       error "HttpUtil.get exception: #{e.inspect}, while trying to get #{uri}"
185       debug e.backtrace.join("\n")
186     end
187     return nil
188   end
189
190   # just like the above, but only gets the head
191   def head(uri_or_str, readtimeout=10, opentimeout=5, max_redir=@bot.config["http.max_redir"])
192     if uri_or_str.class <= URI
193       uri = uri_or_str
194     else
195       uri = URI.parse(uri_or_str.to_s)
196     end
197
198     proxy = get_proxy(uri)
199     proxy.open_timeout = opentimeout
200     proxy.read_timeout = readtimeout
201
202     begin
203       proxy.start() {|http|
204         yield uri.request_uri() if block_given?
205         resp = http.head(uri.request_uri(), @headers)
206         case resp
207         when Net::HTTPSuccess
208           return resp
209         when Net::HTTPRedirection
210           debug "Redirecting #{uri} to #{resp['location']}"
211           yield resp['location'] if block_given?
212           if max_redir > 0
213             return head( URI.parse(resp['location']), readtimeout, opentimeout, max_redir-1)
214           else
215             warning "Max redirection reached, not going to #{resp['location']}"
216           end
217         else
218           debug "HttpUtil.head return code #{resp.code}"
219         end
220         return nil
221       }
222     rescue StandardError, Timeout::Error => e
223       error "HttpUtil.head exception: #{e.inspect}, while trying to get #{uri}"
224       debug e.backtrace.join("\n")
225     end
226     return nil
227   end
228
229   # gets a page from the cache if it's still (assumed to be) valid
230   # TODO remove stale cached pages, except when called with noexpire=true
231   def get_cached(uri_or_str, readtimeout=10, opentimeout=5,
232                  max_redir=@bot.config['http.max_redir'],
233                  noexpire=@bot.config['http.no_expire_cache'])
234     if uri_or_str.class <= URI
235       uri = uri_or_str
236     else
237       uri = URI.parse(uri_or_str.to_s)
238     end
239
240     k = uri.to_s
241     if !@cache.key?(k)
242       remove_stale_cache unless noexpire
243       return get(uri, readtimeout, opentimeout, max_redir, true)
244     end
245     now = Time.new
246     begin
247       # See if the last-modified header can be used
248       # Assumption: the page was not modified if both the header
249       # and the cached copy have the last-modified value, and it's the same time
250       # If only one of the cached copy and the header have the value, or if the
251       # value is different, we assume that the cached copyis invalid and therefore
252       # get a new one.
253       # On our first try, we tested for last-modified in the webpage first,
254       # and then on the local cache. however, this is stupid (in general),
255       # so we only test for the remote page if the local copy had the header
256       # in the first place.
257       if @cache[k].key?(:last_mod)
258         h = head(uri, readtimeout, opentimeout, max_redir)
259         if h.key?('last-modified')
260           if Time.httpdate(h['last-modified']) == @cache[k][:last_mod]
261             if h.key?('date')
262               @cache[k][:last_use] = Time.httpdate(h['date'])
263             else
264               @cache[k][:last_use] = now
265             end
266             @cache[k][:count] += 1
267             return @cache[k][:body]
268           end
269           remove_stale_cache unless noexpire
270           return get(uri, readtimeout, opentimeout, max_redir, true)
271         end
272         remove_stale_cache unless noexpire
273         return get(uri, readtimeout, opentimeout, max_redir, true)
274       end
275     rescue => e
276       warning "Error #{e.inspect} getting the page #{uri}, using cache"
277       debug e.backtrace.join("\n")
278       return @cache[k][:body]
279     end
280     # If we still haven't returned, we are dealing with a non-redirected document
281     # that doesn't have the last-modified attribute
282     debug "Could not use last-modified attribute for URL #{uri}, guessing cache validity"
283     if noexpire or !expired?(@cache[k], now)
284       @cache[k][:count] += 1
285       @cache[k][:last_use] = now
286       debug "Using cache"
287       return @cache[k][:body]
288     end
289     debug "Cache expired, getting anew"
290     @cache.delete(k)
291     remove_stale_cache unless noexpire
292     return get(uri, readtimeout, opentimeout, max_redir, true)
293   end
294
295   def expired?(hash, time)
296     (time - hash[:last_use] > @bot.config['http.expire_time']*60) or
297     (time - hash[:first_use] > @bot.config['http.max_cache_time']*60)
298   end
299
300   def remove_stale_cache
301     now = Time.new
302     @cache.reject! { |k, val|
303       !val.key?(:last_modified) && expired?(val, now)
304     }
305   end
306
307 end
308 end
309 end