OSDN Git Service

Refactoring
[shogi-server/shogi-server.git] / shogi-server
index 4817880..14b2767 100755 (executable)
@@ -2,6 +2,7 @@
 ## $Id$
 
 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
+## Copyright (C) 2007 Daigo Moriwaki (daigo at debian dot org)
 ##
 ## This program is free software; you can redistribute it and/or modify
 ## it under the terms of the GNU General Public License as published by
 ## along with this program; if not, write to the Free Software
 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
-Max_Write_Queue_Size = 1000
-Max_Identifier_Length = 32
-Default_Timeout = 60            # for single socket operation
-
-Default_Game_Name = "default-1500-0"
-
-One_Time = 10
-Least_Time_Per_Move = 1
-Login_Time = 300                # time for LOGIN
-
-Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
-Release.concat("-") if (Release == "")
-Revision = "$Revision$".gsub(/[^\.\d]/, '')
-
-STDOUT.sync = true
-STDERR.sync = true
-
 require 'getoptlong'
 require 'thread'
 require 'timeout'
@@ -41,9 +25,8 @@ require 'socket'
 require 'yaml'
 require 'yaml/store'
 require 'digest/md5'
-
-TCPSocket.do_not_reverse_lookup = true
-Thread.abort_on_exception = true
+require 'webrick'
+require 'fileutils'
 
 
 class TCPSocket
@@ -66,8 +49,9 @@ class TCPSocket
         end
       rescue TimeoutError
         return :timeout
-      rescue
-        return nil
+      rescue Exception => ex
+        log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
+        return :exception
       end
     else
       begin
@@ -87,14 +71,36 @@ class TCPSocket
 end
 
 
+module ShogiServer # for a namespace
+
+Max_Write_Queue_Size = 1000
+Max_Identifier_Length = 32
+Default_Timeout = 60            # for single socket operation
+
+Default_Game_Name = "default-1500-0"
+
+One_Time = 10
+Least_Time_Per_Move = 1
+Login_Time = 300                # time for LOGIN
+
+Release = "$Name$".split[1].sub(/\A[^\d]*/, '').gsub(/_/, '.')
+Release.concat("-") if (Release == "")
+Revision = "$Revision$".gsub(/[^\.\d]/, '')
+
+
 class League
   def initialize
     @games = Hash::new
     @players = Hash::new
     @event = nil
-    @db = YAML::Store.new( File.join(File.dirname(__FILE__), "players.yaml") )
+    @dir = File.dirname(__FILE__)
+  end
+  attr_accessor :players, :games, :event, :dir
+
+  # this should be called just after instanciating a League object.
+  def setup_players_database
+    @db = YAML::Store.new(File.join(@dir, "players.yaml"))
   end
-  attr_accessor :players, :games, :event
 
   def add(player)
     self.load(player) if player.id
@@ -105,32 +111,37 @@ class League
     @players.delete(player.name)
   end
   
-  def get_player(status, game_name, sente, searcher=nil)
-    @players.each do |name, player|
-      if ((player.status == status) &&
-          (player.game_name == game_name) &&
-          ((sente == nil) || (player.sente == nil) || (player.sente == sente)) &&
-          ((searcher == nil) || (player != searcher)))
-        return player
-      end
+  def get_player(status, game_name, sente, searcher)
+    found = @players.find do |name, player|
+      (player.status == status) &&
+      (player.game_name == game_name) &&
+      ( (sente == nil) || 
+        (player.sente == nil) || 
+        (player.sente == sente) ) &&
+      (player != searcher)
     end
-    return nil
+    return found ? found.last : nil
   end
   
   def load(player)
     hash = search(player.id)
     if hash
       # a current user
-      player.name = hash['name']
-      player.rate = hash['rate']
-      player.modified_at = hash['last_modified']
+      player.name         = hash['name']
+      player.rate         = hash['rate']
+      player.modified_at  = hash['last_modified']
+      player.rating_group = hash['rating_group']
     end
   end
 
   def search(id)
     hash = nil
     @db.transaction do
-      hash = @db[id]
+      break unless  @db["players"]
+      @db["players"].each do |group, players|
+        hash = players[id]
+        break if hash
+      end
     end
     hash
   end
