-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathskkserv.rb.in
executable file
·391 lines (335 loc) · 8.91 KB
/
skkserv.rb.in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#!@RUBY@
# coding: utf-8
### skkserv.rb --- rskkserv main routines -*- Mode: Ruby -*-
## Copyright (C) 1997-2000 Shugo Maeda
## Copyright (C) 2000,2001 YAMASHITA Junji
## Author: Shugo Maeda <shugo@aianet.ne.jp>
## Maintainer: YAMASHITA Junji <ysjj@unixuser.org>
## Version: @VERSION@
## This file is part of rskkserv.
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License as
## published by the Free Software Foundation; either version 2, or (at
## your option) any later version.
## This program is distributed in the hope that it will be useful, but
## WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## General Public License for more details.
### Code:
require "thread"
require "socket"
require "optparse"
require "skkserv/conf"
require "skkserv/logger"
require "skkserv/skkdic"
require "skkserv/googledic"
class SKKServer
VERSION_STRING = "rskkserv-@VERSION@ "
DEFAULT_CONFILE = "@sysconfdir@/rskkserv.conf"
DEFAULT_PORT = 1178
CLIENT_END = ?0
CLIENT_REQUEST = ?1
CLIENT_VERSION = ?2
CLIENT_HOST = ?3
CLIENT_COMPLETION = ?4
SERVER_ERROR = ?0
SERVER_FOUND = ?1
SERVER_NOT_FOUND = ?4
SERVER_FULL = ?9
BUFSIZE = 512
def self.main
if $params["help"]
usage
exit(0)
end
if $params["version"]
print("SKK SERVER ", VERSION_STRING, "\n")
exit(0)
end
skkserv = nil
begin
@config = Conf.new($params["config"] || DEFAULT_CONFILE)
skkserv = new(ARGV[0], @config)
daemon if daemon?
write_pid(@config.pid_file) if @config.pid_file
setup_sighdl
skkserv.mainloop
rescue LoadError
$stderr.printf("%s: %s\n", $0, $!)
exit(1)
rescue Errno::EADDRINUSE
$stderr.print("probably rskkserv is already running on port #{@config.port}.\n")
exit(1)
rescue
$stderr.printf("%s: %s\n\t%s\n", $0, $!, $@.join("\n\t"))
exit(1)
end
end
def self.usage
$stderr.printf(<<USAGE, $0)
Usage: %s [OPTION] [skk-dictionary-file]
-d debug mode
-p port open server using specified port
--config specify configuration file
--help display this help and exit
--verbose verbose mode
--version output version information and exit
USAGE
end
def self.daemon?
@config.daemon and ! $params["d"]
end
def self.daemon
exit!(0) if fork
Process::setsid
exit!(0) if fork
Dir::chdir("/")
File::umask(022)
STDIN.reopen(open("/dev/null", "r"))
begin
console = open("/dev/console", "w")
STDOUT.reopen(console)
STDERR.reopen(console)
rescue Errno::EACCES
$stderr.print("failed to open console.\n")
end
end
def self.write_pid(filename)
begin
f = open(filename, "w")
f.printf("%d\n", $$)
rescue
$stderr.printf("failed to write pid(%d): %s\n", $$, $!);
return
ensure
f.close if f
end
at_exit {
File.unlink(@config.pid_file) if File.exists?(@config.pid_file)
}
end
def self.setup_sighdl
@sig = 0
sighdr = proc {|sig| @sig = sig}
for sig in [:INT, :TERM]
trap(sig, sighdr)
end
@sig_watcher = Thread.start {
sleep 0.1 until @sig > 0
Logger.log_info("Caught signal %d, exiting...", @sig)
exit
}
end
def initialize(dic, config)
@config = config
Logger::level = $params["d"] ? Logger::DEBUG : @config.log_level
Logger::verbose = $params["verbose"]
Logger::filename = @config.log_file
Logger::log_debug("running on %s", host)
service = $params["p"] || @config.port || "skkserv"
begin
@server = if @config.host
TCPServer.new(@config.host, service)
else
TCPServer.new(service)
end
rescue
if service == "skkserv"
service = DEFAULT_PORT
retry
else
raise
end
end
Logger::log_debug("listen to %s", @server.addr[1..-1].join(":"))
if @config.tcpwrap
begin
require "tcpwrap"
@server = TCPWrapper.new(File.basename($0), @server, true)
Logger::log_info("loaded tcpwrap")
rescue LoadError
Logger::log_info("failed to load tcpwrap")
end
end
@dictionary = SKKDictionary.new(@config, dic)
@nclients = 0
end
def mainloop
comp_str = []
accept_clients do |s|
peer = peer_string(s)
while cmdbuf = s.sysread(BUFSIZE)
case cmdbuf[0]
when CLIENT_END
Logger::log_debug("message from client %s: END", peer)
break
when CLIENT_REQUEST
Logger::log_debug("message from client %s: WORD", peer)
cmdend = cmdbuf.index(?\ ) || cmdbuf.index(?\n)
kana = cmdbuf[1 .. (cmdend - 1)]
ret = ""
begin
if kanji = @dictionary.search(kana)
ret.concat(SERVER_FOUND)
ret.concat(kanji)
else
ret.concat(SERVER_NOT_FOUND)
ret.concat(cmdbuf[1 .. -1])
end
rescue Exception
ret.concat(SERVER_ERROR)
ret.concat($!)
end
Logger::log_debug("send: \"%s\"", ret)
s.write(ret)
when CLIENT_VERSION
Logger::log_debug("message from client %s: VERSION", peer)
Logger::log_debug("send: \"%s\"", VERSION_STRING)
s.write(VERSION_STRING)
when CLIENT_HOST
ret = host(s)
Logger::log_debug("message from client %s: HOST", peer)
Logger::log_debug("send: \"%s\"", ret)
s.write(ret)
when CLIENT_COMPLETION
ret = ""
ret.concat(SERVER_FOUND)
ret.concat("/")
ret.concat("/\n")
Logger::log_debug("send: completion: %s", ret)
s.write(ret)
else
Logger::log_notice("message from client %s: UNKNOWN: %d/\"%s\"",
peer, cmdbuf[0], cmdbuf)
end
end
end
end
private
def accept_clients
loop do
begin
s = @server.accept
rescue
Logger::log_warn("%s", $!)
next
end
peer = peer_string(s)
Logger::log_info("%s is accepted.", peer)
if @nclients >= @config.max_clients
begin
s.putc(SERVER_FULL)
Logger::log_warn("%s: Connection rejected: %d: too many clients.",
peer, @nclients)
ensure
s.shutdown
s.close
next
end
end
@nclients += 1
Logger::log_debug("There are %d clients.", @nclients)
Thread.start do
begin
yield(s)
rescue Exception
Logger::log_debug("%s: %s", $!, peer)
ensure
s.shutdown
s.close
Logger::log_info("%s is gone.", peer)
@nclients -= 1
Logger::log_debug("There are %d clients.", @nclients)
end
end
end
end
def host(sock = nil)
if sock.nil?
hostname = (@server and @server.addr[2]) || Socket.gethostname
ipaddr = (@server and @server.addr[3]) || TCPSocket.getaddress(hostname)
else
hostname, ipaddr = sock.addr[2], sock.addr[3]
end
hostname + ":" + ipaddr + ": "
end
def peer_string(s)
peerport = s.peeraddr[1].to_s
if s.peeraddr[2] and s.peeraddr[2].length > 0
peerhost = s.peeraddr[2]
else
peerhost = s.peeraddr[3]
end
peerhost.concat(":").concat(peerport)
end
end
class SKKDictionary
def initialize(config, dic)
@search_agents = []
@config = config
unless dic.nil? or dic.empty?
agent = SKKDic.new(dic,
@config.skk_cache_dir,
@config.skk_no_cache)
Logger::log_debug("add agent: %s", agent)
@search_agents.push(agent)
end
@config.dic.each do |dic|
Logger::log_debug("add dic = #{dic}")
@search_agents.push(create_agent(dic))
end
raise "No search agents!" if @search_agents.empty?
@mutex = Mutex.new
end
def search(kana)
# Logger::log_debug("search: \"%s\"", kana)
@mutex.synchronize do
candidates = []
@search_agents.each do |agent|
Logger::log_debug("agent: %s", agent)
if /GOOGLEDic/ =~ agent.inspect
Logger::log_debug("candidates: %s", candidates)
if candidates.empty?
Logger::log_debug("kana: %s", kana)
tmp = agent.search(kana)
else
tmp = []
end
else
tmp = agent.search(kana)
end
candidates |= tmp
Logger::log_debug("tmp: %s", tmp);
end
return nil if candidates.empty?
candidates.delete(kana)
"/" << candidates.join("/") << "/\n"
end
end
private
def create_agent(dic)
/^([^:]+):(.*)$/ =~ dic
klass = $1.upcase + "Dic"
location = $2
begin
return Module.const_get(klass).create(location, dic.options, @config)
rescue NameError
load_backend(klass)
retry
end
end
def load_backend(klass)
feature = "skkserv/#{klass.downcase}"
begin
require(feature) or
raise "probably #{klass} isn't defined in #{feature}"
rescue LoadError
raise "failed to load #{feature} for #{klass}"
end
end
end
if $0 == __FILE__
$params = ARGV.getopts("d", "p:", "config:", "help", "verbose", "version")
SKKServer.main
end
### skkserv.rb ends here