Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

committing my weekends work: 2100 lines :D

  • proxy server now accepts and synchronizes clients like a master server
  • network manager got different network setup interface
  • network stream got different constructure scheme
  • permissions checking and algorithm extended and changed
  • starting ability to connect to multiple network nodes at the same time
  • some very much smaller changes here and there
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/// TODO @THIS IS FOR THE INTSIZE
54#include "converter.h"
55
56
57#define PACKAGE_SIZE  256
58
59
60/**
61 * empty constructor
62 */
63NetworkStream::NetworkStream()
64    : DataStream()
65{
66  this->init();
67  /* initialize the references */
68  this->pInfo->nodeType = NET_CLIENT;
69}
70
71
72NetworkStream::NetworkStream( int nodeType)
73{
74  this->init();
75
76  this->pInfo->nodeType = nodeType;
77
78  switch( nodeType)
79  {
80    case NET_MASTER_SERVER:
81      // init the shared network data
82      SharedNetworkData::getInstance()->setHostID(0);
83      SharedNetworkData::getInstance()->setNodeType(NET_MASTER_SERVER);
84      break;
85
86    case NET_PROXY_SERVER_ACTIVE:
87      // init the shared network data
88      SharedNetworkData::getInstance()->setHostID(0);
89      SharedNetworkData::getInstance()->setNodeType(NET_PROXY_SERVER_ACTIVE);
90      break;
91    case NET_PROXY_SERVER_PASSIVE:
92            // init the shared network data
93      SharedNetworkData::getInstance()->setHostID(0);
94      SharedNetworkData::getInstance()->setNodeType(NET_PROXY_SERVER_PASSIVE);
95      break;
96    case NET_CLIENT:
97      SharedNetworkData::getInstance()->setNodeType(NET_CLIENT);
98      break;
99  }
100
101  SharedNetworkData::getInstance()->setDefaultSyncStream(this);
102
103  // get the local ip address
104  IPaddress ip;
105  SDLNet_ResolveHost( &ip, NULL, 0);
106  this->pInfo->ip = ip;
107}
108
109
110
111/**
112 * generic init functions
113 */
114void NetworkStream::init()
115{
116  /* set the class id for the base object */
117  this->setClassID(CL_NETWORK_STREAM, "NetworkStream");
118  this->serverSocket = NULL;
119  this->networkGameManager = NULL;
120  this->networkMonitor = NULL;
121
122  this->pInfo = new PeerInfo();
123  this->pInfo->userId = 0;
124  this->pInfo->lastAckedState = 0;
125  this->pInfo->lastRecvedState = 0;
126
127
128  this->currentState = 0;
129
130  remainingBytesToWriteToDict = Preferences::getInstance()->getInt( "compression", "writedict", 0 );
131
132  assert( Zip::getInstance()->loadDictionary( "testdict" ) >= 0 );
133  this->dictClient = Zip::getInstance()->loadDictionary( "dict2pl_client" );
134  assert( this->dictClient >= 0 );
135  this->dictServer = Zip::getInstance()->loadDictionary( "dict2p_server" );
136  assert( this->dictServer >= 0 );
137}
138
139
140/**
141 * deconstructor
142 */
143NetworkStream::~NetworkStream()
144{
145  if ( this->serverSocket )
146  {
147    serverSocket->close();
148    delete serverSocket;
149    serverSocket = NULL;
150  }
151  for ( PeerList::iterator i = peers.begin(); i!=peers.end(); i++)
152  {
153    if ( i->second.socket )
154    {
155      i->second.socket->disconnectServer();
156      delete i->second.socket;
157      i->second.socket = NULL;
158    }
159
160    if ( i->second.handshake )
161    {
162      delete i->second.handshake;
163      i->second.handshake = NULL;
164    }
165
166    if ( i->second.connectionMonitor )
167    {
168      delete i->second.connectionMonitor;
169      i->second.connectionMonitor = NULL;
170    }
171  }
172  for ( SynchronizeableList::const_iterator it = getSyncBegin(); it != getSyncEnd(); it ++ )
173    (*it)->setNetworkStream( NULL );
174
175  if( this->pInfo)
176    delete this->pInfo;
177
178  if( this->networkMonitor)
179    delete this->networkMonitor;
180}
181
182
183/**
184 * establish a connection to a remote master server
185 * @param host: host name
186 * @param port: the port number
187 */
188void NetworkStream::connectToMasterServer(std::string host, int port)
189{
190  int node = this->peers.size();
191  this->peers[node].socket = new UdpSocket( host, port );
192  this->peers[node].userId = 0;
193
194  this->peers[node].nodeType = NET_MASTER_SERVER;
195  this->peers[node].connectionMonitor = new ConnectionMonitor( 0 );
196  this->peers[node].ip = this->peers[node].socket->getRemoteAddress();
197}
198
199
200/**
201 * establish a connection to a remote proxy server
202 * @param host: host name
203 * @param port: the port number
204 */
205void NetworkStream::connectToProxyServer(std::string host, int port)
206{
207  int node = this->peers.size();
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 */
244void NetworkStream::startHandshake()
245{
246  Handshake* hs = new Handshake(this->pInfo->nodeType);
247  hs->setUniqueID( 0 );
248  assert( peers[0].handshake == NULL );
249  peers[0].handshake = hs;
250
251  // set the preferred nick name
252  hs->setPreferedNickName( Preferences::getInstance()->getString( "multiplayer", "nickname", "Player" ) );
253
254  PRINTF(0)("NetworkStream: Handshake created: %s\n", hs->getCName());
255}
256
257
258/**
259 * this functions connects a synchronizeable to the networkstream, therefore synchronizeing
260 * it all over the network and creating it on the other platforms (if and only if it is a
261 * server
262 */
263void NetworkStream::connectSynchronizeable(Synchronizeable& sync)
264{
265  this->synchronizeables.push_back(&sync);
266  sync.setNetworkStream( this );
267
268//   this->bActive = true;
269}
270
271
272/**
273 * removes the synchronizeable from the list of synchronized entities
274 */
275void NetworkStream::disconnectSynchronizeable(Synchronizeable& sync)
276{
277  // removing the Synchronizeable from the List.
278  std::list<Synchronizeable*>::iterator disconnectSynchro = std::find(this->synchronizeables.begin(), this->synchronizeables.end(), &sync);
279  if (disconnectSynchro != this->synchronizeables.end())
280    this->synchronizeables.erase(disconnectSynchro);
281
282  oldSynchronizeables[sync.getUniqueID()] = SDL_GetTicks();
283}
284
285
286/**
287 * this is called to process data from the network socket to the synchronizeable and vice versa
288 */
289void NetworkStream::processData()
290{
291  // create the network monitor after all the init work and before there is any connection handlings
292  if( this->networkMonitor == NULL)
293    this->networkMonitor = new NetworkMonitor(this);
294
295
296  int tick = SDL_GetTicks();
297
298  this->currentState++;
299  // there was a wrap around
300  if( this->currentState < 0)
301  {
302    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");
303  }
304
305  if ( this->pInfo->isMasterServer())
306  {
307    // execute everytthing the master server shoudl do
308    if ( serverSocket )
309      serverSocket->update();
310
311    this->updateConnectionList();
312  }
313  else if( this->pInfo->isProxyServer())
314  {
315    // execute everything the proxy server should do
316    if ( serverSocket )
317      serverSocket->update();
318
319    this->updateConnectionList();
320  }
321  else
322  {
323    // check if the connection is ok else terminate and remove
324    if ( peers[0].socket && ( !peers[0].socket->isOk() || peers[0].connectionMonitor->hasTimedOut() ) )
325    {
326      PRINTF(1)("lost connection to server\n");
327
328      peers[0].socket->disconnectServer();
329      delete peers[0].socket;
330      peers[0].socket = NULL;
331
332      if ( peers[0].handshake )
333        delete peers[0].handshake;
334      peers[0].handshake = NULL;
335
336      if ( peers[0].connectionMonitor )
337        delete peers[0].connectionMonitor;
338      peers[0].connectionMonitor = NULL;
339    }
340  }
341
342  cleanUpOldSyncList();
343  handleHandshakes();
344
345  // update the network monitor
346  this->networkMonitor->process();
347
348  // order of up/downstream is important!!!!
349  // don't change it
350  handleDownstream( tick );
351  handleUpstream( tick );
352}
353
354
355/**
356 * if we are a NET_MASTER_SERVER or NET_PROXY_SERVER_ACTIVE update the connection list to accept new
357 * connections (clients) also start the handsake for the new clients
358 */
359void NetworkStream::updateConnectionList( )
360{
361  //check for new connections
362
363  NetworkSocket* tempNetworkSocket = serverSocket->getNewSocket();
364
365  // we got new network node
366  if ( tempNetworkSocket )
367  {
368    int clientId;
369    // if there is a list of free client id slots, take these
370    if ( freeSocketSlots.size() > 0 )
371    {
372      clientId = freeSocketSlots.back();
373      freeSocketSlots.pop_back();
374    }
375    else
376    {
377      clientId = 1;
378
379      for ( PeerList::iterator it = peers.begin(); it != peers.end(); it++ )
380        if ( it->first >= clientId )
381          clientId = it->first + 1;
382    }
383
384    peers[clientId].socket = tempNetworkSocket;
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());
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() ) && sync.getUniqueID() < SharedNetworkData::getInstance()->getMaxPlayer() - 1 )
723        n = Converter::intToByteArray( 0, buf + offset, UDP_PACKET_SIZE - offset );
724      else
725        n = Converter::intToByteArray( sync.getUniqueID(), buf + offset, UDP_PACKET_SIZE - offset );
726
727      assert( n == INTSIZE );
728      offset += n;
729
730      // make space for packet size
731      offset += INTSIZE;
732
733      n = sync.getStateDiff( peer->second.userId, buf + offset, UDP_PACKET_SIZE-offset, currentState, peer->second.lastAckedState, -1000 );
734      offset += n;
735
736      assert( Converter::intToByteArray( n, buf + offset - n - INTSIZE, INTSIZE ) == INTSIZE );
737
738      // check if all data bytes == 0 -> remove data and the synchronizeable from the sync process since there is no update
739      // TODO not all synchronizeables like this maybe add Synchronizeable::canRemoveZeroDiff()
740      bool allZero = true;
741      for ( int i = 0; i < n; i++ )
742      {
743         if ( buf[i+oldOffset+2*INTSIZE] != 0 )
744           allZero = false;
745      }
746      // if there is no new data in this synchronizeable reset the data offset to the last state -> dont synchronizes
747      // data that hast not changed
748      if ( allZero )
749      {
750        offset = oldOffset;
751      }
752    } // all synchronizeables written
753
754
755
756    for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
757    {
758      Synchronizeable & sync = **it;
759
760      if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
761        continue;
762
763      sync.handleSentState( peer->second.userId, currentState, peer->second.lastAckedState );
764    }
765
766
767    assert( Converter::intToByteArray( offset, buf, INTSIZE ) == INTSIZE );
768
769    // now compress the data with the zip library
770    int compLength = 0;
771    if ( SharedNetworkData::getInstance()->isMasterServer() || SharedNetworkData::getInstance()->isProxyServer())
772      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictServer );
773    else
774      compLength = Zip::getInstance()->zip( buf, offset, compBuf, UDP_PACKET_SIZE, dictClient );
775
776    if ( compLength <= 0 )
777    {
778      PRINTF(1)("compression failed!\n");
779      continue;
780    }
781
782    assert( peer->second.socket->writePacket( compBuf, compLength ) );
783
784    if ( this->remainingBytesToWriteToDict > 0 )
785      writeToNewDict( buf, offset, true );
786
787    peer->second.connectionMonitor->processUnzippedOutgoingPacket( tick, buf, offset, currentState );
788    peer->second.connectionMonitor->processZippedOutgoingPacket( tick, compBuf, compLength, currentState );
789
790  }
791}
792
793/**
794 * handle downstream network traffic
795 */
796void NetworkStream::handleDownstream( int tick )
797{
798  int offset = 0;
799
800  int length = 0;
801  int packetLength = 0;
802  int compLength = 0;
803  int uniqueId = 0;
804  int state = 0;
805  int ackedState = 0;
806  int fromState = 0;
807  int syncDataLength = 0;
808
809  for ( PeerList::iterator peer = peers.begin(); peer != peers.end(); peer++ )
810  {
811
812    if ( !peer->second.socket )
813      continue;
814
815    while ( 0 < (compLength = peer->second.socket->readPacket( compBuf, UDP_PACKET_SIZE )) )
816    {
817      peer->second.connectionMonitor->processZippedIncomingPacket( tick, compBuf, compLength );
818
819      packetLength = Zip::getInstance()->unZip( compBuf, compLength, buf, UDP_PACKET_SIZE );
820
821      if ( packetLength < 4*INTSIZE )
822      {
823        if ( packetLength != 0 )
824          PRINTF(1)("got too small packet: %d\n", packetLength);
825        continue;
826      }
827
828      if ( this->remainingBytesToWriteToDict > 0 )
829        writeToNewDict( buf, packetLength, false );
830
831      assert( Converter::byteArrayToInt( buf, &length ) == INTSIZE );
832      assert( Converter::byteArrayToInt( buf + INTSIZE, &state ) == INTSIZE );
833      assert( Converter::byteArrayToInt( buf + 2*INTSIZE, &fromState ) == INTSIZE );
834      assert( Converter::byteArrayToInt( buf + 3*INTSIZE, &ackedState ) == INTSIZE );
835      offset = 4*INTSIZE;
836
837      peer->second.connectionMonitor->processUnzippedIncomingPacket( tick, buf, packetLength, state, ackedState );
838
839
840      //if this is an old state drop it
841      if ( state <= peer->second.lastRecvedState )
842        continue;
843
844      if ( packetLength != length )
845      {
846        PRINTF(1)("real packet length (%d) and transmitted packet length (%d) do not match!\n", packetLength, length);
847        peer->second.socket->disconnectServer();
848        continue;
849      }
850
851      while ( offset + 2 * INTSIZE < length )
852      {
853        assert( offset > 0 );
854        assert( Converter::byteArrayToInt( buf + offset, &uniqueId ) == INTSIZE );
855        offset += INTSIZE;
856
857        assert( Converter::byteArrayToInt( buf + offset, &syncDataLength ) == INTSIZE );
858        offset += INTSIZE;
859
860        assert( syncDataLength > 0 );
861        assert( syncDataLength < 10000 );
862
863        Synchronizeable * sync = NULL;
864
865        // look for the synchronizeable in question
866        for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
867        {
868        //                                        client thinks his handshake has id 0!!!!!
869          if ( (*it)->getUniqueID() == uniqueId || ( uniqueId == 0 && (*it)->getUniqueID() == peer->second.userId ) )
870          {
871            sync = *it;
872            break;
873          }
874        }
875
876        // this synchronizeable does not yet exist! create it
877        if ( sync == NULL )
878        {
879          PRINTF(0)("could not find sync with id %d. try to create it\n", uniqueId);
880
881          // if it is an old synchronizeable already removed, ignore it
882          if ( oldSynchronizeables.find( uniqueId ) != oldSynchronizeables.end() )
883          {
884            offset += syncDataLength;
885            continue;
886          }
887
888          // 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)
889          if ( peers[peer->second.userId].isClient() )
890          {
891            offset += syncDataLength;
892            continue;
893          }
894
895          int leafClassId;
896          if ( INTSIZE > length - offset )
897          {
898            offset += syncDataLength;
899            continue;
900          }
901
902          Converter::byteArrayToInt( buf + offset, &leafClassId );
903
904          assert( leafClassId != 0 );
905
906
907          BaseObject * b = NULL;
908          /* These are some small exeptions in creation: Not all objects can/should be created via Factory */
909          /* Exception 1: NullParent */
910          if( leafClassId == CL_NULL_PARENT || leafClassId == CL_SYNCHRONIZEABLE || leafClassId == CL_NETWORK_GAME_MANAGER )
911          {
912            PRINTF(1)("Don't create Object with ID %x, ignored!\n", (int)leafClassId);
913            offset += syncDataLength;
914            continue;
915          }
916          else
917            b = Factory::fabricate( (ClassID)leafClassId );
918
919          if ( !b )
920          {
921            PRINTF(1)("Could not fabricate Object with classID %x\n", leafClassId);
922            offset += syncDataLength;
923            continue;
924          }
925
926          if ( b->isA(CL_SYNCHRONIZEABLE) )
927          {
928            sync = dynamic_cast<Synchronizeable*>(b);
929            sync->setUniqueID( uniqueId );
930            sync->setSynchronized(true);
931
932            PRINTF(0)("Fabricated %s with id %d\n", sync->getClassCName(), sync->getUniqueID());
933          }
934          else
935          {
936            PRINTF(1)("Class with ID %x is not a synchronizeable!\n", (int)leafClassId);
937            delete b;
938            offset += syncDataLength;
939            continue;
940          }
941        }
942
943
944        int n = sync->setStateDiff( peer->second.userId, buf+offset, syncDataLength, state, fromState );
945        offset += n;
946
947      }
948
949      if ( offset != length )
950      {
951        PRINTF(0)("offset (%d) != length (%d)\n", offset, length);
952        peer->second.socket->disconnectServer();
953      }
954
955
956      for ( SynchronizeableList::iterator it = synchronizeables.begin(); it != synchronizeables.end(); it++ )
957      {
958        Synchronizeable & sync = **it;
959
960        if ( !sync.beSynchronized() || sync.getUniqueID() < 0 )
961          continue;
962
963        sync.handleRecvState( peer->second.userId, state, fromState );
964      }
965
966      assert( peer->second.lastAckedState <= ackedState );
967      peer->second.lastAckedState = ackedState;
968
969      assert( peer->second.lastRecvedState < state );
970      peer->second.lastRecvedState = state;
971
972    }
973
974  }
975
976}
977
978/**
979 * is executed when a handshake has finished
980 */
981void NetworkStream::handleNewClient( int userId )
982{
983  // init and assign the message manager
984  MessageManager::getInstance()->initUser( userId );
985  // do all game relevant stuff here
986  networkGameManager->signalNewPlayer( userId );
987}
988
989
990/**
991 * removes old items from oldSynchronizeables
992 */
993void NetworkStream::cleanUpOldSyncList( )
994{
995  int now = SDL_GetTicks();
996
997  for ( std::map<int,int>::iterator it = oldSynchronizeables.begin(); it != oldSynchronizeables.end();  )
998  {
999    if ( it->second < now - 10*1000 )
1000    {
1001      std::map<int,int>::iterator delIt = it;
1002      it++;
1003      oldSynchronizeables.erase( delIt );
1004      continue;
1005    }
1006    it++;
1007  }
1008}
1009
1010/**
1011 * writes data to DATA/dicts/newdict
1012 * @param data pointer to data
1013 * @param length length
1014 */
1015void NetworkStream::writeToNewDict( byte * data, int length, bool upstream )
1016{
1017  if ( remainingBytesToWriteToDict <= 0 )
1018    return;
1019
1020  if ( length > remainingBytesToWriteToDict )
1021    length = remainingBytesToWriteToDict;
1022
1023  std::string fileName = ResourceManager::getInstance()->getDataDir();
1024  fileName += "/dicts/newdict";
1025
1026  if ( upstream )
1027    fileName += "_upstream";
1028  else
1029    fileName += "_downstream";
1030
1031  FILE * f = fopen( fileName.c_str(), "a" );
1032
1033  if ( !f )
1034  {
1035    PRINTF(2)("could not open %s\n", fileName.c_str());
1036    remainingBytesToWriteToDict = 0;
1037    return;
1038  }
1039
1040  if ( fwrite( data, 1, length, f ) != length )
1041  {
1042    PRINTF(2)("could not write to file\n");
1043    fclose( f );
1044    return;
1045  }
1046
1047  fclose( f );
1048
1049  remainingBytesToWriteToDict -= length;
1050}
1051
1052
1053
1054
1055
1056
Note: See TracBrowser for help on using the repository browser.