@@ -138,11 +149,12 @@ class League
   def rated_players
     players = []
     @db.transaction(true) do
-      @db.roots.each do |id|
-        players << id
+      break unless  @db["players"]
+      @db["players"].each do |group, players_hash|
+        players << players_hash.keys
       end
     end
-    return players.collect do |id|
+    return players.flatten.collect do |id|
       p = BasicPlayer.new
       p.id = id
       self.load(p)
@@ -152,67 +164,9 @@ class League
 end
 
 
-class BasicPlayer
-  # Idetifier of the player in the rating system
-  attr_accessor :id
-
-  # Name of the player
-  attr_accessor :name
-  
-  # Password of the player, which does not include a trip
-  attr_accessor :password
-
-  # Score in the rating sysem
-  attr_accessor :rate
-  
-  # Last timestamp when the rate was modified
-  attr_accessor :modified_at
-
-
-
-  def initialize
-    @name = nil
-    @password = nil
-  end
-
-  def modified_at
-    @modified_at || Time.now
-  end
-
-  def rate=(new_rate)
-    if @rate != new_rate
-      @rate = new_rate
-      @modified_at = Time.now
-    end
-  end
-
-  def rated?
-    @id != nil
-  end
-
-  def simple_id
-    if @trip
-      simple_name = @name.gsub(/@.*?$/, '')
-      "%s+%s" % [simple_name, @trip[0..8]]
-    else
-      @name
-    end
-  end
-
-  ##
-  # Parses str in the LOGIN command, sets up @id and @trip
-  #
-  def set_password(str)
-    if str && !str.empty?
-      @password = str.strip
-      @id   = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
-    else
-      @id = @password = nil
-    end
-  end
-end
-
-
+######################################################
+# Processes the LOGIN command.
+#
 class Login
   def Login.good_login?(str)
     tokens = str.split
@@ -243,69 +197,155 @@ class Login
 
   def Login.factory(str, player)
     (login, player.name, password, ext) = str.chomp.split
-    player.set_password(password)
     if (ext)
-      return Loginx1.new(player)
+      return Loginx1.new(player, password)
     else
-      return LoginCSA.new(player)
+      return LoginCSA.new(player, password)
     end
   end
 
-  attr_reader :player, :csa_1st_str
+  attr_reader :player
+  
+  # the first command that will be executed just after LOGIN.
+  # If it is nil, the default process will be started.
+  attr_reader :csa_1st_str
 
-  def initialize(player)
+  def initialize(player, password)
     @player = player
     @csa_1st_str = nil
+    parse_password(password)
   end
 
   def process
     @player.write_safe(sprintf("LOGIN:%s OK\n", @player.name))
+    log_message(sprintf("user %s run in %s mode", @player.name, @player.protocol))
   end
 
   def incorrect_duplicated_player(str)
     @player.write_safe("LOGIN:incorrect\n")
     @player.write_safe(sprintf("username %s is already connected\n", @player.name)) if (str.split.length >= 4)
     sleep 3 # wait for sending the above messages.
-    @palyer.name = "%s [duplicated]" % [@player.name]
+    @player.name = "%s [duplicated]" % [@player.name]
     @player.finish
   end
 end
 
+######################################################
+# Processes LOGIN for the CSA standard mode.
+#
 class LoginCSA < Login
   PROTOCOL = "CSA"
 
-  def initialize(player)
+  def initialize(player, password)
+    @gamename = nil
     super
     @player.protocol = PROTOCOL
   end
 
-  def process
-    super
-    log_message(sprintf("user %s run in CSA mode", @player.name))
-    if (self.class.good_game_name?(@player.password))
-      @csa_1st_str = "%%GAME #{@player.password} *"
+  def parse_password(password)
+    if Login.good_game_name?(password)
+      @gamename = password
+      @player.set_password(nil)
+    elsif password.split(",").size > 1
+      @gamename, *trip = password.split(",")
+      @player.set_password(trip.join(","))
     else
-      @csa_1st_str = "%%GAME #{Default_Game_Name} *"
+      @player.set_password(password)
+      @gamename = Default_Game_Name
     end
