4 # :title: Web service for bot
6 # Author:: Matthias Hecker (apoc@geekosphere.org)
8 # HTTP(S)/json based web service for remote controlling the bot,
9 # similar to remote but much more portable.
11 # For more info/documentation:
12 # https://github.com/4poc/rbot/wiki/Web-Service
16 require 'webrick/https'
23 # A WebMessage is a web request and response object combined with helper methods.
29 # HTTP method (POST, GET, etc.)
32 # Request object, a instance of WEBrick::HTTPRequest ({http://www.ruby-doc.org/stdlib-2.0/libdoc/webrick/rdoc/WEBrick/HTTPRequest.html docs})
35 # Response object, a instance of WEBrick::HTTPResponse ({http://www.ruby-doc.org/stdlib-2.0/libdoc/webrick/rdoc/WEBrick/HTTPResponse.html docs})
38 # Parsed post request parameters.
41 # Parsed url parameters.
50 # The bot user issuing the command.
53 def initialize(bot, req, res)
58 @method = req.request_method
60 if req.body and not req.body.empty?
61 @post = parse_query(req.body)
64 if req.query_string and not req.query_string.empty?
65 @args = parse_query(req.query_string)
67 @client = req.peeraddr[3]
69 # login a botuser with http authentication
70 WEBrick::HTTPAuth.basic_auth(req, res, 'RBotAuth') { |username, password|
72 botuser = @bot.auth.get_botuser(Auth::BotUser.sanitize_username(username))
73 if botuser and botuser.password == password
79 true # no need to request auth at this point
84 debug '@path = ' + @path.inspect
87 def parse_query(query)
88 params = CGI::parse(query)
89 params.each_pair do |key, val|
90 params[key] = val.last
95 # The target of a RemoteMessage
100 # Remote messages are always 'private'
105 # Sends a plaintext response
106 def send_plaintext(body, status=200)
108 @res['Content-Type'] = 'text/plain'
112 # Sends a json response
113 def send_json(body, status=200)
115 @res['Content-Type'] = 'application/json'
120 # works similar to a message mapper but for url paths
123 attr_reader :botmodule, :pattern, :options
124 def initialize(botmodule, pattern, options={})
125 @botmodule = botmodule
128 set_auth_path(@options)
132 message_route = m.path[1..-1].split('/')
133 template_route = @pattern[1..-1].split('/')
136 debug 'web mapping path %s <-> %s' % [message_route.inspect, template_route.inspect]
138 message_route.each do |part|
139 tmpl = template_route.shift
140 return false if not tmpl
143 # push part as url path parameter
144 params[tmpl[1..-1].to_sym] = part
152 debug 'web mapping params is %s' % [params.inspect]
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"
162 words = @pattern[1..-1].split('/').reject{ |x|
163 x == pre || x =~ /^:/ || x =~ /\[|\]/
170 if hash.has_key?(:auth_path)
171 extra = hash[:auth_path]
172 if extra.sub!(/^:/, "")
176 if extra.sub!(/:$/, "")
178 post = [post,words[1]].compact.join("::")
181 pre = nil if extra.sub!(/^!/, "")
182 post = nil if extra.sub!(/!$/, "")
183 extra = nil if extra.empty?
187 hash[:full_auth_path] = [pre,extra,post].compact.join("::")
188 debug "Web route #{@pattern} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
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
204 # The unmap method for the RemoteDispatcher nils the template at the given index,
205 # therefore effectively removing the mapping
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
215 # Handle a web service request, find matching mapping and dispatch.
217 # In case authentication fails, sends a 401 Not Authorized response.
221 m.send_plaintext('no routes!', 404)
222 return false if @templates.empty?
225 @templates.each do |tmpl|
226 # Skip this element if it was unmapped
228 botmodule = @bot.plugins[tmpl.botmodule]
229 params = tmpl.recognize(m)
231 action = tmpl.options[:action]
232 unless botmodule.respond_to?(action)
233 failures << NoActionFailure.new(tmpl, m)
237 unless not tmpl.options.has_key? :method or tmpl.options[:method] == m.method
238 debug 'request method missmatch'
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)
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)
260 debug "#{r.template.inspect} => #{r}"
262 debug "no handler found"
263 m.send_plaintext('No Handler Found!', 404)
268 # Static web dispatcher instance used internally.
270 if defined? @web_dispatcher
273 @web_dispatcher = WebDispatcher.new(self)
278 # Mixin for plugins that want to provide a web interface of some sort.
280 # Plugins include the module and can then use web_map
281 # to register a url to handle.
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
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)
294 # Unregister the remote maps.
297 return unless defined? @web_maps
299 @bot.web_dispatcher.unmap(self, h)
304 # Redefine the default cleanup method.
312 # And just because I like consistency:
314 module WebCoreBotModule
325 class ::WebServiceUser < Irc::User
326 def initialize(str, botuser, opts={})
332 attr_accessor :response
335 class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
336 def initialize(server, bot)
341 def dispatch(req, res)
342 res['Server'] = 'RBot Web Service (http://ruby-rbot.org/)'
344 m = WebMessage.new(@bot, req, res)
345 @bot.web_dispatcher.handle m
348 res['Content-Type'] = 'text/plain'
349 res.body = "Error: %s\n" % [$!.to_s]
350 error 'web dispatch error: ' + $!.to_s
359 def do_POST(req, res)
364 class WebServiceModule < CoreBotModule
366 include WebCoreBotModule
368 Config.register Config::BooleanValue.new('webservice.autostart',
370 :requires_rescan => true,
371 :desc => 'Whether the web service should be started automatically')
373 Config.register Config::IntegerValue.new('webservice.port',
375 :requires_rescan => true,
376 :desc => 'Port on which the web service will listen')
378 Config.register Config::StringValue.new('webservice.host',
379 :default => '127.0.0.1',
380 :requires_rescan => true,
381 :desc => 'Host the web service will bind on')
383 Config.register Config::BooleanValue.new('webservice.ssl',
385 :requires_rescan => true,
386 :desc => 'Whether the web server should use SSL (recommended!)')
388 Config.register Config::StringValue.new('webservice.ssl_key',
389 :default => '~/.rbot/wskey.pem',
390 :requires_rescan => true,
391 :desc => 'Private key file to use for SSL')
393 Config.register Config::StringValue.new('webservice.ssl_cert',
394 :default => '~/.rbot/wscert.pem',
395 :requires_rescan => true,
396 :desc => 'Certificate file to use for SSL')
398 Config.register Config::BooleanValue.new('webservice.allow_dispatch',
400 :desc => 'Dispatch normal bot commands, just as a user would through the web service, requires auth for certain commands just like a irc user.')
404 @port = @bot.config['webservice.port']
405 @host = @bot.config['webservice.host']
407 @bot.webservice = self
409 start_service if @bot.config['webservice.autostart']
411 error "couldn't start web service provider: #{e.inspect}"
416 raise "Remote service provider already running" if @server
417 opts = {:BindAddress => @host, :Port => @port}
418 if @bot.config['webservice.ssl']
419 opts.merge! :SSLEnable => true
420 cert = File.expand_path @bot.config['webservice.ssl_cert']
421 key = File.expand_path @bot.config['webservice.ssl_key']
422 if File.exists? cert and File.exists? key
423 debug 'using ssl certificate files'
425 :SSLCertificate => OpenSSL::X509::Certificate.new(File.read(cert)),
426 :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(key))
429 debug 'using on-the-fly generated ssl certs'
430 opts.merge! :SSLCertName => [ %w[CN localhost] ]
431 # the problem with this is that it will always use the same
432 # serial number which makes this feature pretty much useless.
435 # Logging to file in ~/.rbot
436 logfile = File.open(@bot.path('webservice.log'), 'a+')
438 :Logger => WEBrick::Log.new(logfile),
439 :AccessLog => [[logfile, WEBrick::AccessLog::COMBINED_LOG_FORMAT]]
441 @server = WEBrick::HTTPServer.new(opts)
442 debug 'webservice started: ' + opts.inspect
443 @server.mount('/', DispatchServlet, @bot)
444 Thread.new { @server.start }
448 @server.shutdown if @server
457 def handle_start(m, params)
459 m.reply 'web service already running'
463 m.reply 'web service started'
465 m.reply 'unable to start web service, error: ' + $!.to_s
470 def handle_stop(m, params)
473 m.reply 'web service stopped'
475 m.reply 'web service not running'
479 def handle_ping(m, params)
480 m.send_plaintext("pong\n")
483 def handle_dispatch(m, params)
484 if not @bot.config['webservice.allow_dispatch']
485 m.send_plaintext('dispatch forbidden by configuration', 403)
489 command = m.post['command']
491 botuser = Auth::defaultbotuser
493 botuser = m.source.botuser
495 netmask = '%s!%s@%s' % [botuser.username, botuser.username, m.client]
497 debug 'dispatch command: ' + command
499 user = WebServiceUser.new(netmask, botuser)
500 message = Irc::PrivMessage.new(@bot, nil, user, @bot.myself, command)
502 res = @bot.plugins.irc_delegate('privmsg', message)
504 if m.req['Accept'] == 'application/json'
505 { :reply => user.response }
507 m.send_plaintext(user.response.join("\n") + "\n")
513 webservice = WebServiceModule.new
515 webservice.map 'webservice start',
516 :action => 'handle_start',
517 :auth_path => ':manage:'
519 webservice.map 'webservice stop',
520 :action => 'handle_stop',
521 :auth_path => ':manage:'
523 webservice.web_map '/ping',
524 :action => :handle_ping,
525 :auth_path => 'public'
527 # executes arbitary bot commands
528 webservice.web_map '/dispatch',
529 :action => :handle_dispatch,
531 :auth_path => 'public'
533 webservice.default_auth('*', false)
534 webservice.default_auth('public', true)