Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 9605 was 9605, checked in by patrick, 18 years ago

MARK: there seems to be still a bug in the permissions system. trying to trace

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