+    @gamename = self.class.good_game_name?(@gamename) ? @gamename : Default_Game_Name
+  end
+
+  def process
+    super
+    @csa_1st_str = "%%GAME #{@gamename} *"
   end
 end
 
+######################################################
+# Processes LOGIN for the extented mode.
+#
 class Loginx1 < Login
   PROTOCOL = "x1"
 
-  def initialize(player)
+  def initialize(player, password)
     super
     @player.protocol = PROTOCOL
   end
-    
+  
+  def parse_password(password)
+    @player.set_password(password)
+  end
+
   def process
     super
-    log_message(sprintf("user %s run in %s mode", @player.name, PROTOCOL))
     @player.write_safe(sprintf("##[LOGIN] +OK %s\n", PROTOCOL))
   end
 end
 
 
+class BasicPlayer
+  # Idetifier of the player in the rating system
+  attr_accessor :id
+
+  # Name of the player
+  attr_accessor :name
+  
+  # Password of the player, which does not include a trip
+  attr_accessor :password
+
+  # Score in the rating sysem
+  attr_accessor :rate
+  
+  # Group in the rating system
+  attr_accessor :rating_group
+
+  # Last timestamp when the rate was modified
+  attr_accessor :modified_at
+
+  def initialize
+    @name = nil
+    @password = nil
+  end
+
+  def modified_at
+    @modified_at || Time.now
+  end
+
+  def rate=(new_rate)
+    if @rate != new_rate
+      @rate = new_rate
+      @modified_at = Time.now
+    end
+  end
+
+  def rated?
+    @id != nil
+  end
+
+  def simple_id
+    if @trip
+      simple_name = @name.gsub(/@.*?$/, '')
+      "%s+%s" % [simple_name, @trip[0..8]]
+    else
+      @name
+    end
+  end
+
+  ##
+  # Parses str in the LOGIN command, sets up @id and @trip
+  #
+  def set_password(str)
+    if str && !str.empty?
+      @password = str.strip
+      @id   = "%s+%s" % [@name, Digest::MD5.hexdigest(@password)]
+    else
+      @id = @password = nil
+    end
+  end
+end
+
+
 class Player < BasicPlayer
   def initialize(str, socket)
     super()
@@ -346,7 +386,7 @@ class Player < BasicPlayer
       # TODO you should confirm that there is no message in the queue.
       Thread::kill(@writer_thread) if @writer_thread
       begin
-        @socket.close if (! @socket.closed?)
+#        @socket.close if (! @socket.closed?)
       rescue
         log_message(sprintf("user %s finish failed", @name))    
       end
@@ -359,7 +399,13 @@ class Player < BasicPlayer
 
   def writer
     while (str = @write_queue.pop)
-      @socket.write_safe(str)
+      begin
+        @socket.write(str)
+      rescue Exception => ex
+        log_error("Failed to send a message to #{@name}.")
+        log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
+        return
+      end
     end
   end
 
@@ -380,14 +426,16 @@ class Player < BasicPlayer
     end
   end
 
-  def write_help
-    @socket.write_safe('##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"')
-  end
-
   def run(csa_1st_str=nil)
     while (csa_1st_str || (str = @socket.gets_safe(Default_Timeout)))
       begin
         $mutex.lock
+
+        if (@writer_thread == nil || @writer_thread.status == false)
+          # The writer_thread has been killed because of socket errors.
+          return
+        end
+
         if (csa_1st_str)
           str = csa_1st_str
           csa_1st_str = nil
@@ -400,8 +448,14 @@ class Player < BasicPlayer
         if (@status == "finished")
           return
         end
-        str.chomp! if (str.class == String)
-        case str
+        str.chomp! if (str.class == String) # may be strip! ?
+        log_message(str) if $DEBUG
+        case str 
+        when "" 
+          # Application-level protocol for Keep-Alive
+          # If the server gets LF, it sends back LF.
+          # 30 sec rule (client may not send LF again within 30 sec) is not implemented yet.
+          write_safe("\n")
         when /^[\+\-][^%]/
           if (@status == "game")
             array_str = str.split(",")
