]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/httputil.rb
httputil: try to guess content-type from extension if it's not defined
[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       else
105         raise "Unhandled content encoding #{method}"
106       end
107     end
108
109     def cooked_body
110       return self.body_to_utf(self.decompress_body(self.raw_body))
111     end
112
113     # Read chunks from the body until we have at least _size_ bytes, yielding
114     # the partial text at each chunk. Return the partial body.
115     def partial_body(size=0, &block)
116
117       self.no_cache = true
118       partial = String.new
119
120       self.read_body { |chunk|
121         partial << chunk
122         yield self.body_to_utf(self.decompress_body(partial)) if block_given?
123         break if size and size > 0 and partial.length >= size
124       }
125
126       return self.body_to_utf(self.decompress_body(partial))
127     end
128   end
129 end
130
131 Net::HTTP.version_1_2
132
133 module ::Irc
134 module Utils
135
136 # class for making http requests easier (mainly for plugins to use)
137 # this class can check the bot proxy configuration to determine if a proxy
138 # needs to be used, which includes support for per-url proxy configuration.
139 class HttpUtil
140     Bot::Config.register Bot::Config::BooleanValue.new('http.use_proxy',
141       :default => false, :desc => "should a proxy be used for HTTP requests?")
142     Bot::Config.register Bot::Config::StringValue.new('http.proxy_uri', :default => false,
143       :desc => "Proxy server to use for HTTP requests (URI, e.g http://proxy.host:port)")
144     Bot::Config.register Bot::Config::StringValue.new('http.proxy_user',
145       :default => nil,
146       :desc => "User for authenticating with the http proxy (if required)")
147     Bot::Config.register Bot::Config::StringValue.new('http.proxy_pass',
148       :default => nil,
149       :desc => "Password for authenticating with the http proxy (if required)")
150     Bot::Config.register Bot::Config::ArrayValue.new('http.proxy_include',
151       :default => [],
152       :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")
153     Bot::Config.register Bot::Config::ArrayValue.new('http.proxy_exclude',
154       :default => [],
155       :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")
156     Bot::Config.register Bot::Config::IntegerValue.new('http.max_redir',
157       :default => 5,
158       :desc => "Maximum number of redirections to be used when getting a document")
159     Bot::Config.register Bot::Config::IntegerValue.new('http.expire_time',
160       :default => 60,
161       :desc => "After how many minutes since last use a cached document is considered to be expired")
162     Bot::Config.register Bot::Config::IntegerValue.new('http.max_cache_time',
163       :default => 60*24,
164       :desc => "After how many minutes since first use a cached document is considered to be expired")
165     Bot::Config.register Bot::Config::IntegerValue.new('http.no_expire_cache',
166       :default => false,
167       :desc => "Set this to true if you want the bot to never expire the cached pages")
168     Bot::Config.register Bot::Config::IntegerValue.new('http.info_bytes',
169       :default => 8192,
170       :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.")
171
172   class CachedObject
173     attr_accessor :response, :last_used, :first_used, :count, :expires, :date
174
175     def self.maybe_new(resp)
176       debug "maybe new #{resp}"
177       return nil if resp.no_cache
178       return nil unless Net::HTTPOK === resp ||
179       Net::HTTPMovedPermanently === resp ||
180       Net::HTTPFound === resp ||
181       Net::HTTPPartialContent === resp
182
183       cc = resp['cache-control']
184       return nil if cc && (cc =~ /no-cache/i)
185
186       date = Time.now
187       if d = resp['date']
188         date = Time.httpdate(d)
189       end
190
191       return nil if resp['expires'] && (Time.httpdate(resp['expires']) < date)
192
193       debug "creating cache obj"
194
195       self.new(resp)
196     end
197
198     def use
199       now = Time.now
200       @first_used = now if @count == 0
201       @last_used = now
202       @count += 1
203     end
204
205     def expired?
206       debug "checking expired?"
207       if cc = self.response['cache-control'] && cc =~ /must-revalidate/
208         return true
209       end
210       return self.expires < Time.now
211     end
212
213     def setup_headers(hdr)
214       hdr['if-modified-since'] = self.date.rfc2822
215
216       debug "ims == #{hdr['if-modified-since']}"
217
218       if etag = self.response['etag']
219         hdr['if-none-match'] = etag
220         debug "etag: #{etag}"
221       end
222     end
223
224     def revalidate(resp = self.response)
225       @count = 0
226       self.use
227       self.date = resp.key?('date') ? Time.httpdate(resp['date']) : Time.now
228
229       cc = resp['cache-control']
230       if cc && (cc =~ /max-age=(\d+)/)
231         self.expires = self.date + $1.to_i
232       elsif resp.key?('expires')
233         self.expires = Time.httpdate(resp['expires'])
234       elsif lm = resp['last-modified']
235         delta = self.date - Time.httpdate(lm)
236         delta = 10 if delta <= 0
237         delta /= 5
238         self.expires = self.date + delta
239       else
240         self.expires = self.date + 300
241       end
242       # self.expires = Time.now + 10 # DEBUG
243       debug "expires on #{self.expires}"
244
245       return true
246     end
247
248     private
249     def initialize(resp)
250       @response = resp
251       begin
252         self.revalidate
253         self.response.raw_body
254       rescue Exception => e
255         error e
256         raise e
257       end
258     end
259   end
260
261   # Create the HttpUtil instance, associating it with Bot _bot_
262   #
263   def initialize(bot)
264     @bot = bot
265     @cache = Hash.new
266     @headers = {
267       'Accept-Charset' => 'utf-8;q=1.0, *;q=0.8',
268       'Accept-Encoding' => 'gzip;q=1, identity;q=0.8, *;q=0.2',
269       'User-Agent' =>
270         "rbot http util #{$version} (http://linuxbrit.co.uk/rbot/)"
271     }
272     debug "starting http cache cleanup timer"
273     @timer = @bot.timer.add(300) {
274       self.remove_stale_cache unless @bot.config['http.no_expire_cache']
275     }
276   end
277
278   # Clean up on HttpUtil unloading, by stopping the cache cleanup timer.
279   def cleanup
280     debug 'stopping http cache cleanup timer'
281     @bot.timer.remove(@timer)
282   end
283
284   # This method checks if a proxy is required to access _uri_, by looking at
285   # the values of config values +http.proxy_include+ and +http.proxy_exclude+.
286   #
287   # Each of these config values, if set, should be a Regexp the server name and
288   # IP address should be checked against.
289   #
290   def proxy_required(uri)
291     use_proxy = true
292     if @bot.config["http.proxy_exclude"].empty? && @bot.config["http.proxy_include"].empty?
293       return use_proxy
294     end
295
296     list = [uri.host]
297     begin
298       list.concat Resolv.getaddresses(uri.host)
299     rescue StandardError => err
300       warning "couldn't resolve host uri.host"
301     end
302
303     unless @bot.config["http.proxy_exclude"].empty?
304       re = @bot.config["http.proxy_exclude"].collect{|r| Regexp.new(r)}
305       re.each do |r|
306         list.each do |item|
307           if r.match(item)
308             use_proxy = false
309             break
310           end
311         end
312       end
313     end
314     unless @bot.config["http.proxy_include"].empty?
315       re = @bot.config["http.proxy_include"].collect{|r| Regexp.new(r)}
316       re.each do |r|
317         list.each do |item|
318           if r.match(item)
319             use_proxy = true
320             break
321           end
322         end
323       end
324     end
325     debug "using proxy for uri #{uri}?: #{use_proxy}"
326     return use_proxy
327   end
328
329   # _uri_:: URI to create a proxy for
330   #
331   # Return a net/http Proxy object, configured for proxying based on the
332   # bot's proxy configuration. See proxy_required for more details on this.
333   #
334   def get_proxy(uri, options = {})
335     opts = {
336       :read_timeout => 10,
337       :open_timeout => 20
338     }.merge(options)
339
340     proxy = nil
341     proxy_host = nil
342     proxy_port = nil
343     proxy_user = nil
344     proxy_pass = nil
345
346     if @bot.config["http.use_proxy"]
347       if (ENV['http_proxy'])
348         proxy = URI.parse ENV['http_proxy'] rescue nil
349       end
350       if (@bot.config["http.proxy_uri"])
351         proxy = URI.parse @bot.config["http.proxy_uri"] rescue nil
352       end
353       if proxy
354         debug "proxy is set to #{proxy.host} port #{proxy.port}"
355         if proxy_required(uri)
356           proxy_host = proxy.host
357           proxy_port = proxy.port
358           proxy_user = @bot.config["http.proxy_user"]
359           proxy_pass = @bot.config["http.proxy_pass"]
360         end
361       end
362     end
363
364     h = Net::HTTP.new(uri.host, uri.port, proxy_host, proxy_port, proxy_user, proxy_port)
365     h.use_ssl = true if uri.scheme == "https"
366
367     h.read_timeout = opts[:read_timeout]
368     h.open_timeout = opts[:open_timeout]
369     return h
370   end
371
372   # Internal method used to hanlde response _resp_ received when making a
373   # request for URI _uri_.
374   #
375   # It follows redirects, optionally yielding them if option :yield is :all.
376   #
377   # Also yields and returns the final _resp_.
378   #
379   def handle_response(uri, resp, opts, &block) # :yields: resp
380     if Net::HTTPRedirection === resp && opts[:max_redir] >= 0
381       if resp.key?('location')
382         raise 'Too many redirections' if opts[:max_redir] <= 0
383         yield resp if opts[:yield] == :all && block_given?
384         loc = resp['location']
385         new_loc = URI.join(uri.to_s, loc) rescue URI.parse(loc)
386         new_opts = opts.dup
387         new_opts[:max_redir] -= 1
388         case opts[:method].to_s.downcase.intern
389         when :post, :"net::http::post"
390           new_opts[:method] = :get
391         end
392         if resp['set-cookie']
393           debug "setting cookie #{resp['set-cookie']}"
394           new_opts[:headers] ||= Hash.new
395           new_opts[:headers]['Cookie'] = resp['set-cookie']
396         end
397         debug "following the redirect to #{new_loc}"
398         return get_response(new_loc, new_opts, &block)
399       else
400         warning ":| redirect w/o location?"
401       end
402     end
403     class << resp
404       undef_method :body
405       alias :body :cooked_body
406     end
407     unless resp['content-type']
408       debug "No content type, guessing"
409       resp['content-type'] =
410         case resp['x-rbot-location']
411         when /.html?$/i
412           'text/html'
413         when /.xml$/i
414           'application/xml'
415         when /.xhtml$/i
416           'application/xml+xhtml'
417         when /.(gif|png|jpe?g|jp2|tiff?)$/i
418           "image/#{$1.sub(/^jpg$/,'jpeg').sub(/^tif$/,'tiff')}"
419         else
420           'application/octetstream'
421         end
422     end
423     if block_given?
424       yield(resp)
425     else
426       # Net::HTTP wants us to read the whole body here
427       resp.raw_body
428     end
429     return resp
430   end
431
432   # _uri_::     uri to query (URI object or String)
433   #
434   # Generic http transaction method. It will return a Net::HTTPResponse
435   # object or raise an exception
436   #
437   # If a block is given, it will yield the response (see :yield option)
438   #
439   # Currently supported _options_:
440   #
441   # method::     request method [:get (default), :post or :head]
442   # open_timeout::     open timeout for the proxy
443   # read_timeout::     read timeout for the proxy
444   # cache::            should we cache results?
445   # yield::      if :final [default], calls the block for the response object;
446   #              if :all, call the block for all intermediate redirects, too
447   # max_redir::  how many redirects to follow before raising the exception
448   #              if -1, don't follow redirects, just return them
449   # range::      make a ranged request (usually GET). accepts a string
450   #              for HTTP/1.1 "Range:" header (i.e. "bytes=0-1000")
451   # body::       request body (usually for POST requests)
452   # headers::    additional headers to be set for the request. Its value must
453   #              be a Hash in the form { 'Header' => 'value' }
454   #
455   def get_response(uri_or_s, options = {}, &block) # :yields: resp
456     uri = uri_or_s.kind_of?(URI) ? uri_or_s : URI.parse(uri_or_s.to_s)
457     opts = {
458       :max_redir => @bot.config['http.max_redir'],
459       :yield => :final,
460       :cache => true,
461       :method => :GET
462     }.merge(options)
463
464     resp = nil
465     cached = nil
466
467     req_class = case opts[:method].to_s.downcase.intern
468                 when :head, :"net::http::head"
469                   opts[:max_redir] = -1
470                   Net::HTTP::Head
471                 when :get, :"net::http::get"
472                   Net::HTTP::Get
473                 when :post, :"net::http::post"
474                   opts[:cache] = false
475                   opts[:body] or raise 'post request w/o a body?'
476                   warning "refusing to cache POST request" if options[:cache]
477                   Net::HTTP::Post
478                 else
479                   warning "unsupported method #{opts[:method]}, doing GET"
480                   Net::HTTP::Get
481                 end
482
483     if req_class != Net::HTTP::Get && opts[:range]
484       warning "can't request ranges for #{req_class}"
485       opts.delete(:range)
486     end
487
488     cache_key = "#{opts[:range]}|#{req_class}|#{uri.to_s}"
489
490     if req_class != Net::HTTP::Get && req_class != Net::HTTP::Head
491       if opts[:cache]
492         warning "can't cache #{req_class.inspect} requests, working w/o cache"
493         opts[:cache] = false
494       end
495     end
496
497     debug "get_response(#{uri}, #{opts.inspect})"
498
499     if opts[:cache] && cached = @cache[cache_key]
500       debug "got cached"
501       if !cached.expired?
502         debug "using cached"
503         cached.use
504         return handle_response(uri, cached.response, opts, &block)
505       end
506     end
507
508     headers = @headers.dup.merge(opts[:headers] || {})
509     headers['Range'] = opts[:range] if opts[:range]
510     headers['Authorization'] = opts[:auth_head] if opts[:auth_head]
511
512     cached.setup_headers(headers) if cached && (req_class == Net::HTTP::Get)
513     req = req_class.new(uri.request_uri, headers)
514     if uri.user && uri.password
515       req.basic_auth(uri.user, uri.password)
516       opts[:auth_head] = req['Authorization']
517     end
518     req.body = opts[:body] if req_class == Net::HTTP::Post
519     debug "prepared request: #{req.to_hash.inspect}"
520
521     begin
522     get_proxy(uri, opts).start do |http|
523       http.request(req) do |resp|
524         resp['x-rbot-location'] = uri.to_s
525         if Net::HTTPNotModified === resp
526           debug "not modified"
527           begin
528             cached.revalidate(resp)
529           rescue Exception => e
530             error e
531           end
532           debug "reusing cached"
533           resp = cached.response
534         elsif Net::HTTPServerError === resp || Net::HTTPClientError === resp
535           debug "http error, deleting cached obj" if cached
536           @cache.delete(cache_key)
537         elsif opts[:cache]
538           begin
539             return handle_response(uri, resp, opts, &block)
540           ensure
541             if cached = CachedObject.maybe_new(resp) rescue nil
542               debug "storing to cache"
543               @cache[cache_key] = cached
544             end
545           end
546           return ret
547         end
548         return handle_response(uri, resp, opts, &block)
549       end
550     end
551     rescue Exception => e
552       error e
553       raise e.message
554     end
555   end
556
557   # _uri_::     uri to query (URI object or String)
558   #
559   # Simple GET request, returns (if possible) response body following redirs
560   # and caching if requested, yielding the actual response(s) to the optional
561   # block. See get_response for details on the supported _options_
562   #
563   def get(uri, options = {}, &block) # :yields: resp
564     begin
565       resp = get_response(uri, options, &block)
566       raise "http error: #{resp}" unless Net::HTTPOK === resp ||
567         Net::HTTPPartialContent === resp
568       return resp.body
569     rescue Exception => e
570       error e
571     end
572     return nil
573   end
574
575   # _uri_::     uri to query (URI object or String)
576   #
577   # Simple HEAD request, returns (if possible) response head following redirs
578   # and caching if requested, yielding the actual response(s) to the optional
579   # block. See get_response for details on the supported _options_
580   #
581   def head(uri, options = {}, &block) # :yields: resp
582     opts = {:method => :head}.merge(options)
583     begin
584       resp = get_response(uri, opts, &block)
585       raise "http error #{resp}" if Net::HTTPClientError === resp ||
586         Net::HTTPServerError == resp
587       return resp
588     rescue Exception => e
589       error e
590     end
591     return nil
592   end
593
594   # _uri_::     uri to query (URI object or String)
595   # _data_::    body of the POST
596   #
597   # Simple POST request, returns (if possible) response following redirs and
598   # caching if requested, yielding the response(s) to the optional block. See
599   # get_response for details on the supported _options_
600   #
601   def post(uri, data, options = {}, &block) # :yields: resp
602     opts = {:method => :post, :body => data, :cache => false}.merge(options)
603     begin
604       resp = get_response(uri, opts, &block)
605       raise 'http error' unless Net::HTTPOK === resp
606       return resp
607     rescue Exception => e
608       error e
609     end
610     return nil
611   end
612
613   # _uri_::     uri to query (URI object or String)
614   # _nbytes_::  number of bytes to get
615   #
616   # Partia GET request, returns (if possible) the first _nbytes_ bytes of the
617   # response body, following redirs and caching if requested, yielding the
618   # actual response(s) to the optional block. See get_response for details on
619   # the supported _options_
620   #
621   def get_partial(uri, nbytes = @bot.config['http.info_bytes'], options = {}, &block) # :yields: resp
622     opts = {:range => "bytes=0-#{nbytes}"}.merge(options)
623     return get(uri, opts, &block)
624   end
625
626   def remove_stale_cache
627     debug "Removing stale cache"
628     now = Time.new
629     max_last = @bot.config['http.expire_time'] * 60
630     max_first = @bot.config['http.max_cache_time'] * 60
631     debug "#{@cache.size} pages before"
632     begin
633       @cache.reject! { |k, val|
634         (now - val.last_used > max_last) || (now - val.first_used > max_first)
635       }
636     rescue => e
637       error "Failed to remove stale cache: #{e.pretty_inspect}"
638     end
639     debug "#{@cache.size} pages after"
640   end
641
642 end
643 end
644 end
645
646 class HttpUtilPlugin < CoreBotModule
647   def initialize(*a)
648     super(*a)
649     debug 'initializing httputil'
650     @bot.httputil = Irc::Utils::HttpUtil.new(@bot)
651   end
652
653   def cleanup
654     debug 'shutting down httputil'
655     @bot.httputil.cleanup
656     @bot.httputil = nil
657     super
658   end
659 end
660
661 HttpUtilPlugin.new