Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

found a bug in the server settings reading

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