server.vala 8.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* 
 * 
 * Copyright (C) 2011 Colomban Wendling <ban@herbesfolles.org>
 *                    Jonathan Michalon <studios.chalmion@no-log.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
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

21
using OVCC;
22 23
using OVCC.Network;

24 25
static const string TILES_FILE   = "tiles.xml";
static const string TILESET_FILE = "tileset.xml";
26 27

/* TODO: add a Source to be notified of incoming messages asynchronously */
28

29 30
public class Server: ThreadedSocketService
{
31
  private List<Client>  clients = null;
32
  private List<Game>    tables  = null;
33 34
  private TilesDef      tiles   = new TilesDef ();
  private TileSet       tileset = new TileSet ();
35 36
  private string        tiles_data;
  private string        tileset_data;
37
  
38 39 40
  public string name        { get; construct; }
  public uint   port        { get; construct; default = 0xdead; }
  public uint   max_tables  { get; set; default = 1; }
41 42 43
  
  public signal void stopped ();
  
44 45 46 47 48
  /* removes old tables */
  private void cleanup_tables ()
  {
    lock (tables) {
      foreach (var game in tables) {
49
        if (game.state != GameState.STOPPED && game.players.length() < 1) {
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
          tables.remove (game);
          debug ("Cleaned up table %p", game);
        }
      }
    }
  }
  
  /* get the most populated open table available, maybe creating one */
  private Game? pick_open_table ()
  {
    Game? candidate     = null;
    uint  n_open_tables = 0;
    
    lock (tables) {
      foreach (var game in tables) {
        if (game.state == GameState.STOPPED &&
66
            (candidate == null || candidate.players.length() < game.players.length())) {
67 68 69 70 71 72 73 74
          candidate = game;
        }
        n_open_tables++;
      }
      /* if there is no open tables but room for more, create a new one */
      if (candidate == null && n_open_tables < max_tables) {
        candidate = new Game (tileset, null);
        tables.prepend (candidate);
75
        debug ("Added table %p, which describes as '%s'", candidate, candidate.describe().to_string());
76 77 78 79 80 81
      }
    }
    
    return candidate;
  }
  
82 83 84
  private bool send_all (Message      message,
                         Client?      exclude = null,
                         Cancellable? cancel = null)
85 86
    throws Error
  {
87 88 89 90 91 92 93 94
    lock (this.clients) {
      foreach (var c in this.clients) {
        if (c != exclude) {
          c.send (message, cancel);
        }
      }
    }
    return true;
95
  }
96 97

  private bool handle_login (LoginMessage msg, Client client)
98
    throws Error
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
  {
    bool ok = true;
    if (msg.status != LoginMessage.State.QUERY) {
      critical ("got LoginMessage with status different from QUERY");
      return false;
    }
    
    /* missing authentication check */
    if (msg.password == "") {
      debug ("rejecting auth as password is empty");
      msg.status = LoginMessage.State.MISSING_AUTHENTICATION;
      client.send (msg);
      return false;
    }

    /* already existing name check WARNING: lock needed */
    lock (this.clients) {
      foreach (Client c in this.clients) {
        if (c.login == msg.login) {
          ok = false;
          debug ("rejecting auth as login already connected");
          msg.status = LoginMessage.State.ALREADY_EXISTS;
          break;
        }
      }
      /* registration */
      if (ok) {
        debug ("accepting auth for %s", msg.login);
        msg.status = LoginMessage.State.OK;
        client.login    = msg.login;
        client.password = msg.password;
      }
    }
    client.send (msg);

    return ok;
  }
136 137

