7e0e21c3883712c9e240251d9a7b7a624bc2ad8f
[carveJwlIkooP6JGAAIwe30JlM.git] / servermonitor_server.c
1 #include <sys/socket.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <errno.h>
5 #include <string.h>
6 #include <sys/types.h>
7 #include <sys/un.h>
8 #include "monitorinfo.h"
9 #include "gameserver.h"
10
11 static int monitor_write_index( int index, const void *buf, size_t nbyte ){
12 int fd = gameserver.monitor_clients[ index ];
13 if( write( fd, buf, nbyte ) == -1 ){
14 gameserver.monitor_clients[ index ] = -1;
15 vg_error( "Monitor client disconnected (%d)\n", index );
16 close( fd );
17 return 0;
18 }
19 else
20 return 1;
21 }
22
23 static void monitor_accept_connections(void){
24 char sendbuff[1025];
25 int fd = accept( gameserver.monitor_fd, (struct sockaddr*)NULL, NULL );
26
27 if( fd == -1 )
28 return;
29
30 int index = -1;
31 for( int i=0; i<vg_list_size(gameserver.monitor_clients); i ++ ){
32 if( gameserver.monitor_clients[i] == -1 ){
33 index = i;
34 break;
35 }
36 }
37
38 vg_info( "New monitor client (fd: %d, index: %d)\n", fd, index );
39
40 if( index == -1 ){
41 snprintf( sendbuff, sizeof(sendbuff), "MONITOR_FULL\n" );
42 write( fd, sendbuff, strlen(sendbuff) );
43 close( fd );
44 return;
45 }
46
47 gameserver.monitor_clients[ index ] = fd;
48
49 time_t ticks = time( NULL );
50 snprintf( sendbuff, sizeof(sendbuff), "logged in %.24s\n", ctime(&ticks) );
51 if( monitor_write_index( index, sendbuff, strlen(sendbuff) ) )
52 vg_success( "Accepted\n" );
53 }
54
55 static void monitor_heartbeat(void){
56 for( int i=0; i<vg_list_size(gameserver.monitor_clients); i++ ){
57 if( gameserver.monitor_clients[i] != -1 )
58 monitor_write_index( i, NULL, 0 );
59 }
60 }
61
62 static void monitor_start_server(void){
63 for( int i=0; i<vg_list_size(gameserver.monitor_clients); i++ ){
64 gameserver.monitor_clients[i] = -1;
65 }
66
67 struct sockaddr_un serv_addr;
68
69 char sendbuff[1025];
70
71 gameserver.monitor_fd = socket( AF_UNIX, SOCK_STREAM|SOCK_NONBLOCK, 0 );
72 memset( &serv_addr, 0, sizeof(serv_addr) );
73 memset( sendbuff, 0, sizeof(sendbuff) );
74
75 serv_addr.sun_family = AF_UNIX;
76 strcpy( serv_addr.sun_path, MONITOR_SOCK_PATH );
77
78 unlink( MONITOR_SOCK_PATH );
79 bind( gameserver.monitor_fd,
80 (struct sockaddr*)&serv_addr, sizeof(serv_addr) );
81 listen( gameserver.monitor_fd, 4 );
82 }
83
84 static void monitor_event_loop(void){
85 monitor_accept_connections();
86 }