Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/masterserver2/src/libraries/network/MasterServer.cc @ 8344

Last change on this file since 8344 was 8280, checked in by smerkli, 14 years ago

ms-delserver command implemented to kick servers from the master server list

File size: 11.7 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      Sandro 'smerkli' Merkli
24 *   Co-authors:
25 *      ...
26 *
27 */
28
29#include "MasterServer.h"
30#include "util/ScopedSingletonManager.h"
31#include "core/command/ConsoleCommand.h"
32#include "core/CoreIncludes.h"
33#include "core/CorePrereqs.h"
34
35namespace orxonox
36{
37  /*** MACROS ***/
38  /* commands for the terminal interface */
39  SetConsoleCommand( "ms-listservers", &MasterServer::listServers );
40  SetConsoleCommand( "ms-delserver", &MasterServer::delServer );
41  //SetConsoleCommand( "ms-serverinfo", &MasterServer::serverInfo );
42
43  /* forward declaration so the linker doesn't complain */
44  MasterServer *MasterServer::instance = NULL;
45
46
47
48
49  /* command: list servers */
50  void 
51  MasterServer::listServers( void )
52  {
53    /* get an iterator */
54    std::list<ServerListElem>::iterator i;
55
56    /* print list header */
57    COUT(0) << "List of connected servers" << std::endl;
58
59    /* loop through list elements */
60    for( i = MasterServer::getInstance()->mainlist.serverlist.begin(); 
61      i != MasterServer::getInstance()->mainlist.serverlist.end(); ++i ) 
62    {
63      COUT(0) << "  " << (*i).ServerInfo.getServerIP() << std::endl;
64    }
65
66    /* display end of list */
67    COUT(0) << MasterServer::getInstance()->mainlist.serverlist.size() <<
68      " servers connected." << std::endl;
69  }
70
71  void 
72  MasterServer::delServer( std::string todeladdr )
73  {
74    /* tell the user we're now removing the entry from the server list */
75    COUT(0) << "MS: Deleting server \"" << todeladdr << "\"..." 
76      << std::endl;
77
78    /* see if we actually have that server on our list */
79    ServerListSearchResult shandle = 
80      MasterServer::getInstance()->mainlist.findServerByAddress(todeladdr);
81
82    if( !shandle.success )
83    { COUT(0) << "MS: Server not found, not removing." << std::endl;
84      return;
85    }
86
87    /* force-disconnect the server */ 
88    enet_peer_disconnect( shandle.result.peer, NULL );
89
90    /* actually remove the entry from the server list by address */
91    MasterServer::getInstance()->mainlist.delServerByAddress( todeladdr);
92
93    /* tell the user about our success */
94    COUT(0) << "MS: Server deletion successful." << std::endl;
95  }
96
97
98  /* helpers */
99  static void 
100  helper_output_debug( ENetEvent *event, char *addrconv )
101  {
102    COUT(4) << "A packet of length" 
103      << event->packet->dataLength
104      << " containing "
105      << (const char*)event->packet->data
106      << " was received from "
107      << addrconv
108      << " on channel "
109      << event->channelID << "\n";
110  }
111
112  void
113  MasterServer::helper_sendlist( ENetEvent *event )
114  {
115    /* get an iterator */
116    std::list<ServerListElem>::iterator i;
117
118    /* packet holder */
119    ENetPacket *reply;
120
121    /* loop through list elements */
122    for( i = mainlist.serverlist.begin(); i
123        != mainlist.serverlist.end(); ++i ) 
124    {
125      /* send this particular server */
126      /* build reply string */
127      char *tosend = (char *)calloc( (*i).ServerInfo.getServerIP().length() 
128          + MSPROTO_SERVERLIST_ITEM_LEN + 2,1 );
129      if( !tosend ) 
130      { COUT(2) << "Masterserver.cc: Memory allocation failed.\n";
131        continue;
132      } 
133      sprintf( tosend, "%s %s", MSPROTO_SERVERLIST_ITEM, 
134          (*i).ServerInfo.getServerIP().c_str() );
135
136      /* create packet from it */
137      reply = enet_packet_create( tosend,
138          strlen( tosend ) + 1, 
139          ENET_PACKET_FLAG_RELIABLE);
140
141      /* Send the reply to the peer over channel id 0. */
142      enet_peer_send( event->peer, 0, reply );
143
144      /* One could just use enet_host_service() instead. */
145      enet_host_flush( this->server );
146
147      /* free the tosend buffer */
148      free( tosend );
149    } 
150
151    /* create end-of-list packet */
152    reply = enet_packet_create( MSPROTO_SERVERLIST_END,
153        MSPROTO_SERVERLIST_END_LEN + 1,
154        ENET_PACKET_FLAG_RELIABLE );
155
156    /* send end-of-list packet */
157    enet_peer_send( event->peer, 0, reply );
158
159    /* One could just use enet_host_service() instead. */
160    enet_host_flush( this->server );
161  }
162
163  /* maybe the two methods below can be merged into one and
164   * made to use ENet's RTT functionality to check for disconnected
165   * servers.
166   */
167  void 
168  MasterServer::helper_cleanupServers( void )
169  {
170    /* get an iterator */
171    std::list<ServerListElem>::iterator i;
172     
173    if( mainlist.serverlist.size() == 0 )
174      return;
175
176    /* loop through list elements */
177    for( i = mainlist.serverlist.begin(); i
178        != mainlist.serverlist.end(); ++i ) 
179    { /* see if we have a disconnected peer */
180      if( (*i).peer && 
181         ((*i).peer->state == ENET_PEER_STATE_DISCONNECTED ||
182          (*i).peer->state == ENET_PEER_STATE_ZOMBIE ))
183      { 
184        /* Remove it from the list */
185        COUT(2) << (char*)(*i).peer->data << " timed out.\n";
186        mainlist.delServerByName( (*i).ServerInfo.getServerName() );
187
188        /* stop iterating, we manipulated the list */
189        /* TODO note: this only removes one dead server per loop
190         * iteration. not beautiful, but one iteration is ~100ms,
191         * so not really relevant for the moment.
192         */
193        break;
194      }
195    }
196 
197  }
198
199
200
201
202  /***** EVENTS *****/
203  /* connect event */
204  int 
205  MasterServer::eventConnect( ENetEvent *event )
206  { /* check for bad parameters */
207    if( !event )
208    { COUT(2) << "MasterServer::eventConnect: No event given.\n" ;
209      return -1;
210    }
211
212    /* convert address to string. */
213    char *addrconv = (char *) calloc( 50, 1 );
214    enet_address_get_host_ip( &(event->peer->address), addrconv, 49 );
215
216    /* output debug info */
217    COUT(4) << "A new client connected from " 
218      << addrconv
219      << " on port " 
220      << event->peer->address.port << "\n";
221
222    /* store string form of address here */
223    event->peer->data = addrconv; 
224
225    /* all fine. */
226    return 0;
227  }
228
229  /* disconnect event */
230  int 
231  MasterServer::eventDisconnect( ENetEvent *event )
232  { /* check for bad parameters */
233    if( !event )
234    { COUT(2) << "No event given.\n";
235      return -1;
236    }
237
238    /* output that the disconnect happened */
239    COUT(2) << (char*)event->peer->data << " disconnected.\n";
240
241    /* create string from peer data */
242    std::string name = std::string( (char*)event->peer->data );
243
244    /* remove the server from the list it belongs to */
245    this->mainlist.delServerByName( name );
246
247    /* Reset the peer's client information. */
248    if( event->peer->data ) free( event->peer->data );
249
250    /* done */
251    return 0;
252  }
253
254  /* data event */
255  int 
256  MasterServer::eventData( ENetEvent *event )
257  { /* validate packet */
258    if( !event || !(event->packet) || !(event->peer) )
259    { COUT(2) << "No complete event given.\n";
260      return -1;
261    }
262     
263    /* generate address in readable form */
264    char *addrconv = (char *) calloc( 50, 1 );
265    enet_address_get_host_ip( &(event->peer->address), addrconv, 49 );
266
267    /* output debug info about the data that has come */
268    helper_output_debug( event, addrconv );
269
270    /* GAME SERVER OR CLIENT CONNECTION? */
271    if( !strncmp( (char *)event->packet->data, MSPROTO_GAME_SERVER, 
272      MSPROTO_GAME_SERVER_LEN ) )
273    { /* Game server */
274
275      if( !strncmp( (char *)event->packet->data
276        + MSPROTO_GAME_SERVER_LEN+1, 
277        MSPROTO_REGISTER_SERVER, MSPROTO_REGISTER_SERVER_LEN ) )
278      { /* register new server */
279        mainlist.addServer( packet::ServerInformation( event ),
280          event->peer );
281       
282        /* tell people we did so */
283        COUT(2) << "Added new server to list: " << 
284          packet::ServerInformation( event ).getServerIP() << "\n";
285      }
286
287      else if( !strncmp( (char *)event->packet->data
288        + MSPROTO_GAME_SERVER_LEN+1,
289        MSPROTO_SERVERDC, MSPROTO_SERVERDC_LEN ) )
290      {
291        /* create string from peer data */
292        std::string name = std::string( addrconv );
293
294        /* remove the server from the list it belongs to */
295        this->mainlist.delServerByAddress( name );
296
297        /* tell the user */
298        COUT(2) << "Removed server " << name << " from list.\n";
299      }
300
301      /* TODO add hook for disconnect here */
302    }
303    else if( !strncmp( (char *)event->packet->data, MSPROTO_CLIENT, 
304      MSPROTO_CLIENT_LEN) )
305    { /* client */
306      if( !strncmp( (char *)event->packet->data + MSPROTO_CLIENT_LEN+1,
307        MSPROTO_REQ_LIST, MSPROTO_REQ_LIST_LEN ) )
308        /* send server list */
309        helper_sendlist( event );
310    }
311    else
312    { /* bad message, don't do anything. */ } 
313
314    /* delete addrconv */
315    if( addrconv ) free( addrconv );
316
317    /* Clean up the packet now that we're done using it. */
318    enet_packet_destroy( event->packet );
319    return 0;
320  }
321
322
323  /**** MAIN ROUTINE *****/
324  int 
325  MasterServer::run()
326  {
327    /***** ENTER MAIN LOOP *****/
328    ENetEvent *event = (ENetEvent *)calloc(sizeof(ENetEvent), sizeof(char));
329    if( event == NULL )
330    { 
331      COUT(1) << "Could not create ENetEvent structure, exiting.\n";
332      exit( EXIT_FAILURE );
333    }
334
335    /* check for timed out peers and remove those from * the server list */
336    helper_cleanupServers();
337
338
339    /* create an iterator for the loop */
340    enet_host_service( this->server, event, 100 );
341
342    /* check what type of event it is and react accordingly */
343    switch (event->type)
344    { /* new connection */
345      case ENET_EVENT_TYPE_CONNECT: 
346        eventConnect( event ); break;
347
348        /* disconnect */
349      case ENET_EVENT_TYPE_DISCONNECT: 
350        eventDisconnect( event ); break;
351
352        /* incoming data */
353      case ENET_EVENT_TYPE_RECEIVE: eventData( event ); break;
354      default: break;
355    }
356
357    /* done */
358    return 0;
359  } 
360
361  /* constructor */
362  MasterServer::MasterServer()
363  {
364    /***** INITIALIZE NETWORKING *****/
365    if( enet_initialize () != 0)
366    { COUT(1) << "An error occurred while initializing ENet.\n";
367      exit( EXIT_FAILURE );
368    }
369
370    /* register deinitialization */
371    atexit( enet_deinitialize );
372
373    /* set the quit flag to false */
374    this->quit = false;
375
376    /* Bind the server to the default localhost and port ORX_MSERVER_PORT */
377    this->address.host = ENET_HOST_ANY;
378    this->address.port = ORX_MSERVER_PORT;
379
380    /* create a host with the above settings (the last two 0 mean: accept
381     * any input/output bandwidth */
382    this->server = enet_host_create( &this->address, ORX_MSERVER_MAXCONNS, 
383        ORX_MSERVER_MAXCHANS, 0, 0 );
384    assert(this->server);
385
386    /* see if creation worked */
387    if( !this->server )
388    { COUT(1) << 
389        "An error occurred while trying to create an ENet server host.\n";
390      exit( EXIT_FAILURE );
391    }
392
393    /* set pointer to this instance */
394    MasterServer::setInstance( this );
395
396    /* tell people we're now initialized */
397    COUT(0) << "MasterServer initialized, waiting for connections.\n";
398  }
399
400  /* destructor */
401  MasterServer::~MasterServer()
402  {
403    /***** CLEANUP PROCESS *****/
404    /* terminate all networking connections */
405    enet_host_destroy( this->server );
406
407    /* TODO free all used memory */
408    /* clear the list of connected game servers */
409    /* clear the list of connected game clients */
410  }
411
412/* end of namespace */
413}
Note: See TracBrowser for help on using the repository browser.