Added copyright.
[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     out, log = @out, @log
102     env = Module.new
103     env.module_eval do
104       @out, @log = out, log
105
106       def send_line(line)
107         @out.puts(line)
108         @log.puts(line) if @log
109       end
110       module_function :send_line
111
112       def output(s)
113         send_line("# output #{Thread.current[:rubyserv_name]} #{s}\r\n")
114       end
115       module_function :output
116     end
117     begin
118       Thread.current[:rubyserv_error] = false
119       Thread.current[:rubyserv_response] = eval(r, env.module_eval {binding()})
120     rescue Exception => e
121       Thread.current[:rubyserv_error] = true
122       Thread.current[:rubyserv_response] = e.to_s.sub(/\A.*?\n/, '')
123     end
124     send_line("# exit #{name}\r\n")
125   end
126
127   def dispatch_poll(c, r)
128     thr = @thr[r]
129     if !thr
130       send_line("ERR 105 Parameter error: no such name \"#{r}\"\r\n")
131     elsif thr.alive?
132       send_line("S running #{r}\r\n")
133       send_line("OK\r\n")
134     else
135       if thr[:rubyserv_error]
136         send_line("S exited #{r}\r\n")
137       else
138         send_line("S finished #{r}\r\n")
139       end
140       if d = thr[:rubyserv_response]
141         send_data(d.to_s)
142       end
143       send_line("OK\r\n")
144     end
145   end
146
147   def dispatch_exit(c, r)
148     thr = @thr[r]
149     if !thr
150       send_line("ERR 105 Parameter error: no such name \"#{r}\"\r\n")
151       return
152     end
153     thr.kill if thr.alive?
154     @thr.delete(r)
155     send_line("OK\r\n")
156   end
157
158   def escape(s)
159     s.gsub(/[%\r\n]/) {|m| '%%%02X' % m[0]}
160   end
161
162   def unescape(s)
163     s.gsub(/%([0-9A-Z][0-9A-Z])/) {[$1].pack('H*')}
164   end
165
166   def send_data(d)
167     d = escape(d)
168     begin
169       len = [d.length, 998].min   # 998 = 1000 - "D "
170       send_line("D #{d[0 ... len]}\r\n")
171       d = d[len .. -1]
172     end until d.empty?
173   end
174
175   def enq_data
176     d = unescape(@buf)
177     @buf = ''
178     @que.enq(d)
179   end
180
181   def deq_data
182     @que.deq
183   end
184
185   def send_line(line)
186     @out.puts(line)
187     @log.puts(line) if @log
188   end
189 end
190
191 if $0 == __FILE__
192   require 'optparse'
193
194   opt_outfile, opt_errfile, opt_logfile = nil, nil, nil
195   opts = OptionParser.new do |opts|
196     opts.banner = <<"End"
197 Usage: #{$0} [OPTIONS]
198 End
199     opts.on('-o', '--out OUTFILE', 'Send stdout to OUTFILE.') do |outfile|
200       opt_outfile = outfile
201     end
202     opts.on('-e', '--err ERRFILE', 'Send stderr to ERRFILE.') do |errfile|
203       opt_errfile = errfile
204     end
205     opts.on('-e', '--log LOGFILE', 'Send stdlog to LOGFILE.') do |logfile|
206       opt_logfile = logfile
207     end
208     opts.on_tail('--help', '-h', 'Show this message.') do
209       $stdout.print(opts.to_s)
210       exit(0)
211     end
212   end
213   begin
214     opts.parse!(ARGV)
215   rescue OptionParser::ParseError
216     $stderr.print(opts.to_s)
217     exit(1)
218   end
219
220   server = Server.new(opt_outfile, opt_errfile, opt_logfile)
221   while gets
222     server.dispatch($_)
223   end
224 end