]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/webservice.rb
21acf87d0d3623d36cd3b5776fb9094386dae2a4
[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 class ::WebServiceUser < Irc::User
22   def initialize(str, botuser, opts={})
23     super(str, opts)
24     @botuser = botuser
25     @response = []
26   end
27   attr_reader :botuser
28   attr_accessor :response
29 end
30
31 class PingServlet < WEBrick::HTTPServlet::AbstractServlet
32   def initialize(server, bot)
33     super server
34     @bot = bot
35   end
36
37   def do_GET(req, res)
38     res['Content-Type'] = 'text/plain'
39     res.body = "pong\r\n"
40   end
41 end
42
43 class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
44   def initialize(server, bot)
45     super server
46     @bot = bot
47   end
48
49   def dispatch_command(command, botuser, ip)
50     netmask = '%s!%s@%s' % [botuser.username, botuser.username, ip]
51
52     user = WebServiceUser.new(netmask, botuser)
53     message = Irc::PrivMessage.new(@bot, nil, user, @bot.myself, command)
54
55     @bot.plugins.irc_delegate('privmsg', message)
56
57     { :reply => user.response }
58   end
59
60   # Handle a dispatch request.
61   def do_POST(req, res)
62     post = CGI::parse(req.body)
63     ip = req.peeraddr[3]
64
65     username = post['username'].first
66     password = post['password'].first
67     command = post['command'].first
68
69     botuser = @bot.auth.get_botuser(username)
70     raise 'Permission Denied' if not botuser or botuser.password != password
71
72     ret = dispatch_command(command, botuser, ip)
73
74     res.status = 200
75     if req['Accept'] == 'application/json'
76       res['Content-Type'] = 'application/json'
77       res.body = JSON.dump ret
78     else
79       res['Content-Type'] = 'text/plain'
80       res.body = ret[:reply].join("\n") + "\n"
81     end
82   end
83 end
84
85 class WebServiceModule < CoreBotModule
86
87   Config.register Config::BooleanValue.new('webservice.autostart',
88     :default => false,
89     :requires_rescan => true,
90     :desc => 'Whether the web service should be started automatically')
91
92   Config.register Config::IntegerValue.new('webservice.port',
93     :default => 7260, # that's 'rbot'
94     :requires_rescan => true,
95     :desc => 'Port on which the web service will listen')
96
97   Config.register Config::StringValue.new('webservice.host',
98     :default => '127.0.0.1',
99     :requires_rescan => true,
100     :desc => 'Host the web service will bind on')
101
102   Config.register Config::BooleanValue.new('webservice.ssl',
103     :default => false,
104     :requires_rescan => true,
105     :desc => 'Whether the web server should use SSL (recommended!)')
106
107   Config.register Config::StringValue.new('webservice.ssl_key',
108     :default => '~/.rbot/wskey.pem',
109     :requires_rescan => true,
110     :desc => 'Private key file to use for SSL')
111
112   Config.register Config::StringValue.new('webservice.ssl_cert',
113     :default => '~/.rbot/wscert.pem',
114     :requires_rescan => true,
115     :desc => 'Certificate file to use for SSL')
116
117   def initialize
118     super
119     @port = @bot.config['webservice.port']
120     @host = @bot.config['webservice.host']
121     @server = nil
122     begin
123       start_service if @bot.config['webservice.autostart']
124     rescue => e
125       error "couldn't start web service provider: #{e.inspect}"
126     end
127   end
128
129   def start_service
130     raise "Remote service provider already running" if @server
131     opts = {:BindAddress => @host, :Port => @port}
132     if @bot.config['webservice.ssl']
133       opts.merge! :SSLEnable => true
134       cert = File.expand_path @bot.config['webservice.ssl_cert']
135       key = File.expand_path @bot.config['webservice.ssl_key']
136       if File.exists? cert and File.exists? key
137         debug 'using ssl certificate files'
138         opts.merge!({
139           :SSLCertificate => OpenSSL::X509::Certificate.new(File.read(cert)),
140           :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(key))
141         })
142       else
143         debug 'using on-the-fly generated ssl certs'
144         opts.merge! :SSLCertName => [ %w[CN localhost] ]
145         # the problem with this is that it will always use the same
146         # serial number which makes this feature pretty much useless.
147       end
148     end
149     # Logging to file in ~/.rbot
150     logfile = File.open(@bot.path('webservice.log'), 'a+')
151     opts.merge!({
152       :Logger => WEBrick::Log.new(logfile),
153       :AccessLog => [[logfile, WEBrick::AccessLog::COMBINED_LOG_FORMAT]]
154     })
155     @server = WEBrick::HTTPServer.new(opts)
156     debug 'webservice started: ' + opts.inspect
157     @server.mount('/dispatch', DispatchServlet, @bot)
158     @server.mount('/ping', PingServlet, @bot)
159     Thread.new { @server.start }
160   end
161
162   def stop_service
163     @server.shutdown if @server
164     @server = nil
165   end
166
167   def cleanup
168     stop_service
169     super
170   end
171
172   def handle_start(m, params)
173     s = ''
174     if @server
175       s << 'web service already running'
176     else
177       begin
178         start_service
179         s << 'web service started'
180       rescue
181         s << 'unable to start web service, error: ' + $!.to_s
182       end
183     end
184     m.reply s
185   end
186
187 end
188
189 webservice = WebServiceModule.new
190
191 webservice.map 'webservice start',
192   :action => 'handle_start',
193   :auth_path => ':manage:'
194
195 webservice.map 'webservice stop',
196   :action => 'handle_stop',
197   :auth_path => ':manage:'
198
199 webservice.default_auth('*', false)
200