Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/network_stream.cc @ 9701

Last change on this file since 9701 was 9656, checked in by bensch, 18 years ago

orxonox/trunk: merged the proxy bache back with no conflicts

File size: 40.7 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11### File Specific:
12   main-programmer: Christoph Renner rennerc@ee.ethz.ch
13   co-programmer:   Patrick Boenzli  patrick@orxonox.ethz.ch
14
15     June 2006: finishing work on the network stream for pps presentation (rennerc@ee.ethz.ch)
16     July 2006: some code rearangement and integration of the proxy server mechanism (patrick@orxonox.ethz.ch)
17*/
18
19
20#define DEBUG_MODULE_NETWORK
21
22#include "proxy/proxy_control.h"
23
24#include "base_object.h"
25#include "network_protocol.h"
26#include "udp_socket.h"
27#include "udp_server_socket.h"
28#include "monitor/connection_monitor.h"
29#include "monitor/network_monitor.h"
30#include "synchronizeable.h"
31#include "ip.h"
32#include "network_game_manager.h"
33#include "shared_network_data.h"
34#include "message_manager.h"
35#include "preferences.h"
36#include "zip.h"
37
38#include "src/lib/util/loading/resource_manager.h"
39
40#include "network_log.h"
41
42#include "player_stats.h"
43
44#include "lib/util/loading/factory.h"
45
46#include "debug.h"
47#include "class_list.h"
48#include <algorithm>
49
50
51#include "network_stream.h"
52
53
54#include "converter.h"
55
56
57#define PACKAGE_SIZE  256
58
59
60/**
61 * empty constructor
62 */
63NetworkStream::NetworkStream()
64    : DataStream()
65{
66  this->init();
67  /* initialize the references */
68  this->pInfo->nodeType = NET_UNASSIGNED;
69}
70
71
72NetworkStream::NetworkStream( int nodeType)
73{
74  this->init();
75
76  this->pInfo->nodeType = nodeType;
77
78  switch( nodeType)
79  {
80    case NET_MASTER_SERVER:
81      // init the shared network data
82      SharedNetworkData::getInstance()->setHostID(NET_ID_MASTER_SERVER);
83      this->pInfo->userId = NET_ID_MASTER_SERVER;
84      this->pInfo->nodeType = NET_MASTER_SERVER;
85
86      break;
87    case NET_PROXY_SERVER_ACTIVE:
88      // init the shared network data
89      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
90      this->pInfo->nodeType = NET_PROXY_SERVER_ACTIVE;
91
92      break;
93    case NET_PROXY_SERVER_PASSIVE:
94      // init the shared network data
95      SharedNetworkData::getInstance()->setHostID(NET_ID_PROXY_SERVER_01);
96      this->pInfo->nodeType = NET_PROXY_SERVER_PASSIVE;
97
98      break;
99    case NET_CLIENT:
100      SharedNetworkData::getInstance()->setHostID(NET_ID_UNASSIGNED);
101      this->pInfo->nodeType = NET_CLIENT;
102      break;
103  }
104
105  SharedNetworkData::getInstance()->setDefaultSyncStream(this);
106
107  // get the local ip address
108  IP ip("localhost", 0);
109  this->pInfo->ip = ip;
110}
111
112
113
114/**
115 * generic init functions
116 */
117void NetworkStream::init()
118{
119  /* set the class id for the base object */
120  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
121  this->clientSocket = NULL;
122  this->clientSoftSocket = NULL;
123  this->proxySocket = NULL;
124  this->networkGameManager = NULL;
125  this->networkMonitor = NULL;
126
127  this->pInfo = new PeerInfo();
128  this->pInfo->userId = NET_UID_UNASSIGNED;
129  this->pInfo->lastAckedState = 0;
130  this->pInfo->lastRecvedState = 0;
131  this->pInfo->bLocal = true;
132
133  this->bRedirect = false;
134
135  this->currentState = 0;
136  this->redirectionUID = NET_ID_MASTER_SERVER;
137
138  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
139
140  assert( Zip::getInstance()->loadDictionary( "testdict" ) >= 0 );
141  this->dictClient = Zip::getInstance()->loadDictionary( "dict2pl_client" );
142  assert( this->dictClient >= 0 );
143  this->dictServer = Zip::getInstance()->loadDictionary( "dict2p_server" );
144  assert( this->dictServer >= 0 );
145}
146
147
148/**
149 * deconstructor
150 */
151NetworkStream::~NetworkStream()
152{
153  if ( this->clientSocket )
154  {
155    this->clientSocket->close();
156    delete this->clientSocket;
157    this->clientSocket = NULL;
158  }
159  if ( this->clientSoftSocket )
160  {
161    this->clientSoftSocket->close();
162    delete this->clientSoftSocket;
163    this->clientSoftSocket = NULL;
164  }
165  if ( this->proxySocket)
166  {
167    proxySocket->close();
168    delete proxySocket;
169    proxySocket = NULL;
170  }
171  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
172  {
173    if ( i->second.socket )
174    {
175      i->second.socket->disconnectServer();
176      delete i->second.socket;
177      i->second.socket = NULL;
178    }
179
180    if ( i->second.handshake )
181    {
182      delete i->second.handshake;
183      i->second.handshake = NULL;
184    }
185
186    if ( i->second.connectionMonitor )
187    {
188      delete i->second.connectionMonitor;
189      i->second.connectionMonitor = NULL;
190    }
191  }
192  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
193    (*it)->setNetworkStream( NULL );
194
195  if( this->pInfo)
196    delete this->pInfo;
197
198  if( this->networkMonitor)
199    delete this->networkMonitor;
200}
201
202
203/**
204 * establish a connection to a remote master server
205 * @param host: host name
206 * @param port: the port number
207 */
208void NetworkStream::connectToMasterServer(std::string host, int port)
209{
210  int node = NET_ID_MASTER_SERVER;
211  // this create the new node in the peers map
212  this->peers[node].socket = new UdpSocket( host, port );
213  this->peers[node].userId = NET_ID_MASTER_SERVER;
214
215  this->peers[node].nodeType = NET_MASTER_SERVER;
216  this->peers[node].connectionMonitor = new ConnectionMonitor( NET_ID_MASTER_SERVER );
217  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
218  this->peers[node].bLocal = true;
219}
220
221
222/**
223 * establish a connection to a remote proxy server
224 * @param host: host name
225 * @param port: the port number
226 */
227void NetworkStream::connectToProxyServer(int proxyId, std::string host, int port)
228{
229  PRINTF(0)("connect to proxy %s, this is proxyId %i\n", host.c_str(), proxyId);
230
231  // this creates the new proxyId in the peers map
232  this->peers[proxyId].socket = new UdpSocket( host, port );
233  this->peers[proxyId].userId = proxyId;
234
235  this->peers[proxyId].nodeType = NET_PROXY_SERVER_ACTIVE;
236  this->peers[proxyId].connectionMonitor = new ConnectionMonitor( proxyId );
237  this->peers[proxyId].ip = this->peers[proxyId].socket->getRemoteAddress();
238  this->peers[proxyId].bLocal = true;
239}
240
241
242/**
243 * create a server
244 * @param port: interface port for all clients
245 */
246void NetworkStream::createServer(int clientPort, int proxyPort, int clientSoftPort)
247{
248  PRINTF(0)(" Creating new Server: listening for clients on port %i and for proxies on port %i", clientPort, proxyPort);
249  this->clientSocket= new UdpServerSocket(clientPort);
250  this->clientSoftSocket= new UdpServerSocket(clientSoftPort);
251  this->proxySocket = new UdpServerSocket(proxyPort);
252}
253
254
255/**
256 * creates a new instance of the network game manager
257 */
258void NetworkStream::createNetworkGameManager()
259{
260  this->networkGameManager = NetworkGameManager::getInstance();
261
262  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
263  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
264}
265
266
267/**
268 * starts the network handshake
269 * handsakes are always initialized from the client side first. this starts the handshake and therefore is only
270 * executed as client
271 * @param userId: start handshake for this user id (optional, default == 0)
272 */
273void NetworkStream::startHandshake(int userId)
274{
275  Handshake* hs = new Handshake(this->pInfo->nodeType);
276  // fake the unique id
277  hs->setUniqueID( userId);
278  assert( this->peers[userId].handshake == NULL );
279  this->peers[userId].handshake = hs;
280  this->peers[userId].bLocal = true;
281
282  // set the preferred nick name
283  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
284
285  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getCName());
286}
287
288
289/**
290 * this functions connects a synchronizeable to the networkstream, therefore synchronizeing
291 * it all over the network and creating it on the other platforms (if and only if it is a
292 * server
293 * @param sync: the synchronizeable to add
294 */
295void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
296{
297  this->synchronizeables.push_back(&sync);
298  sync.setNetworkStream( this );
299}
300
301
302/**
303 * removes the synchronizeable from the list of synchronized entities
304 * @param sync: the syncronizeable to remove
305 */
306void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
307{
308  // removing the Synchronizeable from the List.
309  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
310  if (disconnectSynchro != this->synchronizeables.end())
311    this->synchronizeables.erase(disconnectSynchro);
312
313  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
314}
315
316
317/**
318 * this is called to process data from the network socket to the synchronizeable and vice versa
319 */
320void NetworkStream::processData()
321{
322  // create the network monitor after all the init work and before there is any connection handlings
323  if( this->networkMonitor == NULL)
324  {
325    this->networkMonitor = new NetworkMonitor(this);
326    SharedNetworkData::getInstance()->setNetworkMonitor( this->networkMonitor);
327  }
328
329
330  int tick = SDL_GetTicks();
331
332  this->currentState++;
333  // there was a wrap around
334  if( this->currentState < 0)
335  {
336    PRINTF(1)("A wrap around in the state variable as occured. The server was running so long? Pls restart server or write a mail to the supporters!\n");
337  }
338
339  if ( SharedNetworkData::getInstance()->isMasterServer())
340  {
341    // execute everytthing the master server shoudl do
342    if ( this->clientSocket )
343      this->clientSocket->update();
344    if ( this->clientSoftSocket)
345      this->clientSoftSocket->update();
346    if( this->proxySocket)
347      this->proxySocket->update();
348
349    this->updateConnectionList();
350  }
351  else if( SharedNetworkData::getInstance()->isProxyServerActive())
352  {
353    //execute everything the proxy server should do
354    if ( this->clientSocket )
355      this->clientSocket->update();
356    if ( this->clientSoftSocket)
357      this->clientSoftSocket->update();
358    if( this->proxySocket)
359      this->proxySocket->update();
360
361    this->updateConnectionList();
362  }
363
364#warning make this more modular: every proxy/master server connection should be watched for termination
365  if( !SharedNetworkData::getInstance()->isMasterServer())
366  {
367    // check if the connection is ok else terminate and remove
368    if ( !peers.empty() && peers[NET_ID_MASTER_SERVER].socket &&
369          ( !peers[NET_ID_MASTER_SERVER].socket->isOk() ||
370          peers[NET_ID_MASTER_SERVER].connectionMonitor->hasTimedOut() ) )
371    {
372      this->handleDisconnect( NET_ID_MASTER_SERVER);
373      PRINTF(1)("lost connection to server\n");
374    }
375    // check if there is a redirection command
376    if( this->bRedirect)
377    {
378      this->handleReconnect( this->redirectionUID);
379    }
380  }
381
382  this->cleanUpOldSyncList();
383  this->handleHandshakes();
384
385  // update the network monitor
386  this->networkMonitor->process();
387
388  // order of up/downstream is important!!!!
389  // don't change it
390  this->handleDownstream( tick );
391  this->handleUpstream( tick );
392
393  // process the local data of the message manager
394  MessageManager::getInstance()->processData();
395
396  if( this->bSoftRedirect)
397    this->softReconnectToServer(0, IP("localhost", 10001));
398}
399
400
401/**
402 * @brief handles incoming connections
403 *
404 * if we are a NET_MASTER_SERVER or NET_PROXY_SERVER_ACTIVE update the connection list to accept new connections (clients)
405 * start and initialize the handsake for the new clients
406 */
407void NetworkStream::updateConnectionList( )
408{
409  //check for new connections
410
411  NetworkSocket* tempNetworkSocket = NULL;
412  int userId;
413
414  if( this->clientSocket != NULL)
415  {
416    tempNetworkSocket = this->clientSocket->getNewSocket();
417
418    // we got new NET_CLIENT connecting
419    if ( tempNetworkSocket )
420    {
421      // get a userId
422//       if ( freeSocketSlots.size() > 0 )
423//       {
424//         // this should never be called
425//         userId = freeSocketSlots.back();
426//         freeSocketSlots.pop_back();
427//       }
428//       else
429      {
430        // each server (proxy and master) have an address space for new network nodes of 1000 nodes
431        // the first NET_ID_PROXY_MAX are always reserved for proxy servers
432        userId = SharedNetworkData::getInstance()->getHostID() * 1000 + NET_ID_PROXY_MAX + 1;
433
434        for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
435          if ( it->first >= userId )
436            userId = it->first + 1;
437
438        // make sure that this server only uses an address space of 1000
439        assert( userId < (SharedNetworkData::getInstance()->getHostID() + 1) * 1000);
440      }
441      // this creates a new entry in the peers list
442      peers[userId].socket = tempNetworkSocket;
443      peers[userId].nodeType = NET_CLIENT;
444
445      // handle the newly connected client
446      this->handleConnect(userId);
447
448      PRINTF(0)("New Client: %d\n", userId);
449    }
450  }
451
452  if( this->clientSoftSocket != NULL)
453  {
454    tempNetworkSocket = this->clientSoftSocket->getNewSocket();
455
456    // we got new NET_CLIENT connecting
457    if ( tempNetworkSocket )
458    {
459
460      // this creates a new entry in the peers list
461      peers[userId].socket = tempNetworkSocket;
462      peers[userId].nodeType = NET_CLIENT;
463
464      // handle the newly connected client
465      this->handleSoftConnect(userId);
466
467      PRINTF(0)("New Client softly connected: %d :D\n", userId);
468    }
469  }
470
471
472  if( this->proxySocket != NULL)
473  {
474    tempNetworkSocket = this->proxySocket->getNewSocket();
475
476    // we got new NET_PROXY_SERVER_ACTIVE connecting
477    if ( tempNetworkSocket )
478    {
479      // determine the network node id
480//       if ( freeSocketSlots.size() > 0 )
481//       {
482//         userId = freeSocketSlots.back();
483//         freeSocketSlots.pop_back();
484//       }
485//       else
486      {
487        userId = 1;
488
489        // find an empty slot within the range
490        for( int i = 0; i < NET_ID_PROXY_MAX; i++)
491        {
492          if( this->peers.find( i) == this->peers.end())
493          {
494            userId = i;
495            break;
496          }
497        }
498
499//         for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
500//           if ( it->first >= userId )
501//             userId = it->first + 1;
502      }
503
504      // this creates a new entry in the peers list
505      peers[userId].socket = tempNetworkSocket;
506      peers[userId].nodeType = NET_PROXY_SERVER_ACTIVE;
507
508      // handle the newly connected proxy server
509      this->handleConnect(userId);
510
511      PRINTF(0)("New proxy connected: %d\n", userId);
512    }
513  }
514
515
516
517  //check if connections are ok else remove them
518  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
519  {
520    if (
521          it->second.socket &&
522          (
523            !it->second.socket->isOk()  ||
524            it->second.connectionMonitor->hasTimedOut()
525          )
526       )
527    {
528      std::string reason = "disconnected";
529      if ( it->second.connectionMonitor->hasTimedOut() )
530        reason = "timeout";
531      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
532
533
534      this->handleDisconnect( it->second.userId);
535
536      if( SharedNetworkData::getInstance()->isProxyServerActive())
537        ProxyControl::getInstance()->signalLeaveClient(it->second.userId);
538
539      it++;
540      continue;
541    }
542
543    it++;
544  }
545}
546
547
548/**
549 * this handles new connections
550 * @param userId: the id of the new user node
551 */
552void NetworkStream::handleConnect( int userId)
553{
554  // create new handshake and init its variables
555  this->peers[userId].handshake = new Handshake(this->pInfo->nodeType, userId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
556  this->peers[userId].handshake->setUniqueID(userId);
557
558  this->peers[userId].connectionMonitor = new ConnectionMonitor( userId );
559  this->peers[userId].userId = userId;
560  this->peers[userId].bLocal = true;
561
562  PRINTF(0)("num sync: %d\n", synchronizeables.size());
563
564  // get the proxy server informations and write them to the handshake, if any (proxy)
565  assert( this->networkMonitor != NULL);
566  PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
567  if( pi != NULL)
568  {
569    this->peers[userId].handshake->setProxy1Address( pi->ip);
570  }
571  pi = this->networkMonitor->getSecondChoiceProxy();
572  if( pi != NULL)
573    this->peers[userId].handshake->setProxy2Address( pi->ip);
574
575  // check if the connecting client should reconnect to a proxy server
576  if( SharedNetworkData::getInstance()->isMasterServer())
577  {
578    if( this->networkMonitor->isReconnectNextClient())
579    {
580      this->peers[userId].handshake->setRedirect(true);
581      PRINTF(0)("forwarding client to proxy server because this server is saturated\n");
582    }
583  }
584
585  // the connecting node of course is a client
586  this->peers[userId].ip = this->peers[userId].socket->getRemoteAddress();
587}
588
589
590/**
591 * this handles new soft connections
592 * @param userId: the id of the new user node
593 *
594 * soft connections are connections from clients that are already in the network and don't need a new handshake etc.
595 * the state of all entitites owned by userId are not deleted and stay
596 * soft connections can not be redirected therefore they are negotiated between the to parties
597 */
598void NetworkStream::handleSoftConnect( int userId)
599{
600  // create new handshake and init its variables
601  this->peers[userId].handshake = NULL;
602  this->peers[userId].handshake->setUniqueID(userId);
603
604  this->peers[userId].connectionMonitor = new ConnectionMonitor( userId );
605  this->peers[userId].userId = userId;
606  this->peers[userId].bLocal = true;
607
608  PRINTF(0)("num sync: %d\n", synchronizeables.size());
609
610  // the connecting node of course is a client
611  this->peers[userId].ip = this->peers[userId].socket->getRemoteAddress();
612}
613
614
615
616
617/**
618 * some debug output
619 */
620void NetworkStream::debug()
621{
622  if( SharedNetworkData::getInstance()->isMasterServer()) {
623    PRINT(0)(" Host ist Master Server with ID: %i\n", this->pInfo->userId);
624  }
625  else if( SharedNetworkData::getInstance()->isProxyServerActive()) {
626    PRINT(0)(" Host ist Proxy Server with ID: %i\n", this->pInfo->userId);
627  }
628  else {
629    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
630  }
631
632  PRINT(0)(" Current number of connections is: %i\n", this->peers.size());
633  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
634  {
635    PRINT(0)("  peers[%i] with uniqueId %i and address: %s\n", it->first, it->second.userId, it->second.ip.ipString().c_str());
636  }
637  PRINT(0)("\n\n");
638
639
640  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
641  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
642  {
643    if( (*it)->beSynchronized() == true)
644      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassCName(), (*it)->getCName(),
645               (*it)->getUniqueID(), (*it)->beSynchronized());
646  }
647  PRINT(0)(" Maximal Connections: %i\n", SharedNetworkData::getInstance()->getMaxPlayer() );
648
649}
650
651
652/**
653 * @returns the number of synchronizeables registered to this stream
654 */
655int NetworkStream::getSyncCount()
656{
657  int n = 0;
658  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
659    if( (*it)->beSynchronized() == true)
660      ++n;
661
662  //return synchronizeables.size();
663  return n;
664}
665
666
667/**
668 * check if handshakes completed. if so create the network game manager else remove it again
669 */
670void NetworkStream::handleHandshakes( )
671{
672  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
673  {
674    if ( it->second.handshake )
675    {
676      // handshake finished
677      if ( it->second.handshake->completed() )
678      {
679        //handshake is correct
680        if ( it->second.handshake->ok() )
681        {
682          // write the first informations into the node so they can be read from there for case differentiation
683          it->second.nodeType = it->second.handshake->getRemoteNodeType();
684
685          // the counter part didn't mark it free for deletion yet
686          if ( !it->second.handshake->allowDel() )
687          {
688            // make sure this is a connection:
689            // - client       <==> master server
690            // - proxy server <==> master server
691            if(  SharedNetworkData::getInstance()->isClient() ||
692                 SharedNetworkData::getInstance()->isProxyServerActive() &&
693                 SharedNetworkData::getInstance()->isUserMasterServer(it->second.userId))
694            {
695              PRINTF(4)("Handshake: i am in client role\n");
696
697              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
698              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
699
700//               it->second.ip = it->second.socket->getRemoteAddress();
701
702              it->second.nodeType = it->second.handshake->getRemoteNodeType();
703              // it->second.ip = it->second.socket->getRemoteAddress();
704              // add the new server to the nodes list (it can be a NET_MASTER_SERVER or NET_PROXY_SERVER)
705              this->networkMonitor->addNode(&it->second);
706              // get proxy 1 address and add it
707              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
708              // get proxy 2 address and add it
709              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
710
711              // now check if the server accepted the connection
712              if( SharedNetworkData::getInstance()->isClient() && it->second.handshake->redirect() )
713              {
714                this->bRedirect = true;
715              }
716
717              // create the new network game manager and init it
718              this->networkGameManager = NetworkGameManager::getInstance();
719              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
720              // init the new message manager
721              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
722            }
723
724            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
725            it->second.handshake->del();
726
727          }
728          else
729          {
730            // handshake finished registring new player
731            if ( it->second.handshake->canDel() )
732            {
733
734              if (  SharedNetworkData::getInstance()->isMasterServer() )
735              {
736                it->second.ip = it->second.socket->getRemoteAddress();
737
738                this->networkMonitor->addNode(&it->second);
739
740                this->handleNewClient( it->second.userId );
741
742                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
743                {
744                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
745                }
746              }
747              else if ( SharedNetworkData::getInstance()->isProxyServerActive() && it->second.isClient() )
748              {
749                PRINTF(4)("Handshake: Proxy in server role: connecting %i\n", it->second.userId);
750
751                it->second.ip = it->second.socket->getRemoteAddress();
752
753                this->networkMonitor->addNode(&it->second);
754
755                // work with the ProxyControl to init the new client
756                ProxyControl::getInstance()->signalNewClient( it->second.userId);
757
758                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
759                {
760                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
761                }
762              }
763
764              PRINT(0)("handshake finished delete it\n");
765              delete it->second.handshake;
766              it->second.handshake = NULL;
767            }
768          }
769
770        }
771        else
772        {
773          PRINT(1)("handshake failed!\n");
774          it->second.socket->disconnectServer();
775        }
776      }
777    }
778  }
779}
780
781
782/**
783 * this functions handles a reconnect event received from the a NET_MASTER_SERVER or NET_PROXY_SERVER
784 * @param userId
785 */
786void NetworkStream::handleReconnect(int userId)
787{
788  this->bRedirect = false;
789#warning this peer will be created if it does not yet exist: dangerous
790  PeerInfo* pInfo = &this->peers[userId];
791
792  IP proxyIP;
793  if( this->networkMonitor->isForcedReconnection())
794    proxyIP = this->networkMonitor->getForcedReconnectionIP();
795  else
796    proxyIP = pInfo->handshake->getProxy1Address();
797
798  PRINTF(0)("===============================================\n");
799  PRINTF(0)("Client is redirected to the other proxy servers\n");
800  PRINTF(0)("  user id: %i\n", userId);
801  PRINTF(0)("  connecting to: %s\n", proxyIP.ipString().c_str());
802  PRINTF(0)("===============================================\n");
803
804  // flush the old synchronization states, since the numbering could be completely different
805  pInfo->lastAckedState = 0;
806  pInfo->lastRecvedState = 0;
807
808  // disconnect from the current server and reconnect to proxy server
809  this->handleDisconnect( userId);
810  this->connectToProxyServer(NET_ID_PROXY_SERVER_01, proxyIP.ipString(), 9999);
811//   this->connectToMasterServer(proxyIP.ipString(), 9999);
812  #warning the ports are not yet integrated correctly in the ip class
813
814  // and restart the handshake
815  this->startHandshake( userId);
816}
817
818
819
820/**
821 * reconnects to another server, with full handshake
822 * @param address of the new server
823 */
824void NetworkStream::reconnectToServer(IP address)
825{
826  ///TODO make a redirection struct and push it to the network monitor
827  this->networkMonitor->setForcedReconnection(address);
828
829  // reconnect (depending on how we are connected at the moment)
830  if ( peers.find( NET_ID_MASTER_SERVER) != peers.end() )
831    this->redirectionUID = NET_ID_MASTER_SERVER;
832  else if( peers.find( NET_ID_PROXY_SERVER_01) != peers.end() )
833    this->redirectionUID = NET_ID_PROXY_SERVER_01;
834
835  this->bRedirect = true;
836}
837
838
839
840/**
841 * softly reconnecting to another server
842 * @param serverUserId the id of the client
843 * @param address  of the new server
844 */
845void NetworkStream::softReconnectToServer(int serverUserId, IP address)
846{
847//   this->networkMonitor->setForcedReconnection(address);
848//   this->handleReconnect( NET_ID_MASTER_SERVER);
849
850  // create the new udp socket and open the connection to the soft connection port
851  NetworkSocket* newSocket = new UdpSocket(address.ipString(), 10001);
852
853  // delete the synchronization state of this client for all syncs
854  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
855    (*it2)->cleanUpUser( serverUserId );
856  }
857
858  // temp save the old socket
859  NetworkSocket* oldSocket = this->peers[serverUserId].socket;
860
861  // now integrate the new socket
862  this->peers[serverUserId].socket = newSocket;
863
864  this->bSoftRedirect = false;
865  return;
866
867  // now remove the old socket
868  oldSocket->disconnectServer();
869  delete oldSocket;
870
871  // replace the old connection monitor
872  if ( this->peers[serverUserId].connectionMonitor )
873    delete this->peers[serverUserId].connectionMonitor;
874  this->peers[serverUserId].connectionMonitor = new ConnectionMonitor(serverUserId);
875
876  // remove old node from the network monitor
877  this->networkMonitor->removeNode(&this->peers[serverUserId]);
878
879}
880
881
882
883/**
884 * prepares a soft connection for a client to connect to
885 * @param userId that will connect to this server
886 */
887void NetworkStream::prepareSoftConnection(int userId)
888{
889  PRINTF(0)("prepare soft connection for userId %i\n");
890}
891
892
893
894/**
895 * handles the disconnect event
896 * @param userId id of the user to remove
897 */
898void NetworkStream::handleDisconnect( int userId )
899{
900  this->peers[userId].socket->disconnectServer();
901  delete this->peers[userId].socket;
902  this->peers[userId].socket = NULL;
903
904  if ( this->peers[userId].handshake )
905    delete this->peers[userId].handshake;
906  this->peers[userId].handshake = NULL;
907
908  if ( this->peers[userId].connectionMonitor )
909    delete this->peers[userId].connectionMonitor;
910  this->peers[userId].connectionMonitor = NULL;
911
912  // delete the synchronization state of this client for all syncs
913  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
914    (*it2)->cleanUpUser( userId );
915  }
916
917  if( SharedNetworkData::getInstance()->isMasterServer())
918    NetworkGameManager::getInstance()->signalLeftPlayer(userId);
919
920  this->freeSocketSlots.push_back( userId );
921
922  this->networkMonitor->removeNode(&this->peers[userId]);
923  this->peers.erase( userId);
924}
925
926
927/**
928 * handle upstream network traffic
929 * @param tick: seconds elapsed since last update
930 */
931void NetworkStream::handleUpstream( int tick )
932{
933  int offset;
934  int n;
935
936  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
937  {
938    offset = INTSIZE; // reserve enough space for the packet length
939
940    // continue with the next peer if this peer has no socket assigned (therefore no network)
941    if ( !peer->second.socket )
942      continue;
943
944    // header informations: current state
945    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
946    assert( n == INTSIZE );
947    offset += n;
948
949    // header informations: last acked state
950    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
951    assert( n == INTSIZE );
952    offset += n;
953
954    // header informations: last recved state
955    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
956    assert( n == INTSIZE );
957    offset += n;
958
959    // now write all synchronizeables in the packet
960    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
961    {
962
963      int oldOffset = offset;
964      Synchronizeable & sync = **it;
965
966
967      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
968      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
969        continue;
970
971      // if handshake not finished only sync handshake
972      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
973        continue;
974
975      // if we are a server (both master and proxy servers) and this is not our handshake
976      if ( ( SharedNetworkData::getInstance()->isMasterServer() ||
977             SharedNetworkData::getInstance()->isProxyServerActive() &&  peer->second.isClient())
978             && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
979        continue;
980
981      /* list of synchronizeables that will never be synchronized over the network: */
982      // do not sync null parent
983      if ( sync.getLeafClassID() == CL_NULL_PARENT )
984        continue;
985
986
987      assert( sync.getLeafClassID() != 0);
988
989      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
990
991      // server fakes uniqueid == 0 for handshake synchronizeable
992      if ( ( SharedNetworkData::getInstance()->isMasterServer() ||
993             SharedNetworkData::getInstance()->isProxyServerActive() &&  peer->second.isClient() ) &&
994             ( sync.getUniqueID() >= 1000 || sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1 + NET_ID_PROXY_MAX))
995        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
996      else
997        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
998
999
1000      assert( n == INTSIZE );
1001      offset += n;
1002
1003      // make space for packet size
1004      offset += INTSIZE;
1005
1006      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
1007      offset += n;
1008
1009      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
1010
1011      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
1012      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
1013      bool allZero = true;
1014      for ( int i = 0; i < n; i++ )
1015      {
1016         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
1017           allZero = false;
1018      }
1019      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
1020      // data that hast not changed
1021      if ( allZero )
1022      {
1023        offset = oldOffset;
1024      }
1025    } // all synchronizeables written
1026
1027
1028
1029    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
1030    {
1031      Synchronizeable & sync = **it;
1032
1033      // again exclude all unwanted syncs
1034      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED)
1035        continue;
1036
1037      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
1038    }
1039
1040
1041    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
1042
1043    // now compress the data with the zip library
1044    int compLength = 0;
1045    if ( SharedNetworkData::getInstance()->isMasterServer() ||
1046         SharedNetworkData::getInstance()->isProxyServerActive())
1047      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
1048    else
1049      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
1050
1051    if ( compLength <= 0 )
1052    {
1053      PRINTF(1)("compression failed!\n");
1054      continue;
1055    }
1056
1057    assert( peer->second.socket->writePacket( compBuf, compLength ) );
1058
1059    if ( this->remainingBytesToWriteToDict > 0 )
1060      writeToNewDict( buf, offset, true );
1061
1062    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
1063    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
1064
1065  }
1066}
1067
1068/**
1069 * handle downstream network traffic
1070 */
1071void NetworkStream::handleDownstream( int tick )
1072{
1073  int offset = 0;
1074
1075  int length = 0;
1076  int packetLength = 0;
1077  int compLength = 0;
1078  int uniqueId = 0;
1079  int state = 0;
1080  int ackedState = 0;
1081  int fromState = 0;
1082  int syncDataLength = 0;
1083
1084  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
1085  {
1086
1087    if ( !peer->second.socket )
1088      continue;
1089
1090    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
1091    {
1092      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
1093
1094      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
1095
1096      if ( packetLength < 4*INTSIZE )
1097      {
1098        if ( packetLength != 0 )
1099          PRINTF(1)("got too small packet: %d\n", packetLength);
1100        continue;
1101      }
1102
1103      if ( this->remainingBytesToWriteToDict > 0 )
1104        writeToNewDict( buf, packetLength, false );
1105
1106      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
1107      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
1108      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
1109      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
1110      offset = 4*INTSIZE;
1111
1112      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
1113
1114
1115      //if this is an old state drop it
1116      if ( state <= peer->second.lastRecvedState )
1117        continue;
1118
1119      if ( packetLength != length )
1120      {
1121        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
1122        peer->second.socket->disconnectServer();
1123        continue;
1124      }
1125
1126      while ( offset + 2 * INTSIZE < length )
1127      {
1128        // read the unique id of the sync
1129        assert( offset > 0 );
1130        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
1131        offset += INTSIZE;
1132
1133        // read the data length
1134        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
1135        offset += INTSIZE;
1136
1137        assert( syncDataLength > 0 );
1138        assert( syncDataLength < 10000 );
1139
1140        Synchronizeable * sync = NULL;
1141
1142        // look for the synchronizeable in question
1143        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
1144        {
1145          // client thinks his handshake has a special id: hostId * 1000 (host id of this server)
1146          if ( (*it)->getUniqueID() == uniqueId ||                                          // so this client exists already go to sync work
1147                 ( uniqueId == 0  && (*it)->getUniqueID() == peer->second.userId ) )        // so this is a Handshake!
1148          {
1149            sync = *it;
1150            break;
1151          }
1152        }
1153
1154        // this synchronizeable does not yet exist! create it
1155        if ( sync == NULL )
1156        {
1157          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
1158
1159          // if it is an old synchronizeable already removed, ignore it
1160          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
1161          {
1162            offset += syncDataLength;
1163            continue;
1164          }
1165
1166          // if the node we got this unknown sync we ignore it if:
1167          //  - the remote host is a client
1168          //  - the remote host is a proxy server and we are master server
1169          // (since it has no rights to create a new sync)
1170          if ( peers[peer->second.userId].isClient() ||
1171               (peers[peer->second.userId].isProxyServerActive() && SharedNetworkData::getInstance()->isMasterServer()))
1172          {
1173            offset += syncDataLength;
1174            continue;
1175          }
1176
1177          int leafClassId;
1178          if ( INTSIZE > length - offset )
1179          {
1180            offset += syncDataLength;
1181            continue;
1182          }
1183
1184          Converter::byteArrayToInt( buf + offset, &leafClassId );
1185
1186          assert( leafClassId != 0 );
1187
1188
1189          BaseObject * b = NULL;
1190          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
1191          /* Exception 1: NullParent */
1192          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
1193          {
1194            PRINTF(1)("Don't create Object with ID %x, ignored!\n", (int)leafClassId);
1195            offset += syncDataLength;
1196            continue;
1197          }
1198          else
1199            b = Factory::fabricate( (ClassID)leafClassId );
1200
1201          if ( !b )
1202          {
1203            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
1204            offset += syncDataLength;
1205            continue;
1206          }
1207
1208          if ( b->isA(CL_SYNCHRONIZEABLE) )
1209          {
1210            sync = dynamic_cast<Synchronizeable*>(b);
1211            sync->setUniqueID( uniqueId );
1212            sync->setSynchronized(true);
1213
1214            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
1215          }
1216          else
1217          {
1218            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
1219            delete b;
1220            offset += syncDataLength;
1221            continue;
1222          }
1223        }
1224
1225
1226        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
1227        offset += n;
1228
1229      }
1230
1231      if ( offset != length )
1232      {
1233        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
1234        peer->second.socket->disconnectServer();
1235      }
1236
1237
1238      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
1239      {
1240        Synchronizeable & sync = **it;
1241
1242        if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
1243          continue;
1244
1245        sync.handleRecvState( peer->second.userId, state, fromState );
1246      }
1247
1248      assert( peer->second.lastAckedState <= ackedState );
1249      peer->second.lastAckedState = ackedState;
1250
1251      assert( peer->second.lastRecvedState < state );
1252      peer->second.lastRecvedState = state;
1253
1254    }
1255
1256  }
1257
1258}
1259
1260/**
1261 * is executed when a handshake has finished
1262 */
1263void NetworkStream::handleNewClient( int userId )
1264{
1265  // init and assign the message manager
1266  MessageManager::getInstance()->initUser( userId );
1267  // do all game relevant stuff here
1268  networkGameManager->signalNewPlayer( userId );
1269}
1270
1271
1272/**
1273 * removes old items from oldSynchronizeables
1274 */
1275void NetworkStream::cleanUpOldSyncList( )
1276{
1277  int now = SDL_GetTicks();
1278
1279  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
1280  {
1281    if ( it->second < now - 10*1000 )
1282    {
1283      std::map<int,int>::iterator delIt = it;
1284      it++;
1285      oldSynchronizeables.erase( delIt );
1286      continue;
1287    }
1288    it++;
1289  }
1290}
1291
1292/**
1293 * writes data to DATA/dicts/newdict
1294 * @param data pointer to data
1295 * @param length length
1296 */
1297void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
1298{
1299  if ( remainingBytesToWriteToDict <= 0 )
1300    return;
1301
1302  if ( length > remainingBytesToWriteToDict )
1303    length = remainingBytesToWriteToDict;
1304
1305  std::string fileName = ResourceManager::getInstance()->getDataDir();
1306  fileName += "/dicts/newdict";
1307
1308  if ( upstream )
1309    fileName += "_upstream";
1310  else
1311    fileName += "_downstream";
1312
1313  FILE * f = fopen( fileName.c_str(), "a" );
1314
1315  if ( !f )
1316  {
1317    PRINTF(2)("could not open %s\n", fileName.c_str());
1318    remainingBytesToWriteToDict = 0;
1319    return;
1320  }
1321
1322  if ( fwrite( data, 1, length, f ) != length )
1323  {
1324    PRINTF(2)("could not write to file\n");
1325    fclose( f );
1326    return;
1327  }
1328
1329  fclose( f );
1330
1331  remainingBytesToWriteToDict -= length;
1332}
1333
1334
1335
1336
1337
1338
Note: See TracBrowser for help on using the repository browser.