Use singleton method for preparing empty environment.
[riece] / lisp / server.rb
1 # server.rb --- A simple IPC server executing Ruby programs.
2 # Copyright (C) 1998-2005 Daiki Ueno
3
4 # Author: Daiki Ueno <ueno@unixuser.org>
5 # Created: 1998-09-28
6 # Keywords: IRC, riece, Ruby
7
8 # This file is part of Riece.
9
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2, or (at your option)
13 # any later version.
14
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.   See the
18 # GNU General Public License for more details.
19
20 # You should have received a copy of the GNU General Public License
21 # along with GNU Emacs; see the file COPYING.  If not, write to the
22 # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 # Boston, MA 02111-1307, USA.
24
25 require 'thread'
26 require 'stringio'
27
28 class Server
29   def initialize(outfile, errfile, logfile)
30     @out = $stdout
31     @err = $stderr
32     $stdout = outfile ? File.new(outfile, 'a') : StringIO.new
33     $stderr = errfile ? File.new(errfile, 'a') : StringIO.new
34     @log = File.new(logfile, 'a') if logfile
35
36     @buf = ''
37     @que = Queue.new
38     @thr = Hash.new
39     @cnt = 0
40   end
41
42   def dispatch(line)
43     @log.puts(line) if @log
44     case line.chomp
45     when /\AD /
46       @buf << $'
47     when /\A(\S+)\s*/
48       c = $1
49       r = $'
50       d = "dispatch_#{c.downcase}"
51       if respond_to?(d, true)
52         Thread.start do
53           self.send(d, c, r)
54         end
55       else
56         send_line("ERR 103 Unknown command\r\n")
57       end
58     end
59   end
60
61   def dispatch_cancel(c, r)
62     send_line("ERR 100 Not implemented\r\n")
63   end
64
65   def dispatch_bye(c, r)
66     send_line("ERR 100 Not implemented\r\n")
67   end
68
69   def dispatch_auth(c, r)
70     send_line("ERR 100 Not implemented\r\n")
71   end
72
73   def dispatch_reset(c, r)
74     send_line("ERR 100 Not implemented\r\n")
75   end
76
77   def dispatch_end(c, r)
78     enq_data
79   end
80
81   def dispatch_help(c, r)
82     send_line("ERR 100 Not implemented\r\n")
83   end
84
85   def dispatch_quit(c, r)
86     send_line("ERR 100 Not implemented\r\n")
87   end
88
89   def dispatch_eval(c, r)
90     r = deq_data if r.empty?
91     name = nil
92     Thread.exclusive do
93       while @thr.include?(name = @cnt.to_s)
94         @cnt += 1
95       end
96       @thr[name] = Thread.current
97     end
98     send_line("S name #{name}\r\n")
99     send_line("OK\r\n")
100     Thread.current[:rubyserv_name] = name
101     begin
102       Thread.current[:rubyserv_error] = false
103       Thread.current[:rubyserv_response] = eval(r, exec_env.empty_binding)
104     rescue Exception => e
105       Thread.current[:rubyserv_error] = true
106       Thread.current[:rubyserv_response] = e.to_s.sub(/\A.*?\n/, '')
107     end
108     send_line("# exit #{name}\r\n")
109   end
110
111   def dispatch_poll(c, r)
112     thr = @thr[r]
113     if !thr
114       send_line("ERR 105 Parameter error: no such name \"#{r}\"\r\n")
115     elsif thr.alive?
116       send_line("S running #{r}\r\n")
117       send_line("OK\r\n")
118     else
119       if thr[:rubyserv_error]
120         send_line("S exited #{r}\r\n")
121       else
122         send_line("S finished #{r}\r\n")
123       end
124       if d = thr[:rubyserv_response]
125         send_data(d.to_s)
126       end
127       send_line("OK\r\n")
128     end
129   end
130
131   def dispatch_exit(c, r)
132     thr = @thr[r]
133     if !thr
134       send_line("ERR 105 Parameter error: no such name \"#{r}\"\r\n")
135       return
136     end
137     thr.kill if thr.alive?
138     @thr.delete(r)
139     send_line("OK\r\n")
140   end
141
142   def escape(s)
143     s.gsub(/[%\r\n]/) {|m| '%%%02X' % m[0]}
144   end
145
146   def unescape(s)
147     s.gsub(/%([0-9A-Z][0-9A-Z])/) {[$1].pack('H*')}
148   end
149
150   def send_data(d)
151     d = escape(d)
152     begin
153       len = [d.length, 998].min   # 998 = 1000 - "D "
154       send_line("D #{d[0 ... len]}\r\n")
155       d = d[len .. -1]
156     end until d.empty?
157   end
158
159   def enq_data
160     d = unescape(@buf)
161     @buf = ''
162     @que.enq(d)
163   end
164
165   def deq_data
166     @que.deq
167   end
168
169   def send_line(line)
170     @out.puts(line)
171     @log.puts(line) if @log
172   end
173
174   def exec_env
175     env = Object.new
176     def env.empty_binding
177       binding
178     end
179     out, log = @out, @log
180     env.instance_eval {@out, @log = out, log}
181     def env.send_line(line)
182       @out.puts(line)
183       @log.puts(line) if @log
184     end
185     def env.output(s)
186       send_line("# output #{Thread.current[:rubyserv_name]} #{s}\r\n")
187     end
188     env
189   end
190 end
191
192 if $0 == __FILE__
193   require 'optparse'
194
195   opt_outfile, opt_errfile, opt_logfile = nil, nil, nil
196   opts = OptionParser.new do |opts|
197     opts.banner = <<"End"
198 Usage: #{$0} [OPTIONS]
199 End
200     opts.on('-o', '--out OUTFILE', 'Send stdout to OUTFILE.') do |outfile|
201       opt_outfile = outfile
202     end
203     opts.on('-e', '--err ERRFILE', 'Send stderr to ERRFILE.') do |errfile|
204       opt_errfile = errfile
205     end
206     opts.on('-l', '--log LOGFILE', 'Send stdlog to LOGFILE.') do |logfile|
207       opt_logfile = logfile
208     end
209     opts.on_tail('--help', '-h', 'Show this message.') do
210       $stdout.print(opts.to_s)
211       exit(0)
212     end
213   end
214   begin
215     opts.parse!(ARGV)
216   rescue OptionParser::ParseError
217     $stderr.print(opts.to_s)
218     exit(1)
219   end
220
221   server = Server.new(opt_outfile, opt_errfile, opt_logfile)
222   while gets
223     server.dispatch($_)
224   end
225 end