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-2012 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.expand_path(__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 a prefix of record files.
77 a port number for the server to listen.
80 a file path in which a process ID will be written.
81 Use with --daemon option.
83 run as a daemon. Log files will be put in dir.
84 --floodgate-games game_A[,...]
85 enable Floodgate with various game names (separated by a comma)
87 enable to log network messages for players. Log files
88 will be put in the dir.
92 1. % ./shogi-server test 4081
93 Run the shogi-server. Then clients can connect to port#4081.
94 The server output logs to the stdout.
96 2. % ./shogi-server --daemon . --pid-file ./shogi-server.pid \
97 --player-log-dir ./player-logs \
99 Run the shogi-server as a daemon. The server outputs regular logs
100 to shogi-server.log located in the current directory and network
101 messages in ./player-logs directory.
103 3. % ./shogi-server --daemon . --pid-file ./shogi-server.pid \
104 --player-log-dir ./player-logs \
105 --floodgate-games floodgate-900-0,floodgate-3600-0 \
107 Run the shogi-server with two groups of Floodgate games.
108 Configuration files allow you to schedule starting times. Consult
109 floodgate-0-240.conf.sample or shogi_server/league/floodgate.rb
112 FLOODGATE SCHEDULE CONFIGURATIONS
114 You need to set starting times of floodgate groups in
115 configuration files under the top directory. Each floodgate
116 group requires a corresponding configuration file named
117 "<game_name>.conf". The file will be re-read once just after a
120 For example, a floodgate-3600-30 game group requires
121 floodgate-3600-30.conf. However, for floodgate-900-0 and
122 floodgate-3600-0, which were default enabled in previous
123 versions, configuration files are optional if you are happy with
124 default time settings.
127 # This is a comment line
131 DoW := "Sun" | "Mon" | "Tue" | "Wed" | "Thu" | "Fri" | "Sat" |
132 "Sunday" | "Monday" | "Tuesday" | "Wednesday" | "Thursday" |
133 "Friday" | "Saturday"
142 GPL versoin 2 or later
147 #{ShogiServer::Revision}
173 # Parse command line options. Return a hash containing the option strings
174 # where a key is the option name without the first two slashes. For example,
175 # {"pid-file" => "foo.pid"}.
177 def parse_command_line
179 parser = GetoptLong.new(
180 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
181 ["--floodgate-games", GetoptLong::REQUIRED_ARGUMENT],
182 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT],
183 ["--player-log-dir", GetoptLong::REQUIRED_ARGUMENT])
186 parser.each_option do |name, arg|
188 options[name] = arg.dup
192 raise parser.error_message
197 # Check command line options.
198 # If any of them is invalid, exit the process.
200 def check_command_line
201 if (ARGV.length != 2)
206 if $options["daemon"]
207 $options["daemon"] = File.expand_path($options["daemon"], File.dirname(__FILE__))
208 unless is_writable_dir? $options["daemon"]
210 $stderr.puts "Can not create a file in the daemon directory: %s" % [$options["daemon"]]
215 $topdir = $options["daemon"] || File.expand_path(File.dirname(__FILE__))
217 if $options["player-log-dir"]
218 $options["player-log-dir"] = File.expand_path($options["player-log-dir"], $topdir)
219 unless is_writable_dir?($options["player-log-dir"])
221 $stderr.puts "Can not write a file in the player log dir: %s" % [$options["player-log-dir"]]
226 if $options["pid-file"]
227 $options["pid-file"] = File.expand_path($options["pid-file"], $topdir)
228 unless ShogiServer::is_writable_file? $options["pid-file"]
230 $stderr.puts "Can not create the pid file: %s" % [$options["pid-file"]]
235 if $options["floodgate-games"]
236 names = $options["floodgate-games"].split(",")
238 names.select do |name|
239 ShogiServer::League::Floodgate::game_name?(name)
241 if names.size != new_names.size
242 $stderr.puts "Found a wrong Floodgate game: %s" % [names.join(",")]
245 $options["floodgate-games"] = new_names
248 if $options["floodgate-history"]
249 $stderr.puts "WARNING: --floodgate-history has been deprecated."
250 $options["floodgate-history"] = nil
254 # See if a file can be created in the directory.
255 # Return true if a file is writable in the directory, otherwise false.
257 def is_writable_dir?(dir)
258 unless File.directory? dir
265 temp_file = Tempfile.new("dummy-shogi-server", dir)
274 def write_pid_file(file)
275 open(file, "w") do |fh|
280 def mutex_watchdog(mutex, sec)
288 queue.push(Object.new)
291 log_error("mutex watchdog timeout: %d sec" % [sec])
299 def login_loop(client)
302 while r = select([client], nil, nil, ShogiServer::Login_Time) do
305 break unless str = r[0].first.gets
306 rescue Exception => ex
307 # It is posssible that the socket causes an error (ex. Errno::ECONNRESET)
308 log_error("login_loop: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
311 $mutex.lock # guards $league
315 if (ShogiServer::Login::good_login?(str))
316 player = ShogiServer::Player::new(str, client, eol)
317 login = ShogiServer::Login::factory(str, player)
318 if (current_player = $league.find(player.name))
319 if (current_player.password == player.password &&
320 current_player.status != "game")
321 log_message(sprintf("user %s login forcely", player.name))
324 login.incorrect_duplicated_player(str)
332 client.write("LOGIN:incorrect" + eol)
333 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
339 return [player, login]
342 def setup_logger(log_file)
343 logger = ShogiServer::Logger.new(log_file, 'daily')
344 logger.formatter = ShogiServer::Formatter.new
345 logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO
346 logger.datetime_format = "%Y-%m-%d %H:%M:%S"
350 def setup_watchdog_for_giant_lock
354 mutex_watchdog($mutex, 10)
360 $options = parse_command_line
362 $config = ShogiServer::Config.new $options
364 $league = ShogiServer::League.new($topdir)
366 $league.event = ARGV.shift
369 log_file = $options["daemon"] ? File.join($options["daemon"], "shogi-server.log") : STDOUT
370 $logger = setup_logger(log_file)
372 $league.dir = $topdir
376 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
377 config[:Logger] = $logger
379 setup_floodgate = nil
381 config[:StartCallback] = Proc.new do
383 if $options["pid-file"]
384 write_pid_file($options["pid-file"])
386 setup_watchdog_for_giant_lock
387 $league.setup_players_database
388 setup_floodgate = ShogiServer::SetupFloodgate.new($options["floodgate-games"])
389 setup_floodgate.start
392 config[:StopCallback] = Proc.new do
393 if $options["pid-file"]
394 FileUtils.rm($options["pid-file"], :force => true)
399 server = WEBrick::GenericServer.new(config)
400 ["INT", "TERM"].each do |signal|
406 unless (RUBY_PLATFORM.downcase =~ /mswin|mingw|cygwin|bccwin/)
411 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
412 log_message("server started [Revision: #{ShogiServer::Revision}]")
414 server.start do |client|
416 # client.sync = true # this is already set in WEBrick
417 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
418 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
419 player, login = login_loop(client) # loop
421 log_error("Detected a timed out login attempt")
425 log_message(sprintf("user %s login", player.name))
427 player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
428 player.run(login.csa_1st_str) # loop
432 player.game.kill(player)
435 $league.delete(player)
436 log_message(sprintf("user %s logout", player.name))
440 player.wait_write_thread_finish(1000) # milliseconds
441 rescue Exception => ex
442 log_error("server.start: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
451 TCPSocket.do_not_reverse_lookup = true
452 Thread.abort_on_exception = $DEBUG ? true : false
456 rescue Exception => ex
458 log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
460 $stderr.puts "main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"