Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/branches/network/src/lib/network/network_stream.cc @ 9909

Last change on this file since 9909 was 9909, checked in by rennerc, 18 years ago

ClassID synchronization might work. at least it still works with it :D

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