server.vala 4.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* 
 * 
 * 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/>.
 * 
 */


22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 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
public class Server: ThreadedSocketService
{
  protected MainLoop loop = new MainLoop (null, false);
  
  public string name { get; construct; }
  public uint   port { get; construct; default = 0xdead; }
  
  public signal void stopped ();
  
  /* receive a line from @socket */
  private static string receive_line (Socket  socket,
                                      uint    max_len = 255)
    throws Error
  {
    var buf = new char[max_len + 1];
    var rcv = socket.receive ((string)buf, max_len);
    buf[rcv] = 0;
    
    return ((string)buf).strip ();
  }
  
  private static bool send_line (Socket socket,
                                 string line)
    throws Error
  {
    var msg = line.strip () + "\n";
    return socket.send (msg, msg.length) >= 0;
  }
  
  private bool handle_connection (ThreadedSocketService service,
                                  SocketConnection      connection,
                                  Object?               source)
  {
    debug ("New connection");
    var socket = connection.socket;
    try {
      send_line (socket, "Welcome to server %s".printf (this.name));
    } catch {
    }
    
    bool  running   = true;
    uint  bad_count = 0;
    while (running)
    {
      try {
        bool    bad = false;
        string? msg = null;
        
        var line = receive_line (socket).down ();
        debug ("""received "%s"""", line);
        
        switch (line) {
          case "sht":
          case "shutdown":
            msg = "YOU KILLED ME ;(";
            running = false;
            this.stop();
            break;
          
          case "\004": // EOF
          case "eof":
            msg = "Bye!";
            running = false;
            break;
          
          case "hlo":
          case "hello":
          case "hi":
            msg = "Hi you!";
            break;
          
          case "who":
            msg = """Server name is "%s"""".printf (this.name);
            break;
          
          case "42":
            msg = "You just LOST the game!";
            break;
          
          default:
            bad = true;
            msg = "Sorry, I don't undesrtand what you mean";
            break;
        }
        
        if (bad) {
          bad_count ++;
          if (bad_count > 2) {
            msg = "We don't seem to speak the same language, sorry.";
            running = false;
          }
        } else if (bad_count > 0) {
          bad_count--;
        }
        
        if (msg != null) {
          debug ("""answering "%s"""", msg);
          send_line (socket, msg);
        }
      } catch (Error e) {
        warning ("error receiving data: %s", e.message);
        break;
      }
    }
    connection.socket.close ();
    debug ("Closed connection");
    return true;
  }
  
  construct
  {
    try {
134
      this.add_inet_port ((uint16) port, null);
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
    } catch (Error e) {
      critical ("failed to add address: %s", e.message);
    }
    this.run.connect (handle_connection);
  }
  
  public Server (string name,
                 uint16 port = 0xdead)
  {
    Object (name: name, port: port);
  }
  
  /* a bit ugly since a direct call to parent method will not trigger the
   * :stopped signal */
  public new void stop ()
  {
    base.stop ();
    this.stopped ();
  }
}


157 158
public static int main (string[] args)
{
159 160 161 162 163
  string name = "Unnamed server";
  uint16 port = 0xdead;
  
  if (args.length > 1) {
    name = args[1];
164
  }
165 166 167 168 169 170 171 172 173
  if (args.length > 2) {
    port = (uint16)int.parse (args[2]);
  }
  
  var loop = new MainLoop (null, false);
  var server = new Server (name, port);
  server.stopped.connect (() => loop.quit ());
  server.start ();
  loop.run ();
174 175 176
  
  return 0;
}