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>
17 error "Couldn't load 'net/https': #{e}"
18 error "Secured HTTP connections will fail"
19 # give a nicer error than "undefined method `use_ssl='"
20 ::Net::HTTP.class_eval <<-EOC
21 define_method :use_ssl= do |val|
22 # does anybody really set it to false?
24 raise _("I can't do secure HTTP, sorry (%{msg})") % {
31 # To handle Gzipped pages
37 attr_accessor :no_cache
38 unless method_defined? :raw_body
42 def body_charset(str=self.raw_body)
43 ctype = self['content-type'] || 'text/html'
44 return nil unless ctype =~ /^text/i || ctype =~ /x(ht)?ml/i
46 charsets = ['latin1'] # should be in config
48 if ctype.match(/charset=["']?([^\s"']+)["']?/i)
50 debug "charset #{charsets.last} added from header"
54 when /<\?xml\s[^>]*encoding=['"]([^\s"'>]+)["'][^>]*\?>/i
56 debug "xml charset #{charsets.last} added from xml pi"
57 when /<(meta\s[^>]*http-equiv=["']?Content-Type["']?[^>]*)>/i
59 if meta =~ /charset=['"]?([^\s'";]+)['"]?/
61 debug "html charset #{charsets.last} added from meta"
68 charsets = self.body_charset(str) or return str
70 charsets.reverse_each do |charset|
71 # XXX: this one is really ugly, but i don't know how to make it better
76 debug "trying #{charset} / offset #{off}"
77 return Iconv.iconv('utf-8//ignore',
79 str.slice(0 .. (-1 - off))).first
81 debug "conversion failed for #{charset} / offset #{off}"
88 def decompress_body(str)
89 method = self['content-encoding']
93 when /gzip/ # Matches gzip, x-gzip, and the non-rfc-compliant gzip;q=\d sent by some servers
94 debug "gunzipping body"
96 return Zlib::GzipReader.new(StringIO.new(str)).read
97 rescue Zlib::Error => e
98 # If we can't unpack the whole stream (e.g. because we're doing a
100 debug "full gunzipping failed (#{e}), trying to recover as much as possible"
103 Zlib::GzipReader.new(StringIO.new(str)).each_byte { |byte|
111 debug "inflating body"
112 # From http://www.koders.com/ruby/fid927B4382397E5115AC0ABE21181AB5C1CBDD5C17.aspx?s=thread:
113 # -MAX_WBITS stops zlib from looking for a zlib header
114 inflater = Zlib::Inflate.new(-Zlib::MAX_WBITS)
116 return inflater.inflate(str)
117 rescue Zlib::Error => e
120 # debug "full inflation failed (#{e}), trying to recover as much as possible"
122 when /^(?:iso-8859-\d+|windows-\d+|utf-8|utf8)$/i
123 # B0rked servers (Freshmeat being one of them) sometimes return the charset
124 # in the content-encoding; in this case we assume that the document has
125 # a standarc content-encoding
126 old_hsh = self.to_hash
127 self['content-type']= self['content-type']+"; charset="+method.downcase
128 warning "Charset vs content-encoding confusion, trying to recover: from\n#{old_hsh.pretty_inspect}to\n#{self.to_hash.pretty_inspect}"
132 raise "Unhandled content encoding #{method}"
137 return self.body_to_utf(self.decompress_body(self.raw_body))
140 # Read chunks from the body until we have at least _size_ bytes, yielding
141 # the partial text at each chunk. Return the partial body.
142 def partial_body(size=0, &block)
147 debug "using body() as partial"
149 yield self.body_to_utf(self.decompress_body(partial)) if block_given?
151 debug "disabling cache"
153 self.read_body { |chunk|
155 yield self.body_to_utf(self.decompress_body(partial)) if block_given?
156 break if size and size > 0 and partial.length >= size
160 return self.body_to_utf(self.decompress_body(partial))
165 Net::HTTP.version_1_2
170 # class for making http requests easier (mainly for plugins to use)
171 # this class can check the bot proxy configuration to determine if a proxy
172 # needs to be used, which includes support for per-url proxy configuration.
174 Bot::Config.register Bot::Config::IntegerValue.new('http.read_timeout',
175 :default => 10, :desc => "Default read timeout for HTTP connections")
176 Bot::Config.register Bot::Config::IntegerValue.new('http.open_timeout',
177 :default => 20, :desc => "Default open timeout for HTTP connections")
178 Bot::Config.register Bot::Config::BooleanValue.new('http.use_proxy',
179 :default => false, :desc => "should a proxy be used for HTTP requests?")
180 Bot::Config.register Bot::Config::StringValue.new('http.proxy_uri', :default => false,
181 :desc => "Proxy server to use for HTTP requests (URI, e.g http://proxy.host:port)")
182 Bot::Config.register Bot::Config::StringValue.new('http.proxy_user',
184 :desc => "User for authenticating with the http proxy (if required)")
185 Bot::Config.register Bot::Config::StringValue.new('http.proxy_pass',
187 :desc => "Password for authenticating with the http proxy (if required)")
188 Bot::Config.register Bot::Config::ArrayValue.new('http.proxy_include',
190 :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")
191 Bot::Config.register Bot::Config::ArrayValue.new('http.proxy_exclude',
193 :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")
194 Bot::Config.register Bot::Config::IntegerValue.new('http.max_redir',
196 :desc => "Maximum number of redirections to be used when getting a document")
197 Bot::Config.register Bot::Config::IntegerValue.new('http.expire_time',
199 :desc => "After how many minutes since last use a cached document is considered to be expired")
200 Bot::Config.register Bot::Config::IntegerValue.new('http.max_cache_time',
202 :desc => "After how many minutes since first use a cached document is considered to be expired")
203 Bot::Config.register Bot::Config::BooleanValue.new('http.no_expire_cache',
205 :desc => "Set this to true if you want the bot to never expire the cached pages")
206 Bot::Config.register Bot::Config::IntegerValue.new('http.info_bytes',
208 :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.")
211 attr_accessor :response, :last_used, :first_used, :count, :expires, :date
213 def self.maybe_new(resp)
214 debug "maybe new #{resp}"
215 return nil if resp.no_cache
216 return nil unless Net::HTTPOK === resp ||
217 Net::HTTPMovedPermanently === resp ||
218 Net::HTTPFound === resp ||
219 Net::HTTPPartialContent === resp
221 cc = resp['cache-control']
222 return nil if cc && (cc =~ /no-cache/i)
226 date = Time.httpdate(d)
229 return nil if resp['expires'] && (Time.httpdate(resp['expires']) < date)
231 debug "creating cache obj"
238 @first_used = now if @count == 0
244 debug "checking expired?"
245 if cc = self.response['cache-control'] && cc =~ /must-revalidate/
248 return self.expires < Time.now
251 def setup_headers(hdr)
252 hdr['if-modified-since'] = self.date.rfc2822
254 debug "ims == #{hdr['if-modified-since']}"
256 if etag = self.response['etag']
257 hdr['if-none-match'] = etag
258 debug "etag: #{etag}"
262 def revalidate(resp = self.response)
265 self.date = resp.key?('date') ? Time.httpdate(resp['date']) : Time.now
267 cc = resp['cache-control']
268 if cc && (cc =~ /max-age=(\d+)/)
269 self.expires = self.date + $1.to_i
270 elsif resp.key?('expires')
271 self.expires = Time.httpdate(resp['expires'])
272 elsif lm = resp['last-modified']
273 delta = self.date - Time.httpdate(lm)
274 delta = 10 if delta <= 0
276 self.expires = self.date + delta
278 self.expires = self.date + 300
280 # self.expires = Time.now + 10 # DEBUG
281 debug "expires on #{self.expires}"
291 self.response.raw_body
292 rescue Exception => e
299 # Create the HttpUtil instance, associating it with Bot _bot_
305 'Accept-Charset' => 'utf-8;q=1.0, *;q=0.8',
306 'Accept-Encoding' => 'gzip;q=1, deflate;q=1, identity;q=0.8, *;q=0.2',
308 "rbot http util #{$version} (#{Irc::Bot::SOURCE_URL})"
310 debug "starting http cache cleanup timer"
311 @timer = @bot.timer.add(300) {
312 self.remove_stale_cache unless @bot.config['http.no_expire_cache']
316 # Clean up on HttpUtil unloading, by stopping the cache cleanup timer.
318 debug 'stopping http cache cleanup timer'
319 @bot.timer.remove(@timer)
322 # This method checks if a proxy is required to access _uri_, by looking at
323 # the values of config values +http.proxy_include+ and +http.proxy_exclude+.
325 # Each of these config values, if set, should be a Regexp the server name and
326 # IP address should be checked against.
328 def proxy_required(uri)
330 if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
336 list.concat Resolv.getaddresses(uri.host)
337 rescue StandardError => err
338 warning "couldn't resolve host uri.host"
341 unless @bot.config["http.proxy_exclude"].empty?
342 re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
352 unless @bot.config["http.proxy_include"].empty?
353 re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
363 debug "using proxy for uri #{uri}?: #{use_proxy}"
367 # _uri_:: URI to create a proxy for
369 # Return a net/http Proxy object, configured for proxying based on the
370 # bot's proxy configuration. See proxy_required for more details on this.
372 def get_proxy(uri, options = {})
374 :read_timeout => @bot.config["http.read_timeout"],
375 :open_timeout => @bot.config["http.open_timeout"]
384 if @bot.config["http.use_proxy"]
385 if (ENV['http_proxy'])
386 proxy = URI.parse ENV['http_proxy'] rescue nil
388 if (@bot.config["http.proxy_uri"])
389 proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
392 debug "proxy is set to #{proxy.host} port #{proxy.port}"
393 if proxy_required(uri)
394 proxy_host = proxy.host
395 proxy_port = proxy.port
396 proxy_user = @bot.config["http.proxy_user"]
397 proxy_pass = @bot.config["http.proxy_pass"]
402 h = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, proxy_user, proxy_pass)
403 h.use_ssl = true if uri.scheme == "https"
405 h.read_timeout = opts[:read_timeout]
406 h.open_timeout = opts[:open_timeout]
410 # Internal method used to hanlde response _resp_ received when making a
411 # request for URI _uri_.
413 # It follows redirects, optionally yielding them if option :yield is :all.
415 # Also yields and returns the final _resp_.
417 def handle_response(uri, resp, opts, &block) # :yields: resp
418 if Net::HTTPRedirection === resp && opts[:max_redir] >= 0
419 if resp.key?('location')
420 raise 'Too many redirections' if opts[:max_redir] <= 0
421 yield resp if opts[:yield] == :all && block_given?
422 # some servers actually provide unescaped location, e.g.
423 # http://ulysses.soup.io/post/60734021/Image%20curve%20ball
424 # rediects to something like
425 # http://ulysses.soup.io/post/60734021/Image curve ball?sessid=8457b2a3752085cca3fb1d79b9965446
426 # causing the URI parser to (obviously) complain. We cannot just
427 # escape blindly, as this would make a mess of already-escaped
428 # locations, so we only do it if the URI.parse fails
429 loc = resp['location']
431 debug "redirect location: #{loc.inspect}"
433 new_loc = URI.join(uri.to_s, loc) rescue URI.parse(loc)
438 loc = URI.escape(loc)
440 debug "escaped redirect location: #{loc.inspect}"
445 new_opts[:max_redir] -= 1
446 case opts[:method].to_s.downcase.intern
447 when :post, :"net::http::post"
448 new_opts[:method] = :get
450 if resp['set-cookie']
451 debug "set cookie request for #{resp['set-cookie']}"
452 cookie, cookie_flags = (resp['set-cookie']+'; ').split('; ', 2)
454 cookie_flags.scan(/(\S+)=(\S+);/) { |key, val|
455 if key.intern == :domain
460 debug "cookie domain #{domain} / #{new_loc.host}"
461 if new_loc.host.rindex(domain) == new_loc.host.length - domain.length
462 debug "setting cookie"
463 new_opts[:headers] ||= Hash.new
464 new_opts[:headers]['Cookie'] = cookie
466 debug "cookie is for another domain, ignoring"
469 debug "following the redirect to #{new_loc}"
470 return get_response(new_loc, new_opts, &block)
472 warning ":| redirect w/o location?"
477 alias :body :cooked_body
479 unless resp['content-type']
480 debug "No content type, guessing"
481 resp['content-type'] =
482 case resp['x-rbot-location']
488 'application/xml+xhtml'
489 when /.(gif|png|jpe?g|jp2|tiff?)$/i
490 "image/#{$1.sub(/^jpg$/,'jpeg').sub(/^tif$/,'tiff')}"
492 'application/octetstream'
498 # Net::HTTP wants us to read the whole body here
504 # _uri_:: uri to query (URI object or String)
506 # Generic http transaction method. It will return a Net::HTTPResponse
507 # object or raise an exception
509 # If a block is given, it will yield the response (see :yield option)
511 # Currently supported _options_:
513 # method:: request method [:get (default), :post or :head]
514 # open_timeout:: open timeout for the proxy
515 # read_timeout:: read timeout for the proxy
516 # cache:: should we cache results?
517 # yield:: if :final [default], calls the block for the response object;
518 # if :all, call the block for all intermediate redirects, too
519 # max_redir:: how many redirects to follow before raising the exception
520 # if -1, don't follow redirects, just return them
521 # range:: make a ranged request (usually GET). accepts a string
522 # for HTTP/1.1 "Range:" header (i.e. "bytes=0-1000")
523 # body:: request body (usually for POST requests)
524 # headers:: additional headers to be set for the request. Its value must
525 # be a Hash in the form { 'Header' => 'value' }
527 def get_response(uri_or_s, options = {}, &block) # :yields: resp
528 uri = uri_or_s.kind_of?(URI) ? uri_or_s : URI.parse(uri_or_s.to_s)
529 unless URI::HTTP === uri
531 raise "#{uri.scheme.inspect} URI scheme is not supported"
533 raise "don't know what to do with #{uri.to_s.inspect}"
538 :max_redir => @bot.config['http.max_redir'],
544 req_class = case opts[:method].to_s.downcase.intern
545 when :head, :"net::http::head"
546 opts[:max_redir] = -1
548 when :get, :"net::http::get"
550 when :post, :"net::http::post"
552 opts[:body] or raise 'post request w/o a body?'
553 warning "refusing to cache POST request" if options[:cache]
556 warning "unsupported method #{opts[:method]}, doing GET"
560 if req_class != Net::HTTP::Get && opts[:range]
561 warning "can't request ranges for #{req_class}"
565 cache_key = "#{opts[:range]}|#{req_class}|#{uri.to_s}"
567 if req_class != Net::HTTP::Get && req_class != Net::HTTP::Head
569 warning "can't cache #{req_class.inspect} requests, working w/o cache"
574 debug "get_response(#{uri}, #{opts.inspect})"
576 cached = @cache[cache_key]
578 if opts[:cache] && cached
583 return handle_response(uri, cached.response, opts, &block)
587 headers = @headers.dup.merge(opts[:headers] || {})
588 headers['Range'] = opts[:range] if opts[:range]
589 headers['Authorization'] = opts[:auth_head] if opts[:auth_head]
591 if opts[:cache] && cached && (req_class == Net::HTTP::Get)
592 cached.setup_headers headers
595 req = req_class.new(uri.request_uri, headers)
596 if uri.user && uri.password
597 req.basic_auth(uri.user, uri.password)
598 opts[:auth_head] = req['Authorization']
600 req.body = opts[:body] if req_class == Net::HTTP::Post
601 debug "prepared request: #{req.to_hash.inspect}"
604 get_proxy(uri, opts).start do |http|
605 http.request(req) do |resp|
606 resp['x-rbot-location'] = uri.to_s
607 if Net::HTTPNotModified === resp
610 cached.revalidate(resp)
611 rescue Exception => e
614 debug "reusing cached"
615 resp = cached.response
616 elsif Net::HTTPServerError === resp || Net::HTTPClientError === resp
617 debug "http error, deleting cached obj" if cached
618 @cache.delete(cache_key)
622 return handle_response(uri, resp, opts, &block)
624 if cached = CachedObject.maybe_new(resp) rescue nil
625 debug "storing to cache"
626 @cache[cache_key] = cached
631 rescue Exception => e
637 # _uri_:: uri to query (URI object or String)
639 # Simple GET request, returns (if possible) response body following redirs
640 # and caching if requested, yielding the actual response(s) to the optional
641 # block. See get_response for details on the supported _options_
643 def get(uri, options = {}, &block) # :yields: resp
645 resp = get_response(uri, options, &block)
646 raise "http error: #{resp}" unless Net::HTTPOK === resp ||
647 Net::HTTPPartialContent === resp
649 rescue Exception => e
655 # _uri_:: uri to query (URI object or String)
657 # Simple HEAD request, returns (if possible) response head following redirs
658 # and caching if requested, yielding the actual response(s) to the optional
659 # block. See get_response for details on the supported _options_
661 def head(uri, options = {}, &block) # :yields: resp
662 opts = {:method => :head}.merge(options)
664 resp = get_response(uri, opts, &block)
665 # raise "http error #{resp}" if Net::HTTPClientError === resp ||
666 # Net::HTTPServerError == resp
668 rescue Exception => e
674 # _uri_:: uri to query (URI object or String)
675 # _data_:: body of the POST
677 # Simple POST request, returns (if possible) response following redirs and
678 # caching if requested, yielding the response(s) to the optional block. See
679 # get_response for details on the supported _options_
681 def post(uri, data, options = {}, &block) # :yields: resp
682 opts = {:method => :post, :body => data, :cache => false}.merge(options)
684 resp = get_response(uri, opts, &block)
685 raise 'http error' unless Net::HTTPOK === resp or Net::HTTPCreated === resp
687 rescue Exception => e
693 # _uri_:: uri to query (URI object or String)
694 # _nbytes_:: number of bytes to get
696 # Partial GET request, returns (if possible) the first _nbytes_ bytes of the
697 # response body, following redirs and caching if requested, yielding the
698 # actual response(s) to the optional block. See get_response for details on
699 # the supported _options_
701 def get_partial(uri, nbytes = @bot.config['http.info_bytes'], options = {}, &block) # :yields: resp
702 opts = {:range => "bytes=0-#{nbytes}"}.merge(options)
703 return get(uri, opts, &block)
706 def remove_stale_cache
707 debug "Removing stale cache"
709 max_last = @bot.config['http.expire_time'] * 60
710 max_first = @bot.config['http.max_cache_time'] * 60
711 debug "#{@cache.size} pages before"
713 @cache.reject! { |k, val|
714 (now - val.last_used > max_last) || (now - val.first_used > max_first)
717 error "Failed to remove stale cache: #{e.pretty_inspect}"
719 debug "#{@cache.size} pages after"
726 class HttpUtilPlugin < CoreBotModule
729 debug 'initializing httputil'
730 @bot.httputil = Irc::Utils::HttpUtil.new(@bot)
734 debug 'shutting down httputil'
735 @bot.httputil.cleanup