connection semantics; state change bug
authorhgn <hgodden00@gmail.com>
Wed, 8 Nov 2023 05:13:07 +0000 (05:13 +0000)
committerhgn <hgodden00@gmail.com>
Wed, 8 Nov 2023 05:13:07 +0000 (05:13 +0000)
gameserver.c
gameserver.h

index b7b809087c8e16c2a348891e0876ed7dfdea38b9..b1058bb99ec56b243f1377622210c48027ddd9bb 100644 (file)
@@ -18,41 +18,45 @@ volatile sig_atomic_t sig_stop;
 #include "vg/vg_m.h"
 #include "vg/vg_msg.h"
 
+static u64 const k_steamid_max = 0xffffffffffffffff;
+
 static void inthandler( int signum ) {
    sig_stop = 1;
 }
 
-static const u64 k_connection_unauthorized = 0xffffffffffffffff;
-
-static u64_steamid get_connection_authsteamid( SteamNetworkingMessage_t *msg ){
-   i64 userdata = SteamAPI_ISteamNetworkingSockets_GetConnectionUserData(
-            hSteamNetworkingSockets, msg->m_conn );
+/*
+ * Send message to single client, with authentication checking
+ */
+static void gameserver_send_to_client( i32 client_id,
+                                       const void *pData, u32 cbData,
+                                       int nSendFlags ){
+   struct gameserver_client *client = &gameserver.clients[ client_id ];
 
-   return *((u64_steamid *)&userdata);
-}
+   if( !client->steamid )
+      return;
 
-static void set_connection_authsteamid(HSteamNetConnection con, u64_steamid id){
-   i64 userdata = *((i64 *)&id);
-   
-   SteamAPI_ISteamNetworkingSockets_SetConnectionUserData(
-         hSteamNetworkingSockets, con, userdata );
+   SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
+         hSteamNetworkingSockets, client->connection,
+         pData, cbData, nSendFlags, NULL );
 }
 
+/*
+ * Send message to all clients if they are authenticated
+ */
 static void gameserver_send_to_all( int ignore, 
                                     const void *pData, u32 cbData, 
                                     int nSendFlags ){
    for( int i=0; i<vg_list_size(gameserver.clients); i++ ){
       struct gameserver_client *client = &gameserver.clients[i];
 
-      if( (i==ignore) || !client->active )
-         continue;
-
-      SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
-            hSteamNetworkingSockets, client->connection,
-            pData, cbData, nSendFlags, NULL );
+      if( i != ignore )
+         gameserver_send_to_client( i, pData, cbData, nSendFlags );
    }
 }
 
+/*
+ * handle server update that client #'index' has joined
+ */
 static void gameserver_player_join( int index ){
    struct gameserver_client *joiner = &gameserver.clients[index];
    
@@ -61,8 +65,9 @@ static void gameserver_player_join( int index ){
    gameserver_send_to_all( index, &join, sizeof(join),
                            k_nSteamNetworkingSend_Reliable );
 
-   /* update the joining user about current connections */
-
+   /* 
+    * update the joining user about current connections 
+    */
    netmsg_playerusername *username = 
       alloca( sizeof(netmsg_playerusername) + NETWORK_USERNAME_MAX );
    username->inetmsg_id = k_inetmsg_playerusername;
@@ -74,15 +79,14 @@ static void gameserver_player_join( int index ){
    for( int i=0; i<vg_list_size(gameserver.clients); i++ ){
       struct gameserver_client *client = &gameserver.clients[i];
 
-      if( (i==index) || !client->active )
+      if( (i == index) || !client->steamid )
          continue;
 
       /* join */
       netmsg_playerjoin init = { .inetmsg_id = k_inetmsg_playerjoin,
                                  .index = i };
-      SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
-            hSteamNetworkingSockets, joiner->connection,
-            &init, sizeof(init), k_nSteamNetworkingSend_Reliable, NULL );
+      gameserver_send_to_client( index, &init, sizeof(init),
+                                 k_nSteamNetworkingSend_Reliable );
 
       /* username */
       username->index = i;
@@ -90,9 +94,8 @@ static void gameserver_player_join( int index ){
                             NETWORK_USERNAME_MAX,
                             k_strncpy_always_add_null );
       u32 size = sizeof(netmsg_playerusername) + chs + 1;
-      SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
-            hSteamNetworkingSockets, joiner->connection,
-            username, size, k_nSteamNetworkingSend_Reliable, NULL );
+      gameserver_send_to_client( index, username, size,
+                                 k_nSteamNetworkingSend_Reliable );
 
       /* items */
       for( int j=0; j<k_netmsg_playeritem_max; j++ ){
@@ -101,14 +104,21 @@ static void gameserver_player_join( int index ){
          item->type_index = j;
          item->client = i;
          size = sizeof(netmsg_playeritem) + chs + 1;
-         SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
-               hSteamNetworkingSockets, joiner->connection,
-               item, size, k_nSteamNetworkingSend_Reliable, NULL );
+         gameserver_send_to_client( index, item, size,
+                                    k_nSteamNetworkingSend_Reliable );
       }
    }
 }
 
