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 ctype.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 do |charset|
65 # XXX: this one is really ugly, but i don't know how to make it better
70 debug "trying #{charset} / offset #{off}"
71 return Iconv.iconv('utf-8//ignore',
73 str.slice(0 .. (-1 - off))).first
75 debug "conversion failed for #{charset} / offset #{off}"
82 def decompress_body(str)
83 method = self['content-encoding']
87 when /gzip/ # Matches gzip, x-gzip, and the non-rfc-compliant gzip;q=\d sent by some servers
88 debug "gunzipping body"
90 return Zlib::GzipReader.new(StringIO.new(str)).read
91 rescue Zlib::Error => e
92 # If we can't unpack the whole stream (e.g. because we're doing a
94 debug "full gunzipping failed (#{e}), trying to recover as much as possible"
97 Zlib::GzipReader.new(StringIO.new(str)).each_byte { |byte|
105 debug "inflating body"
106 # From http://www.koders.com/ruby/fid927B4382397E5115AC0ABE21181AB5C1CBDD5C17.aspx?s=thread:
107 # -MAX_WBITS stops zlib from looking for a zlib header
108 inflater = Zlib::Inflate.new(-Zlib::MAX_WBITS)
110 return inflater.inflate(str)
111 rescue Zlib::Error => e
114 # debug "full inflation failed (#{e}), trying to recover as much as possible"
117 raise "Unhandled content encoding #{method}"
122 return self.body_to_utf(self.decompress_body(self.raw_body))
125 # Read chunks from the body until we have at least _size_ bytes, yielding
126 # the partial text at each chunk. Return the partial body.
127 def partial_body(size=0, &block)
132 self.read_body { |chunk|
134 yield self.body_to_utf(self.decompress_body(partial)) if block_given?
135 break if size and size > 0 and partial.length >= size
138 return self.body_to_utf(self.decompress_body(partial))
143 Net::HTTP.version_1_2
148 # class for making http requests easier (mainly for plugins to use)
149 # this class can check the bot proxy configuration to determine if a proxy
150 # needs to be used, which includes support for per-url proxy configuration.
152 Bot::Config.register Bot::Config::BooleanValue.new('http.use_proxy',
153 :default => false, :desc => "should a proxy be used for HTTP requests?")
154 Bot::Config.register Bot::Config::StringValue.new('http.proxy_uri', :default => false,
155 :desc => "Proxy server to use for HTTP requests (URI, e.g http://proxy.host:port)")
156 Bot::Config.register Bot::Config::StringValue.new('http.proxy_user',
158 :desc => "User for authenticating with the http proxy (if required)")
159 Bot::Config.register Bot::Config::StringValue.new('http.proxy_pass',
161 :desc => "Password for authenticating with the http proxy (if required)")
162 Bot::Config.register Bot::Config::ArrayValue.new('http.proxy_include',
164 :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")
165 Bot::Config.register Bot::Config::ArrayValue.new('http.proxy_exclude',
167 :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")
168 Bot::Config.register Bot::Config::IntegerValue.new('http.max_redir',
170 :desc => "Maximum number of redirections to be used when getting a document")
171 Bot::Config.register Bot::Config::IntegerValue.new('http.expire_time',
173 :desc => "After how many minutes since last use a cached document is considered to be expired")
174 Bot::Config.register Bot::Config::IntegerValue.new('http.max_cache_time',
176 :desc => "After how many minutes since first use a cached document is considered to be expired")
177 Bot::Config.register Bot::Config::IntegerValue.new('http.no_expire_cache',
179 :desc => "Set this to true if you want the bot to never expire the cached pages")
180 Bot::Config.register Bot::Config::IntegerValue.new('http.info_bytes',
182 :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.")
185 attr_accessor :response, :last_used, :first_used, :count, :expires, :date
187 def self.maybe_new(resp)
188 debug "maybe new #{resp}"
189 return nil if resp.no_cache
190 return nil unless Net::HTTPOK === resp ||
191 Net::HTTPMovedPermanently === resp ||
192 Net::HTTPFound === resp ||
193 Net::HTTPPartialContent === resp
195 cc = resp['cache-control']
196 return nil if cc && (cc =~ /no-cache/i)
200 date = Time.httpdate(d)
203 return nil if resp['expires'] && (Time.httpdate(resp['expires']) < date)
205 debug "creating cache obj"
212 @first_used = now if @count == 0
218 debug "checking expired?"
219 if cc = self.response['cache-control'] && cc =~ /must-revalidate/
222 return self.expires < Time.now
225 def setup_headers(hdr)
226 hdr['if-modified-since'] = self.date.rfc2822
228 debug "ims == #{hdr['if-modified-since']}"
230 if etag = self.response['etag']
231 hdr['if-none-match'] = etag
232 debug "etag: #{etag}"
236 def revalidate(resp = self.response)
239 self.date = resp.key?('date') ? Time.httpdate(resp['date']) : Time.now
241 cc = resp['cache-control']
242 if cc && (cc =~ /max-age=(\d+)/)
243 self.expires = self.date + $1.to_i
244 elsif resp.key?('expires')
245 self.expires = Time.httpdate(resp['expires'])
246 elsif lm = resp['last-modified']
247 delta = self.date - Time.httpdate(lm)
248 delta = 10 if delta <= 0
250 self.expires = self.date + delta
252 self.expires = self.date + 300
254 # self.expires = Time.now + 10 # DEBUG
255 debug "expires on #{self.expires}"
265 self.response.raw_body
266 rescue Exception => e
273 # Create the HttpUtil instance, associating it with Bot _bot_
279 'Accept-Charset' => 'utf-8;q=1.0, *;q=0.8',
280 'Accept-Encoding' => 'gzip;q=1, identity;q=0.8, *;q=0.2',
282 "rbot http util #{$version} (http://linuxbrit.co.uk/rbot/)"
284 debug "starting http cache cleanup timer"
285 @timer = @bot.timer.add(300) {
286 self.remove_stale_cache unless @bot.config['http.no_expire_cache']
290 # Clean up on HttpUtil unloading, by stopping the cache cleanup timer.
292 debug 'stopping http cache cleanup timer'
293 @bot.timer.remove(@timer)
296 # This method checks if a proxy is required to access _uri_, by looking at
297 # the values of config values +http.proxy_include+ and +http.proxy_exclude+.
299 # Each of these config values, if set, should be a Regexp the server name and
300 # IP address should be checked against.
302 def proxy_required(uri)
304 if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
310 list.concat Resolv.getaddresses(uri.host)
311 rescue StandardError => err
312 warning "couldn't resolve host uri.host"
315 unless @bot.config["http.proxy_exclude"].empty?
316 re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
326 unless @bot.config["http.proxy_include"].empty?
327 re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
337 debug "using proxy for uri #{uri}?: #{use_proxy}"
341 # _uri_:: URI to create a proxy for
343 # Return a net/http Proxy object, configured for proxying based on the
344 # bot's proxy configuration. See proxy_required for more details on this.
346 def get_proxy(uri, options = {})
358 if @bot.config["http.use_proxy"]
359 if (ENV['http_proxy'])
360 proxy = URI.parse ENV['http_proxy'] rescue nil
362 if (@bot.config["http.proxy_uri"])
363 proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
366 debug "proxy is set to #{proxy.host} port #{proxy.port}"
367 if proxy_required(uri)
368 proxy_host = proxy.host
369 proxy_port = proxy.port
370 proxy_user = @bot.config["http.proxy_user"]
371 proxy_pass = @bot.config["http.proxy_pass"]
376 h = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, proxy_user, proxy_port)
377 h.use_ssl = true if uri.scheme == "https"
379 h.read_timeout = opts[:read_timeout]
380 h.open_timeout = opts[:open_timeout]
384 # Internal method used to hanlde response _resp_ received when making a
385 # request for URI _uri_.
387 # It follows redirects, optionally yielding them if option :yield is :all.
389 # Also yields and returns the final _resp_.
391 def handle_response(uri, resp, opts, &block) # :yields: resp
392 if Net::HTTPRedirection === resp && opts[:max_redir] >= 0
393 if resp.key?('location')
394 raise 'Too many redirections' if opts[:max_redir] <= 0
395 yield resp if opts[:yield] == :all && block_given?
396 loc = resp['location']
397 new_loc = URI.join(uri.to_s, loc) rescue URI.parse(loc)
399 new_opts[:max_redir] -= 1
400 case opts[:method].to_s.downcase.intern
401 when :post, :"net::http::post"
402 new_opts[:method] = :get
404 if resp['set-cookie']
405 debug "setting cookie #{resp['set-cookie']}"
406 new_opts[:headers] ||= Hash.new
407 new_opts[:headers]['Cookie'] = resp['set-cookie']
409 debug "following the redirect to #{new_loc}"
410 return get_response(new_loc, new_opts, &block)
412 warning ":| redirect w/o location?"
417 alias :body :cooked_body
419 unless resp['content-type']
420 debug "No content type, guessing"
421 resp['content-type'] =
422 case resp['x-rbot-location']
428 'application/xml+xhtml'
429 when /.(gif|png|jpe?g|jp2|tiff?)$/i
430 "image/#{$1.sub(/^jpg$/,'jpeg').sub(/^tif$/,'tiff')}"
432 'application/octetstream'
438 # Net::HTTP wants us to read the whole body here
444 # _uri_:: uri to query (URI object or String)
446 # Generic http transaction method. It will return a Net::HTTPResponse
447 # object or raise an exception
449 # If a block is given, it will yield the response (see :yield option)
451 # Currently supported _options_:
453 # method:: request method [:get (default), :post or :head]
454 # open_timeout:: open timeout for the proxy
455 # read_timeout:: read timeout for the proxy
456 # cache:: should we cache results?
457 # yield:: if :final [default], calls the block for the response object;
458 # if :all, call the block for all intermediate redirects, too
459 # max_redir:: how many redirects to follow before raising the exception
460 # if -1, don't follow redirects, just return them
461 # range:: make a ranged request (usually GET). accepts a string
462 # for HTTP/1.1 "Range:" header (i.e. "bytes=0-1000")
463 # body:: request body (usually for POST requests)
464 # headers:: additional headers to be set for the request. Its value must
465 # be a Hash in the form { 'Header' => 'value' }
467 def get_response(uri_or_s, options = {}, &block) # :yields: resp
468 uri = uri_or_s.kind_of?(URI) ? uri_or_s : URI.parse(uri_or_s.to_s)
470 :max_redir => @bot.config['http.max_redir'],
479 req_class = case opts[:method].to_s.downcase.intern
480 when :head, :"net::http::head"
481 opts[:max_redir] = -1
483 when :get, :"net::http::get"
485 when :post, :"net::http::post"
487 opts[:body] or raise 'post request w/o a body?'
488 warning "refusing to cache POST request" if options[:cache]
491 warning "unsupported method #{opts[:method]}, doing GET"
495 if req_class != Net::HTTP::Get && opts[:range]
496 warning "can't request ranges for #{req_class}"
500 cache_key = "#{opts[:range]}|#{req_class}|#{uri.to_s}"
502 if req_class != Net::HTTP::Get && req_class != Net::HTTP::Head
504 warning "can't cache #{req_class.inspect} requests, working w/o cache"
509 debug "get_response(#{uri}, #{opts.inspect})"
511 if opts[:cache] && cached = @cache[cache_key]
516 return handle_response(uri, cached.response, opts, &block)
520 headers = @headers.dup.merge(opts[:headers] || {})
521 headers['Range'] = opts[:range] if opts[:range]
522 headers['Authorization'] = opts[:auth_head] if opts[:auth_head]
524 cached.setup_headers(headers) if cached && (req_class == Net::HTTP::Get)
525 req = req_class.new(uri.request_uri, headers)
526 if uri.user && uri.password
527 req.basic_auth(uri.user, uri.password)
528 opts[:auth_head] = req['Authorization']
530 req.body = opts[:body] if req_class == Net::HTTP::Post
531 debug "prepared request: #{req.to_hash.inspect}"
534 get_proxy(uri, opts).start do |http|
535 http.request(req) do |resp|
536 resp['x-rbot-location'] = uri.to_s
537 if Net::HTTPNotModified === resp
540 cached.revalidate(resp)
541 rescue Exception => e
544 debug "reusing cached"
545 resp = cached.response
546 elsif Net::HTTPServerError === resp || Net::HTTPClientError === resp
547 debug "http error, deleting cached obj" if cached
548 @cache.delete(cache_key)
551 return handle_response(uri, resp, opts, &block)
553 if cached = CachedObject.maybe_new(resp) rescue nil
554 debug "storing to cache"
555 @cache[cache_key] = cached
560 return handle_response(uri, resp, opts, &block)
563 rescue Exception => e
569 # _uri_:: uri to query (URI object or String)
571 # Simple GET request, returns (if possible) response body following redirs
572 # and caching if requested, yielding the actual response(s) to the optional
573 # block. See get_response for details on the supported _options_
575 def get(uri, options = {}, &block) # :yields: resp
577 resp = get_response(uri, options, &block)
578 raise "http error: #{resp}" unless Net::HTTPOK === resp ||
579 Net::HTTPPartialContent === resp
581 rescue Exception => e
587 # _uri_:: uri to query (URI object or String)
589 # Simple HEAD request, returns (if possible) response head following redirs
590 # and caching if requested, yielding the actual response(s) to the optional
591 # block. See get_response for details on the supported _options_
593 def head(uri, options = {}, &block) # :yields: resp
594 opts = {:method => :head}.merge(options)
596 resp = get_response(uri, opts, &block)
597 raise "http error #{resp}" if Net::HTTPClientError === resp ||
598 Net::HTTPServerError == resp
600 rescue Exception => e
606 # _uri_:: uri to query (URI object or String)
607 # _data_:: body of the POST
609 # Simple POST request, returns (if possible) response following redirs and
610 # caching if requested, yielding the response(s) to the optional block. See
611 # get_response for details on the supported _options_
613 def post(uri, data, options = {}, &block) # :yields: resp
614 opts = {:method => :post, :body => data, :cache => false}.merge(options)
616 resp = get_response(uri, opts, &block)
617 raise 'http error' unless Net::HTTPOK === resp
619 rescue Exception => e
625 # _uri_:: uri to query (URI object or String)
626 # _nbytes_:: number of bytes to get
628 # Partia GET request, returns (if possible) the first _nbytes_ bytes of the
629 # response body, following redirs and caching if requested, yielding the
630 # actual response(s) to the optional block. See get_response for details on
631 # the supported _options_
633 def get_partial(uri, nbytes = @bot.config['http.info_bytes'], options = {}, &block) # :yields: resp
634 opts = {:range => "bytes=0-#{nbytes}"}.merge(options)
635 return get(uri, opts, &block)
638 def remove_stale_cache
639 debug "Removing stale cache"
641 max_last = @bot.config['http.expire_time'] * 60
642 max_first = @bot.config['http.max_cache_time'] * 60
643 debug "#{@cache.size} pages before"
645 @cache.reject! { |k, val|
646 (now - val.last_used > max_last) || (now - val.first_used > max_first)
649 error "Failed to remove stale cache: #{e.pretty_inspect}"
651 debug "#{@cache.size} pages after"
658 class HttpUtilPlugin < CoreBotModule
661 debug 'initializing httputil'
662 @bot.httputil = Irc::Utils::HttpUtil.new(@bot)
666 debug 'shutting down httputil'
667 @bot.httputil.cleanup