]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/httputil.rb
httputil: inform the servers we also accept deflate
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / httputil.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: rbot HTTP provider
5 #
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>
9 #
10 # Copyright:: (C) 2002-2005 Tom Gilbert
11 # Copyright:: (C) 2006 Tom Gilbert, Giuseppe Bilotta
12 # Copyright:: (C) 2007 Giuseppe Bilotta, Dmitry Kim
13
14 require 'resolv'
15 require 'net/http'
16 require 'cgi'
17 require 'iconv'
18 begin
19   require 'net/https'
20 rescue LoadError => e
21   error "Couldn't load 'net/https':  #{e.pretty_inspect}"
22   error "Secured HTTP connections will fail"
23 end
24
25 # To handle Gzipped pages
26 require 'stringio'
27 require 'zlib'
28
29 module ::Net
30   class HTTPResponse
31     attr_accessor :no_cache
32     if !instance_methods.include?('raw_body')
33       alias :raw_body :body
34     end
35
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
39
40       charsets = ['latin1'] # should be in config
41
42       if ctype.match(/charset=["']?([^\s"']+)["']?/i)
43         charsets << $1
44         debug "charset #{charsets.last} added from header"
45       end
46
47       case str
48       when /<\?xml\s[^>]*encoding=['"]([^\s"'>]+)["'][^>]*\?>/i
49         charsets << $1
50         debug "xml charset #{charsets.last} added from xml pi"
51       when /<(meta\s[^>]*http-equiv=["']?Content-Type["']?[^>]*)>/i
52         meta = $1
53         if meta =~ /charset=['"]?([^\s'";]+)['"]?/
54           charsets << $1
55           debug "html charset #{charsets.last} added from meta"
56         end
57       end
58       return charsets.uniq
59     end
60
61     def body_to_utf(str)
62       charsets = self.body_charset(str) or return str
63
64       charsets.reverse_each do |charset|
65         # XXX: this one is really ugly, but i don't know how to make it better
66         #  -jsn
67
68         0.upto(5) do |off|
69           begin
70             debug "trying #{charset} / offset #{off}"
71             return Iconv.iconv('utf-8//ignore',
72                                charset,
73                                str.slice(0 .. (-1 - off))).first
74           rescue
75             debug "conversion failed for #{charset} / offset #{off}"
76           end
77         end
78       end
79       return str
80     end
81
82     def decompress_body(str)
83       method = self['content-encoding']
84       case method
85       when nil
86         return str
87       when /gzip/ # Matches gzip, x-gzip, and the non-rfc-compliant gzip;q=\d sent by some servers
88         debug "gunzipping body"
89         begin
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
93           # partial read
94           debug "full gunzipping failed (#{e}), trying to recover as much as possible"
95           ret = ""
96           begin
97             Zlib::GzipReader.new(StringIO.new(str)).each_byte { |byte|
98               ret << byte
99             }
100           rescue
101           end
102           return ret
103         end
104       when 'deflate'
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)
109         begin
110           return inflater.inflate(str)
111         rescue Zlib::Error => e
112           raise e
113           # TODO
114           # debug "full inflation failed (#{e}), trying to recover as much as possible"
115         end
116       else
117         raise "Unhandled content encoding #{method}"
118       end
119     end
120
121     def cooked_body
122       return self.body_to_utf(self.decompress_body(self.raw_body))
123     end
124
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)
128
129       self.no_cache = true
130       partial = String.new
131
132       self.read_body { |chunk|
133         partial << 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
136       }
137
138       return self.body_to_utf(self.decompress_body(partial))
139     end
140   end
141 end
142
143 Net::HTTP.version_1_2
144
145 module ::Irc
146 module Utils
147
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.
151 class HttpUtil
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',
157       :default => nil,
158       :desc => "User for authenticating with the http proxy (if required)")
159     Bot::Config.register Bot::Config::StringValue.new('http.proxy_pass',
160       :default => nil,
161       :desc => "Password for authenticating with the http proxy (if required)")
162     Bot::Config.register Bot::Config::ArrayValue.new('http.proxy_include',
163       :default => [],
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',
166       :default => [],
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',
169       :default => 5,
170       :desc => "Maximum number of redirections to be used when getting a document")
171     Bot::Config.register Bot::Config::IntegerValue.new('http.expire_time',
172       :default => 60,
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',
175       :default => 60*24,
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',
178       :default => false,
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',
181       :default => 8192,
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.")
183
184   class CachedObject
185     attr_accessor :response, :last_used, :first_used, :count, :expires, :date
186
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
194
195       cc = resp['cache-control']
196       return nil if cc && (cc =~ /no-cache/i)
197
198       date = Time.now
199       if d = resp['date']
200         date = Time.httpdate(d)
201       end
202
203       return nil if resp['expires'] && (Time.httpdate(resp['expires']) < date)
204
205       debug "creating cache obj"
206
207       self.new(resp)
208     end
209
210     def use
211       now = Time.now
212       @first_used = now if @count == 0
213       @last_used = now
214       @count += 1
215     end
216
217     def expired?
218       debug "checking expired?"
219       if cc = self.response['cache-control'] && cc =~ /must-revalidate/
220         return true
221       end
222       return self.expires < Time.now
223     end
224
225     def setup_headers(hdr)
226       hdr['if-modified-since'] = self.date.rfc2822
227
228       debug "ims == #{hdr['if-modified-since']}"
229
230       if etag = self.response['etag']
231         hdr['if-none-match'] = etag
232         debug "etag: #{etag}"
233       end
234     end
235
236     def revalidate(resp = self.response)
237       @count = 0
238       self.use
239       self.date = resp.key?('date') ? Time.httpdate(resp['date']) : Time.now
240
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
249         delta /= 5
250         self.expires = self.date + delta
251       else
252         self.expires = self.date + 300
253       end
254       # self.expires = Time.now + 10 # DEBUG
255       debug "expires on #{self.expires}"
256
257       return true
258     end
259
260     private
261     def initialize(resp)
262       @response = resp
263       begin
264         self.revalidate
265         self.response.raw_body
266       rescue Exception => e
267         error e
268         raise e
269       end
270     end
271   end
272
273   # Create the HttpUtil instance, associating it with Bot _bot_
274   #
275   def initialize(bot)
276     @bot = bot
277     @cache = Hash.new
278     @headers = {
279       'Accept-Charset' => 'utf-8;q=1.0, *;q=0.8',
280       'Accept-Encoding' => 'gzip;q=1, deflate;q=1, identity;q=0.8, *;q=0.2',
281       'User-Agent' =>
282         "rbot http util #{$version} (http://linuxbrit.co.uk/rbot/)"
283     }
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']
287     }
288   end
289
290   # Clean up on HttpUtil unloading, by stopping the cache cleanup timer.
291   def cleanup
292     debug 'stopping http cache cleanup timer'
293     @bot.timer.remove(@timer)
294   end
295
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+.
298   #
299   # Each of these config values, if set, should be a Regexp the server name and
300   # IP address should be checked against.
301   #
302   def proxy_required(uri)
303     use_proxy = true
304     if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
305       return use_proxy
306     end
307
308     list = [uri.host]
309     begin
310       list.concat Resolv.getaddresses(uri.host)
311     rescue StandardError => err
312       warning "couldn't resolve host uri.host"
313     end
314
315     unless @bot.config["http.proxy_exclude"].empty?
316       re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
317       re.each do |r|
318         list.each do |item|
319           if r.match(item)
320             use_proxy = false
321             break
322           end
323         end
324       end
325     end
326     unless @bot.config["http.proxy_include"].empty?
327       re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
328       re.each do |r|
329         list.each do |item|
330           if r.match(item)
331             use_proxy = true
332             break
333           end
334         end
335       end
336     end
337     debug "using proxy for uri #{uri}?: #{use_proxy}"
338     return use_proxy
339   end
340
341   # _uri_:: URI to create a proxy for
342   #
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.
345   #
346   def get_proxy(uri, options = {})
347     opts = {
348       :read_timeout => 10,
349       :open_timeout => 20
350     }.merge(options)
351
352     proxy = nil
353     proxy_host = nil
354     proxy_port = nil
355     proxy_user = nil
356     proxy_pass = nil
357
358     if @bot.config["http.use_proxy"]
359       if (ENV['http_proxy'])
360         proxy = URI.parse ENV['http_proxy'] rescue nil
361       end
362       if (@bot.config["http.proxy_uri"])
363         proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
364       end
365       if proxy
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"]
372         end
373       end
374     end
375
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"
378
379     h.read_timeout = opts[:read_timeout]
380     h.open_timeout = opts[:open_timeout]
381     return h
382   end
383
384   # Internal method used to hanlde response _resp_ received when making a
385   # request for URI _uri_.
386   #
387   # It follows redirects, optionally yielding them if option :yield is :all.
388   #
389   # Also yields and returns the final _resp_.
390   #
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)
398         new_opts = opts.dup
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
403         end
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']
408         end
409         debug "following the redirect to #{new_loc}"
410         return get_response(new_loc, new_opts, &block)
411       else
412         warning ":| redirect w/o location?"
413       end
414     end
415     class << resp
416       undef_method :body
417       alias :body :cooked_body
418     end
419     unless resp['content-type']
420       debug "No content type, guessing"
421       resp['content-type'] =
422         case resp['x-rbot-location']
423         when /.html?$/i
424           'text/html'
425         when /.xml$/i
426           'application/xml'
427         when /.xhtml$/i
428           'application/xml+xhtml'
429         when /.(gif|png|jpe?g|jp2|tiff?)$/i
430           "image/#{$1.sub(/^jpg$/,'jpeg').sub(/^tif$/,'tiff')}"
431         else
432           'application/octetstream'
433         end
434     end
435     if block_given?
436       yield(resp)
437     else
438       # Net::HTTP wants us to read the whole body here
439       resp.raw_body
440     end
441     return resp
442   end
443
444   # _uri_::     uri to query (URI object or String)
445   #
446   # Generic http transaction method. It will return a Net::HTTPResponse
447   # object or raise an exception
448   #
449   # If a block is given, it will yield the response (see :yield option)
450   #
451   # Currently supported _options_:
452   #
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' }
466   #
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)
469     opts = {
470       :max_redir => @bot.config['http.max_redir'],
471       :yield => :final,
472       :cache => true,
473       :method => :GET
474     }.merge(options)
475
476     resp = nil
477     cached = nil
478
479     req_class = case opts[:method].to_s.downcase.intern
480                 when :head, :"net::http::head"
481                   opts[:max_redir] = -1
482                   Net::HTTP::Head
483                 when :get, :"net::http::get"
484                   Net::HTTP::Get
485                 when :post, :"net::http::post"
486                   opts[:cache] = false
487                   opts[:body] or raise 'post request w/o a body?'
488                   warning "refusing to cache POST request" if options[:cache]
489                   Net::HTTP::Post
490                 else
491                   warning "unsupported method #{opts[:method]}, doing GET"
492                   Net::HTTP::Get
493                 end
494
495     if req_class != Net::HTTP::Get && opts[:range]
496       warning "can't request ranges for #{req_class}"
497       opts.delete(:range)
498     end
499
500     cache_key = "#{opts[:range]}|#{req_class}|#{uri.to_s}"
501
502     if req_class != Net::HTTP::Get && req_class != Net::HTTP::Head
503       if opts[:cache]
504         warning "can't cache #{req_class.inspect} requests, working w/o cache"
505         opts[:cache] = false
506       end
507     end
508
509     debug "get_response(#{uri}, #{opts.inspect})"
510
511     if opts[:cache] && cached = @cache[cache_key]
512       debug "got cached"
513       if !cached.expired?
514         debug "using cached"
515         cached.use
516         return handle_response(uri, cached.response, opts, &block)
517       end
518     end
519
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]
523
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']
529     end
530     req.body = opts[:body] if req_class == Net::HTTP::Post
531     debug "prepared request: #{req.to_hash.inspect}"
532
533     begin
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
538           debug "not modified"
539           begin
540             cached.revalidate(resp)
541           rescue Exception => e
542             error e
543           end
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)
549         elsif opts[:cache]
550           begin
551             return handle_response(uri, resp, opts, &block)
552           ensure
553             if cached = CachedObject.maybe_new(resp) rescue nil
554               debug "storing to cache"
555               @cache[cache_key] = cached
556             end
557           end
558           return ret
559         end
560         return handle_response(uri, resp, opts, &block)
561       end
562     end
563     rescue Exception => e
564       error e
565       raise e.message
566     end
567   end
568
569   # _uri_::     uri to query (URI object or String)
570   #
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_
574   #
575   def get(uri, options = {}, &block) # :yields: resp
576     begin
577       resp = get_response(uri, options, &block)
578       raise "http error: #{resp}" unless Net::HTTPOK === resp ||
579         Net::HTTPPartialContent === resp
580       return resp.body
581     rescue Exception => e
582       error e
583     end
584     return nil
585   end
586
587   # _uri_::     uri to query (URI object or String)
588   #
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_
592   #
593   def head(uri, options = {}, &block) # :yields: resp
594     opts = {:method => :head}.merge(options)
595     begin
596       resp = get_response(uri, opts, &block)
597       raise "http error #{resp}" if Net::HTTPClientError === resp ||
598         Net::HTTPServerError == resp
599       return resp
600     rescue Exception => e
601       error e
602     end
603     return nil
604   end
605
606   # _uri_::     uri to query (URI object or String)
607   # _data_::    body of the POST
608   #
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_
612   #
613   def post(uri, data, options = {}, &block) # :yields: resp
614     opts = {:method => :post, :body => data, :cache => false}.merge(options)
615     begin
616       resp = get_response(uri, opts, &block)
617       raise 'http error' unless Net::HTTPOK === resp
618       return resp
619     rescue Exception => e
620       error e
621     end
622     return nil
623   end
624
625   # _uri_::     uri to query (URI object or String)
626   # _nbytes_::  number of bytes to get
627   #
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_
632   #
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)
636   end
637
638   def remove_stale_cache
639     debug "Removing stale cache"
640     now = Time.new
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"
644     begin
645       @cache.reject! { |k, val|
646         (now - val.last_used > max_last) || (now - val.first_used > max_first)
647       }
648     rescue => e
649       error "Failed to remove stale cache: #{e.pretty_inspect}"
650     end
651     debug "#{@cache.size} pages after"
652   end
653
654 end
655 end
656 end
657
658 class HttpUtilPlugin < CoreBotModule
659   def initialize(*a)
660     super(*a)
661     debug 'initializing httputil'
662     @bot.httputil = Irc::Utils::HttpUtil.new(@bot)
663   end
664
665   def cleanup
666     debug 'shutting down httputil'
667     @bot.httputil.cleanup
668     @bot.httputil = nil
669     super
670   end
671 end
672
673 HttpUtilPlugin.new