@@ -418,7 +472,18 @@ class Player < BasicPlayer
           if (@status == "game")
             s = @game.handle_one_move(str, self)
             return if (s && @protocol == LoginCSA::PROTOCOL)
+          # else
+          #   begin
+          #     @socket.write("##[KEEPALIVE] #{Time.now}\n")
+          #   rescue Exception => ex
+          #     log_error("Failed to send a keepalive to #{@name}.")
+          #     log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
+          #     return
+          #   end
           end
+        when :exception
+          log_error("Failed to receive a message from #{@name}.")
+          return
         when /^REJECT/
           if (@status == "agree_waiting")
             @game.reject(@name)
@@ -457,7 +522,8 @@ class Player < BasicPlayer
             LEAGUE.games[game_id].monitoroff(self)
           end
         when /^%%HELP/
-          write_help
+          write_safe(
+            %!##[HELP] available commands "%%WHO", "%%CHAT str", "%%GAME game_name +", "%%GAME game_name -"\n!)
         when /^%%RATING/
           players = LEAGUE.rated_players
           players.sort {|a,b| b.rate <=> a.rate}.each do |p|
@@ -488,14 +554,6 @@ class Player < BasicPlayer
             write_safe(sprintf("##[ERROR] you are in %s status. GAME is valid in connected or game_waiting status\n", @status))
             next
           end
-          if ((my_sente_str == "*") ||
-              (my_sente_str == "+") ||
-              (my_sente_str == "-"))
-            ## ok
-          else
-            write_safe(sprintf("##[ERROR] bad game option\n"))
-            next
-          end
 
           if (my_sente_str == "*")
             rival = LEAGUE.get_player("game_waiting", game_name, nil, self) # no preference
@@ -505,7 +563,10 @@ class Player < BasicPlayer
             rival = LEAGUE.get_player("game_waiting", game_name, true, self) # rival must be sente
           else
             ## never reached
+            write_safe(sprintf("##[ERROR] bad game option\n"))
+            next
           end
+
           if (rival)
             @game_name = game_name
             if ((my_sente_str == "*") && (rival.sente == nil))
@@ -575,17 +636,23 @@ class Player < BasicPlayer
           @status = "connected"
           write_safe("LOGOUT:completed\n")
           return
+        when /^CHALLENGE/
+          # This command is only available for CSA's official testing server.
+          # So, this means nothing for this program.
+          write_safe("CHALLENGE ACCEPTED\n")
         when /^\s*$/
           ## ignore null string
         else
-          write_safe(sprintf("##[ERROR] unknown command %s\n", str))
+          msg = "##[ERROR] unknown command %s\n" % [str]
+          write_safe(msg)
+          log_error(msg)
         end
       ensure
         $mutex.unlock
       end
-    end                         # enf of while
-  end
-end
+    end # enf of while
+  end # def run
+end # class
 
 class Piece
   PROMOTE = {"FU" => "TO", "KY" => "NY", "KE" => "NK", "GI" => "NG", "KA" => "UM", "HI" => "RY"}
@@ -965,10 +1032,10 @@ end
 class Board
   def initialize
     @sente_hands = Array::new
-    @gote_hands = Array::new
-    @history = Hash::new
-    @sente_history = Hash::new
-    @gote_history = Hash::new
+    @gote_hands  = Array::new
+    @history       = Hash::new(0)
+    @sente_history = Hash::new(0)
+    @gote_history  = Hash::new(0)
     @array = [[], [], [], [], [], [], [], [], [], []]
     @move_count = 0
   end
@@ -987,15 +1054,9 @@ class Board
     PieceKY::new(self, 9, 1, false)
     PieceKA::new(self, 2, 2, false)
     PieceHI::new(self, 8, 2, false)
-    PieceFU::new(self, 1, 3, false)
-    PieceFU::new(self, 2, 3, false)
-    PieceFU::new(self, 3, 3, false)
-    PieceFU::new(self, 4, 3, false)
-    PieceFU::new(self, 5, 3, false)
-    PieceFU::new(self, 6, 3, false)
-    PieceFU::new(self, 7, 3, false)
-    PieceFU::new(self, 8, 3, false)
-    PieceFU::new(self, 9, 3, false)
+    (1..9).each do |i|
+      PieceFU::new(self, i, 3, false)
+    end
 
     PieceKY::new(self, 1, 9, true)
     PieceKE::new(self, 2, 9, true)
@@ -1008,15 +1069,9 @@ class Board
     PieceKY::new(self, 9, 9, true)
     PieceKA::new(self, 8, 8, true)
     PieceHI::new(self, 2, 8, true)
-    PieceFU::new(self, 1, 7, true)
-    PieceFU::new(self, 2, 7, true)
-    PieceFU::new(self, 3, 7, true)
-    PieceFU::new(self, 4, 7, true)
-    PieceFU::new(self, 5, 7, true)
-    PieceFU::new(self, 6, 7, true)
-    PieceFU::new(self, 7, 7, true)
-    PieceFU::new(self, 8, 7, true)
-    PieceFU::new(self, 9, 7, true)
+    (1..9).each do |i|
+      PieceFU::new(self, i, 7, true)
+    end
   end
 
   def have_piece?(hands, name)
@@ -1035,20 +1090,20 @@ class Board
 
     if ((x0 == 0) || (y0 == 0))
       piece = have_piece?(hands, name)
-      return :illegal if (! piece.move_to?(x1, y1, name))
+      return :illegal if (! piece.move_to?(x1, y1, name)) # TODO null check for the piece?
       piece.move_to(x1, y1)
     else
-      return :illegal if (! @array[x0][y0].move_to?(x1, y1, name))
+      return :illegal if (! @array[x0][y0].move_to?(x1, y1, name))  # TODO null check?
       if (@array[x0][y0].name != name) # promoted ?
         @array[x0][y0].promoted = true
       end
-      if (@array[x1][y1])
+      if (@array[x1][y1]) # capture
         if (@array[x1][y1].name == "OU")
           return :outori        # return board update
         end
         @array[x1][y1].sente = @array[x0][y0].sente
         @array[x1][y1].move_to(0, 0)
-        hands.sort! {|a, b|
+        hands.sort! {|a, b| # TODO refactor. Move to Piece class
           a.name <=> b.name
         }
       end
@@ -1075,6 +1130,7 @@ class Board
     raise "can't find ou"
   end
 
+  # note checkmate, but check. sente is checked.
   def checkmated?(sente)        # sente is loosing
     ou = look_for_ou(sente)
     x = 1
@@ -1156,25 +1212,44 @@ class Board
     return true
   end
 
-  def oute_sennichite?(sente)
-    if (checkmated?(! sente))
-      str = to_s
-      if (sente)
-        if (@sente_history[str] && (@sente_history[str] >= 3)) # already 3 times
-          return true
-        end
+  # @[sente|gote]_history has at least one item while the player is checking the other or 
+  # the other escapes.
+  def update_sennichite(player)
+    str = to_s
+    @history[str] += 1
+    if checkmated?(!player)
+      if (player)
+        @sente_history["dummy"] = 1  # flag to see Sente player is checking Gote player
       else
-        if (@gote_history[str] && (@gote_history[str] >= 3)) # already 3 times
-          return true
-        end
+        @gote_history["dummy"]  = 1  # flag to see Gote player is checking Sente player
+      end
+    else
+      if (player)
+        @sente_history.clear # no more continuous check
+      else
+        @gote_history.clear  # no more continuous check
       end
     end
-    return false
+    if @sente_history.size > 0  # possible for Sente's or Gote's turn
+      @sente_history[str] += 1
+    end
+    if @gote_history.size > 0   # possible for Sente's or Gote's turn
+      @gote_history[str] += 1
+    end
+  end
+
+  def oute_sennichite?(player)
+    if (@sente_history[to_s] >= 4)
+      return :oute_sennichite_sente_lose
+    elsif (@gote_history[to_s] >= 4)
+      return :oute_sennichite_gote_lose
+    else
+      return nil
+    end
   end
 
   def sennichite?(sente)
-    str = to_s
-    if (@history[str] && (@history[str] >= 3)) # already 3 times
+    if (@history[to_s] >= 4) # already 3 times
       return true
     end
     return false
@@ -1242,6 +1317,7 @@ class Board
     return true
   end
 
+  # sente is nil only if tests in test_board run
   def handle_one_move(str, sente=nil)
     if (str =~ /^([\+\-])(\d)(\d)(\d)(\d)([A-Z]{2})/)
       sg = $1
@@ -1270,11 +1346,14 @@ class Board
       return :illegal
     end
     
+
     if (sg == "+")
-      sente = true
+      sente = true if sente == nil           # deprecated
+      return :illegal unless sente == true   # black player's move must be black
       hands = @sente_hands
     else
-      sente = false
+      sente = false if sente == nil          # deprecated
+      return :illegal unless sente == false  # white player's move must be white
       hands = @gote_hands
     end
     
@@ -1300,7 +1379,9 @@ class Board
     tmp_board = Marshal.load(Marshal.dump(self))
     return :illegal if (tmp_board.move_to(x0, y0, x1, y1, name, sente) == :illegal)
     return :oute_kaihimore if (tmp_board.checkmated?(sente))
-    return :oute_sennichite if tmp_board.oute_sennichite?(sente)
+    tmp_board.update_sennichite(sente)
+    os_result = tmp_board.oute_sennichite?(sente)
+    return os_result if os_result # :oute_sennichite_sente_lose or :oute_sennichite_gote_lose
     return :sennichite if tmp_board.sennichite?(sente)
 
     if ((x0 == 0) && (y0 == 0) && (name == "FU") && tmp_board.uchifuzume?(sente))
@@ -1310,20 +1391,7 @@ class Board
     move_to(x0, y0, x1, y1, name, sente)
     str = to_s
 
-    if (checkmated?(! sente))
-      if (sente)
-        @sente_history[str] = (@sente_history[str] || 0) + 1
-      else
-        @gote_history[str] = (@gote_history[str] || 0) + 1
-      end
-    else
-      if (sente)
-        @sente_history.clear
-      else
-        @gote_history.clear
-      end
-    end
-    @history[str] = (@history[str] || 0) + 1
+    update_sennichite(sente)
     return :normal
   end
 
@@ -1369,9 +1437,7 @@ class GameResult
   attr_reader :players, :black, :white
 
   def initialize(p1, p2)
-    @players = []
-    @players << p1
-    @players << p2
+    @players = [p1, p2]
     if p1.sente && !p2.sente
       @black, @white = p1, p2
     elsif !p1.sente && p2.sente
@@ -1434,7 +1500,7 @@ class Game
     
     @id = sprintf("%s+%s+%s+%s+%s", 
                   LEAGUE.event, @game_name, @sente.name, @gote.name, issue_current_time)
-    @logfile = @id + ".csa"
+    @logfile = File.join(LEAGUE.dir, @id + ".csa")
 
     LEAGUE.games[@id] = self
 
@@ -1532,7 +1598,7 @@ class Game
         if ((move_status == :illegal) || (move_status == :uchifuzme) || (move_status == :oute_kaihimore))
           @fh.printf("'ILLEGAL_MOVE(%s)\n", str)
         else
-          if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite))
+          if ((move_status == :normal) || (move_status == :outori) || (move_status == :sennichite) || (move_status == :oute_sennichite_sente_lose) || (move_status == :oute_sennichite_gote_lose))
             @sente.write_safe(sprintf("%s,T%d\n", str, t))
             @gote.write_safe(sprintf("%s,T%d\n", str, t))
             @fh.printf("%s\nT%d\n", str, t)