  private bool handle_join (JoinMessage msg, Client client)
138
    throws Error
139
  {
140 141 142 143 144 145
    Game? table = null;
    if (msg.table_index == -1) {
      table = pick_open_table ();
    } else {
      table = tables.nth_data (msg.table_index);
    }
146
    
147 148
    if (table == null || table.state != GameState.STOPPED) {
      debug ("Bad table %d, sending fail join message", msg.table_index);
149 150 151
      var join = new JoinMessage (msg.table_index);
      join.status = JoinMessage.State.FAILED;
      client.send (join);
152 153 154
      return false;
    }
    
155 156 157 158 159
    debug ("Accepting table join");
    var join = new JoinMessage (msg.table_index);
    join.status = JoinMessage.State.OK;
    client.send (join);

160
    client.join (table);
161

162 163 164
    debug ("Sending game data");
    var data = new GamedataMessage (client.game.get_stack_ids(),
                                    client.game.get_player_nicks(),
165
                                    tiles_data, tileset_data);
166 167 168
    client.send (data);
    return true;
  }
169
  
170 171 172 173 174 175 176 177 178 179 180 181 182
  private bool handle_list_tables (ListTablesMessage msg, Client client)
    throws Error
  {
    GameDescription[] list = {};
    foreach (var t in tables) {
      list += t.describe ();
    }
    var data = new ListTablesMessage (list);

    client.send (data);
    return true;
  }

183 184 185 186 187
  private bool handle_connection (ThreadedSocketService service,
                                  SocketConnection      connection,
                                  Object?               source)
  {
    debug ("New connection");
188
    var client = new Client ();
189
    try {
190 191 192 193
      client.connect (connection);
    } catch (Error e) {
      warning ("error connecting client: %s", e.message);
      return false;
194 195
    }
    
196 197 198 199 200 201 202 203 204 205 206
    lock (this.clients) {
      this.clients.prepend (client);
    }
    try {
      client.send (new WelcomeMessage ("Welcome to server %s".printf (this.name)));
    } catch {}
    
    var running = true;
    while (running) {
      Message? msg;
      
207
      try {
208
        msg = client.receive ();
209 210 211 212
      } catch (Error e) {
        warning ("error receiving data: %s", e.message);
        break;
      }
213 214 215 216 217 218 219 220 221 222 223
      
      if (msg == null) {
        debug ("Invalid message received");
        continue;
      }
      
      debug ("Message type %s received", msg.get_type ().name ());
      if (msg is StringMessage) {
        debug (" --- %s", (msg as StringMessage).message);
      }
      switch (msg.message_type) {
224
        case MessageType.LOGIN:
225
          debug ("Login for '%s' with '%s'", (msg as LoginMessage).login,
226
                                             (msg as LoginMessage).password);
227 228 229 230 231 232
          try {
            handle_login ((msg as LoginMessage), client);
          } catch (Error e) {
            /* FIXME send error message */
            warning ("Problems handling a client login... left in unknown state");
          }
233 234
          break;
        case MessageType.JOIN:
235 236 237 238 239 240
          try {
            handle_join (msg as JoinMessage, client);
          } catch (Error e) {
            /* FIXME send error message */
            warning ("Problems handling a client join... left in unknown state");
          }
241
          break;
242 243 244 245 246 247 248 249
        case MessageType.LIST_TABLES:
          try {
            handle_list_tables (msg as ListTablesMessage, client);
          } catch (Error e) {
            /* FIXME send error message */
            warning ("Problems handling a list table action...");
          }
          break;
250
        case MessageType.SIGNAL:
251
          client.signal_handle.emit_received (msg as SignalMessage);
252
          break;
253 254 255 256 257
        case MessageType.DISCONNECT: running = false; break;
      }
    }
    lock (this.clients) {
      this.clients.remove (client);
258
    }
259
    try { client.disconnect (); } catch { /* we don't care if disconnection failed */ }
260
    cleanup_tables ();
261 262 263 264 265 266 267
    debug ("Closed connection");
    return true;
  }
  
  construct
  {
    try {
268
      this.add_inet_port ((uint16) port, null);
269 270 271 272 273 274 275 276
    } catch (Error e) {
      critical ("failed to add address: %s", e.message);
    }
    this.run.connect (handle_connection);
  }
  
  public Server (string name,
                 uint16 port = 0xdead)
277
    throws Error
278
  {
279 280
    uint8[] data1;
    uint8[] data2;
281
    Object (name: name, port: port);
282

283 284 285 286 287 288 289 290 291 292 293
    File tiles_file   = Utils.lookup_resource_path(TILES_FILE);
    File tileset_file = Utils.lookup_resource_path(TILESET_FILE);

    tiles_file.load_contents(null, out data1, null);
    tileset_file.load_contents(null, out data2, null);

    tiles_data   = (string) data1;
    tileset_data = (string) data2;

    tiles.load_from_string (tiles_data);
    tileset.load_from_string (tiles, tileset_data);
294 295 296 297 298 299 300 301 302 303
  }
  
  /* a bit ugly since a direct call to parent method will not trigger the
   * :stopped signal */
  public new void stop ()
  {
    base.stop ();
    this.stopped ();
  }
}