Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/campaignHS15/src/libraries/network/MasterServer.cc @ 10860

Last change on this file since 10860 was 10624, checked in by landauf, 9 years ago

merged branch core7 back to trunk

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