Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

yea finaly the redirection algorithm realy works (testedsvn diff)

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