@@ -1561,10 +1627,12 @@ class Game
         toryo_lose()
       elsif (move_status == :outori)
         outori_win()
+      elsif (move_status == :oute_sennichite_sente_lose)
+        oute_sennichite_win_lose(@gote, @sente) # Sente is checking
+      elsif (move_status == :oute_sennichite_gote_lose)
+        oute_sennichite_win_lose(@sente, @gote) # Gote is checking
       elsif (move_status == :sennichite)
         sennichite_draw()
-      elsif (move_status == :oute_sennichite)
-        oute_sennichite_lose()
       elsif (move_status == :uchifuzume)
         uchifuzume_lose()
       elsif (move_status == :oute_kaihimore)
@@ -1623,14 +1691,18 @@ class Game
     end
   end
 
-  def oute_sennichite_lose
+  def oute_sennichite_win_lose(winner, loser)
     @current_player.status = "connected"
     @next_player.status = "connected"
-    @current_player.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
-    @next_player.write_safe("#OUTE_SENNICHITE\n#WIN\n")
+    loser.write_safe("#OUTE_SENNICHITE\n#LOSE\n")
+    winner.write_safe("#OUTE_SENNICHITE\n#WIN\n")
     @fh.print(@board.to_s.gsub(/^/, "\'"))
-    @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
-    @result = GameResultWin.new(@next_player, @current_player)
+    if loser == @current_player
+      @fh.printf("'summary:oute_sennichite:%s lose:%s win\n", @current_player.name, @next_player.name)
+    else
+      @fh.printf("'summary:oute_sennichite:%s win:%s lose\n", @current_player.name, @next_player.name)
+    end
+    @result = GameResultWin.new(winner, loser)
     @fh.printf("'rating:#{@result.to_s}\n") if rated?
     @monitors.each do |monitor|
       monitor.write_safe(sprintf("##[MONITOR][%s] #OUTE_SENNICHITE\n", @id))
