Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

framework integration

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