]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/webservice.rb
web service: parse uri params; small improvements
[user/henk/code/ruby/rbot.git] / lib / rbot / core / webservice.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Web service for bot
5 #
6 # Author:: Matthias Hecker (apoc@geekosphere.org)
7 #
8 # HTTP(S)/json based web service for remote controlling the bot,
9 # similar to remote but much more portable.
10 #
11 # For more info/documentation:
12 # https://github.com/4poc/rbot/wiki/Web-Service
13 #
14
15 require 'webrick'
16 require 'webrick/https'
17 require 'openssl'
18 require 'cgi'
19 require 'json'
20
21 module ::Irc
22 class Bot
23     # A WebMessage is a web request and response object combined with helper methods.
24     #
25     class WebMessage
26       # Bot instance
27       #
28       attr_reader :bot
29       # HTTP method (POST, GET, etc.)
30       #
31       attr_reader :method
32       # Request object, a instance of WEBrick::HTTPRequest ({http://www.ruby-doc.org/stdlib-2.0/libdoc/webrick/rdoc/WEBrick/HTTPRequest.html docs})
33       #
34       attr_reader :req
35       # Response object, a instance of WEBrick::HTTPResponse ({http://www.ruby-doc.org/stdlib-2.0/libdoc/webrick/rdoc/WEBrick/HTTPResponse.html docs})
36       #
37       attr_reader :res
38       # Parsed post request parameters.
39       #
40       attr_reader :post
41       # Parsed url parameters.
42       #
43       attr_reader :args
44       # Client IP.
45       # 
46       attr_reader :client
47       # URL Path.
48       #
49       attr_reader :path
50       # The bot user issuing the command.
51       #
52       attr_reader :source
53       def initialize(bot, req, res)
54         @bot = bot
55         @req = req
56         @res = res
57
58         @method = req.request_method
59         @post = {}
60         if req.body and not req.body.empty?
61           @post = parse_query(req.body)
62         end
63         @args = {}
64         if req.query_string and not req.query_string.empty?
65           @args = parse_query(req.query_string)
66         end
67         @client = req.peeraddr[3]
68
69         # login a botuser with http authentication
70         WEBrick::HTTPAuth.basic_auth(req, res, 'RBotAuth') { |username, password|
71           if username
72             botuser = @bot.auth.get_botuser(Auth::BotUser.sanitize_username(username))
73             if botuser and botuser.password == password
74               @source = botuser
75               true
76             end
77             false
78           else
79             true # no need to request auth at this point
80           end
81         }
82
83         @path = req.path
84         debug '@path = ' + @path.inspect
85       end
86
87       def parse_query(query)
88         params = CGI::parse(query)
89         params.each_pair do |key, val|
90           params[key] = val.last
91         end
92         params
93       end
94
95       # The target of a RemoteMessage
96       def target
97         @bot
98       end
99
100       # Remote messages are always 'private'
101       def private?
102         true
103       end
104
105       # Sends a plaintext response
106       def send_plaintext(body, status=200)
107         @res.status = status
108         @res['Content-Type'] = 'text/plain'
109         @res.body = body
110       end
111
112       # Sends a json response
113       def send_json(body, status=200)
114         @res.status = status
115         @res['Content-Type'] = 'application/json'
116         @res.body = body
117       end
118     end
119
120     # works similar to a message mapper but for url paths
121     class WebDispatcher
122       class WebTemplate
123         attr_reader :botmodule, :pattern, :options
124         def initialize(botmodule, pattern, options={})
125           @botmodule = botmodule
126           @pattern = pattern
127           @options = options
128           set_auth_path(@options)
129         end
130
131         def recognize(m)
132           message_route = m.path[1..-1].split('/')
133           template_route = @pattern[1..-1].split('/')
134           params = {}
135
136           debug 'web mapping path %s <-> %s' % [message_route.inspect, template_route.inspect]
137
138           message_route.each do |part|
139             tmpl = template_route.shift
140             return false if not tmpl
141
142             if tmpl[0] == ':'
143               # push part as url path parameter
144               params[tmpl[1..-1].to_sym] = part
145             elsif tmpl == part
146               next
147             else
148               return false
149             end
150           end
151
152           debug 'web mapping params is %s' % [params.inspect]
153
154           params
155         end
156
157         def set_auth_path(hash)
158           if hash.has_key?(:full_auth_path)
159             warning "Web route #{@pattern.inspect} in #{@botmodule} sets :full_auth_path, please don't do this"
160           else
161             pre = @botmodule
162             words = @pattern[1..-1].split('/').reject{ |x|
163               x == pre || x =~ /^:/ || x =~ /\[|\]/
164             }
165             if words.empty?
166               post = nil
167             else
168               post = words.first
169             end
170             if hash.has_key?(:auth_path)
171               extra = hash[:auth_path]
172               if extra.sub!(/^:/, "")
173                 pre += "::" + post
174                 post = nil
175               end
176               if extra.sub!(/:$/, "")
177                 if words.length > 1
178                   post = [post,words[1]].compact.join("::")
179                 end
180               end
181               pre = nil if extra.sub!(/^!/, "")
182               post = nil if extra.sub!(/!$/, "")
183               extra = nil if extra.empty?
184             else
185               extra = nil
186             end
187             hash[:full_auth_path] = [pre,extra,post].compact.join("::")
188             debug "Web route #{@pattern} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
189           end
190         end
191       end
192
193       def initialize(bot)
194         @bot = bot
195         @templates = []
196       end
197
198       def map(botmodule, pattern, options={})
199         @templates << WebTemplate.new(botmodule.to_s, pattern, options)
200         debug 'template route: ' + @templates[-1].inspect
201         return @templates.length - 1
202       end
203
204       # The unmap method for the RemoteDispatcher nils the template at the given index,
205       # therefore effectively removing the mapping
206       #
207       def unmap(botmodule, index)
208         tmpl = @templates[index]
209         raise "Botmodule #{botmodule.name} tried to unmap #{tmpl.inspect} that was handled by #{tmpl.botmodule}" unless tmpl.botmodule == botmodule.name
210         debug "Unmapping #{tmpl.inspect}"
211         @templates[handle] = nil
212         @templates.clear unless @templates.compact.size > 0
213       end
214
215       # Handle a web service request, find matching mapping and dispatch.
216       #
217       # In case authentication fails, sends a 401 Not Authorized response.
218       #
219       def handle(m)
220         if @templates.empty?
221           m.send_plaintext('no routes!', 404)
222           return false if @templates.empty?
223         end
224         failures = []
225         @templates.each do |tmpl|
226           # Skip this element if it was unmapped
227           next unless tmpl
228           botmodule = @bot.plugins[tmpl.botmodule]
229           params = tmpl.recognize(m)
230           if params
231             action = tmpl.options[:action]
232             unless botmodule.respond_to?(action)
233               failures << NoActionFailure.new(tmpl, m)
234               next
235             end
236             # check http method:
237             unless not tmpl.options.has_key? :method or tmpl.options[:method] == m.method
238               debug 'request method missmatch'
239               next
240             end
241             auth = tmpl.options[:full_auth_path]
242             debug "checking auth for #{auth.inspect}"
243             # We check for private permission
244             if m.bot.auth.permit?(m.source || Auth::defaultbotuser, auth, '?')
245               debug "template match found and auth'd: #{action.inspect} #{params.inspect}"
246               response = botmodule.send(action, m, params)
247               if m.res.sent_size == 0 and m.res.body.empty?
248                 m.send_json(response.to_json)
249               end
250               return true
251             end
252             debug "auth failed for #{auth}"
253             # if it's just an auth failure but otherwise the match is good,
254             # don't try any more handlers
255             m.send_plaintext('Authentication Required!', 401)
256             return false
257           end
258         end
259         failures.each {|r|
260           debug "#{r.template.inspect} => #{r}"
261         }
262         debug "no handler found"
263         m.send_plaintext('No Handler Found!', 404)
264         return false
265       end
266     end
267
268     # Static web dispatcher instance used internally.
269     def web_dispatcher
270       if defined? @web_dispatcher
271         @web_dispatcher
272       else
273         @web_dispatcher = WebDispatcher.new(self)
274       end
275     end
276
277     module Plugins
278       # Mixin for plugins that want to provide a web interface of some sort.
279       #
280       # Plugins include the module and can then use web_map
281       # to register a url to handle.
282       #
283       module WebBotModule
284         # The remote_map acts just like the BotModule#map method, except that
285         # the map is registered to the @bot's remote_dispatcher. Also, the remote map handle
286         # is handled for the cleanup management
287         #
288         def web_map(*args)
289           # stores the handles/indexes for cleanup:
290           @web_maps = Array.new unless defined? @web_maps
291           @web_maps << @bot.web_dispatcher.map(self, *args)
292         end
293
294         # Unregister the remote maps.
295         #
296         def web_cleanup
297           return unless defined? @web_maps
298           @web_maps.each { |h|
299             @bot.web_dispatcher.unmap(self, h)
300           }
301           @web_maps.clear
302         end
303
304         # Redefine the default cleanup method.
305         #
306         def cleanup
307           super
308           web_cleanup
309         end
310       end
311     end
312 end # Bot
313 end # Irc
314
315 class ::WebServiceUser < Irc::User
316   def initialize(str, botuser, opts={})
317     super(str, opts)
318     @botuser = botuser
319     @response = []
320   end
321   attr_reader :botuser
322   attr_accessor :response
323 end
324
325 class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
326   def initialize(server, bot)
327     super server
328     @bot = bot
329   end
330
331   def dispatch(req, res)
332     res['Server'] = 'RBot Web Service (http://ruby-rbot.org/)'
333     begin
334       m = WebMessage.new(@bot, req, res)
335       @bot.web_dispatcher.handle m
336     rescue
337       res.status = 500
338       res['Content-Type'] = 'text/plain'
339       res.body = "Error: %s\n" % [$!.to_s]
340       error 'web dispatch error: ' + $!.to_s
341       error $@.join("\n")
342     end
343   end
344
345   def do_GET(req, res)
346     dispatch(req, res)
347   end
348
349   def do_POST(req, res)
350     dispatch(req, res)
351   end
352 end
353
354 class WebServiceModule < CoreBotModule
355
356   include WebBotModule
357
358   Config.register Config::BooleanValue.new('webservice.autostart',
359     :default => false,
360     :requires_rescan => true,
361     :desc => 'Whether the web service should be started automatically')
362
363   Config.register Config::IntegerValue.new('webservice.port',
364     :default => 7268,
365     :requires_rescan => true,
366     :desc => 'Port on which the web service will listen')
367
368   Config.register Config::StringValue.new('webservice.host',
369     :default => '127.0.0.1',
370     :requires_rescan => true,
371     :desc => 'Host the web service will bind on')
372
373   Config.register Config::BooleanValue.new('webservice.ssl',
374     :default => false,
375     :requires_rescan => true,
376     :desc => 'Whether the web server should use SSL (recommended!)')
377
378   Config.register Config::StringValue.new('webservice.ssl_key',
379     :default => '~/.rbot/wskey.pem',
380     :requires_rescan => true,
381     :desc => 'Private key file to use for SSL')
382
383   Config.register Config::StringValue.new('webservice.ssl_cert',
384     :default => '~/.rbot/wscert.pem',
385     :requires_rescan => true,
386     :desc => 'Certificate file to use for SSL')
387
388   Config.register Config::BooleanValue.new('webservice.allow_dispatch',
389     :default => true,
390     :desc => 'Dispatch normal bot commands, just as a user would through the web service, requires auth for certain commands just like a irc user.')
391
392   def initialize
393     super
394     @port = @bot.config['webservice.port']
395     @host = @bot.config['webservice.host']
396     @server = nil
397     @bot.webservice = self
398     begin
399       start_service if @bot.config['webservice.autostart']
400     rescue => e
401       error "couldn't start web service provider: #{e.inspect}"
402     end
403   end
404
405   def start_service
406     raise "Remote service provider already running" if @server
407     opts = {:BindAddress => @host, :Port => @port}
408     if @bot.config['webservice.ssl']
409       opts.merge! :SSLEnable => true
410       cert = File.expand_path @bot.config['webservice.ssl_cert']
411       key = File.expand_path @bot.config['webservice.ssl_key']
412       if File.exists? cert and File.exists? key
413         debug 'using ssl certificate files'
414         opts.merge!({
415           :SSLCertificate => OpenSSL::X509::Certificate.new(File.read(cert)),
416           :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(key))
417         })
418       else
419         debug 'using on-the-fly generated ssl certs'
420         opts.merge! :SSLCertName => [ %w[CN localhost] ]
421         # the problem with this is that it will always use the same
422         # serial number which makes this feature pretty much useless.
423       end
424     end
425     # Logging to file in ~/.rbot
426     logfile = File.open(@bot.path('webservice.log'), 'a+')
427     opts.merge!({
428       :Logger => WEBrick::Log.new(logfile),
429       :AccessLog => [[logfile, WEBrick::AccessLog::COMBINED_LOG_FORMAT]]
430     })
431     @server = WEBrick::HTTPServer.new(opts)
432     debug 'webservice started: ' + opts.inspect
433     @server.mount('/', DispatchServlet, @bot)
434     Thread.new { @server.start }
435   end
436
437   def stop_service
438     @server.shutdown if @server
439     @server = nil
440   end
441
442   def cleanup
443     stop_service
444     super
445   end
446
447   def handle_start(m, params)
448     if @server
449       m.reply 'web service already running'
450     else
451       begin
452         start_service
453         m.reply 'web service started'
454       rescue
455         m.reply 'unable to start web service, error: ' + $!.to_s
456       end
457     end
458   end
459
460   def handle_stop(m, params)
461     if @server
462       stop_service
463       m.reply 'web service stopped'
464     else
465       m.reply 'web service not running'
466     end
467   end
468
469   def handle_ping(m, params)
470     m.send_plaintext("pong\n")
471   end
472
473   def handle_dispatch(m, params)
474     if not @bot.config['webservice.allow_dispatch']
475       m.send_plaintext('dispatch forbidden by configuration', 403)
476       return
477     end
478
479     command = m.post['command']
480     if not m.source
481       botuser = Auth::defaultbotuser
482     else
483       botuser = m.source.botuser
484     end
485     netmask = '%s!%s@%s' % [botuser.username, botuser.username, m.client]
486
487     debug 'dispatch command: ' + command
488
489     user = WebServiceUser.new(netmask, botuser)
490     message = Irc::PrivMessage.new(@bot, nil, user, @bot.myself, command)
491
492     res = @bot.plugins.irc_delegate('privmsg', message)
493
494     if m.req['Accept'] == 'application/json'
495       { :reply => user.response }
496     else
497       m.send_plaintext(user.response.join("\n") + "\n")
498     end
499   end
500
501 end
502
503 webservice = WebServiceModule.new
504
505 webservice.map 'webservice start',
506   :action => 'handle_start',
507   :auth_path => ':manage:'
508
509 webservice.map 'webservice stop',
510   :action => 'handle_stop',
511   :auth_path => ':manage:'
512
513 webservice.web_map '/ping',
514   :action => :handle_ping,
515   :auth_path => 'public'
516
517 # executes arbitary bot commands
518 webservice.web_map '/dispatch',
519   :action => :handle_dispatch,
520   :method => 'POST',
521   :auth_path => 'public'
522
523 webservice.default_auth('*', false)
524 webservice.default_auth('public', true)
525