@@ -1762,20 +1834,20 @@ class Game
   end
 
   def propose
-    begin
-      @fh = open(@logfile, "w")
-      @fh.sync = true
+    @fh = open(@logfile, "w")
+    @fh.sync = true
 
-      @fh.printf("V2\n")
-      @fh.printf("N+%s\n", @sente.name)
-      @fh.printf("N-%s\n", @gote.name)
-      @fh.printf("$EVENT:%s\n", @id)
+    @fh.puts("V2")
+    @fh.puts("N+#{@sente.name}")
+    @fh.puts("N-#{@gote.name}")
+    @fh.puts("$EVENT:#{@id}")
 
-      @sente.write_safe(propose_message("+"))
-      @gote.write_safe(propose_message("-"))
+    @sente.write_safe(propose_message("+"))
+    @gote.write_safe(propose_message("-"))
 
-      @fh.printf("$START_TIME:%s\n", Time::new.strftime("%Y/%m/%d %H:%M:%S"))
-      @fh.print <<EOM
+    now = Time::new.strftime("%Y/%m/%d %H:%M:%S")
+    @fh.puts("$START_TIME:#{now}")
+    @fh.print <<EOM
 P1-KY-KE-GI-KI-OU-KI-GI-KE-KY
 P2 * -HI *  *  *  *  * -KA * 
 P3-FU-FU-FU-FU-FU-FU-FU-FU-FU
