4 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
5 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ## GNU General Public License for more details.
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 TOP_DIR = File.expand_path(File.dirname(__FILE__))
22 $:.unshift File.dirname(__FILE__)
23 require 'shogi_server'
25 #################################################
31 def gets_safe(socket, timeout=nil)
32 if r = select([socket], nil, nil, timeout)
33 return r[0].first.gets
37 rescue Exception => ex
38 log_error("gets_safe: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
45 shogi-server - server for CSA server protocol
48 shogi-server [OPTIONS] event_name port_number
51 server for CSA server protocol
55 specify filename for logging process ID
57 run as a daemon. Log files will be put in dir.
59 log network messages for each player. Log files
60 will be put in the dir.
63 GPL versoin 2 or later
68 #{ShogiServer::Release}
71 #{ShogiServer::Revision}
93 def parse_command_line
95 parser = GetoptLong.new(
96 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
97 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT],
98 ["--player-log-dir", GetoptLong::REQUIRED_ARGUMENT])
101 parser.each_option do |name, arg|
103 options[name] = arg.dup
107 raise parser.error_message
112 def write_pid_file(file)
113 open(file, "w") do |fh|
118 def mutex_watchdog(mutex, sec)
126 queue.push(Object.new)
129 log_error("mutex watchdog timeout: %d sec" % [sec])
137 def login_loop(client)
140 while r = select([client], nil, nil, ShogiServer::Login_Time) do
141 break unless str = r[0].first.gets
142 $mutex.lock # guards LEAGUE
146 if (ShogiServer::Login::good_login?(str))
147 player = ShogiServer::Player::new(str, client, eol)
148 login = ShogiServer::Login::factory(str, player)
149 if (current_player = LEAGUE.find(player.name))
150 if (current_player.password == player.password &&
151 current_player.status != "game")
152 log_message(sprintf("user %s login forcely", player.name))
155 login.incorrect_duplicated_player(str)
163 client.write("LOGIN:incorrect" + eol)
164 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
170 return [player, login]
173 def setup_logger(log_file)
174 logger = Logger.new(log_file, 'daily')
175 logger.formatter = ShogiServer::Formatter.new
176 logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO
177 logger.datetime_format = "%Y-%m-%d %H:%M:%S"
181 def setup_watchdog_for_giant_lock
185 mutex_watchdog($mutex, 10)
190 return Thread.start do
192 floodgate = ShogiServer::League::Floodgate.new(LEAGUE)
193 log_message("Flooddgate reloaded. The next match will start at %s." %
194 [floodgate.next_time])
198 diff = floodgate.next_time - Time.now
206 next_time = floodgate.next_time
207 $mutex.synchronize do
208 log_message("Reloading source...")
211 floodgate = ShogiServer::League::Floodgate.new(LEAGUE, next_time)
212 log_message("Floodgate will start the next match at %s." %
213 [floodgate.next_time])
214 rescue Exception => ex
216 log_error("[in Floodgate's thread] #{ex} #{ex.backtrace}")
224 $options = parse_command_line
225 if (ARGV.length != 2)
229 if $options["player-log-dir"]
230 $options["player-log-dir"] = File.expand_path($options["player-log-dir"])
232 if $options["player-log-dir"] &&
233 !File.directory?($options["player-log-dir"])
237 if $options["pid-file"]
238 $options["pid-file"] = File.expand_path($options["pid-file"])
241 LEAGUE.event = ARGV.shift
244 dir = $options["daemon"]
245 dir = File.expand_path(dir) if dir
246 if dir && ! File.exist?(dir)
250 log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
251 $logger = setup_logger(log_file)
253 LEAGUE.dir = dir || TOP_DIR
257 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
258 config[:Logger] = $logger
262 config[:StartCallback] = Proc.new do
264 if $options["pid-file"]
265 write_pid_file($options["pid-file"])
267 setup_watchdog_for_giant_lock
268 LEAGUE.setup_players_database
269 fg_thread = setup_floodgate
272 config[:StopCallback] = Proc.new do
273 if $options["pid-file"]
274 FileUtils.rm($options["pid-file"], :force => true)
278 server = WEBrick::GenericServer.new(config)
279 ["INT", "TERM"].each do |signal|
282 fg_thread.kill if fg_thread
288 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
289 log_message("server started [Revision: #{ShogiServer::Revision}]")
291 server.start do |client|
292 # client.sync = true # this is already set in WEBrick
293 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
294 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
295 player, login = login_loop(client) # loop
298 log_message(sprintf("user %s login", player.name))
300 player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
301 player.run(login.csa_1st_str) # loop
305 player.game.kill(player)
307 player.finish # socket has been closed
308 LEAGUE.delete(player)
309 log_message(sprintf("user %s logout", player.name))
320 TCPSocket.do_not_reverse_lookup = true
321 Thread.abort_on_exception = $DEBUG ? true : false
324 LEAGUE = ShogiServer::League.new(TOP_DIR)
326 rescue Exception => ex
327 log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")