4 # Author:: NABEYA Kenichi, Daigo Moriwaki
5 # Homepage:: http://sourceforge.jp/projects/shogi-server/
8 # Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
9 # Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with this program; if not, write to the Free Software
23 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 $:.unshift File.dirname(__FILE__)
33 require 'shogi_server'
34 require 'shogi_server/config'
35 require 'shogi_server/util'
36 require 'shogi_server/league/floodgate_thread.rb'
39 #################################################
49 # - nil when a socket is closed
51 def gets_safe(socket, timeout=nil)
52 if r = select([socket], nil, nil, timeout)
53 return r[0].first.gets
57 rescue Exception => ex
58 log_error("gets_safe: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
65 shogi-server - server for CSA server protocol
68 shogi-server [OPTIONS] event_name port_number
71 server for CSA server protocol
75 specify filename for logging process ID
77 run as a daemon. Log files will be put in dir.
78 --floodgate-games game_A[,...]
79 enable Floodgate with various game names.
81 log network messages for each player. Log files
82 will be put in the dir.
85 GPL versoin 2 or later
90 #{ShogiServer::Release}
93 #{ShogiServer::Revision}
119 # Parse command line options. Return a hash containing the option strings
120 # where a key is the option name without the first two slashes. For example,
121 # {"pid-file" => "foo.pid"}.
123 def parse_command_line
125 parser = GetoptLong.new(
126 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
127 ["--floodgate-games", GetoptLong::REQUIRED_ARGUMENT],
128 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT],
129 ["--player-log-dir", GetoptLong::REQUIRED_ARGUMENT])
132 parser.each_option do |name, arg|
134 options[name] = arg.dup
138 raise parser.error_message
143 # Check command line options.
144 # If any of them is invalid, exit the process.
146 def check_command_line
147 if (ARGV.length != 2)
152 if $options["daemon"]
153 $options["daemon"] = File.expand_path($options["daemon"], File.dirname(__FILE__))
154 unless is_writable_dir? $options["daemon"]
156 $stderr.puts "Can not create a file in the daemon directory: %s" % [$options["daemon"]]
161 $topdir = $options["daemon"] || File.expand_path(File.dirname(__FILE__))
163 if $options["player-log-dir"]
164 $options["player-log-dir"] = File.expand_path($options["player-log-dir"], $topdir)
165 unless is_writable_dir?($options["player-log-dir"])
167 $stderr.puts "Can not write a file in the player log dir: %s" % [$options["player-log-dir"]]
172 if $options["pid-file"]
173 $options["pid-file"] = File.expand_path($options["pid-file"], $topdir)
174 unless ShogiServer::is_writable_file? $options["pid-file"]
176 $stderr.puts "Can not create the pid file: %s" % [$options["pid-file"]]
181 if $options["floodgate-games"]
182 names = $options["floodgate-games"].split(",")
184 names.select do |name|
185 ShogiServer::League::Floodgate::game_name?(name)
187 if names.size != new_names.size
188 $stderr.puts "Found a wrong Floodgate game: %s" % [names.join(",")]
191 $options["floodgate-games"] = new_names
194 if $options["floodgate-history"]
195 $stderr.puts "WARNING: --floodgate-history has been deprecated."
196 $options["floodgate-history"] = nil
200 # See if a file can be created in the directory.
201 # Return true if a file is writable in the directory, otherwise false.
203 def is_writable_dir?(dir)
204 unless File.directory? dir
211 temp_file = Tempfile.new("dummy-shogi-server", dir)
220 def write_pid_file(file)
221 open(file, "w") do |fh|
226 def mutex_watchdog(mutex, sec)
234 queue.push(Object.new)
237 log_error("mutex watchdog timeout: %d sec" % [sec])
245 def login_loop(client)
248 while r = select([client], nil, nil, ShogiServer::Login_Time) do
251 break unless str = r[0].first.gets
252 rescue Exception => ex
253 # It is posssible that the socket causes an error (ex. Errno::ECONNRESET)
254 log_error("login_loop: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
257 $mutex.lock # guards $league
261 if (ShogiServer::Login::good_login?(str))
262 player = ShogiServer::Player::new(str, client, eol)
263 login = ShogiServer::Login::factory(str, player)
264 if (current_player = $league.find(player.name))
265 if (current_player.password == player.password &&
266 current_player.status != "game")
267 log_message(sprintf("user %s login forcely", player.name))
270 login.incorrect_duplicated_player(str)
278 client.write("LOGIN:incorrect" + eol)
279 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
285 return [player, login]
288 def setup_logger(log_file)
289 logger = ShogiServer::Logger.new(log_file, 'daily')
290 logger.formatter = ShogiServer::Formatter.new
291 logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO
292 logger.datetime_format = "%Y-%m-%d %H:%M:%S"
296 def setup_watchdog_for_giant_lock
300 mutex_watchdog($mutex, 10)
306 $options = parse_command_line
308 $config = ShogiServer::Config.new $options
310 $league = ShogiServer::League.new($topdir)
312 $league.event = ARGV.shift
315 log_file = $options["daemon"] ? File.join($options["daemon"], "shogi-server.log") : STDOUT
316 $logger = setup_logger(log_file)
318 $league.dir = $topdir
322 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
323 config[:Logger] = $logger
325 setup_floodgate = nil
327 config[:StartCallback] = Proc.new do
329 if $options["pid-file"]
330 write_pid_file($options["pid-file"])
332 setup_watchdog_for_giant_lock
333 $league.setup_players_database
334 setup_floodgate = ShogiServer::SetupFloodgate.new($options["floodgate-games"])
335 setup_floodgate.start
338 config[:StopCallback] = Proc.new do
339 if $options["pid-file"]
340 FileUtils.rm($options["pid-file"], :force => true)
345 server = WEBrick::GenericServer.new(config)
346 ["INT", "TERM"].each do |signal|
352 unless (RUBY_PLATFORM.downcase =~ /mswin|mingw|cygwin|bccwin/)
357 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
358 log_message("server started [Revision: #{ShogiServer::Revision}]")
360 server.start do |client|
361 # client.sync = true # this is already set in WEBrick
362 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
363 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
364 player, login = login_loop(client) # loop
367 log_message(sprintf("user %s login", player.name))
369 player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
370 player.run(login.csa_1st_str) # loop
374 player.game.kill(player)
376 player.finish # socket has been closed
377 $league.delete(player)
378 log_message(sprintf("user %s logout", player.name))
389 TCPSocket.do_not_reverse_lookup = true
390 Thread.abort_on_exception = $DEBUG ? true : false
394 rescue Exception => ex
396 log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
398 $stderr.puts "main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"