fix segfault
[carveJwlIkooP6JGAAIwe30JlM.git] / network.c
1 #include "player.h"
2 #include "network.h"
3 #include "network_msg.h"
4 #include "network_common.h"
5 #include "player_remote.h"
6 #include "world.h"
7 #include "world_sfd.h"
8 #include "world_routes.h"
9
10 static void scores_update(void);
11
12 static int packet_minsize( SteamNetworkingMessage_t *msg, u32 size ){
13 if( msg->m_cbSize < size ) {
14 vg_error( "Invalid packet size (must be at least %u)\n", size );
15 return 0;
16 }
17 else{
18 return 1;
19 }
20 }
21
22 static void on_auth_ticket_recieved( void *result, void *context ){
23 EncryptedAppTicketResponse_t *response = result;
24
25 if( response->m_eResult == k_EResultOK ){
26 vg_info( " New app ticket ready\n" );
27 }
28 else{
29 vg_warn( " Could not request new encrypted app ticket (%u)\n",
30 response->m_eResult );
31 }
32
33 if( SteamAPI_ISteamUser_GetEncryptedAppTicket( hSteamUser,
34 network_client.app_symmetric_key,
35 vg_list_size(network_client.app_symmetric_key),
36 &network_client.app_key_length )){
37 vg_success( " Loaded app ticket\n" );
38 }
39 else{
40 vg_error( " No ticket availible\n" );
41 network_client.app_key_length = 0;
42 }
43 }
44
45 static void request_auth_ticket(void){
46 /*
47 * TODO Check for one thats cached on the disk and load it.
48 * This might be OK though because steam seems to cache the result
49 */
50
51 vg_info( "Requesting new authorization ticket\n" );
52
53 vg_steam_async_call *call = vg_alloc_async_steam_api_call();
54 call->userdata = NULL;
55 call->p_handler = on_auth_ticket_recieved;
56 call->id =
57 SteamAPI_ISteamUser_RequestEncryptedAppTicket( hSteamUser, NULL, 0 );
58 }
59
60 static void network_send_username(void){
61 if( !network_connected() )
62 return;
63
64 netmsg_playerusername *update = alloca( sizeof(netmsg_playerusername)+
65 NETWORK_USERNAME_MAX );
66 update->inetmsg_id = k_inetmsg_playerusername;
67 update->index = 0xff;
68
69 ISteamFriends *hSteamFriends = SteamAPI_SteamFriends();
70 const char *username = SteamAPI_ISteamFriends_GetPersonaName(hSteamFriends);
71 u32 chs = str_utf8_collapse( username, update->name, NETWORK_USERNAME_MAX );
72
73 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
74 hSteamNetworkingSockets, network_client.remote,
75 update, sizeof(netmsg_playerusername)+chs+1,
76 k_nSteamNetworkingSend_Reliable, NULL );
77 }
78
79 static void network_send_request( netmsg_request *req, vg_msg *body,
80 void (*callback)(
81 netmsg_request *res, vg_msg *body,
82 u64 userdata),
83 u64 userdata ){
84 u32 len = 0;
85 if( body ){
86 len = body->cur.co;
87 vg_info( "Request scoreboard. Info (%u):\n", body->cur.co );
88 vg_msg_print( body, len );
89
90 if( body->error != k_vg_msg_error_OK ){
91 vg_error( "Body not OK\n" );
92 return;
93 }
94 }
95
96 if( callback ){
97 req->id = vg_pool_lru( &network_client.request_pool );
98 if( req->id ){
99 vg_pool_watch( &network_client.request_pool, req->id );
100 struct network_request *pn =
101 vg_pool_item( &network_client.request_pool, req->id );
102 pn->callback = callback;
103 pn->sendtime = vg.time_real;
104 pn->userdata = userdata;
105 }
106 else{
107 vg_error( "Unable to send request. Pool is full.\n" );
108 return;
109 }
110 }
111 else
112 req->id = 0;
113
114 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
115 hSteamNetworkingSockets, network_client.remote,
116 req, sizeof(netmsg_request)+len,
117 k_nSteamNetworkingSend_Reliable, NULL );
118 }
119
120 static void network_scoreboard_callback( netmsg_request *res, vg_msg *body,
121 u64 userdata ){
122 world_instance *world = world_current_instance();
123
124 world_routes_recv_scoreboard( world, body, userdata, res->status );
125 if( userdata == world_sfd.active_route_board )
126 world_sfd_compile_active_scores();
127 }
128
129
130
131 /* mod_uid: world mod uid,
132 * route_uid: run name (just a string)
133 * week:
134 * 0 ALL TIME
135 * 1 CURRENT WEEK
136 * 2 ALL TIME + CURRENT WEEK
137 * .
138 * 10+ specific week index
139 */
140 static void network_request_scoreboard( const char *mod_uid,
141 const char *route_uid,
142 u32 week, u64 userdata ){
143 if( !network_connected() )
144 return;
145
146 netmsg_request *req = alloca( sizeof(netmsg_request) + 512 );
147 req->inetmsg_id = k_inetmsg_request;
148
149 vg_msg data;
150 vg_msg_init( &data, req->q, 512 );
151 vg_msg_wkvstr( &data, "endpoint", "scoreboard" );
152 vg_msg_wkvstr( &data, "mod", mod_uid );
153 vg_msg_wkvstr( &data, "route", route_uid );
154 vg_msg_wkvu32( &data, "week", week );
155 network_send_request( req, &data, network_scoreboard_callback, userdata );
156 }
157
158 static void network_publish_callback( netmsg_request *res, vg_msg *body,
159 u64 userdata ){
160 if( res->status != k_request_status_ok ){
161 vg_error( "Publish laptime, server error #%d\n", (i32)res->status );
162 }
163 }
164
165 static void network_publish_laptime( const char *mod_uid,
166 const char *route_uid, f64 lap_time ){
167 if( !network_connected() )
168 return;
169
170 i32 time_centiseconds = lap_time * 100.0;
171
172 netmsg_request *req = alloca( sizeof(netmsg_request) + 512 );
173 req->inetmsg_id = k_inetmsg_request;
174
175 vg_msg data;
176 vg_msg_init( &data, req->q, 512 );
177 vg_msg_wkvstr( &data, "endpoint", "setlap" );
178 vg_msg_wkvstr( &data, "mod", mod_uid );
179 vg_msg_wkvstr( &data, "route", route_uid );
180 vg_msg_wkvi32( &data, "time", time_centiseconds );
181 network_send_request( req, &data, network_publish_callback, 0 );
182 }
183
184 static void network_request_rx_300_400( SteamNetworkingMessage_t *msg ){
185 netmsg_blank *tmp = msg->m_pData;
186
187 if( tmp->inetmsg_id == k_inetmsg_request ){
188
189 }
190 else if( tmp->inetmsg_id == k_inetmsg_response ){
191 netmsg_request *res = (netmsg_request *)msg->m_pData;
192
193 vg_msg *body = NULL;
194
195 vg_msg data;
196 if( res->status == k_request_status_ok ){
197 vg_msg_init( &data, res->q, msg->m_cbSize - sizeof(netmsg_request) );
198 vg_success( "Response to #%d:\n", (i32)res->id );
199 vg_msg_print( &data, data.max );
200 body = &data;
201 }
202 else {
203 vg_warn( "Server response to #%d: %d\n", (i32)res->id, res->status );
204 }
205
206 if( res->id ){
207 struct network_request *pn =
208 vg_pool_item( &network_client.request_pool, res->id );
209 pn->callback( res, body, pn->userdata );
210 vg_pool_unwatch( &network_client.request_pool, res->id );
211 }
212 }
213 }
214
215 static void network_send_item( enum netmsg_playeritem_type type ){
216 if( !network_connected() )
217 return;
218
219 netmsg_playeritem *item =
220 alloca( sizeof(netmsg_playeritem) + ADDON_UID_MAX );
221 item->inetmsg_id = k_inetmsg_playeritem;
222 item->type_index = type;
223 item->client = 0;
224
225 if( (type == k_netmsg_playeritem_world0) ||
226 (type == k_netmsg_playeritem_world1) ){
227
228 enum world_purpose purpose = type - k_netmsg_playeritem_world0;
229 addon_reg *reg = world_static.instance_addons[ purpose ];
230
231 if( reg )
232 addon_alias_uid( &reg->alias, item->uid );
233 else
234 item->uid[0] = '\0';
235 }
236 else{
237 u16 view_id = 0;
238 enum addon_type addon_type = k_addon_type_none;
239 if( type == k_netmsg_playeritem_board ){
240 view_id = localplayer.board_view_slot;
241 addon_type = k_addon_type_board;
242 }
243 else if( type == k_netmsg_playeritem_player ){
244 view_id = localplayer.playermodel_view_slot;
245 addon_type = k_addon_type_player;
246 }
247 else
248 assert(0);
249
250 struct addon_cache *cache = &addon_system.cache[addon_type];
251 vg_pool *pool = &cache->pool;
252
253 SDL_AtomicLock( &addon_system.sl_cache_using_resources );
254 addon_cache_entry *entry = vg_pool_item( pool, view_id );
255 addon_alias_uid( &entry->reg_ptr->alias, item->uid );
256 SDL_AtomicUnlock( &addon_system.sl_cache_using_resources );
257 }
258
259 vg_info( "send equip: [%u] %s\n",
260 item->type_index, item->uid );
261 u32 chs = strlen(item->uid);
262
263 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
264 hSteamNetworkingSockets, network_client.remote,
265 item, sizeof(netmsg_playeritem)+chs+1,
266 k_nSteamNetworkingSend_Reliable, NULL );
267 }
268
269 static void network_disconnect(void){
270 SteamAPI_ISteamNetworkingSockets_CloseConnection(
271 hSteamNetworkingSockets, network_client.remote, 0, NULL, 0 );
272 network_client.remote = 0;
273 network_client.state = k_ESteamNetworkingConnectionState_None;
274
275 for( int i=0; i<vg_list_size(netplayers.list); i++ ){
276 netplayers.list[i].active = 0;
277 }
278 }
279
280 static void on_server_connect_status( CallbackMsg_t *msg ){
281 SteamNetConnectionStatusChangedCallback_t *info = (void *)msg->m_pubParam;
282 vg_info( " Connection status changed for %lu\n", info->m_hConn );
283 vg_info( " %s -> %s\n",
284 string_ESteamNetworkingConnectionState(info->m_eOldState),
285 string_ESteamNetworkingConnectionState(info->m_info.m_eState) );
286
287 if( info->m_hConn == network_client.remote ){
288 network_client.state = info->m_info.m_eState;
289
290 if( info->m_info.m_eState ==
291 k_ESteamNetworkingConnectionState_Connected ){
292 vg_success(" Connected to remote server.. authenticating\n");
293
294 /* send version info to server */
295 netmsg_version version;
296 version.inetmsg_id = k_inetmsg_version;
297 version.version = NETWORK_SKATERIFT_VERSION;
298 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
299 hSteamNetworkingSockets, network_client.remote, &version,
300 sizeof(netmsg_version), k_nSteamNetworkingSend_Reliable, NULL );
301
302 /* TODO: We should really wait to see if the server is in auth mode
303 * first... */
304 u32 size = sizeof(netmsg_auth) + network_client.app_key_length;
305 netmsg_auth *auth = alloca(size);
306 auth->inetmsg_id = k_inetmsg_auth;
307 auth->ticket_length = network_client.app_key_length;
308 for( int i=0; i<network_client.app_key_length; i++ )
309 auth->ticket[i] = network_client.app_symmetric_key[i];
310
311 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
312 hSteamNetworkingSockets, network_client.remote, auth, size,
313 k_nSteamNetworkingSend_Reliable, NULL );
314 }
315 else if( info->m_info.m_eState ==
316 k_ESteamNetworkingConnectionState_ClosedByPeer ){
317
318 if( info->m_info.m_eEndReason ==
319 k_ESteamNetConnectionEnd_Misc_InternalError ){
320 network_client.retries = 40;
321 }
322 network_disconnect();
323 }
324 else if( info->m_info.m_eState ==
325 k_ESteamNetworkingConnectionState_ProblemDetectedLocally ){
326 network_disconnect();
327 }
328 }
329 else{
330 //vg_warn( " Recieved signal from unknown connection\n" );
331 }
332 }
333
334 static void on_persona_state_change( CallbackMsg_t *msg ){
335 if( !network_connected() )
336 return;
337
338 PersonaStateChange_t *info = (void *)msg->m_pubParam;
339 ISteamUser *hSteamUser = SteamAPI_SteamUser();
340
341 vg_info( "User: %llu, change: %u\n", info->m_ulSteamID,
342 info->m_nChangeFlags );
343
344 if( info->m_ulSteamID == SteamAPI_ISteamUser_GetSteamID(hSteamUser) ){
345 if( info->m_nChangeFlags & k_EPersonaChangeName ){
346 network_send_username();
347 }
348 }
349
350 if( info->m_nChangeFlags & k_EPersonaChangeRelationshipChanged ){
351 for( u32 i=0; i<NETWORK_MAX_PLAYERS; i ++ ){
352 struct network_player *rp = &netplayers.list[i];
353 if( rp->steamid == info->m_ulSteamID ){
354 player_remote_update_friendflags( rp );
355 }
356 }
357 }
358 }
359
360 static void network_connect(void){
361 char ip_buf[128];
362 vg_str str;
363 vg_strnull( &str, ip_buf, sizeof(ip_buf) );
364 vg_strcat( &str, network_client.server_adress );
365 vg_strcat( &str, ":" );
366 vg_strcati32( &str, NETWORK_PORT );
367
368 if( !vg_strgood(&str) ) return;
369
370 /* Connect to server if not connected */
371 SteamNetworkingIPAddr remoteAddr;
372 SteamAPI_SteamNetworkingIPAddr_ParseString( &remoteAddr, str.buffer );
373
374 char buf[256];
375 SteamAPI_SteamNetworkingIPAddr_ToString( &remoteAddr, buf, 256, 1 );
376 vg_info( "connect to: %s\n", buf );
377
378 network_client.remote = SteamAPI_ISteamNetworkingSockets_ConnectByIPAddress(
379 hSteamNetworkingSockets, &remoteAddr, 0, NULL );
380 }
381
382 static void network_sign_on_complete(void){
383 vg_success( "Sign on completed\n" );
384
385 /* send our init info */
386 network_send_username();
387 for( u32 i=0; i<k_netmsg_playeritem_max; i ++ ){
388 network_send_item(i);
389 }
390 }
391
392 static void poll_remote_connection(void){
393 SteamNetworkingMessage_t *messages[32];
394 int len;
395
396 for( int i=0; i<10; i++ ){
397 len = SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnConnection(
398 hSteamNetworkingSockets, network_client.remote,
399 messages, vg_list_size(messages));
400
401 if( len <= 0 )
402 return;
403
404 for( int i=0; i<len; i++ ){
405 SteamNetworkingMessage_t *msg = messages[i];
406
407 if( msg->m_cbSize < sizeof(netmsg_blank) ){
408 vg_warn( "Discarding message (too small: %d)\n", msg->m_cbSize );
409 continue;
410 }
411
412 netmsg_blank *tmp = msg->m_pData;
413
414 if( (tmp->inetmsg_id >= 200) && (tmp->inetmsg_id < 300) ){
415 player_remote_rx_200_300( msg );
416 }
417 else if( (tmp->inetmsg_id >= 300) && (tmp->inetmsg_id < 400) ){
418 network_request_rx_300_400( msg );
419 }
420 else {
421 if( tmp->inetmsg_id == k_inetmsg_version ){
422 netmsg_version *version = msg->m_pData;
423 if( version->version != NETWORK_SKATERIFT_VERSION ){
424 network_disconnect();
425 /* we dont want to connect to this server ever */
426 network_client.retries = 999;
427 network_client.last_attempt = 999999999.9;
428 vg_error( "version mismatch with server\n" );
429 }
430 else {
431 network_client.remote_version = version->version;
432 network_sign_on_complete();
433 }
434 }
435 }
436
437 SteamAPI_SteamNetworkingMessage_t_Release( msg );
438 }
439 }
440 }
441
442 static void network_update(void){
443 if( !steam_ready )
444 return;
445
446 ESteamNetworkingConnectionState state = network_client.state;
447
448 if( state == k_ESteamNetworkingConnectionState_Connected ){
449 poll_remote_connection();
450 f64 frame_delta = vg.time_real - network_client.last_frame;
451
452 if( frame_delta > NETWORK_FRAMERATE ){
453 network_client.last_frame = vg.time_real;
454 remote_player_send_playerframe();
455 player__clear_sfx_buffer();
456 }
457
458 remote_player_debug_update();
459 }
460 else {
461 if( (state == k_ESteamNetworkingConnectionState_Connecting) ||
462 (state == k_ESteamNetworkingConnectionState_FindingRoute) ){
463 return;
464 }
465 else {
466 f64 waited = vg.time_real - network_client.last_attempt,
467 min_wait = 1.0;
468
469 if( network_client.retries > 5 )
470 min_wait = 60.0;
471
472 if( waited < min_wait )
473 return;
474
475 network_connect();
476 network_client.retries ++;
477 network_client.last_attempt = vg.time_real;
478 }
479 }
480 }
481
482 static void chat_send_message( const char *message ){
483 if( !network_connected() ){
484 return;
485 }
486
487 netmsg_chat *chat = alloca( sizeof(netmsg_chat) + NETWORK_MAX_CHAT );
488 chat->inetmsg_id = k_inetmsg_chat;
489 chat->client = 0;
490
491 u32 l = vg_strncpy( message, chat->msg, NETWORK_MAX_CHAT,
492 k_strncpy_always_add_null );
493
494 SteamAPI_ISteamNetworkingSockets_SendMessageToConnection(
495 hSteamNetworkingSockets, network_client.remote,
496 chat, sizeof(netmsg_chat)+l+1,
497 k_nSteamNetworkingSend_Reliable, NULL );
498 }
499
500 static int cmd_network_send_message( int argc, const char *argv[] ){
501 char buf[ NETWORK_MAX_CHAT ];
502 vg_str str;
503 vg_strnull( &str, buf, NETWORK_MAX_CHAT );
504
505 for( int i=0; i<argc; i ++ ){
506 vg_strcat( &str, argv[i] );
507
508 if( i < argc-1 )
509 vg_strcatch( &str, ' ' );
510 }
511
512 chat_send_message( buf );
513 return 0;
514 }
515
516 static void network_init(void){
517 vg_console_reg_var( "network_info", &network_client.network_info,
518 k_var_dtype_i32, VG_VAR_PERSISTENT );
519 if( steam_ready ){
520 u32 alloc_size = sizeof(struct network_request)*NETWORK_MAX_REQUESTS;
521 network_client.request_buffer =
522 vg_linear_alloc( vg_mem.rtmemory, alloc_size );
523 memset( network_client.request_buffer, 0, alloc_size );
524
525 vg_pool *pool = &network_client.request_pool;
526 pool->buffer = network_client.request_buffer;
527 pool->count = NETWORK_MAX_REQUESTS;
528 pool->stride = sizeof( struct network_request );
529 pool->offset = offsetof( struct network_request, poolnode );
530 vg_pool_init( pool );
531
532 steam_register_callback( k_iSteamNetConnectionStatusChangedCallBack,
533 on_server_connect_status );
534 steam_register_callback( k_iPersonaStateChange,
535 on_persona_state_change );
536 request_auth_ticket();
537
538 vg_console_reg_cmd( "say", cmd_network_send_message, NULL );
539 }
540 }
541
542 static void network_end(void){
543 /* TODO: Send buffered highscores that were not already */
544 if( (network_client.state == k_ESteamNetworkingConnectionState_Connected) ||
545 (network_client.state == k_ESteamNetworkingConnectionState_Connecting) )
546 {
547 SteamAPI_ISteamNetworkingSockets_CloseConnection(
548 hSteamNetworkingSockets, network_client.remote, 0, NULL, 1 );
549 }
550 }