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
80 true # no need to request auth at this point
85 debug '@path = ' + @path.inspect
88 def parse_query(query)
89 params = CGI::parse(query)
90 params.each_pair do |key, val|
91 params[key] = val.last
96 # The target of a RemoteMessage
101 # Remote messages are always 'private'
106 # Sends a response with the specified body, status and content type.
107 def send_response(body, status, type)
109 @res['Content-Type'] = type
113 # Sends a plaintext response
114 def send_plaintext(body, status=200)
115 send_response(body, status, 'text/plain')
118 # Sends a json response
119 def send_json(body, status=200)
120 send_response(body, status, 'application/json')
123 # Sends a html response
124 def send_html(body, status=200)
125 send_response(body, status, 'text/html')
129 # works similar to a message mapper but for url paths
132 attr_reader :botmodule, :pattern, :options
133 def initialize(botmodule, pattern, options={})
134 @botmodule = botmodule
137 set_auth_path(@options)
141 message_route = m.path[1..-1].split('/')
142 template_route = @pattern[1..-1].split('/')
145 debug 'web mapping path %s <-> %s' % [message_route.inspect, template_route.inspect]
147 message_route.each do |part|
148 tmpl = template_route.shift
149 return false if not tmpl
152 # push part as url path parameter
153 params[tmpl[1..-1].to_sym] = part
161 debug 'web mapping params is %s' % [params.inspect]
166 def set_auth_path(hash)
167 if hash.has_key?(:full_auth_path)
168 warning "Web route #{@pattern.inspect} in #{@botmodule} sets :full_auth_path, please don't do this"
171 words = @pattern[1..-1].split('/').reject{ |x|
172 x == pre || x =~ /^:/ || x =~ /\[|\]/
179 if hash.has_key?(:auth_path)
180 extra = hash[:auth_path]
181 if extra.sub!(/^:/, "")
185 if extra.sub!(/:$/, "")
187 post = [post,words[1]].compact.join("::")
190 pre = nil if extra.sub!(/^!/, "")
191 post = nil if extra.sub!(/!$/, "")
192 extra = nil if extra.empty?
196 hash[:full_auth_path] = [pre,extra,post].compact.join("::")
197 debug "Web route #{@pattern} in #{botmodule} will use authPath #{hash[:full_auth_path]}"
207 def map(botmodule, pattern, options={})
208 @templates << WebTemplate.new(botmodule.to_s, pattern, options)
209 debug 'template route: ' + @templates[-1].inspect
210 return @templates.length - 1
213 # The unmap method for the RemoteDispatcher nils the template at the given index,
214 # therefore effectively removing the mapping
216 def unmap(botmodule, index)
217 tmpl = @templates[index]
218 raise "Botmodule #{botmodule.name} tried to unmap #{tmpl.inspect} that was handled by #{tmpl.botmodule}" unless tmpl.botmodule == botmodule.name
219 debug "Unmapping #{tmpl.inspect}"
220 @templates[index] = nil
221 @templates.clear unless @templates.compact.size > 0
224 # Handle a web service request, find matching mapping and dispatch.
226 # In case authentication fails, sends a 401 Not Authorized response.
230 m.send_plaintext('no routes!', 404)
231 return false if @templates.empty?
234 @templates.each do |tmpl|
235 # Skip this element if it was unmapped
237 botmodule = @bot.plugins[tmpl.botmodule]
238 params = tmpl.recognize(m)
240 action = tmpl.options[:action]
241 unless botmodule.respond_to?(action)
242 failures << NoActionFailure.new(tmpl, m)
246 unless not tmpl.options.has_key? :method or tmpl.options[:method] == m.method
247 debug 'request method missmatch'
250 auth = tmpl.options[:full_auth_path]
251 debug "checking auth for #{auth.inspect}"
252 # We check for private permission
253 if m.bot.auth.permit?(m.source || Auth::defaultbotuser, auth, '?')
254 debug "template match found and auth'd: #{action.inspect} #{params.inspect}"
255 response = botmodule.send(action, m, params)
256 if m.res.sent_size == 0 and m.res.body.empty?
257 m.send_json(response.to_json)
261 debug "auth failed for #{auth}"
262 # if it's just an auth failure but otherwise the match is good,
263 # don't try any more handlers
264 m.send_plaintext('Authentication Required!', 401)
269 debug "#{r.template.inspect} => #{r}"
271 debug "no handler found"
272 m.send_plaintext('No Handler Found!', 404)
277 # Static web dispatcher instance used internally.
279 if defined? @web_dispatcher
282 @web_dispatcher = WebDispatcher.new(self)
287 # Mixin for plugins that want to provide a web interface of some sort.
289 # Plugins include the module and can then use web_map
290 # to register a url to handle.
293 # The remote_map acts just like the BotModule#map method, except that
294 # the map is registered to the @bot's remote_dispatcher. Also, the remote map handle
295 # is handled for the cleanup management
298 # stores the handles/indexes for cleanup:
299 @web_maps = Array.new unless defined? @web_maps
300 @web_maps << @bot.web_dispatcher.map(self, *args)
303 # Unregister the remote maps.
306 return unless defined? @web_maps
308 @bot.web_dispatcher.unmap(self, h)
313 # Redefine the default cleanup method.
321 # And just because I like consistency:
323 module WebCoreBotModule
334 class ::WebServiceUser < Irc::User
335 def initialize(str, botuser, opts={})
341 attr_accessor :response
344 class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
345 def initialize(server, bot)
350 def dispatch(req, res)
351 res['Server'] = 'RBot Web Service (http://ruby-rbot.org/)'
353 m = WebMessage.new(@bot, req, res)
354 @bot.web_dispatcher.handle m
355 rescue WEBrick::HTTPStatus::Unauthorized
357 res['Content-Type'] = 'text/plain'
358 res.body = 'Authentication Required!'
359 error 'authentication error (wrong password)'
362 res['Content-Type'] = 'text/plain'
363 res.body = "Error: %s\n" % [$!.to_s]
364 error 'web dispatch error: ' + $!.to_s
373 def do_POST(req, res)
378 class WebServiceModule < CoreBotModule
380 include WebCoreBotModule
382 Config.register Config::BooleanValue.new('webservice.autostart',
384 :requires_rescan => true,
385 :desc => 'Whether the web service should be started automatically')
387 Config.register Config::IntegerValue.new('webservice.port',
389 :requires_rescan => true,
390 :desc => 'Port on which the web service will listen')
392 Config.register Config::StringValue.new('webservice.host',
393 :default => '127.0.0.1',
394 :requires_rescan => true,
395 :desc => 'Host the web service will bind on')
397 Config.register Config::BooleanValue.new('webservice.ssl',
399 :requires_rescan => true,
400 :desc => 'Whether the web server should use SSL (recommended!)')
402 Config.register Config::StringValue.new('webservice.ssl_key',
403 :default => '~/.rbot/wskey.pem',
404 :requires_rescan => true,
405 :desc => 'Private key file to use for SSL')
407 Config.register Config::StringValue.new('webservice.ssl_cert',
408 :default => '~/.rbot/wscert.pem',
409 :requires_rescan => true,
410 :desc => 'Certificate file to use for SSL')
412 Config.register Config::BooleanValue.new('webservice.allow_dispatch',
414 :desc => 'Dispatch normal bot commands, just as a user would through the web service, requires auth for certain commands just like a irc user.')
418 @port = @bot.config['webservice.port']
419 @host = @bot.config['webservice.host']
421 @bot.webservice = self
423 start_service if @bot.config['webservice.autostart']
425 error "couldn't start web service provider: #{e.inspect}"
430 raise "Remote service provider already running" if @server
431 opts = {:BindAddress => @host, :Port => @port}
432 if @bot.config['webservice.ssl']
433 opts.merge! :SSLEnable => true
434 cert = File.expand_path @bot.config['webservice.ssl_cert']
435 key = File.expand_path @bot.config['webservice.ssl_key']
436 if File.exists? cert and File.exists? key
437 debug 'using ssl certificate files'
439 :SSLCertificate => OpenSSL::X509::Certificate.new(File.read(cert)),
440 :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(key))
443 debug 'using on-the-fly generated ssl certs'
444 opts.merge! :SSLCertName => [ %w[CN localhost] ]
445 # the problem with this is that it will always use the same
446 # serial number which makes this feature pretty much useless.
449 # Logging to file in ~/.rbot
450 logfile = File.open(@bot.path('webservice.log'), 'a+')
452 :Logger => WEBrick::Log.new(logfile),
453 :AccessLog => [[logfile, WEBrick::AccessLog::COMBINED_LOG_FORMAT]]
455 @server = WEBrick::HTTPServer.new(opts)
456 debug 'webservice started: ' + opts.inspect
457 @server.mount('/', DispatchServlet, @bot)
458 Thread.new { @server.start }
462 @server.shutdown if @server
471 def handle_start(m, params)
473 m.reply 'web service already running'
477 m.reply 'web service started'
479 m.reply 'unable to start web service, error: ' + $!.to_s
484 def handle_stop(m, params)
487 m.reply 'web service stopped'
489 m.reply 'web service not running'
493 def handle_ping(m, params)
494 m.send_plaintext("pong\n")
497 def handle_dispatch(m, params)
498 if not @bot.config['webservice.allow_dispatch']
499 m.send_plaintext('dispatch forbidden by configuration', 403)
503 command = m.post['command']
505 botuser = Auth::defaultbotuser
507 botuser = m.source.botuser
509 netmask = '%s!%s@%s' % [botuser.username, botuser.username, m.client]
511 debug 'dispatch command: ' + command
513 user = WebServiceUser.new(netmask, botuser)
514 message = Irc::PrivMessage.new(@bot, nil, user, @bot.myself, command)
516 res = @bot.plugins.irc_delegate('privmsg', message)
518 if m.req['Accept'] == 'application/json'
519 { :reply => user.response }
521 m.send_plaintext(user.response.join("\n") + "\n")
527 webservice = WebServiceModule.new
529 webservice.map 'webservice start',
530 :action => 'handle_start',
531 :auth_path => ':manage:'
533 webservice.map 'webservice stop',
534 :action => 'handle_stop',
535 :auth_path => ':manage:'
537 webservice.web_map '/ping',
538 :action => :handle_ping,
539 :auth_path => 'public'
541 # executes arbitary bot commands
542 webservice.web_map '/dispatch',
543 :action => :handle_dispatch,
545 :auth_path => 'public'
547 webservice.default_auth('*', false)
548 webservice.default_auth('public', true)