+/*
+ * Handle server update that player has left
+ */
 static void gameserver_player_leave( int index ){
+   if( gameserver.auth_mode == eServerModeAuthentication ){
+      if( !gameserver.clients[ index ].steamid )
+         return;
+   }
+
    netmsg_playerjoin leave;
    leave.inetmsg_id = k_inetmsg_playerleave;
    leave.index = index;
@@ -118,10 +128,33 @@ static void gameserver_player_leave( int index ){
                            k_nSteamNetworkingSend_Reliable );
 }
 
-static void new_client_connecting( HSteamNetConnection client ){
+/*
+ * Deletes client at index and disconnects the connection handle if it was 
+ * set.
+ */
+static void remove_client( int index ){
+   struct gameserver_client *client = &gameserver.clients[index];
+   if( client->connection ){
+      SteamAPI_ISteamNetworkingSockets_SetConnectionUserData(
+            hSteamNetworkingSockets, client->connection, -1 );
+      SteamAPI_ISteamNetworkingSockets_CloseConnection( 
+            hSteamNetworkingSockets, client->connection,
+            k_ESteamNetConnectionEnd_Misc_InternalError,
+            NULL, 1 );
+   }
+   memset( client, 0, sizeof(struct gameserver_client) );
+}
+
+/*
+ * Handle incoming new connection and init flags on the steam handle. if the 
+ * server is full the userdata (client_id) will be set to -1 on the handle.
+ */
+static void handle_new_connection( HSteamNetConnection conn ){
+   SteamAPI_ISteamNetworkingSockets_SetConnectionUserData(
+         hSteamNetworkingSockets, conn, -1 );
+
    int index = -1;
 
-   /* TODO: LRU */
    for( int i=0; i<vg_list_size(gameserver.clients); i++ ){
       if( !gameserver.clients[i].active ){
          index = i;
@@ -132,37 +165,39 @@ static void new_client_connecting( HSteamNetConnection client ){
    if( index == -1 ){
       vg_error( "Server full\n" );
       SteamAPI_ISteamNetworkingSockets_CloseConnection( 
-            hSteamNetworkingSockets, client
+            hSteamNetworkingSockets, conn
             4500,
             NULL, 1 );
       return;
    }
 
+   struct gameserver_client *client = &gameserver.clients[index];
    EResult accept_status = SteamAPI_ISteamNetworkingSockets_AcceptConnection(
-            hSteamNetworkingSockets, client );
+            hSteamNetworkingSockets, conn );
+
    if( accept_status == k_EResultOK ){
-      vg_success( "Accepted client (id: %u, index: %d)\n", client, index );
-      memset( &gameserver.clients[index], 0, sizeof(struct gameserver_client) );
+      vg_success( "Accepted client (id: %u, index: %d)\n", conn, index );
 
-      gameserver.clients[index].active = 1;
-      gameserver.clients[index].connection = client;
+      client->active = 1;
+      client->connection = conn;
 
       SteamAPI_ISteamNetworkingSockets_SetConnectionPollGroup(
-            hSteamNetworkingSockets,
-            client, gameserver.client_group );
+            hSteamNetworkingSockets, conn, gameserver.client_group );
+      
+      SteamAPI_ISteamNetworkingSockets_SetConnectionUserData(
+            hSteamNetworkingSockets, conn, index );
       
-      /* Just to be sure */
-      set_connection_authsteamid( client, -1 );
-      gameserver_player_join( index );
+      if( gameserver.auth_mode != eServerModeAuthentication ){
+         client->steamid = k_steamid_max;
+         gameserver_player_join( index );
+      }
    }
    else{
-      vg_warn( "Error accepting client (id: %u)\n", client );
+      vg_warn( "Error accepting connection (id: %u)\n", conn );
       SteamAPI_ISteamNetworkingSockets_CloseConnection( 
-            hSteamNetworkingSockets, client
+            hSteamNetworkingSockets, conn
             k_ESteamNetConnectionEnd_Misc_InternalError,
             NULL, 1 );
-      gameserver.clients[index].active = 0;
-      gameserver.clients[index].connection = 0;
    }
 }
 
@@ -173,19 +208,23 @@ static void on_auth_status( CallbackMsg_t *msg ){
    vg_info( "  %s\n", info->m_debugMsg );
 }
 
-static int gameserver_client_index( HSteamNetConnection hconn ){
-   for( int i=0; i<vg_list_size(gameserver.clients); i++ ){
-      struct gameserver_client *client = &gameserver.clients[i];
+/*
+ * Get client id of connection handle. Will be -1 if unkown to us either because
+ * the server is full or we already disconnected them
+ */
+static i32 gameserver_conid( HSteamNetConnection hconn ){
+   i64 id = SteamAPI_ISteamNetworkingSockets_GetConnectionUserData(
+               hSteamNetworkingSockets, hconn );
 
-      if( client->active ){
-         if( client->connection == hconn ){
-            return i;
-         }
-      }
-   }
-   return -1;
+   if( (id < 0) || (id >= NETWORK_MAX_PLAYERS) )
+      return -1;
+
+   return id;
 }
 
+/*
+ * Callback for steam connection state change
+ */
 static void on_connect_status( CallbackMsg_t *msg ){
    SteamNetConnectionStatusChangedCallback_t *info = (void *)msg->m_pubParam;
    vg_info( "  Connection status changed for %lu\n", info->m_hConn );
@@ -195,28 +234,36 @@ static void on_connect_status( CallbackMsg_t *msg ){
          string_ESteamNetworkingConnectionState(info->m_info.m_eState) );
 
    if( info->m_info.m_eState==k_ESteamNetworkingConnectionState_Connecting ){
-      new_client_connecting( info->m_hConn );
+      handle_new_connection( info->m_hConn );
    }
 
    if( (info->m_info.m_eState == 
             k_ESteamNetworkingConnectionState_ClosedByPeer ) ||
        (info->m_info.m_eState == 
-        k_ESteamNetworkingConnectionState_ProblemDetectedLocally ) ){
+        k_ESteamNetworkingConnectionState_ProblemDetectedLocally ) ||
+       (info->m_info.m_eState == 
+        k_ESteamNetworkingConnectionState_Dead) ||
+       (info->m_info.m_eState ==
+        k_ESteamNetworkingConnectionState_None) )
+   {
+      vg_info( "End reason: %d\n", info->m_info.m_eEndReason );
 
-      int client_id = gameserver_client_index( info->m_hConn );
+      int client_id = gameserver_conid( info->m_hConn );
       if( client_id != -1 ){
-         struct gameserver_client *client = &gameserver.clients[client_id];
-         client->connection = 0;
-         client->active = 0;
-         gameserver_player_leave(client_id);
+         gameserver_player_leave( client_id );
+         remove_client( client_id );
+      }
+      else {
+         SteamAPI_ISteamNetworkingSockets_CloseConnection( 
+               hSteamNetworkingSockets, info->m_hConn, 0, NULL, 0 );
       }
-
-      vg_info( "End reason: %d\n", info->m_info.m_eEndReason );
-      SteamAPI_ISteamNetworkingSockets_CloseConnection( 
-            hSteamNetworkingSockets, info->m_hConn, 0, NULL, 0 );
    }
 }
 
+/* 
+ * recieve auth ticket from connection. will only accept it if we've added them
+ * to the client list first.
+ */
 static void gameserver_rx_auth( SteamNetworkingMessage_t *msg ){
    if( gameserver.auth_mode != eServerModeAuthentication ){
       vg_error( "Running server without authentication. "
@@ -224,9 +271,18 @@ static void gameserver_rx_auth( SteamNetworkingMessage_t *msg ){
       return;
    }
 
-   if( get_connection_authsteamid( msg ) != k_connection_unauthorized ){
-      vg_warn( "Already authorized this user but app ticket was sent"
-               " again (%u)\n", msg->m_conn );
+   int client_id = gameserver_conid( msg->m_conn );
+   if( client_id == -1 ) {
+      vg_warn( "Recieved auth ticket from unkown connection (%u)\n", 
+               msg->m_conn );
+      return;
+   }
+
+   struct gameserver_client *client = &gameserver.clients[ client_id ];
+
+   if( client->steamid ){
+      vg_warn( "Already authorized this user but another app ticket was sent"
+               " again (%d conn: %u)\n", client_id, msg->m_conn );
       return;
    }
 
@@ -257,10 +313,7 @@ static void gameserver_rx_auth( SteamNetworkingMessage_t *msg ){
    if( !success ){
       vg_error( "Failed to decrypt users ticket (client %u)\n", msg->m_conn );
       vg_error( "  ticket length: %u\n", auth->ticket_length );
-
-      SteamAPI_ISteamNetworkingSockets_CloseConnection(
-            hSteamNetworkingSockets,
-            msg->m_conn, 0, NULL, 1 );
+      remove_client( client_id );
       return;
    }
 
@@ -272,11 +325,7 @@ static void gameserver_rx_auth( SteamNetworkingMessage_t *msg ){
       
       if( ctime > expiretime ){
          vg_error( "Ticket expired (client %u)\n", msg->m_conn );
-
-         /* TODO: Send expired information */
-         SteamAPI_ISteamNetworkingSockets_CloseConnection(
-               hSteamNetworkingSockets,
-               msg->m_conn, 0, NULL, 1 );
+         remove_client( client_id );
          return;
       }
    }
@@ -286,24 +335,8 @@ static void gameserver_rx_auth( SteamNetworkingMessage_t *msg ){
    vg_success( "User is authenticated! steamid %lu (%u)\n", 
          steamid.m_unAll64Bits, msg->m_conn );
 
-   set_connection_authsteamid( msg->m_conn, steamid.m_unAll64Bits );
-}
-
-static int inet_require_auth( SteamNetworkingMessage_t *msg ){
-   if( gameserver.auth_mode == eServerModeNoAuthentication )
-      return 1;
-
-   if( get_connection_authsteamid( msg ) == k_connection_unauthorized ){
-      vg_warn( "Unauthorized request! Disconnecting client: %u\n", 
-               msg->m_conn );
-
-      SteamAPI_ISteamNetworkingSockets_CloseConnection(
-            hSteamNetworkingSockets,
-            msg->m_conn, 0, NULL, 1 );
-
-      return 0;
-   }
-   else return 1;
+   client->steamid = steamid.m_unAll64Bits;
+   gameserver_player_join( client_id );
 }
 
 /*
@@ -329,7 +362,7 @@ struct db_set_username_thread_data {
 static void gameserver_update_db_username( db_request *db_req ){
    struct db_set_username_thread_data *inf = (void *)db_req->data;
 
-   if( inf->steamid == k_connection_unauthorized )
+   if( inf->steamid == k_steamid_max )
       return;
 
    int admin = 0;
@@ -342,14 +375,15 @@ static void gameserver_update_db_username( db_request *db_req ){
 static void gameserver_rx_200_300( SteamNetworkingMessage_t *msg ){
    netmsg_blank *tmp = msg->m_pData;
 
-   int client_id = gameserver_client_index( msg->m_conn );
+   int client_id = gameserver_conid( msg->m_conn );
    if( client_id == -1 ) return;
 
+   struct gameserver_client *client = &gameserver.clients[ client_id ];
+
    if( tmp->inetmsg_id == k_inetmsg_playerusername ){
       if( !packet_minsize( msg, sizeof(netmsg_playerusername)+1 ))
          return;
       
-      struct gameserver_client *client = &gameserver.clients[ client_id ];
       netmsg_playerusername *src = msg->m_pData;
 
       u32 name_len = network_msgstring( src->name, msg->m_cbSize, 
@@ -376,7 +410,7 @@ static void gameserver_rx_200_300( SteamNetworkingMessage_t *msg ){
       db_request *call = db_alloc_request( 
                            sizeof(struct db_set_username_thread_data) );
       struct db_set_username_thread_data *inf = (void *)call->data;
-      inf->steamid = get_connection_authsteamid( msg );
+      inf->steamid = client->steamid;
       vg_strncpy( client->username, inf->username, 
                   sizeof(inf->username), k_strncpy_always_add_null );
       call->handler = gameserver_update_db_username;
@@ -394,7 +428,6 @@ static void gameserver_rx_200_300( SteamNetworkingMessage_t *msg ){
       netmsg_playeritem *item = msg->m_pData;
 
       /* record */
-      struct gameserver_client *client = &gameserver.clients[ client_id ];
 
       if( item->type_index >= k_netmsg_playeritem_max ){
          vg_warn( "Client #%d invalid equip type %u\n", 
@@ -431,7 +464,7 @@ static void gameserver_rx_200_300( SteamNetworkingMessage_t *msg ){
 static void gameserver_request_respond( enum request_status status,
                                         netmsg_request *res, vg_msg *body,
                                         SteamNetworkingMessage_t *msg ){
-   int client_id = gameserver_client_index( msg->m_conn );
+   int client_id = gameserver_conid( msg->m_conn );
    u32 len = 0;
    if( body ){
       len = body->cur.co;
@@ -486,7 +519,7 @@ static enum request_status gameserver_cat_table(
          i64 steamid_i64 = sqlite3_column_int64( stmt, 0 );
          u64 steamid = *((u64 *)&steamid_i64);
 
-         if( steamid == k_connection_unauthorized )
+         if( steamid == k_steamid_max )
             continue;
 
          vg_msg_frame( msg, "" );
@@ -516,12 +549,14 @@ static void gameserver_process_user_request( db_request *db_req ){
    struct user_request_thread_data *inf = (void *)db_req->data;
    SteamNetworkingMessage_t *msg = inf->msg;
 
-   int client_id = gameserver_client_index( msg->m_conn );
+   int client_id = gameserver_conid( msg->m_conn );
    if( client_id == -1 ){
       SteamAPI_SteamNetworkingMessage_t_Release( msg );
       return;
    }
 
+   struct gameserver_client *client = &gameserver.clients[ client_id ];
+
    netmsg_request *req = (netmsg_request *)msg->m_pData;
    vg_msg data;
    vg_msg_init( &data, req->q, msg->m_cbSize - sizeof(netmsg_request) );
@@ -567,12 +602,7 @@ static void gameserver_process_user_request( db_request *db_req ){
       gameserver_request_respond( k_request_status_ok, res, &body, msg );
    }
    else if( !strcmp( endpoint, "setlap" ) ){
-      /* TODO: we can change userdata to be the client ID and store that in
-       *       the client structure. it also would save us scanning the 
-       *       client array over and over..? 
-       */
-      u64 steamid = get_connection_authsteamid( msg );
-      if( steamid == k_connection_unauthorized ){
+      if( client->steamid == k_steamid_max ){
          gameserver_request_respond( k_request_status_unauthorized,
                                      res, NULL, msg );
          return;
@@ -600,8 +630,8 @@ static void gameserver_process_user_request( db_request *db_req ){
          return;
       }
 
-      db_writeusertime( alltime_table, steamid, centiseconds, 1 );
-      db_writeusertime( weekly_table, steamid, centiseconds, 1 );
+      db_writeusertime( alltime_table, client->steamid, centiseconds, 1 );
+      db_writeusertime( weekly_table, client->steamid, centiseconds, 1 );
 
       gameserver_request_respond( k_request_status_ok, res, NULL, msg );
    }
@@ -614,7 +644,7 @@ static void gameserver_process_user_request( db_request *db_req ){
 static void gameserver_rx_300_400( SteamNetworkingMessage_t *msg ){
    netmsg_blank *tmp = msg->m_pData;
 
-   int client_id = gameserver_client_index( msg->m_conn );
+   int client_id = gameserver_conid( msg->m_conn );
    if( client_id == -1 ){
       SteamAPI_SteamNetworkingMessage_t_Release( msg );
       return;
index 2f5cfd4600bab13ced741ad7f3f11eee1b00bd8c..d8e0d38c018d929938291de77d012c24664bbb0f 100644 (file)
@@ -22,6 +22,7 @@ struct {
       HSteamNetConnection connection;
       char username[ NETWORK_USERNAME_MAX ];
       char items[k_netmsg_playeritem_max][ADDON_UID_MAX];
+      u64  steamid;
    }
    clients[ NETWORK_MAX_PLAYERS ];