@@ -1787,7 +1859,6 @@ P8 * +KA *  *  *  *  * +HI *
 P9+KY+KE+GI+KI+OU+KI+GI+KE+KY
 +
 EOM
-    end
   end
 
   def show()
@@ -1873,6 +1944,7 @@ EOM
     end
   end
 end
+end # module ShogiServer
 
 #################################################
 # MAIN
@@ -1884,7 +1956,7 @@ NAME
        shogi-server - server for CSA server protocol
 
 SYNOPSIS
-       shogi-server event_name port_number
+       shogi-server [OPTIONS] event_name port_number
 
 DESCRIPTION
        server for CSA server protocol
@@ -1892,6 +1964,8 @@ DESCRIPTION
 OPTIONS
        --pid-file file
                specify filename for logging process ID
+    --daemon dir
+        run as a daemon. Log files will be put in dir.
 
 LICENSE
        this file is distributed under GPL version2 and might be compiled by Exerb
@@ -1899,33 +1973,35 @@ LICENSE
 SEE ALSO
 
 RELEASE
-       #{Release}
+       #{ShogiServer::Release}
 
 REVISION
-       #{Revision}
+       #{ShogiServer::Revision}
 EOM
 end
 
+def log_debug(str)
+  $logger.debug(str)
+end
+
 def log_message(str)
