4 # :title: rbot HTTP provider
6 # Author:: Tom Gilbert <tom@linuxbrit.co.uk>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 # Author:: Dmitry "jsn" Kim <dmitry point kim at gmail point com>
10 # Copyright:: (C) 2002-2005 Tom Gilbert
11 # Copyright:: (C) 2006 Tom Gilbert, Giuseppe Bilotta
12 # Copyright:: (C) 2007 Giuseppe Bilotta, Dmitry Kim
21 error "Couldn't load 'net/https': #{e.pretty_inspect}"
22 error "Secured HTTP connections will fail"
25 # To handle Gzipped pages
31 attr_accessor :no_cache
32 if !instance_methods.include?('raw_body')
36 def body_charset(str=self.raw_body)
37 ctype = self['content-type'] || 'text/html'
38 return nil unless ctype =~ /^text/i || ctype =~ /x(ht)?ml/i
40 charsets = ['latin1'] # should be in config
42 if self['content-type'].match(/charset=["']?([^\s"']+)["']?/i)
44 debug "charset #{charsets.last} added from header"
48 when /<\?xml\s[^>]*encoding=['"]([^\s"'>]+)["'][^>]*\?>/i
50 debug "xml charset #{charsets.last} added from xml pi"
51 when /<(meta\s[^>]*http-equiv=["']?Content-Type["']?[^>]*)>/i
53 if meta =~ /charset=['"]?([^\s'";]+)['"]?/
55 debug "html charset #{charsets.last} added from meta"
62 charsets = self.body_charset(str) or return str
64 charsets.reverse_each { |charset|
66 return Iconv.iconv('utf-8//ignore', charset, str).first
68 debug "conversion failed for #{charset}"
74 def decompress_body(str)
75 method = self['content-encoding']
80 debug "gunzipping body"
81 return Zlib::GzipReader.new(StringIO.new(str)).read
83 raise "Unhandled content encoding #{method}"
88 return self.body_to_utf(self.decompress_body(self.raw_body))
91 # Read chunks from the body until we have at least _size_ bytes, yielding
92 # the partial text at each chunk. Return the partial body.
93 def partial_body(size=0, &block)
98 self.read_body { |chunk|
100 yield self.body_to_utf(self.decompress_body(partial)) if block_given?
101 break if size and size > 0 and partial.length >= size
104 return self.body_to_utf(self.decompress_body(partial))
109 Net::HTTP.version_1_2
114 # class for making http requests easier (mainly for plugins to use)
115 # this class can check the bot proxy configuration to determine if a proxy
116 # needs to be used, which includes support for per-url proxy configuration.
118 BotConfig.register BotConfigBooleanValue.new('http.use_proxy',
119 :default => false, :desc => "should a proxy be used for HTTP requests?")
120 BotConfig.register BotConfigStringValue.new('http.proxy_uri', :default => false,
121 :desc => "Proxy server to use for HTTP requests (URI, e.g http://proxy.host:port)")
122 BotConfig.register BotConfigStringValue.new('http.proxy_user',
124 :desc => "User for authenticating with the http proxy (if required)")
125 BotConfig.register BotConfigStringValue.new('http.proxy_pass',
127 :desc => "Password for authenticating with the http proxy (if required)")
128 BotConfig.register BotConfigArrayValue.new('http.proxy_include',
130 :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")
131 BotConfig.register BotConfigArrayValue.new('http.proxy_exclude',
133 :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")
134 BotConfig.register BotConfigIntegerValue.new('http.max_redir',
136 :desc => "Maximum number of redirections to be used when getting a document")
137 BotConfig.register BotConfigIntegerValue.new('http.expire_time',
139 :desc => "After how many minutes since last use a cached document is considered to be expired")
140 BotConfig.register BotConfigIntegerValue.new('http.max_cache_time',
142 :desc => "After how many minutes since first use a cached document is considered to be expired")
143 BotConfig.register BotConfigIntegerValue.new('http.no_expire_cache',
145 :desc => "Set this to true if you want the bot to never expire the cached pages")
146 BotConfig.register BotConfigIntegerValue.new('http.info_bytes',
148 :desc => "How many bytes to download from a web page to find some information. Set to 0 to let the bot download the whole page.")
151 attr_accessor :response, :last_used, :first_used, :count, :expires, :date
153 def self.maybe_new(resp)
154 debug "maybe new #{resp}"
155 return nil if resp.no_cache
156 return nil unless Net::HTTPOK === resp ||
157 Net::HTTPMovedPermanently === resp ||
158 Net::HTTPFound === resp ||
159 Net::HTTPPartialContent === resp
161 cc = resp['cache-control']
162 return nil if cc && (cc =~ /no-cache/i)
166 date = Time.httpdate(d)
169 return nil if resp['expires'] && (Time.httpdate(resp['expires']) < date)
171 debug "creating cache obj"
178 @first_used = now if @count == 0
184 debug "checking expired?"
185 if cc = self.response['cache-control'] && cc =~ /must-revalidate/
188 return self.expires < Time.now
191 def setup_headers(hdr)
192 hdr['if-modified-since'] = self.date.rfc2822
194 debug "ims == #{hdr['if-modified-since']}"
196 if etag = self.response['etag']
197 hdr['if-none-match'] = etag
198 debug "etag: #{etag}"
202 def revalidate(resp = self.response)
205 self.date = resp.key?('date') ? Time.httpdate(resp['date']) : Time.now
207 cc = resp['cache-control']
208 if cc && (cc =~ /max-age=(\d+)/)
209 self.expires = self.date + $1.to_i
210 elsif resp.key?('expires')
211 self.expires = Time.httpdate(resp['expires'])
212 elsif lm = resp['last-modified']
213 delta = self.date - Time.httpdate(lm)
214 delta = 10 if delta <= 0
216 self.expires = self.date + delta
218 self.expires = self.date + 300
220 # self.expires = Time.now + 10 # DEBUG
221 debug "expires on #{self.expires}"
231 self.response.raw_body
232 rescue Exception => e
243 'Accept-Charset' => 'utf-8;q=1.0, *;q=0.8',
244 'Accept-Encoding' => 'gzip;q=1, identity;q=0.8, *;q=0.2',
246 "rbot http util #{$version} (http://linuxbrit.co.uk/rbot/)"
248 debug "starting http cache cleanup timer"
249 @timer = @bot.timer.add(300) {
250 self.remove_stale_cache unless @bot.config['http.no_expire_cache']
255 debug 'stopping http cache cleanup timer'
256 @bot.timer.remove(@timer)
259 # if http_proxy_include or http_proxy_exclude are set, then examine the
260 # uri to see if this is a proxied uri
261 # the in/excludes are a list of regexps, and each regexp is checked against
262 # the server name, and its IP addresses
263 def proxy_required(uri)
265 if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
271 list.concat Resolv.getaddresses(uri.host)
272 rescue StandardError => err
273 warning "couldn't resolve host uri.host"
276 unless @bot.config["http.proxy_exclude"].empty?
277 re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
287 unless @bot.config["http.proxy_include"].empty?
288 re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
298 debug "using proxy for uri #{uri}?: #{use_proxy}"
302 # uri:: Uri to create a proxy for
304 # return a net/http Proxy object, which is configured correctly for
305 # proxying based on the bot's proxy configuration.
306 # This will include per-url proxy configuration based on the bot config
307 # +http_proxy_include/exclude+ options.
309 def get_proxy(uri, options = {})
321 if @bot.config["http.use_proxy"]
322 if (ENV['http_proxy'])
323 proxy = URI.parse ENV['http_proxy'] rescue nil
325 if (@bot.config["http.proxy_uri"])
326 proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
329 debug "proxy is set to #{proxy.host} port #{proxy.port}"
330 if proxy_required(uri)
331 proxy_host = proxy.host
332 proxy_port = proxy.port
333 proxy_user = @bot.config["http.proxy_user"]
334 proxy_pass = @bot.config["http.proxy_pass"]
339 h = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, proxy_user, proxy_port)
340 h.use_ssl = true if uri.scheme == "https"
342 h.read_timeout = opts[:read_timeout]
343 h.open_timeout = opts[:open_timeout]
347 def handle_response(uri, resp, opts, &block)
348 if Net::HTTPRedirection === resp && opts[:max_redir] >= 0
349 if resp.key?('location')
350 raise 'Too many redirections' if opts[:max_redir] <= 0
351 yield resp if opts[:yield] == :all && block_given?
352 loc = resp['location']
353 new_loc = URI.join(uri.to_s, loc) rescue URI.parse(loc)
355 new_opts[:max_redir] -= 1
356 case opts[:method].to_s.downcase.intern
357 when :post, :"net::http::post"
358 new_opts[:method] = :get
360 debug "following the redirect to #{new_loc}"
361 return get_response(new_loc, new_opts, &block)
363 warning ":| redirect w/o location?"
369 # Net::HTTP wants us to read the whole body here
375 # uri:: uri to query (Uri object or String)
376 # opts:: options. Currently used:
377 # :method:: request method [:get (default), :post or :head]
378 # :open_timeout:: open timeout for the proxy
379 # :read_timeout:: read timeout for the proxy
380 # :cache:: should we cache results?
381 # :yield:: if :final [default], call &block for the response object
382 # if :all, call &block for all intermediate redirects, too
383 # :max_redir:: how many redirects to follow before raising the exception
384 # if -1, don't follow redirects, just return them
385 # :range:: make a ranged request (usually GET). accepts a string
386 # for HTTP/1.1 "Range:" header (i.e. "bytes=0-1000")
387 # :body:: request body (usually for POST requests)
389 # Generic http transaction method
391 # It will return a HTTP::Response object or raise an exception
393 # If a block is given, it will yield the response (see :yield option)
395 def get_response(uri_or_s, options = {}, &block)
396 uri = uri_or_s.kind_of?(URI) ? uri_or_s : URI.parse(uri_or_s.to_s)
398 :max_redir => @bot.config['http.max_redir'],
407 req_class = case opts[:method].to_s.downcase.intern
408 when :head, :"net::http::head"
409 opts[:max_redir] = -1
411 when :get, :"net::http::get"
413 when :post, :"net::http::post"
415 opts[:body] or raise 'post request w/o a body?'
416 warning "refusing to cache POST request" if options[:cache]
419 warning "unsupported method #{opts[:method]}, doing GET"
423 if req_class != Net::HTTP::Get && opts[:range]
424 warning "can't request ranges for #{req_class}"
428 cache_key = "#{opts[:range]}|#{req_class}|#{uri.to_s}"
430 if req_class != Net::HTTP::Get && req_class != Net::HTTP::Head
432 warning "can't cache #{req_class.inspect} requests, working w/o cache"
437 debug "get_response(#{uri}, #{opts.inspect})"
439 if opts[:cache] && cached = @cache[cache_key]
444 return handle_response(uri, cached.response, opts, &block)
448 headers = @headers.dup.merge(opts[:headers] || {})
449 headers['Range'] = opts[:range] if opts[:range]
451 cached.setup_headers(headers) if cached && (req_class == Net::HTTP::Get)
452 req = req_class.new(uri.request_uri, headers)
453 req.basic_auth(uri.user, uri.password) if uri.user && uri.password
454 req.body = opts[:body] if req_class == Net::HTTP::Post
455 debug "prepared request: #{req.to_hash.inspect}"
457 get_proxy(uri, opts).start do |http|
458 http.request(req) do |resp|
459 resp['x-rbot-location'] = uri.to_s
460 if Net::HTTPNotModified === resp
463 cached.revalidate(resp)
464 rescue Exception => e
467 debug "reusing cached"
468 resp = cached.response
469 elsif Net::HTTPServerError === resp || Net::HTTPClientError === resp
470 debug "http error, deleting cached obj" if cached
471 @cache.delete(cache_key)
474 return handle_response(uri, resp, opts, &block)
476 if cached = CachedObject.maybe_new(resp) rescue nil
477 debug "storing to cache"
478 @cache[cache_key] = cached
483 return handle_response(uri, resp, opts, &block)
488 # uri:: uri to query (Uri object)
490 # simple get request, returns (if possible) response body following redirs
491 # and caching if requested
492 def get(uri, opts = {}, &block)
494 resp = get_response(uri, opts, &block)
495 raise "http error: #{resp}" unless Net::HTTPOK === resp ||
496 Net::HTTPPartialContent === resp
498 rescue Exception => e
504 def head(uri, options = {}, &block)
505 opts = {:method => :head}.merge(options)
507 resp = get_response(uri, opts, &block)
508 raise "http error #{resp}" if Net::HTTPClientError === resp ||
509 Net::HTTPServerError == resp
511 rescue Exception => e
517 def post(uri, data, options = {}, &block)
518 opts = {:method => :post, :body => data, :cache => false}.merge(options)
520 resp = get_response(uri, opts, &block)
521 raise 'http error' unless Net::HTTPOK === resp
523 rescue Exception => e
529 def get_partial(uri, nbytes = @bot.config['http.info_bytes'], options = {}, &block)
530 opts = {:range => "bytes=0-#{nbytes}"}.merge(options)
531 return get(uri, opts, &block)
534 def remove_stale_cache
535 debug "Removing stale cache"
537 max_last = @bot.config['http.expire_time'] * 60
538 max_first = @bot.config['http.max_cache_time'] * 60
539 debug "#{@cache.size} pages before"
541 @cache.reject! { |k, val|
542 (now - val.last_used > max_last) || (now - val.first_used > max_first)
545 error "Failed to remove stale cache: #{e.pretty_inspect}"
547 debug "#{@cache.size} pages after"
554 class HttpUtilPlugin < CoreBotModule
557 debug 'initializing httputil'
558 @bot.httputil = Irc::Utils::HttpUtil.new(@bot)
562 debug 'shutting down httputil'
563 @bot.httputil.cleanup