Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: orxonox.OLD/trunk/src/lib/network/network_stream.cc @ 9413

Last change on this file since 9413 was 9406, checked in by bensch, 18 years ago

orxonox/trunk: merged the proxy back

merged with commandsvn merge -r9346:HEAD https://svn.orxonox.net/orxonox/branches/proxy .

no conflicts

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