-  printf("%s message: %s\n", Time::new.to_s, str)
+  $logger.info(str)
 end
 
 def log_warning(str)
-  printf("%s warning: %s\n", Time::new.to_s, str)
+  $logger.warn(str)
 end
 
 def log_error(str)
-  printf("%s error: %s\n", Time::new.to_s, str)
+  $logger.error(str)
 end
 
 
 def parse_command_line
   options = Hash::new
-  parser = GetoptLong.new
-  parser.ordering = GetoptLong::REQUIRE_ORDER
-  parser.set_options(
-                     ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
-
+  parser = GetoptLong.new( ["--daemon",         GetoptLong::REQUIRED_ARGUMENT],
+                           ["--pid-file",       GetoptLong::REQUIRED_ARGUMENT]
+                         )
   parser.quiet = true
   begin
     parser.each_option do |name, arg|
@@ -1939,7 +2015,7 @@ def parse_command_line
   return options
 end
 
-def  write_pid_file(file)
+def write_pid_file(file)
   open(file, "w") do |fh|
     fh.print Process::pid, "\n"
   end
@@ -1964,6 +2040,7 @@ def mutex_watchdog(mutex, sec)
 end
 
 def main
+
   $mutex = Mutex::new
   Thread::start do
     Thread.pass
@@ -1981,24 +2058,41 @@ def main
 
   write_pid_file($options["pid-file"]) if ($options["pid-file"])
 
-  server = TCPserver.open(port)
-  log_message("server started")
+  dir = $options["daemon"] || nil
+  if dir && ! File.exist?(dir)
+    FileUtils.mkdir(dir)
+  end
+  log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
+  $logger = WEBrick::Log.new(log_file)
 
-  while true
-    Thread::start(server.accept) do |client|
-      Thread.pass
-      client.sync = true
+  LEAGUE.dir = dir || File.dirname(__FILE__)
+  LEAGUE.setup_players_database
+
+  config = {}
+  config[:Port]       = port
+  config[:ServerType] = WEBrick::Daemon if $options["daemon"]
+  config[:Logger]     = $logger
+
+  server = WEBrick::GenericServer.new(config)
+  ["INT", "TERM"].each {|signal| trap(signal){ server.shutdown } }
+  $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"] 
+  log_message("server started [Revision: #{ShogiServer::Revision}]")
+
+  server.start do |client|
+      # client.sync = true # this is already set in WEBrick 
+      client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
+        # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
       player = nil
       login  = nil
-      while (str = client.gets_timeout(Login_Time))
+      while (str = client.gets_timeout(ShogiServer::Login_Time))
         begin
           $mutex.lock
           str =~ /([\r\n]*)$/
           eol = $1
-          if (Login::good_login?(str))
-            player = Player::new(str, client)
+          if (ShogiServer::Login::good_login?(str))
+            player = ShogiServer::Player::new(str, client)
             player.eol = eol
-            login  = Login::factory(str, player)
+            login  = ShogiServer::Login::factory(str, player)
             if (LEAGUE.players[player.name])
               if ((LEAGUE.players[player.name].password == player.password) &&
                   (LEAGUE.players[player.name].status != "game"))
@@ -2006,8 +2100,11 @@ def main
                 LEAGUE.players[player.name].kill
               else
                 login.incorrect_duplicated_player(str)
-                Thread::exit
-                return
+                #Thread::exit
+                #return
+                # TODO
+                player = nil
+                break
               end
             end
             LEAGUE.add(player)
@@ -2021,9 +2118,10 @@ def main
         end
       end                       # login loop
       if (! player)
-        client.close
-        Thread::exit
-        return
+        #client.close
+        #Thread::exit
+        #return
+        next
       end
       log_message(sprintf("user %s login", player.name))
       login.process
@@ -2039,11 +2137,16 @@ def main
       ensure
         $mutex.unlock
       end
-    end
   end
 end
 
+
 if ($0 == __FILE__)
-  LEAGUE = League::new
+  STDOUT.sync = true
+  STDERR.sync = true
+  TCPSocket.do_not_reverse_lookup = true
+  Thread.abort_on_exception = true
+
+  LEAGUE = ShogiServer::League::new
   main
 end