OSDN Git Service

Debugging Floodgate
[shogi-server/shogi-server.git] / shogi_server / player.rb
1 ## $Id$
2
3 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
4 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
5 ##
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.
10 ##
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.
15 ##
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
19
20 module ShogiServer # for a namespace
21
22 class BasicPlayer
23   def initialize
24     @player_id = nil
25     @name = nil
26     @password = nil
27     @rate = 0
28     @win  = 0
29     @loss = 0
30     @last_game_win = false
31   end
32
33   # Idetifier of the player in the rating system
34   attr_accessor :player_id
35
36   # Name of the player
37   attr_accessor :name
38   
39   # Password of the player, which does not include a trip
40   attr_accessor :password
41
42   # Score in the rating sysem
43   attr_accessor :rate
44
45   # Number of games for win and loss in the rating system
46   attr_accessor :win, :loss
47   
48   # Group in the rating system
49   attr_accessor :rating_group
50
51   # Last timestamp when the rate was modified
52   attr_accessor :modified_at
53
54   # Whether win the previous game or not
55   attr_accessor :last_game_win
56
57   def modified_at
58     @modified_at || Time.now
59   end
60
61   def rate=(new_rate)
62     if @rate != new_rate
63       @rate = new_rate
64       @modified_at = Time.now
65     end
66   end
67
68   def rated?
69     @player_id != nil
70   end
71
72   def last_game_win?
73     return @last_game_win
74   end
75
76   def simple_player_id
77     if @trip
78       simple_name = @name.gsub(/@.*?$/, '')
79       "%s+%s" % [simple_name, @trip[0..8]]
80     else
81       @name
82     end
83   end
84
85   ##
86   # Parses str in the LOGIN command, sets up @player_id and @trip
87   #
88   def set_password(str)
89     if str && !str.empty?
90       @password = str.strip
91       @player_id   = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
92     else
93       @player_id = @password = nil
94     end
95   end
96 end
97
98
99 class Player < BasicPlayer
100   WRITE_THREAD_WATCH_INTERVAL = 20 # sec
101   def initialize(str, socket, eol=nil)
102     super()
103     @socket = socket
104     @status = "connected"       # game_waiting -> agree_waiting -> start_waiting -> game -> finished
105
106     @protocol = nil             # CSA or x1
107     @eol = eol || "\m"          # favorite eol code
108     @game = nil
109     @game_name = ""
110     @mytime = 0                 # set in start method also
111     @sente = nil
112     @socket_buffer = []
113     @main_thread = Thread::current
114     @write_queue = ShogiServer::TimeoutQueue.new(WRITE_THREAD_WATCH_INTERVAL)
115     @player_logger = nil
116     start_write_thread
117   end
118
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
123   
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"
130   end
131
132   def log(level, direction, message)
133     return unless @player_logger
134     str = message.chomp
135     case direction
136       when :in
137         str = "IN: %s" % [str]
138       when :out
139         str = "OUT: %s" % [str]
140       else
141         str = "UNKNOWN DIRECTION: %s %s" % [direction, str]
142     end
143     case level
144       when :debug
145         @player_logger.debug(str)
146       when :info
147         @player_logger.info(str)
148       when :warn
149         @player_logger.warn(str)
150       when :error
151         @player_logger.error(str)
152       else
153         @player_logger.debug("UNKNOWN LEVEL: %s %s" % [level, str])
154     end
155   rescue Exception => ex
156     log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
157   end
158
159   def kill
160     log_message(sprintf("user %s killed", @name))
161     if (@game)
162       @game.kill(self)
163     end
164     finish
165     Thread::kill(@main_thread)  if @main_thread
166     Thread::kill(@write_thread) if @write_thread
167   end
168
169   def finish
170     if (@status != "finished")
171       @status = "finished"
172       log_message(sprintf("user %s finish", @name))    
173       begin
174         log_debug("Terminating %s's write thread..." % [@name])
175         write_safe(nil)
176         @write_thread.join
177         @player_logger.close if @player_logger
178       rescue
179         log_message(sprintf("user %s finish failed", @name))    
180       end
181     end
182   end
183
184   def start_write_thread
185     @write_thread = Thread.start do
186       Thread.pass
187       while !@socket.closed?
188         begin
189           str = @write_queue.deq
190           if (str == nil)
191             log_debug("%s's write thread terminated" % [@name])
192             break
193           end
194           if (str == :timeout)
195             log_debug("%s's write queue timed out. Try again..." % [@name])
196             next
197           end
198
199           if r = select(nil, [@socket], nil, 20)
200             r[1].first.write(str)
201             log(:info, :out, str)
202           else
203             log_error("Sending a message to #{@name} timed up.")
204           end
205         rescue Exception => ex
206           log_error("Failed to send a message to #{@name}. #{ex.class}: #{ex.message}\t#{ex.backtrace[0]}")
207         end
208       end # while loop
209       log_error("%s's socket closed." % [@name]) if @socket.closed?
210     end # thread
211   end
212
213   #
214   # Note that sending a message is included in the giant lock.
215   #
216   def write_safe(str)
217     @write_queue.enq(str)
218   end
219
220   def to_s
221     if ["game_waiting", "start_waiting", "agree_waiting", "game"].include?(status)
222       if (@sente)
223         return sprintf("%s %s %s %s +", rated? ? @player_id : @name, @protocol, @status, @game_name)
224       elsif (@sente == false)
225         return sprintf("%s %s %s %s -", rated? ? @player_id : @name, @protocol, @status, @game_name)
226       elsif (@sente == nil)
227         return sprintf("%s %s %s %s *", rated? ? @player_id : @name, @protocol, @status, @game_name)
228       end
229     else
230       return sprintf("%s %s %s", rated? ? @player_id : @name, @protocol, @status)
231     end
232   end
233
234   def run(csa_1st_str=nil)
235     while ( csa_1st_str || 
236             str = gets_safe(@socket, (@socket_buffer.empty? ? Default_Timeout : 1)) )
237       log(:info, :in, str) if str && str.instance_of?(String) 
238       $mutex.lock
239       begin
240         if !@write_thread.alive?
241           log_error("%s's write thread is dead. Aborting..." % [@name])
242           return
243         end
244         if (@game && @game.turn?(self))
245           @socket_buffer << str
246           str = @socket_buffer.shift
247         end
248         log_debug("%s (%s)" % [str, @socket_buffer.map {|a| String === a ? a.strip : a }.join(",")])
249
250         if (csa_1st_str)
251           str = csa_1st_str
252           csa_1st_str = nil
253         end
254
255         if (@status == "finished")
256           return
257         end
258         str.chomp! if (str.class == String) # may be strip! ?
259         case str 
260         when "" 
261           # Application-level protocol for Keep-Alive
262           # If the server gets LF, it sends back LF.
263           # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
264           write_safe("\n")
265         when /^[\+\-][^%]/
266           if (@status == "game")
267             array_str = str.split(",")
268             move = array_str.shift
269             additional = array_str.shift
270             if /^'(.*)/ =~ additional
271               comment = array_str.unshift("'*#{$1.toeuc}")
272             end
273             s = @game.handle_one_move(move, self)
274             @game.fh.print("#{Kconv.toeuc(comment.first)}\n") if (comment && comment.first && !s)
275             return if (s && @protocol == LoginCSA::PROTOCOL)
276           end
277         when /^%[^%]/, :timeout
278           if (@status == "game")
279             s = @game.handle_one_move(str, self)
280             return if (s && @protocol == LoginCSA::PROTOCOL)
281           end
282         when :exception
283           log_error("Failed to receive a message from #{@name}.")
284           return
285         when /^REJECT/
286           if (@status == "agree_waiting")
287             @game.reject(@name)
288             return if (@protocol == LoginCSA::PROTOCOL)
289           else
290             write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
291           end
292         when /^AGREE/
293           if (@status == "agree_waiting")
294             @status = "start_waiting"
295             if ((@game.sente.status == "start_waiting") &&
296                 (@game.gote.status == "start_waiting"))
297               @game.start
298               @game.sente.status = "game"
299               @game.gote.status = "game"
300             end
301           else
302             write_safe(sprintf("##[ERROR] you are in %s status. AGREE is valid in agree_waiting status\n", @status))
303           end
304         when /^%%SHOW\s+(\S+)/
305           game_id = $1
306           if (LEAGUE.games[game_id])
307             write_safe(LEAGUE.games[game_id].show.gsub(/^/, '##[SHOW] '))
308           end
309           write_safe("##[SHOW] +OK\n")
310         when /^%%MONITORON\s+(\S+)/
311           game_id = $1
312           if (LEAGUE.games[game_id])
313             LEAGUE.games[game_id].monitoron(self)
314             write_safe(LEAGUE.games[game_id].show.gsub(/^/, "##[MONITOR][#{game_id}] "))
315             write_safe("##[MONITOR][#{game_id}] +OK\n")
316           end
317         when /^%%MONITOROFF\s+(\S+)/
318           game_id = $1
319           if (LEAGUE.games[game_id])
320             LEAGUE.games[game_id].monitoroff(self)
321           end
322         when /^%%HELP/
323           write_safe(
324             %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
325         when /^%%RATING/
326           players = LEAGUE.rated_players
327           players.sort {|a,b| b.rate <=> a.rate}.each do |p|
328             write_safe("##[RATING] %s \t %4d @%s\n" % 
329                        [p.simple_player_id, p.rate, p.modified_at.strftime("%Y-%m-%d")])
330           end
331           write_safe("##[RATING] +OK\n")
332         when /^%%VERSION/
333           write_safe "##[VERSION] Shogi Server revision #{Revision}\n"
334           write_safe("##[VERSION] +OK\n")
335         when /^%%GAME\s*$/
336           if ((@status == "connected") || (@status == "game_waiting"))
337             @status = "connected"
338             @game_name = ""
339           else
340             write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
341           end
342         when /^%%(GAME|CHALLENGE)\s+(\S+)\s+([\+\-\*])\s*$/
343           command_name = $1
344           game_name = $2
345           my_sente_str = $3
346           if (! Login::good_game_name?(game_name))
347             write_safe(sprintf("##[ERROR] bad game name\n"))
348             next
349           elsif ((@status == "connected") || (@status == "game_waiting"))
350             ## continue
351           else
352             write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
353             next
354           end
355
356           rival = nil
357           if (League::Floodgate.game_name?(game_name))
358             if (my_sente_str != "*")
359               write_safe(sprintf("##[ERROR] You are not allowed to specify TEBAN %s for the game %s\n", my_sente_str, game_name))
360               next
361             end
362             @sente = nil
363           else
364             if (my_sente_str == "*")
365               rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
366             elsif (my_sente_str == "+")
367               rival = LEAGUE.get_player("game_waiting", game_name, false, self) # rival must be gote
368             elsif (my_sente_str == "-")
369               rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
370             else
371               ## never reached
372               write_safe(sprintf("##[ERROR] bad game option\n"))
373               next
374             end
375           end
376
377           if (rival)
378             @game_name = game_name
379             if ((my_sente_str == "*") && (rival.sente == nil))
380               if (rand(2) == 0)
381                 @sente = true
382                 rival.sente = false
383               else
384                 @sente = false
385                 rival.sente = true
386               end
387             elsif (rival.sente == true) # rival has higher priority
388               @sente = false
389             elsif (rival.sente == false)
390               @sente = true
391             elsif (my_sente_str == "+")
392               @sente = true
393               rival.sente = false
394             elsif (my_sente_str == "-")
395               @sente = false
396               rival.sente = true
397             else
398               ## never reached
399             end
400             Game::new(@game_name, self, rival)
401           else # rival not found
402             if (command_name == "GAME")
403               @status = "game_waiting"
404               @game_name = game_name
405               if (my_sente_str == "+")
406                 @sente = true
407               elsif (my_sente_str == "-")
408                 @sente = false
409               else
410                 @sente = nil
411               end
412             else                # challenge
413               write_safe(sprintf("##[ERROR] can't find rival for %s\n", game_name))
414               @status = "connected"
415               @game_name = ""
416               @sente = nil
417             end
418           end
419         when /^%%CHAT\s+(.+)/
420           message = $1
421           LEAGUE.players.each do |name, player|
422             if (player.protocol != LoginCSA::PROTOCOL)
423               player.write_safe(sprintf("##[CHAT][%s] %s\n", @name, message)) 
424             end
425           end
426         when /^%%LIST/
427           buf = Array::new
428           LEAGUE.games.each do |id, game|
429             buf.push(sprintf("##[LIST] %s\n", id))
430           end
431           buf.push("##[LIST] +OK\n")
432           write_safe(buf.join)
433         when /^%%WHO/
434           buf = Array::new
435           LEAGUE.players.each do |name, player|
436             buf.push(sprintf("##[WHO] %s\n", player.to_s))
437           end
438           buf.push("##[WHO] +OK\n")
439           write_safe(buf.join)
440         when /^LOGOUT/
441           @status = "connected"
442           write_safe("LOGOUT:completed\n")
443           return
444         when /^CHALLENGE/
445           # This command is only available for CSA's official testing server.
446           # So, this means nothing for this program.
447           write_safe("CHALLENGE ACCEPTED\n")
448         when /^\s*$/
449           ## ignore null string
450         else
451           msg = "##[ERROR] unknown command %s\n" % [str]
452           write_safe(msg)
453           log_error(msg)
454         end
455       ensure
456         $mutex.unlock
457       end
458     end # enf of while
459   end # def run
460 end # class
461
462 end # ShogiServer