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.
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',
19 :desc => "User for authenticating with the http proxy (if required)")
20 BotConfig.register BotConfigStringValue.new('http.proxy_pass',
22 :desc => "Password for authenticating with the http proxy (if required)")
23 BotConfig.register BotConfigArrayValue.new('http.proxy_include',
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',
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',
31 :desc => "Maximum number of redirections to be used when getting a document")
32 BotConfig.register BotConfigIntegerValue.new('http.expire_time',
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',
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',
40 :desc => "Set this to true if you want the bot to never expire the cached pages")
46 'User-Agent' => "rbot http util #{$version} (http://linuxbrit.co.uk/rbot/)",
50 attr_reader :last_response
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)
59 if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
65 list.concat Resolv.getaddresses(uri.host)
66 rescue StandardError => err
67 warning "couldn't resolve host uri.host"
70 unless @bot.config["http.proxy_exclude"].empty?
71 re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
81 unless @bot.config["http.proxy_include"].empty?
82 re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
92 debug "using proxy for uri #{uri}?: #{use_proxy}"
96 # uri:: Uri to create a proxy for
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.
109 if @bot.config["http.use_proxy"]
110 if (ENV['http_proxy'])
111 proxy = URI.parse ENV['http_proxy'] rescue nil
113 if (@bot.config["http.proxy_uri"])
114 proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
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"]
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"
132 # uri:: uri to query (Uri object)
133 # readtimeout:: timeout for reading the response
134 # opentimeout:: timeout for opening the connection
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)
144 uri = URI.parse(uri_or_str.to_s)
146 debug "Getting #{uri}"
148 proxy = get_proxy(uri)
149 proxy.open_timeout = opentimeout
150 proxy.read_timeout = readtimeout
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)
159 resp = http.request(req)
161 when Net::HTTPSuccess
162 if cache && !(resp.key?('cache-control') && resp['cache-control']=='must-revalidate')
165 @cache[k][:body] = resp.body
166 @cache[k][:last_mod] = Time.httpdate(resp['last-modified']) if resp.key?('last-modified')
168 @cache[k][:first_use] = Time.httpdate(resp['date'])
169 @cache[k][:last_use] = Time.httpdate(resp['date'])
172 @cache[k][:first_use] = now
173 @cache[k][:last_use] = now
175 @cache[k][:count] = 1
178 when Net::HTTPRedirection
179 debug "Redirecting #{uri} to #{resp['location']}"
180 yield resp['location'] if block_given?
182 return get( URI.join(uri.to_s, resp['location']), readtimeout, opentimeout, max_redir-1, cache)
184 warning "Max redirection reached, not going to #{resp['location']}"
187 debug "HttpUtil.get return code #{resp.code} #{resp.body}"
189 @last_response = resp
192 rescue StandardError, Timeout::Error => e
193 error "HttpUtil.get exception: #{e.inspect}, while trying to get #{uri}"
194 debug e.backtrace.join("\n")
200 # just like the above, but only gets the head
201 def head(uri_or_str, readtimeout=10, opentimeout=5, max_redir=@bot.config["http.max_redir"])
202 if uri_or_str.kind_of?(URI)
205 uri = URI.parse(uri_or_str.to_s)
208 proxy = get_proxy(uri)
209 proxy.open_timeout = opentimeout
210 proxy.read_timeout = readtimeout
213 proxy.start() {|http|
214 yield uri.request_uri() if block_given?
215 req = Net::HTTP::Head.new(uri.request_uri(), @headers)
216 if uri.user and uri.password
217 req.basic_auth(uri.user, uri.password)
219 resp = http.request(req)
221 when Net::HTTPSuccess
223 when Net::HTTPRedirection
224 debug "Redirecting #{uri} to #{resp['location']}"
225 yield resp['location'] if block_given?
227 return head( URI.parse(resp['location']), readtimeout, opentimeout, max_redir-1)
229 warning "Max redirection reached, not going to #{resp['location']}"
232 debug "HttpUtil.head return code #{resp.code}"
234 @last_response = resp
237 rescue StandardError, Timeout::Error => e
238 error "HttpUtil.head exception: #{e.inspect}, while trying to get #{uri}"
239 debug e.backtrace.join("\n")
245 # gets a page from the cache if it's still (assumed to be) valid
246 # TODO remove stale cached pages, except when called with noexpire=true
247 def get_cached(uri_or_str, readtimeout=10, opentimeout=5,
248 max_redir=@bot.config['http.max_redir'],
249 noexpire=@bot.config['http.no_expire_cache'])
250 if uri_or_str.kind_of?(URI)
253 uri = URI.parse(uri_or_str.to_s)
258 remove_stale_cache unless noexpire
259 return get(uri, readtimeout, opentimeout, max_redir, true)
263 # See if the last-modified header can be used
264 # Assumption: the page was not modified if both the header
265 # and the cached copy have the last-modified value, and it's the same time
266 # If only one of the cached copy and the header have the value, or if the
267 # value is different, we assume that the cached copyis invalid and therefore
269 # On our first try, we tested for last-modified in the webpage first,
270 # and then on the local cache. however, this is stupid (in general),
271 # so we only test for the remote page if the local copy had the header
272 # in the first place.
273 if @cache[k].key?(:last_mod)
274 h = head(uri, readtimeout, opentimeout, max_redir)
275 if h.key?('last-modified')
276 if Time.httpdate(h['last-modified']) == @cache[k][:last_mod]
278 @cache[k][:last_use] = Time.httpdate(h['date'])
280 @cache[k][:last_use] = now
282 @cache[k][:count] += 1
283 return @cache[k][:body]
285 remove_stale_cache unless noexpire
286 return get(uri, readtimeout, opentimeout, max_redir, true)
288 remove_stale_cache unless noexpire
289 return get(uri, readtimeout, opentimeout, max_redir, true)
292 warning "Error #{e.inspect} getting the page #{uri}, using cache"
293 debug e.backtrace.join("\n")
294 return @cache[k][:body]
296 # If we still haven't returned, we are dealing with a non-redirected document
297 # that doesn't have the last-modified attribute
298 debug "Could not use last-modified attribute for URL #{uri}, guessing cache validity"
299 if noexpire or !expired?(@cache[k], now)
300 @cache[k][:count] += 1
301 @cache[k][:last_use] = now
303 return @cache[k][:body]
305 debug "Cache expired, getting anew"
307 remove_stale_cache unless noexpire
308 return get(uri, readtimeout, opentimeout, max_redir, true)
311 def expired?(hash, time)
312 (time - hash[:last_use] > @bot.config['http.expire_time']*60) or
313 (time - hash[:first_use] > @bot.config['http.max_cache_time']*60)
316 def remove_stale_cache
318 @cache.reject! { |k, val|
319 !val.key?(:last_modified) && expired?(val, now)