Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

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

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

cleanup of the code

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