Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

proxy server ip synchronizeing bug, nodes get registered

File size: 28.3 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      peers[clientId].ip = tempNetworkSocket->getRemoteAddress();
325
326      // get the proxy server informations and write them to the handshake, if any (proxy)
327      PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
328      if( pi != NULL)
329        peers[clientId].handshake->setProxy1Address( pi->ip);
330      pi = this->networkMonitor->getSecondChoiceProxy();
331      if( pi != NULL)
332        peers[clientId].handshake->setProxy2Address( pi->ip);
333
334       // check if the connecting client should reconnect to a proxy server
335      peers[clientId].handshake->setRedirect(this->networkMonitor->reconnectNextClient());
336
337      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
338      peers[clientId].userId = clientId;
339      peers[clientId].nodeType = NET_CLIENT;
340    }
341    else
342    {
343      clientId = 1;
344
345      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
346        if ( it->first >= clientId )
347          clientId = it->first + 1;
348
349      peers[clientId].socket = tempNetworkSocket;
350      // handshake handling
351      peers[clientId].handshake = new Handshake(this->pInfo->nodeType, clientId, this->networkGameManager->getUniqueID(), MessageManager::getInstance()->getUniqueID());
352      peers[clientId].handshake->setUniqueID(clientId);
353      // get the proxy server informations and write them to the handshake, if any (proxy)
354      PeerInfo* pi = this->networkMonitor->getFirstChoiceProxy();
355      if( pi != NULL)
356        peers[clientId].handshake->setProxy1Address( pi->ip);
357      pi = this->networkMonitor->getSecondChoiceProxy();
358      if( pi != NULL)
359        peers[clientId].handshake->setProxy2Address( pi->ip);
360
361       // check if the connecting client should reconnect to a proxy server
362      peers[clientId].handshake->setRedirect(this->networkMonitor->reconnectNextClient());
363
364      peers[clientId].connectionMonitor = new ConnectionMonitor( clientId );
365      peers[clientId].userId = clientId;
366      peers[clientId].nodeType = NET_CLIENT;
367
368      PRINTF(0)("num sync: %d\n", synchronizeables.size());
369    }
370
371    // check if there are too many clients connected (DEPRECATED: new: the masterserver sends a list of proxy servers)
372    if ( clientId > NET_MAX_CONNECTIONS )
373    {
374//       peers[clientId].handshake->setRedirect(true);
375//
376//       peers[clientId].handshake->doReject( "too many connections" );
377      PRINTF(0)("Will reject client %d because there are to many connections!\n", clientId);
378    }
379    else
380    {
381      PRINTF(0)("New Client: %d\n", clientId);
382    }
383
384    //this->connectSynchronizeable(*handshakes[clientId]);
385  }
386
387
388
389  //check if connections are ok else remove them
390  for ( PeerList::iterator it = peers.begin(); it != peers.end(); )
391  {
392    if (
393          it->second.socket &&
394          (
395            !it->second.socket->isOk()  ||
396            it->second.connectionMonitor->hasTimedOut()
397          )
398       )
399    {
400      std::string reason = "disconnected";
401      if ( it->second.connectionMonitor->hasTimedOut() )
402        reason = "timeout";
403      PRINTF(0)("Client is gone: %d (%s)\n", it->second.userId, reason.c_str());
404
405
406      // clean up the network data
407      it->second.socket->disconnectServer();
408      delete it->second.socket;
409      it->second.socket = NULL;
410
411      if ( it->second.connectionMonitor )
412        delete it->second.connectionMonitor;
413      it->second.connectionMonitor = NULL;
414
415      if ( it->second.handshake )
416        delete it->second.handshake;
417      it->second.handshake = NULL;
418
419      for ( SynchronizeableList::iterator it2 = synchronizeables.begin(); it2 != synchronizeables.end(); it2++ )
420      {
421        (*it2)->cleanUpUser( it->second.userId );
422      }
423
424      NetworkGameManager::getInstance()->signalLeftPlayer(it->second.userId);
425
426      freeSocketSlots.push_back( it->second.userId );
427
428      PeerList::iterator delit = it;
429      it++;
430
431      peers.erase( delit );
432
433      continue;
434    }
435
436    it++;
437  }
438
439
440}
441
442
443void NetworkStream::debug()
444{
445  if( this->isMasterServer())
446    PRINT(0)(" Host ist Server with ID: %i\n", this->pInfo->userId);
447  else
448    PRINT(0)(" Host ist Client with ID: %i\n", this->pInfo->userId);
449
450  PRINT(0)(" Got %i connected Synchronizeables, showing active Syncs:\n", this->synchronizeables.size());
451  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
452  {
453    if( (*it)->beSynchronized() == true)
454      PRINT(0)("  Synchronizeable of class: %s::%s, with unique ID: %i, Synchronize: %i\n", (*it)->getClassName(), (*it)->getName(),
455               (*it)->getUniqueID(), (*it)->beSynchronized());
456  }
457  PRINT(0)(" Maximal Connections: %i\n", NET_MAX_CONNECTIONS );
458
459}
460
461
462/**
463 * @returns the number of synchronizeables registered to this stream
464 */
465int NetworkStream::getSyncCount()
466{
467  int n = 0;
468  for (SynchronizeableList::iterator it = synchronizeables.begin(); it!=synchronizeables.end(); it++)
469    if( (*it)->beSynchronized() == true)
470      ++n;
471
472  //return synchronizeables.size();
473  return n;
474}
475
476
477/**
478 * check if handshakes completed. if so create the network game manager else remove it again
479 */
480void NetworkStream::handleHandshakes( )
481{
482  for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
483  {
484    if ( it->second.handshake )
485    {
486      // handshake finished
487      if ( it->second.handshake->completed() )
488      {
489        //handshake is correct
490        if ( it->second.handshake->ok() )
491        {
492          if ( !it->second.handshake->allowDel() )
493          {
494            if ( this->pInfo->nodeType == NET_CLIENT )
495            {
496              SharedNetworkData::getInstance()->setHostID( it->second.handshake->getHostId() );
497              this->pInfo->userId = SharedNetworkData::getInstance()->getHostID();
498
499              it->second.nodeType = it->second.handshake->getRemoteNodeType();
500              it->second.ip = it->second.socket->getRemoteAddress();
501              this->networkMonitor->addNode(&it->second);
502
503              // get proxy 1 address and add it
504              this->networkMonitor->addNode(it->second.handshake->getProxy1Address(), NET_PROXY_SERVER_ACTIVE);
505              // get proxy 2 address and add it
506              this->networkMonitor->addNode(it->second.handshake->getProxy2Address(), NET_PROXY_SERVER_ACTIVE);
507
508
509              // now check if there server accepted the connection
510              if( it->second.handshake->redirect())
511              {
512                // handle the redirection
513                PRINTF(0)("===============================================\n");
514                PRINTF(0)("Client is redirected to the other proxy servers\n");
515                PRINTF(0)("===============================================\n");
516
517                // disconnect from the current server and reconnect to proxy server
518//                 it->second.socket->disconnectServer();
519              }
520
521              // create the new network game manager and init it
522              this->networkGameManager = NetworkGameManager::getInstance();
523              this->networkGameManager->setUniqueID( it->second.handshake->getNetworkGameManagerId() );
524              // init the new message manager
525              MessageManager::getInstance()->setUniqueID( it->second.handshake->getMessageManagerId() );
526            }
527
528
529            PRINT(0)("handshake finished id=%d\n", it->second.handshake->getNetworkGameManagerId());
530
531            it->second.handshake->del();
532          }
533          else
534          {
535            // handshake finished registring new player
536            if ( it->second.handshake->canDel() )
537            {
538              if ( this->pInfo->nodeType == NET_MASTER_SERVER )
539              {
540                it->second.nodeType = it->second.handshake->getRemoteNodeType();
541                it->second.ip = it->second.socket->getRemoteAddress();
542
543                this->networkMonitor->addNode(&it->second);
544
545                handleNewClient( it->second.userId );
546
547                if ( PlayerStats::getStats( it->second.userId ) && it->second.handshake->getPreferedNickName() != "" )
548                {
549                  PlayerStats::getStats( it->second.userId )->setNickName( it->second.handshake->getPreferedNickName() );
550                }
551              }
552
553              PRINT(0)("handshake finished delete it\n");
554              delete it->second.handshake;
555              it->second.handshake = NULL;
556            }
557          }
558
559        }
560        else
561        {
562          PRINT(1)("handshake failed!\n");
563          it->second.socket->disconnectServer();
564        }
565      }
566    }
567  }
568}
569
570
571/**
572 * handle upstream network traffic
573 */
574void NetworkStream::handleUpstream( int tick )
575{
576  int offset;
577  int n;
578
579  for ( PeerList::reverse_iterator peer = peers.rbegin(); peer != peers.rend(); peer++ )
580  {
581    offset = INTSIZE; // reserve enough space for the packet length
582
583    // continue with the next peer if this peer has no socket assigned (therefore no network)
584    if ( !peer->second.socket )
585      continue;
586
587    // header informations: current state
588    n = Converter::intToByteArray( currentState, buf + offset, UDP_PACKET_SIZE - offset );
589    assert( n == INTSIZE );
590    offset += n;
591
592    // header informations: last acked state
593    n = Converter::intToByteArray( peer->second.lastAckedState, buf + offset, UDP_PACKET_SIZE - offset );
594    assert( n == INTSIZE );
595    offset += n;
596
597    // header informations: last recved state
598    n = Converter::intToByteArray( peer->second.lastRecvedState, buf + offset, UDP_PACKET_SIZE - offset );
599    assert( n == INTSIZE );
600    offset += n;
601
602    // now write all synchronizeables in the packet
603    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
604    {
605      int oldOffset = offset;
606      Synchronizeable & sync = **it;
607
608      // do not include synchronizeables with uninit id and syncs that don't want to be synchronized
609      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
610        continue;
611
612      // if handshake not finished only sync handshake
613      if ( peer->second.handshake && sync.getLeafClassID() != CL_HANDSHAKE )
614        continue;
615
616      // if we are a server and this is not our handshake
617      if ( isMasterServer() && sync.getLeafClassID() == CL_HANDSHAKE && sync.getUniqueID() != peer->second.userId )
618        continue;
619
620      /* list of synchronizeables that will never be synchronized over the network: */
621      // do not sync null parent
622      if ( sync.getLeafClassID() == CL_NULL_PARENT )
623        continue;
624
625      assert( offset + INTSIZE <= UDP_PACKET_SIZE );
626
627      // server fakes uniqueid == 0 for handshake
628      if ( this->isMasterServer() && sync.getUniqueID() < NET_MAX_CONNECTIONS - 1 )
629        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
630      else
631        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
632
633      assert( n == INTSIZE );
634      offset += n;
635
636      // make space for size
637      offset += INTSIZE;
638
639      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
640      offset += n;
641
642      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
643
644      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
645      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
646      bool allZero = true;
647      for ( int i = 0; i < n; i++ )
648      {
649         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
650           allZero = false;
651      }
652      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
653      // data that hast not changed
654      if ( allZero )
655      {
656        offset = oldOffset;
657      }
658    } // all synchronizeables written
659
660
661
662    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
663    {
664      Synchronizeable & sync = **it;
665
666      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
667        continue;
668
669      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
670    }
671
672
673    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
674
675    // now compress the data with the zip library
676    int compLength = 0;
677    if ( this->isMasterServer() )
678      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
679    else
680      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
681
682    if ( compLength <= 0 )
683    {
684      PRINTF(1)("compression failed!\n");
685      continue;
686    }
687
688    assert( peer->second.socket->writePacket( compBuf, compLength ) );
689
690    if ( this->remainingBytesToWriteToDict > 0 )
691      writeToNewDict( buf, offset, true );
692
693    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
694    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
695
696  }
697}
698
699/**
700 * handle downstream network traffic
701 */
702void NetworkStream::handleDownstream( int tick )
703{
704  int offset = 0;
705
706  int length = 0;
707  int packetLength = 0;
708  int compLength = 0;
709  int uniqueId = 0;
710  int state = 0;
711  int ackedState = 0;
712  int fromState = 0;
713  int syncDataLength = 0;
714
715  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
716  {
717
718    if ( !peer->second.socket )
719      continue;
720
721    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
722    {
723      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
724
725      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
726
727      if ( packetLength < 4*INTSIZE )
728      {
729        if ( packetLength != 0 )
730          PRINTF(1)("got too small packet: %d\n", packetLength);
731        continue;
732      }
733
734      if ( this->remainingBytesToWriteToDict > 0 )
735        writeToNewDict( buf, packetLength, false );
736
737      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
738      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
739      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
740      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
741      offset = 4*INTSIZE;
742
743      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
744
745
746      //if this is an old state drop it
747      if ( state <= peer->second.lastRecvedState )
748        continue;
749
750      if ( packetLength != length )
751      {
752        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
753        peer->second.socket->disconnectServer();
754        continue;
755      }
756
757      while ( offset + 2*INTSIZE < length )
758      {
759        assert( offset > 0 );
760        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
761        offset += INTSIZE;
762
763        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
764        offset += INTSIZE;
765
766        assert( syncDataLength > 0 );
767        assert( syncDataLength < 10000 );
768
769        Synchronizeable * sync = NULL;
770
771        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
772        {
773        //                                        client thinks his handshake has id 0!!!!!
774          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
775          {
776            sync = *it;
777            break;
778          }
779        }
780
781        if ( sync == NULL )
782        {
783          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
784          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
785          {
786            offset += syncDataLength;
787            continue;
788          }
789
790          if ( !peers[peer->second.userId].isMasterServer() )
791          {
792            offset += syncDataLength;
793            continue;
794          }
795
796          int leafClassId;
797          if ( INTSIZE > length - offset )
798          {
799            offset += syncDataLength;
800            continue;
801          }
802
803          Converter::byteArrayToInt( buf + offset, &leafClassId );
804
805          assert( leafClassId != 0 );
806
807          BaseObject * b = NULL;
808          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
809          /* Exception 1: NullParent */
810          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
811          {
812            PRINTF(1)("Can not create Class with ID %x!\n", (int)leafClassId);
813            offset += syncDataLength;
814            continue;
815          }
816          else
817            b = Factory::fabricate( (ClassID)leafClassId );
818
819          if ( !b )
820          {
821            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
822            offset += syncDataLength;
823            continue;
824          }
825
826          if ( b->isA(CL_SYNCHRONIZEABLE) )
827          {
828            sync = dynamic_cast<Synchronizeable*>(b);
829            sync->setUniqueID( uniqueId );
830            sync->setSynchronized(true);
831
832            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassName(), sync->getUniqueID());
833          }
834          else
835          {
836            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
837            delete b;
838            offset += syncDataLength;
839            continue;
840          }
841        }
842
843
844        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
845        offset += n;
846        //NETPRINTF(0)("SSSSSEEEEETTTTT: %s %d\n",sync->getClassName(), n);
847
848      }
849
850      if ( offset != length )
851      {
852        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
853        peer->second.socket->disconnectServer();
854      }
855
856
857      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
858      {
859        Synchronizeable & sync = **it;
860
861        if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
862          continue;
863
864        sync.handleRecvState( peer->second.userId, state, fromState );
865      }
866
867      assert( peer->second.lastAckedState <= ackedState );
868      peer->second.lastAckedState = ackedState;
869
870      assert( peer->second.lastRecvedState < state );
871      peer->second.lastRecvedState = state;
872
873    }
874
875  }
876
877}
878
879/**
880 * is executed when a handshake has finished
881 */
882void NetworkStream::handleNewClient( int userId )
883{
884  // init and assign the message manager
885  MessageManager::getInstance()->initUser( userId );
886  // do all game relevant stuff here
887  networkGameManager->signalNewPlayer( userId );
888
889  // register the new client at the network monitor
890//   this->networkMonitor->addClient();
891}
892
893
894/**
895 * removes old items from oldSynchronizeables
896 */
897void NetworkStream::cleanUpOldSyncList( )
898{
899  int now = SDL_GetTicks();
900
901  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
902  {
903    if ( it->second < now - 10*1000 )
904    {
905      std::map<int,int>::iterator delIt = it;
906      it++;
907      oldSynchronizeables.erase( delIt );
908      continue;
909    }
910    it++;
911  }
912}
913
914/**
915 * writes data to DATA/dicts/newdict
916 * @param data pointer to data
917 * @param length length
918 */
919void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
920{
921  if ( remainingBytesToWriteToDict <= 0 )
922    return;
923
924  if ( length > remainingBytesToWriteToDict )
925    length = remainingBytesToWriteToDict;
926
927  std::string fileName = ResourceManager::getInstance()->getDataDir();
928  fileName += "/dicts/newdict";
929
930  if ( upstream )
931    fileName += "_upstream";
932  else
933    fileName += "_downstream";
934
935  FILE * f = fopen( fileName.c_str(), "a" );
936
937  if ( !f )
938  {
939    PRINTF(2)("could not open %s\n", fileName.c_str());
940    remainingBytesToWriteToDict = 0;
941    return;
942  }
943
944  if ( fwrite( data, 1, length, f ) != length )
945  {
946    PRINTF(2)("could not write to file\n");
947    fclose( f );
948    return;
949  }
950
951  fclose( f );
952
953  remainingBytesToWriteToDict -= length;
954}
955
956
957
958
959
960
Note: See TracBrowser for help on using the repository browser.