Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

started implementation for soft connections

File size: 38.4 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 */
770void NetworkStream::handleReconnect(int userId)
771{
772  this->bRedirect = false;
773#warning this peer will be created if it does not yet exist: dangerous
774  PeerInfo* pInfo = &this->peers[userId];
775
776  IP proxyIP;
777  if( this->networkMonitor->isForcedReconnection())
778    proxyIP = this->networkMonitor->getForcedReconnectionIP();
779  else
780    proxyIP = pInfo->handshake->getProxy1Address();
781
782  PRINTF(0)("===============================================\n");
783  PRINTF(0)("Client is redirected to the other proxy servers\n");
784  PRINTF(0)("  user id: %i\n", userId);
785  PRINTF(0)("  connecting to: %s\n", proxyIP.ipString().c_str());
786  PRINTF(0)("===============================================\n");
787
788  // flush the old synchronization states, since the numbering could be completely different
789  pInfo->lastAckedState = 0;
790  pInfo->lastRecvedState = 0;
791
792  // disconnect from the current server and reconnect to proxy server
793  this->handleDisconnect( userId);
794//   this->connectToProxyServer(NET_ID_PROXY_SERVER_01, proxyIP.ipString(), 9999);
795  this->connectToMasterServer(proxyIP.ipString(), 9999);
796  #warning the ports are not yet integrated correctly in the ip class
797
798  // and restart the handshake
799  this->startHandshake( userId);
800}
801
802
803
804/**
805 * reconnects to another server, with full handshake
806 * @param address of the new server
807 */
808void NetworkStream::reconnectToServer(IP address)
809{
810  this->networkMonitor->setForcedReconnection(address);
811  this->handleReconnect( NET_ID_MASTER_SERVER);
812}
813
814
815
816/**
817 * softly reconnecting to another server
818 * @param address  of the new server
819 */
820void NetworkStream::softReconnectToServer(IP address)
821{
822  this->networkMonitor->setForcedReconnection(address);
823  this->handleReconnect( NET_ID_MASTER_SERVER);
824}
825
826
827/**
828 * handles the disconnect event
829 * @param userId id of the user to remove
830 */
831void NetworkStream::handleDisconnect( int userId )
832{
833  this->peers[userId].socket->disconnectServer();
834  delete this->peers[userId].socket;
835  this->peers[userId].socket = NULL;
836
837  if ( this->peers[userId].handshake )
838    delete this->peers[userId].handshake;
839  this->peers[userId].handshake = NULL;
840
841  if ( this->peers[userId].connectionMonitor )
842    delete this->peers[userId].connectionMonitor;
843  this->peers[userId].connectionMonitor = NULL;
844
845
846  for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )  {
847    (*it2)->cleanUpUser( userId );
848  }
849
850  if( SharedNetworkData::getInstance()->isMasterServer())
851    NetworkGameManager::getInstance()->signalLeftPlayer(userId);
852
853  this->freeSocketSlots.push_back( userId );
854
855  this->networkMonitor->removeNode(&this->peers[userId]);
856  this->peers.erase( userId);
857}
858
859
860
861/**
862 * handle upstream network traffic
863 * @param tick: seconds elapsed since last update
864 */
865void NetworkStream::handleUpstream( int tick )
866{
867  int offset;
868  int n;
869
870  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
871  {
872    offset = INTSIZE; // reserve enough space for the packet length
873
874    // continue with the next peer if this peer has no socket assigned (therefore no network)
875    if ( !peer->second.socket )
876      continue;
877
878    // header informations: current state
879    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
880    assert( n == INTSIZE );
881    offset += n;
882
883    // header informations: last acked state
884    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
885    assert( n == INTSIZE );
886    offset += n;
887
888    // header informations: last recved state
889    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
890    assert( n == INTSIZE );
891    offset += n;
892
893    // now write all synchronizeables in the packet
894    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
895    {
896
897      int oldOffset = offset;
898      Synchronizeable & sync = **it;
899
900
901      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
902      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
903        continue;
904
905      // if handshake not finished only sync handshake
906      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
907        continue;
908
909      // if we are a server (both master and proxy servers) and this is not our handshake
910      if ( ( SharedNetworkData::getInstance()->isMasterServer() ||
911             SharedNetworkData::getInstance()->isProxyServerActive() &&  peer->second.isClient())
912             && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
913        continue;
914
915      /* list of synchronizeables that will never be synchronized over the network: */
916      // do not sync null parent
917      if ( sync.getLeafClassID() == CL_NULL_PARENT )
918        continue;
919
920
921      assert( sync.getLeafClassID() != 0);
922
923      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
924
925      // server fakes uniqueid == 0 for handshake synchronizeable
926      if ( ( SharedNetworkData::getInstance()->isMasterServer() ||
927             SharedNetworkData::getInstance()->isProxyServerActive() &&  peer->second.isClient() ) &&
928             ( sync.getUniqueID() >= 1000 || sync.getUniqueID() <= SharedNetworkData::getInstance()->getMaxPlayer() + 1 + NET_ID_PROXY_MAX))
929        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
930      else
931        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
932
933
934      assert( n == INTSIZE );
935      offset += n;
936
937      // make space for packet size
938      offset += INTSIZE;
939
940      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
941      offset += n;
942
943      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
944
945      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
946      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
947      bool allZero = true;
948      for ( int i = 0; i < n; i++ )
949      {
950         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
951           allZero = false;
952      }
953      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
954      // data that hast not changed
955      if ( allZero )
956      {
957        offset = oldOffset;
958      }
959    } // all synchronizeables written
960
961
962
963    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
964    {
965      Synchronizeable & sync = **it;
966
967      // again exclude all unwanted syncs
968      if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED)
969        continue;
970
971      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
972    }
973
974
975    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
976
977    // now compress the data with the zip library
978    int compLength = 0;
979    if ( SharedNetworkData::getInstance()->isMasterServer() ||
980         SharedNetworkData::getInstance()->isProxyServerActive())
981      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
982    else
983      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
984
985    if ( compLength <= 0 )
986    {
987      PRINTF(1)("compression failed!\n");
988      continue;
989    }
990
991    assert( peer->second.socket->writePacket( compBuf, compLength ) );
992
993    if ( this->remainingBytesToWriteToDict > 0 )
994      writeToNewDict( buf, offset, true );
995
996    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
997    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
998
999  }
1000}
1001
1002/**
1003 * handle downstream network traffic
1004 */
1005void NetworkStream::handleDownstream( int tick )
1006{
1007  int offset = 0;
1008
1009  int length = 0;
1010  int packetLength = 0;
1011  int compLength = 0;
1012  int uniqueId = 0;
1013  int state = 0;
1014  int ackedState = 0;
1015  int fromState = 0;
1016  int syncDataLength = 0;
1017
1018  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
1019  {
1020
1021    if ( !peer->second.socket )
1022      continue;
1023
1024    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
1025    {
1026      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
1027
1028      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
1029
1030      if ( packetLength < 4*INTSIZE )
1031      {
1032        if ( packetLength != 0 )
1033          PRINTF(1)("got too small packet: %d\n", packetLength);
1034        continue;
1035      }
1036
1037      if ( this->remainingBytesToWriteToDict > 0 )
1038        writeToNewDict( buf, packetLength, false );
1039
1040      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
1041      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
1042      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
1043      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
1044      offset = 4*INTSIZE;
1045
1046      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
1047
1048
1049      //if this is an old state drop it
1050      if ( state <= peer->second.lastRecvedState )
1051        continue;
1052
1053      if ( packetLength != length )
1054      {
1055        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
1056        peer->second.socket->disconnectServer();
1057        continue;
1058      }
1059
1060      while ( offset + 2 * INTSIZE < length )
1061      {
1062        // read the unique id of the sync
1063        assert( offset > 0 );
1064        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
1065        offset += INTSIZE;
1066
1067        // read the data length
1068        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
1069        offset += INTSIZE;
1070
1071        assert( syncDataLength > 0 );
1072        assert( syncDataLength < 10000 );
1073
1074        Synchronizeable * sync = NULL;
1075
1076        // look for the synchronizeable in question
1077        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
1078        {
1079          // client thinks his handshake has a special id: hostId * 1000 (host id of this server)
1080          if ( (*it)->getUniqueID() == uniqueId ||                                          // so this client exists already go to sync work
1081                 ( uniqueId == 0  && (*it)->getUniqueID() == peer->second.userId ) )        // so this is a Handshake!
1082          {
1083            sync = *it;
1084            break;
1085          }
1086        }
1087
1088        // this synchronizeable does not yet exist! create it
1089        if ( sync == NULL )
1090        {
1091          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
1092
1093          // if it is an old synchronizeable already removed, ignore it
1094          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
1095          {
1096            offset += syncDataLength;
1097            continue;
1098          }
1099
1100          // if the node we got this unknown sync we ignore it if:
1101          //  - the remote host is a client
1102          //  - the remote host is a proxy server and we are master server
1103          // (since it has no rights to create a new sync)
1104          if ( peers[peer->second.userId].isClient() ||
1105               (peers[peer->second.userId].isProxyServerActive() && SharedNetworkData::getInstance()->isMasterServer()))
1106          {
1107            offset += syncDataLength;
1108            continue;
1109          }
1110
1111          int leafClassId;
1112          if ( INTSIZE > length - offset )
1113          {
1114            offset += syncDataLength;
1115            continue;
1116          }
1117
1118          Converter::byteArrayToInt( buf + offset, &leafClassId );
1119
1120          assert( leafClassId != 0 );
1121
1122
1123          BaseObject * b = NULL;
1124          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
1125          /* Exception 1: NullParent */
1126          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
1127          {
1128            PRINTF(1)("Don't create Object with ID %x, ignored!\n", (int)leafClassId);
1129            offset += syncDataLength;
1130            continue;
1131          }
1132          else
1133            b = Factory::fabricate( (ClassID)leafClassId );
1134
1135          if ( !b )
1136          {
1137            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
1138            offset += syncDataLength;
1139            continue;
1140          }
1141
1142          if ( b->isA(CL_SYNCHRONIZEABLE) )
1143          {
1144            sync = dynamic_cast<Synchronizeable*>(b);
1145            sync->setUniqueID( uniqueId );
1146            sync->setSynchronized(true);
1147
1148            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
1149          }
1150          else
1151          {
1152            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
1153            delete b;
1154            offset += syncDataLength;
1155            continue;
1156          }
1157        }
1158
1159
1160        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
1161        offset += n;
1162
1163      }
1164
1165      if ( offset != length )
1166      {
1167        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
1168        peer->second.socket->disconnectServer();
1169      }
1170
1171
1172      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
1173      {
1174        Synchronizeable & sync = **it;
1175
1176        if ( !sync.beSynchronized() || sync.getUniqueID() <= NET_UID_UNASSIGNED )
1177          continue;
1178
1179        sync.handleRecvState( peer->second.userId, state, fromState );
1180      }
1181
1182      assert( peer->second.lastAckedState <= ackedState );
1183      peer->second.lastAckedState = ackedState;
1184
1185      assert( peer->second.lastRecvedState < state );
1186      peer->second.lastRecvedState = state;
1187
1188    }
1189
1190  }
1191
1192}
1193
1194/**
1195 * is executed when a handshake has finished
1196 */
1197void NetworkStream::handleNewClient( int userId )
1198{
1199  // init and assign the message manager
1200  MessageManager::getInstance()->initUser( userId );
1201  // do all game relevant stuff here
1202  networkGameManager->signalNewPlayer( userId );
1203}
1204
1205
1206/**
1207 * removes old items from oldSynchronizeables
1208 */
1209void NetworkStream::cleanUpOldSyncList( )
1210{
1211  int now = SDL_GetTicks();
1212
1213  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
1214  {
1215    if ( it->second < now - 10*1000 )
1216    {
1217      std::map<int,int>::iterator delIt = it;
1218      it++;
1219      oldSynchronizeables.erase( delIt );
1220      continue;
1221    }
1222    it++;
1223  }
1224}
1225
1226/**
1227 * writes data to DATA/dicts/newdict
1228 * @param data pointer to data
1229 * @param length length
1230 */
1231void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
1232{
1233  if ( remainingBytesToWriteToDict <= 0 )
1234    return;
1235
1236  if ( length > remainingBytesToWriteToDict )
1237    length = remainingBytesToWriteToDict;
1238
1239  std::string fileName = ResourceManager::getInstance()->getDataDir();
1240  fileName += "/dicts/newdict";
1241
1242  if ( upstream )
1243    fileName += "_upstream";
1244  else
1245    fileName += "_downstream";
1246
1247  FILE * f = fopen( fileName.c_str(), "a" );
1248
1249  if ( !f )
1250  {
1251    PRINTF(2)("could not open %s\n", fileName.c_str());
1252    remainingBytesToWriteToDict = 0;
1253    return;
1254  }
1255
1256  if ( fwrite( data, 1, length, f ) != length )
1257  {
1258    PRINTF(2)("could not write to file\n");
1259    fclose( f );
1260    return;
1261  }
1262
1263  fclose( f );
1264
1265  remainingBytesToWriteToDict -= length;
1266}
1267
1268
1269
1270
1271
1272
Note: See TracBrowser for help on using the repository browser.