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 response with the specified body, status and content type.
106 def send_response(body, status, type)
108 @res['Content-Type'] = type
112 # Sends a plaintext response
113 def send_plaintext(body, status=200)
114 send_response(body, status, 'text/plain')
117 # Sends a json response
118 def send_json(body, status=200)
119 send_response(body, status, 'application/json')
122 # Sends a html response
123 def send_html(body, status=200)
124 send_response(body, status, 'text/html')
128 # works similar to a message mapper but for url paths
131 attr_reader :botmodule, :pattern, :options
132 def initialize(botmodule, pattern, options={})
133 @botmodule = botmodule
136 set_auth_path(@options)
140 message_route = m.path[1..-1].split('/')
141 template_route = @pattern[1..-1].split('/')
144 debug 'web mapping path %s <-> %s' % [message_route.inspect, template_route.inspect]
146 message_route.each do |part|
147 tmpl = template_route.shift
148 return false if not tmpl
151 # push part as url path parameter
152 params[tmpl[1..-1].to_sym] = part
160 debug 'web mapping params is %s' % [params.inspect]
165 def set_auth_path(hash)
166 if hash.has_key?(:full_auth_path)
167 warning "Web route #{@pattern.inspect} in #{@botmodule} sets :full_auth_path, please don't do this"
170 words = @pattern[1..-1].split('/').reject{ |x|
171 x == pre || x =~ /^:/ || x =~ /\[|\]/
178 if hash.has_key?(:auth_path)
179 extra = hash[:auth_path]
180 if extra.sub!(/^:/, "")
184 if extra.sub!(/:$/, "")
186 post = [post,words[1]].compact.join("::")
189 pre = nil if extra.sub!(/^!/, "")
190 post = nil if extra.sub!(/!$/, "")
191 extra = nil if extra.empty?
195 hash[:full_auth_path] = [pre,extra,post].compact.join("::")
196 debug "Web route #{@pattern} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
206 def map(botmodule, pattern, options={})
207 @templates << WebTemplate.new(botmodule.to_s, pattern, options)
208 debug 'template route: ' + @templates[-1].inspect
209 return @templates.length - 1
212 # The unmap method for the RemoteDispatcher nils the template at the given index,
213 # therefore effectively removing the mapping
215 def unmap(botmodule, index)
216 tmpl = @templates[index]
217 raise "Botmodule #{botmodule.name} tried to unmap #{tmpl.inspect} that was handled by #{tmpl.botmodule}" unless tmpl.botmodule == botmodule.name
218 debug "Unmapping #{tmpl.inspect}"
219 @templates[handle] = nil
220 @templates.clear unless @templates.compact.size > 0
223 # Handle a web service request, find matching mapping and dispatch.
225 # In case authentication fails, sends a 401 Not Authorized response.
229 m.send_plaintext('no routes!', 404)
230 return false if @templates.empty?
233 @templates.each do |tmpl|
234 # Skip this element if it was unmapped
236 botmodule = @bot.plugins[tmpl.botmodule]
237 params = tmpl.recognize(m)
239 action = tmpl.options[:action]
240 unless botmodule.respond_to?(action)
241 failures << NoActionFailure.new(tmpl, m)
245 unless not tmpl.options.has_key? :method or tmpl.options[:method] == m.method
246 debug 'request method missmatch'
249 auth = tmpl.options[:full_auth_path]
250 debug "checking auth for #{auth.inspect}"
251 # We check for private permission
252 if m.bot.auth.permit?(m.source || Auth::defaultbotuser, auth, '?')
253 debug "template match found and auth'd: #{action.inspect} #{params.inspect}"
254 response = botmodule.send(action, m, params)
255 if m.res.sent_size == 0 and m.res.body.empty?
256 m.send_json(response.to_json)
260 debug "auth failed for #{auth}"
261 # if it's just an auth failure but otherwise the match is good,
262 # don't try any more handlers
263 m.send_plaintext('Authentication Required!', 401)
268 debug "#{r.template.inspect} => #{r}"
270 debug "no handler found"
271 m.send_plaintext('No Handler Found!', 404)
276 # Static web dispatcher instance used internally.
278 if defined? @web_dispatcher
281 @web_dispatcher = WebDispatcher.new(self)
286 # Mixin for plugins that want to provide a web interface of some sort.
288 # Plugins include the module and can then use web_map
289 # to register a url to handle.
292 # The remote_map acts just like the BotModule#map method, except that
293 # the map is registered to the @bot's remote_dispatcher. Also, the remote map handle
294 # is handled for the cleanup management
297 # stores the handles/indexes for cleanup:
298 @web_maps = Array.new unless defined? @web_maps
299 @web_maps << @bot.web_dispatcher.map(self, *args)
302 # Unregister the remote maps.
305 return unless defined? @web_maps
307 @bot.web_dispatcher.unmap(self, h)
312 # Redefine the default cleanup method.
320 # And just because I like consistency:
322 module WebCoreBotModule
333 class ::WebServiceUser < Irc::User
334 def initialize(str, botuser, opts={})
340 attr_accessor :response
343 class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
344 def initialize(server, bot)
349 def dispatch(req, res)
350 res['Server'] = 'RBot Web Service (http://ruby-rbot.org/)'
352 m = WebMessage.new(@bot, req, res)
353 @bot.web_dispatcher.handle m
356 res['Content-Type'] = 'text/plain'
357 res.body = "Error: %s\n" % [$!.to_s]
358 error 'web dispatch error: ' + $!.to_s
367 def do_POST(req, res)
372 class WebServiceModule < CoreBotModule
374 include WebCoreBotModule
376 Config.register Config::BooleanValue.new('webservice.autostart',
378 :requires_rescan => true,
379 :desc => 'Whether the web service should be started automatically')
381 Config.register Config::IntegerValue.new('webservice.port',
383 :requires_rescan => true,
384 :desc => 'Port on which the web service will listen')
386 Config.register Config::StringValue.new('webservice.host',
387 :default => '127.0.0.1',
388 :requires_rescan => true,
389 :desc => 'Host the web service will bind on')
391 Config.register Config::BooleanValue.new('webservice.ssl',
393 :requires_rescan => true,
394 :desc => 'Whether the web server should use SSL (recommended!)')
396 Config.register Config::StringValue.new('webservice.ssl_key',
397 :default => '~/.rbot/wskey.pem',
398 :requires_rescan => true,
399 :desc => 'Private key file to use for SSL')
401 Config.register Config::StringValue.new('webservice.ssl_cert',
402 :default => '~/.rbot/wscert.pem',
403 :requires_rescan => true,
404 :desc => 'Certificate file to use for SSL')
406 Config.register Config::BooleanValue.new('webservice.allow_dispatch',
408 :desc => 'Dispatch normal bot commands, just as a user would through the web service, requires auth for certain commands just like a irc user.')
412 @port = @bot.config['webservice.port']
413 @host = @bot.config['webservice.host']
415 @bot.webservice = self
417 start_service if @bot.config['webservice.autostart']
419 error "couldn't start web service provider: #{e.inspect}"
424 raise "Remote service provider already running" if @server
425 opts = {:BindAddress => @host, :Port => @port}
426 if @bot.config['webservice.ssl']
427 opts.merge! :SSLEnable => true
428 cert = File.expand_path @bot.config['webservice.ssl_cert']
429 key = File.expand_path @bot.config['webservice.ssl_key']
430 if File.exists? cert and File.exists? key
431 debug 'using ssl certificate files'
433 :SSLCertificate => OpenSSL::X509::Certificate.new(File.read(cert)),
434 :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(key))
437 debug 'using on-the-fly generated ssl certs'
438 opts.merge! :SSLCertName => [ %w[CN localhost] ]
439 # the problem with this is that it will always use the same
440 # serial number which makes this feature pretty much useless.
443 # Logging to file in ~/.rbot
444 logfile = File.open(@bot.path('webservice.log'), 'a+')
446 :Logger => WEBrick::Log.new(logfile),
447 :AccessLog => [[logfile, WEBrick::AccessLog::COMBINED_LOG_FORMAT]]
449 @server = WEBrick::HTTPServer.new(opts)
450 debug 'webservice started: ' + opts.inspect
451 @server.mount('/', DispatchServlet, @bot)
452 Thread.new { @server.start }
456 @server.shutdown if @server
465 def handle_start(m, params)
467 m.reply 'web service already running'
471 m.reply 'web service started'
473 m.reply 'unable to start web service, error: ' + $!.to_s
478 def handle_stop(m, params)
481 m.reply 'web service stopped'
483 m.reply 'web service not running'
487 def handle_ping(m, params)
488 m.send_plaintext("pong\n")
491 def handle_dispatch(m, params)
492 if not @bot.config['webservice.allow_dispatch']
493 m.send_plaintext('dispatch forbidden by configuration', 403)
497 command = m.post['command']
499 botuser = Auth::defaultbotuser
501 botuser = m.source.botuser
503 netmask = '%s!%s@%s' % [botuser.username, botuser.username, m.client]
505 debug 'dispatch command: ' + command
507 user = WebServiceUser.new(netmask, botuser)
508 message = Irc::PrivMessage.new(@bot, nil, user, @bot.myself, command)
510 res = @bot.plugins.irc_delegate('privmsg', message)
512 if m.req['Accept'] == 'application/json'
513 { :reply => user.response }
515 m.send_plaintext(user.response.join("\n") + "\n")
521 webservice = WebServiceModule.new
523 webservice.map 'webservice start',
524 :action => 'handle_start',
525 :auth_path => ':manage:'
527 webservice.map 'webservice stop',
528 :action => 'handle_stop',
529 :auth_path => ':manage:'
531 webservice.web_map '/ping',
532 :action => :handle_ping,
533 :auth_path => 'public'
535 # executes arbitary bot commands
536 webservice.web_map '/dispatch',
537 :action => :handle_dispatch,
539 :auth_path => 'public'
541 webservice.default_auth('*', false)
542 webservice.default_auth('public', true)