2 * Copyright (C) 2021-2023 Mt.ZERO Software, Harry Godden - All Rights Reserved
5 #define _DEFAULT_SOURCE
10 volatile sig_atomic_t sig_stop
;
12 static void inthandler( int signum
) {
16 #include "gameserver.h"
17 #include "highscores.c"
18 #include "servermonitor_server.c"
19 #include "vg/vg_opt.h"
21 static const u64 k_connection_unauthorized
= 0xffffffffffffffff;
23 static u64_steamid
get_connection_authsteamid( SteamNetworkingMessage_t
*msg
){
24 i64 userdata
= SteamAPI_ISteamNetworkingSockets_GetConnectionUserData(
25 hSteamNetworkingSockets
, msg
->m_conn
);
27 return *((u64_steamid
*)&userdata
);
30 static void set_connection_authsteamid(HSteamNetConnection con
, u64_steamid id
){
31 i64 userdata
= *((i64
*)&id
);
33 SteamAPI_ISteamNetworkingSockets_SetConnectionUserData(
34 hSteamNetworkingSockets
, con
, userdata
);
37 static void gameserver_send_to_all( int ignore
,
38 const void *pData
, u32 cbData
,
40 for( int i
=0; i
<vg_list_size(gameserver
.clients
); i
++ ){
41 struct gameserver_client
*client
= &gameserver
.clients
[i
];
43 if( (i
==ignore
) || !client
->active
)
46 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
47 hSteamNetworkingSockets
, client
->connection
,
48 pData
, cbData
, nSendFlags
, NULL
);
52 static void gameserver_populate_join_msg( int index
, netmsg_playerjoin
*msg
){
53 memset( msg
, 0, sizeof(*msg
) );
54 msg
->inetmsg_id
= k_inetmsg_playerjoin
;
56 vg_strncpy( gameserver
.clients
[index
].username
, msg
->username
,
57 sizeof(msg
->username
), k_strncpy_always_add_null
);
60 static void gameserver_player_join( int index
){
61 struct gameserver_client
*joiner
= &gameserver
.clients
[index
];
63 netmsg_playerjoin join
;
64 gameserver_populate_join_msg( index
, &join
);
65 gameserver_send_to_all( index
, &join
, sizeof(join
),
66 k_nSteamNetworkingSend_Reliable
);
68 /* update the joining user about current connections */
69 for( int i
=0; i
<vg_list_size(gameserver
.clients
); i
++ ){
70 struct gameserver_client
*client
= &gameserver
.clients
[i
];
72 if( (i
==index
) || !client
->active
)
75 netmsg_playerjoin init
;
76 gameserver_populate_join_msg( i
, &init
);
78 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
79 hSteamNetworkingSockets
, joiner
->connection
,
80 &init
, sizeof(init
), k_nSteamNetworkingSend_Reliable
, NULL
);
84 static void gameserver_player_leave( int index
){
85 netmsg_playerjoin leave
;
86 leave
.inetmsg_id
= k_inetmsg_playerleave
;
89 vg_info( "Player leave (%d)\n", index
);
90 gameserver_send_to_all( index
, &leave
, sizeof(leave
),
91 k_nSteamNetworkingSend_Reliable
);
94 static void new_client_connecting( HSteamNetConnection client
){
98 for( int i
=0; i
<vg_list_size(gameserver
.clients
); i
++ ){
99 if( !gameserver
.clients
[i
].active
){
106 vg_error( "Server full\n" );
107 SteamAPI_ISteamNetworkingSockets_CloseConnection(
108 hSteamNetworkingSockets
, client
,
114 EResult accept_status
= SteamAPI_ISteamNetworkingSockets_AcceptConnection(
115 hSteamNetworkingSockets
, client
);
116 if( accept_status
== k_EResultOK
){
117 vg_success( "Accepted client (id: %u, index: %d)\n", client
, index
);
119 gameserver
.clients
[index
].active
= 1;
120 gameserver
.clients
[index
].connection
= client
;
122 SteamAPI_ISteamNetworkingSockets_SetConnectionPollGroup(
123 hSteamNetworkingSockets
,
124 client
, gameserver
.client_group
);
126 /* Just to be sure */
127 set_connection_authsteamid( client
, -1 );
128 gameserver_player_join( index
);
131 vg_warn( "Error accepting client (id: %u)\n", client
);
132 SteamAPI_ISteamNetworkingSockets_CloseConnection(
133 hSteamNetworkingSockets
, client
,
134 k_ESteamNetConnectionEnd_Misc_InternalError
,
136 gameserver
.clients
[index
].active
= 0;
137 gameserver
.clients
[index
].connection
= 0;
141 static void on_auth_status( CallbackMsg_t
*msg
){
142 SteamNetAuthenticationStatus_t
*info
= (void *)msg
->m_pubParam
;
143 vg_info( " Authentication availibility: %s\n",
144 string_ESteamNetworkingAvailability(info
->m_eAvail
) );
145 vg_info( " %s\n", info
->m_debugMsg
);
148 static int gameserver_client_index( HSteamNetConnection hconn
){
149 for( int i
=0; i
<vg_list_size(gameserver
.clients
); i
++ ){
150 struct gameserver_client
*client
= &gameserver
.clients
[i
];
152 if( client
->active
){
153 if( client
->connection
== hconn
){
161 static void on_connect_status( CallbackMsg_t
*msg
){
162 SteamNetConnectionStatusChangedCallback_t
*info
= (void *)msg
->m_pubParam
;
163 vg_info( " Connection status changed for %lu\n", info
->m_hConn
);
165 vg_info( " %s -> %s\n",
166 string_ESteamNetworkingConnectionState(info
->m_eOldState
),
167 string_ESteamNetworkingConnectionState(info
->m_info
.m_eState
) );
169 if( info
->m_info
.m_eState
==k_ESteamNetworkingConnectionState_Connecting
){
170 new_client_connecting( info
->m_hConn
);
173 if( (info
->m_info
.m_eState
==
174 k_ESteamNetworkingConnectionState_ClosedByPeer
) ||
175 (info
->m_info
.m_eState
==
176 k_ESteamNetworkingConnectionState_ProblemDetectedLocally
) ){
178 int client_id
= gameserver_client_index( info
->m_hConn
);
179 if( client_id
!= -1 ){
180 struct gameserver_client
*client
= &gameserver
.clients
[client_id
];
181 client
->connection
= 0;
183 gameserver_player_leave(client_id
);
186 vg_info( "End reason: %d\n", info
->m_info
.m_eEndReason
);
187 SteamAPI_ISteamNetworkingSockets_CloseConnection(
188 hSteamNetworkingSockets
, info
->m_hConn
, 0, NULL
, 0 );
192 static void gameserver_rx_auth( SteamNetworkingMessage_t
*msg
){
193 if( gameserver
.auth_mode
!= eServerModeAuthentication
){
194 vg_error( "Running server without authentication. "
195 "Connection %u tried to authenticate.\n", msg
->m_conn
);
199 if( get_connection_authsteamid( msg
) != k_connection_unauthorized
){
200 vg_warn( "Already authorized this user but app ticket was sent"
201 " again (%u)\n", msg
->m_conn
);
205 vg_low( "Attempting to verify user\n" );
207 if( msg
->m_cbSize
< sizeof(netmsg_auth
) ){
208 vg_error( "Malformed auth ticket, too small (%u)\n", msg
->m_conn
);
212 netmsg_auth
*auth
= msg
->m_pData
;
214 if( msg
->m_cbSize
< sizeof(netmsg_auth
)+auth
->ticket_length
||
215 auth
->ticket_length
> 1024 ){
216 vg_error( "Malformed auth ticket, ticket_length incorrect (%u)\n",
217 auth
->ticket_length
);
222 u32 ticket_len
= 1024;
224 int success
= SteamEncryptedAppTicket_BDecryptTicket(
225 auth
->ticket
, auth
->ticket_length
, decrypted
,
226 &ticket_len
, gameserver
.app_symmetric_key
,
227 k_nSteamEncryptedAppTicketSymmetricKeyLen
);
230 vg_error( "Failed to decrypt users ticket (client %u)\n", msg
->m_conn
);
231 vg_error( " ticket length: %u\n", auth
->ticket_length
);
233 SteamAPI_ISteamNetworkingSockets_CloseConnection(
234 hSteamNetworkingSockets
,
235 msg
->m_conn
, 0, NULL
, 1 );
239 if( SteamEncryptedAppTicket_GetTicketIssueTime( decrypted
, ticket_len
)){
240 RTime32 ctime
= time(NULL
),
241 tickettime
= SteamEncryptedAppTicket_GetTicketIssueTime(
242 decrypted
, ticket_len
),
243 expiretime
= tickettime
+ 24*3*60*60;
245 if( ctime
> expiretime
){
246 vg_error( "Ticket expired (client %u)\n", msg
->m_conn
);
248 /* TODO: Send expired information */
249 SteamAPI_ISteamNetworkingSockets_CloseConnection(
250 hSteamNetworkingSockets
,
251 msg
->m_conn
, 0, NULL
, 1 );
257 SteamEncryptedAppTicket_GetTicketSteamID( decrypted
, ticket_len
, &steamid
);
258 vg_success( "User is authenticated! steamid %lu (%u)\n",
259 steamid
.m_unAll64Bits
, msg
->m_conn
);
261 set_connection_authsteamid( msg
->m_conn
, steamid
.m_unAll64Bits
);
264 static int inet_require_auth( SteamNetworkingMessage_t
*msg
){
265 if( gameserver
.auth_mode
== eServerModeNoAuthentication
)
268 if( get_connection_authsteamid( msg
) == k_connection_unauthorized
){
269 vg_warn( "Unauthorized request! Disconnecting client: %u\n",
272 SteamAPI_ISteamNetworkingSockets_CloseConnection(
273 hSteamNetworkingSockets
,
274 msg
->m_conn
, 0, NULL
, 1 );
282 * Player updates sent to us
283 * -----------------------------------------------------------------------------
286 static int packet_minsize( SteamNetworkingMessage_t
*msg
, u32 size
){
287 if( msg
->m_cbSize
< size
) {
288 vg_error( "Invalid packet size (must be at least %u)\n", size
);
296 static void gameserver_rx_200_300( SteamNetworkingMessage_t
*msg
){
297 netmsg_blank
*tmp
= msg
->m_pData
;
299 if( tmp
->inetmsg_id
== k_inetmsg_playerusername
){
300 if( !packet_minsize( msg
, sizeof(netmsg_playerusername
) ))
303 int client_id
= gameserver_client_index( msg
->m_conn
);
304 if( client_id
!= -1 ){
305 struct gameserver_client
*client
= &gameserver
.clients
[ client_id
];
306 netmsg_playerusername
*src
= msg
->m_pData
;
308 vg_strncpy( src
->username
, client
->username
, sizeof(client
->username
),
309 k_strncpy_always_add_null
);
311 /* update other users about this change */
312 netmsg_playerusername msg
;
313 memset( &msg
, 0, sizeof(msg
) );
314 msg
.inetmsg_id
= k_inetmsg_playerusername
;
315 msg
.index
= client_id
;
316 vg_strncpy( client
->username
, msg
.username
, sizeof(msg
.username
),
317 k_strncpy_always_add_null
);
319 gameserver_send_to_all( client_id
, &msg
, sizeof(msg
),
320 k_nSteamNetworkingSend_Reliable
);
326 static void on_inet_score_request( SteamNetworkingMessage_t
*msg
){
327 if( !inet_require_auth(msg
) ) return;
329 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
330 hSteamNetworkingSockets
, msg
->m_conn
,
331 &scoreboard_client_data
, sizeof(netmsg_scoreboard
),
332 k_nSteamNetworkingSend_Reliable
, NULL
);
335 static void on_inet_set_nickname( SteamNetworkingMessage_t
*msg
){
336 if(!inet_require_auth(msg
)) return;
338 u64_steamid steamid
= get_connection_authsteamid(msg
);
339 netmsg_set_nickname
*setnick
= msg
->m_pData
;
340 if( msg
->m_cbSize
< sizeof(netmsg_set_nickname
) ){
341 vg_warn( "Invalid nickname request from client: %u, steamid: %lu\n",
342 msg
->m_conn
, steamid
);
346 highscore_set_user_nickname( steamid
, setnick
->nickname
);
349 static void on_inet_set_score( SteamNetworkingMessage_t
*msg
){
350 if(!inet_require_auth(msg
)) return;
352 u64_steamid steamid
= get_connection_authsteamid(msg
);
354 if( msg
->m_cbSize
< sizeof(netmsg_set_score
) ){
355 vg_warn( "Invalid set score post from client: %u, steamid: %lu\n",
356 msg
->m_conn
, steamid
);
360 netmsg_set_score
*info
= msg
->m_pData
;
362 if( msg
->m_cbSize
< sizeof(netmsg_set_score
) +
363 sizeof(struct netmsg_score_record
)*info
->record_count
){
364 vg_warn( "Malformed set score post from client: %u, steamid: %lu\n",
365 msg
->m_conn
, steamid
);
369 for( int i
=0; i
<info
->record_count
; i
++ ){
370 highscore_record temp
;
371 temp
.trackid
= info
->records
[i
].trackid
;
372 temp
.datetime
= time(NULL
);
373 temp
.playerid
= steamid
;
374 temp
.points
= info
->records
[i
].points
;
375 temp
.time
= info
->records
[i
].time
;
377 highscores_push_record( &temp
);
382 static void poll_connections(void){
383 SteamNetworkingMessage_t
*messages
[32];
387 len
= SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnPollGroup(
388 hSteamNetworkingSockets
,
389 gameserver
.client_group
, messages
, vg_list_size(messages
) );
394 for( int i
=0; i
<len
; i
++ ){
395 SteamNetworkingMessage_t
*msg
= messages
[i
];
397 if( msg
->m_cbSize
< sizeof(netmsg_blank
) ){
398 vg_warn( "Discarding message (too small: %d)\n",
403 netmsg_blank
*tmp
= msg
->m_pData
;
405 if( (tmp
->inetmsg_id
>= 200) && (tmp
->inetmsg_id
< 300) ){
406 gameserver_rx_200_300( msg
);
409 if( tmp
->inetmsg_id
== k_inetmsg_auth
)
410 gameserver_rx_auth( msg
);
412 else if( tmp
->inetmsg_id
== k_inetmsg_scores_request
)
413 on_inet_score_request( msg
);
414 else if( tmp
->inetmsg_id
== k_inetmsg_set_nickname
)
415 on_inet_set_nickname( msg
);
416 else if( tmp
->inetmsg_id
== k_inetmsg_set_score
)
417 on_inet_set_score( msg
);
418 else if( tmp
->inetmsg_id
== k_inetmsg_playerframe
)
419 on_inet_playerframe( msg
);
422 vg_warn( "Unknown inetmsg_id recieved from client. (%u)\n",
428 SteamAPI_SteamNetworkingMessage_t_Release( msg
);
433 static u64
seconds_to_server_ticks( double s
){
437 static void generate_boards(void){
438 FILE *fp
= fopen( "www/html/srhighscores.txt", "w" );
441 vg_error( "Can't write boards to www/html/srhighscores.txt\n" );
445 for( int i
=0; i
<vg_list_size(track_infos
); i
++ ){
446 struct netmsg_board
*board
= &scoreboard_client_data
.boards
[i
];
448 highscores_board_generate( board
->data
, i
, 10 );
449 highscores_board_printf( fp
, board
->data
, 10 );
455 int main( int argc
, char *argv
[] ){
456 signal( SIGINT
, inthandler
);
457 signal( SIGQUIT
, inthandler
);
458 signal( SIGPIPE
, SIG_IGN
);
461 while( vg_argp( argc
, argv
) ){
462 if( vg_long_opt( "noauth" ) )
463 gameserver
.auth_mode
= eServerModeNoAuthentication
;
466 /* TODO: Options to override, ammend, remove etc */
468 vg_set_mem_quota( 80*1024*1024 );
471 highscores_init( 250000, 10000 );
473 if( !highscores_read() )
474 highscores_create_db();
476 steamworks_ensure_txt( "2103940" );
478 if( gameserver
.auth_mode
== eServerModeAuthentication
){
479 if( !vg_load_steam_symetric_key( "application_key",
480 gameserver
.app_symmetric_key
)){
485 vg_warn( "Running without user authentication.\n" );
488 if( !SteamGameServer_Init( 0, 27400, 27401,
489 gameserver
.auth_mode
, "1.0.0.0" ) ){
490 vg_error( "SteamGameServer_Init failed\n" );
494 void *hSteamGameServer
= SteamAPI_SteamGameServer();
495 SteamAPI_ISteamGameServer_LogOnAnonymous( hSteamGameServer
);
497 SteamAPI_ManualDispatch_Init();
498 HSteamPipe hsteampipe
= SteamGameServer_GetHSteamPipe();
500 //hSteamHTTP = SteamAPI_SteamGameServerHTTP();
501 hSteamNetworkingSockets
=
502 SteamAPI_SteamGameServerNetworkingSockets_SteamAPI();
508 steam_register_callback( k_iSteamNetAuthenticationStatus
, on_auth_status
);
509 steam_register_callback( k_iSteamNetConnectionStatusChangedCallBack
,
512 vg_success( "Steamworks API running\n" );
513 steamworks_event_loop( hsteampipe
);
519 HSteamListenSocket listener
;
520 SteamNetworkingIPAddr localAddr
;
521 SteamAPI_SteamNetworkingIPAddr_Clear( &localAddr
);
522 localAddr
.m_port
= 27402;
524 listener
= SteamAPI_ISteamNetworkingSockets_CreateListenSocketIP(
525 hSteamNetworkingSockets
, &localAddr
, 0, NULL
);
526 gameserver
.client_group
= SteamAPI_ISteamNetworkingSockets_CreatePollGroup(
527 hSteamNetworkingSockets
);
529 u64 server_ticks
= 8000,
530 last_record_save
= 8000,
531 last_scoreboard_gen
= 0,
532 last_monitor_heartbeat
= 0;
535 monitor_start_server();
538 monitor_event_loop();
539 steamworks_event_loop( hsteampipe
);
546 (last_monitor_heartbeat
+ seconds_to_server_ticks(10.0))){
547 last_monitor_heartbeat
= server_ticks
;
551 if( server_ticks
> last_scoreboard_gen
+ seconds_to_server_ticks(60.0) ){
552 last_scoreboard_gen
= server_ticks
;
556 if( server_ticks
> last_record_save
+ seconds_to_server_ticks(10.0*60.0)){
557 last_record_save
= server_ticks
;
558 highscores_serialize_all();
562 highscores_serialize_all();
564 SteamAPI_ISteamNetworkingSockets_DestroyPollGroup( hSteamNetworkingSockets
,
565 gameserver
.client_group
);
566 SteamAPI_ISteamNetworkingSockets_CloseListenSocket(
567 hSteamNetworkingSockets
, listener
);
569 vg_info( "Shutting down\n..." );
570 SteamGameServer_Shutdown();