Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/HUD_HS16/src/libraries/network/MasterServer.cc @ 11888

Last change on this file since 11888 was 11083, checked in by muemart, 9 years ago

Fix some clang-tidy warnings.
Also, Serialise.h was doing some C-style casts that ended up being const casts. I moved those const casts as close to the source as possible and changed the loadAndIncrease functions to not do that.

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