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.
315 class ::WebServiceUser < Irc::User
316 def initialize(str, botuser, opts={})
322 attr_accessor :response
325 class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
326 def initialize(server, bot)
331 def dispatch(req, res)
332 res['Server'] = 'RBot Web Service (http://ruby-rbot.org/)'
334 m = WebMessage.new(@bot, req, res)
335 @bot.web_dispatcher.handle m
338 res['Content-Type'] = 'text/plain'
339 res.body = "Error: %s\n" % [$!.to_s]
340 error 'web dispatch error: ' + $!.to_s
349 def do_POST(req, res)
354 class WebServiceModule < CoreBotModule
358 Config.register Config::BooleanValue.new('webservice.autostart',
360 :requires_rescan => true,
361 :desc => 'Whether the web service should be started automatically')
363 Config.register Config::IntegerValue.new('webservice.port',
365 :requires_rescan => true,
366 :desc => 'Port on which the web service will listen')
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')
373 Config.register Config::BooleanValue.new('webservice.ssl',
375 :requires_rescan => true,
376 :desc => 'Whether the web server should use SSL (recommended!)')
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')
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')
388 Config.register Config::BooleanValue.new('webservice.allow_dispatch',
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.')
394 @port = @bot.config['webservice.port']
395 @host = @bot.config['webservice.host']
397 @bot.webservice = self
399 start_service if @bot.config['webservice.autostart']
401 error "couldn't start web service provider: #{e.inspect}"
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'
415 :SSLCertificate => OpenSSL::X509::Certificate.new(File.read(cert)),
416 :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(key))
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.
425 # Logging to file in ~/.rbot
426 logfile = File.open(@bot.path('webservice.log'), 'a+')
428 :Logger => WEBrick::Log.new(logfile),
429 :AccessLog => [[logfile, WEBrick::AccessLog::COMBINED_LOG_FORMAT]]
431 @server = WEBrick::HTTPServer.new(opts)
432 debug 'webservice started: ' + opts.inspect
433 @server.mount('/', DispatchServlet, @bot)
434 Thread.new { @server.start }
438 @server.shutdown if @server
447 def handle_start(m, params)
449 m.reply 'web service already running'
453 m.reply 'web service started'
455 m.reply 'unable to start web service, error: ' + $!.to_s
460 def handle_stop(m, params)
463 m.reply 'web service stopped'
465 m.reply 'web service not running'
469 def handle_ping(m, params)
470 m.send_plaintext("pong\n")
473 def handle_dispatch(m, params)
474 if not @bot.config['webservice.allow_dispatch']
475 m.send_plaintext('dispatch forbidden by configuration', 403)
479 command = m.post['command']
481 botuser = Auth::defaultbotuser
483 botuser = m.source.botuser
485 netmask = '%s!%s@%s' % [botuser.username, botuser.username, m.client]
487 debug 'dispatch command: ' + command
489 user = WebServiceUser.new(netmask, botuser)
490 message = Irc::PrivMessage.new(@bot, nil, user, @bot.myself, command)
492 res = @bot.plugins.irc_delegate('privmsg', message)
494 if m.req['Accept'] == 'application/json'
495 { :reply => user.response }
497 m.send_plaintext(user.response.join("\n") + "\n")
503 webservice = WebServiceModule.new
505 webservice.map 'webservice start',
506 :action => 'handle_start',
507 :auth_path => ':manage:'
509 webservice.map 'webservice stop',
510 :action => 'handle_stop',
511 :auth_path => ':manage:'
513 webservice.web_map '/ping',
514 :action => :handle_ping,
515 :auth_path => 'public'
517 # executes arbitary bot commands
518 webservice.web_map '/dispatch',
519 :action => :handle_dispatch,
521 :auth_path => 'public'
523 webservice.default_auth('*', false)
524 webservice.default_auth('public', true)