Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

client ip bug

File size: 27.7 KB
Line 
1/*
2   orxonox - the future of 3D-vertical-scrollers
3
4   Copyright (C) 2004 orx
5
6   This program is free software; you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation; either version 2, or (at your option)
9   any later version.
10
11### File Specific:
12   main-programmer: Christoph Renner rennerc@ee.ethz.ch
13   co-programmer:   Patrick Boenzli  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 "network_game_manager.h"
31#include "shared_network_data.h"
32#include "message_manager.h"
33#include "preferences.h"
34#include "zip.h"
35
36#include "src/lib/util/loading/resource_manager.h"
37
38#include "network_log.h"
39
40#include "player_stats.h"
41
42#include "lib/util/loading/factory.h"
43
44#include "debug.h"
45#include "class_list.h"
46#include <algorithm>
47
48
49#include "network_stream.h"
50
51
52using namespace std;
53
54
55#define PACKAGE_SIZE  256
56
57
58/**
59 * empty constructor
60 */
61NetworkStream::NetworkStream()
62    : DataStream()
63{
64  this->init();
65  /* initialize the references */
66  this->pInfo->nodeType = NET_CLIENT;
67}
68
69
70/**
71 * start as a client, connect to a server
72 *  @param host: host name (address)
73 *  @param port: port number
74 */
75NetworkStream::NetworkStream( std::string host, int port )
76{
77  this->init();
78  // init the peers[0] the server to ceonnect to
79  this->peers[0].socket = new UdpSocket( host, port );
80  this->peers[0].userId = 0;
81  this->peers[0].nodeType = NET_MASTER_SERVER;
82  this->peers[0].connectionMonitor = new ConnectionMonitor( 0 );
83  this->peers[0].ip = this->peers[0].socket->getRemoteAddress();
84  // and set also the localhost
85  this->pInfo->nodeType = NET_CLIENT;
86  // get the local ip address
87  SDLNet_ResolveHost( &this->pInfo->ip, NULL, port );
88}
89
90
91/**
92 * start as a server
93 *  @param port: at this port
94 */
95NetworkStream::NetworkStream( int port )
96{
97  this->init();
98  this->serverSocket = new UdpServerSocket(port);
99  this->pInfo->nodeType = NET_MASTER_SERVER;
100  // get the local ip address
101  SDLNet_ResolveHost( &this->pInfo->ip, NULL, port );
102}
103
104
105/**
106 * generic init functions
107 */
108void NetworkStream::init()
109{
110  /* set the class id for the base object */
111  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
112  this->serverSocket = NULL;
113  this->networkGameManager = NULL;
114  this->networkMonitor = NULL;
115
116  this->pInfo = new PeerInfo();
117  this->pInfo->userId = 0;
118  this->pInfo->lastAckedState = 0;
119  this->pInfo->lastRecvedState = 0;
120
121
122  this->currentState = 0;
123
124  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
125
126  assert( Zip::getInstance()->loadDictionary( "testdict" ) >= 0 );
127  this->dictClient = Zip::getInstance()->loadDictionary( "dict2pl_client" );
128  assert( this->dictClient >= 0 );
129  this->dictServer = Zip::getInstance()->loadDictionary( "dict2p_server" );
130  assert( this->dictServer >= 0 );
131}
132
133
134/**
135 * deconstructor
136 */
137NetworkStream::~NetworkStream()
138{
139  if ( this->serverSocket )
140  {
141    serverSocket->close();
142    delete serverSocket;
143    serverSocket = NULL;
144  }
145  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
146  {
147    if ( i->second.socket )
148    {
149      i->second.socket->disconnectServer();
150      delete i->second.socket;
151      i->second.socket = NULL;
152    }
153
154    if ( i->second.handshake )
155    {
156      delete i->second.handshake;
157      i->second.handshake = NULL;
158    }
159
160    if ( i->second.connectionMonitor )
161    {
162      delete i->second.connectionMonitor;
163      i->second.connectionMonitor = NULL;
164    }
165  }
166  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
167    (*it)->setNetworkStream( NULL );
168
169  if( this->pInfo)
170    delete this->pInfo;
171
172  if( this->networkMonitor)
173    delete this->networkMonitor;
174}
175
176
177/**
178 * creates a new instance of the network game manager
179 */
180void NetworkStream::createNetworkGameManager()
181{
182  this->networkGameManager = NetworkGameManager::getInstance();
183  // setUniqueID( maxCon+2 ) because we need one id for every handshake
184  // and one for handshake to reject client maxCon+1
185  this->networkGameManager->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
186  MessageManager::getInstance()->setUniqueID( SharedNetworkData::getInstance()->getNewUniqueID() );
187}
188
189
190/**
191 * starts the network handshake
192 * handsakes are always initialized from the client side first. this starts the handshake and therefore is only
193 * executed as client
194 */
195void NetworkStream::startHandshake()
196{
197  Handshake* hs = new Handshake(this->pInfo->nodeType);
198  hs->setUniqueID( 0 );
199  assert( peers[0].handshake == NULL );
200  peers[0].handshake = hs;
201
202  // set the preferred nick name
203  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
204
205  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getName());
206}
207
208
209/**
210 * this functions connects a synchronizeable to the networkstream, therefore synchronizeing
211 * it all over the network and creating it on the other platforms (if and only if it is a
212 * server
213 */
214void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
215{
216  this->synchronizeables.push_back(&sync);
217  sync.setNetworkStream( this );
218
219//   this->bActive = true;
220}
221
222
223/**
224 * removes the synchronizeable from the list of synchronized entities
225 */
226void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
227{
228  // removing the Synchronizeable from the List.
229  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
230  if (disconnectSynchro != this->synchronizeables.end())
231    this->synchronizeables.erase(disconnectSynchro);
232
233  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
234}
235
236
237/**
238 * this is called to process data from the network socket to the synchronizeable and vice versa
239 */
240void NetworkStream::processData()
241{
242  // create the network monitor after all the init work and before there is any connection handlings
243  if( this->networkMonitor == NULL)
244    this->networkMonitor = new NetworkMonitor(this);
245
246
247  int tick = SDL_GetTicks();
248
249  this->currentState++;
250  // there was a wrap around
251  if( this->currentState < 0)
252  {
253    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");
254  }
255
256  if ( this->pInfo->nodeType == NET_MASTER_SERVER )
257  {
258    // execute everytthing the master server shoudl do
259    if ( serverSocket )
260      serverSocket->update();
261
262    this->updateConnectionList();
263  }
264  else if( this->pInfo->nodeType == NET_PROXY_SERVER_ACTIVE)
265  {
266    // execute everything the proxy server should do
267  }
268  else
269  {
270    // check if the connection is ok else terminate and remove
271    if ( peers[0].socket && ( !peers[0].socket->isOk() || peers[0].connectionMonitor->hasTimedOut() ) )
272    {
273      PRINTF(1)("lost connection to server\n");
274
275      peers[0].socket->disconnectServer();
276      delete peers[0].socket;
277      peers[0].socket = NULL;
278
279      if ( peers[0].handshake )
280        delete peers[0].handshake;
281      peers[0].handshake = NULL;
282
283      if ( peers[0].connectionMonitor )
284        delete peers[0].connectionMonitor;
285      peers[0].connectionMonitor = NULL;
286    }
287  }
288
289  cleanUpOldSyncList();
290  handleHandshakes();
291
292  // update the network monitor
293  this->networkMonitor->process();
294
295  // order of up/downstream is important!!!!
296  // don't change it
297  handleDownstream( tick );
298  handleUpstream( tick );
299}
300
301
302/**
303 * if we are a NET_MASTER_SERVER or NET_PROXY_SERVER_ACTIVE update the connection list to accept new
304 * connections (clients) also start the handsake for the new clients
305 */
306void NetworkStream::updateConnectionList( )
307{
308  //check for new connections
309
310  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
311
312  // we got new network node
313  if ( tempNetworkSocket )
314  {
315    int clientId;
316    // if there is a list of free client id slots, take these
317    if ( freeSocketSlots.size() > 0 )
318    {
319      clientId = freeSocketSlots.back();
320      freeSocketSlots.pop_back();
321      peers[clientId].socket = tempNetworkSocket;
322      peers[clientId].handshake = new Handshake(this->pInfo->nodeType, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID() );
323      peers[clientId].handshake->setUniqueID(clientId);
324
325      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
326      peers[clientId].userId = clientId;
327    }
328    else
329    {
330      clientId = 1;
331
332      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
333        if ( it->first >= clientId )
334          clientId = it->first + 1;
335
336      peers[clientId].socket = tempNetworkSocket;
337      // handshake handling
338      peers[clientId].handshake = new Handshake(this->pInfo->nodeType, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
339      peers[clientId].handshake->setUniqueID(clientId);
340
341      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
342      peers[clientId].userId = clientId;
343
344      PRINTF(0)("num sync: %d\n", synchronizeables.size());
345    }
346
347
348    // get the proxy server informations and write them to the handshake, if any (proxy)
349    PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
350    if( pi != NULL)
351      peers[clientId].handshake->setProxy1Address( pi->ip);
352
353    pi = this->networkMonitor->getSecondChoiceProxy();
354    if( pi != NULL)
355      peers[clientId].handshake->setProxy2Address( pi->ip);
356
357    // check if the connecting client should reconnect to a proxy server
358    peers[clientId].handshake->setRedirect(this->networkMonitor->reconnectNextClient());
359
360
361    peers[clientId].nodeType = NET_CLIENT;
362    peers[clientId].ip = peers[clientId].socket->getRemoteAddress();
363
364
365    // check if there are too many clients connected (DEPRECATED: new: the masterserver sends a list of proxy servers)
366    if ( clientId > NET_MAX_CONNECTIONS )
367    {
368//       peers[clientId].handshake->setRedirect(true);
369//
370//       peers[clientId].handshake->doReject( "too many connections" );
371      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
372    }
373    else
374    {
375      PRINTF(0)("New Client: %d\n", clientId);
376    }
377
378    //this->connectSynchronizeable(*handshakes[clientId]);
379  }
380
381
382
383  //check if connections are ok else remove them
384  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
385  {
386    if (
387          it->second.socket &&
388          (
389            !it->second.socket->isOk()  ||
390            it->second.connectionMonitor->hasTimedOut()
391          )
392       )
393    {
394      std::string reason = "disconnected";
395      if ( it->second.connectionMonitor->hasTimedOut() )
396        reason = "timeout";
397      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
398
399
400      // clean up the network data
401      it->second.socket->disconnectServer();
402      delete it->second.socket;
403      it->second.socket = NULL;
404
405      if ( it->second.connectionMonitor )
406        delete it->second.connectionMonitor;
407      it->second.connectionMonitor = NULL;
408
409      if ( it->second.handshake )
410        delete it->second.handshake;
411      it->second.handshake = NULL;
412
413      for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )
414      {
415        (*it2)->cleanUpUser( it->second.userId );
416      }
417
418      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
419
420      freeSocketSlots.push_back( it->second.userId );
421
422      PeerList::iterator delit = it;
423      it++;
424
425      peers.erase( delit );
426
427      continue;
428    }
429
430    it++;
431  }
432
433
434}
435
436
437void NetworkStream::debug()
438{
439  if( this->isMasterServer())
440    PRINT(0)(" Host ist Server with ID: %i\n", this->pInfo->userId);
441  else
442    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
443
444  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
445  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
446  {
447    if( (*it)->beSynchronized() == true)
448      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
449               (*it)->getUniqueID(), (*it)->beSynchronized());
450  }
451  PRINT(0)(" Maximal Connections: %i\n", NET_MAX_CONNECTIONS );
452
453}
454
455
456/**
457 * @returns the number of synchronizeables registered to this stream
458 */
459int NetworkStream::getSyncCount()
460{
461  int n = 0;
462  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
463    if( (*it)->beSynchronized() == true)
464      ++n;
465
466  //return synchronizeables.size();
467  return n;
468}
469
470
471/**
472 * check if handshakes completed. if so create the network game manager else remove it again
473 */
474void NetworkStream::handleHandshakes( )
475{
476  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
477  {
478    if ( it->second.handshake )
479    {
480      // handshake finished
481      if ( it->second.handshake->completed() )
482      {
483        //handshake is correct
484        if ( it->second.handshake->ok() )
485        {
486          if ( !it->second.handshake->allowDel() )
487          {
488            if ( this->pInfo->nodeType == NET_CLIENT )
489            {
490              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
491              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
492
493              it->second.nodeType = it->second.handshake->getRemoteNodeType();
494              it->second.ip = it->second.socket->getRemoteAddress();
495              this->networkMonitor->addNode(&it->second);
496
497              // get proxy 1 address and add it
498              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
499              // get proxy 2 address and add it
500              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
501
502
503              // now check if there server accepted the connection
504              if( it->second.handshake->redirect())
505              {
506                // handle the redirection
507                PRINTF(0)("===============================================\n");
508                PRINTF(0)("Client is redirected to the other proxy servers\n");
509                PRINTF(0)("===============================================\n");
510
511                // disconnect from the current server and reconnect to proxy server
512//                 it->second.socket->disconnectServer();
513              }
514
515              // create the new network game manager and init it
516              this->networkGameManager = NetworkGameManager::getInstance();
517              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
518              // init the new message manager
519              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
520            }
521
522
523            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
524
525            it->second.handshake->del();
526          }
527          else
528          {
529            // handshake finished registring new player
530            if ( it->second.handshake->canDel() )
531            {
532              if ( this->pInfo->nodeType == NET_MASTER_SERVER )
533              {
534                it->second.nodeType = it->second.handshake->getRemoteNodeType();
535                it->second.ip = it->second.socket->getRemoteAddress();
536
537                this->networkMonitor->addNode(&it->second);
538
539                handleNewClient( it->second.userId );
540
541                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
542                {
543                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
544                }
545              }
546
547              PRINT(0)("handshake finished delete it\n");
548              delete it->second.handshake;
549              it->second.handshake = NULL;
550            }
551          }
552
553        }
554        else
555        {
556          PRINT(1)("handshake failed!\n");
557          it->second.socket->disconnectServer();
558        }
559      }
560    }
561  }
562}
563
564
565/**
566 * handle upstream network traffic
567 */
568void NetworkStream::handleUpstream( int tick )
569{
570  int offset;
571  int n;
572
573  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
574  {
575    offset = INTSIZE; // reserve enough space for the packet length
576
577    // continue with the next peer if this peer has no socket assigned (therefore no network)
578    if ( !peer->second.socket )
579      continue;
580
581    // header informations: current state
582    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
583    assert( n == INTSIZE );
584    offset += n;
585
586    // header informations: last acked state
587    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
588    assert( n == INTSIZE );
589    offset += n;
590
591    // header informations: last recved state
592    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
593    assert( n == INTSIZE );
594    offset += n;
595
596    // now write all synchronizeables in the packet
597    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
598    {
599      int oldOffset = offset;
600      Synchronizeable & sync = **it;
601
602      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
603      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
604        continue;
605
606      // if handshake not finished only sync handshake
607      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
608        continue;
609
610      // if we are a server and this is not our handshake
611      if ( isMasterServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
612        continue;
613
614      /* list of synchronizeables that will never be synchronized over the network: */
615      // do not sync null parent
616      if ( sync.getLeafClassID() == CL_NULL_PARENT )
617        continue;
618
619      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
620
621      // server fakes uniqueid == 0 for handshake
622      if ( this->isMasterServer() && sync.getUniqueID() < NET_MAX_CONNECTIONS - 1 )
623        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
624      else
625        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
626
627      assert( n == INTSIZE );
628      offset += n;
629
630      // make space for size
631      offset += INTSIZE;
632
633      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
634      offset += n;
635
636      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
637
638      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
639      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
640      bool allZero = true;
641      for ( int i = 0; i < n; i++ )
642      {
643         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
644           allZero = false;
645      }
646      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
647      // data that hast not changed
648      if ( allZero )
649      {
650        offset = oldOffset;
651      }
652    } // all synchronizeables written
653
654
655
656    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
657    {
658      Synchronizeable & sync = **it;
659
660      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
661        continue;
662
663      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
664    }
665
666
667    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
668
669    // now compress the data with the zip library
670    int compLength = 0;
671    if ( this->isMasterServer() )
672      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
673    else
674      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
675
676    if ( compLength <= 0 )
677    {
678      PRINTF(1)("compression failed!\n");
679      continue;
680    }
681
682    assert( peer->second.socket->writePacket( compBuf, compLength ) );
683
684    if ( this->remainingBytesToWriteToDict > 0 )
685      writeToNewDict( buf, offset, true );
686
687    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
688    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
689
690  }
691}
692
693/**
694 * handle downstream network traffic
695 */
696void NetworkStream::handleDownstream( int tick )
697{
698  int offset = 0;
699
700  int length = 0;
701  int packetLength = 0;
702  int compLength = 0;
703  int uniqueId = 0;
704  int state = 0;
705  int ackedState = 0;
706  int fromState = 0;
707  int syncDataLength = 0;
708
709  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
710  {
711
712    if ( !peer->second.socket )
713      continue;
714
715    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
716    {
717      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
718
719      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
720
721      if ( packetLength < 4*INTSIZE )
722      {
723        if ( packetLength != 0 )
724          PRINTF(1)("got too small packet: %d\n", packetLength);
725        continue;
726      }
727
728      if ( this->remainingBytesToWriteToDict > 0 )
729        writeToNewDict( buf, packetLength, false );
730
731      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
732      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
733      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
734      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
735      offset = 4*INTSIZE;
736
737      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
738
739
740      //if this is an old state drop it
741      if ( state <= peer->second.lastRecvedState )
742        continue;
743
744      if ( packetLength != length )
745      {
746        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
747        peer->second.socket->disconnectServer();
748        continue;
749      }
750
751      while ( offset + 2*INTSIZE < length )
752      {
753        assert( offset > 0 );
754        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
755        offset += INTSIZE;
756
757        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
758        offset += INTSIZE;
759
760        assert( syncDataLength > 0 );
761        assert( syncDataLength < 10000 );
762
763        Synchronizeable * sync = NULL;
764
765        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
766        {
767        //                                        client thinks his handshake has id 0!!!!!
768          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
769          {
770            sync = *it;
771            break;
772          }
773        }
774
775        if ( sync == NULL )
776        {
777          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
778          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
779          {
780            offset += syncDataLength;
781            continue;
782          }
783
784          if ( !peers[peer->second.userId].isMasterServer() )
785          {
786            offset += syncDataLength;
787            continue;
788          }
789
790          int leafClassId;
791          if ( INTSIZE > length - offset )
792          {
793            offset += syncDataLength;
794            continue;
795          }
796
797          Converter::byteArrayToInt( buf + offset, &leafClassId );
798
799          assert( leafClassId != 0 );
800
801          BaseObject * b = NULL;
802          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
803          /* Exception 1: NullParent */
804          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
805          {
806            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
807            offset += syncDataLength;
808            continue;
809          }
810          else
811            b = Factory::fabricate( (ClassID)leafClassId );
812
813          if ( !b )
814          {
815            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
816            offset += syncDataLength;
817            continue;
818          }
819
820          if ( b->isA(CL_SYNCHRONIZEABLE) )
821          {
822            sync = dynamic_cast<Synchronizeable*>(b);
823            sync->setUniqueID( uniqueId );
824            sync->setSynchronized(true);
825
826            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
827          }
828          else
829          {
830            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
831            delete b;
832            offset += syncDataLength;
833            continue;
834          }
835        }
836
837
838        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
839        offset += n;
840        //NETPRINTF(0)("SSSSSEEEEETTTTT: %s %d\n",sync->getClassName(), n);
841
842      }
843
844      if ( offset != length )
845      {
846        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
847        peer->second.socket->disconnectServer();
848      }
849
850
851      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
852      {
853        Synchronizeable & sync = **it;
854
855        if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
856          continue;
857
858        sync.handleRecvState( peer->second.userId, state, fromState );
859      }
860
861      assert( peer->second.lastAckedState <= ackedState );
862      peer->second.lastAckedState = ackedState;
863
864      assert( peer->second.lastRecvedState < state );
865      peer->second.lastRecvedState = state;
866
867    }
868
869  }
870
871}
872
873/**
874 * is executed when a handshake has finished
875 */
876void NetworkStream::handleNewClient( int userId )
877{
878  // init and assign the message manager
879  MessageManager::getInstance()->initUser( userId );
880  // do all game relevant stuff here
881  networkGameManager->signalNewPlayer( userId );
882
883  // register the new client at the network monitor
884//   this->networkMonitor->addClient();
885}
886
887
888/**
889 * removes old items from oldSynchronizeables
890 */
891void NetworkStream::cleanUpOldSyncList( )
892{
893  int now = SDL_GetTicks();
894
895  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
896  {
897    if ( it->second < now - 10*1000 )
898    {
899      std::map<int,int>::iterator delIt = it;
900      it++;
901      oldSynchronizeables.erase( delIt );
902      continue;
903    }
904    it++;
905  }
906}
907
908/**
909 * writes data to DATA/dicts/newdict
910 * @param data pointer to data
911 * @param length length
912 */
913void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
914{
915  if ( remainingBytesToWriteToDict <= 0 )
916    return;
917
918  if ( length > remainingBytesToWriteToDict )
919    length = remainingBytesToWriteToDict;
920
921  std::string fileName = ResourceManager::getInstance()->getDataDir();
922  fileName += "/dicts/newdict";
923
924  if ( upstream )
925    fileName += "_upstream";
926  else
927    fileName += "_downstream";
928
929  FILE * f = fopen( fileName.c_str(), "a" );
930
931  if ( !f )
932  {
933    PRINTF(2)("could not open %s\n", fileName.c_str());
934    remainingBytesToWriteToDict = 0;
935    return;
936  }
937
938  if ( fwrite( data, 1, length, f ) != length )
939  {
940    PRINTF(2)("could not write to file\n");
941    fclose( f );
942    return;
943  }
944
945  fclose( f );
946
947  remainingBytesToWriteToDict -= length;
948}
949
950
951
952
953
954
Note: See TracBrowser for help on using the repository browser.