Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

Last change on this file since 9473 was 9473, checked in by patrick, 19 years ago

letting proxys handshakes handling again

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