3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 module ShogiServer # for a namespace
30 @last_game_win = false
33 # Idetifier of the player in the rating system
34 attr_accessor :player_id
39 # Password of the player, which does not include a trip
40 attr_accessor :password
42 # Score in the rating sysem
45 # Number of games for win and loss in the rating system
46 attr_accessor :win, :loss
48 # Group in the rating system
49 attr_accessor :rating_group
51 # Last timestamp when the rate was modified
52 attr_accessor :modified_at
54 # Whether win the previous game or not
55 attr_accessor :last_game_win
58 @modified_at || Time.now
64 @modified_at = Time.now
78 simple_name = @name.gsub(/@.*?$/, '')
79 "%s+%s" % [simple_name, @trip[0..8]]
86 # Parses str in the LOGIN command, sets up @player_id and @trip
91 @player_id = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
93 @player_id = @password = nil
99 class Player < BasicPlayer
100 WRITE_THREAD_WATCH_INTERVAL = 20 # sec
101 def initialize(str, socket, eol=nil)
104 @status = "connected" # game_waiting -> agree_waiting -> start_waiting -> game -> finished
106 @protocol = nil # CSA or x1
107 @eol = eol || "\m" # favorite eol code
110 @mytime = 0 # set in start method also
113 @main_thread = Thread::current
114 @write_queue = ShogiServer::TimeoutQueue.new(WRITE_THREAD_WATCH_INTERVAL)
119 attr_accessor :socket, :status
120 attr_accessor :protocol, :eol, :game, :mytime, :game_name, :sente
121 attr_accessor :main_thread
122 attr_reader :socket_buffer
124 def setup_logger(dir)
125 log_file = File.join(dir, "%s.log" % [simple_player_id])
126 @player_logger = Logger.new(log_file, 'daily')
127 @player_logger.formatter = ShogiServer::Formatter.new
128 @player_logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO
129 @player_logger.datetime_format = "%Y-%m-%d %H:%M:%S"
132 def log(level, direction, message)
133 return unless @player_logger
137 str = "IN: %s" % [str]
139 str = "OUT: %s" % [str]
141 str = "UNKNOWN DIRECTION: %s %s" % [direction, str]
145 @player_logger.debug(str)
147 @player_logger.info(str)
149 @player_logger.warn(str)
151 @player_logger.error(str)
153 @player_logger.debug("UNKNOWN LEVEL: %s %s" % [level, str])
155 rescue Exception => ex
156 log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
160 log_message(sprintf("user %s killed", @name))
165 Thread::kill(@main_thread) if @main_thread
166 Thread::kill(@write_thread) if @write_thread
170 if (@status != "finished")
172 log_message(sprintf("user %s finish", @name))
174 log_debug("Terminating %s's write thread..." % [@name])
175 if @write_thread && @write_thread.alive?
178 @player_logger.close if @player_logger
181 log_message(sprintf("user %s finish failed", @name))
186 def start_write_thread
187 @write_thread = Thread.start do
189 while !@socket.closed?
191 str = @write_queue.deq
193 log_debug("%s's write thread terminated" % [@name])
197 log_debug("%s's write queue timed out. Try again..." % [@name])
201 if r = select(nil, [@socket], nil, 20)
202 r[1].first.write(str)
203 log(:info, :out, str)
205 log_error("Gave a try to send a message to #{@name}, but it timed out.")
208 rescue Exception => ex
209 log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
213 log_error("%s's socket closed." % [@name]) if @socket.closed?
214 log_message("At least %d messages are not sent to the client." %
215 [@write_queue.get_messages.size])
220 # Note that sending a message is included in the giant lock.
223 @write_queue.enq(str)
227 if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
229 return sprintf("%s %s %s %s +", rated? ? @player_id : @name, @protocol, @status, @game_name)
230 elsif (@sente == false)
231 return sprintf("%s %s %s %s -", rated? ? @player_id : @name, @protocol, @status, @game_name)
232 elsif (@sente == nil)
233 return sprintf("%s %s %s %s *", rated? ? @player_id : @name, @protocol, @status, @game_name)
236 return sprintf("%s %s %s", rated? ? @player_id : @name, @protocol, @status)
240 def run(csa_1st_str=nil)
241 while ( csa_1st_str ||
242 str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
243 log(:info, :in, str) if str && str.instance_of?(String)
246 if !@write_thread.alive?
247 log_error("%s's write thread is dead. Aborting..." % [@name])
250 if (@game && @game.turn?(self))
251 @socket_buffer << str
252 str = @socket_buffer.shift
254 log_debug("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")])
261 if (@status == "finished")
264 str.chomp! if (str.class == String) # may be strip! ?
267 # Application-level protocol for Keep-Alive
268 # If the server gets LF, it sends back LF.
269 # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
272 if (@status == "game")
273 array_str = str.split(",")
274 move = array_str.shift
275 additional = array_str.shift
277 if /^'(.*)/ =~ additional
278 comment = array_str.unshift("'*#{$1.toeuc}")
280 s = @game.handle_one_move(move, self)
281 @game.fh.print("#{Kconv.toeuc(comment.first)}\n") if (comment && comment.first && !s)
282 return if (s && @protocol == LoginCSA::PROTOCOL)
284 when /^%[^%]/, :timeout
285 if (@status == "game")
286 s = @game.handle_one_move(str, self)
287 return if (s && @protocol == LoginCSA::PROTOCOL)
290 log_error("Failed to receive a message from #{@name}.")
293 if (@status == "agree_waiting")
295 return if (@protocol == LoginCSA::PROTOCOL)
297 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
300 if (@status == "agree_waiting")
301 @status = "start_waiting"
302 if ((@game.sente.status == "start_waiting") &&
303 (@game.gote.status == "start_waiting"))
305 @game.sente.status = "game"
306 @game.gote.status = "game"
309 write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
311 when /^%%SHOW\s+(\S+)/
313 if ($league.games[game_id])
314 write_safe($league.games[game_id].show.gsub(/^/, '##[SHOW] '))
316 write_safe("##[SHOW] +OK\n")
317 when /^%%MONITORON\s+(\S+)/
319 if ($league.games[game_id])
320 $league.games[game_id].monitoron(self)
321 write_safe($league.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
322 write_safe("##[MONITOR][#{game_id}] +OK\n")
324 when /^%%MONITOROFF\s+(\S+)/
326 if ($league.games[game_id])
327 $league.games[game_id].monitoroff(self)
331 %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
333 players = $league.rated_players
334 players.sort {|a,b| b.rate <=> a.rate}.each do |p|
335 write_safe("##[RATING] %s \t %4d @%s\n" %
336 [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
338 write_safe("##[RATING] +OK\n")
340 write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
341 write_safe("##[VERSION] +OK\n")
343 if ((@status == "connected") || (@status == "game_waiting"))
344 @status = "connected"
347 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
349 when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
353 if (! Login::good_game_name?(game_name))
354 write_safe(sprintf("##[ERROR] bad game name\n"))
356 elsif ((@status == "connected") || (@status == "game_waiting"))
359 write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
364 if (League::Floodgate.game_name?(game_name))
365 if (my_sente_str != "*")
366 write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
371 if (my_sente_str == "*")
372 rival = $league.get_player("game_waiting", game_name, nil, self) # no preference
373 elsif (my_sente_str == "+")
374 rival = $league.get_player("game_waiting", game_name, false, self) # rival must be gote
375 elsif (my_sente_str == "-")
376 rival = $league.get_player("game_waiting", game_name, true, self) # rival must be sente
379 write_safe(sprintf("##[ERROR] bad game option\n"))
385 @game_name = game_name
386 if ((my_sente_str == "*") && (rival.sente == nil))
394 elsif (rival.sente == true) # rival has higher priority
396 elsif (rival.sente == false)
398 elsif (my_sente_str == "+")
401 elsif (my_sente_str == "-")
407 Game::new(@game_name, self, rival)
408 else # rival not found
409 if (command_name == "GAME")
410 @status = "game_waiting"
411 @game_name = game_name
412 if (my_sente_str == "+")
414 elsif (my_sente_str == "-")
420 write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
421 @status = "connected"
426 when /^%%CHAT\s+(.+)/
428 $league.players.each do |name, player|
429 if (player.protocol != LoginCSA::PROTOCOL)
430 player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message))
435 $league.games.each do |id, game|
436 buf.push(sprintf("##[LIST] %s\n", id))
438 buf.push("##[LIST] +OK\n")
442 $league.players.each do |name, player|
443 buf.push(sprintf("##[WHO] %s\n", player.to_s))
445 buf.push("##[WHO] +OK\n")
448 @status = "connected"
449 write_safe("LOGOUT:completed\n")
452 # This command is only available for CSA's official testing server.
453 # So, this means nothing for this program.
454 write_safe("CHALLENGE ACCEPTED\n")
456 ## ignore null string
458 msg = "##[ERROR] unknown command %s\n" % [str]